diff --git a/engine/.eslintrc.js b/engine/.eslintrc.js index e24bd82e..8fc83189 100644 --- a/engine/.eslintrc.js +++ b/engine/.eslintrc.js @@ -1,16 +1,27 @@ module.exports = { root: true, env: { - node: true + browser: true, + es6: true, }, extends: [ "eslint:recommended" ], parserOptions: { - ecmaVersion: 2020 + ecmaVersion: 2020, + sourceType: "module" + }, + globals: { + globalThis: true, // eventually aim to remove this }, rules: { "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", - "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off" + "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", + // Temporary while we get the codebase up to speed: + "no-constant-condition": "off", + "no-empty": "off", + "no-extra-boolean-cast": "off", + "no-redeclare": "off", + "no-unused-vars": "off", } }; diff --git a/engine/.gitignore b/engine/.gitignore index be6239f6..d242d636 100644 --- a/engine/.gitignore +++ b/engine/.gitignore @@ -1,6 +1,6 @@ /src/index.js +/src/index.js.map /src/index.min.js +/src/index.min.js.LICENSE.txt /tests/results.xml /tsconfig.tsbuildinfo -/wwtlib/bin/ -/wwtlib/obj/ diff --git a/engine/csharp_ref/Annotation.cs b/engine/csharp_ref/Annotation.cs deleted file mode 100644 index ae2f3a2a..00000000 --- a/engine/csharp_ref/Annotation.cs +++ /dev/null @@ -1,639 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - - public class Annotation - { - // Web GL support for annotations - // Annotations all share a set of supporting primitives, each time any annotation changes the primitives, they must be regenerated if they have been drawn already. - // It is best to do updates in large batches - - protected static PointList PointList = null; - protected static LineList LineList = null; - protected static TriangleFanList TriangleFanPointList = null; - protected static TriangleList TriangleList = null; - - public static bool BatchDirty = true; - public static void PrepBatch(RenderContext renderContext) - { - if (PointList == null || BatchDirty) - { - PointList = new PointList(renderContext); - LineList = new LineList(); - TriangleFanPointList = new TriangleFanList(); - TriangleList = new TriangleList(); - LineList.DepthBuffered = false; - TriangleList.DepthBuffered = false; - } - } - - public static void DrawBatch(RenderContext renderContext ) - { - BatchDirty = false; - if (renderContext.gl == null) - { - return; - } - - if (PointList != null) - { - PointList.Draw(renderContext, 1, false); - } - - if (LineList != null) - { - LineList.DrawLines(renderContext, 1); - } - - - if (TriangleFanPointList != null) - { - TriangleFanPointList.Draw(renderContext, 1); - } - - if (TriangleList != null) - { - TriangleList.Draw(renderContext, 1, CullMode.None); - } - } - - protected bool AddedToPrimitives = false; - - protected bool AnnotationDirty = true; - - public virtual void Draw(RenderContext renderContext) - { - - } - - - public static double Separation(double Alpha1, double Delta1, double Alpha2, double Delta2) - { - Delta1 = Delta1 / 180.0 * Math.PI; - Delta2 = Delta2 / 180.0 * Math.PI; - - Alpha1 = Alpha1/ 12.0 * Math.PI; - Alpha2 = Alpha2/ 12.0 * Math.PI; - - double x = Math.Cos(Delta1) * Math.Sin(Delta2) - Math.Sin(Delta1) * Math.Cos(Delta2) * Math.Cos(Alpha2 - Alpha1); - double y = Math.Cos(Delta2) * Math.Sin(Alpha2 - Alpha1); - double z = Math.Sin(Delta1) * Math.Sin(Delta2) + Math.Cos(Delta1) * Math.Cos(Delta2) * Math.Cos(Alpha2 - Alpha1); - - double @value = Math.Atan2(Math.Sqrt(x * x + y * y), z); - @value = @value/Math.PI * 180.0; - if (@value < 0) - @value += 180; - - return @value; - } - - double opacity = 1; - - public double Opacity - { - get { return opacity; } - set - { - Annotation.BatchDirty = true; - opacity = value; - } - } - string id; - - public string ID - { - get { return id; } - set { id = value; } - } - - string tag; - - public string Tag - { - get { return tag; } - set { tag = value; } - } - - string label; - - public string Label - { - get { return label; } - set { label = value; } - } - - bool showHoverLabel = false; - - public bool ShowHoverLabel - { - get { return showHoverLabel; } - set { showHoverLabel = value; } - } - public virtual bool HitTest(RenderContext renderContext, double RA, double dec, double x, double y) - { - return false; - } - - protected Vector3d center; - - public Vector3d Center - { - get { return center; } - set { center = value; } - } - public static uint ColorToUint(Color col) - { - return ((uint)col.A) << 24 | ((uint)col.R << 16) | ((uint)col.G) << 8 | (uint)col.B; - } - - public static uint ColorToUintAlpha(Color col, uint opacity) - { - return (uint)opacity << 24 | (uint)col.R << 16 | (uint)col.G << 8 | (uint)col.B; - } - - - } - - public class Circle : Annotation - { - public Circle() - { - } - - bool fill = false; - - - public bool Fill - { - get { return fill; } - set - { - Annotation.BatchDirty = true; - fill = value; - } - } - - - bool skyRelative = false; - - - public bool SkyRelative - { - get { return skyRelative; } - set - { - Annotation.BatchDirty = true; - skyRelative = value; - } - } - double strokeWidth = 1; - - public double LineWidth - { - get { return strokeWidth; } - - set - { - Annotation.BatchDirty = true; - strokeWidth = value; - } - } - - double radius = 10; - - public double Radius - { - get { return radius; } - set - { - Annotation.BatchDirty = true; - radius = value; - } - } - - - Color lineColor = Colors.White; - - public string LineColor - { - get { return lineColor.ToString(); } - set - { - Annotation.BatchDirty = true; - lineColor = Color.Load(value); - } - } - Color fillColor = Colors.White; - - public string FillColor - { - get { return fillColor.ToString(); } - set - { - Annotation.BatchDirty = true; - fillColor = Color.FromName(value); - } - } - - - - double ra = 0; - double dec = 0; - - public void SetCenter(double ra, double dec) - { - Annotation.BatchDirty = true; - this.ra = ra / 15; - this.dec = dec; - center = Coordinates.RADecTo3d(this.ra, this.dec); - } - - - public override void Draw(RenderContext renderContext) - { - bool onScreen = true; - double rad = radius; - if (skyRelative) - { - rad /= renderContext.FovScale / 3600; - } - Vector3d screenSpacePnt = renderContext.WVP.Transform(center); - if (screenSpacePnt.Z < 0) - { - onScreen = false; - } - - if (Vector3d.Dot((Vector3d)renderContext.ViewPoint, center) < .55) - { - onScreen = false; - } - - if (renderContext.gl != null) - { - - if (Annotation.BatchDirty || AnnotationDirty) - { - Vector3d up = Vector3d.Create(0, 1, 0); - - Vector3d xNormal = Vector3d.Cross(center, up); - - Vector3d yNormal = Vector3d.Cross(center, xNormal); - - double r = radius / 44; - - int segments = 72; - - double radiansPerSegment = Math.PI * 2 / segments; - List vertexList = new List(); - - for (int j = 0; j <= segments; j++) - { - double x = Math.Cos(j * radiansPerSegment) * r; - double y = Math.Sin(j * radiansPerSegment) * r; - - vertexList.Add(Vector3d.Create(center.X + x * xNormal.X + y * yNormal.X, center.Y + x * xNormal.Y + y * yNormal.Y, center.Z + x * xNormal.Z + y * yNormal.Z)); - - } - - if (strokeWidth > 0 && vertexList.Count > 1) - { - Color lineColorWithOpacity = lineColor.Clone(); - lineColorWithOpacity.A = Math.Round(lineColorWithOpacity.A * Opacity); - - for (int i = 0; i < (vertexList.Count - 1); i++) - { - LineList.AddLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - } - if (fill) - { - Color fillColorWithOpacity = fillColor.Clone(); - fillColorWithOpacity.A = Math.Round(fillColorWithOpacity.A * Opacity); - - Vector3d pos = Vector3d.Create(center.X, center.Y, center.Z); - vertexList.Insert(0, pos); - TriangleFanPointList.AddShape(vertexList, fillColorWithOpacity, new Dates(0, 1)); - } - AnnotationDirty = false; - } - } - else - { - if (onScreen) - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Alpha = Opacity; - ctx.BeginPath(); - ctx.Arc(screenSpacePnt.X, screenSpacePnt.Y, rad, 0, Math.PI * 2, true); - ctx.LineWidth = strokeWidth; - ctx.FillStyle = fillColor.ToString(); - if (fill) - { - ctx.Fill(); - } - ctx.Alpha = 1.0; - ctx.StrokeStyle = lineColor.ToString(); - ctx.Stroke(); - - ctx.Restore(); - } - } - } - - public override bool HitTest(RenderContext renderContext, double RA, double dec, double x, double y) - { - if (string.IsNullOrEmpty(ID)) - { - return false; - } - - double rad = radius; - if (!skyRelative) - { - rad *= renderContext.FovScale / 3600; - } - - return Separation(RA, dec, this.ra, this.dec) < rad; - } - - } - - public class Poly : Annotation - { - List points = new List(); - - - public void AddPoint(double x, double y) - { - Annotation.BatchDirty = true; - points.Add(Coordinates.RADecTo3d(x / 15, y)); - } - - bool fill = false; - - public bool Fill - { - get { return fill; } - set - { - Annotation.BatchDirty = true; - fill = value; - } - } - double strokeWidth = 1; - - public double LineWidth - { - get { return strokeWidth; } - set - { - Annotation.BatchDirty = true; - strokeWidth = value; - } - } - Color lineColor = Colors.White; - - public string LineColor - { - get { return lineColor.ToString(); } - set - { - Annotation.BatchDirty = true; - lineColor = Color.FromName(value); - } - } - Color fillColor = Colors.White; - - public string FillColor - { - get { return fillColor.ToString(); } - set - { - Annotation.BatchDirty = true; - fillColor = Color.FromName(value); - } - } - - //bool hitTestInit = false; - - //void InitHitTest(RenderContext renderContext) - //{ - // Vector2d center = new Vector2d(); - // double radius = 0; - // Vector2d[] screenPoints = new Vector2d[points.Count]; - // int index = 0; - // foreach (Vector3d pnt in points) - // { - // Vector3d screenSpacePnt = renderContext.ViewMatrix.Transform(pnt); - // if (screenSpacePnt.Z < 0) - // { - // return; - // } - // if (Vector3d.Dot(renderContext.ViewPoint, pnt) < .55) - // { - // return; - // } - // screenPoints[index] = new Vector2d(screenSpacePnt.X, screenSpacePnt.Y); - // index++; - // } - - // ConvexHull.FindEnclosingCircle(screenPoints, out center, out radius); - //} - - public override void Draw(RenderContext renderContext) - { - if (renderContext.gl != null) - { - if (Annotation.BatchDirty || AnnotationDirty) - { - //todo can we save this work for later? - List vertexList = points; - - if (strokeWidth > 0 && points.Count > 1) - { - Color lineColorWithOpacity = lineColor.Clone(); - lineColorWithOpacity.A = Math.Round(lineColorWithOpacity.A * Opacity); - - for (int i = 0; i < (points.Count - 1); i++) - { - LineList.AddLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - LineList.AddLine(vertexList[points.Count - 1], vertexList[0], lineColorWithOpacity, new Dates(0, 1)); - } - if (fill) - { - Color fillColorWithOpacity = fillColor.Clone(); - fillColorWithOpacity.A = Math.Round(fillColorWithOpacity.A * Opacity); - - List indexes = Tessellator.TesselateSimplePoly(vertexList); - - for (int i = 0; i < indexes.Count; i += 3) - { - TriangleList.AddSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], fillColorWithOpacity, new Dates(0, 1), 2); - } - } - AnnotationDirty = false; - } - } - else - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Alpha = Opacity; - - ctx.BeginPath(); - - bool first = true; - foreach (Vector3d pnt in points) - { - Vector3d screenSpacePnt = renderContext.WVP.Transform(pnt); - if (screenSpacePnt.Z < 0) - { - ctx.Restore(); - - return; - } - - if (Vector3d.Dot(renderContext.ViewPoint, pnt) < .75) - { - ctx.Restore(); - return; - } - - if (first) - { - first = false; - ctx.MoveTo(screenSpacePnt.X, screenSpacePnt.Y); - } - else - { - ctx.LineTo(screenSpacePnt.X, screenSpacePnt.Y); - } - - } - ctx.ClosePath(); - - ctx.LineWidth = strokeWidth; - if (fill) - { - ctx.FillStyle = fillColor.ToString(); - ctx.Fill(); - } - - ctx.StrokeStyle = lineColor.ToString(); - ctx.Alpha = 1; - ctx.Stroke(); - - ctx.Restore(); - - } - } - } - public class PolyLine : Annotation - { - List points = new List(); - - - public void AddPoint(double x, double y) - { - Annotation.BatchDirty = true; - points.Add(Coordinates.RADecTo3d(x / 15, y)); - } - - double strokeWidth = 1; - - public double LineWidth - { - get { return strokeWidth; } - set - { - Annotation.BatchDirty = true; - strokeWidth = value; - } - } - Color lineColor = Colors.White; - - public string LineColor - { - get { return lineColor.ToString(); } - set - { - Annotation.BatchDirty = true; - lineColor = Color.FromName(value); - } - } - - - - public override void Draw(RenderContext renderContext) - { - if (renderContext.gl != null) - { - if (Annotation.BatchDirty || AnnotationDirty) - { - //todo can we save this work for later? - List vertexList = points; - - if (strokeWidth > 0) - { - Color lineColorWithOpacity = lineColor.Clone(); - lineColorWithOpacity.A = Math.Round(lineColorWithOpacity.A * Opacity); - - for (int i = 0; i < (points.Count - 1); i++) - { - LineList.AddLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - } - - AnnotationDirty = false; - } - } - else - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Alpha = Opacity; - - bool first = true; - foreach (Vector3d pnt in points) - { - Vector3d screenSpacePnt = renderContext.WVP.Transform(pnt); - if (screenSpacePnt.Z < 0) - { - ctx.Restore(); - return; - } - if (Vector3d.Dot(renderContext.ViewPoint, pnt) < .75) - { - ctx.Restore(); - return; - } - if (first) - { - first = false; - ctx.BeginPath(); - ctx.MoveTo(screenSpacePnt.X, screenSpacePnt.Y); - } - else - { - ctx.LineTo(screenSpacePnt.X, screenSpacePnt.Y); - } - } - - ctx.LineWidth = strokeWidth; - - ctx.StrokeStyle = lineColor.ToString(); - - ctx.Stroke(); - - ctx.Restore(); - } - } - } -} diff --git a/engine/csharp_ref/AstroCalc/AAAberration.cs b/engine/csharp_ref/AstroCalc/AAAberration.cs deleted file mode 100644 index c965869b..00000000 --- a/engine/csharp_ref/AstroCalc/AAAberration.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System; -public static partial class GFX -{ - - public static ACFT[] g_ACft = { new ACFT(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1719914, -2, -25, 0, 25, -13, 1578089, 156, 10, 32, 684185, -358), new ACFT(0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6434, 141, 28007, -107, 25697, -95, -5904, -130, 11141, -48, -2559, -55), new ACFT(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 715, 0, 0, 0, 6, 0, -657, 0, -15, 0, -282, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 715, 0, 0, 0, 0, 0, -656, 0, 0, 0, -285, 0), new ACFT(0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 486, -5, -236, -4, -216, -4, -446, 5, -94, 0, -193, 0), new ACFT(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 2, 0, -147, 0, -6, 0, -61, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, -59, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 39, 0, 0, 0, 0, 0, -36, 0, 0, 0, -16, 0), new ACFT(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 33, 0, -10, 0, -9, 0, -30, 0, -5, 0, -13, 0), new ACFT(0, 2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 31, 0, 1, 0, 1, 0, -28, 0, 0, 0, -12, 0), new ACFT(0, 3, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, 25, 0, 8, 0, 11, 0, 3, 0), new ACFT(0, 5, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, -25, 0, -8, 0, -11, 0, -3, 0), new ACFT(2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, -19, 0, 0, 0, -8, 0), new ACFT(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -19, 0, 0, 0, 0, 0, 17, 0, 0, 0, 8, 0), new ACFT(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, -16, 0, 0, 0, -7, 0), new ACFT(0, 1, 0, -2, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 1, 0, 7, 0), new ACFT(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, -15, 0, -3, 0, -6, 0), new ACFT(0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 11, 0, -1, 0, -1, 0, -10, 0, -1, 0, -5, 0), new ACFT(2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -11, 0, -10, 0, 0, 0, -4, 0, 0, 0), new ACFT(0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -11, 0, -2, 0, -2, 0, 9, 0, -1, 0, 4, 0), new ACFT(0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -8, 0, -8, 0, 6, 0, -3, 0, 3, 0), new ACFT(0, 3, 0, -2, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, 0, 0, 0, 9, 0, 0, 0, 4, 0), new ACFT(1, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -9, 0, 0, 0, -4, 0), new ACFT(2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -8, 0, 0, 0, -4, 0), new ACFT(0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, -8, 0, 0, 0, -3, 0, 0, 0), new ACFT(2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 8, 0, 0, 0, 3, 0, 0, 0), new ACFT(0, 3, -2, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, -8, 0, 0, 0, -3, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 2, -1, 0, 8, 0, 0, 0, 0, 0, -7, 0, 0, 0, -3, 0), new ACFT(8, -12, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, -6, 0, 4, 0, -3, 0, 2, 0), new ACFT(8, -14, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, 6, 0, -4, 0, 3, 0, -2, 0), new ACFT(0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -6, 0, -5, 0, -4, 0, 5, 0, -2, 0, 2, 0), new ACFT(3, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -2, 0, -7, 0, 1, 0, -4, 0), new ACFT(0, 2, 0, -2, 0, 0, 0, 0, 0, 0, 0, 4, 0, -6, 0, -5, 0, -4, 0, -2, 0, -2, 0), new ACFT(3, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -6, 0, 0, 0, -3, 0, 0, 0), new ACFT(0, 2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, -5, 0, -4, 0, -5, 0, -2, 0, -2, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, -2, 0, 0, 5, 0, 0, 0, 0, 0, -5, 0, 0, 0, -2, 0) }; -} -// -//Module : AAABERRATION.CPP -//Purpose: Implementation for the algorithms for Aberration -//Created: PJN / 29-12-2003 -//History: PJN / 21-04-2005 1. Renamed "AAAberation.cpp" to "AAAberration.cpp" so that all source code filenames -// match their corresponding header files. Thanks to Jürgen Schuck for suggesting this -// update. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////////// Includes ////////////////////////////////////// - - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class ABR // was CAAAberration -{ -//Static methods - //L2 L3 L4 L5 L6 L7 L8 Ldash D Mdash F xsin xsint xcos xcost ysin ysint ycos ycost zsin zsint zcos zcost - - - //////////////////////////////// Implementation /////////////////////////////// - - public static C3D EarthVelocity(double JD) - { - double T = (JD - 2451545) / 36525; - double L2 = 3.1761467 + 1021.3285546 * T; - double L3 = 1.7534703 + 628.3075849 * T; - double L4 = 6.2034809 + 334.0612431 * T; - double L5 = 0.5995465 + 52.9690965 * T; - double L6 = 0.8740168 + 21.3299095 * T; - double L7 = 5.4812939 + 7.4781599 * T; - double L8 = 5.3118863 + 3.8133036 * T; - double Ldash = 3.8103444 + 8399.6847337 * T; - double D = 5.1984667 + 7771.3771486 * T; - double Mdash = 2.3555559 + 8328.6914289 * T; - double F = 1.6279052 + 8433.4661601 * T; - - C3D velocity = new C3D(); - - int nAberrationCoefficients = GFX.g_ACft.Length; - for (int i =0; i a) - // { - // a = d2; - // b = d1; - // c = d3; - // } - // if (c > a) - // { - // a = d3; - // b = d1; - // c = d2; - // } - - // double @value; - // if (a > Math.Sqrt(b * b + c * c)) - // { - // bType1 = true; - // @value = a; - // } - // else - // { - // bType1 = false; - // @value = 2 * a * b * c / (Math.Sqrt((a + b + c) * (a + b - c) * (b + c - a) * (a + c - b))); - // } - - // return @value; - //} -} diff --git a/engine/csharp_ref/AstroCalc/AABinaryStar.cs b/engine/csharp_ref/AstroCalc/AABinaryStar.cs deleted file mode 100644 index f5f4ac87..00000000 --- a/engine/csharp_ref/AstroCalc/AABinaryStar.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -// -//Module : AABINARYSTAR.CPP -//Purpose: Implementation for the algorithms for an binary stars system -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////////////// Includes ////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAABinaryStarDetails -{ -//Constructors / Destructors - public CAABinaryStarDetails() - { - r = 0; - Theta = 0; - Rho = 0; - } - -//Member variables - public double r; - public double Theta; - public double Rho; -} - -public class CAABinaryStar -{ -//Static methods - //Tangible Process Only End - - - ////////////////////////////////// Implementation ///////////////////////////// - - public static CAABinaryStarDetails Calculate(double t, double P, double T, double e, double a, double i, double omega, double w) - { - double n = 360 / P; - double M = CT.M360(n*(t - T)); - double E = CAAKepler.Calculate(M, e); - E = CT.D2R(E); - i = CT.D2R(i); - w = CT.D2R(w); - omega = CT.D2R(omega); - - CAABinaryStarDetails details = new CAABinaryStarDetails(); - - details.r = a*(1 - e *Math.Cos(E)); - - double v = Math.Atan(Math.Sqrt((1 + e) / (1 - e)) * Math.Tan(E/2)) * 2; - details.Theta = Math.Atan2(Math.Sin(v + w) * Math.Cos(i), Math.Cos(v + w)) + omega; - details.Theta = CT.M360(CT.R2D(details.Theta)); - - double sinvw = Math.Sin(v + w); - double cosvw = Math.Cos(v + w); - double cosi = Math.Cos(i); - details.Rho = details.r * Math.Sqrt((sinvw *sinvw *cosi *cosi) + (cosvw *cosvw)); - - return details; - } - public static double ApparentEccentricity(double e, double i, double w) - { - i = CT.D2R(i); - w = CT.D2R(w); - - double cosi = Math.Cos(i); - double cosw = Math.Cos(w); - double sinw = Math.Sin(w); - double esquared = e *e; - double A = (1 - esquared *cosw *cosw)*cosi *cosi; - double B = esquared *sinw *cosw *cosi; - double C = 1 - esquared *sinw *sinw; - double D = (A - C)*(A - C) + 4 *B *B; - - double sqrtD = Math.Sqrt(D); - return Math.Sqrt(2 *sqrtD / (A + C + sqrtD)); - } -} - diff --git a/engine/csharp_ref/AstroCalc/AACoordinateTransformation.cs b/engine/csharp_ref/AstroCalc/AACoordinateTransformation.cs deleted file mode 100644 index 77f91050..00000000 --- a/engine/csharp_ref/AstroCalc/AACoordinateTransformation.cs +++ /dev/null @@ -1,248 +0,0 @@ - -using System; -using System.Diagnostics; -// -//Module : AACOORDINATETRANSFORMATION.CPP -//Purpose: Implementation for the algorithms which convert between the various celestial coordinate systems -//Created: PJN / 29-12-2003 -//History: PJN / 14-02-2004 1. Fixed a "minus zero" bug in the function CAACoordinateTransformation::DMSToDegrees. -// The sign of the value is now taken explicitly from the new bPositive boolean -// parameter. Thanks to Patrick Wallace for reporting this problem. -// PJN / 02-06-2005 1. Most of the angular conversion functions have now been reimplemented as simply -// numeric constants. All of the AA+ code has also been updated to use these new constants. -// PJN / 25-01-2007 1. Fixed a minor compliance issue with GCC in the AACoordinateTransformation.h to do -// with the declaration of various methods. Thanks to Mathieu Peyréga for reporting this -// issue. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////// Includes ///////////////////////////////////////////// - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// -public class COR -{ - public COR() - { - X = 0; - Y = 0; - } - public static COR Create(double x, double y) - { - COR item = new COR(); - item.X = x; - item.Y = y; - return item; - } - - //Member variables - public double X; - public double Y; -} -public class C3D // was CAA3DCoordinate -{ - public C3D() - { - X = 0; - Y = 0; - Z = 0; - } - public static C3D Create(double x, double y, double z) - { - C3D item = new C3D(); - - item.X = x; - item.Y = y; - item.Z = z; - return item; - } - - //member variables - public double X; - public double Y; - public double Z; -} - -// -// CAACoordinateTransformation becomes CT - -public class CT -{ -//Conversion functions - - /////////////////////// Implementation //////////////////////////////////////// - - public static COR Eq2Ec(double Alpha, double Delta, double Epsilon) // was Equatorial2Ecliptic - { - Alpha = H2R(Alpha); - Delta = D2R(Delta); - Epsilon = D2R(Epsilon); - - COR Ecliptic = new COR(); - Ecliptic.X = R2D(Math.Atan2(Math.Sin(Alpha)*Math.Cos(Epsilon) + Math.Tan(Delta)*Math.Sin(Epsilon), Math.Cos(Alpha))); - if (Ecliptic.X < 0) - Ecliptic.X += 360; - Ecliptic.Y = R2D(Math.Asin(Math.Sin(Delta)*Math.Cos(Epsilon) - Math.Cos(Delta)*Math.Sin(Epsilon)*Math.Sin(Alpha))); - - return Ecliptic; - } - public static COR Ec2Eq(double Lambda, double Beta, double Epsilon) // was Ecliptic2Equatorial - { - Lambda = D2R(Lambda); - Beta = D2R(Beta); - Epsilon = D2R(Epsilon); - - COR Equatorial = new COR(); - Equatorial.X = R2H(Math.Atan2(Math.Sin(Lambda)*Math.Cos(Epsilon) - Math.Tan(Beta)*Math.Sin(Epsilon), Math.Cos(Lambda))); - if (Equatorial.X < 0) - Equatorial.X += 24; - Equatorial.Y = R2D(Math.Asin(Math.Sin(Beta)*Math.Cos(Epsilon) + Math.Cos(Beta)*Math.Sin(Epsilon)*Math.Sin(Lambda))); - - return Equatorial; - } - public static COR Eq2H(double LocalHourAngle, double Delta, double Latitude) // was Equatorial2Horizontal - { - LocalHourAngle = H2R(LocalHourAngle); - Delta = D2R(Delta); - Latitude = D2R(Latitude); - - COR Horizontal = new COR(); - Horizontal.X = R2D(Math.Atan2(Math.Sin(LocalHourAngle), Math.Cos(LocalHourAngle)*Math.Sin(Latitude) - Math.Tan(Delta)*Math.Cos(Latitude))); - if (Horizontal.X < 0) - Horizontal.X += 360; - Horizontal.Y = R2D(Math.Asin(Math.Sin(Latitude)*Math.Sin(Delta) + Math.Cos(Latitude)*Math.Cos(Delta)*Math.Cos(LocalHourAngle))); - - return Horizontal; - } - public static COR H2Eq(double Azimuth, double Altitude, double Latitude) // was Horizontal2Equatorial - { - //Convert from degress to radians - Azimuth = D2R(Azimuth); - Altitude = D2R(Altitude); - Latitude = D2R(Latitude); - - COR Equatorial = new COR(); - Equatorial.X = R2H(Math.Atan2(Math.Sin(Azimuth), Math.Cos(Azimuth)*Math.Sin(Latitude) + Math.Tan(Altitude)*Math.Cos(Latitude))); - if (Equatorial.X < 0) - Equatorial.X += 24; - Equatorial.Y = R2D(Math.Asin(Math.Sin(Latitude)*Math.Sin(Altitude) - Math.Cos(Latitude)*Math.Cos(Altitude)*Math.Cos(Azimuth))); - - return Equatorial; - } - public static COR Eq2G(double Alpha, double Delta) // was Equatorial2Galactic - { - Alpha = 192.25 - H2D(Alpha); - Alpha = D2R(Alpha); - Delta = D2R(Delta); - - COR Galactic = new COR(); - Galactic.X = R2D(Math.Atan2(Math.Sin(Alpha), Math.Cos(Alpha)*Math.Sin(D2R(27.4)) - Math.Tan(Delta)*Math.Cos(D2R(27.4)))); - Galactic.X = 303 - Galactic.X; - if (Galactic.X >= 360) - Galactic.X -= 360; - Galactic.Y = R2D(Math.Asin(Math.Sin(Delta)*Math.Sin(D2R(27.4)) + Math.Cos(Delta)*Math.Cos(D2R(27.4))*Math.Cos(Alpha))); - - return Galactic; - } - public static COR G2Eq(double l, double b) // was Galactic2Equatorial - { - l -= 123; - l = D2R(l); - b = D2R(b); - - COR Equatorial = new COR(); - Equatorial.X = R2D(Math.Atan2(Math.Sin(l), Math.Cos(l)*Math.Sin(D2R(27.4)) - Math.Tan(b)*Math.Cos(D2R(27.4)))); - Equatorial.X += 12.25; - if (Equatorial.X < 0) - Equatorial.X += 360; - Equatorial.X = D2H(Equatorial.X); - Equatorial.Y = R2D(Math.Asin(Math.Sin(b)*Math.Sin(D2R(27.4)) + Math.Cos(b)*Math.Cos(D2R(27.4))*Math.Cos(l))); - - return Equatorial; - } - -//Inlined functions - public static double D2R(double Degrees) // was DegreesToRadians - { - return Degrees * 0.017453292519943295769236907684886; - } - - public static double R2D(double Radians) // was RadiansToDegrees - { - return Radians * 57.295779513082320876798154814105; - } - - public static double R2H(double Radians)// was RadiansToHours - { - return Radians * 3.8197186342054880584532103209403; - } - - public static double H2R(double Hours)// was HoursToRadians - { - return Hours * 0.26179938779914943653855361527329; - } - - public static double H2D(double Hours)// was HoursToDegrees - { - return Hours * 15; - } - - public static double D2H(double Degrees)// was DegreesToHours - { - return Degrees / 15; - } - - public static double PI() - { - return 3.1415926535897932384626433832795; - } - - public static double M360(double Degrees)// was MapTo0To360Range - { - return Degrees - Math.Floor(Degrees / 360.0) * 360.0; - } - - public static double M24(double HourAngle)// was MapTo0To24Range - { - return HourAngle - Math.Floor(HourAngle / 24.0) * 24.0; - } - - public static double DMS2D(double Degrees, double Minutes, double Seconds)// was DMSToDegrees - { - return DMS2Dp(Degrees, Minutes, Seconds, true); - } -//C++ TO C# CONVERTER NOTE: C# does not allow default values for parameters. Overloaded methods are inserted above. -//ORIGINAL LINE: static double DMSToDegrees(double Degrees, double Minutes, double Seconds, bool bPositive = true) - public static double DMS2Dp(double Degrees, double Minutes, double Seconds, bool bPositive)// was DMSToDegreesPos - { - //validate our parameters - if (!bPositive) - { - Debug.Assert(Degrees >= 0); //All parameters should be non negative if the "bPositive" parameter is false - Debug.Assert(Minutes >= 0); - Debug.Assert(Seconds >= 0); - } - - if (bPositive) - return Degrees + Minutes/60 + Seconds/3600; - else - return -Degrees - Minutes/60 - Seconds/3600; - } -} diff --git a/engine/csharp_ref/AstroCalc/AADate.cs b/engine/csharp_ref/AstroCalc/AADate.cs deleted file mode 100644 index 12df1087..00000000 --- a/engine/csharp_ref/AstroCalc/AADate.cs +++ /dev/null @@ -1,468 +0,0 @@ -using System.Diagnostics; -using System; -// -//Module : AADATE.CPP -//Purpose: Implementation for the algorithms which convert between the Gregorian and Julian calendars and the Julian Day -//Created: PJN / 29-12-2003 -//History: PJN / 10-11-2004 1. Fix for CAADate::Get so that it works correctly for propalactive calendar dates -// PJN / 15-05-2005 1. Fix for CAADate::Set(double JD, bool bGregorianCalendarCalendar) not setting the m_bGregorianCalendarCalendar -// member variable correctly. -// PJN / 26-01-2006 1. After a bug report from Ing. Taras Kapuszczak that a round trip of the date 25 January 100 as -// specified in the Gregorian calendar to the Julian day number and then back again produces the -// incorrect date 26 January 100, I've spent some time looking into the 2 key Meeus Julian Day -// algorithms. It seems that the algorithms which converts from a Calendar date to JD works ok for -// propalactive dates, but the reverse algorithm which converts from a JD to a Calendar date does not. -// Since I made the change in behaviour to support propalactive Gregorian dates to address issues -// with the Moslem calendar (and since then I have discovered further unresolved bugs in the Moslem -// calendar algorithms and advised people to check out my AA+ library instead), I am now reverting -// these changes so that the date algorithms are now as presented in Meeus's book. This means that -// dates after 15 October 1582 are assumed to be in the Gregorian calendar and dates before are -// assumed to be in the Julian calendar. This change also means that some of the CAADate class -// methods no longer require the now defunct "bool" parameter to specify which calendar the date -// represents. As part of the testing for this release verification code has been added to AATest.cpp -// to test all the dates from JD 0 (i.e. 1 January -4712) to a date long in the future. Hopefully -// with this verification code, we should have no more reported issues with the class CAADate. Again -// if you would prefer a much more robust and comprehensive Date time class framework, don't forget -// to check out the authors DTime+ library. -// 2. Optimized CAADate constructor code -// 3. Provided a static version of CAADate::DaysInMonth() method -// 4. Discovered an issue in CAADate::JulianToGregorian. It seems the algorithm presented in the -// book to do conversion from the Julian to Gregorian calendar fails for Julian dates before the -// Gregorian calendar reform in 1582. I have sent an email to Jean Meeus to find out if this is a -// bug in my code or a deficiency in the algorithm presented. Currently the code will assert in this -// function if it is called for a date before the Gregorian reform. -// PJN / 27-01-2007 1. The static version of the Set method has been renamed to DateToJD to avoid any confusion with -// the other Set methods. Thanks to Ing. Taras Kapuszczak for reporting this issue. -// 2. The method InGregorianCalendar has now also been renamed to the more appropriate -// AfterPapalReform. -// 3. Reinstated the bGregorianCalendar parameter for the CAADate constructors and Set methods. -// 4. Changed the parameter layout for the static version of DaysInMonth -// 5. Addition of a InGregorianCalendar method. -// 6. Addition of a SetInGregorianCalendar method. -// 7. Reworked implementation of GregorianToJulian method. -// 8. Reworked implementation of JulianToGregorian method. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////////// Includes ///////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CalD -{ - //Constructors / Destructors - public CalD() - { - Year = 0; - Month = 0; - Day = 0; - } - public static CalD Create(int year, int month, int day) - { - CalD item = new CalD(); - item.Year = year; - item.Month = month; - item.Day = day; - - return item; - } - //Member variables - public int Year; - public int Month; - public int Day; -} -public enum DAY_OF_WEEK : int -{ - SUNDAY = 0, - MONDAY = 1, - TUESDAY = 2, - WEDNESDAY = 3, - THURSDAY = 4, - FRIDAY = 5, - SATURDAY = 6 -} - -public class DT -{ -//Enums - - -//Constructors / Destructors - - //////////////////////////// Implementation /////////////////////////////////// - - public DT() - { - m_dblJulian = 0; - m_bGregorianCalendar = false; - } - public static DT Create(int Year, int Month, double Day, bool bGregorianCalendar) - { - DT item = new DT(); - item.Set(Year, Month, Day, 0, 0, 0, bGregorianCalendar); - return item; - } - public static DT CreateHMS(int Year, int Month, double Day, double Hour, double Minute, double Second, bool bGregorianCalendar) - { - DT item = new DT(); - item.Set(Year, Month, Day, Hour, Minute, Second, bGregorianCalendar); - return item; - } - public static DT CreateJD(double JD, bool bGregorianCalendar) - { - DT item = new DT(); - item.SetJD(JD, bGregorianCalendar); - return item; - } - -//Static Methods - public static double DateToJD(int Year, int Month, double Day, bool bGregorianCalendar) - { - int Y = Year; - int M = Month; - if (M < 3) - { - Y = Y - 1; - M = M + 12; - } - - int A = 0; - int B = 0; - if (bGregorianCalendar) - { - A = (int)(Y / 100.0); - B = 2 - A + (int)(A / 4.0); - } - - return (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + Day + B - 1524.5; - } - public static bool IsLeap(int Year, bool bGregorianCalendar) - { - if (bGregorianCalendar) - { - if ((Year % 100) == 0) - return ((Year % 400) == 0) ? true : false; - else - return ((Year % 4) == 0) ? true : false; - } - else - return ((Year % 4) == 0) ? true : false; - } - //public static void DayOfYearToDayAndMonth(int DayOfYear, bool bLeap, ref int DayOfMonth, ref int Month) - //{ - // int K = bLeap ? 1 : 2; - - // Month = (int)(9*(K + DayOfYear)/275.0 + 0.98); - // if (DayOfYear < 32) - // Month = 1; - - // DayOfMonth = DayOfYear - (int)((275 *Month)/9.0) + (K *(int)((Month + 9)/12.0)) + 30; - //} - //public static CAACalendarDate JulianToGregorian(int Year, int Month, int Day) - //{ - // CAADate date = CAADate.Create(Year, Month, Day, false); - // date.SetInGregorianCalendar(true); - - // CAACalendarDate GregorianDate = new CAACalendarDate(); - // int Hour = 0; - // int Minute = 0; - // double Second = 0; - // date.Get(ref GregorianDate.Year, ref GregorianDate.Month, ref GregorianDate.Day, ref Hour, ref Minute, ref Second); - - // return GregorianDate; - //} - //public static CAACalendarDate GregorianToJulian(int Year, int Month, int Day) - //{ - // CAADate date = CAADate.Create(Year, Month, Day, true); - // date.SetInGregorianCalendar(false); - - // CAACalendarDate JulianDate = new CAACalendarDate(); - // double[] D = date.Get(); - - // JulianDate.Year = (int)D[0]; - // JulianDate.Month = (int)D[1]; - // JulianDate.Day = (int)D[2]; - - // return JulianDate; - //} -//C++ TO C# CONVERTER TODO TASK: The implementation of the following method could not be found: -// static int @int(double value); - public static bool AfterPapalReform(int Year, int Month, double Day) - { - return ((Year > 1582) || ((Year == 1582) && (Month > 10)) || ((Year == 1582) && (Month == 10) && (Day >= 15))); - } - public static bool AfterPapalReformJD(double JD) - { - return (JD >= 2299160.5); - } - public static double DayOfYearJD(double JD, int Year, bool bGregorianCalendar) - { - return JD - DateToJD(Year, 1, 1, bGregorianCalendar) + 1; - } - public static int DaysInMonthForMonth(int Month, bool bLeap) - { - //Validate our parameters - Debug.Assert(Month >= 1 && Month <= 12); - - int[] MonthLength = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0 }; - if (bLeap) - MonthLength[1]++; - - return MonthLength[Month-1]; - } - -//Non Static methods -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: double Julian() const - public double Julian() - { - return m_dblJulian; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: operator double() const - //public static implicit operator double(CAADate ImpliedObject) - //{ - // return ImpliedObject.m_dblJulian; - //} - - - -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int Day() const - public int Day() - { - double[] D = Get(); - return (int)D[2]; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int Month() const - public int Month() - { - double[] D = Get(); - return (int)D[1]; - - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int Year() const - public int Year() - { - double[] D = Get(); - return (int)D[0]; - - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int Hour() const - public int Hour() - { - double[] D = Get(); - return (int)D[3]; - - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int Minute() const - public int Minute() - { - double[] D = Get(); - return (int)D[4]; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: double Second() const - public double Second() - { - double[] D = Get(); - return (int)D[5]; - } - public void Set(int Year, int Month, double Day, double Hour, double Minute, double Second, bool bGregorianCalendar) - { - double dblDay = Day + (Hour/24) + (Minute/1440) + (Second / 86400); - SetJD(DateToJD(Year, Month, dblDay, bGregorianCalendar), bGregorianCalendar); - } - public void SetJD(double JD, bool bGregorianCalendar) - { - m_dblJulian = JD; - SetInGregorianCalendar(bGregorianCalendar); - } - public void SetInGregorianCalendar(bool bGregorianCalendar) - { - bool bAfterPapalReform = (m_dblJulian >= 2299160.5); - - - m_bGregorianCalendar = bGregorianCalendar && bAfterPapalReform; - } - - -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: void Get(int& Year, int& Month, int& Day, int& Hour, int& Minute, double& Second) const - public double[] Get() - { - int Year; - int Month; - int Day; - int Hour; - int Minute; - double Second; - - double JD = m_dblJulian + 0.5; - double tempZ = Math.Floor(JD); - double F = JD - tempZ; - int Z = (int)(tempZ); - int A; - - if (m_bGregorianCalendar) //There is a difference here between the Meeus implementation and this one - //if (Z >= 2299161) //The Meeus implementation automatically assumes the Gregorian Calendar - //came into effect on 15 October 1582 (JD: 2299161), while the CAADate - //implementation has a "m_bGregorianCalendar" value to decide if the date - //was specified in the Gregorian or Julian Calendars. This difference - //means in effect that CAADate fully supports a propalactive version of the - //Julian calendar. This allows you to construct Julian dates after the Papal - //reform in 1582. This is useful if you want to construct dates in countries - //which did not immediately adapt the Gregorian calendar - { - int alpha = (int)((Z - 1867216.25) / 36524.25); - A = Z + 1 + alpha - (int)((int)alpha/4.0); - } - else - A = Z; - - int B = A + 1524; - int C = (int)((B - 122.1) / 365.25); - int D = (int)(365.25 * C); - int E = (int)((B - D) / 30.6001); - - double dblDay = B - D - (int)(30.6001 * E) + F; - Day = (int)(dblDay); - - if (E < 14) - Month = E - 1; - else - Month = E - 13; - - if (Month > 2) - Year = C - 4716; - else - Year = C - 4715; - tempZ = Math.Floor(dblDay); - - F = dblDay - tempZ; - Hour = (int)(F *24); - Minute = (int)((F - (Hour)/24.0)*1440.0); - Second = (F - (Hour / 24.0) - (Minute / 1440.0)) * 86400.0; - - return new double[] { Year, Month, Day, Hour, Minute, Second }; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: CAADate::DAY_OF_WEEK DayOfWeek() const - public DAY_OF_WEEK DayOfWeek() - { - return (DAY_OF_WEEK)(((int)(m_dblJulian + 1.5) % 7)); - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: double DayOfYear() const - public double DayOfYear() - { - int year = (int)Get()[0]; - - return DayOfYearJD(m_dblJulian, year, AfterPapalReform(year, 1, 1)); - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int DaysInMonth() const - public int DaysInMonth() - { - double[] D = Get(); - - int Year = (int)D[0]; - int Month = (int)D[1]; - - - return DaysInMonthForMonth(Month, IsLeap(Year, m_bGregorianCalendar)); - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: int DaysInYear() const - public int DaysInYear() - { - double[] D = Get(); - - int Year = (int)D[0]; - - - if (IsLeap(Year, m_bGregorianCalendar)) - return 366; - else - return 365; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: bool Leap() const - public bool Leap() - { - return IsLeap(Year(), m_bGregorianCalendar); - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: bool InGregorianCalendar() const - public bool InGregorianCalendar() - { - return m_bGregorianCalendar; - } -//C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: -//ORIGINAL LINE: double FractionalYear() const - public double FractionalYear() - { - double[] D = Get(); - - int Year = (int)D[0]; - int Month = (int)D[1]; - int Day = (int)D[2]; - int Hour = (int)D[3]; - int Minute = (int)D[4]; - double Second = D[5]; - - int DaysInYear; - if (IsLeap(Year, m_bGregorianCalendar)) - DaysInYear = 366; - else - DaysInYear = 365; - - return Year + ((m_dblJulian - DateToJD(Year, 1, 1, AfterPapalReform(Year, 1, 1))) / DaysInYear); - } - -//Member variables - protected double m_dblJulian; //Julian Day number for this date - protected bool m_bGregorianCalendar; //Is this date in the Gregorian calendar - - public static int INT(double @value) - { - if (@value >= 0) - return (int)(@value); - else - return (int)(@value - 1); - } -} - -////C++ TO C# CONVERTER WARNING: The declaration of the following method implementation was not found: -////ORIGINAL LINE: int CAADate::INT(double value) - - - -//public class CAADate -//{ -// public int INT(double @value) -// { -// if (@value >= 0) -// return (int)(@value); -// else -// return (int)(@value - 1); -// } -//} \ No newline at end of file diff --git a/engine/csharp_ref/AstroCalc/AADiameters.cs b/engine/csharp_ref/AstroCalc/AADiameters.cs deleted file mode 100644 index 5827a2c4..00000000 --- a/engine/csharp_ref/AstroCalc/AADiameters.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -// -//Module : AADIAMETERS.CPP -//Purpose: Implementation for the algorithms for the semi diameters of the Sun, Moon, Planets and Asteroids -//Created: PJN / 15-01-2004 -//History: None -// -//Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////// Includes ///////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAADiameters -{ -//Static methods - //Tangible Process Only End - - - //////////////////// Implementation /////////////////////////////////////////// - - public static double SunSemidiameterA(double Delta) - { - return 959.63/Delta; - } - public static double MercurySemidiameterA(double Delta) - { - return 3.34/Delta; - } - public static double VenusSemidiameterA(double Delta) - { - return 8.41/Delta; - } - public static double MarsSemidiameterA(double Delta) - { - return 4.68/Delta; - } - public static double JupiterEquatorialSemidiameterA(double Delta) - { - return 98.47/Delta; - } - public static double JupiterPolarSemidiameterA(double Delta) - { - return 91.91/Delta; - } - public static double SaturnEquatorialSemidiameterA(double Delta) - { - return 83.33/Delta; - } - public static double SaturnPolarSemidiameterA(double Delta) - { - return 74.57/Delta; - } - public static double ApparentSaturnPolarSemidiameterA(double Delta, double B) - { - double cosB = Math.Cos(CT.D2R(B)); - return SaturnPolarSemidiameterA(Delta)*Math.Sqrt(1 - 0.199197 *cosB *cosB); - } - public static double UranusSemidiameterA(double Delta) - { - return 34.28/Delta; - } - public static double NeptuneSemidiameterA(double Delta) - { - return 36.56/Delta; - } - public static double MercurySemidiameterB(double Delta) - { - return 3.36/Delta; - } - public static double VenusSemidiameterB(double Delta) - { - return 8.34/Delta; - } - public static double MarsSemidiameterB(double Delta) - { - return 4.68/Delta; - } - public static double JupiterEquatorialSemidiameterB(double Delta) - { - return 98.44/Delta; - } - public static double JupiterPolarSemidiameterB(double Delta) - { - return 92.06/Delta; - } - public static double SaturnEquatorialSemidiameterB(double Delta) - { - return 82.73/Delta; - } - public static double SaturnPolarSemidiameterB(double Delta) - { - return 73.82/Delta; - } - public static double ApparentSaturnPolarSemidiameterB(double Delta, double B) - { - double cosB = Math.Cos(CT.D2R(B)); - return SaturnPolarSemidiameterB(Delta)*Math.Sqrt(1 - 0.203800 *cosB *cosB); - } - public static double UranusSemidiameterB(double Delta) - { - return 35.02/Delta; - } - public static double NeptuneSemidiameterB(double Delta) - { - return 33.50/Delta; - } - public static double PlutoSemidiameterB(double Delta) - { - return 2.07/Delta; - } - public static double GeocentricMoonSemidiameter(double Delta) - { - return CT.R2D(0.272481 *6378.14/Delta)*3600; - } - public static double TopocentricMoonSemidiameter(double DistanceDelta, double Delta, double H, double Latitude, double Height) - { - //Convert to radians - H = CT.H2R(H); - Delta = CT.D2R(Delta); - - double pi = Math.Asin(6378.14/DistanceDelta); - double A = Math.Cos(Delta)*Math.Sin(H); - double B = Math.Cos(Delta)*Math.Cos(H) - CAAGlobe.RhoCosThetaPrime(Latitude, Height)*Math.Sin(pi); - double C = Math.Sin(Delta) - CAAGlobe.RhoSinThetaPrime(Latitude, Height)*Math.Sin(pi); - double q = Math.Sqrt(A *A + B *B + C *C); - - double s = CT.D2R(GeocentricMoonSemidiameter(DistanceDelta)/3600); - return CT.R2D(Math.Asin(Math.Sin(s)/q))*3600; - } - public static double AsteroidDiameter(double H, double A) - { - double x = 3.12 - H/5 - 0.217147 *Math.Log(A); - return Math.Pow(10.0, x); - } - public static double ApparentAsteroidDiameter(double Delta, double d) - { - return 0.0013788 *d/Delta; - } -} - diff --git a/engine/csharp_ref/AstroCalc/AADynamicalTime.cs b/engine/csharp_ref/AstroCalc/AADynamicalTime.cs deleted file mode 100644 index 05c63747..00000000 --- a/engine/csharp_ref/AstroCalc/AADynamicalTime.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Diagnostics; -public static partial class GFX -{ - - - - ////////////////////////////////// Macros / Defines /////////////////////////// - - public static double[] DeltaTTable = { 121, 112, 103, 95, 88, 82, 77, 72, 68, 63, 60, 56, 53, 51, 48, 46, 44, 42, 40, 38, 35, 33, 31, 29, 26, 24, 22, 20, 18, 16, 14, 12, 11, 10, 9, 8, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 14, 13, 13.1, 12.5, 12.2, 12.0, 12.0, 12, 12, 12, 12, 11.9, 11.6, 11, 10.2, 9.2, 8.2, 7.1, 6.2, 5.6, 5.4, 5.3, 5.4, 5.6, 5.9, 6.2, 6.5, 6.8, 7.1, 7.3, 7.5, 7.6, 7.7, 7.3, 6.2, 5.2, 2.7, 1.4, -1.2, -2.8, -3.8, -4.8, -5.5, -5.3, -5.6, -5.7, -5.9, -6, -6.3, -6.5, -6.2, -4.7, -2.8, -0.1, 2.6, 5.3, 7.7, 10.4, 13.3, 16, 18.2, 20.2, 21.2, 22.4, 23.5, 23.8, 24.3, 24, 23.9, 23.9, 23.7, 24, 24.3, 25.3, 26.2, 27.3, 28.2, 29.1, 30, 30.7, 31.4, 32.2, 33.1, 34.0, 35.0, 36.5, 38.3, 40.18, 42.2, 44.5, 46.5, 48.5, 50.54, 52.2, 53.8, 54.9, 55.8, 56.86, 58.31, 59.99, 61.63, 62.97 }; -} -// -//Module : AADYNAMICALTIME.CPP -//Purpose: Implementation for the algorithms which calculate the difference between Dynamical Time and Universal Time -//Created: PJN / 29-12-2003 -//History: PJN / 01-02-2005 1. Fixed a problem with the declaration of the variable "Index" in the function -// CAADynamicalTime::DeltaT. Thanks to Mika Heiskanen for reporting this problem. -// PJN / 26-01-2007 1. Update to fit in with new layout of CAADate class -// PJN / 28-01-2007 1. Further updates to fit in with new layout of CAADate class -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -////////////////////////////////// Includes /////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class DYT// was CAADynamicalTime -{ -//Static methods - - ////////////////////////////////// Implementation ///////////////////////////// - - public static double DeltaT(double JD) - { - //Construct a CAADate from the julian day - DT date = DT.CreateJD(JD, DT.AfterPapalReformJD(JD)); - - double y = date.FractionalYear(); - double T = (y - 2000) / 100; - - double Delta; - if (y < 948) - Delta = 2177 + (497 *T) + (44.1 *T *T); - else if (y < 1620) - Delta = 102 + (102 *T) + (25.3 *T *T); - else if (y < 1998) - { - int Index = (int)((y - 1620) / 2); - Debug.Assert(Index < GFX.DeltaTTable.Length); - - y = y / 2 - Index - 810; - Delta = (GFX.DeltaTTable[Index] + (GFX.DeltaTTable[Index + 1] - GFX.DeltaTTable[Index]) * y); - } - else if (y <= 2000) - { - int nLookupSize = GFX.DeltaTTable.Length; - Delta = GFX.DeltaTTable[nLookupSize-1]; - } - else if (y < 2100) - Delta = 102 + (102 *T) + (25.3 *T *T) + 0.37*(y - 2100); - else - Delta = 102 + (102 *T) + (25.3 *T *T); - - return Delta; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAEarth.cs b/engine/csharp_ref/AstroCalc/AAEarth.cs deleted file mode 100644 index b5ed170a..00000000 --- a/engine/csharp_ref/AstroCalc/AAEarth.cs +++ /dev/null @@ -1,344 +0,0 @@ -using System; -public static partial class GFX -{ - //public static double modf(double orig, ref double intpart) - //{ - // return orig - (intpart = Math.Floor(orig)); - //} - public static VSC[] g_L0EarthCoefficients = { new VSC(175347046, 0, 0), new VSC(3341656, 4.6692568, 6283.0758500), new VSC(34894, 4.62610, 12566.15170), new VSC(3497, 2.7441, 5753.3849), new VSC(3418, 2.8289, 3.5231), new VSC(3136, 3.6277, 77713.7715), new VSC(2676, 4.4181, 7860.4194), new VSC(2343, 6.1352, 3930.2097), new VSC(1324, 0.7425, 11506.7698), new VSC(1273, 2.0371, 529.6910), new VSC(1199, 1.1096, 1577.3435), new VSC(990, 5.233, 5884.927), new VSC(902, 2.045, 26.298), new VSC(857, 3.508, 398.149), new VSC(780, 1.179, 5223.694), new VSC(753, 2.533, 5507.553), new VSC(505, 4.583, 18849.228), new VSC(492, 4.205, 775.523), new VSC(357, 2.920, 0.067), new VSC(317, 5.849, 11790.629), new VSC(284, 1.899, 796.288), new VSC(271, 0.315, 10977.079), new VSC(243, 0.345, 5486.778), new VSC(206, 4.806, 2544.314), new VSC(205, 1.869, 5573.143), new VSC(202, 2.458, 6069.777), new VSC(156, 0.833, 213.299), new VSC(132, 3.411, 2942.463), new VSC(126, 1.083, 20.775), new VSC(115, 0.645, 0.980), new VSC(103, 0.636, 4694.003), new VSC(102, 0.976, 15720.839), new VSC(102, 4.267, 7.114), new VSC(99, 6.21, 2146.17), new VSC(98, 0.68, 155.42), new VSC(86, 5.98, 161000.69), new VSC(85, 1.30, 6275.96), new VSC(85, 3.67, 71430.70), new VSC(80, 1.81, 17260.15), new VSC(79, 3.04, 12036.46), new VSC(75, 1.76, 5088.63), new VSC(74, 3.50, 3154.69), new VSC(74, 4.68, 801.82), new VSC(70, 0.83, 9437.76), new VSC(62, 3.98, 8827.39), new VSC(61, 1.82, 7084.90), new VSC(57, 2.78, 6286.60), new VSC(56, 4.39, 14143.50), new VSC(56, 3.47, 6279.55), new VSC(52, 0.19, 12139.55), new VSC(52, 1.33, 1748.02), new VSC(51, 0.28, 5856.48), new VSC(49, 0.49, 1194.45), new VSC(41, 5.37, 8429.24), new VSC(41, 2.40, 19651.05), new VSC(39, 6.17, 10447.39), new VSC(37, 6.04, 10213.29), new VSC(37, 2.57, 1059.38), new VSC(36, 1.71, 2352.87), new VSC(36, 1.78, 6812.77), new VSC(33, 0.59, 17789.85), new VSC(30, 0.44, 83996.85), new VSC(30, 2.74, 1349.87), new VSC(25, 3.16, 4690.48) }; - - public static VSC[] g_L1EarthCoefficients = { new VSC(628331966747.0, 0, 0), new VSC(206059, 2.678235, 6283.075850), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.590, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.40, 796.30), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.30), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694.00), new VSC(11, 0.77, 553.57), new VSC(10, 1.30, 6286.60), new VSC(10, 4.24, 1349.87), new VSC(9, 2.70, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.30, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48) }; - - public static VSC[] g_L2EarthCoefficients = { new VSC(52919, 0, 0), new VSC(8720, 1.0721, 6283.0758), new VSC(309, 0.867, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.30), new VSC(16, 3.68, 155.42), new VSC(10, 0.76, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.30), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.31, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98) }; - - public static VSC[] g_L3EarthCoefficients = { new VSC(289, 5.844, 6283.076), new VSC(35, 0, 0), new VSC(17, 5.49, 12566.15), new VSC(3, 5.20, 155.42), new VSC(1, 4.72, 3.52), new VSC(1, 5.30, 18849.23), new VSC(1, 5.97, 242.73) }; - - public static VSC[] g_L4EarthCoefficients = { new VSC(114, 3.142, 0), new VSC(8, 4.13, 6283.08), new VSC(1, 3.84, 12566.15) }; - - public static VSC[] g_L5EarthCoefficients = { new VSC(1, 3.14, 0) }; - - - public static VSC[] g_B0EarthCoefficients = { new VSC(280, 3.199, 84334.662), new VSC(102, 5.422, 5507.553), new VSC(80, 3.88, 5223.69), new VSC(44, 3.70, 2352.87), new VSC(32, 4.00, 1577.34) }; - - public static VSC[] g_B1EarthCoefficients = { new VSC(9, 3.90, 5507.55), new VSC(6, 1.73, 5223.69) }; - - public static VSC[] g_B2EarthCoefficients = { new VSC(22378, 3.38509, 10213.28555), new VSC(282, 0, 0), new VSC(173, 5.256, 20426.571), new VSC(27, 3.87, 30639.86) }; - - public static VSC[] g_B3EarthCoefficients = { new VSC(647, 4.992, 10213.286), new VSC(20, 3.14, 0), new VSC(6, 0.77, 20426.57), new VSC(3, 5.44, 30639.86) }; - - public static VSC[] g_B4EarthCoefficients = { new VSC(14, 0.32, 10213.29) }; - - - public static VSC[] g_R0EarthCoefficients = { new VSC(100013989, 0, 0), new VSC(1670700, 3.0984635, 6283.0758500), new VSC(13956, 3.05525, 12566.15170), new VSC(3084, 5.1985, 77713.7715), new VSC(1628, 1.1739, 5753.3849), new VSC(1576, 2.8469, 7860.4194), new VSC(925, 5.453, 11506.770), new VSC(542, 4.564, 3930.210), new VSC(472, 3.661, 5884.927), new VSC(346, 0.964, 5507.553), new VSC(329, 5.900, 5223.694), new VSC(307, 0.299, 5573.143), new VSC(243, 4.273, 11790.629), new VSC(212, 5.847, 1577.344), new VSC(186, 5.022, 10977.079), new VSC(175, 3.012, 18849.228), new VSC(110, 5.055, 5486.778), new VSC(98, 0.89, 6069.78), new VSC(86, 5.69, 15720.84), new VSC(86, 1.27, 161000.69), new VSC(65, 0.27, 17260.15), new VSC(63, 0.92, 529.69), new VSC(57, 2.01, 83996.85), new VSC(56, 5.24, 71430.70), new VSC(49, 3.25, 2544.31), new VSC(47, 2.58, 775.52), new VSC(45, 5.54, 9437.76), new VSC(43, 6.01, 6275.96), new VSC(39, 5.36, 4694.00), new VSC(38, 2.39, 8827.39), new VSC(37, 0.83, 19651.05), new VSC(37, 4.90, 12139.55), new VSC(36, 1.67, 12036.46), new VSC(35, 1.84, 2942.46), new VSC(33, 0.24, 7084.90), new VSC(32, 0.18, 5088.63), new VSC(32, 1.78, 398.15), new VSC(28, 1.21, 6286.60), new VSC(28, 1.90, 6279.55), new VSC(26, 4.59, 10447.39) }; - - public static VSC[] g_R1EarthCoefficients = { new VSC(103019, 1.107490, 6283.075850), new VSC(1721, 1.0644, 12566.1517), new VSC(702, 3.142, 0), new VSC(32, 1.02, 18849.23), new VSC(31, 2.84, 5507.55), new VSC(25, 1.32, 5223.69), new VSC(18, 1.42, 1577.34), new VSC(10, 5.91, 10977.08), new VSC(9, 1.42, 6275.96), new VSC(9, 0.27, 5486.78) }; - - public static VSC[] g_R2EarthCoefficients = { new VSC(4359, 5.7846, 6283.0758), new VSC(124, 5.579, 12566.152), new VSC(12, 3.14, 0), new VSC(9, 3.63, 77713.77), new VSC(6, 1.87, 5573.14), new VSC(3, 5.47, 18849.23) }; - - public static VSC[] g_R3EarthCoefficients = { new VSC(145, 4.273, 6283.076), new VSC(7, 3.92, 12566.15) }; - - public static VSC[] g_R4EarthCoefficients = { new VSC(4, 2.56, 6283.08) }; - - - public static VSC[] g_L1EarthCoefficientsJ2000 = { new VSC(628307584999.0, 0, 0), new VSC(206059, 2.678235, 6283.075850), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.590, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.40, 796.30), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.30), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694.00), new VSC(11, 0.77, 553.57), new VSC(10, 1.30, 6286.60), new VSC(10, 4.24, 1349.87), new VSC(9, 2.70, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.30, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48) }; - - public static VSC[] g_L2EarthCoefficientsJ2000 = { new VSC(8722, 1.0725, 6283.0758), new VSC(991, 3.1416, 0), new VSC(295, 0.437, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.30), new VSC(16, 3.69, 155.42), new VSC(9, 0.30, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.30), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.30, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98) }; - - public static VSC[] g_L3EarthCoefficientsJ2000 = { new VSC(289, 5.842, 6283.076), new VSC(21, 6.05, 12566.15), new VSC(3, 5.20, 155.42), new VSC(3, 3.14, 0), new VSC(1, 4.72, 3.52), new VSC(1, 5.97, 242.73), new VSC(1, 5.54, 18849.23) }; - - public static VSC[] g_L4EarthCoefficientsJ2000 = { new VSC(8, 4.14, 6283.08), new VSC(1, 3.28, 12566.15) }; - - - - public static VSC[] g_B1EarthCoefficientsJ2000 = { new VSC(227778, 3.413766, 6283.075850), new VSC(3806, 3.3706, 12566.1517), new VSC(3620, 0, 0), new VSC(72, 3.33, 18849.23), new VSC(8, 3.89, 5507.55), new VSC(8, 1.79, 5223.69), new VSC(6, 5.20, 2352.87) }; - - public static VSC[] g_B2EarthCoefficientsJ2000 = { new VSC(9721, 5.1519, 6283.07585), new VSC(233, 3.1416, 0), new VSC(134, 0.644, 12566.152), new VSC(7, 1.07, 18849.23) }; - - public static VSC[] g_B3EarthCoefficientsJ2000 = { new VSC(276, 0.595, 6283.076), new VSC(17, 3.14, 0), new VSC(4, 0.12, 12566.15) }; - - public static VSC[] g_B4EarthCoefficientsJ2000 = { new VSC(6, 2.27, 6283.08), new VSC(1, 0, 0) }; -} -// -//Module : AAEARTH.CPP -//Purpose: Implementation for the algorithms which calculate the position of Earth -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////// Includes //////////////////////////////////////// - - - -//////////////////////// Classes ////////////////////////////////////////////// - -public class CAAEarth -{ - //Static methods - public static double EclipticLongitude(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho * rho; - double rhocubed = rhosquared * rho; - double rho4 = rhocubed * rho; - double rho5 = rho4 * rho; - - //Calculate L0 - int nL0Coefficients = GFX.g_L0EarthCoefficients.Length; - double L0 = 0; - int i; - for (i = 0; i < nL0Coefficients; i++) - L0 += GFX.g_L0EarthCoefficients[i].A * Math.Cos(GFX.g_L0EarthCoefficients[i].B + GFX.g_L0EarthCoefficients[i].C * rho); - - //Calculate L1 - int nL1Coefficients = GFX.g_L1EarthCoefficients.Length; - double L1 = 0; - for (i = 0; i < nL1Coefficients; i++) - L1 += GFX.g_L1EarthCoefficients[i].A * Math.Cos(GFX.g_L1EarthCoefficients[i].B + GFX.g_L1EarthCoefficients[i].C * rho); - - //Calculate L2 - int nL2Coefficients = GFX.g_L2EarthCoefficients.Length; - double L2 = 0; - for (i = 0; i < nL2Coefficients; i++) - L2 += GFX.g_L2EarthCoefficients[i].A * Math.Cos(GFX.g_L2EarthCoefficients[i].B + GFX.g_L2EarthCoefficients[i].C * rho); - - //Calculate L3 - int nL3Coefficients = GFX.g_L3EarthCoefficients.Length; - double L3 = 0; - for (i = 0; i < nL3Coefficients; i++) - L3 += GFX.g_L3EarthCoefficients[i].A * Math.Cos(GFX.g_L3EarthCoefficients[i].B + GFX.g_L3EarthCoefficients[i].C * rho); - - //Calculate L4 - int nL4Coefficients = GFX.g_L4EarthCoefficients.Length; - double L4 = 0; - for (i = 0; i < nL4Coefficients; i++) - L4 += GFX.g_L4EarthCoefficients[i].A * Math.Cos(GFX.g_L4EarthCoefficients[i].B + GFX.g_L4EarthCoefficients[i].C * rho); - - //Calculate L5 - int nL5Coefficients = GFX.g_L5EarthCoefficients.Length; - double L5 = 0; - for (i = 0; i < nL5Coefficients; i++) - L5 += GFX.g_L5EarthCoefficients[i].A * Math.Cos(GFX.g_L5EarthCoefficients[i].B + GFX.g_L5EarthCoefficients[i].C * rho); - - double @value = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - - //convert results back to degrees - @value = CT.M360(CT.R2D(@value)); - return @value; - } - public static double EclipticLatitude(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho * rho; - double rhocubed = rhosquared * rho; - double rho4 = rhocubed * rho; - - //Calculate B0 - int nB0Coefficients = GFX.g_B0EarthCoefficients.Length; - double B0 = 0; - int i; - for (i = 0; i < nB0Coefficients; i++) - B0 += GFX.g_B0EarthCoefficients[i].A * Math.Cos(GFX.g_B0EarthCoefficients[i].B + GFX.g_B0EarthCoefficients[i].C * rho); - - //Calculate B1 - int nB1Coefficients = GFX.g_B1EarthCoefficients.Length; - double B1 = 0; - for (i = 0; i < nB1Coefficients; i++) - B1 += GFX.g_B1EarthCoefficients[i].A * Math.Cos(GFX.g_B1EarthCoefficients[i].B + GFX.g_B1EarthCoefficients[i].C * rho); - - //Calculate B2 - int nB2Coefficients = GFX.g_B2EarthCoefficients.Length; - double B2 = 0; - for (i = 0; i < nB2Coefficients; i++) - B2 += GFX.g_B2EarthCoefficients[i].A * Math.Cos(GFX.g_B2EarthCoefficients[i].B + GFX.g_B2EarthCoefficients[i].C * rho); - - //Calculate B3 - int nB3Coefficients = GFX.g_B3EarthCoefficients.Length; - double B3 = 0; - for (i = 0; i < nB3Coefficients; i++) - B3 += GFX.g_B3EarthCoefficients[i].A * Math.Cos(GFX.g_B3EarthCoefficients[i].B + GFX.g_B3EarthCoefficients[i].C * rho); - - //Calculate B4 - int nB4Coefficients = GFX.g_B4EarthCoefficients.Length; - double B4 = 0; - for (i = 0; i < nB4Coefficients; i++) - B4 += GFX.g_B4EarthCoefficients[i].A * Math.Cos(GFX.g_B4EarthCoefficients[i].B + GFX.g_B4EarthCoefficients[i].C * rho); - - double @value = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - - //convert results back to degrees - @value = CT.R2D(@value); - return @value; - } - public static double RadiusVector(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho * rho; - double rhocubed = rhosquared * rho; - double rho4 = rhocubed * rho; - - //Calculate R0 - int nR0Coefficients = GFX.g_R0EarthCoefficients.Length; - double R0 = 0; - int i; - for (i = 0; i < nR0Coefficients; i++) - R0 += GFX.g_R0EarthCoefficients[i].A * Math.Cos(GFX.g_R0EarthCoefficients[i].B + GFX.g_R0EarthCoefficients[i].C * rho); - - //Calculate R1 - int nR1Coefficients = GFX.g_R1EarthCoefficients.Length; - double R1 = 0; - for (i = 0; i < nR1Coefficients; i++) - R1 += GFX.g_R1EarthCoefficients[i].A * Math.Cos(GFX.g_R1EarthCoefficients[i].B + GFX.g_R1EarthCoefficients[i].C * rho); - - //Calculate R2 - int nR2Coefficients = GFX.g_R2EarthCoefficients.Length; - double R2 = 0; - for (i = 0; i < nR2Coefficients; i++) - R2 += GFX.g_R2EarthCoefficients[i].A * Math.Cos(GFX.g_R2EarthCoefficients[i].B + GFX.g_R2EarthCoefficients[i].C * rho); - - //Calculate R3 - int nR3Coefficients = GFX.g_R3EarthCoefficients.Length; - double R3 = 0; - for (i = 0; i < nR3Coefficients; i++) - R3 += GFX.g_R3EarthCoefficients[i].A * Math.Cos(GFX.g_R3EarthCoefficients[i].B + GFX.g_R3EarthCoefficients[i].C * rho); - - //Calculate R4 - int nR4Coefficients = GFX.g_R4EarthCoefficients.Length; - double R4 = 0; - for (i = 0; i < nR4Coefficients; i++) - R4 += GFX.g_R4EarthCoefficients[i].A * Math.Cos(GFX.g_R4EarthCoefficients[i].B + GFX.g_R4EarthCoefficients[i].C * rho); - - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; - } - public static double SunMeanAnomaly(double JD) - { - double T = (JD - 2451545) / 36525; - double Tsquared = T * T; - double Tcubed = Tsquared * T; - return CT.M360(357.5291092 + 35999.0502909 * T - 0.0001536 * Tsquared + Tcubed / 24490000); - } - public static double Eccentricity(double JD) - { - double T = (JD - 2451545) / 36525; - double Tsquared = T * T; - return 1 - 0.002516 * T - 0.0000074 * Tsquared; - } - public static double EclipticLongitudeJ2000(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho * rho; - double rhocubed = rhosquared * rho; - double rho4 = rhocubed * rho; - - //Calculate L0 - int nL0Coefficients = GFX.g_L0EarthCoefficients.Length; - double L0 = 0; - int i; - for (i = 0; i < nL0Coefficients; i++) - L0 += GFX.g_L0EarthCoefficients[i].A * Math.Cos(GFX.g_L0EarthCoefficients[i].B + GFX.g_L0EarthCoefficients[i].C * rho); - - //Calculate L1 - int nL1Coefficients = GFX.g_L1EarthCoefficientsJ2000.Length; - double L1 = 0; - for (i = 0; i < nL1Coefficients; i++) - L1 += GFX.g_L1EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_L1EarthCoefficientsJ2000[i].B + GFX.g_L1EarthCoefficientsJ2000[i].C * rho); - - //Calculate L2 - int nL2Coefficients = GFX.g_L2EarthCoefficientsJ2000.Length; - double L2 = 0; - for (i = 0; i < nL2Coefficients; i++) - L2 += GFX.g_L2EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_L2EarthCoefficientsJ2000[i].B + GFX.g_L2EarthCoefficientsJ2000[i].C * rho); - - //Calculate L3 - int nL3Coefficients = GFX.g_L3EarthCoefficientsJ2000.Length; - double L3 = 0; - for (i = 0; i < nL3Coefficients; i++) - L3 += GFX.g_L3EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_L3EarthCoefficientsJ2000[i].B + GFX.g_L3EarthCoefficientsJ2000[i].C * rho); - - //Calculate L4 - int nL4Coefficients = GFX.g_L4EarthCoefficientsJ2000.Length; - double L4 = 0; - for (i = 0; i < nL4Coefficients; i++) - L4 += GFX.g_L4EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_L4EarthCoefficientsJ2000[i].B + GFX.g_L4EarthCoefficientsJ2000[i].C * rho); - - double @value = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; - - //convert results back to degrees - @value = CT.M360(CT.R2D(@value)); - return @value; - } - public static double EclipticLatitudeJ2000(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho * rho; - double rhocubed = rhosquared * rho; - double rho4 = rhocubed * rho; - - //Calculate B0 - int nB0Coefficients = GFX.g_B0EarthCoefficients.Length; - double B0 = 0; - int i; - for (i = 0; i < nB0Coefficients; i++) - B0 += GFX.g_B0EarthCoefficients[i].A * Math.Cos(GFX.g_B0EarthCoefficients[i].B + GFX.g_B0EarthCoefficients[i].C * rho); - - //Calculate B1 - int nB1Coefficients = GFX.g_B1EarthCoefficientsJ2000.Length; - double B1 = 0; - for (i = 0; i < nB1Coefficients; i++) - B1 += GFX.g_B1EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_B1EarthCoefficientsJ2000[i].B + GFX.g_B1EarthCoefficientsJ2000[i].C * rho); - - //Calculate B2 - int nB2Coefficients = GFX.g_B2EarthCoefficientsJ2000.Length; - double B2 = 0; - for (i = 0; i < nB2Coefficients; i++) - B2 += GFX.g_B2EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_B2EarthCoefficientsJ2000[i].B + GFX.g_B2EarthCoefficientsJ2000[i].C * rho); - - //Calculate B3 - int nB3Coefficients = GFX.g_B3EarthCoefficientsJ2000.Length; - double B3 = 0; - for (i = 0; i < nB3Coefficients; i++) - B3 += GFX.g_B3EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_B3EarthCoefficientsJ2000[i].B + GFX.g_B3EarthCoefficientsJ2000[i].C * rho); - - //Calculate B4 - int nB4Coefficients = GFX.g_B4EarthCoefficientsJ2000.Length; - double B4 = 0; - for (i = 0; i < nB4Coefficients; i++) - B4 += GFX.g_B4EarthCoefficientsJ2000[i].A * Math.Cos(GFX.g_B4EarthCoefficientsJ2000[i].B + GFX.g_B4EarthCoefficientsJ2000[i].C * rho); - - double @value = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - - //convert results back to degrees - @value = CT.R2D(@value); - return @value; - } -} - - - -//////////////////////////// Macros / Defines ///////////////////////////////// - -public class VSC // VSOP87Coefficient -{ - public VSC(double a, double b, double c) - { - A = a; - B = b; - C = c; - } - public double A; - public double B; - public double C; -} diff --git a/engine/csharp_ref/AstroCalc/AAEclipses.cs b/engine/csharp_ref/AstroCalc/AAEclipses.cs deleted file mode 100644 index 32a90774..00000000 --- a/engine/csharp_ref/AstroCalc/AAEclipses.cs +++ /dev/null @@ -1,231 +0,0 @@ -using System.Diagnostics; -using System; -// -//Module : AAECLIPSES.CPP -//Purpose: Implementation for the algorithms which obtain the principal characteristics of an eclipse of the Sun or the Moon -//Created: PJN / 21-01-2004 -//History: PJN / 25-02-2004 1. Calculation of semi durations is now calculated only when required -// PJN / 31-01-2005 1. Fixed a GCC compiler error related to missing include for memset. Thanks to Mika Heiskanen for -// reporting this problem. -// -//Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////////// Includes ///////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAASolarEclipseDetails -{ -//Constructors / Destructors - public CAASolarEclipseDetails() - { - bEclipse = false; - TimeOfMaximumEclipse = 0; - F = 0; - u = 0; - gamma = 0; - GreatestMagnitude = 0; - } - -//Member variables - public bool bEclipse; - public double TimeOfMaximumEclipse; - public double F; - public double u; - public double gamma; - public double GreatestMagnitude; -} - - -public class CAALunarEclipseDetails -{ -//Constructors / Destructors - public CAALunarEclipseDetails() - { - bEclipse = false; - TimeOfMaximumEclipse = 0; - F = 0; - u = 0; - gamma = 0; - PenumbralRadii = 0; - UmbralRadii = 0; - PenumbralMagnitude = 0; - UmbralMagnitude = 0; - PartialPhaseSemiDuration = 0; - TotalPhaseSemiDuration = 0; - PartialPhasePenumbraSemiDuration = 0; - } - -//Member variables - public bool bEclipse; - public double TimeOfMaximumEclipse; - public double F; - public double u; - public double gamma; - public double PenumbralRadii; - public double UmbralRadii; - public double PenumbralMagnitude; - public double UmbralMagnitude; - public double PartialPhaseSemiDuration; - public double TotalPhaseSemiDuration; - public double PartialPhasePenumbraSemiDuration; -} - -public class CAAEclipses -{ - //Static methods - public static CAASolarEclipseDetails CalculateSolar(double k) - { -#if _DEBUG - double intp = 0; - bool bSolarEclipse = (GlobalMembersStdafx.modf(k, ref intp) == 0); - Debug.Assert(bSolarEclipse); -#endif - - double Mdash = 0; - return Calculate(k, ref Mdash); - } - public static CAALunarEclipseDetails CalculateLunar(double k) - { -#if _DEBUG - double intp = 0; - bool bSolarEclipse = (GlobalMembersStdafx.modf(k, ref intp) == 0); - Debug.Assert(!bSolarEclipse); -#endif - - double Mdash = 0; - CAASolarEclipseDetails solarDetails = Calculate(k, ref Mdash); - - //What will be the return value - CAALunarEclipseDetails details = new CAALunarEclipseDetails(); - details.bEclipse = solarDetails.bEclipse; - details.F = solarDetails.F; - details.gamma = solarDetails.gamma; - details.TimeOfMaximumEclipse = solarDetails.TimeOfMaximumEclipse; - details.u = solarDetails.u; - - if (details.bEclipse) - { - details.PenumbralRadii = 1.2848 + details.u; - details.UmbralRadii = 0.7403 - details.u; - double fgamma = Math.Abs(details.gamma); - details.PenumbralMagnitude = (1.5573 + details.u - fgamma) / 0.5450; - details.UmbralMagnitude = (1.0128 - details.u - fgamma) / 0.5450; - - double p = 1.0128 - details.u; - double t = 0.4678 - details.u; - double n = 0.5458 + 0.0400 * Math.Cos(Mdash); - - double gamma2 = details.gamma * details.gamma; - double p2 = p * p; - if (p2 >= gamma2) - details.PartialPhaseSemiDuration = 60 / n * Math.Sqrt(p2 - gamma2); - - double t2 = t * t; - if (t2 >= gamma2) - details.TotalPhaseSemiDuration = 60 / n * Math.Sqrt(t2 - gamma2); - - double h = 1.5573 + details.u; - double h2 = h * h; - if (h2 >= gamma2) - details.PartialPhasePenumbraSemiDuration = 60 / n * Math.Sqrt(h2 - gamma2); - } - - return details; - } - - //Tangible Process Only End - - - //////////////////////////// Implementation /////////////////////////////////// - - protected static CAASolarEclipseDetails Calculate(double k, ref double Mdash) - { - //Are we looking for a solar or lunar eclipse - double intp = Math.Floor(k); - bool bSolarEclipse = ((k - intp) == 0); - - //What will be the return value - CAASolarEclipseDetails details = new CAASolarEclipseDetails(); - - //convert from K to T - double T = k / 1236.85; - double T2 = T * T; - double T3 = T2 * T; - double T4 = T3 * T; - - double E = 1 - 0.002516 * T - 0.0000074 * T2; - - double M = CAACoordinateTransformation.MapTo0To360Range(2.5534 + 29.10535670 * k - 0.0000014 * T2 - 0.00000011 * T3); - M = CAACoordinateTransformation.DegreesToRadians(M); - - Mdash = CAACoordinateTransformation.MapTo0To360Range(201.5643 + 385.81693528 * k + 0.0107582 * T2 + 0.00001238 * T3 - 0.000000058 * T4); - Mdash = CAACoordinateTransformation.DegreesToRadians(Mdash); - - double omega = CAACoordinateTransformation.MapTo0To360Range(124.7746 - 1.56375588 * k + 0.0020672 * T2 + 0.00000215 * T3); - omega = CAACoordinateTransformation.DegreesToRadians(omega); - - double F = CAACoordinateTransformation.MapTo0To360Range(160.7108 + 390.67050284 * k - 0.0016118 * T2 - 0.00000227 * T3 + 0.00000001 * T4); - details.F = F; - double Fdash = F - 0.02665 * Math.Sin(omega); - - F = CAACoordinateTransformation.DegreesToRadians(F); - Fdash = CAACoordinateTransformation.DegreesToRadians(Fdash); - - //Do the first check to see if we have an eclipse - if (Math.Abs(Math.Sin(F)) > 0.36) - return details; - - double A1 = CAACoordinateTransformation.MapTo0To360Range(299.77 + 0.107408 * k - 0.009173 * T2); - A1 = CAACoordinateTransformation.DegreesToRadians(A1); - - details.TimeOfMaximumEclipse = CAAMoonPhases.MeanPhase(k); - - double DeltaJD = 0; - if (bSolarEclipse) - DeltaJD += -0.4075 * Math.Sin(Mdash) + 0.1721 * E * Math.Sin(M); - else - DeltaJD += -0.4065 * Math.Sin(Mdash) + 0.1727 * E * Math.Sin(M); - DeltaJD += 0.0161 * Math.Sin(2 * Mdash) + -0.0097 * Math.Sin(2 * Fdash) + 0.0073 * E * Math.Sin(Mdash - M) + -0.0050 * E * Math.Sin(Mdash + M) + -0.0023 * Math.Sin(Mdash - 2 * Fdash) + 0.0021 * E * Math.Sin(2 * M) + 0.0012 * Math.Sin(Mdash + 2 * Fdash) + 0.0006 * E * Math.Sin(2 * Mdash + M) + -0.0004 * Math.Sin(3 * Mdash) + -0.0003 * E * Math.Sin(M + 2 * Fdash) + 0.0003 * Math.Sin(A1) + -0.0002 * E * Math.Sin(M - 2 * Fdash) + -0.0002 * E * Math.Sin(2 * Mdash - M) + -0.0002 * Math.Sin(omega); - - details.TimeOfMaximumEclipse += DeltaJD; - - double P = 0.2070 * E * Math.Sin(M) + 0.0024 * E * Math.Sin(2 * M) + -0.0392 * Math.Sin(Mdash) + 0.0116 * Math.Sin(2 * Mdash) + -0.0073 * E * Math.Sin(Mdash + M) + 0.0067 * E * Math.Sin(Mdash - M) + 0.0118 * Math.Sin(2 * Fdash); - - double Q = 5.2207 + -0.0048 * E * Math.Cos(M) + 0.0020 * E * Math.Cos(2 * M) + -0.3299 * Math.Cos(Mdash) + -0.0060 * E * Math.Cos(Mdash + M) + 0.0041 * E * Math.Cos(Mdash - M); - - double W = Math.Abs(Math.Cos(Fdash)); - - details.gamma = (P * Math.Cos(Fdash) + Q * Math.Sin(Fdash)) * (1 - 0.0048 * W); - - details.u = 0.0059 + 0.0046 * E * Math.Cos(M) + -0.0182 * Math.Cos(Mdash) + 0.0004 * Math.Cos(2 * Mdash) + -0.0005 * Math.Cos(M + Mdash); - - //Check to see if the eclipse is visible from the Earth's surface - if (Math.Abs(details.gamma) > (1.5433 + details.u)) - return details; - - //We have an eclipse at this time - details.bEclipse = true; - - //In the case of a partial eclipse, calculate its magnitude - double fgamma = Math.Abs(details.gamma); - if (((fgamma > 0.9972) && (fgamma < 1.5433 + details.u))) - details.GreatestMagnitude = (1.5433 + details.u - fgamma) / (0.5461 + 2 * details.u); - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAEclipticalElements.cs b/engine/csharp_ref/AstroCalc/AAEclipticalElements.cs deleted file mode 100644 index a1a06258..00000000 --- a/engine/csharp_ref/AstroCalc/AAEclipticalElements.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -// -//Module : AAECLIPTICALELEMENTS.CPP -//Purpose: Implementation for the algorithms which map the ecliptical elements from one equinox to another -//Created: PJN / 29-12-2003 -//History: PJN / 29-11-2006 1. Fixed a bug where CAAEclipticalElements::Calculate and CAAEclipticalElements::FK4B1950ToFK5J2000 -// would return the incorrect value for the reduced inclination when the initial inclination value -// was > 90 degrees. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////// Includes ////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAEclipticalElementDetails -{ -//Constructors / Destructors - public CAAEclipticalElementDetails() - { - i = 0; - w = 0; - omega = 0; - } - -//Member variables - public double i; - public double w; - public double omega; -} - -public class CAAEclipticalElements -{ -//Static methods - - /////////////////////////// Implementation //////////////////////////////////// - - public static CAAEclipticalElementDetails Calculate(double i0, double w0, double omega0, double JD0, double JD) - { - double T = (JD0 - 2451545.0) / 36525; - double Tsquared = T *T; - double t = (JD - JD0) / 36525; - double tsquared = t *t; - double tcubed = tsquared * t; - - //Now convert to radians - double i0rad = CT.D2R(i0); - double omega0rad = CT.D2R(omega0); - - double eta = (47.0029 - 0.06603 *T + 0.000598 *Tsquared)*t + (-0.03302 + 0.000598 *T)*tsquared + 0.00006 *tcubed; - eta = CT.D2R(CT.DMS2D(0, 0, eta)); - - double pi = 174.876384 *3600 + 3289.4789 *T + 0.60622 *Tsquared - (869.8089 + 0.50491 *T)*t + 0.03536 *tsquared; - pi = CT.D2R(CT.DMS2D(0, 0, pi)); - - double p = (5029.0966 + 2.22226 *T - 0.000042 *Tsquared)*t + (1.11113 - 0.000042 *T)*tsquared - 0.000006 *tcubed; - p = CT.D2R(CT.DMS2D(0, 0, p)); - - double sini0rad = Math.Sin(i0rad); - double cosi0rad = Math.Cos(i0rad); - double sinomega0rad_pi = Math.Sin(omega0rad - pi); - double cosomega0rad_pi = Math.Cos(omega0rad - pi); - double sineta = Math.Sin(eta); - double coseta = Math.Cos(eta); - double A = sini0rad *sinomega0rad_pi; - double B = -sineta *cosi0rad + coseta *sini0rad *cosomega0rad_pi; - double irad = Math.Asin(Math.Sqrt(A *A + B *B)); - - CAAEclipticalElementDetails details = new CAAEclipticalElementDetails(); - - details.i = CT.R2D(irad); - double cosi = cosi0rad *coseta + sini0rad *sineta *cosomega0rad_pi; - if (cosi < 0) - details.i = 180 - details.i; - - double phi = pi + p; - details.omega = CT.M360(CT.R2D(Math.Atan2(A, B) + phi)); - - A = -sineta *sinomega0rad_pi; - B = sini0rad *coseta - cosi0rad *sineta *cosomega0rad_pi; - double deltaw = CT.R2D(Math.Atan2(A, B)); - details.w = CT.M360(w0 + deltaw); - - return details; - } - public static CAAEclipticalElementDetails FK4B1950ToFK5J2000(double i0, double w0, double omega0) - { - //convert to radians - double L = CT.D2R(5.19856209); - double J = CT.D2R(0.00651966); - double i0rad = CT.D2R(i0); - double omega0rad = CT.D2R(omega0); - double sini0rad = Math.Sin(i0rad); - double cosi0rad = Math.Cos(i0rad); - - //Calculate some values used later - double cosJ = Math.Cos(J); - double sinJ = Math.Sin(J); - double W = L + omega0rad; - double cosW = Math.Cos(W); - double sinW = Math.Sin(W); - double A = sinJ *sinW; - double B = sini0rad *cosJ + cosi0rad *sinJ *cosW; - - //Calculate the values - CAAEclipticalElementDetails details = new CAAEclipticalElementDetails(); - details.i = CT.R2D(Math.Asin(Math.Sqrt(A *A + B *B))); - double cosi = cosi0rad *cosJ - sini0rad *sinJ *cosW; - if (cosi < 0) - details.i = 180 - details.i; - - details.w = CT.M360(w0 + CT.R2D(Math.Atan2(A, B))); - details.omega = CT.M360(CT.R2D(Math.Atan2(sini0rad *sinW, cosi0rad *sinJ + sini0rad *cosJ *cosW)) - 4.50001688); - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAElementsPlanetaryOrbit.cs b/engine/csharp_ref/AstroCalc/AAElementsPlanetaryOrbit.cs deleted file mode 100644 index 2ef82d9e..00000000 --- a/engine/csharp_ref/AstroCalc/AAElementsPlanetaryOrbit.cs +++ /dev/null @@ -1,667 +0,0 @@ -// -//Module : AAELEMENTSPLANETARYORBIT.CPP -//Purpose: Implementation for the algorithms to calculate the elements of the planetary orbits -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////// Includes ////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class EPO // was CAAElementsPlanetaryOrbit -{ -//Static methods - - /////////////////////////// Implementation //////////////////////////////////// - - public static double MercuryMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(252.250906 + 149474.0722491 *T + 0.00030350 *Tsquared + 0.000000018 *Tcubed); - } - - //C++ TO C# CONVERTER NOTE: Embedded comments are not maintained by C++ to C# Converter - //ORIGINAL LINE: double CAAElementsPlanetaryOrbit::MercurySemimajorAxis(double /*JD*/) - public static double MercurySemimajorAxis(double UnnamedParameter1) - { - return 0.387098310; - } - public static double MercuryEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.20563175 + 0.000020407 *T - 0.0000000283 *Tsquared - 0.00000000018 *Tcubed; - } - public static double MercuryInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(7.004986 + 0.0018215 *T - 0.00001810 *Tsquared + 0.000000056 *Tcubed); - } - public static double MercuryLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(48.330893 + 1.1861883 *T + 0.00017542 *Tsquared + 0.000000215 *Tcubed); - } - public static double MercuryLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(77.456119 + 1.5564776 *T + 0.00029544 *Tsquared + 0.000000009 *Tcubed); - } - - public static double VenusMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(181.979801 + 58519.2130302 *T + 0.00031014 *Tsquared + 0.000000015 *Tcubed); - } - - //C++ TO C# CONVERTER NOTE: Embedded comments are not maintained by C++ to C# Converter - //ORIGINAL LINE: double CAAElementsPlanetaryOrbit::VenusSemimajorAxis(double /*JD*/) - public static double VenusSemimajorAxis(double UnnamedParameter1) - { - return 0.723329820; - } - public static double VenusEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.00677192 - 0.000047765 *T + 0.0000000981 *Tsquared + 0.00000000046 *Tcubed; - } - public static double VenusInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(3.394662 + 0.0010037 *T - 0.00000088 *Tsquared - 0.000000007 *Tcubed); - } - public static double VenusLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(76.679920 + 0.9011206 *T + 0.00040618 *Tsquared - 0.000000093 *Tcubed); - } - public static double VenusLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(131.563703 + 1.4022288 *T - 0.00107618 *Tsquared - 0.000005678 *Tcubed); - } - - public static double EarthMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(100.466457 + 36000.7698278 *T + 0.00030322 *Tsquared + 0.000000020 *Tcubed); - } - - //C++ TO C# CONVERTER NOTE: Embedded comments are not maintained by C++ to C# Converter - //ORIGINAL LINE: double CAAElementsPlanetaryOrbit::EarthSemimajorAxis(double /*JD*/) - public static double EarthSemimajorAxis(double UnnamedParameter1) - { - return 1.000001018; - } - public static double EarthEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.01670863 - 0.000042037 *T - 0.0000001267 *Tsquared + 0.00000000014 *Tcubed; - } - - //C++ TO C# CONVERTER NOTE: Embedded comments are not maintained by C++ to C# Converter - //ORIGINAL LINE: double CAAElementsPlanetaryOrbit::EarthInclination(double /*JD*/) - public static double EarthInclination(double UnnamedParameter1) - { - return 0; - } - public static double EarthLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(102.937348 + 1.17195366 *T + 0.00045688 *Tsquared - 0.000000018 *Tcubed); - } - - public static double MarsMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(355.433000 + 19141.6964471 *T + 0.00031052 *Tsquared + 0.000000016 *Tcubed); - } - - //C++ TO C# CONVERTER NOTE: Embedded comments are not maintained by C++ to C# Converter - //ORIGINAL LINE: double CAAElementsPlanetaryOrbit::MarsSemimajorAxis(double /*JD*/) - public static double MarsSemimajorAxis(double UnnamedParameter1) - { - return 1.523679342; - } - public static double MarsEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.09340065 + 0.000090484 *T - 0.0000000806 *Tsquared - 0.00000000025 *Tcubed; - } - public static double MarsInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(1.849726 - 0.0006011 *T + 0.00001276 *Tsquared - 0.000000007 *Tcubed); - } - public static double MarsLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(49.588093 + 0.7720959 *T + 0.00001557 *Tsquared + 0.000002267 *Tcubed); - } - public static double MarsLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(336.060234 + 1.8410449 *T + 0.00013477 *Tsquared + 0.000000536 *Tcubed); - } - - public static double JupiterMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(34.351519 + 3036.3027748 *T + 0.00022330 *Tsquared + 0.000000037 *Tcubed); - } - public static double JupiterSemimajorAxis(double JD) - { - double T = (JD - 2451545.0) / 36525; - - return 5.202603209 + 0.0000001913 *T; - } - public static double JupiterEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.04849793 + 0.000163225 *T - 0.0000004714 *Tsquared - 0.00000000201 *Tcubed; - } - public static double JupiterInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(1.303267 - 0.0054965 *T + 0.00000466 *Tsquared - 0.000000002 *Tcubed); - } - public static double JupiterLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(100.464407 + 1.0209774 *T + 0.00040315 *Tsquared + 0.000000404 *Tcubed); - } - public static double JupiterLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(14.331207 + 1.6126352 *T + 0.00103042 *Tsquared - 0.000004464 *Tcubed); - } - - public static double SaturnMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(50.077444 + 1223.5110686 *T + 0.00051908 *Tsquared - 0.000000030 *Tcubed); - } - public static double SaturnSemimajorAxis(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - - return 9.554909192 - 0.0000021390 *T + 0.000000004 *Tsquared; - } - public static double SaturnEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.05554814 - 0.0003446641 *T - 0.0000006436 *Tsquared + 0.00000000340 *Tcubed; - } - public static double SaturnInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(2.488879 - 0.0037362 *T - 0.00001519 *Tsquared + 0.000000087 *Tcubed); - } - public static double SaturnLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(113.665503 + 0.8770880 *T - 0.00012176 *Tsquared - 0.000002249 *Tcubed); - } - public static double SaturnLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(93.057237 + 1.19637613 *T + 0.00083753 *Tsquared + 0.000004928 *Tcubed); - } - - public static double UranusMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(314.055005 + 429.8640561 *T + 0.00030390 *Tsquared + 0.000000026 *Tcubed); - } - public static double UranusSemimajorAxis(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - - return 19.218446062 - 0.0000000372 *T + 0.00000000098 *Tsquared; - } - public static double UranusEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.04638122 - 0.000027293 *T + 0.0000000789 *Tsquared + 0.00000000024 *Tcubed; - } - public static double UranusInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(0.773197 + 0.0007744 *T + 0.00003749 *Tsquared - 0.000000092 *Tcubed); - } - public static double UranusLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(74.005957 + 0.5211278 *T + 0.00133947 *Tsquared + 0.000018484 *Tcubed); - } - public static double UranusLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(173.005291 + 1.4863790 *T + 0.00021406 *Tsquared + 0.000000434 *Tcubed); - } - - public static double NeptuneMeanLongitude(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(304.348665 + 219.8833092 *T + 0.00030882 *Tsquared + 0.000000018 *Tcubed); - } - public static double NeptuneSemimajorAxis(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - - return 30.110386869 - 0.0000001663 *T + 0.00000000069 *Tsquared; - } - public static double NeptuneEccentricity(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tcubed = T *T *T; - - return 0.00945575 + 0.000006033 *T - 0.00000000005 *Tcubed; - } - public static double NeptuneInclination(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(1.769953 - 0.0093082 *T - 0.00000708 *Tsquared + 0.000000027 *Tcubed); - } - public static double NeptuneLongitudeAscendingNode(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(131.784057 + 1.1022039 *T + 0.00025952 *Tsquared - 0.000000637 *Tcubed); - } - public static double NeptuneLongitudePerihelion(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(48.120276 + 1.4262957 *T + 0.00038434 *Tsquared + 0.000000020 *Tcubed); - } - - public static double MercuryMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(252.250906 + 149472.6746358 *T - 0.00000536 *Tsquared + 0.000000002 *Tcubed); - } - public static double MercuryInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(7.004986 - 0.0059516 *T + 0.00000080 *Tsquared + 0.000000043 *Tcubed); - } - public static double MercuryLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(48.330893 - 0.1254227 *T - 0.00008833 *Tsquared - 0.000000200 *Tcubed); - } - public static double MercuryLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(77.456119 + 0.1588643 *T - 0.00001342 *Tsquared - 0.000000007 *Tcubed); - } - - public static double VenusMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(181.979801 + 58517.8156760 *T + 0.00000165 *Tsquared - 0.000000002 *Tcubed); - } - public static double VenusInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(3.394662 - 0.0008568 *T - 0.00003244 *Tsquared + 0.000000009 *Tcubed); - } - public static double VenusLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(76.679920 - 0.2780134 *T - 0.00014257 *Tsquared - 0.000000164 *Tcubed); - } - public static double VenusLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(131.563703 + 0.0048746 *T - 0.00138467 *Tsquared - 0.000005695 *Tcubed); - } - - public static double EarthMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(100.466457 + 35999.3728565 *T - 0.00000568 *Tsquared - 0.000000001 *Tcubed); - } - public static double EarthInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return 0.0130548 *T - 0.00000931 *Tsquared - 0.000000034 *Tcubed; - } - public static double EarthLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(174.873176 - 0.241098 *T + 0.00004262 *Tsquared + 0.000000001 *Tcubed); - } - public static double EarthLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(102.937348 + 0.3225654 *T + 0.00014799 *Tsquared - 0.000000039 *Tcubed); - } - - public static double MarsMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(355.433000 + 19140.2993039 *T + 0.00000262 *Tsquared - 0.000000003 *Tcubed); - } - public static double MarsInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(1.849726 - 0.0081477 *T - 0.00002255 *Tsquared - 0.000000029 *Tcubed); - } - public static double MarsLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(49.588093 - 0.2950250 *T - 0.00064048 *Tsquared - 0.000001964 *Tcubed); - } - public static double MarsLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(336.060234 + 0.4439016 *T - 0.00017313 *Tsquared + 0.000000518 *Tcubed); - } - - public static double JupiterMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(34.351519 + 3034.9056606 *T - 0.00008501 *Tsquared + 0.000000016 *Tcubed); - } - public static double JupiterInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(1.303267 - 0.0019877 *T + 0.00003320 *Tsquared + 0.000000097 *Tcubed); - } - public static double JupiterLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(100.464407 + 0.1767232 *T + 0.00090700 *Tsquared - 0.000007272 *Tcubed); - } - public static double JupiterLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(14.331207 + 0.2155209 *T + 0.00072211 *Tsquared - 0.000004485 *Tcubed); - } - - public static double SaturnMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(50.077444 + 1222.1138488 *T + 0.00021004 *Tsquared - 0.000000046 *Tcubed); - } - public static double SaturnInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(2.488879 + 0.0025514 *T - 0.00004906 *Tsquared + 0.000000017 *Tcubed); - } - public static double SaturnLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(113.665503 - 0.2566722 *T - 0.00018399 *Tsquared + 0.000000480 *Tcubed); - } - public static double SaturnLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(93.057237 + 0.5665415 *T + 0.00052850 *Tsquared + 0.000004912 *Tcubed); - } - - public static double UranusMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(314.055005 + 428.4669983 *T - 0.00000486 *Tsquared + 0.000000006 *Tcubed); - } - public static double UranusInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(0.773197 - 0.0016869 *T + 0.00000349 *Tsquared + 0.000000016 *Tcubed); - } - public static double UranusLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(74.005957 + 0.0741431 *T + 0.00040539 *Tsquared + 0.000000119 *Tcubed); - } - public static double UranusLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(173.005291 + 0.0893212 *T - 0.00009470 *Tsquared + 0.000000414 *Tcubed); - } - - public static double NeptuneMeanLongitudeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(304.348665 + 218.4862002 *T + 0.00000059 *Tsquared - 0.000000002 *Tcubed); - } - public static double NeptuneInclinationJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - - return CT.M360(1.769953 + 0.0002256 *T + 0.00000023 *Tsquared); - } - public static double NeptuneLongitudeAscendingNodeJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - double Tcubed = Tsquared *T; - - return CT.M360(131.784057 - 0.0061651 *T - 0.00000219 *Tsquared - 0.000000078 *Tcubed); - } - public static double NeptuneLongitudePerihelionJ2000(double JD) - { - double T = (JD - 2451545.0) / 36525; - double Tsquared = T *T; - - return CT.M360(48.120276 + 0.0291866 *T + 0.00007610 *Tsquared); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAElliptical.cs b/engine/csharp_ref/AstroCalc/AAElliptical.cs deleted file mode 100644 index a31a4358..00000000 --- a/engine/csharp_ref/AstroCalc/AAElliptical.cs +++ /dev/null @@ -1,647 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using wwtlib; -//using TerraViewer; -// -//Module : AAELLIPTICAL.CPP -//Purpose: Implementation for the algorithms for an elliptical orbit -//Created: PJN / 29-12-2003 -//History: PJN / 24-05-2004 1. Fixed a missing break statement in CAAElliptical::Calculate. Thanks to -// Carsten A. Arnholm for reporting this bug. -// 2. Also fixed an issue with the calculation of the apparent distance to -// the Sun. -// PJN / 31-12-2004 1. Fix for CAAElliptical::MinorPlanetMagnitude where the phase angle was -// being incorrectly converted from Radians to Degress when it was already -// in degrees. Thanks to Martin Burri for reporting this problem. -// PJN / 05-06-2006 1. Fixed a bug in CAAElliptical::Calculate(double JD, EllipticalObject object) -// where the correction for nutation was incorrectly using the Mean obliquity of -// the ecliptic instead of the true value. The results from the test program now -// agree much more closely with the example Meeus provides which is the position -// of Venus on 1992 Dec. 20 at 0h Dynamical Time. I've also checked the positions -// against the JPL Horizons web site and the agreement is much better. Because the -// True obliquity of the Ecliptic is defined as the mean obliquity of the ecliptic -// plus the nutation in obliquity, it is relatively easy to determine the magnitude -// of error this was causing. From the chapter on Nutation in the book, and -// specifically the table which gives the cosine coefficients for nutation in -// obliquity you can see that the absolute worst case error would be the sum of the -// absolute values of all of the coefficients and would have been c. 10 arc seconds -// of degree, which is not a small amount!. This value would be an absolute worst -// case and I would expect the average error value to be much much smaller -// (probably much less than an arc second). Anyway the bug has now been fixed. -// Thanks to Patrick Wong for pointing out this rather significant bug. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -////////////////////////////// Includes /////////////////////////////////////// - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class EOE // was CAAEllipticalObjectElements -{ - //Constructors / Destructors - public EOE() - { - a = 0; - e = 0; - i = 0; - w = 0; - omega = 0; - JDEquinox = 0; - T = 0; - } - - internal static EOE Create(BinaryReader br) - { - EOE tmp = new EOE(); - - tmp.a = br.ReadSingle(); - tmp.e = br.ReadSingle(); - tmp.i = br.ReadSingle(); - tmp.w = br.ReadSingle(); - tmp.omega = br.ReadSingle(); - tmp.JDEquinox = br.ReadSingle(); - tmp.T = br.ReadSingle(); - return tmp; - } - - //public CAAEllipticalObjectElements(BinaryReader br) - //{ - // a = br.ReadSingle(); - // e = br.ReadSingle(); - // i = br.ReadSingle(); - // w = br.ReadSingle(); - // omega = br.ReadSingle(); - // JDEquinox = br.ReadSingle(); - // T = br.ReadSingle(); - //} - - //public CAAEllipticalObjectElements(string line1, string line2, double gravity) - //{ - // JDEquinox = SpaceTimeController.TwoLineDateToJulian(line1.Substring(18,14)); - // e = double.Parse("0." + line2.Substring(26, 7)); - // i = double.Parse(line2.Substring(8, 8)); - // omega = double.Parse(line2.Substring(17, 8)); - // w = double.Parse(line2.Substring(34, 8)); - // double revs = double.Parse(line2.Substring(52, 11)); - // double meanAnomoly = double.Parse(line2.Substring(43, 8)); - // n = revs * 360.0; - // double part =(86400.0/revs)/(Math.PI*2.0); - // a = Math.Pow((part*part)*gravity,1.0/3.0); - // T = JDEquinox - (meanAnomoly / n); - - - //} - - - //public void WriteBin(BinaryWriter bw) - //{ - // bw.Write((float)a); - // bw.Write((float)e); - // bw.Write((float)i); - // bw.Write((float)w); - // bw.Write((float)omega); - // bw.Write((float)JDEquinox); - // bw.Write((float)T); - //} - //member variables - public double a; - public double e; - public double i; - public double w; - public double omega; - public double JDEquinox; - public double T; - public double n; - - public double meanAnnomolyOut; - - -} - -public class EPD // was CAAEllipticalPlanetaryDetails -{ -//Constructors / Destructors - public EPD() - { - ApparentGeocentricLongitude = 0; - ApparentGeocentricLatitude = 0; - ApparentGeocentricDistance = 0; - ApparentLightTime = 0; - ApparentGeocentricRA = 0; - ApparentGeocentricDeclination = 0; - } - -//Member variables - public double ApparentGeocentricLongitude; - public double ApparentGeocentricLatitude; - public double ApparentGeocentricDistance; - public double ApparentLightTime; - public double ApparentGeocentricRA; - public double ApparentGeocentricDeclination; -} - -public class EOD // was CAAEllipticalObjectDetails -{ -//Constructors / Destructors - public EOD() - { - HeliocentricEclipticLongitude = 0; - HeliocentricEclipticLatitude = 0; - TrueGeocentricRA = 0; - TrueGeocentricDeclination = 0; - TrueGeocentricDistance = 0; - TrueGeocentricLightTime = 0; - AstrometricGeocenticRA = 0; - AstrometricGeocentricDeclination = 0; - AstrometricGeocentricDistance = 0; - AstrometricGeocentricLightTime = 0; - Elongation = 0; - PhaseAngle = 0; - } - -//Member variables - public C3D HeliocentricRectangularEquatorial = new C3D(); - public C3D HeliocentricRectangularEcliptical = new C3D(); - public double HeliocentricEclipticLongitude; - public double HeliocentricEclipticLatitude; - public double TrueGeocentricRA; - public double TrueGeocentricDeclination; - public double TrueGeocentricDistance; - public double TrueGeocentricLightTime; - public double AstrometricGeocenticRA; - public double AstrometricGeocentricDeclination; - public double AstrometricGeocentricDistance; - public double AstrometricGeocentricLightTime; - public double Elongation; - public double PhaseAngle; -} -public enum EO : int // was EllipticalObject -{ - SUN = 0, - MERCURY = 1, - VENUS = 2, - MARS = 3, - JUPITER = 4, - SATURN = 5, - URANUS = 6, - NEPTUNE = 7, - PLUTO = 8 -} -public class ELL // was CAAElliptical -{ -//Enums - - -//Static methods - //Tangible Process Only End - - - ////////////////////////////// Implementation ///////////////////////////////// - - public static double DistanceToLightTime(double Distance) - { - return Distance * 0.0057755183; - } - public static EPD Calculate(double JD, EO @object) - { - //What will the the return value - EPD details = new EPD(); - - double JD0 = JD; - double L0 = 0; - double B0 = 0; - double R0 = 0; - double cosB0 = 0; - if (@object != EO.SUN) - { - L0 = CAAEarth.EclipticLongitude(JD0); - B0 = CAAEarth.EclipticLatitude(JD0); - R0 = CAAEarth.RadiusVector(JD0); - L0 = CT.D2R(L0); - B0 = CT.D2R(B0); - cosB0 = Math.Cos(B0); - } - - - //Calculate the initial values - double L = 0; - double B = 0; - double R = 0; - - double Lrad; - double Brad; - double cosB; - double cosL; - double x; - double y; - double z; - bool bRecalc = true; - bool bFirstRecalc = true; - double LPrevious = 0; - double BPrevious = 0; - double RPrevious = 0; - while (bRecalc) - { - switch (@object) - { - case EO.SUN: - { - L = CAASun.GeometricEclipticLongitude(JD0); - B = CAASun.GeometricEclipticLatitude(JD0); - R = CAAEarth.RadiusVector(JD0); - break; - } - case EO.MERCURY: - { - L = CAAMercury.EclipticLongitude(JD0); - B = CAAMercury.EclipticLatitude(JD0); - R = CAAMercury.RadiusVector(JD0); - break; - } - case EO.VENUS: - { - L = CAAVenus.EclipticLongitude(JD0); - B = CAAVenus.EclipticLatitude(JD0); - R = CAAVenus.RadiusVector(JD0); - break; - } - case EO.MARS: - { - L = CAAMars.EclipticLongitude(JD0); - B = CAAMars.EclipticLatitude(JD0); - R = CAAMars.RadiusVector(JD0); - break; - } - case EO.JUPITER: - { - L = CAAJupiter.EclipticLongitude(JD0); - B = CAAJupiter.EclipticLatitude(JD0); - R = CAAJupiter.RadiusVector(JD0); - break; - } - case EO.SATURN: - { - L = CAASaturn.EclipticLongitude(JD0); - B = CAASaturn.EclipticLatitude(JD0); - R = CAASaturn.RadiusVector(JD0); - break; - } - case EO.URANUS: - { - L = CAAUranus.EclipticLongitude(JD0); - B = CAAUranus.EclipticLatitude(JD0); - R = CAAUranus.RadiusVector(JD0); - break; - } - case EO.NEPTUNE: - { - L = CAANeptune.EclipticLongitude(JD0); - B = CAANeptune.EclipticLatitude(JD0); - R = CAANeptune.RadiusVector(JD0); - break; - } - case EO.PLUTO: - { - L = CAAPluto.EclipticLongitude(JD0); - B = CAAPluto.EclipticLatitude(JD0); - R = CAAPluto.RadiusVector(JD0); - break; - } - default: - { - Debug.Assert(false); - break; - } - } - - if (!bFirstRecalc) - { - bRecalc = ((Math.Abs(L - LPrevious) > 0.00001) || (Math.Abs(B - BPrevious) > 0.00001) || (Math.Abs(R - RPrevious) > 0.000001)); - LPrevious = L; - BPrevious = B; - RPrevious = R; - } - else - bFirstRecalc = false; - - - - //Calculate the new value - if (bRecalc) - { - double distance = 0; - if (@object != EO.SUN) - { - Lrad = CT.D2R(L); - Brad = CT.D2R(B); - cosB = Math.Cos(Brad); - cosL = Math.Cos(Lrad); - x = R * cosB * cosL - R0 * cosB0 * Math.Cos(L0); - y = R * cosB * Math.Sin(Lrad) - R0 * cosB0 * Math.Sin(L0); - z = R * Math.Sin(Brad) - R0 * Math.Sin(B0); - distance = Math.Sqrt(x *x + y *y + z *z); - } - else - distance = R; //Distance to the sun from the earth is in fact the radius vector - - //Prepare for the next loop around - JD0 = JD - ELL.DistanceToLightTime(distance); - } - } - - Lrad = CT.D2R(L); - Brad = CT.D2R(B); - cosB = Math.Cos(Brad); - cosL = Math.Cos(Lrad); - x = R * cosB * cosL - R0 * cosB0 * Math.Cos(L0); - y = R * cosB * Math.Sin(Lrad) - R0 * cosB0 * Math.Sin(L0); - z = R * Math.Sin(Brad) - R0 * Math.Sin(B0); - double x2 = x *x; - double y2 = y *y; - - details.ApparentGeocentricLatitude = CT.R2D(Math.Atan2(z, Math.Sqrt(x2 + y2))); - details.ApparentGeocentricDistance = Math.Sqrt(x2 + y2 + z *z); - details.ApparentGeocentricLongitude = CT.M360(CT.R2D(Math.Atan2(y, x))); - details.ApparentLightTime = ELL.DistanceToLightTime(details.ApparentGeocentricDistance); - - //Adjust for Aberration - COR Aberration = ABR.EclipticAberration(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, JD); - details.ApparentGeocentricLongitude += Aberration.X; - details.ApparentGeocentricLatitude += Aberration.Y; - - //convert to the FK5 system - double DeltaLong = CAAFK5.CorrectionInLongitude(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, JD); - details.ApparentGeocentricLatitude += CAAFK5.CorrectionInLatitude(details.ApparentGeocentricLongitude, JD); - details.ApparentGeocentricLongitude += DeltaLong; - - //Correct for nutation - double NutationInLongitude = CAANutation.NutationInLongitude(JD); - double Epsilon = CAANutation.TrueObliquityOfEcliptic(JD); - details.ApparentGeocentricLongitude += CT.DMS2D(0, 0, NutationInLongitude); - - //Convert to RA and Dec - COR ApparentEqu = CT.Ec2Eq(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, Epsilon); - details.ApparentGeocentricRA = ApparentEqu.X; - details.ApparentGeocentricDeclination = ApparentEqu.Y; - - return details; - } - - - public static double SemiMajorAxisFromPerihelionDistance(double q, double e) - { - return q / (1 - e); - } - public static double MeanMotionFromSemiMajorAxis(double a) - { - return 0.9856076686 / (a * Math.Sqrt(a)); - } - - - public static Vector3d CalculateRectangularJD(double JD, EOE elements) - { - double JD0 = JD; - - double omega = CT.D2R(elements.omega); - double w = CT.D2R(elements.w); - double i = CT.D2R(elements.i); - - double sinEpsilon = 0; - double cosEpsilon = 1; - double sinOmega = Math.Sin(omega); - double cosOmega = Math.Cos(omega); - double cosi = Math.Cos(i); - double sini = Math.Sin(i); - - double F = cosOmega; - double G = sinOmega * cosEpsilon; - double H = sinOmega * sinEpsilon; - double P = -sinOmega * cosi; - double Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; - double R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; - double a = Math.Sqrt(F * F + P * P); - double b = Math.Sqrt(G * G + Q * Q); - double c = Math.Sqrt(H * H + R * R); - double A = Math.Atan2(F, P); - double B = Math.Atan2(G, Q); - double C = Math.Atan2(H, R); - //double n = CAAElliptical.MeanMotionFromSemiMajorAxis(elements.a); - // double n = ; - - - double M = elements.n * (JD0 - elements.T); - elements.meanAnnomolyOut = M; - double E = CAAKepler.Calculate(M, elements.e); - E = CT.D2R(E); - double v = 2 * Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E / 2)); - double r = elements.a * (1 - elements.e * Math.Cos(E)); - double x = r * a * Math.Sin(A + w + v); - double y = r * b * Math.Sin(B + w + v); - double z = r * c * Math.Sin(C + w + v); - - //elements.meanAnnomolyOut contains the mean annomoly - return Vector3d.Create(x, z, y); - } - public static Vector3d CalculateRectangular(EOE elements, double meanAnomoly) - { - -// double JD0 = JD; - - double omega = CT.D2R(elements.omega); - double w = CT.D2R(elements.w); - double i = CT.D2R(elements.i); - - double sinEpsilon = 0; - double cosEpsilon = 1; - double sinOmega = Math.Sin(omega); - double cosOmega = Math.Cos(omega); - double cosi = Math.Cos(i); - double sini = Math.Sin(i); - - double F = cosOmega; - double G = sinOmega * cosEpsilon; - double H = sinOmega * sinEpsilon; - double P = -sinOmega * cosi; - double Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; - double R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; - double a = Math.Sqrt(F * F + P * P); - double b = Math.Sqrt(G * G + Q * Q); - double c = Math.Sqrt(H * H + R * R); - double A = Math.Atan2(F, P); - double B = Math.Atan2(G, Q); - double C = Math.Atan2(H, R); - double n = elements.n; - - - double M = meanAnomoly; - double E = CAAKepler.Calculate(M, elements.e); - E = CT.D2R(E); - double v = 2 * Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E / 2)); - double r = elements.a * (1 - elements.e * Math.Cos(E)); - double x = r * a * Math.Sin(A + w + v); - double y = r * b * Math.Sin(B + w + v); - double z = r * c * Math.Sin(C + w + v); - - return Vector3d.Create(x, z, y); - - } - - public static EOD CalculateElements(double JD, EOE elements) - { - double Epsilon = CAANutation.MeanObliquityOfEcliptic(elements.JDEquinox); - - double JD0 = JD; - - //What will be the return value - EOD details = new EOD(); - - Epsilon = CT.D2R(Epsilon); - double omega = CT.D2R(elements.omega); - double w = CT.D2R(elements.w); - double i = CT.D2R(elements.i); - - double sinEpsilon = Math.Sin(Epsilon); - double cosEpsilon = Math.Cos(Epsilon); - double sinOmega = Math.Sin(omega); - double cosOmega = Math.Cos(omega); - double cosi = Math.Cos(i); - double sini = Math.Sin(i); - - double F = cosOmega; - double G = sinOmega * cosEpsilon; - double H = sinOmega * sinEpsilon; - double P = -sinOmega * cosi; - double Q = cosOmega *cosi *cosEpsilon - sini *sinEpsilon; - double R = cosOmega *cosi *sinEpsilon + sini *cosEpsilon; - double a = Math.Sqrt(F *F + P *P); - double b = Math.Sqrt(G *G + Q *Q); - double c = Math.Sqrt(H *H + R *R); - double A = Math.Atan2(F, P); - double B = Math.Atan2(G, Q); - double C = Math.Atan2(H, R); - double n = ELL.MeanMotionFromSemiMajorAxis(elements.a); - - C3D SunCoord = CAASun.EquatorialRectangularCoordinatesAnyEquinox(JD, elements.JDEquinox); - - for (int j =0; j<2; j++) - { - double M = n * (JD0 - elements.T); - double E = CAAKepler.Calculate(M, elements.e); - E = CT.D2R(E); - double v = 2 *Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E/2)); - double r = elements.a * (1 - elements.e *Math.Cos(E)); - double x = r * a * Math.Sin(A + w + v); - double y = r * b * Math.Sin(B + w + v); - double z = r * c * Math.Sin(C + w + v); - - if (j == 0) - { - details.HeliocentricRectangularEquatorial.X = x; - details.HeliocentricRectangularEquatorial.Y = y; - details.HeliocentricRectangularEquatorial.Z = z; - - //Calculate the heliocentric ecliptic coordinates also - double u = omega + v; - double cosu = Math.Cos(u); - double sinu = Math.Sin(u); - - details.HeliocentricRectangularEcliptical.X = r * (cosOmega *cosu - sinOmega *sinu *cosi); - details.HeliocentricRectangularEcliptical.Y = r * (sinOmega *cosu + cosOmega *sinu *cosi); - details.HeliocentricRectangularEcliptical.Z = r *sini *sinu; - - details.HeliocentricEclipticLongitude = Math.Atan2(y, x); - details.HeliocentricEclipticLongitude = CT.M24(CT.R2D(details.HeliocentricEclipticLongitude) / 15); - details.HeliocentricEclipticLatitude = Math.Asin(z / r); - details.HeliocentricEclipticLatitude = CT.R2D(details.HeliocentricEclipticLatitude); - } - - double psi = SunCoord.X + x; - double nu = SunCoord.Y + y; - double sigma = SunCoord.Z + z; - - double Alpha = Math.Atan2(nu, psi); - Alpha = CT.R2D(Alpha); - double Delta = Math.Atan2(sigma, Math.Sqrt(psi *psi + nu *nu)); - Delta = CT.R2D(Delta); - double Distance = Math.Sqrt(psi *psi + nu *nu + sigma *sigma); - - if (j == 0) - { - details.TrueGeocentricRA = CT.M24(Alpha / 15); - details.TrueGeocentricDeclination = Delta; - details.TrueGeocentricDistance = Distance; - details.TrueGeocentricLightTime = DistanceToLightTime(Distance); - } - else - { - details.AstrometricGeocenticRA = CT.M24(Alpha / 15); - details.AstrometricGeocentricDeclination = Delta; - details.AstrometricGeocentricDistance = Distance; - details.AstrometricGeocentricLightTime = DistanceToLightTime(Distance); - - double RES = Math.Sqrt(SunCoord.X *SunCoord.X + SunCoord.Y *SunCoord.Y + SunCoord.Z *SunCoord.Z); - - details.Elongation = Math.Acos((RES *RES + Distance *Distance - r *r) / (2 * RES * Distance)); - details.Elongation = CT.R2D(details.Elongation); - - details.PhaseAngle = Math.Acos((r *r + Distance *Distance - RES *RES) / (2 * r * Distance)); - details.PhaseAngle = CT.R2D(details.PhaseAngle); - } - - if (j == 0) //Prepare for the next loop around - JD0 = JD - details.TrueGeocentricLightTime; - } - - return details; - } - public static double InstantaneousVelocity(double r, double a) - { - return 42.1219 * Math.Sqrt((1/r) - (1/(2 *a))); - } - public static double VelocityAtPerihelion(double e, double a) - { - return 29.7847 / Math.Sqrt(a) * Math.Sqrt((1+e)/(1-e)); - } - public static double VelocityAtAphelion(double e, double a) - { - return 29.7847 / Math.Sqrt(a) * Math.Sqrt((1-e)/(1+e)); - } - public static double LengthOfEllipse(double e, double a) - { - double b = a * Math.Sqrt(1 - e *e); - return CT.PI() * (3 * (a+b) - Math.Sqrt((a+3 *b)*(3 *a + b))); - } - public static double CometMagnitude(double g, double delta, double k, double r) - { - return g + 5 * Util.Log10(delta) + k * Util.Log10(r); - } - public static double MinorPlanetMagnitude(double H, double delta, double G, double r, double PhaseAngle) - { - //Convert from degrees to radians - PhaseAngle = CT.D2R(PhaseAngle); - - double phi1 = Math.Exp(-3.33 *Math.Pow(Math.Tan(PhaseAngle/2), 0.63)); - double phi2 = Math.Exp(-1.87 *Math.Pow(Math.Tan(PhaseAngle/2), 1.22)); - - return H + 5 * Util.Log10(r * delta) - 2.5 * Util.Log10((1 - G) * phi1 + G * phi2); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAEquationOfTime.cs b/engine/csharp_ref/AstroCalc/AAEquationOfTime.cs deleted file mode 100644 index 32fb8c3c..00000000 --- a/engine/csharp_ref/AstroCalc/AAEquationOfTime.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -// -//Module : AAEQUATIONOFTIME.CPP -//Purpose: Implementation for the algorithms to calculate the "Equation of Time" -//Created: PJN / 29-12-2003 -//History: PJN / 05-07-2005 1. Fix for a bug to ensure that values returned from CAAEquationOfTime::Calculate -// does not return discontinuities. Instead it now returns negative values when -// required. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////// Includes //////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class EOT // was CAAEquationOfTime -{ -//Static methods - - ///////////////////////// Implementation ////////////////////////////////////// - - public static double Calculate(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho *rho; - double rhocubed = rhosquared *rho; - double rho4 = rhocubed *rho; - double rho5 = rho4 *rho; - - //Calculate the Suns mean longitude - double L0 = CT.M360(280.4664567 + 360007.6982779 *rho + 0.03032028 *rhosquared + rhocubed / 49931 - rho4 / 15300 - rho5 / 2000000); - - //Calculate the Suns apparent right ascension - double SunLong = CAASun.ApparentEclipticLongitude(JD); - double SunLat = CAASun.ApparentEclipticLatitude(JD); - double epsilon = CAANutation.TrueObliquityOfEcliptic(JD); - COR Equatorial = CT.Ec2Eq(SunLong, SunLat, epsilon); - - epsilon = CT.D2R(epsilon); - double E = L0 - 0.0057183 - Equatorial.X *15 + CT.DMS2D(0, 0, CAANutation.NutationInLongitude(JD))*Math.Cos(epsilon); - if (E > 180) - E = -(360 - E); - E *= 4; //Convert to minutes of time - - return E; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAEquinoxesAndSolstices.cs b/engine/csharp_ref/AstroCalc/AAEquinoxesAndSolstices.cs deleted file mode 100644 index 01d93ec1..00000000 --- a/engine/csharp_ref/AstroCalc/AAEquinoxesAndSolstices.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System; -// -//Module : AAEQUINOXESANDSOLTICES.CPP -//Purpose: Implementation for the algorithms to calculate the dates of the Equinoxes and Solstices -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////////////// Includes ///////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAEquinoxesAndSolstices -{ -//Static methods - - //////////////////////////////// Implementation /////////////////////////////// - - public static double SpringEquinox(int Year) - { - //calculate the approximate date - double JDE = 0; - if (Year <= 1000) - { - double Y = Year / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 1721139.29189 + 365242.13740 *Y + 0.06134 *Ysquared + 0.00111 *Ycubed - 0.00071 *Y4; - } - else - { - double Y = (Year - 2000) / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 2451623.80984 + 365242.37404 *Y + 0.05169 *Ysquared - 0.00411 *Ycubed - 0.00057 *Y4; - } - - double Correction; - do - { - double SunLongitude = CAASun.ApparentEclipticLongitude(JDE); - Correction = 58 * Math.Sin(CT.D2R(-SunLongitude)); - JDE += Correction; - } - while (Math.Abs(Correction) > 0.00001); //Corresponds to an error of 0.86 of a second - - return JDE; - } - public static double SummerSolstice(int Year) - { - //calculate the approximate date - double JDE = 0; - - if (Year <= 1000) - { - double Y = Year / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 1721233.25401 + 365241.72562 *Y - 0.05323 *Ysquared + 0.00907 *Ycubed + 0.00025 *Y4; - } - else - { - double Y = (Year - 2000) / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 2451716.56767 + 365241.62603 *Y + 0.00325 *Ysquared + 0.00888 *Ycubed - 0.00030 *Y4; - } - - double Correction; - do - { - double SunLongitude = CAASun.ApparentEclipticLongitude(JDE); - Correction = 58 * Math.Sin(CT.D2R(90 - SunLongitude)); - JDE += Correction; - } - while (Math.Abs(Correction) > 0.00001); //Corresponds to an error of 0.86 of a second - - return JDE; - } - public static double AutumnEquinox(int Year) - { - //calculate the approximate date - double JDE = 0; - - if (Year <= 1000) - { - double Y = Year / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 1721325.70455 + 365242.49558 *Y - 0.11677 *Ysquared - 0.00297 *Ycubed + 0.00074 *Y4; - } - else - { - double Y = (Year - 2000) / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 2451810.21715 + 365242.01767 *Y - 0.11575 *Ysquared + 0.00337 *Ycubed + 0.00078 *Y4; - } - - double Correction; - do - { - double SunLongitude = CAASun.ApparentEclipticLongitude(JDE); - Correction = 58 * Math.Sin(CT.D2R(180 - SunLongitude)); - JDE += Correction; - } - while (Math.Abs(Correction) > 0.00001); //Corresponds to an error of 0.86 of a second - - return JDE; - } - public static double WinterSolstice(int Year) - { - //calculate the approximate date - double JDE = 0; - - if (Year <= 1000) - { - double Y = Year / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 1721414.39987 + 365242.88257 *Y - 0.00769 *Ysquared - 0.00933 *Ycubed - 0.00006 *Y4; - } - else - { - double Y = (Year - 2000) / 1000.0; - double Ysquared = Y *Y; - double Ycubed = Ysquared *Y; - double Y4 = Ycubed *Y; - JDE = 2451900.05952 + 365242.74049 *Y - 0.06223 *Ysquared - 0.00823 *Ycubed + 0.00032 *Y4; - } - - double Correction; - do - { - double SunLongitude = CAASun.ApparentEclipticLongitude(JDE); - Correction = 58 * Math.Sin(CT.D2R(270 - SunLongitude)); - JDE += Correction; - } - while (Math.Abs(Correction) > 0.00001); //Corresponds to an error of 0.86 of a second - - return JDE; - } - - public static double LengthOfSpring(int Year) - { - return SummerSolstice(Year) - SpringEquinox(Year); - } - public static double LengthOfSummer(int Year) - { - return AutumnEquinox(Year) - SummerSolstice(Year); - } - public static double LengthOfAutumn(int Year) - { - return WinterSolstice(Year) - AutumnEquinox(Year); - } - public static double LengthOfWinter(int Year) - { - //The winter season wraps around into the following Year - return SpringEquinox(Year+1) - WinterSolstice(Year); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAFK5.cs b/engine/csharp_ref/AstroCalc/AAFK5.cs deleted file mode 100644 index 46d9c075..00000000 --- a/engine/csharp_ref/AstroCalc/AAFK5.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -// -//Module : AAFK5.CPP -//Purpose: Implementation for the algorithms to convert to the FK5 standard reference frame -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////// Includes ////////////////////////////////////////////// - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAFK5 -{ -//Static methods - - /////////////////////// Implementation //////////////////////////////////////// - - public static double CorrectionInLongitude(double Longitude, double Latitude, double JD) - { - double T = (JD - 2451545) / 36525; - double Ldash = Longitude - 1.397 *T - 0.00031 *T *T; - - //Convert to radians - Ldash = CT.D2R(Ldash); - Longitude = CT.D2R(Longitude); - Latitude = CT.D2R(Latitude); - - double @value = -0.09033 + 0.03916*(Math.Cos(Ldash) + Math.Sin(Ldash))*Math.Tan(Latitude); - return CT.DMS2D(0, 0, @value); - } - public static double CorrectionInLatitude(double Longitude, double JD) - { - double T = (JD - 2451545) / 36525; - double Ldash = Longitude - 1.397 *T - 0.00031 *T *T; - - //Convert to radians - Ldash = CT.D2R(Ldash); - Longitude = CT.D2R(Longitude); - - double @value = 0.03916*(Math.Cos(Ldash) - Math.Sin(Ldash)); - return CT.DMS2D(0, 0, @value); - } - public static C3D ConvertVSOPToFK5J2000(C3D @value) - { - C3D result = new C3D(); - result.X = @value.X + 0.000000440360 * @value.Y - 0.000000190919 * @value.Z; - result.Y = -0.000000479966 * @value.X + 0.917482137087 * @value.Y - 0.397776982902 * @value.Z; - result.Z = 0.397776982902 * @value.Y + 0.917482137087 * @value.Z; - - return result; - } - public static C3D ConvertVSOPToFK5B1950(C3D @value) - { - C3D result = new C3D(); - result.X = 0.999925702634 * @value.X + 0.012189716217 * @value.Y + 0.000011134016 * @value.Z; - result.Y = -0.011179418036 * @value.X + 0.917413998946 * @value.Y - 0.397777041885 * @value.Z; - result.Z = -0.004859003787 * @value.X + 0.397747363646 * @value.Y + 0.917482111428 * @value.Z; - - return result; - } - public static C3D ConvertVSOPToFK5AnyEquinox(C3D @value, double JDEquinox) - { - double t = (JDEquinox - 2451545.0) / 36525; - double tsquared = t *t; - double tcubed = tsquared * t; - - double sigma = 2306.2181 *t + 0.30188 *tsquared + 0.017988 *tcubed; - sigma = CT.D2R(CT.DMS2D(0, 0, sigma)); - - double zeta = 2306.2181 *t + 1.09468 *tsquared + 0.018203 *tcubed; - zeta = CT.D2R(CT.DMS2D(0, 0, zeta)); - - double phi = 2004.3109 *t - 0.42665 *tsquared - 0.041833 *tcubed; - phi = CT.D2R(CT.DMS2D(0, 0, phi)); - - double cossigma = Math.Cos(sigma); - double coszeta = Math.Cos(zeta); - double cosphi = Math.Cos(phi); - double sinsigma = Math.Sin(sigma); - double sinzeta = Math.Sin(zeta); - double sinphi = Math.Sin(phi); - - double xx = cossigma * coszeta * cosphi -sinsigma *sinzeta; - double xy = sinsigma * coszeta + cossigma * sinzeta * cosphi; - double xz = cossigma * sinphi; - double yx = -cossigma * sinzeta - sinsigma * coszeta * cosphi; - double yy = cossigma * coszeta - sinsigma * sinzeta * cosphi; - double yz = -sinsigma * sinphi; - double zx = -coszeta * sinphi; - double zy = -sinzeta * sinphi; - double zz = cosphi; - - C3D result = new C3D(); - result.X = xx * @value.X + yx * @value.Y + zx * @value.Z; - result.Y = xy * @value.X + yy * @value.Y + zy * @value.Z; - result.Z = xz * @value.X + yz * @value.Y + zz * @value.Z; - - return result; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAGalileanMoons.cs b/engine/csharp_ref/AstroCalc/AAGalileanMoons.cs deleted file mode 100644 index 28fa4bed..00000000 --- a/engine/csharp_ref/AstroCalc/AAGalileanMoons.cs +++ /dev/null @@ -1,527 +0,0 @@ - -using System; -// -//Module : AAGALILEANMOONS.CPP -//Purpose: Implementation for the algorithms which obtain the positions of the 4 great moons of Jupiter -//Created: PJN / 06-01-2004 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class GMD // was CAAGalileanMoonDetail -{ -//Constructors / Destructors - public GMD() - { - MeanLongitude = 0; - TrueLongitude = 0; - TropicalLongitude = 0; - EquatorialLatitude = 0; - r = 0; - bInTransit = false; - bInOccultation = false; - bInEclipse = false; - bInShadowTransit = false; - } - -//Member variables - public double MeanLongitude; - public double TrueLongitude; - public double TropicalLongitude; - public double EquatorialLatitude; - public double r; - public C3D EclipticRectangularCoordinates = new C3D(); - public C3D TrueRectangularCoordinates = new C3D(); - public C3D ApparentRectangularCoordinates = new C3D(); - public bool bInTransit; - public bool bInOccultation; - public bool bInEclipse; - public bool bInShadowTransit; - public C3D ApparentShadowRectangularCoordinates = new C3D(); -} - -public class GMDS //was CAAGalileanMoonsDetails -{ -//Member variables - public GMD Satellite1 = new GMD(); - public GMD Satellite2 = new GMD(); - public GMD Satellite3 = new GMD(); - public GMD Satellite4 = new GMD(); -} - - -public class GM //was CAAGalileanMoons -{ -//Static methods - public static GMDS Calculate(double JD) - { - //Calculate the position of the Sun - double sunlong = CAASun.GeometricEclipticLongitude(JD); - double sunlongrad = CT.D2R(sunlong); - double beta = CAASun.GeometricEclipticLatitude(JD); - double betarad = CT.D2R(beta); - double R = CAAEarth.RadiusVector(JD); - - //Calculate the the light travel time from Jupiter to the Earth - double DELTA = 5; - double PreviousEarthLightTravelTime = 0; - double EarthLightTravelTime = ELL.DistanceToLightTime(DELTA); - double JD1 = JD - EarthLightTravelTime; - bool bIterate = true; - double x = 0; - double y = 0; - double z = 0; - - double l = 0; - double lrad =0; - double b = 0; - double brad =0; - double r = 0; - - while (bIterate) - { - //Calculate the position of Jupiter - l = CAAJupiter.EclipticLongitude(JD1); - lrad = CT.D2R(l); - b = CAAJupiter.EclipticLatitude(JD1); - brad = CT.D2R(b); - r = CAAJupiter.RadiusVector(JD1); - - x = r *Math.Cos(brad)*Math.Cos(lrad) + R *Math.Cos(sunlongrad); - y = r *Math.Cos(brad)*Math.Sin(lrad) + R *Math.Sin(sunlongrad); - z = r *Math.Sin(brad) + R *Math.Sin(betarad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - EarthLightTravelTime = ELL.DistanceToLightTime(DELTA); - - //Prepare for the next loop around - bIterate = (Math.Abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-6); //2E-6 corresponds to 0.17 of a second - if (bIterate) - { - JD1 = JD - EarthLightTravelTime; - PreviousEarthLightTravelTime = EarthLightTravelTime; - } - } - - //Calculate the details as seen from the earth - GMDS details1 = CalculateHelper(JD, sunlongrad, betarad, R); - FillInPhenomenaDetails( details1.Satellite1); - FillInPhenomenaDetails( details1.Satellite2); - FillInPhenomenaDetails( details1.Satellite3); - FillInPhenomenaDetails( details1.Satellite4); - - //Calculate the the light travel time from Jupiter to the Sun - JD1 = JD - EarthLightTravelTime; - l = CAAJupiter.EclipticLongitude(JD1); - lrad = CT.D2R(l); - b = CAAJupiter.EclipticLatitude(JD1); - brad = CT.D2R(b); - r = CAAJupiter.RadiusVector(JD1); - x = r *Math.Cos(brad)*Math.Cos(lrad); - y = r *Math.Cos(brad)*Math.Sin(lrad); - z = r *Math.Sin(brad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - double SunLightTravelTime = ELL.DistanceToLightTime(DELTA); - - //Calculate the details as seen from the Sun - GMDS details2 = CalculateHelper(JD + SunLightTravelTime - EarthLightTravelTime, sunlongrad, betarad, 0); - FillInPhenomenaDetails( details2.Satellite1); - FillInPhenomenaDetails( details2.Satellite2); - FillInPhenomenaDetails( details2.Satellite3); - FillInPhenomenaDetails( details2.Satellite4); - - //Finally transfer the required values from details2 to details1 - details1.Satellite1.bInEclipse = details2.Satellite1.bInOccultation; - details1.Satellite2.bInEclipse = details2.Satellite2.bInOccultation; - details1.Satellite3.bInEclipse = details2.Satellite3.bInOccultation; - details1.Satellite4.bInEclipse = details2.Satellite4.bInOccultation; - details1.Satellite1.bInShadowTransit = details2.Satellite1.bInTransit; - details1.Satellite2.bInShadowTransit = details2.Satellite2.bInTransit; - details1.Satellite3.bInShadowTransit = details2.Satellite3.bInTransit; - details1.Satellite4.bInShadowTransit = details2.Satellite4.bInTransit; -//C++ TO C# CONVERTER WARNING: The following line was determined to be a copy assignment (rather than a reference assignment) - this should be verified and a 'CopyFrom' method should be created if it does not yet exist: -//ORIGINAL LINE: details1.Satellite1.ApparentShadowRectangularCoordinates = details2.Satellite1.ApparentRectangularCoordinates; - details1.Satellite1.ApparentShadowRectangularCoordinates = details2.Satellite1.ApparentRectangularCoordinates; -//C++ TO C# CONVERTER WARNING: The following line was determined to be a copy assignment (rather than a reference assignment) - this should be verified and a 'CopyFrom' method should be created if it does not yet exist: -//ORIGINAL LINE: details1.Satellite2.ApparentShadowRectangularCoordinates = details2.Satellite2.ApparentRectangularCoordinates; - details1.Satellite2.ApparentShadowRectangularCoordinates = details2.Satellite2.ApparentRectangularCoordinates; -//C++ TO C# CONVERTER WARNING: The following line was determined to be a copy assignment (rather than a reference assignment) - this should be verified and a 'CopyFrom' method should be created if it does not yet exist: -//ORIGINAL LINE: details1.Satellite3.ApparentShadowRectangularCoordinates = details2.Satellite3.ApparentRectangularCoordinates; - details1.Satellite3.ApparentShadowRectangularCoordinates = details2.Satellite3.ApparentRectangularCoordinates; -//C++ TO C# CONVERTER WARNING: The following line was determined to be a copy assignment (rather than a reference assignment) - this should be verified and a 'CopyFrom' method should be created if it does not yet exist: -//ORIGINAL LINE: details1.Satellite4.ApparentShadowRectangularCoordinates = details2.Satellite4.ApparentRectangularCoordinates; - details1.Satellite4.ApparentShadowRectangularCoordinates = details2.Satellite4.ApparentRectangularCoordinates; - return details1; - } - - - //////////////////////////////// Implementation /////////////////////////////// - - protected static GMDS CalculateHelper(double JD, double sunlongrad, double betarad, double R) - { - //What will be the return value - GMDS details = new GMDS(); - - //Calculate the position of Jupiter decreased by the light travel time from Jupiter to the specified position - double DELTA = 5; - double PreviousLightTravelTime = 0; - double LightTravelTime = ELL.DistanceToLightTime(DELTA); - double x = 0; - double y = 0; - double z = 0; - double l = 0; - double lrad = 0; - double b = 0; - double brad = 0; - double r = 0; - double JD1 = JD - LightTravelTime; - bool bIterate = true; - while (bIterate) - { - //Calculate the position of Jupiter - l = CAAJupiter.EclipticLongitude(JD1); - lrad = CT.D2R(l); - b = CAAJupiter.EclipticLatitude(JD1); - brad = CT.D2R(b); - r = CAAJupiter.RadiusVector(JD1); - - x = r *Math.Cos(brad)*Math.Cos(lrad) + R *Math.Cos(sunlongrad); - y = r *Math.Cos(brad)*Math.Sin(lrad) + R *Math.Sin(sunlongrad); - z = r *Math.Sin(brad) + R *Math.Sin(betarad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - LightTravelTime = ELL.DistanceToLightTime(DELTA); - - //Prepare for the next loop around - bIterate = (Math.Abs(LightTravelTime - PreviousLightTravelTime) > 2E-6); //2E-6 corresponds to 0.17 of a second - if (bIterate) - { - JD1 = JD - LightTravelTime; - PreviousLightTravelTime = LightTravelTime; - } - } - - //Calculate Jupiter's Longitude and Latitude - double lambda0 = Math.Atan2(y, x); - double beta0 = Math.Atan(z/Math.Sqrt(x *x + y *y)); - - double t = JD - 2443000.5 - LightTravelTime; - - //Calculate the mean longitudes - double l1 = 106.07719 + 203.488955790 *t; - double l1rad = CT.D2R(l1); - double l2 = 175.73161 + 101.374724735 *t; - double l2rad = CT.D2R(l2); - double l3 = 120.55883 + 50.317609207 *t; - double l3rad = CT.D2R(l3); - double l4 = 84.44459 + 21.571071177 *t; - double l4rad = CT.D2R(l4); - - //Calculate the perijoves - double pi1 = CT.D2R(CT.M360(97.0881 + 0.16138586 *t)); - double pi2 = CT.D2R(CT.M360(154.8663 + 0.04726307 *t)); - double pi3 = CT.D2R(CT.M360(188.1840 + 0.00712734 *t)); - double pi4 = CT.D2R(CT.M360(335.2868 + 0.00184000 *t)); - - //Calculate the nodes on the equatorial plane of jupiter - double w1 = 312.3346 - 0.13279386 *t; - double w1rad = CT.D2R(w1); - double w2 = 100.4411 - 0.03263064 *t; - double w2rad = CT.D2R(w2); - double w3 = 119.1942 - 0.00717703 *t; - double w3rad = CT.D2R(w3); - double w4 = 322.6186 - 0.00175934 *t; - double w4rad = CT.D2R(w4); - - //Calculate the Principal inequality in the longitude of Jupiter - double GAMMA = 0.33033 *Math.Sin(CT.D2R(163.679 + 0.0010512 *t)) + 0.03439 *Math.Sin(CT.D2R(34.486 - 0.0161731 *t)); - - //Calculate the "phase of free libration" - double philambda = CT.D2R(199.6766 + 0.17379190 *t); - - //Calculate the longitude of the node of the equator of Jupiter on the ecliptic - double psi = CT.D2R(316.5182 - 0.00000208 *t); - - //Calculate the mean anomalies of Jupiter and Saturn - double G = CT.D2R(30.23756 + 0.0830925701 *t + GAMMA); - double Gdash = CT.D2R(31.97853 + 0.0334597339 *t); - - //Calculate the longitude of the perihelion of Jupiter - double PI = CT.D2R(13.469942); - - //Calculate the periodic terms in the longitudes of the satellites - double Sigma1 = 0.47259 *Math.Sin(2*(l1rad - l2rad)) + -0.03478 *Math.Sin(pi3 - pi4) + 0.01081 *Math.Sin(l2rad - 2 *l3rad + pi3) + 0.00738 *Math.Sin(philambda) + 0.00713 *Math.Sin(l2rad - 2 *l3rad + pi2) + -0.00674 *Math.Sin(pi1 + pi3 - 2 *PI - 2 *G) + 0.00666 *Math.Sin(l2rad - 2 *l3rad + pi4) + 0.00445 *Math.Sin(l1rad - pi3) + -0.00354 *Math.Sin(l1rad - l2rad) + -0.00317 *Math.Sin(2 *psi - 2 *PI) + 0.00265 *Math.Sin(l1rad - pi4) + -0.00186 *Math.Sin(G) + 0.00162 *Math.Sin(pi2 - pi3) + 0.00158 *Math.Sin(4*(l1rad - l2rad)) + -0.00155 *Math.Sin(l1rad - l3rad) + -0.00138 *Math.Sin(psi + w3rad - 2 *PI - 2 *G) + -0.00115 *Math.Sin(2*(l1rad - 2 *l2rad + w2rad)) + 0.00089 *Math.Sin(pi2 - pi4) + 0.00085 *Math.Sin(l1rad + pi3 - 2 *PI - 2 *G) + 0.00083 *Math.Sin(w2rad - w3rad) + 0.00053 *Math.Sin(psi - w2rad); - - double Sigma2 = 1.06476 *Math.Sin(2*(l2rad - l3rad)) + 0.04256 *Math.Sin(l1rad - 2 *l2rad + pi3) + 0.03581 *Math.Sin(l2rad - pi3) + 0.02395 *Math.Sin(l1rad - 2 *l2rad + pi4) + 0.01984 *Math.Sin(l2rad - pi4) + -0.01778 *Math.Sin(philambda) + 0.01654 *Math.Sin(l2rad - pi2) + 0.01334 *Math.Sin(l2rad - 2 *l3rad + pi2) + 0.01294 *Math.Sin(pi3 - pi4) + -0.01142 *Math.Sin(l2rad - l3rad) + -0.01057 *Math.Sin(G) + -0.00775 *Math.Sin(2*(psi - PI)) + 0.00524 *Math.Sin(2*(l1rad - l2rad)) + -0.00460 *Math.Sin(l1rad - l3rad) + 0.00316 *Math.Sin(psi - 2 *G + w3rad - 2 *PI) + -0.00203 *Math.Sin(pi1 + pi3 - 2 *PI - 2 *G) + 0.00146 *Math.Sin(psi - w3rad) + -0.00145 *Math.Sin(2 *G) + 0.00125 *Math.Sin(psi - w4rad) + -0.00115 *Math.Sin(l1rad - 2 *l3rad + pi3) + -0.00094 *Math.Sin(2*(l2rad - w2rad)) + 0.00086 *Math.Sin(2*(l1rad - 2 *l2rad + w2rad)) + -0.00086 *Math.Sin(5 *Gdash - 2 *G + CT.D2R(52.225)) + -0.00078 *Math.Sin(l2rad - l4rad) + -0.00064 *Math.Sin(3 *l3rad - 7 *l4rad + 4 *pi4) + 0.00064 *Math.Sin(pi1 - pi4) + -0.00063 *Math.Sin(l1rad - 2 *l3rad + pi4) + 0.00058 *Math.Sin(w3rad - w4rad) + 0.00056 *Math.Sin(2*(psi - PI - G)) + 0.00056 *Math.Sin(2*(l2rad - l4rad)) + 0.00055 *Math.Sin(2*(l1rad - l3rad)) + 0.00052 *Math.Sin(3 *l3rad - 7 *l4rad + pi3 + 3 *pi4) + -0.00043 *Math.Sin(l1rad - pi3) + 0.00041 *Math.Sin(5*(l2rad - l3rad)) + 0.00041 *Math.Sin(pi4 - PI) + 0.00032 *Math.Sin(w2rad - w3rad) + 0.00032 *Math.Sin(2*(l3rad - G - PI)); - - double Sigma3 = 0.16490 *Math.Sin(l3rad - pi3) + 0.09081 *Math.Sin(l3rad - pi4) + -0.06907 *Math.Sin(l2rad - l3rad) + 0.03784 *Math.Sin(pi3 - pi4) + 0.01846 *Math.Sin(2*(l3rad - l4rad)) + -0.01340 *Math.Sin(G) + -0.01014 *Math.Sin(2*(psi - PI)) + 0.00704 *Math.Sin(l2rad - 2 *l3rad + pi3) + -0.00620 *Math.Sin(l2rad - 2 *l3rad + pi2) + -0.00541 *Math.Sin(l3rad - l4rad) + 0.00381 *Math.Sin(l2rad - 2 *l3rad + pi4) + 0.00235 *Math.Sin(psi - w3rad) + 0.00198 *Math.Sin(psi - w4rad) + 0.00176 *Math.Sin(philambda) + 0.00130 *Math.Sin(3*(l3rad - l4rad)) + 0.00125 *Math.Sin(l1rad - l3rad) + -0.00119 *Math.Sin(5 *Gdash - 2 *G + CT.D2R(52.225)) + 0.00109 *Math.Sin(l1rad - l2rad) + -0.00100 *Math.Sin(3 *l3rad - 7 *l4rad + 4 *pi4) + 0.00091 *Math.Sin(w3rad - w4rad) + 0.00080 *Math.Sin(3 *l3rad - 7 *l4rad + pi3 + 3 *pi4) + -0.00075 *Math.Sin(2 *l2rad - 3 *l3rad + pi3) + 0.00072 *Math.Sin(pi1 + pi3 - 2 *PI - 2 *G) + 0.00069 *Math.Sin(pi4 - PI) + -0.00058 *Math.Sin(2 *l3rad - 3 *l4rad + pi4) + -0.00057 *Math.Sin(l3rad - 2 *l4rad + pi4) + 0.00056 *Math.Sin(l3rad + pi3 - 2 *PI - 2 *G) + -0.00052 *Math.Sin(l2rad - 2 *l3rad + pi1) + -0.00050 *Math.Sin(pi2 - pi3) + 0.00048 *Math.Sin(l3rad - 2 *l4rad + pi3) + -0.00045 *Math.Sin(2 *l2rad - 3 *l3rad + pi4) + -0.00041 *Math.Sin(pi2 - pi4) + -0.00038 *Math.Sin(2 *G) + -0.00037 *Math.Sin(pi3 - pi4 + w3rad - w4rad) + -0.00032 *Math.Sin(3 *l3rad - 7 *l4rad + 2 *pi3 + 2 *pi4) + 0.00030 *Math.Sin(4*(l3rad - l4rad)) + 0.00029 *Math.Sin(l3rad + pi4 - 2 *PI - 2 *G) + -0.00028 *Math.Sin(w3rad + psi - 2 *PI - 2 *G) + 0.00026 *Math.Sin(l3rad - PI - G) + 0.00024 *Math.Sin(l2rad - 3 *l3rad + 2 *l4rad) + 0.00021 *Math.Sin(l3rad - PI - G) + -0.00021 *Math.Sin(l3rad - pi2) + 0.00017 *Math.Sin(2*(l3rad - pi3)); - - double Sigma4 = 0.84287 *Math.Sin(l4rad - pi4) + 0.03431 *Math.Sin(pi4 - pi3) + -0.03305 *Math.Sin(2*(psi - PI)) + -0.03211 *Math.Sin(G) + -0.01862 *Math.Sin(l4rad - pi3) + 0.01186 *Math.Sin(psi - w4rad) + 0.00623 *Math.Sin(l4rad + pi4 - 2 *G - 2 *PI) + 0.00387 *Math.Sin(2*(l4rad - pi4)) + -0.00284 *Math.Sin(5 *Gdash - 2 *G + CT.D2R(52.225)) + -0.00234 *Math.Sin(2*(psi - pi4)) + -0.00223 *Math.Sin(l3rad - l4rad) + -0.00208 *Math.Sin(l4rad - PI) + 0.00178 *Math.Sin(psi + w4rad - 2 *pi4) + 0.00134 *Math.Sin(pi4 - PI) + 0.00125 *Math.Sin(2*(l4rad - G - PI)) + -0.00117 *Math.Sin(2 *G) + -0.00112 *Math.Sin(2*(l3rad - l4rad)) + 0.00107 *Math.Sin(3 *l3rad - 7 *l4rad + 4 *pi4) + 0.00102 *Math.Sin(l4rad - G - PI) + 0.00096 *Math.Sin(2 *l4rad - psi - w4rad) + 0.00087 *Math.Sin(2*(psi - w4rad)) + -0.00085 *Math.Sin(3 *l3rad - 7 *l4rad + pi3 + 3 *pi4) + 0.00085 *Math.Sin(l3rad - 2 *l4rad + pi4) + -0.00081 *Math.Sin(2*(l4rad - psi)) + 0.00071 *Math.Sin(l4rad + pi4 - 2 *PI - 3 *G) + 0.00061 *Math.Sin(l1rad - l4rad) + -0.00056 *Math.Sin(psi - w3rad) + -0.00054 *Math.Sin(l3rad - 2 *l4rad + pi3) + 0.00051 *Math.Sin(l2rad - l4rad) + 0.00042 *Math.Sin(2*(psi - G - PI)) + 0.00039 *Math.Sin(2*(pi4 - w4rad)) + 0.00036 *Math.Sin(psi + PI - pi4 - w4rad) + 0.00035 *Math.Sin(2 *Gdash - G + CT.D2R(188.37)) + -0.00035 *Math.Sin(l4rad - pi4 + 2 *PI - 2 *psi) + -0.00032 *Math.Sin(l4rad + pi4 - 2 *PI - G) + 0.00030 *Math.Sin(2 *Gdash - 2 *G + CT.D2R(149.15)) + 0.00029 *Math.Sin(3 *l3rad - 7 *l4rad + 2 *pi3 + 2 *pi4) + 0.00028 *Math.Sin(l4rad - pi4 + 2 *psi - 2 *PI) + -0.00028 *Math.Sin(2*(l4rad - w4rad)) + -0.00027 *Math.Sin(pi3 - pi4 + w3rad - w4rad) + -0.00026 *Math.Sin(5 *Gdash - 3 *G + CT.D2R(188.37)) + 0.00025 *Math.Sin(w4rad - w3rad) + -0.00025 *Math.Sin(l2rad - 3 *l3rad + 2 *l4rad) + -0.00023 *Math.Sin(3*(l3rad - l4rad)) + 0.00021 *Math.Sin(2 *l4rad - 2 *PI - 3 *G) + -0.00021 *Math.Sin(2 *l3rad - 3 *l4rad + pi4) + 0.00019 *Math.Sin(l4rad - pi4 - G) + -0.00019 *Math.Sin(2 *l4rad - pi3 - pi4) + -0.00018 *Math.Sin(l4rad - pi4 + G) + -0.00016 *Math.Sin(l4rad + pi3 - 2 *PI - 2 *G); - - details.Satellite1.MeanLongitude = CT.M360(l1); - details.Satellite1.TrueLongitude = CT.M360(l1 + Sigma1); - double L1 = CT.D2R(details.Satellite1.TrueLongitude); - - details.Satellite2.MeanLongitude = CT.M360(l2); - details.Satellite2.TrueLongitude = CT.M360(l2 + Sigma2); - double L2 = CT.D2R(details.Satellite2.TrueLongitude); - - details.Satellite3.MeanLongitude = CT.M360(l3); - details.Satellite3.TrueLongitude = CT.M360(l3 + Sigma3); - double L3 = CT.D2R(details.Satellite3.TrueLongitude); - - details.Satellite4.MeanLongitude = CT.M360(l4); - details.Satellite4.TrueLongitude = CT.M360(l4 + Sigma4); - double L4 = CT.D2R(details.Satellite4.TrueLongitude); - - //Calculate the periodic terms in the latitudes of the satellites - double B1 = Math.Atan(0.0006393 *Math.Sin(L1 - w1rad) + 0.0001825 *Math.Sin(L1 - w2rad) + 0.0000329 *Math.Sin(L1 - w3rad) + -0.0000311 *Math.Sin(L1 - psi) + 0.0000093 *Math.Sin(L1 - w4rad) + 0.0000075 *Math.Sin(3 *L1 - 4 *l2rad - 1.9927 *Sigma1 + w2rad) + 0.0000046 *Math.Sin(L1 + psi - 2 *PI - 2 *G)); - details.Satellite1.EquatorialLatitude = CT.R2D(B1); - - double B2 = Math.Atan(0.0081004 *Math.Sin(L2 - w2rad) + 0.0004512 *Math.Sin(L2 - w3rad) + -0.0003284 *Math.Sin(L2 - psi) + 0.0001160 *Math.Sin(L2 - w4rad) + 0.0000272 *Math.Sin(l1rad - 2 *l3rad + 1.0146 *Sigma2 + w2rad) + -0.0000144 *Math.Sin(L2 - w1rad) + 0.0000143 *Math.Sin(L2 + psi - 2 *PI - 2 *G) + 0.0000035 *Math.Sin(L2 - psi + G) + -0.0000028 *Math.Sin(l1rad - 2 *l3rad + 1.0146 *Sigma2 + w3rad)); - details.Satellite2.EquatorialLatitude = CT.R2D(B2); - - double B3 = Math.Atan(0.0032402 *Math.Sin(L3 - w3rad) + -0.0016911 *Math.Sin(L3 - psi) + 0.0006847 *Math.Sin(L3 - w4rad) + -0.0002797 *Math.Sin(L3 - w2rad) + 0.0000321 *Math.Sin(L3 + psi - 2 *PI - 2 *G) + 0.0000051 *Math.Sin(L3 - psi + G) + -0.0000045 *Math.Sin(L3 - psi - G) + -0.0000045 *Math.Sin(L3 + psi - 2 *PI) + 0.0000037 *Math.Sin(L3 + psi - 2 *PI - 3 *G) + 0.0000030 *Math.Sin(2 *l2rad - 3 *L3 + 4.03 *Sigma3 + w2rad) + -0.0000021 *Math.Sin(2 *l2rad - 3 *L3 + 4.03 *Sigma3 + w3rad)); - details.Satellite3.EquatorialLatitude = CT.R2D(B3); - - double B4 = Math.Atan(-0.0076579 *Math.Sin(L4 - psi) + 0.0044134 *Math.Sin(L4 - w4rad) + -0.0005112 *Math.Sin(L4 - w3rad) + 0.0000773 *Math.Sin(L4 + psi - 2 *PI - 2 *G) + 0.0000104 *Math.Sin(L4 - psi + G) + -0.0000102 *Math.Sin(L4 - psi - G) + 0.0000088 *Math.Sin(L4 + psi - 2 *PI - 3 *G) + -0.0000038 *Math.Sin(L4 + psi - 2 *PI - G)); - details.Satellite4.EquatorialLatitude = CT.R2D(B4); - - //Calculate the periodic terms for the radius vector - details.Satellite1.r = 5.90569 * (1 + (-0.0041339 *Math.Cos(2*(l1rad - l2rad)) + -0.0000387 *Math.Cos(l1rad - pi3) + -0.0000214 *Math.Cos(l1rad - pi4) + 0.0000170 *Math.Cos(l1rad - l2rad) + -0.0000131 *Math.Cos(4*(l1rad - l2rad)) + 0.0000106 *Math.Cos(l1rad - l3rad) + -0.0000066 *Math.Cos(l1rad + pi3 - 2 *PI - 2 *G))); - - details.Satellite2.r = 9.39657 * (1 + (0.0093848 *Math.Cos(l1rad - l2rad) + -0.0003116 *Math.Cos(l2rad - pi3) + -0.0001744 *Math.Cos(l2rad - pi4) + -0.0001442 *Math.Cos(l2rad - pi2) + 0.0000553 *Math.Cos(l2rad - l3rad) + 0.0000523 *Math.Cos(l1rad - l3rad) + -0.0000290 *Math.Cos(2*(l1rad - l2rad)) + 0.0000164 *Math.Cos(2*(l2rad - w2rad)) + 0.0000107 *Math.Cos(l1rad - 2 *l3rad + pi3) + -0.0000102 *Math.Cos(l2rad - pi1) + -0.0000091 *Math.Cos(2*(l1rad - l3rad)))); - - details.Satellite3.r = 14.98832 * (1 + (-0.0014388 *Math.Cos(l3rad - pi3) + -0.0007919 *Math.Cos(l3rad - pi4) + 0.0006342 *Math.Cos(l2rad - l3rad) + -0.0001761 *Math.Cos(2*(l3rad - l4rad)) + 0.0000294 *Math.Cos(l3rad - l4rad) + -0.0000156 *Math.Cos(3*(l3rad - l4rad)) + 0.0000156 *Math.Cos(l1rad - l3rad) + -0.0000153 *Math.Cos(l1rad - l2rad) + 0.0000070 *Math.Cos(2 *l2rad - 3 *l3rad + pi3) + -0.0000051 *Math.Cos(l3rad + pi3 - 2 *PI - 2 *G))); - - details.Satellite4.r = 26.36273 * (1 + (-0.0073546 *Math.Cos(l4rad - pi4) + 0.0001621 *Math.Cos(l4rad - pi3) + 0.0000974 *Math.Cos(l3rad - l4rad) + -0.0000543 *Math.Cos(l4rad + pi4 - 2 *PI - 2 *G) + -0.0000271 *Math.Cos(2*(l4rad - pi4)) + 0.0000182 *Math.Cos(l4rad - PI) + 0.0000177 *Math.Cos(2*(l3rad - l4rad)) + -0.0000167 *Math.Cos(2 *l4rad - psi - w4rad) + 0.0000167 *Math.Cos(psi - w4rad) + -0.0000155 *Math.Cos(2*(l4rad - PI - G)) + 0.0000142 *Math.Cos(2*(l4rad - psi)) + 0.0000105 *Math.Cos(l1rad - l4rad) + 0.0000092 *Math.Cos(l2rad - l4rad) + -0.0000089 *Math.Cos(l4rad - PI - G) + -0.0000062 *Math.Cos(l4rad + pi4 - 2 *PI - 3 *G) + 0.0000048 *Math.Cos(2*(l4rad - w4rad)))); - - - - //Calculate T0 - double T0 = (JD - 2433282.423)/36525; - - //Calculate the precession in longitude from Epoch B1950 to the date - double P = CT.D2R(1.3966626 *T0 + 0.0003088 *T0 *T0); - - //Add it to L1 - L4 and psi - L1 += P; - details.Satellite1.TropicalLongitude = CT.M360(CT.R2D(L1)); - L2 += P; - details.Satellite2.TropicalLongitude = CT.M360(CT.R2D(L2)); - L3 += P; - details.Satellite3.TropicalLongitude = CT.M360(CT.R2D(L3)); - L4 += P; - details.Satellite4.TropicalLongitude = CT.M360(CT.R2D(L4)); - psi += P; - - //Calculate the inclination of Jupiter's axis of rotation on the orbital plane - double T = (JD - 2415020.5)/36525; - double I = 3.120262 + 0.0006 *T; - double Irad = CT.D2R(I); - - double X1 = details.Satellite1.r *Math.Cos(L1 - psi)*Math.Cos(B1); - double X2 = details.Satellite2.r *Math.Cos(L2 - psi)*Math.Cos(B2); - double X3 = details.Satellite3.r *Math.Cos(L3 - psi)*Math.Cos(B3); - double X4 = details.Satellite4.r *Math.Cos(L4 - psi)*Math.Cos(B4); - double X5 = 0; - - double Y1 = details.Satellite1.r *Math.Sin(L1 - psi)*Math.Cos(B1); - double Y2 = details.Satellite2.r *Math.Sin(L2 - psi)*Math.Cos(B2); - double Y3 = details.Satellite3.r *Math.Sin(L3 - psi)*Math.Cos(B3); - double Y4 = details.Satellite4.r *Math.Sin(L4 - psi)*Math.Cos(B4); - double Y5 = 0; - - double Z1 = details.Satellite1.r *Math.Sin(B1); - double Z2 = details.Satellite2.r *Math.Sin(B2); - double Z3 = details.Satellite3.r *Math.Sin(B3); - double Z4 = details.Satellite4.r *Math.Sin(B4); - double Z5 = 1; - - //Now do the rotations, first for the ficticious 5th satellite, so that we can calculate D - double omega = CT.D2R(EPO.JupiterLongitudeAscendingNode(JD)); - double i = CT.D2R(EPO.JupiterInclination(JD)); - double A6=0; - double B6=0; - double C6=0; - C3D north = new C3D(); - double[] abc = Rotations(X5, Y5, Z5, Irad, psi, i, omega, lambda0, beta0,north); - - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - - double D = Math.Atan2(A6, C6); - - //Now calculate the values for satellite 1 - - abc = Rotations(X1, Y1, Z1, Irad, psi, i, omega, lambda0, beta0, details.Satellite1.EclipticRectangularCoordinates); - - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - - details.Satellite1.TrueRectangularCoordinates.X = A6 *Math.Cos(D) - C6 *Math.Sin(D); - details.Satellite1.TrueRectangularCoordinates.Y = A6 *Math.Sin(D) + C6 *Math.Cos(D); - details.Satellite1.TrueRectangularCoordinates.Z = B6; - - //Now calculate the values for satellite 2 - abc = Rotations(X2, Y2, Z2, Irad, psi, i, omega, lambda0, beta0, details.Satellite2.EclipticRectangularCoordinates); - - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - - - details.Satellite2.TrueRectangularCoordinates.X = A6 *Math.Cos(D) - C6 *Math.Sin(D); - details.Satellite2.TrueRectangularCoordinates.Y = A6 *Math.Sin(D) + C6 *Math.Cos(D); - details.Satellite2.TrueRectangularCoordinates.Z = B6; - - //Now calculate the values for satellite 3 - abc= Rotations(X3, Y3, Z3, Irad, psi, i, omega, lambda0, beta0, details.Satellite3.EclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - - details.Satellite3.TrueRectangularCoordinates.X = A6 *Math.Cos(D) - C6 *Math.Sin(D); - details.Satellite3.TrueRectangularCoordinates.Y = A6 *Math.Sin(D) + C6 *Math.Cos(D); - details.Satellite3.TrueRectangularCoordinates.Z = B6; - - //And finally for satellite 4 - abc = Rotations(X4, Y4, Z4, Irad, psi, i, omega, lambda0, beta0, details.Satellite4.EclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - - details.Satellite4.TrueRectangularCoordinates.X = A6 *Math.Cos(D) - C6 *Math.Sin(D); - details.Satellite4.TrueRectangularCoordinates.Y = A6 *Math.Sin(D) + C6 *Math.Cos(D); - details.Satellite4.TrueRectangularCoordinates.Z = B6; - - //apply the differential light-time correction - details.Satellite1.ApparentRectangularCoordinates.X = details.Satellite1.TrueRectangularCoordinates.X + Math.Abs(details.Satellite1.TrueRectangularCoordinates.Z)/17295 *Math.Sqrt(1 - (details.Satellite1.TrueRectangularCoordinates.X/details.Satellite1.r)*(details.Satellite1.TrueRectangularCoordinates.X/details.Satellite1.r)); - details.Satellite1.ApparentRectangularCoordinates.Y = details.Satellite1.TrueRectangularCoordinates.Y; - details.Satellite1.ApparentRectangularCoordinates.Z = details.Satellite1.TrueRectangularCoordinates.Z; - - details.Satellite2.ApparentRectangularCoordinates.X = details.Satellite2.TrueRectangularCoordinates.X + Math.Abs(details.Satellite2.TrueRectangularCoordinates.Z)/21819 *Math.Sqrt(1 - (details.Satellite2.TrueRectangularCoordinates.X/details.Satellite2.r)*(details.Satellite2.TrueRectangularCoordinates.X/details.Satellite2.r)); - details.Satellite2.ApparentRectangularCoordinates.Y = details.Satellite2.TrueRectangularCoordinates.Y; - details.Satellite2.ApparentRectangularCoordinates.Z = details.Satellite2.TrueRectangularCoordinates.Z; - - details.Satellite3.ApparentRectangularCoordinates.X = details.Satellite3.TrueRectangularCoordinates.X + Math.Abs(details.Satellite3.TrueRectangularCoordinates.Z)/27558 *Math.Sqrt(1 - (details.Satellite3.TrueRectangularCoordinates.X/details.Satellite3.r)*(details.Satellite3.TrueRectangularCoordinates.X/details.Satellite3.r)); - details.Satellite3.ApparentRectangularCoordinates.Y = details.Satellite3.TrueRectangularCoordinates.Y; - details.Satellite3.ApparentRectangularCoordinates.Z = details.Satellite3.TrueRectangularCoordinates.Z; - - details.Satellite4.ApparentRectangularCoordinates.X = details.Satellite4.TrueRectangularCoordinates.X + Math.Abs(details.Satellite4.TrueRectangularCoordinates.Z)/36548 *Math.Sqrt(1 - (details.Satellite4.TrueRectangularCoordinates.X/details.Satellite4.r)*(details.Satellite4.TrueRectangularCoordinates.X/details.Satellite4.r)); - details.Satellite4.ApparentRectangularCoordinates.Y = details.Satellite4.TrueRectangularCoordinates.Y; - details.Satellite4.ApparentRectangularCoordinates.Z = details.Satellite4.TrueRectangularCoordinates.Z; - - //apply the perspective effect correction - double W = DELTA/(DELTA + details.Satellite1.TrueRectangularCoordinates.Z/2095); - details.Satellite1.ApparentRectangularCoordinates.X *= W; - details.Satellite1.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite2.TrueRectangularCoordinates.Z/2095); - details.Satellite2.ApparentRectangularCoordinates.X *= W; - details.Satellite2.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite3.TrueRectangularCoordinates.Z/2095); - details.Satellite3.ApparentRectangularCoordinates.X *= W; - details.Satellite3.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite4.TrueRectangularCoordinates.Z/2095); - details.Satellite4.ApparentRectangularCoordinates.X *= W; - details.Satellite4.ApparentRectangularCoordinates.Y *= W; - - return details; - } - protected static double[] Rotations(double X, double Y, double Z, double I, double psi, double i, double omega, double lambda0, double beta0, C3D eclipticCoord) - { - double A6; - double B6; - double C6; - - //eclipticCoord = new CAA3DCoordinate(); - double phi = psi - omega; - - //Rotation towards Jupiter's orbital plane - double A1 = X; - double B1 = Y * Math.Cos(I) - Z * Math.Sin(I); - double C1 = Y * Math.Sin(I) + Z * Math.Cos(I); - - //Rotation towards the ascending node of the orbit of jupiter - double A2 = A1 * Math.Cos(phi) - B1 * Math.Sin(phi); - double B2 = A1 * Math.Sin(phi) + B1 * Math.Cos(phi); - double C2 = C1; - - //Rotation towards the plane of the ecliptic - double A3 = A2; - double B3 = B2 * Math.Cos(i) - C2 * Math.Sin(i); - double C3 = B2 * Math.Sin(i) + C2 * Math.Cos(i); - - //Rotation towards the vernal equinox - double A4 = A3 * Math.Cos(omega) - B3 * Math.Sin(omega); - double B4 = A3 * Math.Sin(omega) + B3 * Math.Cos(omega); - double C4 = C3; - - const double JupiterRadiiToAU = 1.0 / 2095.0; // Not exact, but this is the value used elsewhere in the calculation - eclipticCoord.X = A4 * JupiterRadiiToAU; - eclipticCoord.Y = B4 * JupiterRadiiToAU; - eclipticCoord.Z = C4 * JupiterRadiiToAU; - - double A5 = A4 * Math.Sin(lambda0) - B4 * Math.Cos(lambda0); - double B5 = A4 * Math.Cos(lambda0) + B4 * Math.Sin(lambda0); - double C5 = C4; - - A6 = A5; - B6 = C5 * Math.Sin(beta0) + B5 * Math.Cos(beta0); - C6 = C5 * Math.Cos(beta0) - B5 * Math.Sin(beta0); - - return new double[] { A6, B6, C6 }; - } - protected static void FillInPhenomenaDetails( GMD detail) - { - double Y1 = 1.071374 * detail.ApparentRectangularCoordinates.Y; - - double r = Y1 *Y1 + detail.ApparentRectangularCoordinates.X *detail.ApparentRectangularCoordinates.X; - - if (r < 1) - { - if (detail.ApparentRectangularCoordinates.Z < 0) - { - //Satellite nearer to Earth than Jupiter, so it must be a transit not an occultation - detail.bInTransit = true; - detail.bInOccultation = false; - } - else - { - detail.bInTransit = false; - detail.bInOccultation = true; - } - } - else - { - detail.bInTransit = false; - detail.bInOccultation = false; - } - } -} diff --git a/engine/csharp_ref/AstroCalc/AAGlobe.cs b/engine/csharp_ref/AstroCalc/AAGlobe.cs deleted file mode 100644 index 6257cf18..00000000 --- a/engine/csharp_ref/AstroCalc/AAGlobe.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -// -//Module : AAGLOBE.CPP -//Purpose: Implementation for the algorithms for the Earth's Globe -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////// Includes ////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAGlobe -{ -//Static methods - - /////////////////////////// Implementation //////////////////////////////////// - - public static double RhoSinThetaPrime(double GeographicalLatitude, double Height) - { - GeographicalLatitude = CT.D2R(GeographicalLatitude); - - double U = Math.Atan(0.99664719 * Math.Tan(GeographicalLatitude)); - return 0.99664719 * Math.Sin(U) + (Height/6378149 * Math.Sin(GeographicalLatitude)); - } - public static double RhoCosThetaPrime(double GeographicalLatitude, double Height) - { - //Convert from degress to radians - GeographicalLatitude = CT.D2R(GeographicalLatitude); - - double U = Math.Atan(0.99664719 * Math.Tan(GeographicalLatitude)); - return Math.Cos(U) + (Height/6378149 * Math.Cos(GeographicalLatitude)); - } - public static double RadiusOfParallelOfLatitude(double GeographicalLatitude) - { - //Convert from degress to radians - GeographicalLatitude = CT.D2R(GeographicalLatitude); - - double sinGeo = Math.Sin(GeographicalLatitude); - return (6378.14 * Math.Cos(GeographicalLatitude)) / (Math.Sqrt(1 - 0.0066943847614084 *sinGeo *sinGeo)); - } - public static double RadiusOfCurvature(double GeographicalLatitude) - { - //Convert from degress to radians - GeographicalLatitude = CT.D2R(GeographicalLatitude); - - double sinGeo = Math.Sin(GeographicalLatitude); - return (6378.14 * (1 - 0.0066943847614084)) / Math.Pow((1 - 0.0066943847614084 * sinGeo * sinGeo), 1.5); - } - public static double DistanceBetweenPoints(double GeographicalLatitude1, double GeographicalLongitude1, double GeographicalLatitude2, double GeographicalLongitude2) - { - //Convert from degress to radians - GeographicalLatitude1 = CT.D2R(GeographicalLatitude1); - GeographicalLatitude2 = CT.D2R(GeographicalLatitude2); - GeographicalLongitude1 = CT.D2R(GeographicalLongitude1); - GeographicalLongitude2 = CT.D2R(GeographicalLongitude2); - - double F = (GeographicalLatitude1 + GeographicalLatitude2) / 2; - double G = (GeographicalLatitude1 - GeographicalLatitude2) / 2; - double lambda = (GeographicalLongitude1 - GeographicalLongitude2) / 2; - double sinG = Math.Sin(G); - double cosG = Math.Cos(G); - double cosF = Math.Cos(F); - double sinF = Math.Sin(F); - double sinLambda = Math.Sin(lambda); - double cosLambda = Math.Cos(lambda); - double S = (sinG *sinG *cosLambda *cosLambda) + (cosF *cosF *sinLambda *sinLambda); - double C = (cosG *cosG *cosLambda *cosLambda) + (sinF *sinF *sinLambda *sinLambda); - double w = Math.Atan(Math.Sqrt(S/C)); - double R = Math.Sqrt(S *C)/w; - double D = 2 *w *6378.14; - double Hprime = (3 *R - 1) / (2 *C); - double Hprime2 = (3 *R + 1) / (2 *S); - double f = 0.0033528131778969144060323814696721; - - return D * (1 + (f *Hprime *sinF *sinF *cosG *cosG) - (f *Hprime2 *cosF *cosF *sinG *sinG)); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAIlluminatedFraction.cs b/engine/csharp_ref/AstroCalc/AAIlluminatedFraction.cs deleted file mode 100644 index 2863531e..00000000 --- a/engine/csharp_ref/AstroCalc/AAIlluminatedFraction.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using wwtlib; -// -//Module : AAILLUMINATEDFRACTION.CPP -//Purpose: Implementation for the algorithms for a planet's Phase Angle, Illuminated Fraction and Magnitude -//Created: PJN / 29-12-2003 -//History: PJN / 21-01-2005 1. Fixed a small but important error in the function PhaseAngle(r, R, Delta). The code -// was producing incorrect results and raises acos DOMAIN errors and floating point exceptions -// when calculating phase angles for the inner planets. Thanks to MICHAEL R. MEYER for -// reporting this problem. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////// Includes ///////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class IFR // was CAAILLUMINATEDFRACTION -{ -//Static methods - - //////////////////// Implementation /////////////////////////////////////////// - - public static double PhaseAngle(double r, double R, double Delta) - { - //Return the result - return CT.M360(CT.R2D(Math.Acos((r *r + Delta *Delta - R *R) / (2 *r *Delta)))); - } - public static double PhaseAngle2(double R, double R0, double B, double L, double L0, double Delta) - { - //Convert from degrees to radians - B = CT.D2R(B); - L = CT.D2R(L); - L0 = CT.D2R(L0); - - //Return the result - return CT.M360(CT.R2D(Math.Acos((R - R0 *Math.Cos(B)*Math.Cos(L - L0))/Delta))); - } - public static double PhaseAngleRectangular(double x, double y, double z, double B, double L, double Delta) - { - //Convert from degrees to radians - B = CT.D2R(B); - L = CT.D2R(L); - double cosB = Math.Cos(B); - - //Return the result - return CT.M360(CT.R2D(Math.Acos((x *cosB *Math.Cos(L) + y *cosB *Math.Sin(L) + z *Math.Sin(B)) / Delta))); - } - public static double IlluminatedFraction(double PhaseAngle) - { - //Convert from degrees to radians - PhaseAngle = CT.D2R(PhaseAngle); - - //Return the result - return (1 + Math.Cos(PhaseAngle)) / 2; - } - public static double IlluminatedFraction2(double r, double R, double Delta) - { - return (((r+Delta)*(r+Delta) - R *R) / (4 *r *Delta)); - } - public static double MercuryMagnitudeMuller(double r, double Delta, double i) - { - double I_50 = i - 50; - return 1.16 + 5 * Util.Log10(r * Delta) + 0.02838 * I_50 + 0.0001023 * I_50 * I_50; - } - public static double VenusMagnitudeMuller(double r, double Delta, double i) - { - return -4.00 + 5 * Util.Log10(r * Delta) + 0.01322 * i + 0.0000004247 * i * i * i; - } - public static double MarsMagnitudeMuller(double r, double Delta, double i) - { - return -1.3 + 5 * Util.Log10(r * Delta) + 0.01486 * i; - } - public static double JupiterMagnitudeMuller(double r, double Delta) - { - return -8.93 + 5 * Util.Log10(r * Delta); - } - public static double SaturnMagnitudeMuller(double r, double Delta, double DeltaU, double B) - { - //Convert from degrees to radians - B = CT.D2R(B); - double sinB = Math.Sin(B); - - return -8.68 + 5 * Util.Log10(r * Delta) + 0.044 * Math.Abs(DeltaU) - 2.60 * Math.Sin(Math.Abs(B)) + 1.25 * sinB * sinB; - } - public static double UranusMagnitudeMuller(double r, double Delta) - { - return -6.85 + 5 * Util.Log10(r * Delta); - } - public static double NeptuneMagnitudeMuller(double r, double Delta) - { - return -7.05 + 5 * Util.Log10(r * Delta); - } - public static double MercuryMagnitudeAA(double r, double Delta, double i) - { - double i2 = i *i; - double i3 = i2 *i; - - return -0.42 + 5 * Util.Log10(r * Delta) + 0.0380 * i - 0.000273 * i2 + 0.000002 * i3; - } - public static double VenusMagnitudeAA(double r, double Delta, double i) - { - double i2 = i *i; - double i3 = i2 *i; - - return -4.40 + 5 * Util.Log10(r * Delta) + 0.0009 * i + 0.000239 * i2 - 0.00000065 * i3; - } - public static double MarsMagnitudeAA(double r, double Delta, double i) - { - return -1.52 + 5 * Util.Log10(r * Delta) + 0.016 * i; - } - public static double JupiterMagnitudeAA(double r, double Delta, double i) - { - return -9.40 + 5 * Util.Log10(r * Delta) + 0.005 * i; - } - public static double SaturnMagnitudeAA(double r, double Delta, double DeltaU, double B) - { - //Convert from degrees to radians - B = CT.D2R(B); - double sinB = Math.Sin(B); - - return -8.88 + 5 * Util.Log10(r * Delta) + 0.044 * Math.Abs(DeltaU) - 2.60 * Math.Sin(Math.Abs(B)) + 1.25 * sinB * sinB; - } - public static double UranusMagnitudeAA(double r, double Delta) - { - return -7.19 + 5 * Util.Log10(r * Delta); - } - public static double NeptuneMagnitudeAA(double r, double Delta) - { - return -6.87 + 5 * Util.Log10(r * Delta); - } - public static double PlutoMagnitudeAA(double r, double Delta) - { - return -1.00 + 5 * Util.Log10(r * Delta); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAInterpolate.cs b/engine/csharp_ref/AstroCalc/AAInterpolate.cs deleted file mode 100644 index e22b2330..00000000 --- a/engine/csharp_ref/AstroCalc/AAInterpolate.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System.Diagnostics; -using System; -// -//Module : AAINTERPOLATE.CPP -//Purpose: Implementation for the algorithms for Interpolation -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -////////////////////// Includes /////////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class INTP // was -{ -//Static methods - - ////////////////////// Implementation ///////////////////////////////////////// - - public static double Interpolate(double n, double Y1, double Y2, double Y3) - { - double a = Y2 - Y1; - double b = Y3 - Y2; - double c = Y1 + Y3 - 2 *Y2; - - return Y2 + n / 2 * (a + b + n *c); - } - public static double Interpolate2(double n, double Y1, double Y2, double Y3, double Y4, double Y5) - { - double A = Y2 - Y1; - double B = Y3 - Y2; - double C = Y4 - Y3; - double D = Y5 - Y4; - double E = B - A; - double F = C - B; - double G = D - C; - double H = F - E; - double J = G - F; - double K = J - H; - - double N2 = n *n; - double N3 = N2 *n; - double N4 = N3 *n; - - return Y3 + n*((B+C)/2 - (H+J)/12) + N2*(F/2 - K/24) + N3*((H+J)/12) + N4*(K/24); - } - public static double InterpolateToHalves(double Y1, double Y2, double Y3, double Y4) - { - return (9*(Y2 + Y3) - Y1 - Y4) / 16; - } - public static double LagrangeInterpolate(double X, int n, double[] pX, double[] pY) - { - double V = 0; - - for (int i =1; i<=n; i++) - { - double C = 1; - for (int j =1; j<=n; j++) - { - if (j != i) - C = C*(X - pX[j-1]) / (pX[i-1] - pX[j-1]); - } - - V += C *pY[i - 1]; - } - - return V; - } - //public static double Extremum(double Y1, double Y2, double Y3, ref double nm) - //{ - // double a = Y2 - Y1; - // double b = Y3 - Y2; - // double c = Y1 + Y3 - 2 *Y2; - - // double ab = a + b; - - // nm = -ab/(2 *c); - // return (Y2 - ((ab *ab)/(8 *c))); - //} - //public static double Extremum2(double Y1, double Y2, double Y3, double Y4, double Y5, ref double nm) - //{ - // double A = Y2 - Y1; - // double B = Y3 - Y2; - // double C = Y4 - Y3; - // double D = Y5 - Y4; - // double E = B - A; - // double F = C - B; - // double G = D - C; - // double H = F - E; - // double J = G - F; - // double K = J - H; - - // bool bRecalc = true; - // double nmprev = 0; - // nm = nmprev; - // while (bRecalc) - // { - // double NMprev2 = nmprev *nmprev; - // double NMprev3 = NMprev2 *nmprev; - // nm = (6 *B + 6 *C - H - J +3 *NMprev2*(H+J) + 2 *NMprev3 *K) / (K - 12 *F); - - // bRecalc = (Math.Abs(nm - nmprev) > 1E-12); - // if (bRecalc) - // nmprev = nm; - // } - - // return Interpolate2(nm, Y1, Y2, Y3, Y4, Y5); - //} - public static double Zero(double Y1, double Y2, double Y3) - { - double a = Y2 - Y1; - double b = Y3 - Y2; - double c = Y1 + Y3 - 2 *Y2; - - bool bRecalc = true; - double n0prev = 0; - double n0 = n0prev; - while (bRecalc) - { - n0 = -2 *Y2/(a + b + c *n0prev); - - bRecalc = (Math.Abs(n0 - n0prev) > 1E-12); - if (bRecalc) - n0prev = n0; - } - - return n0; - } - public static double ZeroB(double Y1, double Y2, double Y3, double Y4, double Y5) - { - double A = Y2 - Y1; - double B = Y3 - Y2; - double C = Y4 - Y3; - double D = Y5 - Y4; - double E = B - A; - double F = C - B; - double G = D - C; - double H = F - E; - double J = G - F; - double K = J - H; - - bool bRecalc = true; - double n0prev = 0; - double n0 = n0prev; - while (bRecalc) - { - double n0prev2 = n0prev *n0prev; - double n0prev3 = n0prev2 *n0prev; - double n0prev4 = n0prev3 *n0prev; - - n0 = (-24 *Y3 + n0prev2*(K - 12 *F) - 2 *n0prev3*(H+J) - n0prev4 *K)/(2*(6 *B + 6 *C - H - J)); - - bRecalc = (Math.Abs(n0 - n0prev) > 1E-12); - if (bRecalc) - n0prev = n0; - } - - return n0; - } - public static double Zero2(double Y1, double Y2, double Y3) - { - double a = Y2 - Y1; - double b = Y3 - Y2; - double c = Y1 + Y3 - 2 *Y2; - - bool bRecalc = true; - double n0prev = 0; - double n0 = n0prev; - while (bRecalc) - { - double deltan0 = - (2 *Y2 + n0prev*(a + b + c *n0prev)) / (a + b + 2 *c *n0prev); - n0 = n0prev + deltan0; - - bRecalc = (Math.Abs(deltan0) > 1E-12); - if (bRecalc) - n0prev = n0; - } - - return n0; - } - public static double Zero2B(double Y1, double Y2, double Y3, double Y4, double Y5) - { - double A = Y2 - Y1; - double B = Y3 - Y2; - double C = Y4 - Y3; - double D = Y5 - Y4; - double E = B - A; - double F = C - B; - double G = D - C; - double H = F - E; - double J = G - F; - double K = J - H; - double M = K / 24; - double N = (H + J)/12; - double P = F/2 - M; - double Q = (B+C)/2 - N; - - bool bRecalc = true; - double n0prev = 0; - double n0 = n0prev; - while (bRecalc) - { - double n0prev2 = n0prev *n0prev; - double n0prev3 = n0prev2 *n0prev; - double n0prev4 = n0prev3 *n0prev; - - double deltan0 = - (M * n0prev4 + N *n0prev3 + P *n0prev2 + Q *n0prev + Y3) / (4 *M *n0prev3 + 3 *N *n0prev2 + 2 *P *n0prev + Q); - n0 = n0prev + deltan0; - - bRecalc = (Math.Abs(deltan0) > 1E-12); - if (bRecalc) - n0prev = n0; - } - - return n0; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAJupiter.cs b/engine/csharp_ref/AstroCalc/AAJupiter.cs deleted file mode 100644 index 43d84b30..00000000 --- a/engine/csharp_ref/AstroCalc/AAJupiter.cs +++ /dev/null @@ -1,238 +0,0 @@ -using System; -public static partial class GFX -{ - - public static VSC[] g_L0JupiterCoefficients = { new VSC(59954691, 0, 0), new VSC(9695899, 5.0619179, 529.6909651), new VSC(573610, 1.444062, 7.113547), new VSC(306389, 5.417347, 1059.381930), new VSC(97178, 4.14265, 632.78374), new VSC(72903, 3.64043, 522.57742), new VSC(64264, 3.41145, 103.09277), new VSC(39806, 2.29377, 419.48464), new VSC(38858, 1.27232, 316.39187), new VSC(27965, 1.78455, 536.80451), new VSC(13590, 5.77481, 1589.07290), new VSC(8769, 3.6300, 949.1756), new VSC(8246, 3.5823, 206.1855), new VSC(7368, 5.0810, 735.8765), new VSC(6263, 0.0250, 213.2991), new VSC(6114, 4.5132, 1162.4747), new VSC(5305, 4.1863, 1052.2684), new VSC(5305, 1.3067, 14.2271), new VSC(4905, 1.3208, 110.2063), new VSC(4647, 4.6996, 3.9322), new VSC(3045, 4.3168, 426.5982), new VSC(2610, 1.5667, 846.0828), new VSC(2028, 1.0638, 3.1814), new VSC(1921, 0.9717, 639.8973), new VSC(1765, 2.1415, 1066.4955), new VSC(1723, 3.8804, 1265.5675), new VSC(1633, 3.5820, 515.4639), new VSC(1432, 4.2968, 625.6702), new VSC(973, 4.098, 95.979), new VSC(884, 2.437, 412.371), new VSC(733, 6.085, 838.969), new VSC(731, 3.806, 1581.959), new VSC(709, 1.293, 742.990), new VSC(692, 6.134, 2118.764), new VSC(614, 4.109, 1478.867), new VSC(582, 4.540, 309.278), new VSC(495, 3.756, 323.505), new VSC(441, 2.958, 454.909), new VSC(417, 1.036, 2.488), new VSC(390, 4.897, 1692.166), new VSC(376, 4.703, 1368.660), new VSC(341, 5.715, 533.623), new VSC(330, 4.740, 0.048), new VSC(262, 1.877, 0.963), new VSC(261, 0.820, 380.128), new VSC(257, 3.724, 199.072), new VSC(244, 5.220, 728.763), new VSC(235, 1.227, 909.819), new VSC(220, 1.651, 543.918), new VSC(207, 1.855, 525.759), new VSC(202, 1.807, 1375.774), new VSC(197, 5.293, 1155.361), new VSC(175, 3.730, 942.062), new VSC(175, 3.226, 1898.351), new VSC(175, 5.910, 956.289), new VSC(158, 4.365, 1795.258), new VSC(151, 3.906, 74.782), new VSC(149, 4.377, 1685.052), new VSC(141, 3.136, 491.558), new VSC(138, 1.318, 1169.588), new VSC(131, 4.169, 1045.155), new VSC(117, 2.500, 1596.186), new VSC(117, 3.389, 0.521), new VSC(106, 4.554, 526.510) }; - - public static VSC[] g_L1JupiterCoefficients = { new VSC(52993480757.0, 0, 0), new VSC(489741, 4.220667, 529.690965), new VSC(228919, 6.026475, 7.113547), new VSC(27655, 4.57266, 1059.38193), new VSC(20721, 5.45939, 522.57742), new VSC(12106, 0.16986, 536.80451), new VSC(6068, 4.4242, 103.0928), new VSC(5434, 3.9848, 419.4846), new VSC(4238, 5.8901, 14.2271), new VSC(2212, 5.2677, 206.1855), new VSC(1746, 4.9267, 1589.0729), new VSC(1296, 5.5513, 3.1814), new VSC(1173, 5.8565, 1052.2684), new VSC(1163, 0.5145, 3.9322), new VSC(1099, 5.3070, 515.4639), new VSC(1007, 0.4648, 735.8765), new VSC(1004, 3.1504, 426.5982), new VSC(848, 5.758, 110.206), new VSC(827, 4.803, 213.299), new VSC(816, 0.586, 1066.495), new VSC(725, 5.518, 639.897), new VSC(568, 5.989, 625.670), new VSC(474, 4.132, 412.371), new VSC(413, 5.737, 95.979), new VSC(345, 4.242, 632.784), new VSC(336, 3.732, 1162.475), new VSC(234, 4.035, 949.176), new VSC(234, 6.243, 309.278), new VSC(199, 1.505, 838.969), new VSC(195, 2.219, 323.505), new VSC(187, 6.086, 742.990), new VSC(184, 6.280, 543.918), new VSC(171, 5.417, 199.072), new VSC(131, 0.626, 728.763), new VSC(115, 0.680, 846.083), new VSC(115, 5.286, 2118.764), new VSC(108, 4.493, 956.289), new VSC(80, 5.82, 1045.15), new VSC(72, 5.34, 942.06), new VSC(70, 5.97, 532.87), new VSC(67, 5.73, 21.34), new VSC(66, 0.13, 526.51), new VSC(65, 6.09, 1581.96), new VSC(59, 0.59, 1155.36), new VSC(58, 0.99, 1596.19), new VSC(57, 5.97, 1169.59), new VSC(57, 1.41, 533.62), new VSC(55, 5.43, 10.29), new VSC(52, 5.73, 117.32), new VSC(52, 0.23, 1368.66), new VSC(50, 6.08, 525.76), new VSC(47, 3.63, 1478.87), new VSC(47, 0.51, 1265.57), new VSC(40, 4.16, 1692.17), new VSC(34, 0.10, 302.16), new VSC(33, 5.04, 220.41), new VSC(32, 5.37, 508.35), new VSC(29, 5.42, 1272.68), new VSC(29, 3.36, 4.67), new VSC(29, 0.76, 88.87), new VSC(25, 1.61, 831.86) }; - - public static VSC[] g_L2JupiterCoefficients = { new VSC(47234, 4.32148, 7.11355), new VSC(38966, 0, 0), new VSC(30629, 2.93021, 529.69097), new VSC(3189, 1.0550, 522.5774), new VSC(2729, 4.8455, 536.8045), new VSC(2723, 3.4141, 1059.3819), new VSC(1721, 4.1873, 14.2271), new VSC(383, 5.768, 419.485), new VSC(378, 0.760, 515.464), new VSC(367, 6.055, 103.093), new VSC(337, 3.786, 3.181), new VSC(308, 0.694, 206.186), new VSC(218, 3.814, 1589.073), new VSC(199, 5.340, 1066.495), new VSC(197, 2.484, 3.932), new VSC(156, 1.406, 1052.268), new VSC(146, 3.814, 639.897), new VSC(142, 1.634, 426.598), new VSC(130, 5.837, 412.371), new VSC(117, 1.414, 625.670), new VSC(97, 4.03, 110.21), new VSC(91, 1.11, 95.98), new VSC(87, 2.52, 632.78), new VSC(79, 4.64, 543.92), new VSC(72, 2.22, 735.88), new VSC(58, 0.83, 199.07), new VSC(57, 3.12, 213.30), new VSC(49, 1.67, 309.28), new VSC(40, 4.02, 21.34), new VSC(40, 0.62, 323.51), new VSC(36, 2.33, 728.76), new VSC(29, 3.61, 10.29), new VSC(28, 3.24, 838.97), new VSC(26, 4.50, 742.99), new VSC(26, 2.51, 1162.47), new VSC(25, 1.22, 1045.15), new VSC(24, 3.01, 956.29), new VSC(19, 4.29, 532.87), new VSC(18, 0.81, 508.35), new VSC(17, 4.20, 2118.76), new VSC(17, 1.83, 526.51), new VSC(15, 5.81, 1596.19), new VSC(15, 0.68, 942.06), new VSC(15, 4.00, 117.32), new VSC(14, 5.95, 316.39), new VSC(14, 1.80, 302.16), new VSC(13, 2.52, 88.87), new VSC(13, 4.37, 1169.59), new VSC(11, 4.44, 525.76), new VSC(10, 1.72, 1581.96), new VSC(9, 2.18, 1155.36), new VSC(9, 3.29, 220.41), new VSC(9, 3.32, 831.86), new VSC(8, 5.76, 846.08), new VSC(8, 2.71, 533.62), new VSC(7, 2.18, 1265.57), new VSC(6, 0.50, 949.18) }; - - public static VSC[] g_L3JupiterCoefficients = { new VSC(6502, 2.5986, 7.1135), new VSC(1357, 1.3464, 529.6910), new VSC(471, 2.475, 14.227), new VSC(417, 3.245, 536.805), new VSC(353, 2.974, 522.577), new VSC(155, 2.076, 1059.382), new VSC(87, 2.51, 515.46), new VSC(44, 0, 0), new VSC(34, 3.83, 1066.50), new VSC(28, 2.45, 206.19), new VSC(24, 1.28, 412.37), new VSC(23, 2.98, 543.92), new VSC(20, 2.10, 639.90), new VSC(20, 1.40, 419.48), new VSC(19, 1.59, 103.09), new VSC(17, 2.30, 21.34), new VSC(17, 2.60, 1589.07), new VSC(16, 3.15, 625.67), new VSC(16, 3.36, 1052.27), new VSC(13, 2.76, 95.98), new VSC(13, 2.54, 199.07), new VSC(13, 6.27, 426.60), new VSC(9, 1.76, 10.29), new VSC(9, 2.27, 110.21), new VSC(7, 3.43, 309.28), new VSC(7, 4.04, 728.76), new VSC(6, 2.52, 508.35), new VSC(5, 2.91, 1045.15), new VSC(5, 5.25, 323.51), new VSC(4, 4.30, 88.87), new VSC(4, 3.52, 302.16), new VSC(4, 4.09, 735.88), new VSC(3, 1.43, 956.29), new VSC(3, 4.36, 1596.19), new VSC(3, 1.25, 213.30), new VSC(3, 5.02, 838.97), new VSC(3, 2.24, 117.32), new VSC(2, 2.90, 742.99), new VSC(2, 2.36, 942.06) }; - - public static VSC[] g_L4JupiterCoefficients = { new VSC(669, 0.853, 7.114), new VSC(114, 3.142, 0), new VSC(100, 0.743, 14.227), new VSC(50, 1.65, 536.80), new VSC(44, 5.82, 529.69), new VSC(32, 4.86, 522.58), new VSC(15, 4.29, 515.46), new VSC(9, 0.71, 1059.38), new VSC(5, 1.30, 543.92), new VSC(4, 2.32, 1066.50), new VSC(4, 0.48, 21.34), new VSC(3, 3.00, 412.37), new VSC(2, 0.40, 639.90), new VSC(2, 4.26, 199.07), new VSC(2, 4.91, 625.67), new VSC(2, 4.26, 206.19), new VSC(1, 5.26, 1052.27), new VSC(1, 4.72, 95.98), new VSC(1, 1.29, 1589.07) }; - - public static VSC[] g_L5JupiterCoefficients = { new VSC(50, 5.26, 7.11), new VSC(16, 5.25, 14.23), new VSC(4, 0.01, 536.80), new VSC(2, 1.10, 522.58), new VSC(1, 3.14, 0) }; - - - public static VSC[] g_B0JupiterCoefficients = { new VSC(2268616, 3.5585261, 529.6909651), new VSC(110090, 0, 0), new VSC(109972, 3.908093, 1059.381930), new VSC(8101, 3.6051, 522.5774), new VSC(6438, 0.3063, 536.8045), new VSC(6044, 4.2588, 1589.0729), new VSC(1107, 2.9853, 1162.4747), new VSC(944, 1.675, 426.598), new VSC(942, 2.936, 1052.268), new VSC(894, 1.754, 7.114), new VSC(836, 5.179, 103.093), new VSC(767, 2.155, 632.784), new VSC(684, 3.678, 213.299), new VSC(629, 0.643, 1066.495), new VSC(559, 0.014, 846.083), new VSC(532, 2.703, 110.206), new VSC(464, 1.173, 949.176), new VSC(431, 2.608, 419.485), new VSC(351, 4.611, 2118.764), new VSC(132, 4.778, 742.990), new VSC(123, 3.350, 1692.166), new VSC(116, 1.387, 323.505), new VSC(115, 5.049, 316.392), new VSC(104, 3.701, 515.464), new VSC(103, 2.319, 1478.867), new VSC(102, 3.153, 1581.959) }; - - public static VSC[] g_B1JupiterCoefficients = { new VSC(177352, 5.701665, 529.690965), new VSC(3230, 5.7794, 1059.3819), new VSC(3081, 5.4746, 522.5774), new VSC(2212, 4.7348, 536.8045), new VSC(1694, 3.1416, 0), new VSC(346, 4.746, 1052.268), new VSC(234, 5.189, 1066.495), new VSC(196, 6.186, 7.114), new VSC(150, 3.927, 1589.073), new VSC(114, 3.439, 632.784), new VSC(97, 2.91, 949.18), new VSC(82, 5.08, 1162.47), new VSC(77, 2.51, 103.09), new VSC(77, 0.61, 419.48), new VSC(74, 5.50, 515.46), new VSC(61, 5.45, 213.30), new VSC(50, 3.95, 735.88), new VSC(46, 0.54, 110.21), new VSC(45, 1.90, 846.08), new VSC(37, 4.70, 543.92), new VSC(36, 6.11, 316.39), new VSC(32, 4.92, 1581.96) }; - - public static VSC[] g_B2JupiterCoefficients = { new VSC(8094, 1.4632, 529.6910), new VSC(813, 3.1416, 0), new VSC(742, 0.957, 522.577), new VSC(399, 2.899, 536.805), new VSC(342, 1.447, 1059.382), new VSC(74, 0.41, 1052.27), new VSC(46, 3.48, 1066.50), new VSC(30, 1.93, 1589.07), new VSC(29, 0.99, 515.46), new VSC(23, 4.27, 7.11), new VSC(14, 2.92, 543.92), new VSC(12, 5.22, 632.78), new VSC(11, 4.88, 949.18), new VSC(6, 6.21, 1045.15) }; - - public static VSC[] g_B3JupiterCoefficients = { new VSC(252, 3.381, 529.691), new VSC(122, 2.733, 522.577), new VSC(49, 1.04, 536.80), new VSC(11, 2.31, 1052.27), new VSC(8, 2.77, 515.46), new VSC(7, 4.25, 1059.38), new VSC(6, 1.78, 1066.50), new VSC(4, 1.13, 543.92), new VSC(3, 3.14, 0) }; - - - public static VSC[] g_B4JupiterCoefficients = { new VSC(15, 4.53, 522.58), new VSC(5, 4.47, 529.69), new VSC(4, 5.44, 536.80), new VSC(3, 0, 0), new VSC(2, 4.52, 515.46), new VSC(1, 4.20, 1052.27) }; - - public static VSC[] g_B5JupiterCoefficients = { new VSC(1, 0.09, 522.58) }; - - public static VSC[] g_R0JupiterCoefficients = { new VSC(520887429, 0, 0), new VSC(25209327, 3.49108640, 529.69096509), new VSC(610600, 3.841154, 1059.381930), new VSC(282029, 2.574199, 632.783739), new VSC(187647, 2.075904, 522.577418), new VSC(86793, 0.71001, 419.48464), new VSC(72063, 0.21466, 536.80451), new VSC(65517, 5.97996, 316.39187), new VSC(30135, 2.16132, 949.17561), new VSC(29135, 1.67759, 103.09277), new VSC(23947, 0.27458, 7.11355), new VSC(23453, 3.54023, 735.87651), new VSC(22284, 4.19363, 1589.07290), new VSC(13033, 2.96043, 1162.47470), new VSC(12749, 2.71550, 1052.26838), new VSC(9703, 1.9067, 206.1855), new VSC(9161, 4.4135, 213.2991), new VSC(7895, 2.4791, 426.5982), new VSC(7058, 2.1818, 1265.5675), new VSC(6138, 6.2642, 846.0828), new VSC(5477, 5.6573, 639.8973), new VSC(4170, 2.0161, 515.4639), new VSC(4137, 2.7222, 625.6702), new VSC(3503, 0.5653, 1066.4955), new VSC(2617, 2.0099, 1581.9593), new VSC(2500, 4.5518, 838.9693), new VSC(2128, 6.1275, 742.9901), new VSC(1912, 0.8562, 412.3711), new VSC(1611, 3.0887, 1368.6603), new VSC(1479, 2.6803, 1478.8666), new VSC(1231, 1.8904, 323.5054), new VSC(1217, 1.8017, 110.2063), new VSC(1015, 1.3867, 454.9094), new VSC(999, 2.872, 309.278), new VSC(961, 4.549, 2118.764), new VSC(886, 4.148, 533.623), new VSC(821, 1.593, 1898.351), new VSC(812, 5.941, 909.819), new VSC(777, 3.677, 728.763), new VSC(727, 3.988, 1155.361), new VSC(655, 2.791, 1685.052), new VSC(654, 3.382, 1692.166), new VSC(621, 4.823, 956.289), new VSC(615, 2.276, 942.062), new VSC(562, 0.081, 543.918), new VSC(542, 0.284, 525.759) }; - - public static VSC[] g_R1JupiterCoefficients = { new VSC(1271802, 2.6493751, 529.6909651), new VSC(61662, 3.00076, 1059.38193), new VSC(53444, 3.89718, 522.57742), new VSC(41390, 0, 0), new VSC(31185, 4.88277, 536.80451), new VSC(11847, 2.41330, 419.48464), new VSC(9166, 4.7598, 7.1135), new VSC(3404, 3.3469, 1589.0729), new VSC(3203, 5.2108, 735.8765), new VSC(3176, 2.7930, 103.0928), new VSC(2806, 3.7422, 515.4639), new VSC(2677, 4.3305, 1052.2684), new VSC(2600, 3.6344, 206.1855), new VSC(2412, 1.4695, 426.5982), new VSC(2101, 3.9276, 639.8973), new VSC(1646, 4.4163, 1066.4955), new VSC(1641, 4.4163, 625.6702), new VSC(1050, 3.1611, 213.2991), new VSC(1025, 2.5543, 412.3711), new VSC(806, 2.678, 632.784), new VSC(741, 2.171, 1162.475), new VSC(677, 6.250, 838.969), new VSC(567, 4.577, 742.990), new VSC(485, 2.469, 949.176), new VSC(469, 4.710, 543.918), new VSC(445, 0.403, 323.505), new VSC(416, 5.368, 728.763), new VSC(402, 4.605, 309.278), new VSC(347, 4.681, 14.227), new VSC(338, 3.168, 956.289), new VSC(261, 5.343, 846.083), new VSC(247, 3.923, 942.062), new VSC(220, 4.842, 1368.660), new VSC(203, 5.600, 1155.361), new VSC(200, 4.439, 1045.155), new VSC(197, 3.706, 2118.764), new VSC(196, 3.759, 199.072), new VSC(184, 4.265, 95.979), new VSC(180, 4.402, 532.872), new VSC(170, 4.846, 526.510), new VSC(146, 6.130, 533.623), new VSC(133, 1.322, 110.206), new VSC(132, 4.512, 525.759) }; - - public static VSC[] g_R2JupiterCoefficients = { new VSC(79645, 1.35866, 529.69097), new VSC(8252, 5.7777, 522.5774), new VSC(7030, 3.2748, 536.8045), new VSC(5314, 1.8384, 1059.3819), new VSC(1861, 2.9768, 7.1135), new VSC(964, 5.480, 515.464), new VSC(836, 4.199, 419.485), new VSC(498, 3.142, 0), new VSC(427, 2.228, 639.897), new VSC(406, 3.783, 1066.495), new VSC(377, 2.242, 1589.073), new VSC(363, 5.368, 206.186), new VSC(342, 6.099, 1052.268), new VSC(339, 6.127, 625.670), new VSC(333, 0.003, 426.598), new VSC(280, 4.262, 412.371), new VSC(257, 0.963, 632.784), new VSC(230, 0.705, 735.877), new VSC(201, 3.069, 543.918), new VSC(200, 4.429, 103.093), new VSC(139, 2.932, 14.227), new VSC(114, 0.787, 728.763), new VSC(95, 1.70, 838.97), new VSC(86, 5.14, 323.51), new VSC(83, 0.06, 309.28), new VSC(80, 2.98, 742.99), new VSC(75, 1.60, 956.29), new VSC(70, 1.51, 213.30), new VSC(67, 5.47, 199.07), new VSC(62, 6.10, 1045.15), new VSC(56, 0.96, 1162.47), new VSC(52, 5.58, 942.06), new VSC(50, 2.72, 532.87), new VSC(45, 5.52, 508.35), new VSC(44, 0.27, 526.51), new VSC(40, 5.95, 95.98) }; - - public static VSC[] g_R3JupiterCoefficients = { new VSC(3519, 6.0580, 529.6910), new VSC(1073, 1.6732, 536.8045), new VSC(916, 1.413, 522.577), new VSC(342, 0.523, 1059.382), new VSC(255, 1.196, 7.114), new VSC(222, 0.952, 515.464), new VSC(90, 3.14, 0), new VSC(69, 2.27, 1066.50), new VSC(58, 1.41, 543.92), new VSC(58, 0.53, 639.90), new VSC(51, 5.98, 412.37), new VSC(47, 1.58, 625.67), new VSC(43, 6.12, 419.48), new VSC(37, 1.18, 14.23), new VSC(34, 1.67, 1052.27), new VSC(34, 0.85, 206.19), new VSC(31, 1.04, 1589.07), new VSC(30, 4.63, 426.60), new VSC(21, 2.50, 728.76), new VSC(15, 0.89, 199.07), new VSC(14, 0.96, 508.35), new VSC(13, 1.50, 1045.15), new VSC(12, 2.61, 735.88), new VSC(12, 3.56, 323.51), new VSC(11, 1.79, 309.28), new VSC(11, 6.28, 956.29), new VSC(10, 6.26, 103.09), new VSC(9, 3.45, 838.97) }; - - public static VSC[] g_R4JupiterCoefficients = { new VSC(129, 0.084, 536.805), new VSC(113, 4.249, 529.691), new VSC(83, 3.30, 522.58), new VSC(38, 2.73, 515.46), new VSC(27, 5.69, 7.11), new VSC(18, 5.40, 1059.38), new VSC(13, 6.02, 543.92), new VSC(9, 0.77, 1066.50), new VSC(8, 5.68, 14.23), new VSC(7, 1.43, 412.37), new VSC(6, 5.12, 639.90), new VSC(5, 3.34, 625.67), new VSC(3, 3.40, 1052.27), new VSC(3, 4.16, 728.76), new VSC(3, 2.90, 426.60) }; - - public static VSC[] g_R5JupiterCoefficients = { new VSC(11, 4.75, 536.80), new VSC(4, 5.92, 522.58), new VSC(2, 5.57, 515.46), new VSC(2, 4.30, 543.92), new VSC(2, 3.69, 7.11), new VSC(2, 4.13, 1059.38), new VSC(2, 5.49, 1066.50) }; -} -// -//Module : AAJUPITER.CPP -//Purpose: Implementation for the algorithms which obtain the heliocentric position of Uranus -//Created: PJN / 29-12-2003 -//History: PJN / 31-05-2004 1) Added a missing coefficient to g_L1JupiterCoefficients array as used by -// CAAJupiter::EclipticLongitude. Thanks to Brian Orme for reporting this problem. -// 2) Added missing g_B5JupiterCoefficients[] in CAAJupiter::EclipticLatitude. Again -// thanks to Brian Orme for reporting this problem. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////// Includes ////////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAJupiter -{ -//Static methods - - ////////////////////////// Implementation ///////////////////////////////////// - - public static double EclipticLongitude(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho *rho; - double rhocubed = rhosquared *rho; - double rho4 = rhocubed *rho; - double rho5 = rho4 *rho; - - //Calculate L0 - int nL0Coefficients = GFX.g_L0JupiterCoefficients.Length; - double L0 = 0; - int i; - for (i =0; i PI) - F = -1; - if (M > PI) - M = 2 *PI - M; - - double E = PI / 2; - double scale = PI / 4; - for (int i =0; i R) - E += scale; - else - E -= scale; - scale /= 2; - } - - //Convert the result back to degrees - return CT.R2D(E) * F; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAMars.cs b/engine/csharp_ref/AstroCalc/AAMars.cs deleted file mode 100644 index b7b0445b..00000000 --- a/engine/csharp_ref/AstroCalc/AAMars.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System; -public static partial class GFX -{ - - public static VSC[] g_L0MarsCoefficients = { new VSC(620347712, 0, 0), new VSC(18656368, 5.05037100, 3340.61242670), new VSC(1108217, 5.4009984, 6681.2248534), new VSC(91798, 5.75479, 10021.83728), new VSC(27745, 5.97050, 3.52312), new VSC(12316, 0.84956, 2810.92146), new VSC(10610, 2.93959, 2281.23050), new VSC(8927, 4.1570, 0.0173), new VSC(8716, 6.1101, 13362.4497), new VSC(7775, 3.3397, 5621.8429), new VSC(6798, 0.3646, 398.1490), new VSC(4161, 0.2281, 2942.4634), new VSC(3575, 1.6619, 2544.3144), new VSC(3075, 0.8570, 191.4483), new VSC(2938, 6.0789, 0.0673), new VSC(2628, 0.6481, 3337.0893), new VSC(2580, 0.0300, 3344.1355), new VSC(2389, 5.0390, 796.2980), new VSC(1799, 0.6563, 529.6910), new VSC(1546, 2.9158, 1751.5395), new VSC(1528, 1.1498, 6151.5339), new VSC(1286, 3.0680, 2146.1654), new VSC(1264, 3.6228, 5092.1520), new VSC(1025, 3.6933, 8962.4553), new VSC(892, 0.183, 16703.062), new VSC(859, 2.401, 2914.014), new VSC(833, 4.495, 3340.630), new VSC(833, 2.464, 3340.595), new VSC(749, 3.822, 155.420), new VSC(724, 0.675, 3738.761), new VSC(713, 3.663, 1059.382), new VSC(655, 0.489, 3127.313), new VSC(636, 2.922, 8432.764), new VSC(553, 4.475, 1748.016), new VSC(550, 3.810, 0.980), new VSC(472, 3.625, 1194.447), new VSC(426, 0.554, 6283.076), new VSC(415, 0.497, 213.299), new VSC(312, 0.999, 6677.702), new VSC(307, 0.381, 6684.748), new VSC(302, 4.486, 3532.061), new VSC(299, 2.783, 6254.627), new VSC(293, 4.221, 20.775), new VSC(284, 5.769, 3149.164), new VSC(281, 5.882, 1349.867), new VSC(274, 0.542, 3340.545), new VSC(274, 0.134, 3340.680), new VSC(239, 5.372, 4136.910), new VSC(236, 5.755, 3333.499), new VSC(231, 1.282, 3870.303), new VSC(221, 3.505, 382.897), new VSC(204, 2.821, 1221.849), new VSC(193, 3.357, 3.590), new VSC(189, 1.491, 9492.146), new VSC(179, 1.006, 951.718), new VSC(174, 2.414, 553.569), new VSC(172, 0.439, 5486.778), new VSC(160, 3.949, 4562.461), new VSC(144, 1.419, 135.065), new VSC(140, 3.326, 2700.715), new VSC(138, 4.301, 7.114), new VSC(131, 4.045, 12303.068), new VSC(128, 2.208, 1592.596), new VSC(128, 1.807, 5088.629), new VSC(117, 3.128, 7903.073), new VSC(113, 3.701, 1589.073), new VSC(110, 1.052, 242.729), new VSC(105, 0.785, 8827.390), new VSC(100, 3.243, 11773.377) }; - - public static VSC[] g_L1MarsCoefficients = { new VSC(334085627474.0, 0, 0), new VSC(1458227, 3.6042605, 3340.6124267), new VSC(164901, 3.926313, 6681.224853), new VSC(19963, 4.26594, 10021.83728), new VSC(3452, 4.7321, 3.5231), new VSC(2485, 4.6128, 13362.4497), new VSC(842, 4.459, 2281.230), new VSC(538, 5.016, 398.149), new VSC(521, 4.994, 3344.136), new VSC(433, 2.561, 191.448), new VSC(430, 5.316, 155.420), new VSC(382, 3.539, 796.298), new VSC(314, 4.963, 16703.062), new VSC(283, 3.160, 2544.314), new VSC(206, 4.569, 2146.165), new VSC(169, 1.329, 3337.089), new VSC(158, 4.185, 1751.540), new VSC(134, 2.233, 0.980), new VSC(134, 5.974, 1748.016), new VSC(118, 6.024, 6151.534), new VSC(117, 2.213, 1059.382), new VSC(114, 2.129, 1194.447), new VSC(114, 5.428, 3738.761), new VSC(91, 1.10, 1349.87), new VSC(85, 3.91, 553.57), new VSC(83, 5.30, 6684.75), new VSC(81, 4.43, 529.69), new VSC(80, 2.25, 8962.46), new VSC(73, 2.50, 951.72), new VSC(73, 5.84, 242.73), new VSC(71, 3.86, 2914.01), new VSC(68, 5.02, 382.90), new VSC(65, 1.02, 3340.60), new VSC(65, 3.05, 3340.63), new VSC(62, 4.15, 3149.16), new VSC(57, 3.89, 4136.91), new VSC(48, 4.87, 213.30), new VSC(48, 1.18, 3333.50), new VSC(47, 1.31, 3185.19), new VSC(41, 0.71, 1592.60), new VSC(40, 2.73, 7.11), new VSC(40, 5.32, 20043.67), new VSC(33, 5.41, 6283.08), new VSC(28, 0.05, 9492.15), new VSC(27, 3.89, 1221.85), new VSC(27, 5.11, 2700.72) }; - - public static VSC[] g_L2MarsCoefficients = { new VSC(58016, 2.04979, 3340.61243), new VSC(54188, 0, 0), new VSC(13908, 2.45742, 6681.22485), new VSC(2465, 2.8000, 10021.8373), new VSC(398, 3.141, 13362.450), new VSC(222, 3.194, 3.523), new VSC(121, 0.543, 155.420), new VSC(62, 3.49, 16703.06), new VSC(54, 3.54, 3344.14), new VSC(34, 6.00, 2281.23), new VSC(32, 4.14, 191.45), new VSC(30, 2.00, 796.30), new VSC(23, 4.33, 242.73), new VSC(22, 3.45, 398.15), new VSC(20, 5.42, 553.57), new VSC(16, 0.66, 0.98), new VSC(16, 6.11, 2146.17), new VSC(16, 1.22, 1748.02), new VSC(15, 6.10, 3185.19), new VSC(14, 4.02, 951.72), new VSC(14, 2.62, 1349.87), new VSC(13, 0.60, 1194.45), new VSC(12, 3.86, 6684.75), new VSC(11, 4.72, 2544.31), new VSC(10, 0.25, 382.90), new VSC(9, 0.68, 1059.38), new VSC(9, 3.83, 20043.67), new VSC(9, 3.88, 3738.76), new VSC(8, 5.46, 1751.54), new VSC(7, 2.58, 3149.16), new VSC(7, 2.38, 4136.91), new VSC(6, 5.48, 1592.60), new VSC(6, 2.34, 3097.88) }; - - public static VSC[] g_L3MarsCoefficients = { new VSC(1482, 0.4443, 3340.6124), new VSC(662, 0.885, 6681.225), new VSC(188, 1.288, 10021.837), new VSC(41, 1.65, 13362.45), new VSC(26, 0, 0), new VSC(23, 2.05, 155.42), new VSC(10, 1.58, 3.52), new VSC(8, 2.00, 16703.06), new VSC(5, 2.82, 242.73), new VSC(4, 2.02, 3344.14), new VSC(3, 4.59, 3185.19), new VSC(3, 0.65, 553.57) }; - - public static VSC[] g_L4MarsCoefficients = { new VSC(114, 3.1416, 0), new VSC(29, 5.64, 6681.22), new VSC(24, 5.14, 3340.61), new VSC(11, 6.03, 10021.84), new VSC(3, 0.13, 13362.45), new VSC(3, 3.56, 155.42), new VSC(1, 0.49, 16703.06), new VSC(1, 1.32, 242.73) }; - - public static VSC[] g_L5MarsCoefficients = { new VSC(1, 3.14, 0), new VSC(1, 4.04, 6681.22) }; - - - public static VSC[] g_B0MarsCoefficients = { new VSC(3197135, 3.7683204, 3340.6124267), new VSC(298033, 4.106170, 6681.224853), new VSC(289105, 0, 0), new VSC(31366, 4.44651, 10021.83728), new VSC(3484, 4.7881, 13362.4497), new VSC(443, 5.026, 3344.136), new VSC(443, 5.652, 3337.089), new VSC(399, 5.131, 16703.062), new VSC(293, 3.793, 2281.230), new VSC(182, 6.136, 6151.534), new VSC(163, 4.264, 529.691), new VSC(160, 2.232, 1059.382), new VSC(149, 2.165, 5621.843), new VSC(143, 1.182, 3340.595), new VSC(143, 3.213, 3340.630), new VSC(139, 2.418, 8962.455) }; - - public static VSC[] g_B1MarsCoefficients = { new VSC(350069, 5.368478, 3340.612427), new VSC(14116, 3.14159, 0), new VSC(9671, 5.4788, 6681.2249), new VSC(1472, 3.2021, 10021.8373), new VSC(426, 3.408, 13362.450), new VSC(102, 0.776, 3337.089), new VSC(79, 3.72, 16703.06), new VSC(33, 3.46, 5621.84), new VSC(26, 2.48, 2281.23) }; - - public static VSC[] g_B2MarsCoefficients = { new VSC(16727, 0.60221, 3340.61243), new VSC(4987, 4.1416, 0), new VSC(302, 3.559, 6681.225), new VSC(26, 1.90, 13362.45), new VSC(21, 0.92, 10021.84), new VSC(12, 2.24, 3337.09), new VSC(8, 2.25, 16703.06) }; - - public static VSC[] g_B3MarsCoefficients = { new VSC(607, 1.981, 3340.612), new VSC(43, 0, 0), new VSC(14, 1.80, 6681.22), new VSC(3, 3.45, 10021.84) }; - - public static VSC[] g_B4MarsCoefficients = { new VSC(13, 0, 0), new VSC(11, 3.46, 3340.61), new VSC(1, 0.50, 6681.22) }; - - - public static VSC[] g_R0MarsCoefficients = { new VSC(153033488, 0, 0), new VSC(14184953, 3.47971284, 3340.61242670), new VSC(660776, 3.817834, 6681.224853), new VSC(46179, 4.15595, 10021.83728), new VSC(8110, 5.5596, 2810.9215), new VSC(7485, 1.7724, 5621.8429), new VSC(5523, 1.3644, 2281.2305), new VSC(3825, 4.4941, 13362.4497), new VSC(2484, 4.9255, 2942.4634), new VSC(2307, 0.0908, 2544.3144), new VSC(1999, 5.3606, 3337.0893), new VSC(1960, 4.7425, 3344.1355), new VSC(1167, 2.1126, 5092.1520), new VSC(1103, 5.0091, 398.1490), new VSC(992, 5.839, 6151.534), new VSC(899, 4.408, 529.691), new VSC(807, 2.102, 1059.382), new VSC(798, 3.448, 796.298), new VSC(741, 1.499, 2146.165), new VSC(726, 1.245, 8432.764), new VSC(692, 2.134, 8962.455), new VSC(633, 0.894, 3340.595), new VSC(633, 2.924, 3340.630), new VSC(630, 1.287, 1751.540), new VSC(574, 0.829, 2914.014), new VSC(526, 5.383, 3738.761), new VSC(473, 5.199, 3127.313), new VSC(348, 4.832, 16703.062), new VSC(284, 2.907, 3532.061), new VSC(280, 5.257, 6283.076), new VSC(276, 1.218, 6254.627), new VSC(275, 2.908, 1748.016), new VSC(270, 3.764, 5884.927), new VSC(239, 2.037, 1194.447), new VSC(234, 5.105, 5486.778), new VSC(228, 3.255, 6872.673), new VSC(223, 4.199, 3149.164), new VSC(219, 5.583, 191.448), new VSC(208, 5.255, 3340.545), new VSC(208, 4.846, 3340.680), new VSC(186, 5.699, 6677.702), new VSC(183, 5.081, 6684.748), new VSC(179, 4.184, 3333.499), new VSC(176, 5.953, 3870.303), new VSC(164, 3.799, 4136.910) }; - - public static VSC[] g_R1MarsCoefficients = { new VSC(1107433, 2.0325052, 3340.6124267), new VSC(103176, 2.370718, 6681.224853), new VSC(12877, 0, 0), new VSC(10816, 2.70888, 10021.83728), new VSC(1195, 3.0470, 13362.4497), new VSC(439, 2.888, 2281.230), new VSC(396, 3.423, 3344.136), new VSC(183, 1.584, 2544.314), new VSC(136, 3.385, 16703.062), new VSC(128, 6.043, 3337.089), new VSC(128, 0.630, 1059.382), new VSC(127, 1.954, 796.298), new VSC(118, 2.998, 2146.165), new VSC(88, 3.42, 398.15), new VSC(83, 3.86, 3738.76), new VSC(76, 4.45, 6151.53), new VSC(72, 2.76, 529.69), new VSC(67, 2.55, 1751.54), new VSC(66, 4.41, 1748.02), new VSC(58, 0.54, 1194.45), new VSC(54, 0.68, 8962.46), new VSC(51, 3.73, 6684.75), new VSC(49, 5.73, 3340.60), new VSC(49, 1.48, 3340.63), new VSC(48, 2.58, 3149.16), new VSC(48, 2.29, 2914.01), new VSC(39, 2.32, 4136.91) }; - - public static VSC[] g_R2MarsCoefficients = { new VSC(44242, 0.47931, 3340.61243), new VSC(8138, 0.8700, 6681.2249), new VSC(1275, 1.2259, 10021.8373), new VSC(187, 1.573, 13362.450), new VSC(52, 3.14, 0), new VSC(41, 1.97, 3344.14), new VSC(27, 1.92, 16703.06), new VSC(18, 4.43, 2281.23), new VSC(12, 4.53, 3185.19), new VSC(10, 5.39, 1059.38), new VSC(10, 0.42, 796.30) }; - - public static VSC[] g_R3MarsCoefficients = { new VSC(1113, 5.1499, 3340.6124), new VSC(424, 5.613, 6681.225), new VSC(100, 5.997, 10021.837), new VSC(20, 0.08, 13362.45), new VSC(5, 3.14, 0), new VSC(3, 0.43, 16703.06) }; - - public static VSC[] g_R4MarsCoefficients = { new VSC(20, 3.58, 3340.61), new VSC(16, 4.05, 6681.22), new VSC(6, 4.46, 10021.84), new VSC(2, 4.84, 13362.45) }; -} -// -//Module : AAMARS.CPP -//Purpose: Implementation for the algorithms which obtain the heliocentric position of Uranus -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////// Includes ///////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAMars -{ -//Static methods - - ///////////////////////////// Implementation ////////////////////////////////// - - public static double EclipticLongitude(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho *rho; - double rhocubed = rhosquared *rho; - double rho4 = rhocubed *rho; - double rho5 = rho4 *rho; - - //Calculate L0 - int nL0Coefficients = GFX.g_L0MarsCoefficients.Length; - double L0 = 0; - int i; - for (i =0; i 0.000001); - S = NextS; - } - - return S; - } - public static CAAParabolicObjectDetails Calculate(double JD, CAAParabolicObjectElements elements) - { - double Epsilon = CAANutation.MeanObliquityOfEcliptic(elements.JDEquinox); - - double JD0 = JD; - - //What will be the return value - CAAParabolicObjectDetails details = new CAAParabolicObjectDetails(); - - Epsilon = CT.D2R(Epsilon); - double omega = CT.D2R(elements.omega); - double w = CT.D2R(elements.w); - double i = CT.D2R(elements.i); - - double sinEpsilon = Math.Sin(Epsilon); - double cosEpsilon = Math.Cos(Epsilon); - double sinOmega = Math.Sin(omega); - double cosOmega = Math.Cos(omega); - double cosi = Math.Cos(i); - double sini = Math.Sin(i); - - double F = cosOmega; - double G = sinOmega * cosEpsilon; - double H = sinOmega * sinEpsilon; - double P = -sinOmega * cosi; - double Q = cosOmega *cosi *cosEpsilon - sini *sinEpsilon; - double R = cosOmega *cosi *sinEpsilon + sini *cosEpsilon; - double a = Math.Sqrt(F *F + P *P); - double b = Math.Sqrt(G *G + Q *Q); - double c = Math.Sqrt(H *H + R *R); - double A = Math.Atan2(F, P); - double B = Math.Atan2(G, Q); - double C = Math.Atan2(H, R); - - C3D SunCoord = CAASun.EquatorialRectangularCoordinatesAnyEquinox(JD, elements.JDEquinox); - - for (int j =0; j<2; j++) - { - double W = 0.03649116245/(elements.q * Math.Sqrt(elements.q)) * (JD0 - elements.T); - double s = CalculateBarkers(W); - double v = 2 *Math.Atan(s); - double r = elements.q * (1 + s *s); - double x = r * a * Math.Sin(A + w + v); - double y = r * b * Math.Sin(B + w + v); - double z = r * c * Math.Sin(C + w + v); - - if (j == 0) - { - details.HeliocentricRectangularEquatorial.X = x; - details.HeliocentricRectangularEquatorial.Y = y; - details.HeliocentricRectangularEquatorial.Z = z; - - //Calculate the heliocentric ecliptic coordinates also - double u = omega + v; - double cosu = Math.Cos(u); - double sinu = Math.Sin(u); - - details.HeliocentricRectangularEcliptical.X = r * (cosOmega *cosu - sinOmega *sinu *cosi); - details.HeliocentricRectangularEcliptical.Y = r * (sinOmega *cosu + cosOmega *sinu *cosi); - details.HeliocentricRectangularEcliptical.Z = r *sini *sinu; - - details.HeliocentricEclipticLongitude = Math.Atan2(y, x); - details.HeliocentricEclipticLongitude = CT.M24(CT.R2D(details.HeliocentricEclipticLongitude) / 15); - details.HeliocentricEclipticLatitude = Math.Asin(z / r); - details.HeliocentricEclipticLatitude = CT.R2D(details.HeliocentricEclipticLatitude); - } - - double psi = SunCoord.X + x; - double nu = SunCoord.Y + y; - double sigma = SunCoord.Z + z; - - double Alpha = Math.Atan2(nu, psi); - Alpha = CT.R2D(Alpha); - double Delta = Math.Atan2(sigma, Math.Sqrt(psi *psi + nu *nu)); - Delta = CT.R2D(Delta); - double Distance = Math.Sqrt(psi *psi + nu *nu + sigma *sigma); - - if (j == 0) - { - details.TrueGeocentricRA = CT.M24(Alpha / 15); - details.TrueGeocentricDeclination = Delta; - details.TrueGeocentricDistance = Distance; - details.TrueGeocentricLightTime = ELL.DistanceToLightTime(Distance); - } - else - { - details.AstrometricGeocenticRA = CT.M24(Alpha / 15); - details.AstrometricGeocentricDeclination = Delta; - details.AstrometricGeocentricDistance = Distance; - details.AstrometricGeocentricLightTime = ELL.DistanceToLightTime(Distance); - - double RES = Math.Sqrt(SunCoord.X *SunCoord.X + SunCoord.Y *SunCoord.Y + SunCoord.Z *SunCoord.Z); - - details.Elongation = CT.R2D(Math.Acos((RES *RES + Distance *Distance - r *r) / (2 * RES * Distance))); - details.PhaseAngle = CT.R2D(Math.Acos((r *r + Distance *Distance - RES *RES) / (2 * r * Distance))); - } - - if (j == 0) //Prepare for the next loop around - JD0 = JD - details.TrueGeocentricLightTime; - } - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAParallactic.cs b/engine/csharp_ref/AstroCalc/AAParallactic.cs deleted file mode 100644 index b41f612f..00000000 --- a/engine/csharp_ref/AstroCalc/AAParallactic.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -// -//Module : AAPARALLACTIC.CPP -//Purpose: Implementation for the algorithms which calculate various celestial globe angles -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -////////////////////// Includes /////////////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAParallactic -{ -//Static methods - - ////////////////////// Implementation ///////////////////////////////////////// - - public static double ParallacticAngle(double HourAngle, double Latitude, double delta) - { - HourAngle = CT.H2R(HourAngle); - Latitude = CT.D2R(Latitude); - delta = CT.D2R(delta); - - return CT.R2D(Math.Atan2(Math.Sin(HourAngle), Math.Tan(Latitude)*Math.Cos(delta) - Math.Sin(delta)*Math.Cos(HourAngle))); - } - public static double EclipticLongitudeOnHorizon(double LocalSiderealTime, double ObliquityOfEcliptic, double Latitude) - { - LocalSiderealTime = CT.H2R(LocalSiderealTime); - Latitude = CT.D2R(Latitude); - ObliquityOfEcliptic = CT.D2R(ObliquityOfEcliptic); - - double @value = CT.R2D(Math.Atan2(-Math.Cos(LocalSiderealTime), Math.Sin(ObliquityOfEcliptic)*Math.Tan(Latitude) + Math.Cos(ObliquityOfEcliptic)*Math.Sin(LocalSiderealTime))); - return CT.M360(@value); - } - public static double AngleBetweenEclipticAndHorizon(double LocalSiderealTime, double ObliquityOfEcliptic, double Latitude) - { - LocalSiderealTime = CT.H2R(LocalSiderealTime); - Latitude = CT.D2R(Latitude); - ObliquityOfEcliptic = CT.D2R(ObliquityOfEcliptic); - - double @value = CT.R2D(Math.Acos(Math.Cos(ObliquityOfEcliptic)*Math.Sin(Latitude) - Math.Sin(ObliquityOfEcliptic)*Math.Cos(Latitude)*Math.Sin(LocalSiderealTime))); - return CT.M360(@value); - } - public static double AngleBetweenNorthCelestialPoleAndNorthPoleOfEcliptic(double Lambda, double Beta, double ObliquityOfEcliptic) - { - Lambda = CT.D2R(Lambda); - Beta = CT.D2R(Beta); - ObliquityOfEcliptic = CT.D2R(ObliquityOfEcliptic); - - double @value = CT.R2D(Math.Atan2(Math.Cos(Lambda)*Math.Tan(ObliquityOfEcliptic), Math.Sin(Beta)*Math.Sin(Lambda)*Math.Tan(ObliquityOfEcliptic) - Math.Cos(Beta))); - return CT.M360(@value); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAParallax.cs b/engine/csharp_ref/AstroCalc/AAParallax.cs deleted file mode 100644 index dc68a34f..00000000 --- a/engine/csharp_ref/AstroCalc/AAParallax.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -public static partial class GFX -{ - - - - //////////////////////// Macros / Defines /////////////////////////////////////////////// - - public static double g_AAParallax_C1 = Math.Sin(CT.D2R(CT.DMS2D(0, 0, 8.794))); -} -// -//Module : AAPARALLAX.CPP -//Purpose: Implementation for the algorithms which convert a geocentric set of coordinates to their topocentric equivalent -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes ////////////////////////////////// - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAATopocentricEclipticDetails -{ -//Constructors / Destructors - public CAATopocentricEclipticDetails() - { - Lambda = 0; - Beta = 0; - Semidiameter = 0; - } - -//Member variables - public double Lambda; - public double Beta; - public double Semidiameter; -} - -public class CAAParallax -{ -//Conversion functions - public static COR Equatorial2TopocentricDelta(double Alpha, double Delta, double Distance, double Longitude, double Latitude, double Height, double JD) - { - double RhoSinThetaPrime = CAAGlobe.RhoSinThetaPrime(Latitude, Height); - double RhoCosThetaPrime = CAAGlobe.RhoCosThetaPrime(Latitude, Height); - - //Calculate the Sidereal time - double theta = CAASidereal.ApparentGreenwichSiderealTime(JD); - - //Convert to radians - Delta = CT.D2R(Delta); - double cosDelta = Math.Cos(Delta); - - //Calculate the Parallax - double pi = Math.Asin(GFX.g_AAParallax_C1 / Distance); - - //Calculate the hour angle - double H = CT.H2R(theta - Longitude/15 - Alpha); - double cosH = Math.Cos(H); - double sinH = Math.Sin(H); - - COR DeltaTopocentric = new COR(); - DeltaTopocentric.X = CT.R2H(-pi *RhoCosThetaPrime *sinH/cosDelta); - DeltaTopocentric.Y = CT.R2D(-pi*(RhoSinThetaPrime *cosDelta - RhoCosThetaPrime *cosH *Math.Sin(Delta))); - return DeltaTopocentric; - } - public static COR Equatorial2Topocentric(double Alpha, double Delta, double Distance, double Longitude, double Latitude, double Height, double JD) - { - double RhoSinThetaPrime = CAAGlobe.RhoSinThetaPrime(Latitude, Height); - double RhoCosThetaPrime = CAAGlobe.RhoCosThetaPrime(Latitude, Height); - - //Calculate the Sidereal time - double theta = CAASidereal.ApparentGreenwichSiderealTime(JD); - - //Convert to radians - Delta = CT.D2R(Delta); - double cosDelta = Math.Cos(Delta); - - //Calculate the Parallax - double pi = Math.Asin(GFX.g_AAParallax_C1 / Distance); - double sinpi = Math.Sin(pi); - - //Calculate the hour angle - double H = CT.H2R(theta - Longitude/15 - Alpha); - double cosH = Math.Cos(H); - double sinH = Math.Sin(H); - - //Calculate the adjustment in right ascension - double DeltaAlpha = Math.Atan2(-RhoCosThetaPrime *sinpi *sinH, cosDelta - RhoCosThetaPrime *sinpi *cosH); - - COR Topocentric = new COR(); - Topocentric.X = CT.M24(Alpha + CT.R2H(DeltaAlpha)); - Topocentric.Y = CT.R2D(Math.Atan2((Math.Sin(Delta) - RhoSinThetaPrime *sinpi) * Math.Cos(DeltaAlpha), cosDelta - RhoCosThetaPrime *sinpi *cosH)); - - return Topocentric; - } - public static CAATopocentricEclipticDetails Ecliptic2Topocentric(double Lambda, double Beta, double Semidiameter, double Distance, double Epsilon, double Longitude, double Latitude, double Height, double JD) - { - double S = CAAGlobe.RhoSinThetaPrime(Latitude, Height); - double C = CAAGlobe.RhoCosThetaPrime(Latitude, Height); - - //Convert to radians - Lambda = CT.D2R(Lambda); - Beta = CT.D2R(Beta); - Epsilon = CT.D2R(Epsilon); - Longitude = CT.D2R(Longitude); - Latitude = CT.D2R(Latitude); - Semidiameter = CT.D2R(Semidiameter); - double sine = Math.Sin(Epsilon); - double cose = Math.Cos(Epsilon); - double cosBeta = Math.Cos(Beta); - double sinBeta = Math.Sin(Beta); - - //Calculate the Sidereal time - double theta = CAASidereal.ApparentGreenwichSiderealTime(JD); - theta = CT.H2R(theta); - double sintheta = Math.Sin(theta); - - //Calculate the Parallax - double pi = Math.Asin(GFX.g_AAParallax_C1 / Distance); - double sinpi = Math.Sin(pi); - - double N = Math.Cos(Lambda)*cosBeta - C *sinpi *Math.Cos(theta); - - CAATopocentricEclipticDetails Topocentric = new CAATopocentricEclipticDetails(); - Topocentric.Lambda = Math.Atan2(Math.Sin(Lambda)*cosBeta - sinpi*(S *sine + C *cose *sintheta), N); - double cosTopocentricLambda = Math.Cos(Topocentric.Lambda); - Topocentric.Beta = Math.Atan(cosTopocentricLambda*(sinBeta - sinpi*(S *cose - C *sine *sintheta)) / N); - Topocentric.Semidiameter = Math.Asin(cosTopocentricLambda *Math.Cos(Topocentric.Beta)*Math.Sin(Semidiameter) / N); - - //Convert back to degrees - Topocentric.Semidiameter = CT.R2D(Topocentric.Semidiameter); - Topocentric.Lambda = CT.M360(CT.R2D(Topocentric.Lambda)); - Topocentric.Beta = CT.R2D(Topocentric.Beta); - - return Topocentric; - } - - public static double ParallaxToDistance(double Parallax) - { - return GFX.g_AAParallax_C1 / Math.Sin(CT.D2R(Parallax)); - } - - //////////////////////// Implementation ///////////////////////////////////////////////// - - public static double DistanceToParallax(double Distance) - { - double pi = Math.Asin(GFX.g_AAParallax_C1 / Distance); - return CT.R2D(pi); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPhysicalJupiter.cs b/engine/csharp_ref/AstroCalc/AAPhysicalJupiter.cs deleted file mode 100644 index 0a979eb6..00000000 --- a/engine/csharp_ref/AstroCalc/AAPhysicalJupiter.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -// -//Module : AAPHYSICALJUPITER.CPP -//Purpose: Implementation for the algorithms which obtain the physical parameters of the Jupiter -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAPhysicalJupiterDetails -{ -//Constructors / Destructors - public CAAPhysicalJupiterDetails() - { - DE = 0; - DS = 0; - Geometricw1 = 0; - Geometricw2 = 0; - Apparentw1 = 0; - Apparentw2 = 0; - P = 0; - } - -//Member variables - public double DE; - public double DS; - public double Geometricw1; - public double Geometricw2; - public double Apparentw1; - public double Apparentw2; - public double P; -} - -public class CAAPhysicalJupiter -{ -//Static methods - - //////////////////////////////// Implementation /////////////////////////////// - - public static CAAPhysicalJupiterDetails Calculate(double JD) - { - //What will be the return value - CAAPhysicalJupiterDetails details = new CAAPhysicalJupiterDetails(); - - //Step 1 - double d = JD - 2433282.5; - double T1 = d/36525; - double alpha0 = 268.00 + 0.1061 *T1; - double alpha0rad = CT.D2R(alpha0); - double delta0 = 64.50 - 0.0164 *T1; - double delta0rad = CT.D2R(delta0); - - //Step 2 - double W1 = CT.M360(17.710 + 877.90003539 *d); - double W2 = CT.M360(16.838 + 870.27003539 *d); - - //Step 3 - double l0 = CAAEarth.EclipticLongitude(JD); - double l0rad = CT.D2R(l0); - double b0 = CAAEarth.EclipticLatitude(JD); - double b0rad = CT.D2R(b0); - double R = CAAEarth.RadiusVector(JD); - - //Step 4 - double l = CAAJupiter.EclipticLongitude(JD); - double lrad = CT.D2R(l); - double b = CAAJupiter.EclipticLatitude(JD); - double brad = CT.D2R(b); - double r = CAAJupiter.RadiusVector(JD); - - //Step 5 - double x = r *Math.Cos(brad)*Math.Cos(lrad) - R *Math.Cos(l0rad); - double y = r *Math.Cos(brad)*Math.Sin(lrad) - R *Math.Sin(l0rad); - double z = r *Math.Sin(brad) - R *Math.Sin(b0rad); - double DELTA = Math.Sqrt(x *x + y *y + z *z); - - //Step 6 - l -= 0.012990 *DELTA/(r *r); - lrad = CT.D2R(l); - - //Step 7 - x = r *Math.Cos(brad)*Math.Cos(lrad) - R *Math.Cos(l0rad); - y = r *Math.Cos(brad)*Math.Sin(lrad) - R *Math.Sin(l0rad); - z = r *Math.Sin(brad) - R *Math.Sin(b0rad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - - //Step 8 - double e0 = CAANutation.MeanObliquityOfEcliptic(JD); - double e0rad = CT.D2R(e0); - - //Step 9 - double alphas = Math.Atan2(Math.Cos(e0rad)*Math.Sin(lrad) - Math.Sin(e0rad)*Math.Tan(brad), Math.Cos(lrad)); - double deltas = Math.Asin(Math.Cos(e0rad)*Math.Sin(brad) + Math.Sin(e0rad)*Math.Cos(brad)*Math.Sin(lrad)); - - //Step 10 - details.DS = CT.R2D(Math.Asin(-Math.Sin(delta0rad)*Math.Sin(deltas) - Math.Cos(delta0rad)*Math.Cos(deltas)*Math.Cos(alpha0rad - alphas))); - - //Step 11 - double u = y *Math.Cos(e0rad) - z *Math.Sin(e0rad); - double v = y *Math.Sin(e0rad) + z *Math.Cos(e0rad); - double alpharad = Math.Atan2(u, x); - double alpha = CT.R2D(alpharad); - double deltarad = Math.Atan2(v, Math.Sqrt(x *x + u *u)); - double delta = CT.R2D(deltarad); - double xi = Math.Atan2(Math.Sin(delta0rad)*Math.Cos(deltarad)*Math.Cos(alpha0rad - alpharad) - Math.Sin(deltarad)*Math.Cos(delta0rad), Math.Cos(deltarad)*Math.Sin(alpha0rad - alpharad)); - - //Step 12 - details.DE = CT.R2D(Math.Asin(-Math.Sin(delta0rad)*Math.Sin(deltarad) - Math.Cos(delta0rad)*Math.Cos(deltarad)*Math.Cos(alpha0rad - alpharad))); - - //Step 13 - details.Geometricw1 = CT.M360(W1 - CT.R2D(xi) - 5.07033 *DELTA); - details.Geometricw2 = CT.M360(W2 - CT.R2D(xi) - 5.02626 *DELTA); - - //Step 14 - double C = 57.2958 * (2 *r *DELTA + R *R - r *r - DELTA *DELTA)/(4 *r *DELTA); - if (Math.Sin(lrad - l0rad) > 0) - { - details.Apparentw1 = CT.M360(details.Geometricw1 + C); - details.Apparentw2 = CT.M360(details.Geometricw2 + C); - } - else - { - details.Apparentw1 = CT.M360(details.Geometricw1 - C); - details.Apparentw2 = CT.M360(details.Geometricw2 - C); - } - - //Step 15 - double NutationInLongitude = CAANutation.NutationInLongitude(JD); - double NutationInObliquity = CAANutation.NutationInObliquity(JD); - e0 += NutationInObliquity/3600; - e0rad = CT.D2R(e0); - - //Step 16 - alpha += 0.005693*(Math.Cos(alpharad)*Math.Cos(l0rad)*Math.Cos(e0rad) + Math.Sin(alpharad)*Math.Sin(l0rad))/Math.Cos(deltarad); - alpha = CT.M360(alpha); - alpharad = CT.D2R(alpha); - delta += 0.005693*(Math.Cos(l0rad)*Math.Cos(e0rad)*(Math.Tan(e0rad)*Math.Cos(deltarad) - Math.Sin(alpharad)*Math.Sin(deltarad)) + Math.Cos(alpharad)*Math.Sin(deltarad)*Math.Sin(l0rad)); - deltarad = CT.D2R(delta); - - //Step 17 - double NutationRA = CAANutation.NutationInRightAscension(alpha/15, delta, e0, NutationInLongitude, NutationInObliquity); - double alphadash = alpha + NutationRA/3600; - double alphadashrad = CT.D2R(alphadash); - double NutationDec = CAANutation.NutationInDeclination(alpha/15, delta, e0, NutationInLongitude, NutationInObliquity); - double deltadash = delta + NutationDec/3600; - double deltadashrad = CT.D2R(deltadash); - NutationRA = CAANutation.NutationInRightAscension(alpha0/15, delta0, e0, NutationInLongitude, NutationInObliquity); - double alpha0dash = alpha0 + NutationRA/3600; - double alpha0dashrad = CT.D2R(alpha0dash); - NutationDec = CAANutation.NutationInDeclination(alpha0/15, delta0, e0, NutationInLongitude, NutationInObliquity); - double delta0dash = delta0 + NutationDec/3600; - double delta0dashrad = CT.D2R(delta0dash); - - //Step 18 - details.P = CT.M360(CT.R2D(Math.Atan2(Math.Cos(delta0dashrad)*Math.Sin(alpha0dashrad - alphadashrad), Math.Sin(delta0dashrad)*Math.Cos(deltadashrad) - Math.Cos(delta0dashrad)*Math.Sin(deltadashrad)*Math.Cos(alpha0dashrad - alphadashrad)))); - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPhysicalMars.cs b/engine/csharp_ref/AstroCalc/AAPhysicalMars.cs deleted file mode 100644 index afcb3263..00000000 --- a/engine/csharp_ref/AstroCalc/AAPhysicalMars.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -// -//Module : AAPHYSICALMARS.CPP -//Purpose: Implementation for the algorithms which obtain the physical parameters of Mars -//Created: PJN / 04-01-2004 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAPhysicalMarsDetails -{ - public CAAPhysicalMarsDetails() - { - DE = 0; - DS = 0; - w = 0; - P = 0; - X = 0; - k = 0; - q = 0; - d = 0; - } - -//Member variables - public double DE; - public double DS; - public double w; - public double P; - public double X; - public double k; - public double q; - public double d; -} - -public class CAAPhysicalMars -{ -//Static methods - - //////////////////////////////// Implementation /////////////////////////////// - - public static CAAPhysicalMarsDetails Calculate(double JD) - { - //What will be the return value - CAAPhysicalMarsDetails details = new CAAPhysicalMarsDetails(); - - //Step 1 - double T = (JD - 2451545) / 36525; - double Lambda0 = 352.9065 + 1.17330 *T; - double Lambda0rad = CT.D2R(Lambda0); - double Beta0 = 63.2818 - 0.00394 *T; - double Beta0rad = CT.D2R(Beta0); - - //Step 2 - double l0 = CAAEarth.EclipticLongitude(JD); - double l0rad = CT.D2R(l0); - double b0 = CAAEarth.EclipticLatitude(JD); - double b0rad = CT.D2R(b0); - double R = CAAEarth.RadiusVector(JD); - - double PreviousLightTravelTime = 0; - double LightTravelTime = 0; - double x = 0; - double y = 0; - double z = 0; - bool bIterate = true; - double DELTA = 0; - double l = 0; - double lrad = 0; - double b = 0; - double brad = 0; - double r = 0; - while (bIterate) - { - double JD2 = JD - LightTravelTime; - - //Step 3 - l = CAAMars.EclipticLongitude(JD2); - lrad = CT.D2R(l); - b = CAAMars.EclipticLatitude(JD2); - brad = CT.D2R(b); - r = CAAMars.RadiusVector(JD2); - - //Step 4 - x = r *Math.Cos(brad)*Math.Cos(lrad) - R *Math.Cos(l0rad); - y = r *Math.Cos(brad)*Math.Sin(lrad) - R *Math.Sin(l0rad); - z = r *Math.Sin(brad) - R *Math.Sin(b0rad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - LightTravelTime = ELL.DistanceToLightTime(DELTA); - - //Prepare for the next loop around - bIterate = (Math.Abs(LightTravelTime - PreviousLightTravelTime) > 2E-6); //2E-6 correponds to 0.17 of a second - if (bIterate) - PreviousLightTravelTime = LightTravelTime; - } - - //Step 5 - double lambdarad = Math.Atan2(y, x); - double lambda = CT.R2D(lambdarad); - double betarad = Math.Atan2(z, Math.Sqrt(x *x + y *y)); - double beta = CT.R2D(betarad); - - //Step 6 - details.DE = CT.R2D(Math.Asin(-Math.Sin(Beta0rad)*Math.Sin(betarad) - Math.Cos(Beta0rad)*Math.Cos(betarad)*Math.Cos(Lambda0rad - lambdarad))); - - //Step 7 - double N = 49.5581 + 0.7721 *T; - double Nrad = CT.D2R(N); - - double ldash = l - 0.00697/r; - double ldashrad = CT.D2R(ldash); - double bdash = b - 0.000225*(Math.Cos(lrad - Nrad)/r); - double bdashrad = CT.D2R(bdash); - - //Step 8 - details.DS = CT.R2D(Math.Asin(-Math.Sin(Beta0rad)*Math.Sin(bdashrad) - Math.Cos(Beta0rad)*Math.Cos(bdashrad)*Math.Cos(Lambda0rad - ldashrad))); - - //Step 9 - double W = CT.M360(11.504 + 350.89200025*(JD - LightTravelTime - 2433282.5)); - - //Step 10 - double e0 = CAANutation.MeanObliquityOfEcliptic(JD); - double e0rad = CT.D2R(e0); - COR PoleEquatorial = CT.Ec2Eq(Lambda0, Beta0, e0); - double alpha0rad = CT.H2R(PoleEquatorial.X); - double delta0rad = CT.D2R(PoleEquatorial.Y); - - //Step 11 - double u = y *Math.Cos(e0rad) - z *Math.Sin(e0rad); - double v = y *Math.Sin(e0rad) + z *Math.Cos(e0rad); - double alpharad = Math.Atan2(u, x); - double alpha = CT.R2H(alpharad); - double deltarad = Math.Atan2(v, Math.Sqrt(x *x + u *u)); - double delta = CT.R2D(deltarad); - double xi = Math.Atan2(Math.Sin(delta0rad)*Math.Cos(deltarad)*Math.Cos(alpha0rad - alpharad) - Math.Sin(deltarad)*Math.Cos(delta0rad), Math.Cos(deltarad)*Math.Sin(alpha0rad - alpharad)); - - //Step 12 - details.w = CT.M360(W - CT.R2D(xi)); - - //Step 13 - double NutationInLongitude = CAANutation.NutationInLongitude(JD); - double NutationInObliquity = CAANutation.NutationInObliquity(JD); - - //Step 14 - lambda += 0.005693 *Math.Cos(l0rad - lambdarad)/Math.Cos(betarad); - beta += 0.005693 *Math.Sin(l0rad - lambdarad)*Math.Sin(betarad); - - //Step 15 - Lambda0 += NutationInLongitude/3600; - Lambda0rad = CT.D2R(Lambda0); - lambda += NutationInLongitude/3600; - lambdarad = CT.D2R(lambda); - e0 += NutationInObliquity/3600; - e0rad = CT.D2R(e0rad); - - //Step 16 - COR ApparentPoleEquatorial = CT.Ec2Eq(Lambda0, Beta0, e0); - double alpha0dash = CT.H2R(ApparentPoleEquatorial.X); - double delta0dash = CT.D2R(ApparentPoleEquatorial.Y); - COR ApparentMars = CT.Ec2Eq(lambda, beta, e0); - double alphadash = CT.H2R(ApparentMars.X); - double deltadash = CT.D2R(ApparentMars.Y); - - //Step 17 - details.P = CT.M360(CT.R2D(Math.Atan2(Math.Cos(delta0dash)*Math.Sin(alpha0dash - alphadash), Math.Sin(delta0dash)*Math.Cos(deltadash) - Math.Cos(delta0dash)*Math.Sin(deltadash)*Math.Cos(alpha0dash - alphadash)))); - - //Step 18 - double SunLambda = CAASun.GeometricEclipticLongitude(JD); - double SunBeta = CAASun.GeometricEclipticLatitude(JD); - COR SunEquatorial = CT.Ec2Eq(SunLambda, SunBeta, e0); - details.X = MIFR.PositionAngle(SunEquatorial.X, SunEquatorial.Y, alpha, delta); - - //Step 19 - details.d = 9.36 / DELTA; - details.k = IFR.IlluminatedFraction2(r, R, DELTA); - details.q = (1 - details.k)*details.d; - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPhysicalMoon.cs b/engine/csharp_ref/AstroCalc/AAPhysicalMoon.cs deleted file mode 100644 index b6c06d17..00000000 --- a/engine/csharp_ref/AstroCalc/AAPhysicalMoon.cs +++ /dev/null @@ -1,274 +0,0 @@ -using System; -// -//Module : AAPHYSICALMOON.CPP -//Purpose: Implementation for the algorithms which obtain the physical parameters of the Moon -//Created: PJN / 17-01-2004 -//History: PJN / 19-02-2004 1. The optical libration in longitude is now returned in the range -180 - 180 degrees -// -//Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - - -/////////////////////// Includes ////////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAPhysicalMoonDetails -{ -//Constructors / Destructors - public CAAPhysicalMoonDetails() - { - ldash = 0; - bdash = 0; - ldash2 = 0; - bdash2 = 0; - l = 0; - b = 0; - P = 0; - } - -//Member variables - public double ldash; - public double bdash; - public double ldash2; - public double bdash2; - public double l; - public double b; - public double P; -} - -public class CAASelenographicMoonDetails -{ -//Constructors / Destructors - public CAASelenographicMoonDetails() - { - l0 = 0; - b0 = 0; - c0 = 0; - } - -//Member variables - public double l0; - public double b0; - public double c0; -} - -public class CAAPhysicalMoon -{ -//Static methods - public static CAAPhysicalMoonDetails CalculateGeocentric(double JD) - { - double Lambda=0; - double Beta=0; - double epsilon=0; - CAA2DCoordinate Equatorial = new CAA2DCoordinate(); - return CalculateHelper(JD, ref Lambda, ref Beta, ref epsilon, ref Equatorial); - } - public static CAAPhysicalMoonDetails CalculateTopocentric(double JD, double Longitude, double Latitude) - { - //First convert to radians - Longitude = CAACoordinateTransformation.DegreesToRadians(Longitude); - Latitude = CAACoordinateTransformation.DegreesToRadians(Latitude); - - double Lambda=0; - double Beta=0; - double epsilon=0; - CAA2DCoordinate Equatorial = new CAA2DCoordinate(); - CAAPhysicalMoonDetails details = CalculateHelper(JD, ref Lambda, ref Beta, ref epsilon, ref Equatorial); - - double R = CAAMoon.RadiusVector(JD); - double pi = CAAMoon.RadiusVectorToHorizontalParallax(R); - double Alpha = CAACoordinateTransformation.HoursToRadians(Equatorial.X); - double Delta = CAACoordinateTransformation.DegreesToRadians(Equatorial.Y); - - double AST = CAASidereal.ApparentGreenwichSiderealTime(JD); - double H = CAACoordinateTransformation.HoursToRadians(AST) - Longitude - Alpha; - - double Q = Math.Atan2(Math.Cos(Latitude)*Math.Sin(H), Math.Cos(Delta)*Math.Sin(Latitude) - Math.Sin(Delta)*Math.Cos(Latitude)*Math.Cos(H)); - double Z = Math.Acos(Math.Sin(Delta)*Math.Sin(Latitude) + Math.Cos(Delta)*Math.Cos(Latitude)*Math.Cos(H)); - double pidash = pi*(Math.Sin(Z) + 0.0084 *Math.Sin(2 *Z)); - - double Prad = CAACoordinateTransformation.DegreesToRadians(details.P); - - double DeltaL = -pidash *Math.Sin(Q - Prad)/Math.Cos(CAACoordinateTransformation.DegreesToRadians(details.b)); - details.l += DeltaL; - double DeltaB = pidash *Math.Cos(Q - Prad); - details.b += DeltaB; - details.P += DeltaL *Math.Sin(CAACoordinateTransformation.DegreesToRadians(details.b)) - pidash *Math.Sin(Q)*Math.Tan(Delta); - - return details; - } - public static CAASelenographicMoonDetails CalculateSelenographicPositionOfSun(double JD) - { - double R = CAAEarth.RadiusVector(JD)*149597970; - double Delta = CAAMoon.RadiusVector(JD); - double lambda0 = CAASun.ApparentEclipticLongitude(JD); - double lambda = CAAMoon.EclipticLongitude(JD); - double beta = CAAMoon.EclipticLatitude(JD); - - double lambdah = CAACoordinateTransformation.MapTo0To360Range(lambda0 + 180 + Delta/R *57.296 *Math.Cos(CAACoordinateTransformation.DegreesToRadians(beta))*Math.Sin(CAACoordinateTransformation.DegreesToRadians(lambda0 - lambda))); - double betah = Delta/R *beta; - - //What will be the return value - CAASelenographicMoonDetails details = new CAASelenographicMoonDetails(); - - //Calculate the optical libration - double omega=0; - double DeltaU = 0; - double sigma = 0; - double I = 0; - double rho = 0; - double ldash0 = 0; - double bdash0 = 0; - double ldash20 = 0; - double bdash20 = 0; - double epsilon = 0; - CalculateOpticalLibration(JD, lambdah, betah, ref ldash0, ref bdash0, ref ldash20, ref bdash20, ref epsilon, ref omega, ref DeltaU, ref sigma, ref I, ref rho); - - details.l0 = ldash0 + ldash20; - details.b0 = bdash0 + bdash20; - details.c0 = CAACoordinateTransformation.MapTo0To360Range(450 - details.l0); - return details; - } - public static double AltitudeOfSun(double JD, double Longitude, double Latitude) - { - //Calculate the selenographic details - CAASelenographicMoonDetails selenographicDetails = CalculateSelenographicPositionOfSun(JD); - - //convert to radians - Latitude = CAACoordinateTransformation.DegreesToRadians(Latitude); - Longitude = CAACoordinateTransformation.DegreesToRadians(Longitude); - selenographicDetails.b0 = CAACoordinateTransformation.DegreesToRadians(selenographicDetails.b0); - selenographicDetails.c0 = CAACoordinateTransformation.DegreesToRadians(selenographicDetails.c0); - - return CAACoordinateTransformation.RadiansToDegrees(Math.Asin(Math.Sin(selenographicDetails.b0)*Math.Sin(Latitude) + Math.Cos(selenographicDetails.b0)*Math.Cos(Latitude)*Math.Sin(selenographicDetails.c0 + Longitude))); - } - public static double TimeOfSunrise(double JD, double Longitude, double Latitude) - { - return SunriseSunsetHelper(JD, Longitude, Latitude, true); - } - public static double TimeOfSunset(double JD, double Longitude, double Latitude) - { - return SunriseSunsetHelper(JD, Longitude, Latitude, false); - } - - protected static double SunriseSunsetHelper(double JD, double Longitude, double Latitude, bool bSunrise) - { - double JDResult = JD; - double Latituderad = CAACoordinateTransformation.DegreesToRadians(Latitude); - double h; - do - { - h = AltitudeOfSun(JDResult, Longitude, Latitude); - double DeltaJD = h/(12.19075 *Math.Cos(Latituderad)); - if (bSunrise) - JDResult -= DeltaJD; - else - JDResult += DeltaJD; - } - while (Math.Abs(h) > 0.001); - - return JDResult; - } - protected static CAAPhysicalMoonDetails CalculateHelper(double JD, ref double Lambda, ref double Beta, ref double epsilon, ref CAA2DCoordinate Equatorial) - { - //What will be the return value - CAAPhysicalMoonDetails details = new CAAPhysicalMoonDetails(); - - //Calculate the initial quantities - Lambda = CAAMoon.EclipticLongitude(JD); - Beta = CAAMoon.EclipticLatitude(JD); - - //Calculate the optical libration - double omega=0; - double DeltaU=0; - double sigma=0; - double I=0; - double rho=0; - CalculateOpticalLibration(JD, Lambda, Beta, ref details.ldash, ref details.bdash, ref details.ldash2, ref details.bdash2, ref epsilon, ref omega, ref DeltaU, ref sigma, ref I, ref rho); - double epsilonrad = CAACoordinateTransformation.DegreesToRadians(epsilon); - - //Calculate the total libration - details.l = details.ldash + details.ldash2; - details.b = details.bdash + details.bdash2; - double b = CAACoordinateTransformation.DegreesToRadians(details.b); - - //Calculate the position angle - double V = omega + DeltaU + CAACoordinateTransformation.DegreesToRadians(sigma)/Math.Sin(I); - double I_rho = I + CAACoordinateTransformation.DegreesToRadians(rho); - double X = Math.Sin(I_rho)*Math.Sin(V); - double Y = Math.Sin(I_rho)*Math.Cos(V)*Math.Cos(epsilonrad) - Math.Cos(I_rho)*Math.Sin(epsilonrad); - double w = Math.Atan2(X, Y); - - Equatorial = CAACoordinateTransformation.Ecliptic2Equatorial(Lambda, Beta, epsilon); - double Alpha = CAACoordinateTransformation.HoursToRadians(Equatorial.X); - - details.P = CAACoordinateTransformation.RadiansToDegrees(Math.Asin(Math.Sqrt(X *X + Y *Y)*Math.Cos(Alpha - w)/(Math.Cos(b)))); - - return details; - } - - //////////////////////////////// Implementation /////////////////////////////// - - protected static void CalculateOpticalLibration(double JD, double Lambda, double Beta, ref double ldash, ref double bdash, ref double ldash2, ref double bdash2, ref double epsilon, ref double omega, ref double DeltaU, ref double sigma, ref double I, ref double rho) - { - //Calculate the initial quantities - double Lambdarad = CAACoordinateTransformation.DegreesToRadians(Lambda); - double Betarad = CAACoordinateTransformation.DegreesToRadians(Beta); - I = CAACoordinateTransformation.DegreesToRadians(1.54242); - DeltaU = CAACoordinateTransformation.DegreesToRadians(CAANutation.NutationInLongitude(JD)/3600); - double F = CAACoordinateTransformation.DegreesToRadians(CAAMoon.ArgumentOfLatitude(JD)); - omega = CAACoordinateTransformation.DegreesToRadians(CAAMoon.MeanLongitudeAscendingNode(JD)); - epsilon = CAANutation.MeanObliquityOfEcliptic(JD) + CAANutation.NutationInObliquity(JD)/3600; - - //Calculate the optical librations - double W = Lambdarad - DeltaU/3600 - omega; - double A = Math.Atan2(Math.Sin(W)*Math.Cos(Betarad)*Math.Cos(I) - Math.Sin(Betarad)*Math.Sin(I), Math.Cos(W)*Math.Cos(Betarad)); - ldash = CAACoordinateTransformation.MapTo0To360Range(CAACoordinateTransformation.RadiansToDegrees(A) - CAACoordinateTransformation.RadiansToDegrees(F)); - if (ldash > 180) - ldash -= 360; - bdash = Math.Asin(-Math.Sin(W)*Math.Cos(Betarad)*Math.Sin(I) - Math.Sin(Betarad)*Math.Cos(I)); - - //Calculate the physical librations - double T = (JD - 2451545.0)/36525; - double K1 = 119.75 + 131.849 *T; - K1 = CAACoordinateTransformation.DegreesToRadians(K1); - double K2 = 72.56 + 20.186 *T; - K2 = CAACoordinateTransformation.DegreesToRadians(K2); - - double M = CAAEarth.SunMeanAnomaly(JD); - M = CAACoordinateTransformation.DegreesToRadians(M); - double Mdash = CAAMoon.MeanAnomaly(JD); - Mdash = CAACoordinateTransformation.DegreesToRadians(Mdash); - double D = CAAMoon.MeanElongation(JD); - D = CAACoordinateTransformation.DegreesToRadians(D); - double E = CAAEarth.Eccentricity(JD); - - rho = -0.02752 *Math.Cos(Mdash) + -0.02245 *Math.Sin(F) + 0.00684 *Math.Cos(Mdash - 2 *F) + -0.00293 *Math.Cos(2 *F) + -0.00085 *Math.Cos(2 *F - 2 *D) + -0.00054 *Math.Cos(Mdash - 2 *D) + -0.00020 *Math.Sin(Mdash + F) + -0.00020 *Math.Cos(Mdash + 2 *F) + -0.00020 *Math.Cos(Mdash - F) + 0.00014 *Math.Cos(Mdash + 2 *F - 2 *D); - - sigma = -0.02816 *Math.Sin(Mdash) + 0.02244 *Math.Cos(F) + -0.00682 *Math.Sin(Mdash - 2 *F) + -0.00279 *Math.Sin(2 *F) + -0.00083 *Math.Sin(2 *F - 2 *D) + 0.00069 *Math.Sin(Mdash - 2 *D) + 0.00040 *Math.Cos(Mdash + F) + -0.00025 *Math.Sin(2 *Mdash) + -0.00023 *Math.Sin(Mdash + 2 *F) + 0.00020 *Math.Cos(Mdash - F) + 0.00019 *Math.Sin(Mdash - F) + 0.00013 *Math.Sin(Mdash + 2 *F - 2 *D) + -0.00010 *Math.Cos(Mdash - 3 *F); - - double tau = 0.02520 *E *Math.Sin(M) + 0.00473 *Math.Sin(2 *Mdash - 2 *F) + -0.00467 *Math.Sin(Mdash) + 0.00396 *Math.Sin(K1) + 0.00276 *Math.Sin(2 *Mdash - 2 *D) + 0.00196 *Math.Sin(omega) + -0.00183 *Math.Cos(Mdash - F) + 0.00115 *Math.Sin(Mdash - 2 *D) + -0.00096 *Math.Sin(Mdash - D) + 0.00046 *Math.Sin(2 *F - 2 *D) + -0.00039 *Math.Sin(Mdash - F) + -0.00032 *Math.Sin(Mdash - M - D) + 0.00027 *Math.Sin(2 *Mdash - M - 2 *D) + 0.00023 *Math.Sin(K2) + -0.00014 *Math.Sin(2 *D) + 0.00014 *Math.Cos(2 *Mdash - 2 *F) + -0.00012 *Math.Sin(Mdash - 2 *F) + -0.00012 *Math.Sin(2 *Mdash) + 0.00011 *Math.Sin(2 *Mdash - 2 *M - 2 *D); - - ldash2 = -tau + (rho *Math.Cos(A) + sigma *Math.Sin(A))*Math.Tan(bdash); - bdash = CAACoordinateTransformation.RadiansToDegrees(bdash); - bdash2 = sigma *Math.Cos(A) - rho *Math.Sin(A); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPhysicalSun.cs b/engine/csharp_ref/AstroCalc/AAPhysicalSun.cs deleted file mode 100644 index 3269dff5..00000000 --- a/engine/csharp_ref/AstroCalc/AAPhysicalSun.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -// -//Module : AAPHYSICALSUN.CPP -//Purpose: Implementation for the algorithms which obtain the physical parameters of the Sun -//Created: PJN / 29-12-2003 -//History: PJN / 16-06-2004 1) Fixed a typo in the calculation of SunLongDash in CAAPhysicalSun::Calculate. -// Thanks to Brian Orme for spotting this problem. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - -//////////////////////////// Classes ////////////////////////////////////////// - -public class CAAPhysicalSunDetails -{ -//Constructors / Destructors - public CAAPhysicalSunDetails() - { - P = 0; - B0 = 0; - L0 = 0; - } - -//Member variables - public double P; - public double B0; - public double L0; -} - -public class CAAPhysicalSun -{ -//Static methods - - //////////////////////////////// Implementation /////////////////////////////// - - public static CAAPhysicalSunDetails Calculate(double JD) - { - double theta = CT.M360((JD - 2398220) * 360 / 25.38); - double I = 7.25; - double K = 73.6667 + 1.3958333*(JD - 2396758)/36525; - - //Calculate the apparent longitude of the sun (excluding the effect of nutation) - double L = CAAEarth.EclipticLongitude(JD); - double R = CAAEarth.RadiusVector(JD); - double SunLong = L + 180 - CT.DMS2D(0, 0, 20.4898 / R); - double SunLongDash = SunLong + CT.DMS2D(0, 0, CAANutation.NutationInLongitude(JD)); - - double epsilon = CAANutation.TrueObliquityOfEcliptic(JD); - - //Convert to radians - epsilon = CT.D2R(epsilon); - SunLong = CT.D2R(SunLong); - SunLongDash = CT.D2R(SunLongDash); - K = CT.D2R(K); - I = CT.D2R(I); - theta = CT.D2R(theta); - - double x = Math.Atan(-Math.Cos(SunLong)*Math.Tan(epsilon)); - double y = Math.Atan(-Math.Cos(SunLong - K)*Math.Tan(I)); - - CAAPhysicalSunDetails details = new CAAPhysicalSunDetails(); - - details.P = CT.R2D(x + y); - details.B0 = CT.R2D(Math.Asin(Math.Sin(SunLong - K)*Math.Sin(I))); - - double eta = Math.Atan(Math.Tan(SunLong - K)*Math.Cos(I)); - details.L0 = CT.M360(CT.R2D(eta - theta)); - - return details; - } - public static double TimeOfStartOfRotation(int C) - { - double JED = 2398140.2270 + 27.2752316 *C; - - double M = CT.M360(281.96 + 26.882476 *C); - M = CT.D2R(M); - - JED += (0.1454 *Math.Sin(M) - 0.0085 *Math.Sin(2 *M) - 0.0141 *Math.Cos(2 *M)); - - return JED; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPlanetPerihelionAphelion.cs b/engine/csharp_ref/AstroCalc/AAPlanetPerihelionAphelion.cs deleted file mode 100644 index 15d8512b..00000000 --- a/engine/csharp_ref/AstroCalc/AAPlanetPerihelionAphelion.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System; -// -//Module : AAPLANETPERIHELIONAPHELION.CPP -//Purpose: Implementation for the algorithms which obtain the dates of Perihelion and Aphelion of the planets -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAPlanetPerihelionAphelion -{ -//Static methods - - ///////////////////////////////// Implementation ////////////////////////////// - - public static int MercuryK(double Year) - { - return (int)(4.15201*(Year - 2000.12)); - } - public static double MercuryPerihelion(int k) - { - return 2451590.257 + 87.96934963 *k; - } - public static double MercuryAphelion(int k) - { - double kdash = k + 0.5; - return 2451590.257 + 87.96934963 *kdash; - } - - public static int VenusK(double Year) - { - return (int)(1.62549*(Year - 2000.53)); - } - public static double VenusPerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2451738.233 + 224.7008188 *kdash - 0.0000000327 *ksquared; - } - public static double VenusAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2451738.233 + 224.7008188 *kdash - 0.0000000327 *ksquared; - } - - public static int EarthK(double Year) - { - return (int)(0.99997*(Year - 2000.01)); - } - public static double EarthPerihelion(int k) - { - return EarthPerihelion(k, false); - } -//C++ TO C# CONVERTER NOTE: C# does not allow default values for parameters. Overloaded methods are inserted above. -//ORIGINAL LINE: static double EarthPerihelion(int k, bool bBarycentric = false) - public static double EarthPerihelion(int k, bool bBarycentric) - { - double kdash = k; - double ksquared = kdash * kdash; - double JD = 2451547.507 + 365.2596358 *kdash + 0.0000000156 *ksquared; - - if (!bBarycentric) - { - //Apply the corrections - double A1 = CAACoordinateTransformation.MapTo0To360Range(328.41 + 132.788585 *k); - A1 = CAACoordinateTransformation.DegreesToRadians(A1); - double A2 = CAACoordinateTransformation.MapTo0To360Range(316.13 + 584.903153 *k); - A2 = CAACoordinateTransformation.DegreesToRadians(A2); - double A3 = CAACoordinateTransformation.MapTo0To360Range(346.20 + 450.380738 *k); - A3 = CAACoordinateTransformation.DegreesToRadians(A3); - double A4 = CAACoordinateTransformation.MapTo0To360Range(136.95 + 659.306737 *k); - A4 = CAACoordinateTransformation.DegreesToRadians(A4); - double A5 = CAACoordinateTransformation.MapTo0To360Range(249.52 + 329.653368 *k); - A5 = CAACoordinateTransformation.DegreesToRadians(A5); - - JD += 1.278 *Math.Sin(A1); - JD -= 0.055 *Math.Sin(A2); - JD -= 0.091 *Math.Sin(A3); - JD -= 0.056 *Math.Sin(A4); - JD -= 0.045 *Math.Sin(A5); - } - - return JD; - } - public static double EarthAphelion(int k) - { - return EarthAphelion(k, false); - } -//C++ TO C# CONVERTER NOTE: C# does not allow default values for parameters. Overloaded methods are inserted above. -//ORIGINAL LINE: static double EarthAphelion(int k, bool bBarycentric = false) - public static double EarthAphelion(int k, bool bBarycentric) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - double JD = 2451547.507 + 365.2596358 *kdash + 0.0000000156 *ksquared; - - if (!bBarycentric) - { - //Apply the corrections - double A1 = CAACoordinateTransformation.MapTo0To360Range(328.41 + 132.788585 *k); - A1 = CAACoordinateTransformation.DegreesToRadians(A1); - double A2 = CAACoordinateTransformation.MapTo0To360Range(316.13 + 584.903153 *k); - A2 = CAACoordinateTransformation.DegreesToRadians(A2); - double A3 = CAACoordinateTransformation.MapTo0To360Range(346.20 + 450.380738 *k); - A3 = CAACoordinateTransformation.DegreesToRadians(A3); - double A4 = CAACoordinateTransformation.MapTo0To360Range(136.95 + 659.306737 *k); - A4 = CAACoordinateTransformation.DegreesToRadians(A4); - double A5 = CAACoordinateTransformation.MapTo0To360Range(249.52 + 329.653368 *k); - A5 = CAACoordinateTransformation.DegreesToRadians(A5); - - JD -= 1.352 *Math.Sin(A1); - JD += 0.061 *Math.Sin(A2); - JD += 0.062 *Math.Sin(A3); - JD += 0.029 *Math.Sin(A4); - JD += 0.031 *Math.Sin(A5); - } - - return JD; - } - - public static int MarsK(double Year) - { - return (int)(0.53166*(Year - 2001.78)); - } - public static double MarsPerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2452195.026 + 686.9957857 *kdash - 0.0000001187 *ksquared; - } - public static double MarsAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2452195.026 + 686.9957857 *kdash - 0.0000001187 *ksquared; - } - - public static int JupiterK(double Year) - { - return (int)(0.08430*(Year - 2011.20)); - } - public static double JupiterPerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2455636.936 + 4332.897065 *kdash + 0.0001367 *ksquared; - } - public static double JupiterAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2455636.936 + 4332.897065 *kdash + 0.0001367 *ksquared; - } - - public static int SaturnK(double Year) - { - return (int)(0.03393*(Year - 2003.52)); - } - public static double SaturnPerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2452830.12 + 10764.21676 *kdash + 0.000827 *ksquared; - } - public static double SaturnAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2452830.12 + 10764.21676 *kdash + 0.000827 *ksquared; - } - - public static int UranusK(double Year) - { - return (int)(0.01190*(Year - 2051.1)); - } - public static double UranusPerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2470213.5 + 30694.8767 *kdash - 0.00541 *ksquared; - } - public static double UranusAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2470213.5 + 30694.8767 *kdash - 0.00541 *ksquared; - } - - public static int NeptuneK(double Year) - { - return (int)(0.00607*(Year - 2047.5)); - } - public static double NeptunePerihelion(int k) - { - double kdash = k; - double ksquared = kdash * kdash; - return 2468895.1 + 60190.33 *kdash + 0.03429 *ksquared; - } - public static double NeptuneAphelion(int k) - { - double kdash = k + 0.5; - double ksquared = kdash * kdash; - return 2468895.1 + 60190.33 *kdash + 0.03429 *ksquared; - } -} diff --git a/engine/csharp_ref/AstroCalc/AAPlanetaryPhenomena.cs b/engine/csharp_ref/AstroCalc/AAPlanetaryPhenomena.cs deleted file mode 100644 index f4b5d0ef..00000000 --- a/engine/csharp_ref/AstroCalc/AAPlanetaryPhenomena.cs +++ /dev/null @@ -1,405 +0,0 @@ -using System.Diagnostics; -using System; -public static partial class GlobalMembersStdafx -{ - - public static PlanetaryPhenomenaCoefficient1[] g_PlanetaryPhenomenaCoefficient1 = { new PlanetaryPhenomenaCoefficient1(2451612.023, 115.8774771, 63.5867, 114.2088742), new PlanetaryPhenomenaCoefficient1(2451554.084, 115.8774771, 6.4822, 114.2088742), new PlanetaryPhenomenaCoefficient1(2451996.706, 583.921361, 82.7311, 215.513058), new PlanetaryPhenomenaCoefficient1(2451704.746, 583.921361, 154.9745, 215.513058), new PlanetaryPhenomenaCoefficient1(2452097.382, 779.936104, 181.9573, 48.705244), new PlanetaryPhenomenaCoefficient1(2451707.414, 779.936104, 157.6047, 48.705244), new PlanetaryPhenomenaCoefficient1(2451870.628, 398.884046, 318.4681, 33.140229), new PlanetaryPhenomenaCoefficient1(2451671.186, 398.884046, 121.8980, 33.140229), new PlanetaryPhenomenaCoefficient1(2451870.170, 378.091904, 318.0172, 12.647487), new PlanetaryPhenomenaCoefficient1(2451681.124, 378.091904, 131.6934, 12.647487), new PlanetaryPhenomenaCoefficient1(2451764.317, 369.656035, 213.6884, 4.333093), new PlanetaryPhenomenaCoefficient1(2451579.489, 369.656035, 31.5219, 4.333093), new PlanetaryPhenomenaCoefficient1(2451753.122, 367.486703, 202.6544, 2.194998), new PlanetaryPhenomenaCoefficient1(2451569.379, 367.486703, 21.5569, 2.194998) }; -} -// -//Module : AAPLANETARYPHENOMENA.CPP -//Purpose: Implementation for the algorithms which obtain the dates of various planetary phenomena -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////////// Includes ///////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - public enum PlanetaryObject: int - { - MERCURY, - VENUS, - MARS, - JUPITER, - SATURN, - URANUS, - NEPTUNE - } -public class CAAPlanetaryPhenomena -{ -//Enums - - - public enum EventType: int - { - INFERIOR_CONJUNCTION, - SUPERIOR_CONJUNCTION, - OPPOSITION, - CONJUNCTION, - EASTERN_ELONGATION, - WESTERN_ELONGATION, - STATION1, - STATION2 - } - -//Static methods - - /////////////////////////// Implementation //////////////////////////////////// - - public static double K(double Year, PlanetaryObject @object, EventType type) - { - int nCoefficient = -1; - if ((int)@object >= (int)PlanetaryObject.MARS) - { - Debug.Assert(type == EventType.OPPOSITION || type == EventType.CONJUNCTION); - - if (type == EventType.OPPOSITION) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - else - { - Debug.Assert(type == EventType.INFERIOR_CONJUNCTION || type == EventType.SUPERIOR_CONJUNCTION); - - if (type == EventType.INFERIOR_CONJUNCTION) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - - double k = (365.2425 *Year + 1721060 - GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].A) / GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].B; - return Math.Floor(k + 0.5); - } - public static double Mean(double k, PlanetaryObject @object, EventType type) - { - int nCoefficient = -1; - if ((int)@object >= (int)PlanetaryObject.MARS) - { - Debug.Assert(type == EventType.OPPOSITION || type == EventType.CONJUNCTION); - - if (type == EventType.OPPOSITION) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - else - { - Debug.Assert(type == EventType.INFERIOR_CONJUNCTION || type == EventType.SUPERIOR_CONJUNCTION); - - if (type == EventType.INFERIOR_CONJUNCTION) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - - return GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].A + GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].B *k; - } - public static double True(double k, PlanetaryObject @object, EventType type) - { - double JDE0; - - if (type == EventType.WESTERN_ELONGATION || type == EventType.EASTERN_ELONGATION || type == EventType.STATION1 || type == EventType.STATION2) - { - if ((int)@object >= (int)PlanetaryObject.MARS) - JDE0 = Mean(k, @object, EventType.OPPOSITION); - else - JDE0 = Mean(k, @object, EventType.INFERIOR_CONJUNCTION); - } - else - JDE0 = Mean(k, @object, type); - - int nCoefficient = -1; - if (@object >= PlanetaryObject.MARS) - { - Debug.Assert(type == EventType.OPPOSITION || type == EventType.CONJUNCTION || type == EventType.STATION1 || type == EventType.STATION2); - - if (type == EventType.OPPOSITION || type == EventType.STATION1 || type == EventType.STATION2) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - else - { - Debug.Assert(type == EventType.INFERIOR_CONJUNCTION || type == EventType.SUPERIOR_CONJUNCTION || type == EventType.EASTERN_ELONGATION || type == EventType.WESTERN_ELONGATION || type == EventType.STATION1 || type == EventType.STATION2); - - if (type == EventType.INFERIOR_CONJUNCTION || type == EventType.EASTERN_ELONGATION || type == EventType.WESTERN_ELONGATION || type == EventType.STATION1 || type == EventType.STATION2) - nCoefficient = (int)@object *2; - else - nCoefficient = (int)@object *2 + 1; - } - - double M = CAACoordinateTransformation.MapTo0To360Range(GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].M0 + GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].M1 *k); - M = CAACoordinateTransformation.DegreesToRadians(M); //convert M to radians - - double T = (JDE0 - 2451545) / 36525; - double T2 = T *T; - - double a =0; - double b =0; - double c =0; - double d =0; - double e =0; - double f =0; - double g =0; - - if (@object == PlanetaryObject.JUPITER) - { - a = CAACoordinateTransformation.MapTo0To360Range(82.74 + 40.76 *T); - a = CAACoordinateTransformation.DegreesToRadians(a); - } - else if ((int)@object == (int)PlanetaryObject.SATURN) - { - a = CAACoordinateTransformation.MapTo0To360Range(82.74 + 40.76 *T); - a = CAACoordinateTransformation.DegreesToRadians(a); - b = CAACoordinateTransformation.MapTo0To360Range(29.86 + 1181.36 *T); - b = CAACoordinateTransformation.DegreesToRadians(b); - c = CAACoordinateTransformation.MapTo0To360Range(14.13 + 590.68 *T); - c = CAACoordinateTransformation.DegreesToRadians(c); - d = CAACoordinateTransformation.MapTo0To360Range(220.02 + 1262.87 *T); - d = CAACoordinateTransformation.DegreesToRadians(d); - } - else if ((int)@object == (int)PlanetaryObject.URANUS) - { - e = CAACoordinateTransformation.MapTo0To360Range(207.83 + 8.51 *T); - e = CAACoordinateTransformation.DegreesToRadians(e); - f = CAACoordinateTransformation.MapTo0To360Range(108.84 + 419.96 *T); - f = CAACoordinateTransformation.DegreesToRadians(f); - } - else if ((int)@object == (int)PlanetaryObject.NEPTUNE) - { - e = CAACoordinateTransformation.MapTo0To360Range(207.83 + 8.51 *T); - e = CAACoordinateTransformation.DegreesToRadians(e); - g = CAACoordinateTransformation.MapTo0To360Range(276.74 + 209.98 *T); - g = CAACoordinateTransformation.DegreesToRadians(g); - } - - double delta = 0; - if ((int)@object == (int)PlanetaryObject.MERCURY) - { - if (type == EventType.INFERIOR_CONJUNCTION) - { - delta = (0.0545 + 0.0002 *T) + Math.Sin(M) * (-6.2008 + 0.0074 *T + 0.00003 *T2) + Math.Cos(M) * (-3.2750 - 0.0197 *T + 0.00001 *T2) + Math.Sin(2 *M) * (0.4737 - 0.0052 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.8111 + 0.0033 *T - 0.00002 *T2) + Math.Sin(3 *M) * (0.0037 + 0.0018 *T) + Math.Cos(3 *M) * (-0.1768 + 0.00001 *T2) + Math.Sin(4 *M) * (-0.0211 - 0.0004 *T) + Math.Cos(4 *M) * (0.0326 - 0.0003 *T) + Math.Sin(5 *M) * (0.0083 + 0.0001 *T) + Math.Cos(5 *M) * (-0.0040 + 0.0001 *T); - } - else if (type == EventType.SUPERIOR_CONJUNCTION) - { - delta = (-0.0548 - 0.0002 *T) + Math.Sin(M) * (7.3894 - 0.0100 *T - 0.00003 *T2) + Math.Cos(M) * (3.2200 + 0.0197 *T - 0.00001 *T2) + Math.Sin(2 *M) * (0.8383 - 0.0064 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.9666 + 0.0039 *T - 0.00003 *T2) + Math.Sin(3 *M) * (0.0770 - 0.0026 *T) + Math.Cos(3 *M) * (0.2758 + 0.0002 *T - 0.00002 *T2) + Math.Sin(4 *M) * (-0.0128 - 0.0008 *T) + Math.Cos(4 *M) * (0.0734 - 0.0004 *T - 0.00001 *T2) + Math.Sin(5 *M) * (-0.0122 - 0.0002 *T) + Math.Cos(5 *M) * (0.0173 - 0.0002 *T); - } - else if (type == EventType.EASTERN_ELONGATION) - { - delta = (-21.6101 + 0.0002 *T) + Math.Sin(M) * (-1.9803 - 0.0060 *T + 0.00001 *T2) + Math.Cos(M) * (1.4151 - 0.0072 *T - 0.00001 *T2) + Math.Sin(2 *M) * (0.5528 - 0.0005 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.2905 + 0.0034 *T + 0.00001 *T2) + Math.Sin(3 *M) * (-0.1121 - 0.0001 *T + 0.00001 *T2) + Math.Cos(3 *M) * (-0.0098 - 0.0015 *T) + Math.Sin(4 *M) * (0.0192) + Math.Cos(4 *M) * (0.0111 + 0.0004 *T) + Math.Sin(5 *M) * (-0.0061) + Math.Cos(5 *M) * (-0.0032 - 0.0001 *T2); - } - else if (type == EventType.WESTERN_ELONGATION) - { - delta = (21.6249 - 0.0002 *T) + Math.Sin(M) * (0.1306 + 0.0065 *T) + Math.Cos(M) * (-2.7661 - 0.0011 *T + 0.00001 *T2) + Math.Sin(2 *M) * (0.2438 - 0.0024 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.5767 + 0.0023 *T) + Math.Sin(3 *M) * (0.1041) + Math.Cos(3 *M) * (-0.0184 + 0.0007 *T) + Math.Sin(4 *M) * (-0.0051 - 0.0001 *T) + Math.Cos(4 *M) * (0.0048 + 0.0001 *T) + Math.Sin(5 *M) * (0.0026) + Math.Cos(5 *M) * (0.0037); - } - else if (type == EventType.STATION1) - { - delta = (-11.0761 + 0.0003 *T) + Math.Sin(M) * (-4.7321 + 0.0023 *T + 0.00002 *T2) + Math.Cos(M) * (-1.3230 - 0.0156 *T) + Math.Sin(2 *M) * (0.2270 - 0.0046 *T) + Math.Cos(2 *M) * (0.7184 + 0.0013 *T - 0.00002 *T2) + Math.Sin(3 *M) * (0.0638 + 0.0016 *T) + Math.Cos(3 *M) * (-0.1655 + 0.0007 *T) + Math.Sin(4 *M) * (-0.0395 - 0.0003 *T) + Math.Cos(4 *M) * (0.0247 - 0.0006 *T) + Math.Sin(5 *M) * (0.0131) + Math.Cos(5 *M) * (0.0008 + 0.0002 *T); - } - else - { - Debug.Assert(type == EventType.STATION2); - - delta = (11.1343 - 0.0001 *T) + Math.Sin(M) * (-3.9137 + 0.0073 *T + 0.00002 *T2) + Math.Cos(M) * (-3.3861 - 0.0128 *T + 0.00001 *T2) + Math.Sin(2 *M) * (0.5222 - 0.0040 *T - 0.00002 *T2) + Math.Cos(2 *M) * (0.5929 + 0.0039 *T - 0.00002 *T2) + Math.Sin(3 *M) * (-0.0593 + 0.0018 *T) + Math.Cos(3 *M) * (-0.1733 - 0.0007 *T + 0.00001 *T2) + Math.Sin(4 *M) * (-0.0053 - 0.0006 *T) + Math.Cos(4 *M) * (0.0476 - 0.0001 *T) + Math.Sin(5 *M) * (0.0070 + 0.0002 *T) + Math.Cos(5 *M) * (-0.0115 + 0.0001 *T); - } - } - else if ((int)@object == (int)PlanetaryObject.VENUS) - { - if (type == EventType.INFERIOR_CONJUNCTION) - { - delta = (-0.0096 + 0.0002 *T - 0.00001 *T2) + Math.Sin(M) * (2.0009 - 0.0033 *T - 0.00001 *T2) + Math.Cos(M) * (0.5980 - 0.0104 *T + 0.00001 *T2) + Math.Sin(2 *M) * (0.0967 - 0.0018 *T - 0.00003 *T2) + Math.Cos(2 *M) * (0.0913 + 0.0009 *T - 0.00002 *T2) + Math.Sin(3 *M) * (0.0046 - 0.0002 *T) + Math.Cos(3 *M) * (0.0079 + 0.0001 *T); - } - else if (type == EventType.SUPERIOR_CONJUNCTION) - { - delta = (0.0099 - 0.0002 *T - 0.00001 *T2) + Math.Sin(M) * (4.1991 - 0.0121 *T - 0.00003 *T2) + Math.Cos(M) * (-0.6095 + 0.0102 *T - 0.00002 *T2) + Math.Sin(2 *M) * (0.2500 - 0.0028 *T - 0.00003 *T2) + Math.Cos(2 *M) * (0.0063 + 0.0025 *T - 0.00002 *T2) + Math.Sin(3 *M) * (0.0232 - 0.0005 *T - 0.00001 *T2) + Math.Cos(3 *M) * (0.0031 + 0.0004 *T); - } - else if (type == EventType.EASTERN_ELONGATION) - { - delta = (-70.7600 + 0.0002 *T - 0.00001 *T2) + Math.Sin(M) * (1.0282 - 0.0010 *T - 0.00001 *T2) + Math.Cos(M) * (0.2761 - 0.0060 *T) + Math.Sin(2 *M) * (-0.0438 - 0.0023 *T + 0.00002 *T2) + Math.Cos(2 *M) * (0.1660 - 0.0037 *T - 0.00004 *T2) + Math.Sin(3 *M) * (0.0036 + 0.0001 *T) + Math.Cos(3 *M) * (-0.0011 + 0.00001 *T2); - } - else if (type == EventType.WESTERN_ELONGATION) - { - delta = (70.7462 - 0.00001 *T2) + Math.Sin(M) * (1.1218 - 0.0025 *T - 0.00001 *T2) + Math.Cos(M) * (0.4538 - 0.0066 *T) + Math.Sin(2 *M) * (0.1320 + 0.0020 *T - 0.00003 *T2) + Math.Cos(2 *M) * (-0.0702 + 0.0022 *T + 0.00004 *T2) + Math.Sin(3 *M) * (0.0062 - 0.0001 *T) + Math.Cos(3 *M) * (0.0015 - 0.00001 *T2); - } - else if (type == EventType.STATION1) - { - delta = (-21.0672 + 0.0002 *T - 0.00001 *T2) + Math.Sin(M) * (1.9396 - 0.0029 *T - 0.00001 *T2) + Math.Cos(M) * (1.0727 - 0.0102 *T) + Math.Sin(2 *M) * (0.0404 - 0.0023 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.1305 - 0.0004 *T - 0.00003 *T2) + Math.Sin(3 *M) * (-0.0007 - 0.0002 *T) + Math.Cos(3 *M) * (0.0098); - } - else - { - Debug.Assert(type == EventType.STATION2); - - delta = (21.0623 - 0.00001 *T2) + Math.Sin(M) * (1.9913 - 0.0040 *T - 0.00001 *T2) + Math.Cos(M) * (-0.0407 - 0.0077 *T) + Math.Sin(2 *M) * (0.1351 - 0.0009 *T - 0.00004 *T2) + Math.Cos(2 *M) * (0.0303 + 0.0019 *T) + Math.Sin(3 *M) * (0.0089 - 0.0002 *T) + Math.Cos(3 *M) * (0.0043 + 0.0001 *T); - } - } - else if ((int)@object == (int)PlanetaryObject.MARS) - { - if (type == EventType.OPPOSITION) - { - delta = (-0.3088 + 0.00002 *T2) + Math.Sin(M) * (-17.6965 + 0.0363 *T + 0.00005 *T2) + Math.Cos(M) * (18.3131 + 0.0467 *T - 0.00006 *T2) + Math.Sin(2 *M) * (-0.2162 - 0.0198 *T - 0.00001 *T2) + Math.Cos(2 *M) * (-4.5028 - 0.0019 *T + 0.00007 *T2) + Math.Sin(3 *M) * (0.8987 + 0.0058 *T - 0.00002 *T2) + Math.Cos(3 *M) * (0.7666 - 0.0050 *T - 0.00003 *T2) + Math.Sin(4 *M) * (-0.3636 - 0.0001 *T + 0.00002 *T2) + Math.Cos(4 *M) * (0.0402 + 0.0032 *T) + Math.Sin(5 *M) * (0.0737 - 0.0008 *T) + Math.Cos(5 *M) * (-0.0980 - 0.0011 *T); - } - else if (type == EventType.CONJUNCTION) - { - delta = (0.3102 - 0.0001 *T + 0.00001 *T2) + Math.Sin(M) * (9.7273 - 0.0156 *T + 0.00001 *T2) + Math.Cos(M) * (-18.3195 - 0.0467 *T + 0.00009 *T2) + Math.Sin(2 *M) * (-1.6488 - 0.0133 *T + 0.00001 *T2) + Math.Cos(2 *M) * (-2.6117 - 0.0020 *T + 0.00004 *T2) + Math.Sin(3 *M) * (-0.6827 - 0.0026 *T + 0.00001 *T2) + Math.Cos(3 *M) * (0.0281 + 0.0035 *T + 0.00001 *T2) + Math.Sin(4 *M) * (-0.0823 + 0.0006 *T + 0.00001 *T2) + Math.Cos(4 *M) * (0.1584 + 0.0013 *T) + Math.Sin(5 *M) * (0.0270 + 0.0005 *T) + Math.Cos(5 *M) * (0.0433); - } - else if (type == EventType.STATION1) - { - delta = (-37.0790 - 0.0009 *T + 0.00002 *T2) + Math.Sin(M) * (-20.0651 + 0.0228 *T + 0.00004 *T2) + Math.Cos(M) * (14.5205 + 0.0504 - 0.00001 *T2) + Math.Sin(2 *M) * (1.1737 - 0.0169 *T) + Math.Cos(2 *M) * (-4.2550 - 0.0075 *T + 0.00008 *T2) + Math.Sin(3 *M) * (0.4897 + 0.0074 *T - 0.00001 *T2) + Math.Cos(3 *M) * (1.1151 - 0.0021 *T - 0.00005 *T2) + Math.Sin(4 *M) * (-0.3636 - 0.0020 *T + 0.00001 *T2) + Math.Cos(4 *M) * (-0.1769 + 0.0028 *T + 0.00002 *T2) + Math.Sin(5 *M) * (0.1437 - 0.0004 *T) + Math.Cos(5 *M) * (-0.0383 - 0.0016 *T); - } - else - { - Debug.Assert(type == EventType.STATION2); - - delta = (36.7191 + 0.0016 *T + 0.00003 *T2) + Math.Sin(M) * (-12.6163 + 0.0417 *T - 0.00001 *T2) + Math.Cos(M) * (20.1218 + 0.0379 *T - 0.00006 *T2) + Math.Sin(2 *M) * (-1.6360 - 0.0190 *T) + Math.Cos(2 *M) * (-3.9657 + 0.0045 *T + 0.00007 *T2) + Math.Sin(3 *M) * (1.1546 + 0.0029 *T - 0.00003 *T2) + Math.Cos(3 *M) * (0.2888 - 0.0073 *T - 0.00002 *T2) + Math.Sin(4 *M) * (-0.3128 + 0.0017 *T + 0.00002 *T2) + Math.Cos(4 *M) * (0.2513 + 0.0026 *T - 0.00002 *T2) + Math.Sin(5 *M) * (-0.0021 - 0.0016 *T) + Math.Cos(5 *M) * (-0.1497 - 0.0006 *T); - } - } - else if ((int)@object == (int)PlanetaryObject.JUPITER) - { - if (type == EventType.OPPOSITION) - { - delta = (-0.1029 - 0.00009 *T2) + Math.Sin(M) * (-1.9658 - 0.0056 *T + 0.00007 *T2) + Math.Cos(M) * (6.1537 + 0.0210 *T - 0.00006 *T2) + Math.Sin(2 *M) * (-0.2081 - 0.0013 *T) + Math.Cos(2 *M) * (-0.1116 - 0.0010 *T) + Math.Sin(3 *M) * (0.0074 + 0.0001 *T) + Math.Cos(3 *M) * (-0.0097 - 0.0001 *T) + Math.Sin(a) * (0.0144 *T - 0.00008 *T2) + Math.Cos(a) * (0.3642 - 0.0019 *T - 0.00029 *T2); - } - else if (type == EventType.CONJUNCTION) - { - delta = (0.1027 + 0.0002 *T - 0.00009 *T2) + Math.Sin(M) * (-2.2637 + 0.0163 *T - 0.00003 *T2) + Math.Cos(M) * (-6.1540 - 0.0210 *T + 0.00008 *T2) + Math.Sin(2 *M) * (-0.2021 - 0.0017 *T + 0.00001 *T2) + Math.Cos(2 *M) * (0.1310 - 0.0008 *T) + Math.Sin(3 *M) * (0.0086) + Math.Cos(3 *M) * (0.0087 + 0.0002 *T) + Math.Sin(a) * (0.0144 *T - 0.00008 *T2) + Math.Cos(a) * (0.3642 - 0.0019 *T - 0.00029 *T2); - } - else if (type == EventType.STATION1) - { - delta = (-60.3670 - 0.0001 *T - 0.00009 *T2) + Math.Sin(M) * (-2.3144 - 0.0124 *T + 0.00007 *T2) + Math.Cos(M) * (6.7439 + 0.0166 *T - 0.00006 *T2) + Math.Sin(2 *M) * (-0.2259 - 0.0010 *T) + Math.Cos(2 *M) * (-0.1497 - 0.0014 *T) + Math.Sin(3 *M) * (0.0105 + 0.0001 *T) + Math.Cos(3 *M) * (-0.0098) + Math.Sin(a) * (0.0144 *T - 0.00008 *T2) + Math.Cos(a) * (0.3642 - 0.0019 *T - 0.00029 *T2); - } - else - { - Debug.Assert(type == EventType.STATION2); - - delta = (60.3023 + 0.0002 *T - 0.00009 *T2) + Math.Sin(M) * (0.3506 - 0.0034 *T + 0.00004 *T2) + Math.Cos(M) * (5.3635 + 0.0247 *T - 0.00007 *T2) + Math.Sin(2 *M) * (-0.1872 - 0.0016 *T) + Math.Cos(2 *M) * (-0.0037 - 0.0005 *T) + Math.Sin(3 *M) * (0.0012 + 0.0001 *T) + Math.Cos(3 *M) * (-0.0096 - 0.0001 *T) + Math.Sin(a) * (0.0144 *T - 0.00008 *T2) + Math.Cos(a) * (0.3642 - 0.0019 *T - 0.00029 *T2); - } - } - else if ((int)@object == (int)PlanetaryObject.SATURN) - { - if (type == EventType.OPPOSITION) - { - delta = (-0.0209 + 0.0006 *T + 0.00023 *T2) + Math.Sin(M) * (4.5795 - 0.0312 *T - 0.00017 *T2) + Math.Cos(M) * (1.1462 - 0.0351 *T + 0.00011 *T2) + Math.Sin(2 *M) * (0.0985 - 0.0015 *T) + Math.Cos(2 *M) * (0.0733 - 0.0031 *T + 0.00001 *T2) + Math.Sin(3 *M) * (0.0025 - 0.0001 *T) + Math.Cos(3 *M) * (0.0050 - 0.0002 *T) + Math.Sin(a) * (-0.0337 *T + 0.00018 *T2) + Math.Cos(a) * (-0.8510 + 0.0044 *T + 0.00068 *T2) + Math.Sin(b) * (-0.0064 *T + 0.00004 *T2) + Math.Cos(b) * (0.2397 - 0.0012 *T - 0.00008 *T2) + Math.Sin(c) * (-0.0010 *T) + Math.Cos(c) * (0.1245 + 0.0006 *T) + Math.Sin(d) * (0.0024 *T - 0.00003 *T2) + Math.Cos(d) * (0.0477 - 0.0005 *T - 0.00006 *T2); - } - else if (type == EventType.CONJUNCTION) - { - delta = (0.0172 - 0.0006 *T + 0.00023 *T2) + Math.Sin(M) * (-8.5885 + 0.0411 *T + 0.00020 *T2) + Math.Cos(M) * (-1.1470 + 0.0352 *T - 0.00011 *T2) + Math.Sin(2 *M) * (0.3331 - 0.0034 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.1145 - 0.0045 *T + 0.00002 *T2) + Math.Sin(3 *M) * (-0.0169 + 0.0002 *T) + Math.Cos(3 *M) * (-0.0109 + 0.0004 *T) + Math.Sin(a) * (-0.0337 *T + 0.00018 *T2) + Math.Cos(a) * (-0.8510 + 0.0044 *T + 0.00068 *T2) + Math.Sin(b) * (-0.0064 *T + 0.00004 *T2) + Math.Cos(b) * (0.2397 - 0.0012 *T - 0.00008 *T2) + Math.Sin(c) * (-0.0010 *T) + Math.Cos(c) * (0.1245 + 0.0006 *T) + Math.Sin(d) * (0.0024 *T - 0.00003 *T2) + Math.Cos(d) * (0.0477 - 0.0005 *T - 0.00006 *T2); - } - else if (type == EventType.STATION1) - { - delta = (-68.8840 + 0.0009 *T + 0.00023 *T2) + Math.Sin(M) * (5.5452 - 0.0279 *T - 0.00020 *T2) + Math.Cos(M) * (3.0727 - 0.0430 *T + 0.00007 *T2) + Math.Sin(2 *M) * (0.1101 - 0.0006 *T - 0.00001 *T2) + Math.Cos(2 *M) * (0.1654 - 0.0043 *T + 0.00001 *T2) + Math.Sin(3 *M) * (0.0010 + 0.0001 *T) + Math.Cos(3 *M) * (0.0095 - 0.0003 *T) + Math.Sin(a) * (-0.0337 *T + 0.00018 *T2) + Math.Cos(a) * (-0.8510 + 0.0044 *T + 0.00068 *T2) + Math.Sin(b) * (-0.0064 *T + 0.00004 *T2) + Math.Cos(b) * (0.2397 - 0.0012 *T - 0.00008 *T2) + Math.Sin(c) * (-0.0010 *T) + Math.Cos(c) * (0.1245 + 0.0006 *T) + Math.Sin(d) * (0.0024 *T - 0.00003 *T2) + Math.Cos(d) * (0.0477 - 0.0005 *T - 0.00006 *T2); - } - else - { - Debug.Assert(type == EventType.STATION2); - - delta = (68.8720 - 0.0007 *T + 0.00023 *T2) + Math.Sin(M) * (5.9399 - 0.0400 *T - 0.00015 *T2) + Math.Cos(M) * (-0.7998 - 0.0266 *T + 0.00014 *T2) + Math.Sin(2 *M) * (0.1738 - 0.0032 *T) + Math.Cos(2 *M) * (-0.0039 - 0.0024 *T + 0.00001 *T2) + Math.Sin(3 *M) * (0.0073 - 0.0002 *T) + Math.Cos(3 *M) * (0.0020 - 0.0002 *T) + Math.Sin(a) * (-0.0337 *T + 0.00018 *T2) + Math.Cos(a) * (-0.8510 + 0.0044 *T + 0.00068 *T2) + Math.Sin(b) * (-0.0064 *T + 0.00004 *T2) + Math.Cos(b) * (0.2397 - 0.0012 *T - 0.00008 *T2) + Math.Sin(c) * (-0.0010 *T) + Math.Cos(c) * (0.1245 + 0.0006 *T) + Math.Sin(d) * (0.0024 *T - 0.00003 *T2) + Math.Cos(d) * (0.0477 - 0.0005 *T - 0.00006 *T2); - } - } - else if ((int)@object == (int)PlanetaryObject.URANUS) - { - if (type == EventType.OPPOSITION) - { - delta = (0.0844 - 0.0006 *T) + Math.Sin(M) * (-0.1048 + 0.0246 *T) + Math.Cos(M) * (-5.1221 + 0.0104 *T + 0.00003 *T2) + Math.Sin(2 *M) * (-0.1428 - 0.0005 *T) + Math.Cos(2 *M) * (-0.0148 - 0.0013 *T) + Math.Cos(3 *M) * 0.0055 + Math.Cos(e) * 0.8850 + Math.Cos(f) * 0.2153; - } - else - { - Debug.Assert(type == EventType.CONJUNCTION); - - delta = (-0.0859 + 0.0003 *T) + Math.Sin(M) * (-3.8179 - 0.0148 *T + 0.00003 *T2) + Math.Cos(M) * (5.1228 - 0.0105 *T - 0.00002 *T2) + Math.Sin(2 *M) * (-0.0803 + 0.0011 *T) + Math.Cos(2 *M) * (-0.1905 - 0.0006 *T) + Math.Sin(3 *M) * (0.0088 + 0.0001 *T) + Math.Cos(e) * 0.8850 + Math.Cos(f) * 0.2153; - } - } - else - { - Debug.Assert((int)@object == (int)PlanetaryObject.NEPTUNE); - - if (type == EventType.OPPOSITION) - { - delta = (-0.0140 + 0.00001 *T2) + Math.Sin(M) * (-1.3486 + 0.0010 *T + 0.00001 *T2) + Math.Cos(M) * (0.8597 + 0.0037 *T) + Math.Sin(2 *M) * (-0.0082 - 0.0002 *T + 0.00001 *T2) + Math.Cos(2 *M) * (0.0037 - 0.0003 *T) + Math.Cos(e) * (-0.5964) + Math.Cos(g) * (0.0728); - } - else - { - Debug.Assert(type == EventType.CONJUNCTION); - - delta = (0.0168) + Math.Sin(M) * (-2.5606 + 0.0088 *T + 0.00002 *T2) + Math.Cos(M) * (-0.8611 - 0.0037 *T + 0.00002 *T2) + Math.Sin(2 *M) * (0.0118 - 0.0004 *T + 0.00001 *T2) + Math.Cos(2 *M) * (0.0307 - 0.0003 *T) + Math.Cos(e) * (-0.5964) + Math.Cos(g) * (0.0728); - } - } - - return JDE0 + delta; - } - public static double ElongationValue(double k, PlanetaryObject @object, bool bEastern) - { - double JDE0 = Mean(k, @object, EventType.INFERIOR_CONJUNCTION); - - Debug.Assert((int)@object < (int)PlanetaryObject.MARS); - - int nCoefficient = (int)@object *2; - - double M = CAACoordinateTransformation.MapTo0To360Range(GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].M0 + GlobalMembersStdafx.g_PlanetaryPhenomenaCoefficient1[nCoefficient].M1 *k); - M = CAACoordinateTransformation.DegreesToRadians(M); //convert M to radians - - double T = (JDE0 - 2451545) / 36525; - double T2 = T *T; - - double @value = 0; - if ((int)@object == (int)PlanetaryObject.MERCURY) - { - if (bEastern) - { - @value = (22.4697) + Math.Sin(M) * (-4.2666 + 0.0054 *T + 0.00002 *T2) + Math.Cos(M) * (-1.8537 - 0.0137 *T) + Math.Sin(2 *M) * (0.3598 + 0.0008 *T - 0.00001 *T2) + Math.Cos(2 *M) * (-0.0680 + 0.0026 *T) + Math.Sin(3 *M) * (-0.0524 - 0.0003 *T) + Math.Cos(3 *M) * (0.0052 - 0.0006 *T) + Math.Sin(4 *M) * (0.0107 + 0.0001 *T) + Math.Cos(4 *M) * (-0.0013 + 0.0001 *T) + Math.Sin(5 *M) * (-0.0021) + Math.Cos(5 *M) * (0.0003); - } - else - { - @value = (22.4143 - 0.0001 *T) + Math.Sin(M) * (4.3651 - 0.0048 *T - 0.00002 *T2) + Math.Cos(M) * (2.3787 + 0.0121 *T - 0.00001 *T2) + Math.Sin(2 *M) * (0.2674 + 0.0022 *T) + Math.Cos(2 *M) * (-0.3873 + 0.0008 *T + 0.00001 *T2) + Math.Sin(3 *M) * (-0.0369 - 0.0001 *T) + Math.Cos(3 *M) * (0.0017 - 0.0001 *T) + Math.Sin(4 *M) * (0.0059) + Math.Cos(4 *M) * (0.0061 + 0.0001 *T) + Math.Sin(5 *M) * (0.0007) + Math.Cos(5 *M) * (-0.0011); - } - } - else if ((int)@object == (int)PlanetaryObject.VENUS) - { - if (bEastern) - { - @value = (46.3173 + 0.0001 *T) + Math.Sin(M) * (0.6916 - 0.0024 *T) + Math.Cos(M) * (0.6676 - 0.0045 *T) + Math.Sin(2 *M) * (0.0309 - 0.0002 *T) + Math.Cos(2 *M) * (0.0036 - 0.0001 *T); - } - else - { - @value = (46.3245) + Math.Sin(M) * (-0.5366 - 0.0003 *T + 0.00001 *T2) + Math.Cos(M) * (0.3097 + 0.0016 *T - 0.00001 *T2) + Math.Sin(2 *M) * (-0.0163) + Math.Cos(2 *M) * (-0.0075 + 0.0001 *T); - } - } - - return @value; - } -} - - - - -//////////////////////////// Macros / Defines ///////////////////////////////// - -public class PlanetaryPhenomenaCoefficient1 -{ - public PlanetaryPhenomenaCoefficient1(double a, double b, double m0, double m1) - { - A = a; - B = b; - M0 = m0; - M1 = m1; - } - public double A; - public double B; - public double M0; - public double M1; -} diff --git a/engine/csharp_ref/AstroCalc/AAPluto.cs b/engine/csharp_ref/AstroCalc/AAPluto.cs deleted file mode 100644 index 76232073..00000000 --- a/engine/csharp_ref/AstroCalc/AAPluto.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -public static partial class GFX -{ - - public static PlutoCoefficient1[] g_PlutoArgumentCoefficients = { new PlutoCoefficient1(0, 0, 1), new PlutoCoefficient1(0, 0, 2), new PlutoCoefficient1(0, 0, 3), new PlutoCoefficient1(0, 0, 4), new PlutoCoefficient1(0, 0, 5), new PlutoCoefficient1(0, 0, 6), new PlutoCoefficient1(0, 1, -1), new PlutoCoefficient1(0, 1, 0), new PlutoCoefficient1(0, 1, 1), new PlutoCoefficient1(0, 1, 2), new PlutoCoefficient1(0, 1, 3), new PlutoCoefficient1(0, 2, -2), new PlutoCoefficient1(0, 2, -1), new PlutoCoefficient1(0, 2, 0), new PlutoCoefficient1(1, -1, 0), new PlutoCoefficient1(1, -1, 1), new PlutoCoefficient1(1, 0, -3), new PlutoCoefficient1(1, 0, -2), new PlutoCoefficient1(1, 0, -1), new PlutoCoefficient1(1, 0, 0), new PlutoCoefficient1(1, 0, 1), new PlutoCoefficient1(1, 0, 2), new PlutoCoefficient1(1, 0, 3), new PlutoCoefficient1(1, 0, 4), new PlutoCoefficient1(1, 1, -3), new PlutoCoefficient1(1, 1, -2), new PlutoCoefficient1(1, 1, -1), new PlutoCoefficient1(1, 1, 0), new PlutoCoefficient1(1, 1, 1), new PlutoCoefficient1(1, 1, 3), new PlutoCoefficient1(2, 0, -6), new PlutoCoefficient1(2, 0, -5), new PlutoCoefficient1(2, 0, -4), new PlutoCoefficient1(2, 0, -3), new PlutoCoefficient1(2, 0, -2), new PlutoCoefficient1(2, 0, -1), new PlutoCoefficient1(2, 0, 0), new PlutoCoefficient1(2, 0, 1), new PlutoCoefficient1(2, 0, 2), new PlutoCoefficient1(2, 0, 3), new PlutoCoefficient1(3, 0, -2), new PlutoCoefficient1(3, 0, -1), new PlutoCoefficient1(3, 0, 0) }; - - public static PlutoCoefficient2[] g_PlutoLongitudeCoefficients = { new PlutoCoefficient2(-19799805, 19850055), new PlutoCoefficient2(897144, -4954829), new PlutoCoefficient2(611149, 1211027), new PlutoCoefficient2(-341243, -189585), new PlutoCoefficient2(129287, -34992), new PlutoCoefficient2(-38164, 30893), new PlutoCoefficient2(20442, -9987), new PlutoCoefficient2(-4063, -5071), new PlutoCoefficient2(-6016, -3336), new PlutoCoefficient2(-3956, 3039), new PlutoCoefficient2(-667, 3572), new PlutoCoefficient2(1276, 501), new PlutoCoefficient2(1152, -917), new PlutoCoefficient2(630, -1277), new PlutoCoefficient2(2571, -459), new PlutoCoefficient2(899, -1449), new PlutoCoefficient2(-1016, 1043), new PlutoCoefficient2(-2343, -1012), new PlutoCoefficient2(7042, 788), new PlutoCoefficient2(1199, -338), new PlutoCoefficient2(418, -67), new PlutoCoefficient2(120, -274), new PlutoCoefficient2(-60, -159), new PlutoCoefficient2(-82, -29), new PlutoCoefficient2(-36, -29), new PlutoCoefficient2(-40, 7), new PlutoCoefficient2(-14, 22), new PlutoCoefficient2(4, 13), new PlutoCoefficient2(5, 2), new PlutoCoefficient2(-1, 0), new PlutoCoefficient2(2, 0), new PlutoCoefficient2(-4, 5), new PlutoCoefficient2(4, -7), new PlutoCoefficient2(14, 24), new PlutoCoefficient2(-49, -34), new PlutoCoefficient2(163, -48), new PlutoCoefficient2(9, -24), new PlutoCoefficient2(-4, 1), new PlutoCoefficient2(-3, 1), new PlutoCoefficient2(1, 3), new PlutoCoefficient2(-3, -1), new PlutoCoefficient2(5, -3), new PlutoCoefficient2(0, 0) }; - - - public static PlutoCoefficient2[] g_PlutoLatitudeCoefficients = { new PlutoCoefficient2(-5452852, -14974862), new PlutoCoefficient2(3527812, 1672790), new PlutoCoefficient2(-1050748, 327647), new PlutoCoefficient2(178690, -292153), new PlutoCoefficient2(18650, 100340), new PlutoCoefficient2(-30697, -25823), new PlutoCoefficient2(4878, 11248), new PlutoCoefficient2(226, -64), new PlutoCoefficient2(2030, -836), new PlutoCoefficient2(69, -604), new PlutoCoefficient2(-247, -567), new PlutoCoefficient2(-57, 1), new PlutoCoefficient2(-122, 175), new PlutoCoefficient2(-49, -164), new PlutoCoefficient2(-197, 199), new PlutoCoefficient2(-25, 217), new PlutoCoefficient2(589, -248), new PlutoCoefficient2(-269, 711), new PlutoCoefficient2(185, 193), new PlutoCoefficient2(315, 807), new PlutoCoefficient2(-130, -43), new PlutoCoefficient2(5, 3), new PlutoCoefficient2(2, 17), new PlutoCoefficient2(2, 5), new PlutoCoefficient2(2, 3), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(2, -1), new PlutoCoefficient2(1, -1), new PlutoCoefficient2(0, -1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-7, 0), new PlutoCoefficient2(10, -8), new PlutoCoefficient2(-3, 20), new PlutoCoefficient2(6, 5), new PlutoCoefficient2(14, 17), new PlutoCoefficient2(-2, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(1, 0) }; - - public static PlutoCoefficient2[] g_PlutoRadiusCoefficients = { new PlutoCoefficient2(66865439, 68951812), new PlutoCoefficient2(-11827535, -332538), new PlutoCoefficient2(1593179, -1438890), new PlutoCoefficient2(-18444, 483220), new PlutoCoefficient2(-65977, -85431), new PlutoCoefficient2(31174, -6032), new PlutoCoefficient2(-5794, 22161), new PlutoCoefficient2(4601, 4032), new PlutoCoefficient2(-1729, 234), new PlutoCoefficient2(-415, 702), new PlutoCoefficient2(239, 723), new PlutoCoefficient2(67, -67), new PlutoCoefficient2(1034, -451), new PlutoCoefficient2(-129, 504), new PlutoCoefficient2(480, -231), new PlutoCoefficient2(2, -441), new PlutoCoefficient2(-3359, 265), new PlutoCoefficient2(7856, -7832), new PlutoCoefficient2(36, 45763), new PlutoCoefficient2(8663, 8547), new PlutoCoefficient2(-809, -769), new PlutoCoefficient2(263, -144), new PlutoCoefficient2(-126, 32), new PlutoCoefficient2(-35, -16), new PlutoCoefficient2(-19, -4), new PlutoCoefficient2(-15, 8), new PlutoCoefficient2(-4, 12), new PlutoCoefficient2(5, 6), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(6, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-2, -2), new PlutoCoefficient2(14, 13), new PlutoCoefficient2(-63, 13), new PlutoCoefficient2(136, -236), new PlutoCoefficient2(273, 1065), new PlutoCoefficient2(251, 149), new PlutoCoefficient2(-25, -9), new PlutoCoefficient2(9, -2), new PlutoCoefficient2(-8, 7), new PlutoCoefficient2(2, -10), new PlutoCoefficient2(19, 35), new PlutoCoefficient2(10, 3) }; -} -// -//Module : AAPLUTO.CPP -//Purpose: Implementation for the algorithms which obtain the heliocentric position of Pluto -//Created: PJN / 29-12-2003 -//History: None -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -//////////////////////// Includes ///////////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAAPluto -{ -//Static methods - - /////////////////////////////////// Implementation //////////////////////////// - - public static double EclipticLongitude(double JD) - { - double T = (JD - 2451545) / 36525; - double J = 34.35 + 3034.9057 *T; - double S = 50.08 + 1222.1138 *T; - double P = 238.96 + 144.9600 *T; - - //Calculate Longitude - double L = 0; - int nPlutoCoefficients = GFX.g_PlutoArgumentCoefficients.Length; - for (int i =0; i 1) || (cosH0 < -1)) - return details; - - double H0 = Math.Acos(cosH0); - H0 = CT.R2D(H0); - - double M0 = (Alpha2 *15 + Longitude - theta0) / 360; - double M1 = M0 - H0/360; - double M2 = M0 + H0/360; - - if (M0 > 1) - M0 -= 1; - else if (M0 < 0) - M0 += 1; - - if (M1 > 1) - M1 -= 1; - else if (M1 < 0) - M1 += 1; - - if (M2 > 1) - M2 -= 1; - else if (M2 < 0) - M2 += 1; - - for (int i =0; i<2; i++) - { - //Calculate the details of rising - - double theta1 = theta0 + 360.985647 *M1; - theta1 = CT.M360(theta1); - - double n = M1 + deltaT/86400; - - double Alpha = INTP.Interpolate(n, Alpha1, Alpha2, Alpha3); - double Delta = INTP.Interpolate(n, Delta1, Delta2, Delta3); - - double H = theta1 - Longitude - Alpha *15; - COR Horizontal = CT.Eq2H(H/15, Delta, Latitude); - - double DeltaM = (Horizontal.Y - h0) / (360 *Math.Cos(CT.D2R(Delta))*Math.Cos(LatitudeRad)*Math.Sin(CT.D2R(H))); - M1 += DeltaM; - - - //Calculate the details of transit - - theta1 = theta0 + 360.985647 *M0; - theta1 = CT.M360(theta1); - - n = M0 + deltaT/86400; - - Alpha = INTP.Interpolate(n, Alpha1, Alpha2, Alpha3); - - H = theta1 - Longitude - Alpha *15; - - if (H < -180) - { - H+=360; - } - - DeltaM = -H / 360; - M0 += DeltaM; - - - //Calculate the details of setting - - theta1 = theta0 + 360.985647 *M2; - theta1 = CT.M360(theta1); - - n = M2 + deltaT/86400; - - Alpha = INTP.Interpolate(n, Alpha1, Alpha2, Alpha3); - Delta = INTP.Interpolate(n, Delta1, Delta2, Delta3); - - H = theta1 - Longitude - Alpha *15; - Horizontal = CT.Eq2H(H/15, Delta, Latitude); - - DeltaM = (Horizontal.Y - h0) / (360 *Math.Cos(CT.D2R(Delta))*Math.Cos(LatitudeRad)*Math.Sin(CT.D2R(H))); - M2 += DeltaM; - } - - //Finally before we exit, convert to hours - details.bValid = true; - details.Rise = M1 * 24; - details.Set = M2 * 24; - details.Transit = M0 * 24; - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AASaturn.cs b/engine/csharp_ref/AstroCalc/AASaturn.cs deleted file mode 100644 index 5176b4a8..00000000 --- a/engine/csharp_ref/AstroCalc/AASaturn.cs +++ /dev/null @@ -1,245 +0,0 @@ -using System; -public static partial class GFX -{ - - public static VSC[] g_L0SaturnCoefficients = { new VSC(87401354, 0, 0), new VSC(11107660, 3.96205090, 213.29909544), new VSC(1414151, 4.5858152, 7.1135470), new VSC(398379, 0.521120, 206.185548), new VSC(350769, 3.303299, 426.598191), new VSC(206816, 0.246584, 103.092774), new VSC(79271, 3.84007, 220.41264), new VSC(23990, 4.66977, 110.20632), new VSC(16574, 0.43719, 419.48464), new VSC(15820, 0.93809, 632.78374), new VSC(15054, 2.71670, 639.89729), new VSC(14907, 5.76903, 316.39187), new VSC(14610, 1.56519, 3.93215), new VSC(13160, 4.44891, 14.22709), new VSC(13005, 5.98119, 11.04570), new VSC(10725, 3.12940, 202.25340), new VSC(6126, 1.7633, 277.0350), new VSC(5863, 0.2366, 529.6910), new VSC(5228, 4.2078, 3.1814), new VSC(5020, 3.1779, 433.7117), new VSC(4593, 0.6198, 199.0720), new VSC(4006, 2.2448, 63.7359), new VSC(3874, 3.2228, 138.5175), new VSC(3269, 0.7749, 949.1756), new VSC(2954, 0.9828, 95.9792), new VSC(2461, 2.0316, 735.8765), new VSC(1758, 3.2658, 522.5774), new VSC(1640, 5.5050, 846.0828), new VSC(1581, 4.3727, 309.2783), new VSC(1391, 4.0233, 323.5054), new VSC(1124, 2.8373, 415.5525), new VSC(1087, 4.1834, 2.4477), new VSC(1017, 3.7170, 227.5262), new VSC(957, 0.507, 1265.567), new VSC(853, 3.421, 175.166), new VSC(849, 3.191, 209.367), new VSC(789, 5.007, 0.963), new VSC(749, 2.144, 853.196), new VSC(744, 5.253, 224.345), new VSC(687, 1.747, 1052.268), new VSC(654, 1.599, 0.048), new VSC(634, 2.299, 412.371), new VSC(625, 0.970, 210.118), new VSC(580, 3.093, 74.782), new VSC(546, 2.127, 350.332), new VSC(543, 1.518, 9.561), new VSC(530, 4.449, 117.320), new VSC(478, 2.965, 137.033), new VSC(474, 5.475, 742.990), new VSC(452, 1.044, 490.334), new VSC(449, 1.290, 127.472), new VSC(372, 2.278, 217.231), new VSC(355, 3.013, 838.969), new VSC(347, 1.539, 340.771), new VSC(343, 0.246, 0.521), new VSC(330, 0.247, 1581.959), new VSC(322, 0.961, 203.738), new VSC(322, 2.572, 647.011), new VSC(309, 3.495, 216.480), new VSC(287, 2.370, 351.817), new VSC(278, 0.400, 211.815), new VSC(249, 1.470, 1368.660), new VSC(227, 4.910, 12.530), new VSC(220, 4.204, 200.769), new VSC(209, 1.345, 625.670), new VSC(208, 0.483, 1162.475), new VSC(208, 1.283, 39.357), new VSC(204, 6.011, 265.989), new VSC(185, 3.503, 149.563), new VSC(184, 0.973, 4.193), new VSC(182, 5.491, 2.921), new VSC(174, 1.863, 0.751), new VSC(165, 0.440, 5.417), new VSC(149, 5.736, 52.690), new VSC(148, 1.535, 5.629), new VSC(146, 6.231, 195.140), new VSC(140, 4.295, 21.341), new VSC(131, 4.068, 10.295), new VSC(125, 6.277, 1898.351), new VSC(122, 1.976, 4.666), new VSC(118, 5.341, 554.070), new VSC(117, 2.679, 1155.361), new VSC(114, 5.594, 1059.382), new VSC(112, 1.105, 191.208), new VSC(110, 0.166, 1.484), new VSC(109, 3.438, 536.805), new VSC(107, 4.012, 956.289), new VSC(104, 2.192, 88.866), new VSC(103, 1.197, 1685.052), new VSC(101, 4.965, 269.921) }; - - public static VSC[] g_L1SaturnCoefficients = { new VSC(21354295596.0, 0, 0), new VSC(1296855, 1.8282054, 213.2990954), new VSC(564348, 2.885001, 7.113547), new VSC(107679, 2.277699, 206.185548), new VSC(98323, 1.08070, 426.59819), new VSC(40255, 2.04128, 220.41264), new VSC(19942, 1.27955, 103.09277), new VSC(10512, 2.74880, 14.22709), new VSC(6939, 0.4049, 639.8973), new VSC(4803, 2.4419, 419.4846), new VSC(4056, 2.9217, 110.2063), new VSC(3769, 3.6497, 3.9322), new VSC(3385, 2.4169, 3.1814), new VSC(3302, 1.2626, 433.7117), new VSC(3071, 2.3274, 199.0720), new VSC(1953, 3.5639, 11.0457), new VSC(1249, 2.6280, 95.9792), new VSC(922, 1.961, 227.526), new VSC(706, 4.417, 529.691), new VSC(650, 6.174, 202.253), new VSC(628, 6.111, 309.278), new VSC(487, 6.040, 853.196), new VSC(479, 4.988, 522.577), new VSC(468, 4.617, 63.736), new VSC(417, 2.117, 323.505), new VSC(408, 1.299, 209.367), new VSC(352, 2.317, 632.784), new VSC(344, 3.959, 412.371), new VSC(340, 3.634, 316.392), new VSC(336, 3.772, 735.877), new VSC(332, 2.861, 210.118), new VSC(289, 2.733, 117.320), new VSC(281, 5.744, 2.448), new VSC(266, 0.543, 647.011), new VSC(230, 1.644, 216.480), new VSC(192, 2.965, 224.345), new VSC(173, 4.077, 846.083), new VSC(167, 2.597, 21.341), new VSC(136, 2.286, 10.295), new VSC(131, 3.441, 742.990), new VSC(128, 4.095, 217.231), new VSC(109, 6.161, 415.552), new VSC(98, 4.73, 838.97), new VSC(94, 3.48, 1052.27), new VSC(92, 3.95, 88.87), new VSC(87, 1.22, 440.83), new VSC(83, 3.11, 625.67), new VSC(78, 6.24, 302.16), new VSC(67, 0.29, 4.67), new VSC(66, 5.65, 9.56), new VSC(62, 4.29, 127.47), new VSC(62, 1.83, 195.14), new VSC(58, 2.48, 191.96), new VSC(57, 5.02, 137.03), new VSC(55, 0.28, 74.78), new VSC(54, 5.13, 490.33), new VSC(51, 1.46, 536.80), new VSC(47, 1.18, 149.56), new VSC(47, 5.15, 515.46), new VSC(46, 2.23, 956.29), new VSC(44, 2.71, 5.42), new VSC(40, 0.41, 269.92), new VSC(40, 3.89, 728.76), new VSC(38, 0.65, 422.67), new VSC(38, 2.53, 12.53), new VSC(37, 3.78, 2.92), new VSC(35, 6.08, 5.63), new VSC(34, 3.21, 1368.66), new VSC(33, 4.64, 277.03), new VSC(33, 5.43, 1066.50), new VSC(33, 0.30, 351.82), new VSC(32, 4.39, 1155.36), new VSC(31, 2.43, 52.69), new VSC(30, 2.84, 203.00), new VSC(30, 6.19, 284.15), new VSC(30, 3.39, 1059.38), new VSC(29, 2.03, 330.62), new VSC(28, 2.74, 265.99), new VSC(26, 4.51, 340.77) }; - - public static VSC[] g_L2SaturnCoefficients = { new VSC(116441, 1.179879, 7.113547), new VSC(91921, 0.07425, 213.29910), new VSC(90592, 0, 0), new VSC(15277, 4.06492, 206.18555), new VSC(10631, 0.25778, 220.41264), new VSC(10605, 5.40964, 426.59819), new VSC(4265, 1.0460, 14.2271), new VSC(1216, 2.9186, 103.0928), new VSC(1165, 4.6094, 639.8973), new VSC(1082, 5.6913, 433.7117), new VSC(1045, 4.0421, 199.0720), new VSC(1020, 0.6337, 3.1814), new VSC(634, 4.388, 419.485), new VSC(549, 5.573, 3.932), new VSC(457, 1.268, 110.206), new VSC(425, 0.209, 227.526), new VSC(274, 4.288, 95.979), new VSC(162, 1.381, 11.046), new VSC(129, 1.566, 309.278), new VSC(117, 3.881, 853.196), new VSC(105, 4.900, 647.011), new VSC(101, 0.893, 21.341), new VSC(96, 2.91, 316.39), new VSC(95, 5.63, 412.37), new VSC(85, 5.73, 209.37), new VSC(83, 6.05, 216.48), new VSC(82, 1.02, 117.32), new VSC(75, 4.76, 210.12), new VSC(67, 0.46, 522.58), new VSC(66, 0.48, 10.29), new VSC(64, 0.35, 323.51), new VSC(61, 4.88, 632.78), new VSC(53, 2.75, 529.69), new VSC(46, 5.69, 440.83), new VSC(45, 1.67, 202.25), new VSC(42, 5.71, 88.87), new VSC(32, 0.07, 63.74), new VSC(32, 1.67, 302.16), new VSC(31, 4.16, 191.96), new VSC(27, 0.83, 224.34), new VSC(25, 5.66, 735.88), new VSC(20, 5.94, 217.23), new VSC(18, 4.90, 625.67), new VSC(17, 1.63, 742.99), new VSC(16, 0.58, 515.46), new VSC(14, 0.21, 838.97), new VSC(14, 3.76, 195.14), new VSC(12, 4.72, 203.00), new VSC(12, 0.13, 234.64), new VSC(12, 3.12, 846.08), new VSC(11, 5.92, 536.80), new VSC(11, 5.60, 728.76), new VSC(11, 3.20, 1066.50), new VSC(10, 4.99, 422.67), new VSC(10, 0.26, 330.62), new VSC(10, 4.15, 860.31), new VSC(9, 0.46, 956.29), new VSC(8, 2.14, 269.92), new VSC(8, 5.25, 429.78), new VSC(8, 4.03, 9.56), new VSC(7, 5.40, 1052.27), new VSC(6, 4.46, 284.15), new VSC(6, 5.93, 405.26) }; - - public static VSC[] g_L3SaturnCoefficients = { new VSC(16039, 5.73945, 7.11355), new VSC(4250, 4.5854, 213.2991), new VSC(1907, 4.7608, 220.4126), new VSC(1466, 5.9133, 206.1855), new VSC(1162, 5.6197, 14.2271), new VSC(1067, 3.6082, 426.5982), new VSC(239, 3.861, 433.712), new VSC(237, 5.768, 199.072), new VSC(166, 5.116, 3.181), new VSC(151, 2.736, 639.897), new VSC(131, 4.743, 227.526), new VSC(63, 0.23, 419.48), new VSC(62, 4.74, 103.09), new VSC(40, 5.47, 21.34), new VSC(40, 5.96, 95.98), new VSC(39, 5.83, 110.21), new VSC(28, 3.01, 647.01), new VSC(25, 0.99, 3.93), new VSC(19, 1.92, 853.20), new VSC(18, 4.97, 10.29), new VSC(18, 1.03, 412.37), new VSC(18, 4.20, 216.48), new VSC(18, 3.32, 309.28), new VSC(16, 3.90, 440.83), new VSC(16, 5.62, 117.32), new VSC(13, 1.18, 88.87), new VSC(11, 5.58, 11.05), new VSC(11, 5.93, 191.96), new VSC(10, 3.95, 209.37), new VSC(9, 3.39, 302.16), new VSC(8, 4.88, 323.51), new VSC(7, 0.38, 632.78), new VSC(6, 2.25, 522.58), new VSC(6, 1.06, 210.12), new VSC(5, 4.64, 234.64), new VSC(4, 3.14, 0), new VSC(4, 2.31, 515.46), new VSC(3, 2.20, 860.31), new VSC(3, 0.59, 529.69), new VSC(3, 4.93, 224.34), new VSC(3, 0.42, 625.67), new VSC(2, 4.77, 330.62), new VSC(2, 3.35, 429.78), new VSC(2, 3.20, 202.25), new VSC(2, 1.19, 1066.50), new VSC(2, 1.35, 405.26), new VSC(2, 4.16, 223.59), new VSC(2, 3.07, 654.12) }; - - public static VSC[] g_L4SaturnCoefficients = { new VSC(1662, 3.9983, 7.1135), new VSC(257, 2.984, 220.413), new VSC(236, 3.902, 14.227), new VSC(149, 2.741, 213.299), new VSC(114, 3.142, 0), new VSC(110, 1.515, 206.186), new VSC(68, 1.72, 426.60), new VSC(40, 2.05, 433.71), new VSC(38, 1.24, 199.07), new VSC(31, 3.01, 227.53), new VSC(15, 0.83, 639.90), new VSC(9, 3.71, 21.34), new VSC(6, 2.42, 419.48), new VSC(6, 1.16, 647.01), new VSC(4, 1.45, 95.98), new VSC(4, 2.12, 440.83), new VSC(3, 4.09, 110.21), new VSC(3, 2.77, 412.37), new VSC(3, 3.01, 88.87), new VSC(3, 0.00, 853.20), new VSC(3, 0.39, 103.09), new VSC(2, 3.78, 117.32), new VSC(2, 2.83, 234.64), new VSC(2, 5.08, 309.28), new VSC(2, 2.24, 216.48), new VSC(2, 5.19, 302.16), new VSC(1, 1.55, 191.96) }; - - public static VSC[] g_L5SaturnCoefficients = { new VSC(124, 2.259, 7.114), new VSC(34, 2.16, 14.23), new VSC(28, 1.20, 220.41), new VSC(6, 1.22, 227.53), new VSC(5, 0.24, 433.71), new VSC(4, 6.23, 426.60), new VSC(3, 2.97, 199.07), new VSC(3, 4.29, 206.19), new VSC(2, 6.25, 213.30), new VSC(1, 5.28, 639.90), new VSC(1, 0.24, 440.83), new VSC(1, 3.14, 0) }; - - public static VSC[] g_B0SaturnCoefficients = { new VSC(4330678, 3.6028443, 213.2990954), new VSC(240348, 2.852385, 426.598191), new VSC(84746, 0, 0), new VSC(34116, 0.57297, 206.18555), new VSC(30863, 3.48442, 220.41264), new VSC(14734, 2.11847, 639.89729), new VSC(9917, 5.7900, 419.4846), new VSC(6994, 4.7360, 7.1135), new VSC(4808, 5.4331, 316.3919), new VSC(4788, 4.9651, 110.2063), new VSC(3432, 2.7326, 433.7117), new VSC(1506, 6.0130, 103.0928), new VSC(1060, 5.6310, 529.6910), new VSC(969, 5.204, 632.784), new VSC(942, 1.396, 853.196), new VSC(708, 3.803, 323.505), new VSC(552, 5.131, 202.253), new VSC(400, 3.359, 227.526), new VSC(319, 3.626, 209.367), new VSC(316, 1.997, 647.011), new VSC(314, 0.465, 217.231), new VSC(284, 4.886, 224.345), new VSC(236, 2.139, 11.046), new VSC(215, 5.950, 846.083), new VSC(209, 2.120, 415.552), new VSC(207, 0.730, 199.072), new VSC(179, 2.954, 63.736), new VSC(141, 0.644, 490.334), new VSC(139, 4.595, 14.227), new VSC(139, 1.998, 735.877), new VSC(135, 5.245, 742.990), new VSC(122, 3.115, 522.577), new VSC(116, 3.109, 216.480), new VSC(114, 0.963, 210.118) }; - - public static VSC[] g_B1SaturnCoefficients = { new VSC(397555, 5.332900, 213.299095), new VSC(49479, 3.14159, 0), new VSC(18572, 6.09919, 426.59819), new VSC(14801, 2.30586, 206.18555), new VSC(9644, 1.6967, 220.4126), new VSC(3757, 1.2543, 419.4846), new VSC(2717, 5.9117, 639.8973), new VSC(1455, 0.8516, 433.7117), new VSC(1291, 2.9177, 7.1135), new VSC(853, 0.436, 316.392), new VSC(298, 0.919, 632.784), new VSC(292, 5.316, 853.196), new VSC(284, 1.619, 227.526), new VSC(275, 3.889, 103.093), new VSC(172, 0.052, 647.011), new VSC(166, 2.444, 199.072), new VSC(158, 5.209, 110.206), new VSC(128, 1.207, 529.691), new VSC(110, 2.457, 217.231), new VSC(82, 2.76, 210.12), new VSC(81, 2.86, 14.23), new VSC(69, 1.66, 202.25), new VSC(65, 1.26, 216.48), new VSC(61, 1.25, 209.37), new VSC(59, 1.82, 323.51), new VSC(46, 0.82, 440.83), new VSC(36, 1.82, 224.34), new VSC(34, 2.84, 117.32), new VSC(33, 1.31, 412.37), new VSC(32, 1.19, 846.08), new VSC(27, 4.65, 1066.50), new VSC(27, 4.44, 11.05) }; - - public static VSC[] g_B2SaturnCoefficients = { new VSC(20630, 0.50482, 213.29910), new VSC(3720, 3.9983, 206.1855), new VSC(1627, 6.1819, 220.4126), new VSC(1346, 0, 0), new VSC(706, 3.039, 419.485), new VSC(365, 5.099, 426.598), new VSC(330, 5.279, 433.712), new VSC(219, 3.828, 639.897), new VSC(139, 1.043, 7.114), new VSC(104, 6.157, 227.526), new VSC(93, 1.98, 316.39), new VSC(71, 4.15, 199.07), new VSC(52, 2.88, 632.78), new VSC(49, 4.43, 647.01), new VSC(41, 3.16, 853.20), new VSC(29, 4.53, 210.12), new VSC(24, 1.12, 14.23), new VSC(21, 4.35, 217.23), new VSC(20, 5.31, 440.83), new VSC(18, 0.85, 110.21), new VSC(17, 5.68, 216.48), new VSC(16, 4.26, 103.09), new VSC(14, 3.00, 412.37), new VSC(12, 2.53, 529.69), new VSC(8, 3.32, 202.25), new VSC(7, 5.56, 209.37), new VSC(7, 0.29, 323.51), new VSC(6, 1.16, 117.32), new VSC(6, 3.61, 869.31) }; - - public static VSC[] g_B3SaturnCoefficients = { new VSC(666, 1.990, 213.299), new VSC(632, 5.698, 206.186), new VSC(398, 0, 0), new VSC(188, 4.338, 220.413), new VSC(92, 4.84, 419.48), new VSC(52, 3.42, 433.71), new VSC(42, 2.38, 426.60), new VSC(26, 4.40, 227.53), new VSC(21, 5.85, 199.07), new VSC(18, 1.99, 639.90), new VSC(11, 5.37, 7.11), new VSC(10, 2.55, 647.01), new VSC(7, 3.46, 316.39), new VSC(6, 4.80, 632.78), new VSC(6, 0.02, 210.12), new VSC(6, 3.52, 440.83), new VSC(5, 5.64, 14.23), new VSC(5, 1.22, 853.20), new VSC(4, 4.71, 412.37), new VSC(3, 0.63, 103.09), new VSC(2, 3.72, 216.48) }; - - - public static VSC[] g_B4SaturnCoefficients = { new VSC(80, 1.12, 206.19), new VSC(32, 3.12, 213.30), new VSC(17, 2.48, 220.41), new VSC(12, 3.14, 0), new VSC(9, 0.38, 419.48), new VSC(6, 1.56, 433.71), new VSC(5, 2.63, 227.53), new VSC(5, 1.28, 199.07), new VSC(1, 1.43, 426.60), new VSC(1, 0.67, 647.01), new VSC(1, 1.72, 440.83), new VSC(1, 6.18, 639.90) }; - - public static VSC[] g_B5SaturnCoefficients = { new VSC(8, 2.82, 206.19), new VSC(1, 0.51, 220.41) }; - - public static VSC[] g_R0SaturnCoefficients = { new VSC(955758136, 0, 0), new VSC(52921382, 2.39226220, 213.29909544), new VSC(1873680, 5.2354961, 206.1855484), new VSC(1464664, 1.6476305, 426.5981909), new VSC(821891, 5.935200, 316.391870), new VSC(547507, 5.015326, 103.092774), new VSC(371684, 2.271148, 220.412642), new VSC(361778, 3.139043, 7.113547), new VSC(140618, 5.704067, 632.783739), new VSC(108975, 3.293136, 110.206321), new VSC(69007, 5.94100, 419.48464), new VSC(61053, 0.94038, 639.89729), new VSC(48913, 1.55733, 202.25340), new VSC(34144, 0.19519, 277.03499), new VSC(32402, 5.47085, 949.17561), new VSC(20937, 0.46349, 735.87651), new VSC(20839, 1.52103, 433.71174), new VSC(20747, 5.33256, 199.07200), new VSC(15298, 3.05944, 529.69097), new VSC(14296, 2.60434, 323.50542), new VSC(12884, 1.64892, 138.51750), new VSC(11993, 5.98051, 846.08283), new VSC(11380, 1.73106, 522.57742), new VSC(9796, 5.2048, 1265.5675), new VSC(7753, 5.8519, 95.9792), new VSC(6771, 3.0043, 14.2271), new VSC(6466, 0.1773, 1052.2684), new VSC(5850, 1.4552, 415.5525), new VSC(5307, 0.5974, 63.7359), new VSC(4696, 2.1492, 227.5262), new VSC(4044, 1.6401, 209.3669), new VSC(3688, 0.7802, 412.3711), new VSC(3461, 1.8509, 175.1661), new VSC(3420, 4.9455, 1581.9593), new VSC(3401, 0.5539, 350.3321), new VSC(3376, 3.6953, 224.3448), new VSC(2976, 5.6847, 210.1177), new VSC(2885, 1.3876, 838.9693), new VSC(2881, 0.1796, 853.1964), new VSC(2508, 3.5385, 742.9901), new VSC(2448, 6.1841, 1368.6603), new VSC(2406, 2.9656, 117.3199), new VSC(2174, 0.0151, 340.7709), new VSC(2024, 5.0541, 11.0457) }; - - public static VSC[] g_R1SaturnCoefficients = { new VSC(6182981, 0.2584352, 213.2990954), new VSC(506578, 0.711147, 206.185548), new VSC(341394, 5.796358, 426.598191), new VSC(188491, 0.472157, 220.412642), new VSC(186262, 3.141593, 0), new VSC(143891, 1.407449, 7.113547), new VSC(49621, 6.01744, 103.09277), new VSC(20928, 5.09246, 639.89729), new VSC(19953, 1.17560, 419.48464), new VSC(18840, 1.60820, 110.20632), new VSC(13877, 0.75886, 199.07200), new VSC(12893, 5.94330, 433.71174), new VSC(5397, 1.2885, 14.2271), new VSC(4869, 0.8679, 323.5054), new VSC(4247, 0.3930, 227.5262), new VSC(3252, 1.2585, 95.9792), new VSC(3081, 3.4366, 522.5774), new VSC(2909, 4.6068, 202.2534), new VSC(2856, 2.1673, 735.8765), new VSC(1988, 2.4505, 412.3711), new VSC(1941, 6.0239, 209.3669), new VSC(1581, 1.2919, 210.1177), new VSC(1340, 4.3080, 853.1964), new VSC(1316, 1.2530, 117.3199), new VSC(1203, 1.8665, 316.3919), new VSC(1091, 0.0753, 216.4805), new VSC(966, 0.480, 632.784), new VSC(954, 5.152, 647.011), new VSC(898, 0.983, 529.691), new VSC(882, 1.885, 1052.268), new VSC(874, 1.402, 224.345), new VSC(785, 3.064, 838.969), new VSC(740, 1.382, 625.670), new VSC(658, 4.144, 309.278), new VSC(650, 1.725, 742.990), new VSC(613, 3.033, 63.736), new VSC(599, 2.549, 217.231), new VSC(503, 2.130, 3.932) }; - - public static VSC[] g_R2SaturnCoefficients = { new VSC(436902, 4.786717, 213.299095), new VSC(71923, 2.50070, 206.18555), new VSC(49767, 4.97168, 220.41264), new VSC(43221, 3.86940, 426.59819), new VSC(29646, 5.96310, 7.11355), new VSC(4721, 2.4753, 199.0720), new VSC(4142, 4.1067, 433.7117), new VSC(3789, 3.0977, 639.8973), new VSC(2964, 1.3721, 103.0928), new VSC(2556, 2.8507, 419.4846), new VSC(2327, 0, 0), new VSC(2208, 6.2759, 110.2063), new VSC(2188, 5.8555, 14.2271), new VSC(1957, 4.9245, 227.5262), new VSC(924, 5.464, 323.505), new VSC(706, 2.971, 95.979), new VSC(546, 4.129, 412.371), new VSC(431, 5.178, 522.577), new VSC(405, 4.173, 209.367), new VSC(391, 4.481, 216.480), new VSC(374, 5.834, 117.320), new VSC(361, 3.277, 647.011), new VSC(356, 3.192, 210.118), new VSC(326, 2.269, 853.196), new VSC(207, 4.022, 735.877), new VSC(204, 0.088, 202.253), new VSC(180, 3.597, 632.784), new VSC(178, 4.097, 440.825), new VSC(154, 3.135, 625.670), new VSC(148, 0.136, 302.165), new VSC(133, 2.594, 191.958), new VSC(132, 5.933, 309.278) }; - - public static VSC[] g_R3SaturnCoefficients = { new VSC(20315, 3.02187, 213.29910), new VSC(8924, 3.1914, 220.4126), new VSC(6909, 4.3517, 206.1855), new VSC(4087, 4.2241, 7.1135), new VSC(3879, 2.0106, 426.5982), new VSC(1071, 4.2036, 199.0720), new VSC(907, 2.283, 433.712), new VSC(606, 3.175, 227.526), new VSC(597, 4.135, 14.227), new VSC(483, 1.173, 639.897), new VSC(393, 0, 0), new VSC(229, 4.698, 419.485), new VSC(188, 4.590, 110.206), new VSC(150, 3.202, 103.093), new VSC(121, 3.768, 323.505), new VSC(102, 4.710, 95.979), new VSC(101, 5.819, 412.371), new VSC(93, 1.44, 647.01), new VSC(84, 2.63, 216.48), new VSC(73, 4.15, 117.32), new VSC(62, 2.31, 440.83), new VSC(55, 0.31, 853.20), new VSC(50, 2.39, 209.37), new VSC(45, 4.37, 191.96), new VSC(41, 0.69, 522.58), new VSC(40, 1.84, 302.16), new VSC(38, 5.94, 88.87), new VSC(32, 4.01, 21.34) }; - - public static VSC[] g_R4SaturnCoefficients = { new VSC(1202, 1.4150, 220.4126), new VSC(708, 1.162, 213.299), new VSC(516, 6.240, 206.186), new VSC(427, 2.469, 7.114), new VSC(268, 0.187, 426.598), new VSC(170, 5.959, 199.072), new VSC(150, 0.480, 433.712), new VSC(145, 1.442, 227.526), new VSC(121, 2.405, 14.227), new VSC(47, 5.57, 639.90), new VSC(19, 5.86, 647.01), new VSC(17, 0.53, 440.83), new VSC(16, 2.90, 110.21), new VSC(15, 0.30, 419.48), new VSC(14, 1.30, 412.37), new VSC(13, 2.09, 323.51), new VSC(11, 0.22, 95.98), new VSC(11, 2.46, 117.32), new VSC(10, 3.14, 0), new VSC(9, 1.56, 88.87), new VSC(9, 2.28, 21.34), new VSC(9, 0.68, 216.48), new VSC(8, 1.27, 234.64) }; - - public static VSC[] g_R5SaturnCoefficients = { new VSC(129, 5.913, 220.413), new VSC(32, 0.69, 7.11), new VSC(27, 5.91, 227.53), new VSC(20, 4.95, 433.71), new VSC(20, 0.67, 14.23), new VSC(14, 2.67, 206.19), new VSC(14, 1.46, 199.07), new VSC(13, 4.59, 426.60), new VSC(7, 4.63, 213.30), new VSC(5, 3.61, 639.90), new VSC(4, 4.90, 440.83), new VSC(3, 4.07, 647.01), new VSC(3, 4.66, 191.96), new VSC(3, 0.49, 323.51), new VSC(3, 3.18, 419.48), new VSC(2, 3.70, 88.87), new VSC(2, 3.32, 95.98), new VSC(2, 0.56, 117.32) }; -} -// -//Module : AASATURN.CPP -//Purpose: Implementation for the algorithms which obtain the heliocentric position of Saturn -//Created: PJN / 29-12-2003 -//History: PJN / 31-05-2004 1) In CAASaturn::EclipticLongitude the g_L5SaturnCoefficients[] were -// not included. Thanks to Brian Orme for reporting this problem. -// 2) In CAASaturn::EclipticLatitude the g_B5SaturnCoefficients[] were -// not included. Thanks to Brian Orme for reporting this problem. -// 3) In CAASaturn::RadiusVector the g_R5SaturnCoefficients[] were not -// included. Thanks to Brian Orme for reporting this problem. -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////// Includes //////////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAASaturn -{ -//Static methods - - ///////////////////////////// Implementation ////////////////////////////////// - - public static double EclipticLongitude(double JD) - { - double rho = (JD - 2451545) / 365250; - double rhosquared = rho *rho; - double rhocubed = rhosquared *rho; - double rho4 = rhocubed *rho; - double rho5 = rho4 *rho; - - //Calculate L0 - int nL0Coefficients = GFX.g_L0SaturnCoefficients.Length; - double L0 = 0; - int i; - for (i =0; i 2E-6); //2E-6 corresponds to 0.17 of a second - if (bIterate) - { - JD1 = JD - EarthLightTravelTime; - PreviousEarthLightTravelTime = EarthLightTravelTime; - } - } - - //Calculate the details as seen from the earth - CAASaturnMoonsDetails details1 = CalculateHelper(JD, sunlongrad, betarad, R); - FillInPhenomenaDetails(ref details1.Satellite1); - FillInPhenomenaDetails(ref details1.Satellite2); - FillInPhenomenaDetails(ref details1.Satellite3); - FillInPhenomenaDetails(ref details1.Satellite4); - FillInPhenomenaDetails(ref details1.Satellite5); - FillInPhenomenaDetails(ref details1.Satellite6); - FillInPhenomenaDetails(ref details1.Satellite7); - FillInPhenomenaDetails(ref details1.Satellite8); - - //Calculate the the light travel time from Saturn to the Sun - JD1 = JD - EarthLightTravelTime; - l = CAASaturn.EclipticLongitude(JD1); - lrad = CAACoordinateTransformation.DegreesToRadians(l); - b = CAASaturn.EclipticLatitude(JD1); - brad = CAACoordinateTransformation.DegreesToRadians(b); - r = CAASaturn.RadiusVector(JD1); - x = r * Math.Cos(brad) * Math.Cos(lrad); - y = r * Math.Cos(brad) * Math.Sin(lrad); - z = r * Math.Sin(brad); - DELTA = Math.Sqrt(x * x + y * y + z * z); - double SunLightTravelTime = CAAElliptical.DistanceToLightTime(DELTA); - - //Calculate the details as seen from the Sun - CAASaturnMoonsDetails details2 = CalculateHelper(JD + SunLightTravelTime - EarthLightTravelTime, sunlongrad, betarad, 0); - FillInPhenomenaDetails(ref details2.Satellite1); - FillInPhenomenaDetails(ref details2.Satellite2); - FillInPhenomenaDetails(ref details2.Satellite3); - FillInPhenomenaDetails(ref details2.Satellite4); - FillInPhenomenaDetails(ref details2.Satellite5); - FillInPhenomenaDetails(ref details2.Satellite6); - FillInPhenomenaDetails(ref details2.Satellite7); - FillInPhenomenaDetails(ref details2.Satellite8); - - //Finally transfer the required values from details2 to details1 - details1.Satellite1.bInEclipse = details2.Satellite1.bInOccultation; - details1.Satellite2.bInEclipse = details2.Satellite2.bInOccultation; - details1.Satellite3.bInEclipse = details2.Satellite3.bInOccultation; - details1.Satellite4.bInEclipse = details2.Satellite4.bInOccultation; - details1.Satellite5.bInEclipse = details2.Satellite5.bInOccultation; - details1.Satellite6.bInEclipse = details2.Satellite6.bInOccultation; - details1.Satellite7.bInEclipse = details2.Satellite7.bInOccultation; - details1.Satellite8.bInEclipse = details2.Satellite8.bInOccultation; - details1.Satellite1.bInShadowTransit = details2.Satellite1.bInTransit; - details1.Satellite2.bInShadowTransit = details2.Satellite2.bInTransit; - details1.Satellite3.bInShadowTransit = details2.Satellite3.bInTransit; - details1.Satellite4.bInShadowTransit = details2.Satellite4.bInTransit; - details1.Satellite5.bInShadowTransit = details2.Satellite5.bInTransit; - details1.Satellite6.bInShadowTransit = details2.Satellite6.bInTransit; - details1.Satellite7.bInShadowTransit = details2.Satellite7.bInTransit; - details1.Satellite8.bInShadowTransit = details2.Satellite8.bInTransit; - - return details1; - } - - protected static CAASaturnMoonsDetails CalculateHelper(double JD, double sunlongrad, double betarad, double R) - { - //What will be the return value - CAASaturnMoonsDetails details = new CAASaturnMoonsDetails(); - - //Calculate the position of Saturn decreased by the light travel time from Saturn to the specified position - double DELTA = 9; - double PreviousLightTravelTime = 0; - double LightTravelTime = CAAElliptical.DistanceToLightTime(DELTA); - double x = 0; - double y = 0; - double z = 0; - double l = 0; - double lrad = 0; - double b = 0; - double brad = 0; - double r = 0; - double JD1 = JD - LightTravelTime; - bool bIterate = true; - while (bIterate) - { - //Calculate the position of Saturn - l = CAASaturn.EclipticLongitude(JD1); - lrad = CAACoordinateTransformation.DegreesToRadians(l); - b = CAASaturn.EclipticLatitude(JD1); - brad = CAACoordinateTransformation.DegreesToRadians(b); - r = CAASaturn.RadiusVector(JD1); - - x = r *Math.Cos(brad)*Math.Cos(lrad) + R *Math.Cos(sunlongrad); - y = r *Math.Cos(brad)*Math.Sin(lrad) + R *Math.Sin(sunlongrad); - z = r *Math.Sin(brad) + R *Math.Sin(betarad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - LightTravelTime = CAAElliptical.DistanceToLightTime(DELTA); - - //Prepare for the next loop around - bIterate = (Math.Abs(LightTravelTime - PreviousLightTravelTime) > 2E-6); //2E-6 corresponds to 0.17 of a second - if (bIterate) - { - JD1 = JD - LightTravelTime; - PreviousLightTravelTime = LightTravelTime; - } - } - - //Calculate Saturn's Longitude and Latitude - double lambda0 = Math.Atan2(y, x); - lambda0 = CAACoordinateTransformation.RadiansToDegrees(lambda0); - double beta0 = Math.Atan(z/Math.Sqrt(x *x + y *y)); - beta0 = CAACoordinateTransformation.RadiansToDegrees(beta0); - - //Precess the longtitude and Latitutude to B1950.0 - CAA2DCoordinate Saturn1950 = CAAPrecession.PrecessEcliptic(lambda0, beta0, JD, 2433282.4235); - lambda0 = Saturn1950.X; - double lambda0rad = CAACoordinateTransformation.DegreesToRadians(lambda0); - beta0 = Saturn1950.Y; - double beta0rad = CAACoordinateTransformation.DegreesToRadians(beta0); - - double JDE = JD - LightTravelTime; - - double t1 = JDE - 2411093.0; - double t2 = t1/365.25; - double t3 = ((JDE - 2433282.423)/365.25) + 1950.0; - double t4 = JDE - 2411368.0; - double t5 = t4/365.25; - double t6 = JDE - 2415020.0; - double t7 = t6/36525.0; - double t8 = t6/365.25; - double t9 = (JDE - 2442000.5)/365.25; - double t10 = JDE - 2409786.0; - double t11 = t10/36525.0; - double t112 = t11 *t11; - double t113 = t112 *t11; - - double W0 = CAACoordinateTransformation.MapTo0To360Range(5.095*(t3 - 1866.39)); - double W0rad = CAACoordinateTransformation.DegreesToRadians(W0); - double W1 = CAACoordinateTransformation.MapTo0To360Range(74.4 + 32.39 *t2); - double W1rad = CAACoordinateTransformation.DegreesToRadians(W1); - double W2 = CAACoordinateTransformation.MapTo0To360Range(134.3 + 92.62 *t2); - double W2rad = CAACoordinateTransformation.DegreesToRadians(W2); - double W3 = CAACoordinateTransformation.MapTo0To360Range(42.0 - 0.5118 *t5); - double W3rad = CAACoordinateTransformation.DegreesToRadians(W3); - double W4 = CAACoordinateTransformation.MapTo0To360Range(276.59 + 0.5118 *t5); - double W4rad = CAACoordinateTransformation.DegreesToRadians(W4); - double W5 = CAACoordinateTransformation.MapTo0To360Range(267.2635 + 1222.1136 *t7); - double W5rad = CAACoordinateTransformation.DegreesToRadians(W5); - double W6 = CAACoordinateTransformation.MapTo0To360Range(175.4762 + 1221.5515 *t7); - double W6rad = CAACoordinateTransformation.DegreesToRadians(W6); - double W7 = CAACoordinateTransformation.MapTo0To360Range(2.4891 + 0.002435 *t7); - double W7rad = CAACoordinateTransformation.DegreesToRadians(W7); - double W8 = CAACoordinateTransformation.MapTo0To360Range(113.35 - 0.2597 *t7); - double W8rad = CAACoordinateTransformation.DegreesToRadians(W8); - - double s1 = Math.Sin(CAACoordinateTransformation.DegreesToRadians(28.0817)); - double s2 = Math.Sin(CAACoordinateTransformation.DegreesToRadians(168.8112)); - double c1 = Math.Cos(CAACoordinateTransformation.DegreesToRadians(28.0817)); - double c2 = Math.Cos(CAACoordinateTransformation.DegreesToRadians(168.8112)); - double e1 = 0.05589 - 0.000346 *t7; - - - //Satellite 1 - double L = CAACoordinateTransformation.MapTo0To360Range(127.64 + 381.994497 *t1 - 43.57 *Math.Sin(W0rad) - 0.720 *Math.Sin(3 *W0rad) - 0.02144 *Math.Sin(5 *W0rad)); - double p = 106.1 + 365.549 *t2; - double M = L - p; - double Mrad = CAACoordinateTransformation.DegreesToRadians(M); - double C = 2.18287 *Math.Sin(Mrad) + 0.025988 *Math.Sin(2 *Mrad) + 0.00043 *Math.Sin(3 *Mrad); - double Crad = CAACoordinateTransformation.DegreesToRadians(C); - double lambda1 = CAACoordinateTransformation.MapTo0To360Range(L + C); - double r1 = 3.06879/(1 + 0.01905 *Math.Cos(Mrad + Crad)); - double gamma1 = 1.563; - double omega1 = CAACoordinateTransformation.MapTo0To360Range(54.5 - 365.072 *t2); - - //Satellite 2 - L = CAACoordinateTransformation.MapTo0To360Range(200.317 + 262.7319002 *t1 + 0.25667 *Math.Sin(W1rad) + 0.20883 *Math.Sin(W2rad)); - p = 309.107 + 123.44121 *t2; - M = L - p; - Mrad = CAACoordinateTransformation.DegreesToRadians(M); - C = 0.55577 *Math.Sin(Mrad) + 0.00168 *Math.Sin(2 *Mrad); - Crad = CAACoordinateTransformation.DegreesToRadians(C); - double lambda2 = CAACoordinateTransformation.MapTo0To360Range(L + C); - double r2 = 3.94118/(1 + 0.00485 *Math.Cos(Mrad + Crad)); - double gamma2 = 0.0262; - double omega2 = CAACoordinateTransformation.MapTo0To360Range(348 - 151.95 *t2); - - //Satellite 3 - double lambda3 = CAACoordinateTransformation.MapTo0To360Range(285.306 + 190.69791226 *t1 + 2.063 *Math.Sin(W0rad) + 0.03409 *Math.Sin(3 *W0rad) + 0.001015 *Math.Sin(5 *W0rad)); - double r3 = 4.880998; - double gamma3 = 1.0976; - double omega3 = CAACoordinateTransformation.MapTo0To360Range(111.33 - 72.2441 *t2); - - //Satellite 4 - L = CAACoordinateTransformation.MapTo0To360Range(254.712 + 131.53493193 *t1 - 0.0215 *Math.Sin(W1rad) - 0.01733 *Math.Sin(W2rad)); - p = 174.8 + 30.820 *t2; - M = L - p; - Mrad = CAACoordinateTransformation.DegreesToRadians(M); - C = 0.24717 *Math.Sin(Mrad) + 0.00033 *Math.Sin(2 *Mrad); - Crad = CAACoordinateTransformation.DegreesToRadians(C); - double lambda4 = CAACoordinateTransformation.MapTo0To360Range(L + C); - double r4 = 6.24871/(1 + 0.002157 *Math.Cos(Mrad + Crad)); - double gamma4 = 0.0139; - double omega4 = CAACoordinateTransformation.MapTo0To360Range(232 - 30.27 *t2); - - //Satellite 5 - double pdash = 342.7 + 10.057 *t2; - double pdashrad = CAACoordinateTransformation.DegreesToRadians(pdash); - double a1 = 0.000265 *Math.Sin(pdashrad) + 0.001 *Math.Sin(W4rad); //Note the book uses the incorrect constant 0.01*sin(W4rad); - double a2 = 0.000265 *Math.Cos(pdashrad) + 0.001 *Math.Cos(W4rad); //Note the book uses the incorrect constant 0.01*cos(W4rad); - double e = Math.Sqrt(a1 *a1 + a2 *a2); - p = CAACoordinateTransformation.RadiansToDegrees(Math.Atan2(a1, a2)); - double N = 345 - 10.057 *t2; - double Nrad = CAACoordinateTransformation.DegreesToRadians(N); - double lambdadash = CAACoordinateTransformation.MapTo0To360Range(359.244 + 79.69004720 *t1 + 0.086754 *Math.Sin(Nrad)); - double i = 28.0362 + 0.346898 *Math.Cos(Nrad) + 0.01930 *Math.Cos(W3rad); - double omega = 168.8034 + 0.736936 *Math.Sin(Nrad) + 0.041 *Math.Sin(W3rad); - double a = 8.725924; - double lambda5 = 0; - double gamma5 = 0; - double omega5 = 0; - double r5 = 0; - HelperSubroutine(e, lambdadash, p, a, omega, i, c1, s1, ref r5, ref lambda5, ref gamma5, ref omega5); - - //Satellite 6 - L = 261.1582 + 22.57697855 *t4 + 0.074025 *Math.Sin(W3rad); - double idash = 27.45141 + 0.295999 *Math.Cos(W3rad); - double idashrad = CAACoordinateTransformation.DegreesToRadians(idash); - double omegadash = 168.66925 + 0.628808 *Math.Sin(W3rad); - double omegadashrad = CAACoordinateTransformation.DegreesToRadians(omegadash); - a1 = Math.Sin(W7rad)*Math.Sin(omegadashrad - W8rad); - a2 = Math.Cos(W7rad)*Math.Sin(idashrad) - Math.Sin(W7rad)*Math.Cos(idashrad)*Math.Cos(omegadashrad - W8rad); - double g0 = CAACoordinateTransformation.DegreesToRadians(102.8623); - double psi = Math.Atan2(a1, a2); - if (a2 < 0) - psi += CAACoordinateTransformation.PI(); - double psideg = CAACoordinateTransformation.RadiansToDegrees(psi); - double s = Math.Sqrt(a1 *a1 + a2 *a2); - double g = W4 - omegadash - psideg; - double w_ = 0; - for (int j =0; j<3; j++) - { - w_ = W4 + 0.37515*(Math.Sin(2 *CAACoordinateTransformation.DegreesToRadians(g)) - Math.Sin(2 *g0)); - g = w_ - omegadash - psideg; - } - double grad = CAACoordinateTransformation.DegreesToRadians(g); - double edash = 0.029092 + 0.00019048*(Math.Cos(2 *grad) - Math.Cos(2 *g0)); - double q = CAACoordinateTransformation.DegreesToRadians(2*(W5 - w_)); - double b1 = Math.Sin(idashrad)*Math.Sin(omegadashrad - W8rad); - double b2 = Math.Cos(W7rad)*Math.Sin(idashrad)*Math.Cos(omegadashrad - W8rad) - Math.Sin(W7rad)*Math.Cos(idashrad); - double atanb1b2 = Math.Atan2(b1, b2); - double theta = atanb1b2 + W8rad; - e = edash + 0.002778797 *edash *Math.Cos(q); - p = w_ + 0.159215 *Math.Sin(q); - double u = 2 *W5rad - 2 *theta + psi; - double h = 0.9375 *edash *edash *Math.Sin(q) + 0.1875 *s *s *Math.Sin(2*(W5rad - theta)); - lambdadash = CAACoordinateTransformation.MapTo0To360Range(L - 0.254744*(e1 *Math.Sin(W6rad) + 0.75 *e1 *e1 *Math.Sin(2 *W6rad) + h)); - i = idash + 0.031843 *s *Math.Cos(u); - omega = omegadash + (0.031843 *s *Math.Sin(u))/Math.Sin(idashrad); - a = 20.216193; - double lambda6 = 0; - double gamma6 = 0; - double omega6 = 0; - double r6 = 0; - HelperSubroutine(e, lambdadash, p, a, omega, i, c1, s1, ref r6, ref lambda6, ref gamma6, ref omega6); - - //Satellite 7 - double eta = 92.39 + 0.5621071 *t6; - double etarad = CAACoordinateTransformation.DegreesToRadians(eta); - double zeta = 148.19 - 19.18 *t8; - double zetarad = CAACoordinateTransformation.DegreesToRadians(zeta); - theta = CAACoordinateTransformation.DegreesToRadians(184.8 - 35.41 *t9); - double thetadash = theta - CAACoordinateTransformation.DegreesToRadians(7.5); - double @as = CAACoordinateTransformation.DegreesToRadians(176 + 12.22 *t8); - double bs = CAACoordinateTransformation.DegreesToRadians(8 + 24.44 *t8); - double cs = bs + CAACoordinateTransformation.DegreesToRadians(5); - w_ = 69.898 - 18.67088 *t8; - double phi = 2*(w_ - W5); - double phirad = CAACoordinateTransformation.DegreesToRadians(phi); - double chi = 94.9 - 2.292 *t8; - double chirad = CAACoordinateTransformation.DegreesToRadians(chi); - a = 24.50601 - 0.08686 *Math.Cos(etarad) - 0.00166 *Math.Cos(zetarad + etarad) + 0.00175 *Math.Cos(zetarad - etarad); - e = 0.103458 - 0.004099 *Math.Cos(etarad) - 0.000167 *Math.Cos(zetarad + etarad) + 0.000235 *Math.Cos(zetarad - etarad) + 0.02303 *Math.Cos(zetarad) - 0.00212 *Math.Cos(2 *zetarad) + 0.000151 *Math.Cos(3 *zetarad) + 0.00013 *Math.Cos(phirad); - p = w_ + 0.15648 *Math.Sin(chirad) - 0.4457 *Math.Sin(etarad) - 0.2657 *Math.Sin(zetarad + etarad) + -0.3573 *Math.Sin(zetarad - etarad) - 12.872 *Math.Sin(zetarad) + 1.668 *Math.Sin(2 *zetarad) + -0.2419 *Math.Sin(3 *zetarad) - 0.07 *Math.Sin(phirad); - lambdadash = CAACoordinateTransformation.MapTo0To360Range(177.047 + 16.91993829 *t6 + 0.15648 *Math.Sin(chirad) + 9.142 *Math.Sin(etarad) + 0.007 *Math.Sin(2 *etarad) - 0.014 *Math.Sin(3 *etarad) + 0.2275 *Math.Sin(zetarad + etarad) + 0.2112 *Math.Sin(zetarad - etarad) - 0.26 *Math.Sin(zetarad) - 0.0098 *Math.Sin(2 *zetarad) + -0.013 *Math.Sin(@as) + 0.017 *Math.Sin(bs) - 0.0303 *Math.Sin(phirad)); - i = 27.3347 + 0.643486 *Math.Cos(chirad) + 0.315 *Math.Cos(W3rad) + 0.018 *Math.Cos(theta) - 0.018 *Math.Cos(cs); - omega = 168.6812 + 1.40136 *Math.Cos(chirad) + 0.68599 *Math.Sin(W3rad) - 0.0392 *Math.Sin(cs) + 0.0366 *Math.Sin(thetadash); - double lambda7 = 0; - double gamma7 = 0; - double omega7 = 0; - double r7 = 0; - HelperSubroutine(e, lambdadash, p, a, omega, i, c1, s1, ref r7, ref lambda7, ref gamma7, ref omega7); - - //Satellite 8 - L = CAACoordinateTransformation.MapTo0To360Range(261.1582 + 22.57697855 *t4); - double w_dash = 91.796 + 0.562 *t7; - psi = 4.367 - 0.195 *t7; - double psirad = CAACoordinateTransformation.DegreesToRadians(psi); - theta = 146.819 - 3.198 *t7; - phi = 60.470 + 1.521 *t7; - phirad = CAACoordinateTransformation.DegreesToRadians(phi); - double PHI = 205.055 - 2.091 *t7; - edash = 0.028298 + 0.001156 *t11; - double w_0 = 352.91 + 11.71 *t11; - double mu = CAACoordinateTransformation.MapTo0To360Range(76.3852 + 4.53795125 *t10); - mu = CAACoordinateTransformation.MapTo0To360Range(189097.71668440815); - idash = 18.4602 - 0.9518 *t11 - 0.072 *t112 + 0.0054 *t113; - idashrad = CAACoordinateTransformation.DegreesToRadians(idash); - omegadash = 143.198 - 3.919 *t11 + 0.116 *t112 + 0.008 *t113; - l = CAACoordinateTransformation.DegreesToRadians(mu - w_0); - g = CAACoordinateTransformation.DegreesToRadians(w_0 - omegadash - psi); - double g1 = CAACoordinateTransformation.DegreesToRadians(w_0 - omegadash - phi); - double ls = CAACoordinateTransformation.DegreesToRadians(W5 - w_dash); - double gs = CAACoordinateTransformation.DegreesToRadians(w_dash - theta); - double lt = CAACoordinateTransformation.DegreesToRadians(L - W4); - double gt = CAACoordinateTransformation.DegreesToRadians(W4 - PHI); - double u1 = 2*(l + g - ls - gs); - double u2 = l + g1 - lt - gt; - double u3 = l + 2*(g - ls - gs); - double u4 = lt + gt - g1; - double u5 = 2*(ls + gs); - a = 58.935028 + 0.004638 *Math.Cos(u1) + 0.058222 *Math.Cos(u2); - e = edash - 0.0014097 *Math.Cos(g1 - gt) + 0.0003733 *Math.Cos(u5 - 2 *g) + 0.0001180 *Math.Cos(u3) + 0.0002408 *Math.Cos(l) + 0.0002849 *Math.Cos(l + u2) + 0.0006190 *Math.Cos(u4); - double w = 0.08077 *Math.Sin(g1 - gt) + 0.02139 *Math.Sin(u5 - 2 *g) - 0.00676 *Math.Sin(u3) + 0.01380 *Math.Sin(l) + 0.01632 *Math.Sin(l + u2) + 0.03547 *Math.Sin(u4); - p = w_0 + w/edash; - lambdadash = mu - 0.04299 *Math.Sin(u2) - 0.00789 *Math.Sin(u1) - 0.06312 *Math.Sin(ls) + -0.00295 *Math.Sin(2 *ls) - 0.02231 *Math.Sin(u5) + 0.00650 *Math.Sin(u5 + psirad); - i = idash + 0.04204 *Math.Cos(u5 + psirad) + 0.00235 *Math.Cos(l + g1 + lt + gt + phirad) + 0.00360 *Math.Cos(u2 + phirad); - double wdash = 0.04204 *Math.Sin(u5 + psirad) + 0.00235 *Math.Sin(l + g1 + lt + gt + phirad) + 0.00358 *Math.Sin(u2 + phirad); - omega = omegadash + wdash/Math.Sin(idashrad); - double lambda8 = 0; - double gamma8 = 0; - double omega8 = 0; - double r8 = 0; - HelperSubroutine(e, lambdadash, p, a, omega, i, c1, s1, ref r8, ref lambda8, ref gamma8, ref omega8); - - - u = CAACoordinateTransformation.DegreesToRadians(lambda1 - omega1); - w = CAACoordinateTransformation.DegreesToRadians(omega1 - 168.8112); - double gamma1rad = CAACoordinateTransformation.DegreesToRadians(gamma1); - double X1 = r1*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma1rad)*Math.Sin(w)); - double Y1 = r1*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma1rad) + Math.Cos(u)*Math.Sin(w)); - double Z1 = r1 *Math.Sin(u)*Math.Sin(gamma1rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda2 - omega2); - w = CAACoordinateTransformation.DegreesToRadians(omega2 - 168.8112); - double gamma2rad = CAACoordinateTransformation.DegreesToRadians(gamma2); - double X2 = r2*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma2rad)*Math.Sin(w)); - double Y2 = r2*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma2rad) + Math.Cos(u)*Math.Sin(w)); - double Z2 = r2 *Math.Sin(u)*Math.Sin(gamma2rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda3 - omega3); - w = CAACoordinateTransformation.DegreesToRadians(omega3 - 168.8112); - double gamma3rad = CAACoordinateTransformation.DegreesToRadians(gamma3); - double X3 = r3*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma3rad)*Math.Sin(w)); - double Y3 = r3*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma3rad) + Math.Cos(u)*Math.Sin(w)); - double Z3 = r3 *Math.Sin(u)*Math.Sin(gamma3rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda4 - omega4); - w = CAACoordinateTransformation.DegreesToRadians(omega4 - 168.8112); - double gamma4rad = CAACoordinateTransformation.DegreesToRadians(gamma4); - double X4 = r4*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma4rad)*Math.Sin(w)); - double Y4 = r4*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma4rad) + Math.Cos(u)*Math.Sin(w)); - double Z4 = r4 *Math.Sin(u)*Math.Sin(gamma4rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda5 - omega5); - w = CAACoordinateTransformation.DegreesToRadians(omega5 - 168.8112); - double gamma5rad = CAACoordinateTransformation.DegreesToRadians(gamma5); - double X5 = r5*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma5rad)*Math.Sin(w)); - double Y5 = r5*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma5rad) + Math.Cos(u)*Math.Sin(w)); - double Z5 = r5 *Math.Sin(u)*Math.Sin(gamma5rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda6 - omega6); - w = CAACoordinateTransformation.DegreesToRadians(omega6 - 168.8112); - double gamma6rad = CAACoordinateTransformation.DegreesToRadians(gamma6); - double X6 = r6*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma6rad)*Math.Sin(w)); - double Y6 = r6*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma6rad) + Math.Cos(u)*Math.Sin(w)); - double Z6 = r6 *Math.Sin(u)*Math.Sin(gamma6rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda7 - omega7); - w = CAACoordinateTransformation.DegreesToRadians(omega7 - 168.8112); - double gamma7rad = CAACoordinateTransformation.DegreesToRadians(gamma7); - double X7 = r7*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma7rad)*Math.Sin(w)); - double Y7 = r7*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma7rad) + Math.Cos(u)*Math.Sin(w)); - double Z7 = r7 *Math.Sin(u)*Math.Sin(gamma7rad); - - u = CAACoordinateTransformation.DegreesToRadians(lambda8 - omega8); - w = CAACoordinateTransformation.DegreesToRadians(omega8 - 168.8112); - double gamma8rad = CAACoordinateTransformation.DegreesToRadians(gamma8); - double X8 = r8*(Math.Cos(u)*Math.Cos(w) - Math.Sin(u)*Math.Cos(gamma8rad)*Math.Sin(w)); - double Y8 = r8*(Math.Sin(u)*Math.Cos(w)*Math.Cos(gamma8rad) + Math.Cos(u)*Math.Sin(w)); - double Z8 = r8 *Math.Sin(u)*Math.Sin(gamma8rad); - - double X9 = 0; - double Y9 = 0; - double Z9 = 1; - - //Now do the rotations, first for the ficticious 9th satellite, so that we can calculate D - double A4=0; - double B4=0; - double C4=0; - Rotations(X9, Y9, Z9, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - double D = Math.Atan2(A4, C4); - - //Now calculate the values for satellite 1 - Rotations(X1, Y1, Z1, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite1.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite1.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite1.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 2 - Rotations(X2, Y2, Z2, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite2.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite2.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite2.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 3 - Rotations(X3, Y3, Z3, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite3.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite3.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite3.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 4 - Rotations(X4, Y4, Z4, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite4.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite4.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite4.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 5 - Rotations(X5, Y5, Z5, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite5.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite5.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite5.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 6 - Rotations(X6, Y6, Z6, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite6.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite6.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite6.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 7 - Rotations(X7, Y7, Z7, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite7.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite7.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite7.TrueRectangularCoordinates.Z = B4; - - //Now calculate the values for satellite 8 - Rotations(X8, Y8, Z8, c1, s1, c2, s2, lambda0rad, beta0rad, ref A4, ref B4, ref C4); - details.Satellite8.TrueRectangularCoordinates.X = A4 *Math.Cos(D) - C4 *Math.Sin(D); - details.Satellite8.TrueRectangularCoordinates.Y = A4 *Math.Sin(D) + C4 *Math.Cos(D); - details.Satellite8.TrueRectangularCoordinates.Z = B4; - - - //apply the differential light-time correction - details.Satellite1.ApparentRectangularCoordinates.X = details.Satellite1.TrueRectangularCoordinates.X + Math.Abs(details.Satellite1.TrueRectangularCoordinates.Z)/20947 *Math.Sqrt(1 - (details.Satellite1.TrueRectangularCoordinates.X/r1)*(details.Satellite1.TrueRectangularCoordinates.X/r1)); - details.Satellite1.ApparentRectangularCoordinates.Y = details.Satellite1.TrueRectangularCoordinates.Y; - details.Satellite1.ApparentRectangularCoordinates.Z = details.Satellite1.TrueRectangularCoordinates.Z; - - details.Satellite2.ApparentRectangularCoordinates.X = details.Satellite2.TrueRectangularCoordinates.X + Math.Abs(details.Satellite2.TrueRectangularCoordinates.Z)/23715 *Math.Sqrt(1 - (details.Satellite2.TrueRectangularCoordinates.X/r2)*(details.Satellite2.TrueRectangularCoordinates.X/r2)); - details.Satellite2.ApparentRectangularCoordinates.Y = details.Satellite2.TrueRectangularCoordinates.Y; - details.Satellite2.ApparentRectangularCoordinates.Z = details.Satellite2.TrueRectangularCoordinates.Z; - - details.Satellite3.ApparentRectangularCoordinates.X = details.Satellite3.TrueRectangularCoordinates.X + Math.Abs(details.Satellite3.TrueRectangularCoordinates.Z)/26382 *Math.Sqrt(1 - (details.Satellite3.TrueRectangularCoordinates.X/r3)*(details.Satellite3.TrueRectangularCoordinates.X/r3)); - details.Satellite3.ApparentRectangularCoordinates.Y = details.Satellite3.TrueRectangularCoordinates.Y; - details.Satellite3.ApparentRectangularCoordinates.Z = details.Satellite3.TrueRectangularCoordinates.Z; - - details.Satellite4.ApparentRectangularCoordinates.X = details.Satellite4.TrueRectangularCoordinates.X + Math.Abs(details.Satellite4.TrueRectangularCoordinates.Z)/29876 *Math.Sqrt(1 - (details.Satellite4.TrueRectangularCoordinates.X/r4)*(details.Satellite4.TrueRectangularCoordinates.X/r4)); - details.Satellite4.ApparentRectangularCoordinates.Y = details.Satellite4.TrueRectangularCoordinates.Y; - details.Satellite4.ApparentRectangularCoordinates.Z = details.Satellite4.TrueRectangularCoordinates.Z; - - details.Satellite5.ApparentRectangularCoordinates.X = details.Satellite5.TrueRectangularCoordinates.X + Math.Abs(details.Satellite5.TrueRectangularCoordinates.Z)/35313 *Math.Sqrt(1 - (details.Satellite5.TrueRectangularCoordinates.X/r5)*(details.Satellite5.TrueRectangularCoordinates.X/r5)); - details.Satellite5.ApparentRectangularCoordinates.Y = details.Satellite5.TrueRectangularCoordinates.Y; - details.Satellite5.ApparentRectangularCoordinates.Z = details.Satellite5.TrueRectangularCoordinates.Z; - - details.Satellite6.ApparentRectangularCoordinates.X = details.Satellite6.TrueRectangularCoordinates.X + Math.Abs(details.Satellite6.TrueRectangularCoordinates.Z)/53800 *Math.Sqrt(1 - (details.Satellite6.TrueRectangularCoordinates.X/r6)*(details.Satellite6.TrueRectangularCoordinates.X/r6)); - details.Satellite6.ApparentRectangularCoordinates.Y = details.Satellite6.TrueRectangularCoordinates.Y; - details.Satellite6.ApparentRectangularCoordinates.Z = details.Satellite6.TrueRectangularCoordinates.Z; - - details.Satellite7.ApparentRectangularCoordinates.X = details.Satellite7.TrueRectangularCoordinates.X + Math.Abs(details.Satellite7.TrueRectangularCoordinates.Z)/59222 *Math.Sqrt(1 - (details.Satellite7.TrueRectangularCoordinates.X/r7)*(details.Satellite7.TrueRectangularCoordinates.X/r7)); - details.Satellite7.ApparentRectangularCoordinates.Y = details.Satellite7.TrueRectangularCoordinates.Y; - details.Satellite7.ApparentRectangularCoordinates.Z = details.Satellite7.TrueRectangularCoordinates.Z; - - details.Satellite8.ApparentRectangularCoordinates.X = details.Satellite8.TrueRectangularCoordinates.X + Math.Abs(details.Satellite8.TrueRectangularCoordinates.Z)/91820 *Math.Sqrt(1 - (details.Satellite8.TrueRectangularCoordinates.X/r8)*(details.Satellite8.TrueRectangularCoordinates.X/r8)); - details.Satellite8.ApparentRectangularCoordinates.Y = details.Satellite8.TrueRectangularCoordinates.Y; - details.Satellite8.ApparentRectangularCoordinates.Z = details.Satellite8.TrueRectangularCoordinates.Z; - - - //apply the perspective effect correction - double W = DELTA/(DELTA + details.Satellite1.TrueRectangularCoordinates.Z/2475); - details.Satellite1.ApparentRectangularCoordinates.X *= W; - details.Satellite1.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite2.TrueRectangularCoordinates.Z/2475); - details.Satellite2.ApparentRectangularCoordinates.X *= W; - details.Satellite2.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite3.TrueRectangularCoordinates.Z/2475); - details.Satellite3.ApparentRectangularCoordinates.X *= W; - details.Satellite3.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite4.TrueRectangularCoordinates.Z/2475); - details.Satellite4.ApparentRectangularCoordinates.X *= W; - details.Satellite4.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite5.TrueRectangularCoordinates.Z/2475); - details.Satellite5.ApparentRectangularCoordinates.X *= W; - details.Satellite5.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite6.TrueRectangularCoordinates.Z/2475); - details.Satellite6.ApparentRectangularCoordinates.X *= W; - details.Satellite6.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite7.TrueRectangularCoordinates.Z/2475); - details.Satellite7.ApparentRectangularCoordinates.X *= W; - details.Satellite7.ApparentRectangularCoordinates.Y *= W; - - W = DELTA/(DELTA + details.Satellite8.TrueRectangularCoordinates.Z/2475); - details.Satellite8.ApparentRectangularCoordinates.X *= W; - details.Satellite8.ApparentRectangularCoordinates.Y *= W; - - return details; - } - - //////////////////////////////// Implementation /////////////////////////////// - - protected static void HelperSubroutine(double e, double lambdadash, double p, double a, double omega, double i, double c1, double s1, ref double r, ref double lambda, ref double gamma, ref double w) - { - double e2 = e *e; - double e3 = e2 *e; - double e4 = e3 *e; - double e5 = e4 *e; - double M = CAACoordinateTransformation.DegreesToRadians(lambdadash - p); - - double Crad = (2 *e - 0.25 *e3 + 0.0520833333 *e5)*Math.Sin(M) + (1.25 *e2 - 0.458333333 *e4)*Math.Sin(2 *M) + (1.083333333 *e3 - 0.671875 *e5)*Math.Sin(3 *M) + 1.072917 *e4 *Math.Sin(4 *M) + 1.142708 *e5 *Math.Sin(5 *M); - double C = CAACoordinateTransformation.RadiansToDegrees(Crad); - r = a*(1 - e2)/(1 + e *Math.Cos(M + Crad)); - double g = omega - 168.8112; - double grad = CAACoordinateTransformation.DegreesToRadians(g); - double irad = CAACoordinateTransformation.DegreesToRadians(i); - double a1 = Math.Sin(irad)*Math.Sin(grad); - double a2 = c1 *Math.Sin(irad)*Math.Cos(grad) - s1 *Math.Cos(irad); - gamma = CAACoordinateTransformation.RadiansToDegrees(Math.Asin(Math.Sqrt(a1 *a1 + a2 *a2))); - double urad = Math.Atan2(a1, a2); - double u = CAACoordinateTransformation.RadiansToDegrees(urad); - w = CAACoordinateTransformation.MapTo0To360Range(168.8112 + u); - double h = c1 *Math.Sin(irad) - s1 *Math.Cos(irad)*Math.Cos(grad); - double psirad = Math.Atan2(s1 *Math.Sin(grad), h); - double psi = CAACoordinateTransformation.RadiansToDegrees(psirad); - lambda = lambdadash + C + u - g - psi; - } - protected static void Rotations(double X, double Y, double Z, double c1, double s1, double c2, double s2, double lambda0, double beta0, ref double A4, ref double B4, ref double C4) - { - //Rotation towards the plane of the ecliptic - double A1 = X; - double B1 = c1 *Y - s1 *Z; - double C1 = s1 *Y + c1 *Z; - - //Rotation towards the vernal equinox - double A2 = c2 *A1 - s2 *B1; - double B2 = s2 *A1 + c2 *B1; - double C2 = C1; - - double A3 = A2 *Math.Sin(lambda0) - B2 *Math.Cos(lambda0); - double B3 = A2 *Math.Cos(lambda0) + B2 *Math.Sin(lambda0); - double C3 = C2; - - A4 = A3; - B4 = B3 *Math.Cos(beta0) + C3 *Math.Sin(beta0); - C4 = C3 *Math.Cos(beta0) - B3 *Math.Sin(beta0); - } - protected static void FillInPhenomenaDetails(ref CAASaturnMoonDetail detail) - { - double Y1 = 1.108601 * detail.ApparentRectangularCoordinates.Y; - - double r = Y1 *Y1 + detail.ApparentRectangularCoordinates.X *detail.ApparentRectangularCoordinates.X; - - if (r < 1) - { - if (detail.ApparentRectangularCoordinates.Z < 0) - { - //Satellite nearer to Earth than Saturn, so it must be a transit not an occultation - detail.bInTransit = true; - detail.bInOccultation = false; - } - else - { - detail.bInTransit = false; - detail.bInOccultation = true; - } - } - else - { - detail.bInTransit = false; - detail.bInOccultation = false; - } - } -} diff --git a/engine/csharp_ref/AstroCalc/AASaturnRings.cs b/engine/csharp_ref/AstroCalc/AASaturnRings.cs deleted file mode 100644 index c3a160fc..00000000 --- a/engine/csharp_ref/AstroCalc/AASaturnRings.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -// -//Module : AASATURNRINGS.CPP -//Purpose: Implementation for the algorithms which calculate various parameters related to the Rings of Saturn -//Created: PJN / 08-01-2004 -//History: None -// -//Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -///////////////////////////////// Includes //////////////////////////////////// - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAASaturnRingDetails -{ -//Constructors / Destructors - public CAASaturnRingDetails() - { - B = 0; - Bdash = 0; - P = 0; - a = 0; - b = 0; - DeltaU = 0; - } - -//Member variables - public double B; - public double Bdash; - public double P; - public double a; - public double b; - public double DeltaU; -} - -public class CAASaturnRings -{ -//Static methods - - //////////////////////////////// Implementation /////////////////////////////// - - public static CAASaturnRingDetails Calculate(double JD) - { - //What will be the return value - CAASaturnRingDetails details = new CAASaturnRingDetails(); - - double T = (JD - 2451545) / 36525; - double T2 = T *T; - - //Step 1. Calculate the inclination of the plane of the ring and the longitude of the ascending node referred to the ecliptic and mean equinox of the date - double i = 28.075216 - 0.012998 *T + 0.000004 *T2; - double irad = CT.D2R(i); - double omega = 169.508470 + 1.394681 *T + 0.000412 *T2; - double omegarad = CT.D2R(omega); - - //Step 2. Calculate the heliocentric longitude, latitude and radius vector of the Earth in the FK5 system - double l0 = CAAEarth.EclipticLongitude(JD); - double b0 = CAAEarth.EclipticLatitude(JD); - l0 += CAAFK5.CorrectionInLongitude(l0, b0, JD); - double l0rad = CT.D2R(l0); - b0 += CAAFK5.CorrectionInLatitude(l0, JD); - double b0rad = CT.D2R(b0); - double R = CAAEarth.RadiusVector(JD); - - //Step 3. Calculate the corresponding coordinates l,b,r for Saturn but for the instance t-lightraveltime - double DELTA = 9; - double PreviousEarthLightTravelTime = 0; - double EarthLightTravelTime = ELL.DistanceToLightTime(DELTA); - double JD1 = JD - EarthLightTravelTime; - bool bIterate = true; - double x = 0; - double y = 0; - double z = 0; - double l = 0; - double b = 0; - double r = 0; - while (bIterate) - { - //Calculate the position of Saturn - l = CAASaturn.EclipticLongitude(JD1); - b = CAASaturn.EclipticLatitude(JD1); - l += CAAFK5.CorrectionInLongitude(l, b, JD1); - b += CAAFK5.CorrectionInLatitude(l, JD1); - - double lrad = CT.D2R(l); - double brad = CT.D2R(b); - r = CAASaturn.RadiusVector(JD1); - - //Step 4 - x = r *Math.Cos(brad)*Math.Cos(lrad) - R *Math.Cos(l0rad); - y = r *Math.Cos(brad)*Math.Sin(lrad) - R *Math.Sin(l0rad); - z = r *Math.Sin(brad) - R *Math.Sin(b0rad); - DELTA = Math.Sqrt(x *x + y *y + z *z); - EarthLightTravelTime = ELL.DistanceToLightTime(DELTA); - - //Prepare for the next loop around - bIterate = (Math.Abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-6); //2E-6 corresponds to 0.17 of a second - if (bIterate) - { - JD1 = JD - EarthLightTravelTime; - PreviousEarthLightTravelTime = EarthLightTravelTime; - } - } - - //Step 5. Calculate Saturn's geocentric Longitude and Latitude - double lambda = Math.Atan2(y, x); - double beta = Math.Atan2(z, Math.Sqrt(x *x + y *y)); - - //Step 6. Calculate B, a and b - details.B = Math.Asin(Math.Sin(irad)*Math.Cos(beta)*Math.Sin(lambda - omegarad) - Math.Cos(irad)*Math.Sin(beta)); - details.a = 375.35 / DELTA; - details.b = details.a * Math.Sin(Math.Abs(details.B)); - details.B = CT.R2D(details.B); - - //Step 7. Calculate the longitude of the ascending node of Saturn's orbit - double N = 113.6655 + 0.8771 *T; - double Nrad = CT.D2R(N); - double ldash = l - 0.01759/r; - double ldashrad = CT.D2R(ldash); - double bdash = b - 0.000764 *Math.Cos(ldashrad - Nrad)/r; - double bdashrad = CT.D2R(bdash); - - //Step 8. Calculate Bdash - details.Bdash = CT.R2D(Math.Asin(Math.Sin(irad)*Math.Cos(bdashrad)*Math.Sin(ldashrad - omegarad) - Math.Cos(irad)*Math.Sin(bdashrad))); - - //Step 9. Calculate DeltaU - double U1 = Math.Atan2(Math.Sin(irad)*Math.Sin(bdashrad) + Math.Cos(irad)*Math.Cos(bdashrad)*Math.Sin(ldashrad - omegarad), Math.Cos(bdashrad)*Math.Cos(ldashrad - omegarad)); - double U2 = Math.Atan2(Math.Sin(irad)*Math.Sin(beta) + Math.Cos(irad)*Math.Cos(beta)*Math.Sin(lambda - omegarad), Math.Cos(beta)*Math.Cos(lambda - omegarad)); - details.DeltaU = CT.R2D(Math.Abs(U1 - U2)); - - //Step 10. Calculate the Nutations - double Obliquity = CAANutation.TrueObliquityOfEcliptic(JD); - double NutationInLongitude = CAANutation.NutationInLongitude(JD); - - //Step 11. Calculate the Ecliptical longitude and latitude of the northern pole of the ring plane - double lambda0 = omega - 90; - double beta0 = 90 - i; - - //Step 12. Correct lambda and beta for the aberration of Saturn - lambda += CT.D2R(0.005693 *Math.Cos(l0rad - lambda)/Math.Cos(beta)); - beta += CT.D2R(0.005693 *Math.Sin(l0rad - lambda)*Math.Sin(beta)); - - //Step 13. Add nutation in longitude to lambda0 and lambda - //double NLrad = CAACoordinateTransformation::DegreesToRadians(NutationInLongitude/3600); - lambda = CT.R2D(lambda); - lambda += NutationInLongitude/3600; - lambda = CT.M360(lambda); - lambda0 += NutationInLongitude/3600; - lambda0 = CT.M360(lambda0); - - //Step 14. Convert to equatorial coordinates - beta = CT.R2D(beta); - COR GeocentricEclipticSaturn = CT.Ec2Eq(lambda, beta, Obliquity); - double alpha = CT.H2R(GeocentricEclipticSaturn.X); - double delta = CT.D2R(GeocentricEclipticSaturn.Y); - COR GeocentricEclipticNorthPole = CT.Ec2Eq(lambda0, beta0, Obliquity); - double alpha0 = CT.H2R(GeocentricEclipticNorthPole.X); - double delta0 = CT.D2R(GeocentricEclipticNorthPole.Y); - - //Step 15. Calculate the Position angle - details.P = CT.R2D(Math.Atan2(Math.Cos(delta0)*Math.Sin(alpha0 - alpha), Math.Sin(delta0)*Math.Cos(delta) - Math.Cos(delta0)*Math.Sin(delta)*Math.Cos(alpha0 - alpha))); - - return details; - } -} diff --git a/engine/csharp_ref/AstroCalc/AASidereal.cs b/engine/csharp_ref/AstroCalc/AASidereal.cs deleted file mode 100644 index d3cd21a0..00000000 --- a/engine/csharp_ref/AstroCalc/AASidereal.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -// -//Module : AASIDEREAL.CPP -//Purpose: Implementation for the algorithms which obtain sidereal time -//Created: PJN / 29-12-2003 -// PJN / 26-01-2007 1. Update to fit in with new layout of CAADate class -// PJN / 28-01-2007 1. Minor updates to fit in with new layout of CAADate class -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -/////////////////////////////// Includes ////////////////////////////////////// - - - -/////////////////////// Classes /////////////////////////////////////////////// - -public class CAASidereal -{ -//Static methods - - /////////////////////////////// Implementation //////////////////////////////// - - public static double MeanGreenwichSiderealTime(double JD) - { - //Get the Julian day for the same day at midnight - - DT date = new DT(); - date.SetJD(JD, DT.AfterPapalReformJD(JD)); - double[] D = date.Get(); - - int Year = (int)D[0]; - int Month = (int)D[1]; - int Day = (int)D[2]; - int Hour = (int)D[3]; - int Minute = (int)D[4]; - double Second = D[5]; - - date.Set(Year, Month, Day, 0, 0, 0, date.InGregorianCalendar()); - double JDMidnight = date.Julian(); - - //Calculate the sidereal time at midnight - double T = (JDMidnight - 2451545) / 36525; - double TSquared = T *T; - double TCubed = TSquared *T; - double Value = 100.46061837 + (36000.770053608 *T) + (0.000387933 *TSquared) - (TCubed/38710000); - - //Adjust by the time of day - Value += (((Hour * 15) + (Minute * 0.25) + (Second * 0.0041666666666666666666666666666667)) * 1.00273790935); - - Value = CT.D2H(Value); - - return CT.M24(Value); - } - - public static double ApparentGreenwichSiderealTime(double JD) - { - double MeanObliquity = CAANutation.MeanObliquityOfEcliptic(JD); - double TrueObliquity = MeanObliquity + CAANutation.NutationInObliquity(JD) / 3600; - double NutationInLongitude = CAANutation.NutationInLongitude(JD); - - double Value = MeanGreenwichSiderealTime(JD) + (NutationInLongitude * Math.Cos(CT.D2R(TrueObliquity)) / 54000); - return CT.M24(Value); - } -} diff --git a/engine/csharp_ref/AstroCalc/AAStellarMagnitudes.cs b/engine/csharp_ref/AstroCalc/AAStellarMagnitudes.cs deleted file mode 100644 index 3404ddcc..00000000 --- a/engine/csharp_ref/AstroCalc/AAStellarMagnitudes.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using wwtlib; -// -//Module : AASTELLARMAGNITUDES.CPP -//Purpose: Implementation for the algorithms which operate on the stellar magntidue system -//Created: PJN / 29-12-2003 -//History: PJN / 12-02-2004 1. Fixed a number of level 4 warnings when the code is compiled in VC.Net 2003 -// -//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) -// -//All rights reserved. -// -//Copyright / Usage Details: -// -//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) -//when your product is released in binary form. You are allowed to modify the source code in any way you want -//except you cannot modify the copyright details at the top of each module. If you want to distribute source -//code with your application, then you are only allowed to distribute versions released by the author. This is -//to maintain a single distribution point for the source code. -// -// - - -////////////////////////// Includes /////////////////////////////////////////// - - - -////////////////////// Classes //////////////////////////////////////////////// - -public class CAAStellarMagnitudes -{ -//functions - - ////////////////////////// Implementation ///////////////////////////////////// - - public static double CombinedMagnitude(double m1, double m2) - { - double x = 0.4*(m2 - m1); - return m2 - 2.5 *Util.Log10(Math.Pow(10.0, x) + 1); - } - public static double CombinedMagnitude2(int Magnitudes, double[] pMagnitudes) - { - double @value = 0; - for (int i =0; i delayTime) - { - state = targetState; - } - - return true; - } - - return state; - } - set - { - switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); - state = value; - targetState = state; - } - } - - bool targetState; - - public bool TargetState - { - get - { - return targetState; - } - set - { - if (targetState != value) - { - switchedTime = Date.Now; - targetState = value; - } - } - } - - public float Opacity - { - get - { - if (targetState != state) - { - int ts = Date.Now - switchedTime; - if (ts > delayTime) - { - state = targetState; - - } - else - { - float opacity = (float)(ts / delayTime); - - return targetState ? opacity : 1f - opacity; - } - } - return state ? 1f : 0f; - } - } - Date switchedTime; - double delayTime = 0; - - public double DelayTime - { - get { return delayTime; } - set { delayTime = value; } - } - - public BlendState() - { - switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); - state = false; - targetState = state; - this.delayTime = 1000; - } - - public static BlendState Create(bool initialState, double delayTime) - { - BlendState temp = new BlendState(); - - temp.state = initialState; - temp.targetState = initialState; - temp.delayTime = delayTime; - return temp; - } - } -} diff --git a/engine/csharp_ref/CameraParameters.cs b/engine/csharp_ref/CameraParameters.cs deleted file mode 100644 index 13153e54..00000000 --- a/engine/csharp_ref/CameraParameters.cs +++ /dev/null @@ -1,275 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - public enum SolarSystemObjects - { - Sun = 0, - Mercury = 1, - Venus = 2, - Mars = 3, - Jupiter = 4, - Saturn = 5, - Uranus = 6, - Neptune = 7, - Pluto = 8, - Moon = 9, - Io = 10, - Europa = 11, - Ganymede = 12, - Callisto = 13, - IoShadow = 14, - EuropaShadow = 15, - GanymedeShadow = 16, - CallistoShadow = 17, - SunEclipsed = 18, - Earth = 19, - Custom = 20, - Undefined = 65536 - }; - - - - public enum InterpolationType { Linear = 0, EaseIn = 1, EaseOut = 2, EaseInOut = 3, Exponential = 4, DefaultV = 5 }; - public class CameraParameters - { - public double Lat; - public double Lng; - public double Zoom; - public double Rotation; - public double Angle; - public bool RaDec; - public double Opacity; - public Vector3d ViewTarget; - public SolarSystemObjects Target; - public string TargetReferenceFrame; - public CameraParameters() - { - Zoom = 360; - ViewTarget = new Vector3d(); - } - public static CameraParameters Create(double lat, double lng, double zoom, double rotation, double angle, float opactity) - { - CameraParameters temp = new CameraParameters(); - temp.Lat = lat; - temp.Lng = lng; - temp.Zoom = zoom; - temp.Rotation = rotation; - temp.Angle = angle; - temp.RaDec = false; - temp.Opacity = opactity; - temp.ViewTarget = Vector3d.Create(0, 0, 0); - temp.Target = SolarSystemObjects.Custom; - temp.TargetReferenceFrame = ""; - return temp; - } - - public CameraParameters Copy() - { - CameraParameters temp = new CameraParameters(); - temp.Lat = Lat; - temp.Lng = Lng; - temp.Zoom = Zoom; - temp.Rotation = Rotation; - temp.Angle = Angle; - temp.RaDec = RaDec; - temp.Opacity = Opacity; - temp.ViewTarget = ViewTarget.Copy(); - temp.Target = Target; - temp.TargetReferenceFrame = TargetReferenceFrame; - return temp; - } - - public double RA - { - get - { - return ((((180 - (Lng - 180)) / 360) * 24.0) % 24); - } - set - { - Lng = 180 - ((value) / 24.0 * 360) - 180; - RaDec = true; - } - } - public double Dec - { - get - { - return Lat; - } - set - { - Lat = value; - } - } - - public static double LogN(double num, double b) - { - return Math.Log(num) / Math.Log(b); - } - - public static double Sinh(double v) - { - return (Math.Exp(v) - Math.Exp(-v)) / 2; - } - - public static CameraParameters Interpolate(CameraParameters from, CameraParameters to, double alphaIn, InterpolationType type, bool fastDirectionMove) - { - CameraParameters result = new CameraParameters(); - double alpha = EaseCurve(alphaIn, type); - double alphaBIn = Math.Min(1.0, alphaIn * 2); - double alphaB = EaseCurve(alphaBIn, type); - result.Angle = to.Angle * alpha + from.Angle * (1.0 - alpha); - result.Rotation = to.Rotation * alpha + from.Rotation * (1.0 - alpha); - if (fastDirectionMove) - { - result.Lat = to.Lat * alphaB + from.Lat * (1.0 - alphaB); - result.Lng = to.Lng * alphaB + from.Lng * (1.0 - alphaB); - } - else - { - result.Lat = to.Lat * alpha + from.Lat * (1.0 - alpha); - result.Lng = to.Lng * alpha + from.Lng * (1.0 - alpha); - } - result.Zoom = Math.Pow(2, LogN(to.Zoom, 2) * alpha + LogN(from.Zoom, 2) * (1.0 - alpha)); - result.Opacity = (double)(to.Opacity * alpha + from.Opacity * (1.0 - alpha)); - result.ViewTarget = Vector3d.Lerp(from.ViewTarget, to.ViewTarget, alpha); - result.TargetReferenceFrame = to.TargetReferenceFrame; - if (to.Target == from.Target) - { - result.Target = to.Target; - } - else - { - result.Target = SolarSystemObjects.Custom; - } - return result; - } - - public static CameraParameters InterpolateGreatCircle(CameraParameters from, CameraParameters to, double alphaIn, InterpolationType type, bool fastDirectionMove) - { - CameraParameters result = new CameraParameters(); - double alpha = EaseCurve(alphaIn, type); - double alphaBIn = Math.Min(1.0, alphaIn * 2); - double alphaB = EaseCurve(alphaBIn, type); - result.Angle = to.Angle * alpha + from.Angle * (1.0 - alpha); - result.Rotation = to.Rotation * alpha + from.Rotation * (1.0 - alpha); - - Vector3d left = Coordinates.GeoTo3dDouble(from.Lat, from.Lng); - Vector3d right = Coordinates.GeoTo3dDouble(to.Lat, to.Lng); - - Vector3d mid = Vector3d.Slerp(left, right, alpha); - - Vector2d midV2 = Coordinates.CartesianToLatLng(mid); - - result.Lat = midV2.Y; - result.Lng = midV2.X; - - - result.Zoom = Math.Pow(2, LogN(to.Zoom, 2) * alpha + LogN(from.Zoom, 2) * (1.0 - alpha)); - result.Opacity = (double)(to.Opacity * alpha + from.Opacity * (1.0 - alpha)); - result.ViewTarget = Vector3d.Lerp(from.ViewTarget, to.ViewTarget, alpha); - - result.TargetReferenceFrame = to.TargetReferenceFrame; - if (to.Target == from.Target) - { - result.Target = to.Target; - } - else - { - result.Target = SolarSystemObjects.Custom; - } - return result; - } - - - const double factor = 0.1085712344; - - public static double EaseCurve(double alpha, InterpolationType type) - { - // =100-SINH(A29/Factor*PI()) - - switch (type) - { - case InterpolationType.Linear: - return alpha; - case InterpolationType.Exponential: - return Math.Pow(alpha, 2); - case InterpolationType.EaseIn: - return ((1 - alpha) * Sinh(alpha / (factor * 2)) / 100.0) + alpha * alpha; - case InterpolationType.EaseOut: - return (alpha * (1 - Sinh((1.0 - alpha) / (factor * 2)) / 100.0)) + (1.0 - alpha) * alpha; - case InterpolationType.EaseInOut: - if (alpha < .5) - { - return Sinh(alpha / factor) / 100.0; - } - else - { - return 1.0 - (Sinh((1.0 - alpha) / factor) / 100.0); - } - default: - return alpha; - } - } - - - //public static double EaseCurve(double alpha) - //{ - // // =100-SINH(A29/Factor*PI()) - - // if (alpha < .5) - // { - // return Sinh(alpha / factor) / 100.0; - // } - // else - // { - // return 1.0 - (Sinh((1.0 - alpha) / factor) / 100.0); - // } - //} - - //public static bool operator ==(CameraParameters c1, CameraParameters c2) - //{ - // if (!(c1 is CameraParameters)) - // { - // return !(c2 is CameraParameters); - // } - - // return c1.Equals(c2); - //} - - //public static bool operator !=(CameraParameters c1, CameraParameters c2) - //{ - // if (!(c1 is CameraParameters)) - // { - // return (c2 is CameraParameters); - // } - - // return !c1.Equals(c2); - //} - - - public bool Equals(object obj) - { - if (obj is CameraParameters) - { - CameraParameters cam = (CameraParameters)obj; - - if (Math.Abs(cam.Angle - this.Angle) > .01 || Math.Abs(cam.Lat - this.Lat) > (cam.Zoom / 10000) || Math.Abs(cam.RA - this.RA) > (cam.Zoom / 1000) || Math.Abs(cam.Rotation - this.Rotation) > .1 || Math.Abs(cam.Zoom - this.Zoom) > (Math.Abs(cam.Zoom) / 1000)) - { - return false; - } - return true; - } - else - { - return false; - } - } - } -} - diff --git a/engine/csharp_ref/Color.cs b/engine/csharp_ref/Color.cs deleted file mode 100644 index 77a87621..00000000 --- a/engine/csharp_ref/Color.cs +++ /dev/null @@ -1,634 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - public class Color - { - public float A = 255.0f; - public float B = 255.0f; - public float G = 255.0f; - public float R = 255.0f; - public string Name = ""; - public static Color FromArgb(float a, float r, float g, float b) - { - Color temp = new Color(); - temp.A = a; - temp.R = r; - temp.G = g; - temp.B = b; - - return temp; - } - - - - internal static Color FromArgbColor(int a, Color col) - { - Color temp = new Color(); - temp.A = a; - temp.R = col.R; - temp.G = col.G; - temp.B = col.B; - - return temp; - } - - - public static Color FromName(string name) - { - Color temp = Load(name); - return temp; - } - public string ToFormat() - { - if (string.IsNullOrEmpty(Name)) - { - return String.Format("rgb({0},{1},{2})", R.ToString(), G.ToString(), B.ToString()); - - // return String.Format("#{0}{1}{2}{3}", Util.ToHex(A), Util.ToHex(R), Util.ToHex(G), Util.ToHex(B)); - } - else - { - return Name; - } - } - - public string Save() - { - if (!string.IsNullOrEmpty(Name)) - { - return string.Format("{0}:{1}", - 0, Name); - } - else - { - return string.Format("{0}:{1}:{2}:{3}:{4}", 1, A, R, G, B); - } - } - - public override string ToString() - { - if (string.IsNullOrEmpty(Name)) - { - - return String.Format("#{0}{1}{2}", Util.ToHex(R), Util.ToHex(G), Util.ToHex(B)); - // return String.Format("#{0}{1}{2}{3}", Util.ToHex(A), Util.ToHex(R), Util.ToHex(G), Util.ToHex(B)); - } - else - { - return Name; - } - } - - public string ToSimpleHex() - { - if (string.IsNullOrEmpty(Name)) - { - - return String.Format("{0}{1}{2}{3}", Util.ToHex(A), Util.ToHex(R), Util.ToHex(G), Util.ToHex(B)); - } - else - { - return Name; - } - } - public static Color Load(string color) - { - int a=255, r=255, g=255, b=255; - - string[] pieces = color.Split(":"); - - if (pieces.Length == 5) - { - - a = int.Parse(pieces[1]); - r = int.Parse(pieces[2]); - g = int.Parse(pieces[3]); - b = int.Parse(pieces[4]); - } - else if (pieces.Length == 2) - { - return Color.FromName(pieces[1].ToLowerCase()); - } - else if (pieces.Length == 1 && pieces[0].StartsWith("#")) - { - return FromHex(pieces[0]); - } - else if (pieces.Length == 1 && pieces[0].Length == 8) - { - return FromSimpleHex(pieces[0]); - } - else if (pieces.Length == 1) - { - return FromWindowsNamedColor(pieces[0]); - } - return Color.FromArgb(a, r, g, b); - } - - private static Color FromWindowsNamedColor(string color) - { - switch (color.ToLowerCase()) - { - case "activeborder": - return Color.FromArgb(255, 180, 180, 180); - case "activecaption": - return Color.FromArgb(255, 153, 180, 209); - case "activecaptiontext": - return Color.FromArgb(255, 0, 0, 0); - case "appworkspace": - return Color.FromArgb(255, 171, 171, 171); - case "control": - return Color.FromArgb(255, 240, 240, 240); - case "controldark": - return Color.FromArgb(255, 160, 160, 160); - case "controldarkdark": - return Color.FromArgb(255, 105, 105, 105); - case "controllight": - return Color.FromArgb(255, 227, 227, 227); - case "controllightlight": - return Color.FromArgb(255, 255, 255, 255); - case "controltext": - return Color.FromArgb(255, 0, 0, 0); - case "desktop": - return Color.FromArgb(255, 255, 255, 255); - case "graytext": - return Color.FromArgb(255, 109, 109, 109); - case "highlight": - return Color.FromArgb(255, 51, 153, 255); - case "highlighttext": - return Color.FromArgb(255, 255, 255, 255); - case "hottrack": - return Color.FromArgb(255, 0, 102, 204); - case "inactiveborder": - return Color.FromArgb(255, 244, 247, 252); - case "inactivecaption": - return Color.FromArgb(255, 191, 205, 219); - case "inactivecaptiontext": - return Color.FromArgb(255, 0, 0, 0); - case "info": - return Color.FromArgb(255, 255, 255, 225); - case "infotext": - return Color.FromArgb(255, 0, 0, 0); - case "menu": - return Color.FromArgb(255, 240, 240, 240); - case "menutext": - return Color.FromArgb(255, 0, 0, 0); - case "scrollbar": - return Color.FromArgb(255, 200, 200, 200); - case "window": - return Color.FromArgb(255, 255, 255, 255); - case "windowframe": - return Color.FromArgb(255, 100, 100, 100); - case "windowtext": - return Color.FromArgb(255, 0, 0, 0); - case "transparent": - return Color.FromArgb(0, 255, 255, 255); - case "aliceblue": - return Color.FromArgb(255, 240, 248, 255); - case "antiquewhite": - return Color.FromArgb(255, 250, 235, 215); - case "aqua": - return Color.FromArgb(255, 0, 255, 255); - case "aquamarine": - return Color.FromArgb(255, 127, 255, 212); - case "azure": - return Color.FromArgb(255, 240, 255, 255); - case "beige": - return Color.FromArgb(255, 245, 245, 220); - case "bisque": - return Color.FromArgb(255, 255, 228, 196); - case "black": - return Color.FromArgb(255, 0, 0, 0); - case "blanchedalmond": - return Color.FromArgb(255, 255, 235, 205); - case "blue": - return Color.FromArgb(255, 0, 0, 255); - case "blueviolet": - return Color.FromArgb(255, 138, 43, 226); - case "brown": - return Color.FromArgb(255, 165, 42, 42); - case "burlywood": - return Color.FromArgb(255, 222, 184, 135); - case "cadetblue": - return Color.FromArgb(255, 95, 158, 160); - case "chartreuse": - return Color.FromArgb(255, 127, 255, 0); - case "chocolate": - return Color.FromArgb(255, 210, 105, 30); - case "coral": - return Color.FromArgb(255, 255, 127, 80); - case "cornflowerblue": - return Color.FromArgb(255, 100, 149, 237); - case "cornsilk": - return Color.FromArgb(255, 255, 248, 220); - case "crimson": - return Color.FromArgb(255, 220, 20, 60); - case "cyan": - return Color.FromArgb(255, 0, 255, 255); - case "darkblue": - return Color.FromArgb(255, 0, 0, 139); - case "darkcyan": - return Color.FromArgb(255, 0, 139, 139); - case "darkgoldenrod": - return Color.FromArgb(255, 184, 134, 11); - case "darkgray": - return Color.FromArgb(255, 169, 169, 169); - case "darkgreen": - return Color.FromArgb(255, 0, 100, 0); - case "darkkhaki": - return Color.FromArgb(255, 189, 183, 107); - case "darkmagenta": - return Color.FromArgb(255, 139, 0, 139); - case "darkolivegreen": - return Color.FromArgb(255, 85, 107, 47); - case "darkorange": - return Color.FromArgb(255, 255, 140, 0); - case "darkorchid": - return Color.FromArgb(255, 153, 50, 204); - case "darkred": - return Color.FromArgb(255, 139, 0, 0); - case "darksalmon": - return Color.FromArgb(255, 233, 150, 122); - case "darkseagreen": - return Color.FromArgb(255, 143, 188, 139); - case "darkslateblue": - return Color.FromArgb(255, 72, 61, 139); - case "darkslategray": - return Color.FromArgb(255, 47, 79, 79); - case "darkturquoise": - return Color.FromArgb(255, 0, 206, 209); - case "darkviolet": - return Color.FromArgb(255, 148, 0, 211); - case "deeppink": - return Color.FromArgb(255, 255, 20, 147); - case "deepskyblue": - return Color.FromArgb(255, 0, 191, 255); - case "dimgray": - return Color.FromArgb(255, 105, 105, 105); - case "dodgerblue": - return Color.FromArgb(255, 30, 144, 255); - case "firebrick": - return Color.FromArgb(255, 178, 34, 34); - case "floralwhite": - return Color.FromArgb(255, 255, 250, 240); - case "forestgreen": - return Color.FromArgb(255, 34, 139, 34); - case "fuchsia": - return Color.FromArgb(255, 255, 0, 255); - case "gainsboro": - return Color.FromArgb(255, 220, 220, 220); - case "ghostwhite": - return Color.FromArgb(255, 248, 248, 255); - case "gold": - return Color.FromArgb(255, 255, 215, 0); - case "goldenrod": - return Color.FromArgb(255, 218, 165, 32); - case "gray": - return Color.FromArgb(255, 128, 128, 128); - case "green": - return Color.FromArgb(255, 0, 128, 0); - case "greenyellow": - return Color.FromArgb(255, 173, 255, 47); - case "honeydew": - return Color.FromArgb(255, 240, 255, 240); - case "hotpink": - return Color.FromArgb(255, 255, 105, 180); - case "indianred": - return Color.FromArgb(255, 205, 92, 92); - case "indigo": - return Color.FromArgb(255, 75, 0, 130); - case "ivory": - return Color.FromArgb(255, 255, 255, 240); - case "khaki": - return Color.FromArgb(255, 240, 230, 140); - case "lavender": - return Color.FromArgb(255, 230, 230, 250); - case "lavenderblush": - return Color.FromArgb(255, 255, 240, 245); - case "lawngreen": - return Color.FromArgb(255, 124, 252, 0); - case "lemonchiffon": - return Color.FromArgb(255, 255, 250, 205); - case "lightblue": - return Color.FromArgb(255, 173, 216, 230); - case "lightcoral": - return Color.FromArgb(255, 240, 128, 128); - case "lightcyan": - return Color.FromArgb(255, 224, 255, 255); - case "lightgoldenrodyellow": - return Color.FromArgb(255, 250, 250, 210); - case "lightgray": - return Color.FromArgb(255, 211, 211, 211); - case "lightgreen": - return Color.FromArgb(255, 144, 238, 144); - case "lightpink": - return Color.FromArgb(255, 255, 182, 193); - case "lightsalmon": - return Color.FromArgb(255, 255, 160, 122); - case "lightseagreen": - return Color.FromArgb(255, 32, 178, 170); - case "lightskyblue": - return Color.FromArgb(255, 135, 206, 250); - case "lightslategray": - return Color.FromArgb(255, 119, 136, 153); - case "lightsteelblue": - return Color.FromArgb(255, 176, 196, 222); - case "lightyellow": - return Color.FromArgb(255, 255, 255, 224); - case "lime": - return Color.FromArgb(255, 0, 255, 0); - case "limegreen": - return Color.FromArgb(255, 50, 205, 50); - case "linen": - return Color.FromArgb(255, 250, 240, 230); - case "magenta": - return Color.FromArgb(255, 255, 0, 255); - case "maroon": - return Color.FromArgb(255, 128, 0, 0); - case "mediumaquamarine": - return Color.FromArgb(255, 102, 205, 170); - case "mediumblue": - return Color.FromArgb(255, 0, 0, 205); - case "mediumorchid": - return Color.FromArgb(255, 186, 85, 211); - case "mediumpurple": - return Color.FromArgb(255, 147, 112, 219); - case "mediumseagreen": - return Color.FromArgb(255, 60, 179, 113); - case "mediumslateblue": - return Color.FromArgb(255, 123, 104, 238); - case "mediumspringgreen": - return Color.FromArgb(255, 0, 250, 154); - case "mediumturquoise": - return Color.FromArgb(255, 72, 209, 204); - case "mediumvioletred": - return Color.FromArgb(255, 199, 21, 133); - case "midnightblue": - return Color.FromArgb(255, 25, 25, 112); - case "mintcream": - return Color.FromArgb(255, 245, 255, 250); - case "mistyrose": - return Color.FromArgb(255, 255, 228, 225); - case "moccasin": - return Color.FromArgb(255, 255, 228, 181); - case "navajowhite": - return Color.FromArgb(255, 255, 222, 173); - case "navy": - return Color.FromArgb(255, 0, 0, 128); - case "oldlace": - return Color.FromArgb(255, 253, 245, 230); - case "olive": - return Color.FromArgb(255, 128, 128, 0); - case "olivedrab": - return Color.FromArgb(255, 107, 142, 35); - case "orange": - return Color.FromArgb(255, 255, 165, 0); - case "orangered": - return Color.FromArgb(255, 255, 69, 0); - case "orchid": - return Color.FromArgb(255, 218, 112, 214); - case "palegoldenrod": - return Color.FromArgb(255, 238, 232, 170); - case "palegreen": - return Color.FromArgb(255, 152, 251, 152); - case "paleturquoise": - return Color.FromArgb(255, 175, 238, 238); - case "palevioletred": - return Color.FromArgb(255, 219, 112, 147); - case "papayawhip": - return Color.FromArgb(255, 255, 239, 213); - case "peachpuff": - return Color.FromArgb(255, 255, 218, 185); - case "peru": - return Color.FromArgb(255, 205, 133, 63); - case "pink": - return Color.FromArgb(255, 255, 192, 203); - case "plum": - return Color.FromArgb(255, 221, 160, 221); - case "powderblue": - return Color.FromArgb(255, 176, 224, 230); - case "purple": - return Color.FromArgb(255, 128, 0, 128); - case "red": - return Color.FromArgb(255, 255, 0, 0); - case "rosybrown": - return Color.FromArgb(255, 188, 143, 143); - case "royalblue": - return Color.FromArgb(255, 65, 105, 225); - case "saddlebrown": - return Color.FromArgb(255, 139, 69, 19); - case "salmon": - return Color.FromArgb(255, 250, 128, 114); - case "sandybrown": - return Color.FromArgb(255, 244, 164, 96); - case "seagreen": - return Color.FromArgb(255, 46, 139, 87); - case "seashell": - return Color.FromArgb(255, 255, 245, 238); - case "sienna": - return Color.FromArgb(255, 160, 82, 45); - case "silver": - return Color.FromArgb(255, 192, 192, 192); - case "skyblue": - return Color.FromArgb(255, 135, 206, 235); - case "slateblue": - return Color.FromArgb(255, 106, 90, 205); - case "slategray": - return Color.FromArgb(255, 112, 128, 144); - case "snow": - return Color.FromArgb(255, 255, 250, 250); - case "springgreen": - return Color.FromArgb(255, 0, 255, 127); - case "steelblue": - return Color.FromArgb(255, 70, 130, 180); - case "tan": - return Color.FromArgb(255, 210, 180, 140); - case "teal": - return Color.FromArgb(255, 0, 128, 128); - case "thistle": - return Color.FromArgb(255, 216, 191, 216); - case "tomato": - return Color.FromArgb(255, 255, 99, 71); - case "turquoise": - return Color.FromArgb(255, 64, 224, 208); - case "violet": - return Color.FromArgb(255, 238, 130, 238); - case "wheat": - return Color.FromArgb(255, 245, 222, 179); - case "white": - return Color.FromArgb(255, 255, 255, 255); - case "whitesmoke": - return Color.FromArgb(255, 245, 245, 245); - case "yellow": - return Color.FromArgb(255, 255, 255, 0); - case "yellowgreen": - return Color.FromArgb(255, 154, 205, 50); - case "buttonface": - return Color.FromArgb(255, 240, 240, 240); - case "buttonhighlight": - return Color.FromArgb(255, 255, 255, 255); - case "buttonshadow": - return Color.FromArgb(255, 160, 160, 160); - case "gradientactivecaption": - return Color.FromArgb(255, 185, 209, 234); - case "gradientinactivecaption": - return Color.FromArgb(255, 215, 228, 242); - case "menubar": - return Color.FromArgb(255, 240, 240, 240); - case "menuhighlight": - return Color.FromArgb(255, 51, 153, 255); - } - return Color.FromArgb(255, 255, 255, 255); - } - - - - public static Color FromHex(string data) - { - int r = Util.FromHex(data.Substr(1, 2)); - int g = Util.FromHex(data.Substr(3, 2)); - int b = Util.FromHex(data.Substr(5, 2)); - // int b = Util.FromHex(data.Substr(7, 2)); - int a = 255; - return Color.FromArgb(a, r, g, b); - } - - public static Color FromSimpleHex(string data) - { - int a = Util.FromHex(data.Substr(0, 2)); - int r = Util.FromHex(data.Substr(2, 2)); - int g = Util.FromHex(data.Substr(4, 2)); - int b = Util.FromHex(data.Substr(6, 2)); - return Color.FromArgb(a, r, g, b); - } - - public static Color FromInt(UInt32 color) - { - UInt32 r = (color & 0xFF000000) >> 24; - UInt32 g = (color & 0x00FF0000) >> 16; - UInt32 b = (color & 0x0000FF00) >> 8; - UInt32 a = (color & 0x00000FF); - return Color.FromArgb(a, r, g, b); - } - - - - internal Color Clone() - { - return Color.FromArgb(A, R, G, B); - } - } - - // Summary: - // Implements a set of predefined colors. - public sealed class Colors - { - // Summary: - // Gets the system-defined color that has the ARGB value of #FF000000. - // - // Returns: - // A System.Windows.Media.Color that has an ARGB value of #FF000000. - public static Color Black { get { return Color.FromArgb(255, 0, 0, 0); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FF0000FF. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FF0000FF. - public static Color Blue { get { return Color.FromArgb(255, 0, 0, 255); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFA52A2A. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFA52A2A. - public static Color Brown { get { return Color.FromArgb(255, 165, 42, 42); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FF00FFFF. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FF00FFFF. - public static Color Cyan { get { return Color.FromArgb(255, 0, 255, 255); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFA9A9A9. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFA9A9A9. - public static Color DarkGray { get { return Color.FromArgb(255, 169, 169, 169); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FF808080. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FF808080. - public static Color Gray { get { return Color.FromArgb(255, 128, 128, 128); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FF008000. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FF008000. - public static Color Green { get { return Color.FromArgb(255, 0, 255, 0); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFD3D3D3. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFD3D3D3. - public static Color LightGray { get { return Color.FromArgb(255, 211, 211, 211); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFFF00FF. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFFF00FF. - public static Color Magenta { get { return Color.FromArgb(255, 255, 0, 255); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFFFA500. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFFFA500. - public static Color Orange { get { return Color.FromArgb(255, 255, 165, 0); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FF800080. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FF800080. - public static Color Purple { get { return Color.FromArgb(255, 128, 0, 128); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFFF0000. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFFF0000. - public static Color Red { get { return Color.FromArgb(255, 255, 0, 0); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #00FFFFFF. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #00FFFFFF. - public static Color Transparent { get { return Color.FromArgb(0, 255, 255, 255); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFFFFFFF. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFFFFFFF. - public static Color White { get { return Color.FromArgb(255, 255, 255, 255); } } - // - // Summary: - // Gets the system-defined color that has the ARGB value of #FFFFFF00. - // - // Returns: - // A System.Windows.Media.Color that has the ARGB value of #FFFFFF00. - public static Color Yellow { get { return Color.FromArgb(255, 255, 255, 0); } } - } -} diff --git a/engine/csharp_ref/Constellations.cs b/engine/csharp_ref/Constellations.cs deleted file mode 100644 index 8a2663ea..00000000 --- a/engine/csharp_ref/Constellations.cs +++ /dev/null @@ -1,1112 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Html.Media.Graphics; -using System.Runtime.CompilerServices; - -namespace wwtlib -{ - public class Constellations - { - string name; - static WebFile webFileConstNames; - WebFile webFile; - - public string Name - { - get { return name; } - set { name = value; } - } - - string url; - public List lines; - int pointCount = 0; - bool boundry = false; - bool noInterpollation = false; - public bool ReadOnly = false; - - public static Constellations CreateBasic(string name) - { - Constellations temp = new Constellations(); - temp.name = name; - temp.url = null; - temp.lines = new List(); - foreach (string abbrv in FullNames.Keys) - { - temp.lines.Add(new Lineset(abbrv)); - } - return temp; - } - - public Constellations() - { - } - - public static Constellations Create(string name, string url, bool boundry, bool noInterpollation, bool resource) - { - Constellations temp = new Constellations(); - - temp.noInterpollation = noInterpollation; - temp.boundry = boundry; - temp.name = name; - temp.url = url; - - temp.GetFile(); - - return temp; - } - - public void GetFile() - { - webFile = new WebFile(url); - webFile.OnStateChange = FileStateChange; - webFile.Send(); - } - - public void FileStateChange() - { - if(webFile.State == StateType.Error) - { - Script.Literal("alert({0})", webFile.Message); - } - else if(webFile.State == StateType.Received) - { - LoadConstellationData(webFile.GetText()); - } - - } - - private void LoadConstellationData(string data) - { - if (boundry && !noInterpollation) - { - boundries = new Dictionary(); - } - lines = new List(); - - Lineset lineSet = null; - - try - { - string[] rows = data.Split("\r\n"); - string abrv; - string abrvOld = ""; - double ra; - double dec; - double lastRa = 0; - PointType type = PointType.Move; - - foreach(string row in rows) - { - string line = row; - - if (line.Substr(11, 2) == "- ") - { - line = line.Substr(0, 11) + " -" + line.Substr(13, (line.Length - 13)); - } - if (line.Substr(11, 2) == "+ ") - { - line = line.Substr(0, 11) + " +" + line.Substr(13, (line.Length - 13)); - } - dec = double.Parse(line.Substr(11, 10)); - if (noInterpollation) - { - ra = double.Parse(line.Substr(0, 10)); - } - else - { - ra = double.Parse(line.Substr(0, 10)); - } - - abrv = line.Substr(23, 4).Trim(); - if (!boundry) - { - if (line.Substr(28, 1).Trim() != "") - { - type = (PointType)int.Parse(line.Substr(28, 1)); - } - } - else - { - if (this.noInterpollation && line.Substr(28, 1) != "O") - { - continue; - } - } - - // if (abrv != abrvOld || type == PointType.Move) - if (abrv != abrvOld) - { - type = PointType.Start; - lineSet = new Lineset(abrv); - lines.Add(lineSet); - if (boundry && !noInterpollation) - { - boundries[abrv] = lineSet; - } - abrvOld = abrv; - lastRa = 0; - } - - - if (this.noInterpollation) - { - if (Math.Abs(ra - lastRa) > 12) - { - ra = ra - (24 * ((ra - lastRa) < 0 ? -1 : 1)); - } - lastRa = ra; - //console.WriteLine(String.Format("{0}, ra:{1}",abrv,ra)); - } - string starName = null; - if (line.Length > 30) - { - starName = line.Substr(30).Trim(); - } - - if (starName == null || starName != "Empty") - { - lineSet.Add(ra, dec, type, starName); - } - pointCount++; - type = PointType.Line; - - } - } - catch - { - } - - WWTControl.RenderNeeded = true; - } - - protected const double RC = 0.017453292519943; - protected double radius = 1.0f; - - public void Draw(RenderContext renderContext, bool showOnlySelected, string focusConsteallation, bool clearExisting) - { - maxSeperation = Math.Max(.6, Math.Cos((renderContext.FovAngle * 2) / 180.0 * Math.PI)); - - drawCount = 0; - Lineset lsSelected = null; - if (lines == null || ConstellationCentroids == null) - { - return; - } - - constToDraw = focusConsteallation; - - foreach (Lineset ls in this.lines) - { - if (constToDraw == ls.Name && boundry) - { - lsSelected = ls; - } - else if (!showOnlySelected || !boundry) - { - DrawSingleConstellation(renderContext, ls, 1f); - } - } - - if (lsSelected != null) - { - DrawSingleConstellation(renderContext, lsSelected, 1f); - - } - } - - int drawCount = 0; - static double maxSeperation = .745; - - Dictionary constellationVertexBuffers = new Dictionary(); - - private void DrawSingleConstellation(RenderContext renderContext, Lineset ls, float opacity) - { - bool reverse = false; - Place centroid = ConstellationCentroids[ls.Name]; - if (centroid != null) - { - Vector3d pos = Coordinates.RADecTo3d(reverse ? -centroid.RA - 6 : centroid.RA, reverse ? centroid.Dec : centroid.Dec); - - if (Vector3d.Dot(renderContext.ViewPoint, pos) < maxSeperation) - { - return; - } - } - - if (!constellationVertexBuffers.ContainsKey(ls.Name)) - { - int count = ls.Points.Count; - - SimpleLineList linelist = new SimpleLineList(); - linelist.DepthBuffered = false; - constellationVertexBuffers[ls.Name] = linelist; - - Vector3d currentPoint = new Vector3d(); - Vector3d temp; - - for (int i = 0; i < count; i++) - { - - if (ls.Points[i].PointType == PointType.Move || i == 0) - { - currentPoint = Coordinates.RADecTo3d(ls.Points[i].RA, ls.Points[i].Dec); - } - else - { - temp = Coordinates.RADecTo3d(ls.Points[i].RA, ls.Points[i].Dec); - linelist.AddLine(currentPoint, temp); - currentPoint = temp; - } - } - - if (boundry) - { - temp = Coordinates.RADecTo3d(ls.Points[0].RA, ls.Points[0].Dec); - linelist.AddLine(currentPoint, temp); - } - } - - string col = "red"; - if (boundry) - { - if (constToDraw != ls.Name) - { - col = Settings.GlobalSettings.ConstellationBoundryColor; - } - else - { - col = Settings.GlobalSettings.ConstellationSelectionColor; - } - } - else - { - col = Settings.GlobalSettings.ConstellationFigureColor; - } - - constellationVertexBuffers[ls.Name].DrawLines(renderContext, opacity, Color.Load(col)); - - } - - //protected Vector3d RaDecTo3d(double lat, double lng) - //{ - // return Vector3d.Create((Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius), (Math.Sin(lat * RC) * radius), (Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius)); - //} - - private void DrawSingleConstellationOld(RenderContext renderContext, Lineset ls) - { - bool reverse = false; - // todo get this working - Place centroid = ConstellationCentroids[ls.Name]; - if (centroid != null) - { - Vector3d pos = Coordinates.RADecTo3d(reverse ? -centroid.RA - 6 : centroid.RA, reverse ? centroid.Dec : centroid.Dec); - - if (Vector3d.Dot(renderContext.ViewPoint, pos) < maxSeperation) - { - return; - } - } - - drawCount++; - string col; - if (boundry) - { - if (constToDraw != ls.Name) - { - col = Settings.GlobalSettings.ConstellationBoundryColor; - } - else - { - col = Settings.GlobalSettings.ConstellationSelectionColor; - } - } - else - { - col = Settings.GlobalSettings.ConstellationFigureColor; - } - - if (renderContext.gl == null) - { - CanvasContext2D ctx = renderContext.Device; - - int count = ls.Points.Count; - - Vector3d lastPoint = new Vector3d(); - ctx.Save(); - bool linePending = false; - ctx.BeginPath(); - ctx.StrokeStyle = col; - ctx.LineWidth = 2; - ctx.Alpha = .25; - for (int i = 0; i < count; i++) - { - - - if (ls.Points[i].PointType == PointType.Move || i == 0) - { - if (linePending) - { - ctx.Stroke(); - } - lastPoint = renderContext.WVP.Transform(Coordinates.RADecTo3d(ls.Points[i].RA, ls.Points[i].Dec)); - - ctx.MoveTo(lastPoint.X, lastPoint.Y); - } - else - { - Vector3d newPoint = renderContext.WVP.Transform(Coordinates.RADecTo3d(ls.Points[i].RA, ls.Points[i].Dec)); - - // if (lastPoint.Z > 0 && newPoint.Z > 0) - { - ctx.LineTo(newPoint.X, newPoint.Y); - linePending = true; - } - } - } - - if (boundry) - { - ctx.ClosePath(); - } - - ctx.Stroke(); - ctx.Restore(); - } - else - { - //todo add webgl method of drawing - } - } - - public static Constellations Containment = null; // initialized in InitializeConstellations - - static string constToDraw = ""; - - public static Linepoint SelectedSegment = null; - - public string FindConstellationForPoint(double ra, double dec) - { - if (dec > 88.402 || this.lines == null) - { - return "UMI"; - } - - foreach (Lineset ls in this.lines) - { - int count = ls.Points.Count; - - int i; - int j; - bool inside = false; - for (i = 0, j = count - 1; i < count; j = i++) - { - - if ((((ls.Points[i].Dec <= dec) && (dec < ls.Points[j].Dec)) || - ((ls.Points[j].Dec <= dec) && (dec < ls.Points[i].Dec))) && - (ra < (ls.Points[j].RA - ls.Points[i].RA) * (dec - ls.Points[i].Dec) / (ls.Points[j].Dec - ls.Points[i].Dec) + ls.Points[i].RA)) - { - - inside = !inside; - } - } - if (inside) - { - //constToDraw = ls.Name; - return ls.Name; - } - } - if (ra > 0) - { - return FindConstellationForPoint(ra - 24, dec); - } - - // Ursa Minor is tricky since it wraps around the poles. It can evade the point in rect test - if (dec > 65.5) - { - return "UMI"; - } - if (dec < -65.5) - { - return "OCT"; - } - return "Error"; - } - - static Text3dBatch NamesBatch; - - public static void DrawConstellationNames(RenderContext renderContext, float opacity, Color drawColor) - { - if (NamesBatch == null) - { - - InitializeConstellationNames(); - if (NamesBatch == null) - { - return; - } - } - NamesBatch.Draw(renderContext, opacity, drawColor); - } - - public static void InitializeConstellationNames() - { - if (ConstellationCentroids == null) - { - return; - } - - NamesBatch = new Text3dBatch(Settings.Active.ConstellationLabelsHeight); - - foreach (string key in ConstellationCentroids.Keys) - { - IPlace centroid = ConstellationCentroids[key]; - - Vector3d center = Coordinates.RADecTo3dAu(centroid.RA, centroid.Dec, 1); - Vector3d up = Vector3d.Create(0, 1, 0); - string name = centroid.Name; - - if (centroid.Name == "Triangulum Australe") - { - name = name.Replace(" ", "\n "); - } - NamesBatch.Add(new Text3d(center, up, name, Settings.Active.ConstellationLabelsHeight, .000125)); - } - } - - static Folder artFile = null; - public static List Artwork = null; - - // The WWTControl driver will not (and should not) call this function in - // "freestanding mode", because the functionality depends on a - // worldwidetelescope.org API. - public static void DrawArtwork(RenderContext renderContext) - { - if (Artwork == null) - { - if (artFile == null) - { - artFile = new Folder(); - artFile.LoadFromUrl(URLHelpers.singleton.coreStaticUrl("wwtweb/catalog.aspx?W=hevelius"), OnArtReady); - } - - return; - } - - maxSeperation = Math.Max(.50, Math.Cos((renderContext.FovAngle * 2) / 180.0 * Math.PI)); - - foreach (Place place in Artwork) - { - BlendState bs = PictureBlendStates[place.Constellation]; - bs.TargetState = Settings.Active.ConstellationArtFilter.IsSet(place.Constellation); - - if (bs.State) - { - bool reverse = false; - Place centroid = ConstellationCentroids[place.Constellation]; - if (centroid != null) - { - Vector3d pos = Coordinates.RADecTo3d(reverse ? -centroid.RA - 6 : centroid.RA, reverse ? centroid.Dec : centroid.Dec); - - if (Vector3d.Dot(renderContext.ViewPoint, pos) > maxSeperation) - { - - renderContext.DrawImageSet(place.StudyImageset, 100); - } - - } - } - } - } - - static void OnArtReady() - { - artFile.ChildLoadCallback(LoadArtList); - } - - static void LoadArtList() - { - Artwork = artFile.Places; - } - - public static Dictionary boundries = null; - public static Dictionary FullNames; - public static Dictionary Abbreviations; - public static Dictionary ConstellationCentroids; - public static Dictionary PictureBlendStates = new Dictionary(); - - // Repeated invocations of this function are OK. - public static void InitializeConstellations() - { - if (Containment == null) { - string url = URLHelpers.singleton.engineAssetUrl("ConstellationNamePositions_EN.txt"); - webFileConstNames = new WebFile(url); - webFileConstNames.OnStateChange = LoadNames; - webFileConstNames.Send(); - - Containment = Constellations.Create( - "Constellations", - URLHelpers.singleton.engineAssetUrl("constellations.txt"), - true, // "boundry" - true, // "noInterpollation" - true // "resource" - ); - } - } - - static void LoadNames() - { - if (webFileConstNames.State == StateType.Error) - { - Script.Literal("alert({0})", webFileConstNames.Message); - } - else if (webFileConstNames.State == StateType.Received) - { - CentroidsReady(webFileConstNames.GetText()); - } - } - public static Dictionary BitIDs; - static void CentroidsReady(string file) - { - ConstellationCentroids = new Dictionary(); - FullNames = new Dictionary(); - Abbreviations = new Dictionary(); - BitIDs = new Dictionary(); - string[] rows = file.Split("\r\n"); - int id = 0; - string line; - foreach (string row in rows) - { - line = row; - string[] data = line.Split( ","); - FullNames[data[1]] = data[0]; - Abbreviations[data[0]] = data[1]; - BitIDs[data[1]] = id++; - PictureBlendStates[data[1]] = BlendState.Create(true, 1000); - ConstellationCentroids[data[1]] = Place.Create(data[0], double.Parse(data[3]), double.Parse(data[2]), Classification.Constellation, data[1], ImageSetType.Sky, 360); - } - WWTControl.RenderNeeded = true; - ConstellationFilter.BuildConstellationFilters(); - } - - static public string FullName(string name) - { - if (FullNames.ContainsKey(name)) - { - return FullNames[name]; - } - return name; - } - static public string Abbreviation(string name) - { - if (Abbreviations != null && !String.IsNullOrEmpty(name) && Abbreviations.ContainsKey(name)) - { - return Abbreviations[name]; - } - - return name; - } - - - } - - public class Lineset - { - string name; - - public string Name - { - get { return name; } - set { name = value; } - } - - public List Points; - - public Lineset(string name) - { - this.name = name; - - Points = new List(); - } - - public void Add(double ra, double dec, PointType pointType, string name) - { - Points.Add(new Linepoint(ra, dec, pointType, name)); - } - } - public class Linepoint - { - public double RA; - public double Dec; - public PointType PointType; - public string Name = null; - - public Linepoint(double ra, double dec, PointType type, string name) - { - RA = ra; - Dec = dec; - PointType = type; - Name = name; - } - public override string ToString() - { - if (string.IsNullOrEmpty(Name)) - { - return Coordinates.FormatDMS((((((RA)) / 360) * 24.0 + 12) % 24)) + ", " + Coordinates.FormatDMS(Dec) + ", " + PointType.ToString(); - } - else - { - return Name + ", " + PointType.ToString(); - } - } - } - public enum PointType { Move=0, Line=1, Dash=2, Start=3 }; - - - public class ConstellationFilter - { - public Int32[] Bits = new Int32[3]; - public Int32[] OldBits = new Int32[3]; - public BlendState BlendState = BlendState.Create(false, 1000); - public bool Internal = false; - public ConstellationFilter() - { - for (int i = 0; i < 3; i++) - { - Bits[i] = ~ Bits[i]; - OldBits[i] = Bits[i]; - } - } - private void SaveBits() - { - for (int i = 0; i < 3; i++) - { - OldBits[i] = Bits[i]; - } - } - - private bool IsChanged() - { - for (int i = 0; i < 3; i++) - { - if (OldBits[i] != Bits[i]) - { - return true; - } - } - return false; - } - - private void CheckChanged() - { - if (IsChanged()) - { - FireChanged(); - } - } - - public bool IsEnabled(string abbrev) - { - Int32 bitID = Constellations.BitIDs[abbrev]; - - int index = bitID / 32; - bitID = bitID % 32; - - return BlendState.State && ((1 << (bitID)) & Bits[index]) != 0; - } - - public bool IsSet(string abbrev) - { - SaveBits(); - - Int32 bitID = Constellations.BitIDs[abbrev]; - - int index = (int) (bitID / 32); - bitID = bitID % 32; - - return ((1 << (bitID)) & Bits[index]) != 0; - } - - public void Set(string abbrev, bool state) - { - SaveBits(); - int bitID = Constellations.BitIDs[abbrev]; - - int index = bitID / 32; - bitID = bitID % 32; - - if (state) - { - Bits[index] = Bits[index] | (1 << bitID); - } - else - { - Bits[index] = Bits[index] ^ (1 << bitID); - } - - CheckChanged(); - } - - public void SetAll(bool state) - { - SaveBits(); - for (int bitID = 0; bitID < 89; bitID++) - { - - int index = bitID / 32; - int bit = bitID % 32; - - if (state) - { - Bits[index] = Bits[index] | (1 << bit); - } - else - { - Bits[index] = Bits[index] ^ (1 << bit); - } - } - CheckChanged(); - } - - public void SetBits(byte[] bits) - { - SaveBits(); - for (int i = 0; i < 3; i++) - { - Bits[i] = ((int)bits[i * 4]) + (((int)bits[i * 4 + 1]) << 8) + (((int)bits[i * 4 + 2]) << 16) + (((int)bits[i * 4 + 3]) << 24); - } - CheckChanged(); - } - - public byte[] GetBits() - { - byte[] bits = new byte[12]; - - int index = 0; - for (int i = 0; i < 3; i++) - { - bits[index++] = (byte)(Bits[i]); - bits[index++] = (byte)(Bits[i] >> 8); - bits[index++] = (byte)(Bits[i] >> 16); - bits[index++] = (byte)(Bits[i] >> 24); - } - - return bits; - - } - - public void CloneFilter(ConstellationFilter filter) - { - SaveBits(); - for (int i = 0; i < 3; i++) - { - Bits[i] = filter.Bits[i]; - } - CheckChanged(); - } - - public ConstellationFilter Clone() - { - ConstellationFilter newFilter = new ConstellationFilter(); - newFilter.CloneFilter(this); - return newFilter; - } - - public void Combine(ConstellationFilter filter) - { - SaveBits(); - for (int i = 0; i < 3; i++) - { - Bits[i] = Bits[i] | filter.Bits[i]; - } - CheckChanged(); - } - - public void Remove(ConstellationFilter filter) - { - SaveBits(); - for (int i = 0; i < 3; i++) - { - Bits[i] = Bits[i] & ~filter.Bits[i]; - } - CheckChanged(); - } - - public static Dictionary Families = new Dictionary(); - - public static void BuildConstellationFilters() - { - ConstellationFilter all = AllConstellation; - all.Internal = true; - Families["AllConstellation"] = all; - Families["Zodiacal"] = Zodiacal; - Families["Ursa Major Family"]= UrsaMajorFamily; - Families["Perseus Family"]= PerseusFamily; - Families["Hercules Family"]= HerculesFamily; - Families["Orion Family"]= OrionFamily; - Families["Heavenly Waters"]= HeavenlyWaters; - Families["Bayer Family"]= BayerFamily; - Families["La Caille Family"]= LaCaileFamily; - //LoadCustomFilters(); - } - - public static void SaveCustomFilters() - { - StringBuilder sb = new StringBuilder(); - - foreach (KeyValuePair kv in Families) - { - if (!kv.Value.Internal) - { - sb.Append(kv.Key); - sb.Append(";"); - sb.AppendLine(kv.Value.ToString()); - - } - } - - //Properties.Settings.Default.SavedFilters = sb.ToString(); - } - - //public static void LoadCustomFilters() - //{ - // string[] lines = Properties.Settings.Default.SavedFilters.Split(new char[] { '\n' }); - // foreach (string line in lines) - // { - // try - // { - // string[] parts = line.Split(new char[] { ';' }); - // if (parts.Length > 1) - // { - // ConstellationFilter filter = ConstellationFilter.Parse(parts[1]); - // Families.Add(parts[0], filter); - // } - // } - // catch - // { - // } - // } - //} - - public static ConstellationFilter AllConstellation - { - get - { - ConstellationFilter all = new ConstellationFilter(); - - all.SetAll(true); - - return all; - } - - } - - public static ConstellationFilter Zodiacal - { - get - { - ConstellationFilter zodiacal = new ConstellationFilter(); - zodiacal.Set("ARI", true); - zodiacal.Set("TAU", true); - zodiacal.Set("GEM", true); - zodiacal.Set("CNC", true); - zodiacal.Set("LEO", true); - zodiacal.Set("VIR", true); - zodiacal.Set("LIB", true); - zodiacal.Set("SCO", true); - zodiacal.Set("SGR", true); - zodiacal.Set("CAP", true); - zodiacal.Set("AQR", true); - zodiacal.Set("PSC", true); - zodiacal.Internal = true; - return zodiacal; - } - - } - - public static ConstellationFilter UrsaMajorFamily - { - get - { - ConstellationFilter uma = new ConstellationFilter(); - uma.Set("UMA", true); - uma.Set("UMI", true); - uma.Set("DRA", true); - uma.Set("CVN", true); - uma.Set("BOO", true); - uma.Set("COM", true); - uma.Set("CRB", true); - uma.Set("CAM", true); - uma.Set("LYN", true); - uma.Set("LMI", true); - uma.Internal = true; - return uma; - } - } - - public static ConstellationFilter PerseusFamily - { - get - { - ConstellationFilter Perseus = new ConstellationFilter(); - Perseus.Set("CAS", true); - Perseus.Set("CEP", true); - Perseus.Set("AND", true); - Perseus.Set("PER", true); - Perseus.Set("PEG", true); - Perseus.Set("CET", true); - Perseus.Set("AUR", true); - Perseus.Set("LAC", true); - Perseus.Set("TRI", true); - Perseus.Internal = true; - - return Perseus; - } - - } - - public static ConstellationFilter HerculesFamily - { - get - { - ConstellationFilter hercules = new ConstellationFilter(); - hercules.Set("HER", true); - hercules.Set("SGE", true); - hercules.Set("AQL", true); - hercules.Set("LYR", true); - hercules.Set("CYG", true); - hercules.Set("VUL", true); - hercules.Set("HYA", true); - hercules.Set("SEX", true); - hercules.Set("CRT", true); - hercules.Set("CRV", true); - hercules.Set("OPH", true); - hercules.Set("SER1", true); - hercules.Set("SER2", true); - hercules.Set("SCT", true); - hercules.Set("CEN", true); - hercules.Set("LUP", true); - hercules.Set("CRA", true); - hercules.Set("ARA", true); - hercules.Set("TRA", true); - hercules.Set("CRU", true); - hercules.Internal = true; - - return hercules; - } - - } - public static ConstellationFilter OrionFamily - { - get - { - ConstellationFilter orion = new ConstellationFilter(); - orion.Set("ORI", true); - orion.Set("CMA", true); - orion.Set("CMI", true); - orion.Set("MON", true); - orion.Set("LEP", true); - orion.Internal = true; - - return orion; - } - - } - public static ConstellationFilter HeavenlyWaters - { - get - { - ConstellationFilter waters = new ConstellationFilter(); - waters.Set("DEL", true); - waters.Set("EQU", true); - waters.Set("ERI", true); - waters.Set("PSA", true); - waters.Set("CAR", true); - waters.Set("PUP", true); - waters.Set("VEL", true); - waters.Set("PYX", true); - waters.Set("COL", true); - waters.Internal = true; - return waters; - } - } - public static ConstellationFilter BayerFamily - { - get - { - ConstellationFilter bayer = new ConstellationFilter(); - bayer.Set("HYA", true); - bayer.Set("DOR", true); - bayer.Set("VOL", true); - bayer.Set("APS", true); - bayer.Set("PAV", true); - bayer.Set("GRU", true); - bayer.Set("PHE", true); - bayer.Set("TUC", true); - bayer.Set("IND", true); - bayer.Set("CHA", true); - bayer.Set("MUS", true); - bayer.Internal = true; - return bayer; - } - - } - public static ConstellationFilter LaCaileFamily - { - get - { - ConstellationFilter LaCaile = new ConstellationFilter(); - LaCaile.Set("NOR", true); - LaCaile.Set("CIR", true); - LaCaile.Set("TEL", true); - LaCaile.Set("MIC", true); - LaCaile.Set("SCL", true); - LaCaile.Set("FOR", true); - LaCaile.Set("CAE", true); - LaCaile.Set("HOR", true); - LaCaile.Set("OCT", true); - LaCaile.Set("MEN", true); - LaCaile.Set("RET", true); - LaCaile.Set("PIC", true); - LaCaile.Set("ANT", true); - LaCaile.Internal = true; - return LaCaile; - } - - } - - public bool SettingsOwned = false; - private void FireChanged() - { - if (SettingsOwned) - { - // Properties.Settings.Default.PulseMeForUpdate = !Properties.Settings.Default.PulseMeForUpdate; - } - } - - public override string ToString() - { - return string.Format("{0},{1},{2}", Bits[0], Bits[1], Bits[2]); - } - - public static ConstellationFilter Parse(string val) - { - string[] parts = ((string)val).Split(","); - - ConstellationFilter cf = new ConstellationFilter(); - try - { - for (int i = 0; i < 3; i++) - { - cf.Bits[i] = Int32.Parse(parts[i]); - } - } - catch - { - } - - return cf; - } - } -} diff --git a/engine/csharp_ref/Coordinates.cs b/engine/csharp_ref/Coordinates.cs deleted file mode 100644 index 4dfba303..00000000 --- a/engine/csharp_ref/Coordinates.cs +++ /dev/null @@ -1,1186 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace wwtlib -{ - public class Coordinates - { - protected const double RC = (3.1415927 / 180.0); - protected const double RCRA = (3.1415927 / 12.0); - protected const float radius = 1; - - // NB: these functions are redundant in the webclient because we don't - // have the single-precision `Vector3` type that's distinguished from - // `Vector3d`. To minimize the code delta from Windows, we keep both - // names for simplicity. But the `...Rad` functions are added because - // ScriptSharp can't deal with overloads. - - static public Vector3d GeoTo3d(double lat, double lng) - { - return Vector3d.Create(Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius, Math.Sin(lat * RC) * radius, Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius); - } - - static public Vector3d GeoTo3dDouble(double lat, double lng) - { - return Vector3d.Create(Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius, Math.Sin(lat * RC) * radius, Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius); - } - - //static public Vector3d GeoTo3dDoubleRad(double lat, double lng, double radius) - //{ - // return Vector3d.Create(Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius, Math.Sin(lat * RC) * radius, Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius); - //} - - static public Vector3d GeoTo3dRad(double lat, double lng, double radius) - { - return Vector3d.Create(Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius, Math.Sin(lat * RC) * radius, Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius); - } - - static public Vector3d RADecTo3d(double ra, double dec) - { - return Vector3d.Create(Math.Cos(ra * RCRA) * Math.Cos(dec * RC) * radius, Math.Sin(dec * RC) * radius, Math.Sin(ra * RCRA) * Math.Cos(dec * RC) * radius); - } - - static public Vector3d RADecTo3dAu(double ra, double dec, double au) - { - return Vector3d.Create(Math.Cos(ra * RCRA) * Math.Cos(dec * RC) * au, Math.Sin(dec * RC) * au, Math.Sin(ra * RCRA) * Math.Cos(dec * RC) * au); - } - - static public Vector3d RADecTo3dMat(double ra, double dec, Matrix3d mat) - { - return Vector3d.TransformCoordinate(Vector3d.Create((Math.Cos(ra * RCRA) * Math.Cos(dec * RC) * radius), (Math.Sin(dec * RC) * radius), (Math.Sin(ra * RCRA) * Math.Cos(dec * RC) * radius)), mat); - } - - static public Vector3d RADecTo3dPointRad(Coordinates point, double radius) - { - point.Dec = -point.Dec; - return Vector3d.Create((Math.Cos(point.RA * RCRA) * Math.Cos(point.Dec * RC) * radius), (Math.Sin(point.Dec * RC) * radius), (Math.Sin(point.RA * RCRA) * Math.Cos(point.Dec * RC) * radius)); - } - - const double EarthRadius = 6371000; - - static public Vector3d SterographicTo3d(double x, double y, double radius, double standardLat, double meridean, double falseEasting, double falseNorthing, double scale, bool north ) - { - double lat=90; - double lng=0; - - x -= falseEasting; - y -= falseNorthing; - - if (x != 0 || y != 0) - { - double re = (1 + Math.Sin(Math.Abs(standardLat) / 180 * Math.PI)) * EarthRadius / scale; - double rere = re * re; - double c1 = 180 / Math.PI; - - if (x == 0) - { - lng = 90 * y < 0 ? -1 : 1; - } - else - { - lng = Math.Atan2(y , x) * c1; - } - - //if (x < 0) - //{ - // lng = lng + (180 * Math.Sign(y)); - //} - - //if (lng > 180) - //{ - // lng -= 360; - //} - - //if (lng < -180) - //{ - // lng += 360; - //} - - double len = (x * x) + (y * y); - lat = (rere - len) / (rere + len); - lat = Math.Asin(lat) * c1; - - if (!north) - { - lat = -lat; - lng = -lng; - meridean = -meridean; - } - } - return Coordinates.GeoTo3dRad(lat, 90 + lng + meridean, radius); - } - - //static public Coordinates EquitorialToHorizon4(Coordinates equitorial, Coordinates location, Date utc) - //{ - - // double lon = location.Lng; - - - - - // double hour = utc.GetHours() + utc.GetMinutes() / 60.00 + utc.GetSeconds() / 3600.0 + utc.GetMilliseconds() / 3600000.0; - - - // double day = utc.GetDate() + hour / 24.0; - - // double fullDays = Math.Floor(day); - - // int month = utc.GetMonth(); - // int year = utc.GetFullYear(); - // if (month < 3) - // { - // year--; - // month += 12; - // } - - - // double gr; - // if (year + month / 100 + fullDays / 10000 >= 1582.1015) - // { - // gr = 2 - Math.Floor(year / 100.0) + Math.Floor(Math.Floor(year / 100.0) / 4); - // } - // else - // { - // gr = 0; - // } - - - // double julianDay = Math.Floor(365.25 * year) + Math.Floor(30.6001 * (month + 1)) + fullDays + 1720994.5 + gr; - - // double julianDay2 = julianDay + hour / 24; - // double t = (julianDay - 2415020) / 36525; - // double ss1 = 6.6460656 + 2400.051 * t + 0.00002581 * t * t; - // double st = (ss1 / 24 - Math.Floor(ss1 / 24)) * 24; - // double gsth = Math.Floor(st); - // double gstm = Math.Floor((st - Math.Floor(st)) * 60); - // double gsts = ((st - Math.Floor(st)) * 60 - gstm) * 60; - - // double sa = st + (day - Math.Floor(day)) * 24 * 1.002737908; - - // sa = sa + (lon / 15); - - // if (sa < 0) - // { - // sa += 24; - // } - - // if (sa > 24) - // { - // sa -= 24; - // } - // double tsh = Math.Floor(sa); - // double tsm = Math.Floor((sa - Math.Floor(sa)) * 60); - // double tss = ((sa - Math.Floor(sa)) * 60 - tsm) * 60; - - // return new Coordinates(0, 0); - - //} - - public double Distance(Coordinates pointB) - { - double y = this.Lat; - double x = this.Lng * Math.Cos(y * RC); - double y1 = pointB.Lat; - double x1 = pointB.Lng * Math.Cos(y1 * RC); - return Math.Sqrt((y - y1) * (y - y1) + (x - x1) * (x - x1)); - } - - public double Distance3d(Coordinates pointB) - { - Vector3d pnt1 = Coordinates.GeoTo3dDouble(pointB.Lat, pointB.Lng); - Vector3d pnt2 = Coordinates.GeoTo3dDouble(this.Lat, this.Lng); - - Vector3d pntDiff = Vector3d.SubtractVectors(pnt1, pnt2); - - return pntDiff.Length() / RC; - } - - public double Angle(Coordinates pointB) - { - double y = this.Lat; - double x = this.Lng * Math.Cos(y * RC); - double y1 = pointB.Lat; - double x1 = pointB.Lng * Math.Cos(y1 * RC); - return Math.Atan2((y1 - y), (x1 - x)); - } - - static public Coordinates EquitorialToHorizon(Coordinates equitorial, Coordinates location, Date utc) - { - double hourAngle = MstFromUTC2(utc, location.Lng) - (equitorial.RA * 15); - - if (hourAngle < 0) - { - hourAngle += 360.00; - } - - double ha = hourAngle * RC; - double dec = equitorial.Dec * RC; - double lat = (location.Lat) * RC; - - double sinAlt = Math.Sin(dec) * Math.Sin(lat) + Math.Cos(dec) * Math.Cos(lat) * Math.Cos(ha); - - double altitude = Math.Asin(sinAlt); - - double cosAzimith = (Math.Sin(dec) - Math.Sin(altitude) * Math.Sin(lat)) / (Math.Cos(altitude) * Math.Cos(lat)); - double azimuth = Math.Acos(cosAzimith); - - - - Coordinates altAz = new Coordinates(azimuth, altitude); - if (Math.Sin(ha) > 0) - { - altAz.Az = (360 - altAz.Az); - } - return altAz; - } - - static public Coordinates HorizonToEquitorial(Coordinates altAz, Coordinates location, Date utc) - { - double hourAngle = MstFromUTC2(utc, location.Lng);// -(equitorial.RA * 15); - - double haLocal; - double declination; - Vector2d raDec = AltAzToRaDec(altAz.Alt * RC, altAz.Az * RC, location.Lat * RC); - - haLocal = raDec.X; - declination = raDec.Y; - - double ha = (haLocal / RC); - - hourAngle += ha; - - if (hourAngle < 0) - { - hourAngle += 360.00; - } - if (hourAngle > 360) - { - hourAngle -= 360; - } - - return Coordinates.FromRaDec(hourAngle / 15, declination / RC); - } - static Vector2d AltAzToRaDec(double Altitude, double Azimuth, double Latitude) - { - double hrAngle = 0; - double dec = 0; - Azimuth = Math.PI - Azimuth; - if (Azimuth < 0) - { - Azimuth += Math.PI * 2; - } - hrAngle = Math.Atan2(Math.Sin(Azimuth), Math.Cos(Azimuth) * Math.Sin(Latitude) + Math.Tan(Altitude) * Math.Cos(Latitude)); - - if (hrAngle < 0) - { - hrAngle += Math.PI * 2; - } - dec = Math.Asin(Math.Sin(Latitude) * Math.Sin(Altitude) - Math.Cos(Latitude) * Math.Cos(Altitude) * Math.Cos(Azimuth)); - - return Vector2d.Create(hrAngle,dec); - } - - //static void AltAzToRaDec2(double alt, double az, out double hrAngle, out double dec, double lat) - //{ - // if (alt == 0) - // { - // alt = .00000000001; - // } - // if (az == 0) - // { - // az = .00000000001; - // } - // double sin_dec; - // double cos_lat = Math.Cos(lat); - - // if (alt > Math.PI / 2.0) - // { - // alt = Math.PI - alt; - // az += Math.PI; - // } - // if (alt < -Math.PI / 2.0) - // { - // alt = -Math.PI - alt; - // az -= Math.PI; - // } - - // sin_dec = Math.Sin(lat) * Math.Sin(alt) + cos_lat * Math.Cos(alt) * Math.Cos(az); - // dec = Math.Asin(sin_dec); - - // if (cos_lat < .00001) - // { - // hrAngle = az + Math.PI; - // } - // else - // { - // double cos_lat_cos_dec = (cos_lat * Math.Cos(dec)); - // double sin_alt_sinLat_sin_dec = Math.Sin(alt) - Math.Sin(lat) * sin_dec; - - // double acosTarget = sin_alt_sinLat_sin_dec / cos_lat_cos_dec; - // double temp = 0; - // if (Math.Abs(acosTarget) < 1.1) - // { - // if (acosTarget > 1) - // { - // acosTarget = 1.0; - // } - // if (acosTarget < -1) - // { - // acosTarget = -1.0; - // } - // temp = Math.Acos(acosTarget); - // } - // else - // { - // temp = Math.PI; - // } - // //if (double.IsNaN(temp)) - // //{ - // // temp = Math.PI; - // //} - - // if (Math.Sin(az) > 0.0) - // { - // hrAngle = Math.PI - temp; - // } - // else - // { - // hrAngle = Math.PI + temp; - // } - // } - //} - - public static double MstFromUTC2(Date utc, double lng) - { - - int year = utc.GetUTCFullYear(); - int month = utc.GetUTCMonth()+1; - int day = utc.GetUTCDate(); - int hour = utc.GetUTCHours(); - int minute = utc.GetUTCMinutes(); - double second = utc.GetUTCSeconds() + utc.GetUTCMilliseconds() / 1000.0; - - if (month == 1 || month == 2) - { - year -= 1; - month += 12; - } - - int a = (int)(year / 100); - int b = 2 - a + (int)Math.Floor((double)(a / 4.0)); - int c = (int)Math.Floor(365.25 * year); - int d = (int)Math.Floor(30.6001 * (month + 1)); - - double julianDays; - double julianCenturies; - double mst; - - julianDays = b + c + d - 730550.5 + day + (hour + minute / 60.00 + second / 3600.00) / 24.00; - - julianCenturies = julianDays / 36525.0d; - mst = 280.46061837 + 360.98564736629d * julianDays + 0.000387933d * julianCenturies * julianCenturies - julianCenturies * julianCenturies * julianCenturies / 38710000 + lng; - - - if (mst > 0.0) - { - while (mst > 360.0) - { - mst = mst - 360.0; - } - } - else - { - while (mst < 0.0) - { - mst = mst + 360.0; - } - } - - return mst; - } - - - - public double RA - { - get - { - return (((ascention / Math.PI) * 12) + 12) % 24; - } - set - { - ascention = (value/12)* Math.PI; - } - } - - - public double Dec - { - get - { - return declination/RC; - } - set - { - declination = value*RC; - } - } - - public double Lat - { - get - { - - return declination / RC; - } - set - { - declination = value * RC; - } - } - - public double Lng - { - get - { - double lng = ascention / RC; - - if (lng <= 180) - { - return lng; - } - else - { - return (-180 + (180 - lng)); - } - - } - //todo This was broken check callers to see what effect it had. - set - { - ascention = ((value*RC)+(Math.PI*2)%(Math.PI*2)); - } - } - - public double Alt - { - get - { - return declination / RC; - } - set - { - declination = value * RC; - } - } - public double Az - { - get - { - return ascention / RC; - - } - set - { - ascention = value * RC; - } - } - - // Held in radians - double ascention; - double declination; - - public Coordinates(double ascention, double declination) - { - this.ascention = ascention + (Math.PI * 80) % (Math.PI * 2); - this.declination = declination; - } - - public override string ToString() - { - return string.Format("Lat: {0}, Lng: {1}", Lat, Lng); - } - - static public Coordinates CartesianToSpherical(Vector3d vector) - { - double ascention; - double declination; - - double radius = Math.Sqrt((double)vector.X * (double)vector.X + (double)vector.Y * (double)vector.Y + (double)vector.Z * (double)vector.Z); - double XZ = Math.Sqrt((double)vector.X * (double)vector.X + (double)vector.Z * (double)vector.Z); - - declination = Math.Asin((double)vector.Y / radius); - - if (0 < vector.X) - { - ascention = Math.Asin((double)vector.Z / XZ); - } - else if (0 > vector.X) - { - ascention = Math.PI - Math.Asin((double)vector.Z / XZ); - } - else - { - ascention = 0; - } - - - return new Coordinates(ascention, declination); - - } - - - static public Coordinates CartesianToSpherical2(Vector3d vector) - { - double rho = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z); - double longitude = Math.Atan2(vector.Z, vector.X); - double latitude = Math.Asin(vector.Y / rho); - - return new Coordinates(longitude, latitude); - - } - - static public Vector2d CartesianToSphericalSky(Vector3d vector) - { - double rho = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z); - double ra = Math.Atan2(vector.Z, vector.X); - double dec = Math.Asin(-vector.Y / rho); - - return Vector2d.Create(ra / Math.PI * 12, dec / Math.PI * 180); - - } - - static public Vector3d SphericalSkyToCartesian(Vector2d vector) - { - double ra = vector.X * (Math.PI / 12); - double dec = vector.Y * (Math.PI / 180); - double x = Math.Cos(ra) * Math.Cos(dec); - double y = -Math.Sin(dec); - double z = Math.Sin(ra) * Math.Cos(dec); - return Vector3d.Create(x, y, z); - } - - static public Vector2d CartesianToLatLng(Vector3d vector) - { - double rho = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z); - double longitude = Math.Atan2(vector.Z, vector.X); - double latitude = Math.Asin(vector.Y / rho); - - return Vector2d.Create(longitude * 180 / Math.PI, latitude * 180 / Math.PI); - - } - - static public Coordinates CartesianToSpherical3(Vector3d vector) - { - double rho = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z); - double longitude = Math.Atan2(vector.Z, vector.X); - double latitude = Math.Asin(vector.Y / rho); - - return new Coordinates(longitude, latitude); - - } - - static public double Sign(double target) - { - return target < 0 ? -1 : 1; - } - - static public string FormatDMSSign(double angle, bool sign) - { - - try - { - angle += (Sign(angle) * .0001388888888889); - int degrees = (int)angle; - double minutes = (((angle - (double)(int)angle) * 60)); - double seconds = ((minutes - ((int)minutes)) * 60); - if (sign) - { - string signString = angle > 0 ? "+" : "-"; - return String.Format("{3}{0:00;00}:{1:00}:{2:00}", degrees, Math.Abs((int)minutes), Math.Abs((int)seconds), signString); - } - else - { - return String.Format("{0:00}:{1:00}:{2:00}", degrees, Math.Abs((int)minutes), Math.Abs((int)seconds)); - } - } - catch - { - return ""; - } - } - - static public string TwoPlaces(int val) - { - string num = val.ToString(); - if (num.Length < 2) - { - num = "0" + num; - } - - return num; - } - - static public string FormatDMS(double angle) - { - try - { - angle += ((angle < 0 ? -1 : 1) * .0001388888888889); - int degrees = Math.Abs((int)angle); - double minutes = (((angle - (double)(int)angle) * 60)); - double seconds = ((minutes - ((int)minutes)) * 60); - string sign = angle < 0 ? "-" : ""; - // return String.Format("{3}{0:00}:{1:00}:{2:00}", Math.Abs(degrees), Math.Abs((int)minutes), Math.Abs((int)seconds), sign); - return String.Format("{3}{0}:{1}:{2}", Math.Abs(degrees), TwoPlaces(Math.Abs((int)minutes)), TwoPlaces(Math.Abs((int)seconds)), sign); - } - catch - { - return ""; - } - } - static public string FormatDMSWide(double angle) - { - try - { - angle += (Sign(angle) * .0001388888888889); - int degrees = Math.Abs((int)angle); - double minutes = (((angle - (double)(int)angle) * 60)); - double seconds = ((minutes - ((int)minutes)) * 60); - string sign = angle < 0 ? "-" : ""; - return String.Format("{3}{0:00} : {1:00} : {2:00}", degrees, Math.Abs((int)minutes), Math.Abs((int)seconds),sign); - } - catch - { - return ""; - } - } - static public string FormatHMS(double angle) - { - try - { - angle += (Sign(angle) * .0001388888888889); - int degrees = (int)angle; - double minutes = (((angle - (double)(int)angle) * 60)); - double seconds = ((minutes - ((int)minutes)) * 60); - return String.Format("{0:00}h{1:00}m{2:00}s", degrees, Math.Abs((int)minutes), Math.Abs((int)seconds)); - } - catch - { - return ""; - } - } - - static public double ParseRA(string data, bool degrees) - { - - data = data.Trim().ToLowerCase(); - - - if (data.IndexOf("d") > -1 || data.IndexOf("°")> -1) - { - degrees = true; - } - if (data.IndexOf("h") > -1 || data.IndexOf(":") > -1) - { - degrees = false; - } - double ra = Parse(data) / (degrees ? 15 : 1); - - return Math.Max(Math.Min(ra, 24.00), 0); - - } - - - //static public bool ValidateRA(string data) - //{ - - // data = data.Trim().ToLower(); - - // bool degrees = false; - // if (data.Contains("d") || data.Contains("°")) - // { - // degrees = true; - // } - - // try - // { - // data = data.Trim().ToLower(); - - // data = data.Replace("d ", "d").Replace("h ", "h").Replace("m ", "m").Replace("s ", "s").Replace("\' ", "\'").Replace("\" ", "\""); - // double val = 0; - // if (data.IndexOfAny(new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' }) > -1) - // { - // double hours = 0; - // double minutes = 0; - // double seconds = 0; - // double sign = 0; - // string[] parts = data.Split(new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' }); - // if (parts.GetLength(0) > 0) - // { - // if (!String.IsNullOrEmpty(parts[0])) - // { - // hours = Math.Abs(Convert.ToDouble(parts[0])); - // sign = Math.Sign(Convert.ToDouble(parts[0])); - // } - // } - - // if (parts.GetLength(0) > 1) - // { - // if (!String.IsNullOrEmpty(parts[1])) - // { - // minutes = Convert.ToDouble(parts[1]); - // } - // } - - // if (parts.GetLength(0) > 2) - // { - // if (!String.IsNullOrEmpty(parts[2])) - // { - // seconds = Convert.ToDouble(parts[2]); - // } - // } - // if (sign == 0) - // { - // sign = 1; - // } - - // val = sign * (hours + minutes / 60 + seconds / 3600); - // } - // else - // { - // val = Convert.ToDouble(data); - - // } - - // val = val * (degrees ? 1 : 15); - // return (val >= 0 && val <= 360); - // } - // catch - // { - // return false; - // } - - //} - - //static public bool Validate(string data) - //{ - - // data = data.Trim().ToLower(); - - - - // try - // { - // data = data.Trim().ToLower(); - - // data = data.Replace("d ", "d").Replace("m ", "m").Replace("s ", "s").Replace("\' ", "\'").Replace("\" ", "\""); - // double val = 0; - // if (data.IndexOfAny(new char[] { ':', ' ', 'd', 'm', 's', '\'', '\"', '°' }) > -1) - // { - // double degrees = 0; - // double minutes = 0; - // double seconds = 0; - // double sign = 0; - // string[] parts = data.Split(new char[] { ':', ' ', 'd', 'm', 's', '\'', '\"', '°' }); - // if (parts.GetLength(0) > 0) - // { - // if (!String.IsNullOrEmpty(parts[0])) - // { - // degrees = Math.Abs(Convert.ToDouble(parts[0])); - // sign = Math.Sign(Convert.ToDouble(parts[0])); - // } - // } - - // if (parts.GetLength(0) > 1) - // { - // if (!String.IsNullOrEmpty(parts[1])) - // { - // minutes = Convert.ToDouble(parts[1]); - // } - // } - - // if (parts.GetLength(0) > 2) - // { - // if (!String.IsNullOrEmpty(parts[2])) - // { - // seconds = Convert.ToDouble(parts[2]); - // } - // } - // if (sign == 0) - // { - // sign = 1; - // } - - // val = sign * (degrees + minutes / 60 + seconds / 3600); - // } - // else - // { - // val = Convert.ToDouble(data); - - // } - - // return (val >= -360 && val <= 360); - // } - // catch - // { - // return false; - // } - - //} - - static public double ParseDec(string data) - { - - double dec = Parse(data); - return Math.Max(Math.Min(dec, 90.00), -90); - - } - - //static public bool ValidateDec(string data) - //{ - // try - // { - // data = data.Trim().ToLower(); - - // data = data.Replace("d ", "d").Replace("h ", "h").Replace("m ", "m").Replace("s ", "s").Replace("\' ", "\'").Replace("\" ", "\""); - - // if (data.IndexOfAny(new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' }) > -1) - // { - // double hours = 0; - // double minutes = 0; - // double seconds = 0; - // double sign = 0; - // string[] parts = data.Split(new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' }); - // if (parts.GetLength(0) > 0) - // { - // if (!String.IsNullOrEmpty(parts[0])) - // { - // hours = Math.Abs(Convert.ToDouble(parts[0])); - // sign = Math.Sign(Convert.ToDouble(parts[0])); - // } - // } - - // if (parts.GetLength(0) > 1) - // { - // if (!String.IsNullOrEmpty(parts[1])) - // { - // minutes = Convert.ToDouble(parts[1]); - // } - // } - - // if (parts.GetLength(0) > 2) - // { - // if (!String.IsNullOrEmpty(parts[2])) - // { - // seconds = Convert.ToDouble(parts[2]); - // } - // } - // if (sign == 0) - // { - // sign = 1; - // } - - // double val = sign * (hours + minutes / 60 + seconds / 3600); - // return (val >= -90 && val <= 90); - // } - // else - // { - // double val = Convert.ToDouble(data); - // return (val >= -90 && val <= 90); - - // } - // } - // catch - // { - // return false; - // } - //} - - static public double Parse(string data) - { - try - { - data = data.Trim().ToLowerCase(); - - data = data.Replace("d ", "d").Replace("h ", "h").Replace("m ", "m").Replace("s ", "s").Replace("\' ", "\'").Replace("\" ", "\""); - - if (Util.StringContains(data, new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' })) - { - double hours = 0; - double minutes = 0; - double seconds = 0; - double sign = 0; - string[] parts = Util.SplitString(data, new char[] { ':', ' ', 'd', 'h', 'm', 's', '\'', '\"', '°' }); - if (parts.Length > 0) - { - if (!String.IsNullOrEmpty(parts[0])) - { - hours = Math.Abs(double.Parse(parts[0])); - sign = double.Parse(parts[0]) < 0 ? -1 : 1; - if (parts[0].IndexOf("-") > -1) - { - sign = -1; - } - } - } - - if (parts.Length > 1) - { - if (!String.IsNullOrEmpty(parts[1])) - { - minutes = double.Parse(parts[1]); - } - } - - if (parts.Length > 2) - { - if (!String.IsNullOrEmpty(parts[2])) - { - seconds = double.Parse(parts[2]); - } - } - if (sign == 0) - { - sign = 1; - } - - return sign * (hours + minutes / 60 + seconds / 3600); - } - else - { - double val = 0; - try - { - val = double.Parse(data); - } - catch - { - val = 0; - } - return val; - } - } - catch - { - return 0; - } - } - - //public static bool operator == (Coordinates one, Coordinates two) - //{ - // if (!(one is Coordinates)) - // { - // return !(two is Coordinates); - // } - - // return one.Equals(two); - - //} - //public override bool Equals(object obj) - //{ - // if (!(obj is Coordinates)) - // { - // return false; - // } - // Coordinates that = (Coordinates)obj; - // return (this.ascention == that.ascention && this.declination == that.declination); - //} - - //public static bool operator != (Coordinates one, Coordinates two) - //{ - // if (one.ascention == two.ascention && one.declination == two.declination) - // { - // return false; - // } - // else - // { - // return true; - // } - //} - //public override int GetHashCode() - //{ - // return ascention.GetHashCode() ^ declination.GetHashCode(); - //} - - public static Coordinates FromRaDec(double ra, double dec) - { - return new Coordinates((ra-12)*15 * RC, dec * RC); - } - - public static Coordinates FromLatLng(double lat, double lng) - { - return new Coordinates(lng * RC, lat * RC); - } - - public static double DMSToDegrees(double Degrees, double Minutes, double Seconds) - { - return Degrees + Minutes / 60 + Seconds / 3600; - } - - public static double DegreesToRadians(double Degrees) - { - return Degrees * 0.017453292519943295769236907684886; - } - - public static double RadiansToDegrees(double Radians) - { - return Radians * 57.295779513082320876798154814105; - } - - public static double RadiansToHours(double Radians) - { - return Radians * 3.8197186342054880584532103209403; - } - - public static double HoursToRadians(double Hours) - { - return Hours * 0.26179938779914943653855361527329; - } - - public static double HoursToDegrees(double Hours) - { - return Hours * 15; - } - - public static double DegreesToHours(double Degrees) - { - return Degrees / 15; - } - - public static double PI() - { - return 3.1415926535897932384626433832795; - } - - public static double MapTo0To360Range(double Degrees) - { - double Value = Degrees; - - //map it to the range 0 - 360 - while (Value < 0) - Value += 360; - while (Value > 360) - Value -= 360; - - return Value; - } - - public static double MapTo0To24Range(double HourAngle) - { - double Value = HourAngle; - - //map it to the range 0 - 24 - while (Value < 0) - Value += 24; - while (Value > 24) - Value -= 24; - - return Value; - } - - public static double MeanObliquityOfEcliptic(double JD) - { - double U = (JD - 2451545) / 3652500; - double Usquared = U*U; - double Ucubed = Usquared*U; - double U4 = Ucubed*U; - double U5 = U4*U; - double U6 = U5*U; - double U7 = U6*U; - double U8 = U7*U; - double U9 = U8*U; - double U10 = U9*U; - - - return DMSToDegrees(23, 26, 21.448) - DMSToDegrees(0, 0, 4680.93) * U - - DMSToDegrees(0, 0, 1.55) * Usquared - + DMSToDegrees(0, 0, 1999.25) * Ucubed - - DMSToDegrees(0, 0, 51.38) * U4 - - DMSToDegrees(0, 0, 249.67) * U5 - - DMSToDegrees(0, 0, 39.05) * U6 - + DMSToDegrees(0, 0, 7.12) * U7 - + DMSToDegrees(0, 0, 27.87) * U8 - + DMSToDegrees(0, 0, 5.79) * U9 - + DMSToDegrees(0, 0, 2.45) * U10; - } - - - - - static double[][] RotationMatrix = null; - - public static double[] J2000toGalactic(double J2000RA, double J2000DEC) - { - double[] J2000pos = new double[] { Math.Cos(J2000RA / 180.0 * Math.PI) * Math.Cos(J2000DEC / 180.0 * Math.PI), Math.Sin(J2000RA / 180.0 * Math.PI) * Math.Cos(J2000DEC / 180.0 * Math.PI), Math.Sin(J2000DEC / 180.0 * Math.PI) }; - - if (RotationMatrix == null) - { - RotationMatrix = new double[3][]; - RotationMatrix[0] = new double[] { -.0548755604, -.8734370902, -.4838350155 }; - RotationMatrix[1] = new double[] { .4941094279, -.4448296300, .7469822445 }; - RotationMatrix[2] = new double[] { -.8676661490, -.1980763734, .4559837762 }; - } - - - double[] Galacticpos = new double[3]; - for (int i = 0; i < 3; i++) - { - Galacticpos[i] = J2000pos[0] * RotationMatrix[i][0] + J2000pos[1] * RotationMatrix[i][1] + J2000pos[2] * RotationMatrix[i][2]; - } - - double GalacticL2 = Math.Atan2(Galacticpos[1], Galacticpos[0]); - if (GalacticL2 < 0) - { - GalacticL2 = GalacticL2 + 2 * Math.PI; - } - if (GalacticL2 > 2 * Math.PI) - { - GalacticL2 = GalacticL2 - 2 * Math.PI; - } - - double GalacticB2 = Math.Atan2(Galacticpos[2], Math.Sqrt(Galacticpos[0] * Galacticpos[0] + Galacticpos[1] * Galacticpos[1])); - - return new double[] { GalacticL2 / Math.PI * 180.0, GalacticB2 / Math.PI * 180.0 }; - } - - static public Vector3d GalacticTo3dDouble(double l, double b) - { - double[] result = GalactictoJ2000(l, b); - return RADecTo3dAu(result[0] / 15, result[1], 1); - } - - - public static double[] GalactictoJ2000(double GalacticL2, double GalacticB2) - { - double[] Galacticpos = new double[] { Math.Cos(GalacticL2 / 180.0 * Math.PI) * Math.Cos(GalacticB2 / 180.0 * Math.PI), Math.Sin(GalacticL2 / 180.0 * Math.PI) * Math.Cos(GalacticB2 / 180.0 * Math.PI), Math.Sin(GalacticB2 / 180.0 * Math.PI) }; - if (RotationMatrix == null) - { - RotationMatrix = new double[3][]; - RotationMatrix[0] = new double[] { -.0548755604, -.8734370902, -.4838350155 }; - RotationMatrix[1] = new double[] { .4941094279, -.4448296300, .7469822445 }; - RotationMatrix[2] = new double[] { -.8676661490, -.1980763734, .4559837762 }; - } - - double[] J2000pos = new double[3]; - for (int i = 0; i < 3; i++) - { - J2000pos[i] = Galacticpos[0] * RotationMatrix[0][i] + Galacticpos[1] * RotationMatrix[1][i] + Galacticpos[2] * RotationMatrix[2][i]; - } - - double J2000RA = Math.Atan2(J2000pos[1], J2000pos[0]); - if (J2000RA < 0) - { - J2000RA = J2000RA + 2 * Math.PI; - } - if (J2000RA > 2 * Math.PI) - { - J2000RA = J2000RA - 2 * Math.PI; - } - - double J2000DEC = Math.Atan2(J2000pos[2], Math.Sqrt(J2000pos[0] * J2000pos[0] + J2000pos[1] * J2000pos[1])); - - return new double[] { J2000RA / Math.PI * 180.0, J2000DEC / Math.PI * 180.0 }; - - } - } -} diff --git a/engine/csharp_ref/Double3D.cs b/engine/csharp_ref/Double3D.cs deleted file mode 100644 index bdfc5d8c..00000000 --- a/engine/csharp_ref/Double3D.cs +++ /dev/null @@ -1,3668 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - // Summary: - // Describes a custom vertex format structure that contains position and one - // set of texture coordinates. - public enum LocationHint { Slash = 0, Backslash = 1, Top = 2 }; - - public class PositionTexture - { - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv; - //// - //// Summary: - //// Retrieves or sets the x component of the position. - //public double X; - //// - //// Summary: - //// Retrieves or sets the y component of the position. - //public double Y; - //// - //// Summary: - //// Retrieves or sets the z component of the position. - //public double Z; - - public PositionTexture() - { - Position = new Vector3d(); - } - - // - // Summary: - // Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured - // class. - // - // Parameters: - // pos: - // A Microsoft.DirectX.Vector3d object that contains the vertex position. - // - // u: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - public static PositionTexture CreatePos(Vector3d pos, double u, double v) - { - PositionTexture temp = new PositionTexture(); - - temp.Tu = u*Tile.uvMultiple; - temp.Tv = v*Tile.uvMultiple; - temp.Position = pos; - - return temp; - } - - public static PositionTexture CreatePosRaw(Vector3d pos, double u, double v) - { - PositionTexture temp = new PositionTexture(); - - temp.Tu = u; - temp.Tv = v; - temp.Position = pos; - - return temp; - } - - public static PositionTexture CreatePosSize(Vector3d pos, double u, double v, double width, double height) - { - PositionTexture temp = new PositionTexture(); - - temp.Tu = u * width; - temp.Tv = v * height; - temp.Position = pos; - - return temp; - } - // - // Summary: - // Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured - // class. - // - // Parameters: - // xvalue: - // Floating-point value that represents the x coordinate of the position. - // - // yvalue: - // Floating-point value that represents the y coordinate of the position. - // - // zvalue: - // Floating-point value that represents the z coordinate of the position. - // - // u: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - public static PositionTexture Create(double xvalue, double yvalue, double zvalue, double u, double v) - { - PositionTexture temp = new PositionTexture(); - temp.Position = Vector3d.Create(xvalue, yvalue, zvalue); - temp.Tu = u*Tile.uvMultiple; - temp.Tv = v*Tile.uvMultiple; - return temp; - } - - // Summary: - // Retrieves or sets the vertex position. - public Vector3d Position; - //{ - // get - // { - // return Vector3d.Create(X, Y, Z); - // } - // set - // { - // X = value.X; - // Y = value.Y; - // Z = value.Z; - // } - //} - - public PositionTexture Copy() - { - PositionTexture temp = new PositionTexture(); - temp.Position = Vector3d.MakeCopy(this.Position); - temp.Tu = this.Tu; - temp.Tv = this.Tv; - return temp; - } - - //public PositionNormalTexturedX2 PositionNormalTextured(Vector3d center, bool backslash) - //{ - - - // Coordinates latLng = Coordinates.CartesianToSpherical2(this.Position); - // // latLng.Lng += 90; - // if (latLng.Lng < -180) - // { - // latLng.Lng += 360; - // } - // if (latLng.Lng > 180) - // { - // latLng.Lng -= 360; - // } - // if (latLng.Lng == -180 && !backslash) - // { - // latLng.Lng = 180; - // } - // if (latLng.Lng == 180 && backslash) - // { - // latLng.Lng = -180; - // } - // PositionNormalTexturedX2 pnt = new PositionNormalTexturedX2(); - - // pnt.X = (float)(X - center.X); - // pnt.Y = (float)(Y - center.Y); - // pnt.Z = (float)(Z - center.Z); - // pnt.Tu = (float)Tu; - // pnt.Tv = (float)Tv; - // pnt.Lng = latLng.Lng; - // pnt.Lat = latLng.Lat; - // pnt.Normal = Position; - // return pnt; - - //} - - // Summary: - // Obtains a string representation of the current instance. - // - // Returns: - // String that represents the object. - public override string ToString() - { - return String.Format("{0}, {1}, {2}, {3}, {4}", Position.X, Position.Y, Position.Z, Tu, Tv); - } - } - - - public class PositionColoredTextured - { - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv; - //// - //// Summary: - //// Retrieves or sets the x component of the position. - //public double X; - //// - //// Summary: - //// Retrieves or sets the y component of the position. - //public double Y; - //// - //// Summary: - //// Retrieves or sets the z component of the position. - //public double Z; - - public PositionColoredTextured() - { - Position = new Vector3d(); - } - - // - // Summary: - // Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured - // class. - // - // Parameters: - // pos: - // A Microsoft.DirectX.Vector3d object that contains the vertex position. - // - // u: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - public static PositionColoredTextured CreatePos(Vector3d pos, double u, double v) - { - PositionColoredTextured temp = new PositionColoredTextured(); - - temp.Tu = u * Tile.uvMultiple; - temp.Tv = v * Tile.uvMultiple; - temp.Position = pos; - - return temp; - } - - public static PositionColoredTextured CreatePosRaw(Vector3d pos, double u, double v) - { - PositionColoredTextured temp = new PositionColoredTextured(); - - temp.Tu = u; - temp.Tv = v; - temp.Position = pos; - - return temp; - } - - public static PositionColoredTextured CreatePosSize(Vector3d pos, double u, double v, double width, double height) - { - PositionColoredTextured temp = new PositionColoredTextured(); - - temp.Tu = u * width; - temp.Tv = v * height; - temp.Position = pos; - - return temp; - } - - public Color Color = new Color(); - - // - // Summary: - // Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured - // class. - // - // Parameters: - // xvalue: - // Floating-point value that represents the x coordinate of the position. - // - // yvalue: - // Floating-point value that represents the y coordinate of the position. - // - // zvalue: - // Floating-point value that represents the z coordinate of the position. - // - // u: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() - // component of the texture coordinate. - public static PositionTexture Create(double xvalue, double yvalue, double zvalue, double u, double v) - { - PositionTexture temp = new PositionTexture(); - temp.Position = Vector3d.Create(xvalue, yvalue, zvalue); - temp.Tu = u * Tile.uvMultiple; - temp.Tv = v * Tile.uvMultiple; - return temp; - } - - // Summary: - // Retrieves or sets the vertex position. - public Vector3d Position; - //{ - // get - // { - // return Vector3d.Create(X, Y, Z); - // } - // set - // { - // X = value.X; - // Y = value.Y; - // Z = value.Z; - // } - //} - - public PositionTexture Copy() - { - PositionTexture temp = new PositionTexture(); - temp.Position = Vector3d.MakeCopy(this.Position); - temp.Tu = this.Tu; - temp.Tv = this.Tv; - return temp; - } - - - public override string ToString() - { - return String.Format("{0}, {1}, {2}, {3}, {4}", Position.X, Position.Y, Position.Z, Tu, Tv); - } - - - - } - - public class PositionColored - { - - - public PositionColored (Vector3d pos, Color color) - { - - Color = color.Clone(); - Position = pos.Copy(); - } - - public Color Color = new Color(); - public Vector3d Position; - - public PositionColored Copy() - { - PositionColored temp = new PositionColored(this.Position, this.Color); - return temp; - } - - public override string ToString() - { - return String.Format("{0}, {1}, {2}, {3}", Position.X, Position.Y, Position.Z, Color.ToString()); - } - } - - // Summary: - // Custom vertex format with position, normal, texture coordinate, and tangent vector. The - // tangent vector is stored in the second texture coordinate. - public class PositionNormalTexturedTangent - { - // Summary: - // Retrieves the Microsoft.DirectX.Direct3D.VertexFormats for the current custom - // vertex. - //public static VertexFormats Format = VertexFormats.Position | - // VertexFormats.Normal | - // VertexFormats.Texture2 | - // VertexTextureCoordinate.Size3(1); - public double X; - // - // Summary: - // Retrieves or sets the y component of the position. - public double Y; - // - // Summary: - // Retrieves or sets the z component of the position. - public double Z; - // Summary: - // Retrieves or sets the nx component of the vertex normal. - public double Nx; - // - // Summary: - // Retrieves or sets the ny component of the vertex normal. - public double Ny; - // - // Summary: - // Retrieves or sets the nz component of the vertex normal. - public double Nz; - // - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv; - // - // Summary: - // Retrieves or sets the x component of the tangent vector - public double Tanx; - // - // Summary: - // Retrieves or sets the y component of the tangent vector - public double Tany; - // - // Summary: - // Retrieves or sets the z component of the tangent vector - public double Tanz; - - // - // Summary: - // Initializes a new instance of the PositionNormalTexturedTangent - // class. - // - public PositionNormalTexturedTangent(Vector3d position, Vector3d normal, Vector2d texCoord, Vector3d tangent) - { - X = position.X; - Y = position.Y; - Z = position.Z; - Nx = normal.X; - Ny = normal.Y; - Nz = normal.Z; - Tu = texCoord.X; - Tv = texCoord.Y; - Tanx = tangent.X; - Tany = tangent.Y; - Tanz = tangent.Z; - } - - // Summary: - // Retrieves or sets the vertex normal data. - public Vector3d Normal - { - get - { - return Vector3d.Create(Nx, Ny, Nz); - } - set - { - Nx = value.X; - Ny = value.Y; - Nz = value.Z; - } - } - - // Summary: - // Retrieves or sets the vertex position. - public Vector3d Position - { - get - { - return Vector3d.Create(X, Y, Z); - } - set - { - X = value.X; - Y = value.Y; - Z = value.Z; - } - } - - // Summary: - // Retrieves or sets the texture coordinate. - public Vector2d TexCoord - { - get - { - return Vector2d.Create(Tu, Tv); - } - set - { - Tu = value.X; - Tv = value.Y; - } - } - - // Summary: - // Retrieves or sets the vertex tangent. - public Vector3d Tangent - { - get - { - return Vector3d.Create(Tanx, Tany, Tanz); - } - set - { - Tanx = value.X; - Tany = value.Y; - Tanz = value.Z; - } - } - - - - // Summary: - // Obtains a string representation of the current instance. - // - // Returns: - // String that represents the object. - public override string ToString() - { - return string.Format( - "X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, TanX={8}, TanY={9}, TanZ={10}", - X, Y, Z, Nx, Ny, Nz, Tu, Tv, Tanx, Tany, Tanz - ); - } - } - - - // Summary: - // Describes and manipulates a vector in three-dimensional (3-D) space. - - public class Vector3d - { - // Summary: - // Retrieves or sets the x component of a 3-D vector. - public double X; - // - // Summary: - // Retrieves or sets the y component of a 3-D vector. - public double Y; - // - // Summary: - // Retrieves or sets the z component of a 3-D vector. - public double Z; - - // - // Summary: - // Initializes a new instance of the Microsoft.DirectX.Vector3d class. - // - // Parameters: - // valueX: - // Initial Microsoft.DirectX.Vector3d.X value. - // - // valueY: - // Initial Microsoft.DirectX.Vector3d.Y value. - // - // valueZ: - // Initial Microsoft.DirectX.Vector3d.Z value. - public static Vector3d Create(double valueX, double valueY, double valueZ) - { - Vector3d temp = new Vector3d(); - temp.X = valueX; - temp.Y = valueY; - temp.Z = valueZ; - return temp; - } - - public void Set(double valueX, double valueY, double valueZ) - { - X = valueX; - Y = valueY; - Z = valueZ; - } - - public static Vector3d MakeCopy(Vector3d value) - { - Vector3d temp = new Vector3d(); - temp.X = value.X; - temp.Y = value.Y; - temp.Z = value.Z; - return temp; - } - - public Vector3d Copy() - { - Vector3d temp = new Vector3d(); - temp.X = X; - temp.Y = Y; - temp.Z = Z; - return temp; - } - // Summary: - // Negates the vector. - // - // Parameters: - // vec: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // The Microsoft.DirectX.Vector3d structure that is the result of the operation. - public static Vector3d Negate(Vector3d vec) - { - return Vector3d.Create(-vec.X, -vec.Y, -vec.Z); - } - // - // Summary: - // Subtracts two 3-D vectors. - // - // Parameters: - // left: - // The Microsoft.DirectX.Vector3d structure to the left of the subtraction operator. - // - // right: - // The Microsoft.DirectX.Vector3d structure to the right of the subtraction operator. - // - // Returns: - // Resulting Microsoft.DirectX.Vector3d structure. - //public static Vector3d Subtract(Vector3d left, Vector3d right) - //{ - // return Vector3d.Create(left.X - right.X, left.Y - right.Y, left.Z - right.Z); - //} - // - // Summary: - // Compares the current instance of a class to another instance to determine - // whether they are different. - // - // Parameters: - // left: - // The Microsoft.DirectX.Vector3d structure to the left of the inequality operator. - // - // right: - // The Microsoft.DirectX.Vector3d structure to the right of the inequality operator. - // - // Returns: - // Value that is true if the objects are different, or false if they are the - // same. - //public static bool operator !=(Vector3d left, Vector3d right) - //{ - // return (left.X != right.X || left.Y != right.Y || left.Z != right.Z); - //} - // - // Summary: - // Determines the product of a single value and a 3-D vector. - // - // Parameters: - // right: - // Source System.Single structure. - // - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the product of the Microsoft.DirectX.Vector3d.op_Multiply() - // and Microsoft.DirectX.Vector3d.op_Multiply() parameters. - //public static Vector3d operator *(double right, Vector3d left); - // - // Summary: - // Determines the product of a single value and a 3-D vector. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source System.Single structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the product of the Microsoft.DirectX.Vector3d.op_Multiply() - // and Microsoft.DirectX.Vector3d.op_Multiply() parameters. - //public static Vector3d operator *(Vector3d left, double right); - // - // Summary: - // Adds two vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that contains the sum of the parameters. - //public static Vector3d operator +(Vector3d left, Vector3d right); - // - // Summary: - // Compares the current instance of a class to another instance to determine - // whether they are the same. - // - // Parameters: - // left: - // The Microsoft.DirectX.Vector3d structure to the left of the equality operator. - // - // right: - // The Microsoft.DirectX.Vector3d structure to the right of the equality operator. - // - // Returns: - // Value that is true if the objects are the same, or false if they are different. - //public static bool operator ==(Vector3d left, Vector3d right) - //{ - // return (left.X == right.X || left.Y == right.Y || left.Z == right.Z); - //} - public static Vector3d MidPoint(Vector3d left, Vector3d right) - { - Vector3d result = Vector3d.Create((left.X + right.X) / 2, (left.Y + right.Y) / 2, (left.Z + right.Z) / 2); - return result; - } - public static Vector3d MidPointByLength(Vector3d left, Vector3d right) - { - Vector3d result = Vector3d.Create((left.X + right.X) / 2, (left.Y + right.Y) / 2, (left.Z + right.Z) / 2); - result.Normalize(); - - result.Multiply(left.Length()); - return result; - } - // Summary: - // Retrieves an empty 3-D vector. - public static Vector3d Empty - { - get - { - return Vector3d.Create(0, 0, 0); - } - } - - - - public static Vector3d Zero = new Vector3d(); - - // rounds to factor - public void Round() - { - X = (double)((int)(X * 65536)) / 65536.0; - Y = (double)((int)(Y * 65536)) / 65536.0; - Z = (double)((int)(Z * 65536)) / 65536.0; - } - // Summary: - // Adds two 3-D vectors. - // - // Parameters: - // source: - public void Add(Vector3d source) - { - X += source.X; - Y += source.Y; - Z += source.Z; - } - - // - // Summary: - // Adds two 3-D vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d. - // - // right: - // Source Microsoft.DirectX.Vector3d. - // - // Returns: - // Sum of the two Microsoft.DirectX.Vector3d structures. - public static Vector3d AddVectors(Vector3d left, Vector3d right) - { - return Vector3d.Create(left.X + right.X, left.Y + right.Y, left.Z + right.Z); - } - - // - // Summary: - // Returns a point in barycentric coordinates, using specified 3-D vectors. - // - // Parameters: - // v1: - // Source Microsoft.DirectX.Vector3d structure. - // - // v2: - // Source Microsoft.DirectX.Vector3d structure. - // - // v3: - // Source Microsoft.DirectX.Vector3d structure. - // - // f: - // Weighting factor. See Remarks. - // - // g: - // Weighting factor. See Remarks. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure in barycentric coordinates. - //public static Vector3d BaryCentric(Vector3d v1, Vector3d v2, Vector3d v3, double f, double g); - // - // Summary: - // Performs a Catmull-Rom interpolation using specified 3-D vectors. - // - // Parameters: - // position1: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // position2: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // position3: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // position4: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // weightingFactor: - // Weighting factor. See Remarks. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the result of the Catmull-Rom - // interpolation. - //public static Vector3d CatmullRom(Vector3d position1, Vector3d position2, Vector3d position3, Vector3d position4, double weightingFactor) - //{ - //} - // - // Summary: - // Determines the cross product of two 3-D vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the cross product of two 3-D - // vectors. - public static Vector3d Cross(Vector3d left, Vector3d right) - { - return Vector3d.Create( - left.Y * right.Z - left.Z * right.Y, - left.Z * right.X - left.X * right.Z, - left.X * right.Y - left.Y * right.X); - - } - // - // Summary: - // Determines the dot product of two 3-D vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A System.Single value that is the dot product. - public static double Dot(Vector3d left, Vector3d right) - { - return left.X * right.X + left.Y * right.Y + left.Z * right.Z; - } - // - // Summary: - // Returns a value that indicates whether the current instance is equal to a - // specified object. - // - // Parameters: - // compare: - // Object with which to make the comparison. - // - // Returns: - // Value that is true if the current instance is equal to the specified object, - // or false if it is not. - //public override bool Equals(object compare) - //{ - // Vector3d comp = (Vector3d)compare; - // return this.X == comp.X && this.Y == comp.Y && this.Z == comp.Z; - //} - // - // Summary: - // Returns the hash code for the current instance. - // - // Returns: - // Hash code for the instance. - //public override int GetHashCode() - //{ - // return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); - //} - // - // Summary: - // Performs a Hermite spline interpolation using the specified 3-D vectors. - // - // Parameters: - // position: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // tangent: - // Source Microsoft.DirectX.Vector3d structure that is a tangent vector. - // - // position2: - // Source Microsoft.DirectX.Vector3d structure that is a position vector. - // - // tangent2: - // Source Microsoft.DirectX.Vector3d structure that is a tangent vector. - // - // weightingFactor: - // Weighting factor. See Remarks. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the result of the Hermite spline - // interpolation. - //public static Vector3d Hermite(Vector3d position, Vector3d tangent, Vector3d position2, Vector3d tangent2, double weightingFactor); - // - // Summary: - // Returns the length of a 3-D vector. - // - // Returns: - // A System.Single value that contains the vector's length. - public double Length() - { - return Math.Sqrt(X * X + Y * Y + Z * Z); - } - // - // Summary: - // Returns the length of a 3-D vector. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A System.Single value that contains the vector's length. - public static double GetLength(Vector3d source) - { - return Math.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z); - - } - // - // Summary: - // Returns the square of the length of a 3-D vector. - // - // Returns: - // A System.Single value that contains the vector's squared length. - public double LengthSq() - { - return X * X + Y * Y + Z * Z; - } - // - // Summary: - // Returns the square of the length of a 3-D vector. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A System.Single value that contains the vector's squared length. - public static double GetLengthSq(Vector3d source) - { - return source.X * source.X + source.Y * source.Y + source.Z * source.Z; - } - - // - // Summary: - // Performs a linear interpolation between two 3-D vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // interpolater: - // Parameter that linearly interpolates between the vectors. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the result of the linear interpolation. - public static Vector3d Lerp(Vector3d left, Vector3d right, double interpolater) - { - return Vector3d.Create( - left.X * (1.0 - interpolater) + right.X * interpolater, - left.Y * (1.0 - interpolater) + right.Y * interpolater, - left.Z * (1.0 - interpolater) + right.Z * interpolater); - - } - - - public static Vector3d Midpoint(Vector3d left, Vector3d right) - { - Vector3d tmp = Vector3d.Create( - left.X * (.5) + right.X * .5, - left.Y * (.5) + right.Y * .5, - left.Z * (.5) + right.Z * .5); - tmp.Normalize(); - return tmp; - } - - - public static Vector3d Slerp(Vector3d left, Vector3d right, double interpolater) - { - double dot = Dot(left, right); - while (dot < .98) - { - Vector3d middle = Midpoint(left, right); - if (interpolater > .5) - { - left = middle; - interpolater -= .5; - interpolater *= 2; - } - else - { - right = middle; - interpolater *= 2; - } - dot = Dot(left, right); - } - - Vector3d tmp = Lerp(left, right, interpolater); - tmp.Normalize(); - return tmp; - } - // - // Summary: - // Returns a 3-D vector that is made up of the largest components of two 3-D - // vectors. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - //public void Maximize(Vector3d source); - // - // Summary: - // Returns a 3-D vector that is made up of the largest components of two 3-D - // vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is made up of the largest components - // of the two vectors. - //public static Vector3d Maximize(Vector3d left, Vector3d right); - // - // Summary: - // Returns a 3-D vector that is made up of the smallest components of two 3-D - // vectors. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - //public void Minimize(Vector3d source); - // - // Summary: - // Returns a 3-D vector that is made up of the smallest components of two 3-D - // vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure. - // - // right: - // Source Microsoft.DirectX.Vector3d structure. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is made up of the smallest components - // of the two vectors. - //public static Vector3d Minimize(Vector3d left, Vector3d right); - // - // Summary: - // Multiplies a 3-D vector by a System.Single value. - // - // Parameters: - // s: - // Source System.Single value used as a multiplier. - public void Multiply(double s) - { - X *= s; - Y *= s; - Z *= s; - } - - - // - // Summary: - // Multiplies a 3-D vector by a System.Single value. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - // - // f: - // Source System.Single value used as a multiplier. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is multiplied by the System.Single - // value. - public static Vector3d MultiplyScalar(Vector3d source, double f) - { - Vector3d result = source.Copy(); - result.Multiply(f); - return result; - } - // - // Summary: - // Returns the normalized version of a 3-D vector. - public void Normalize() - { - // Vector3.Length property is under length section - double length = this.Length(); - if (length != 0) - { - X /= length; - Y /= length; - Z /= length; - } - } - - // - // Summary: - // Scales a 3-D vector. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure. - // - // scalingFactor: - // Scaling value. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the scaled vector. - public static Vector3d Scale(Vector3d source, double scalingFactor) - { - Vector3d result = source; - result.Multiply(scalingFactor); - return result; - } - - public void RotateX(double radians) - { - double zTemp; - double yTemp; - //radians = -radians; - yTemp = Y * Math.Cos(radians) - Z * Math.Sin(radians); - zTemp = Y * Math.Sin(radians) + Z * Math.Cos(radians); - Z = zTemp; - Y = yTemp; - } - - public void RotateZ(double radians) - { - double xTemp; - double yTemp; - //radians = -radians; - xTemp = X * Math.Cos(radians) - Y * Math.Sin(radians); - yTemp = X * Math.Sin(radians) + Y * Math.Cos(radians); - Y = yTemp; - X = xTemp; - } - - public void RotateY(double radians) - { - double zTemp; - double xTemp; - //radians = -radians; - zTemp = Z * Math.Cos(radians) - X * Math.Sin(radians); - xTemp = Z * Math.Sin(radians) + X * Math.Cos(radians); - X = xTemp; - Z = zTemp; - } - // - // Summary: - // Subtracts two 3-D vectors. - // - // Parameters: - // source: - // Source Microsoft.DirectX.Vector3d structure to subtract from the current instance. - public Vector3d Subtract(Vector3d source) - { - this.X -= source.X; - this.Y -= source.Y; - this.Z -= source.Z; - return this; - } - // - // Summary: - // Subtracts two 3-D vectors. - // - // Parameters: - // left: - // Source Microsoft.DirectX.Vector3d structure to the left of the subtraction - // operator. - // - // right: - // Source Microsoft.DirectX.Vector3d structure to the right of the subtraction - // operator. - // - // Returns: - // A Microsoft.DirectX.Vector3d structure that is the result of the operation. - public static Vector3d SubtractVectors(Vector3d left, Vector3d right) - { - Vector3d result = left.Copy(); - result.Subtract(right); - return result; - } - - - // - // Summary: - // Obtains a string representation of the current instance. - // - // Returns: - // String that represents the object. - public override string ToString() - { - return String.Format("{0}, {1}, {2}", X, Y, Z); - } - - public static Vector3d Parse(string data) - { - Vector3d newVector = new Vector3d(); - - string[] list = data.Split( ',' ); - if (list.Length == 3) - { - newVector.X = double.Parse(list[0]); - newVector.Y = double.Parse(list[1]); - newVector.Z = double.Parse(list[2]); - } - return newVector; - } - - public Vector2d ToSpherical() - { - - double ascention; - double declination; - - double radius = Math.Sqrt(X * X + Y * Y + Z * Z); - double XZ = Math.Sqrt(X * X + Z * Z); - declination = Math.Asin(Y / radius); - if (XZ == 0) - { - ascention = 0; - } - else if (0 <= X) - { - ascention = Math.Asin(Z / XZ); - } - else - { - ascention = Math.PI - Math.Asin(Z / XZ); - } - - //if (vector.Z < 0) - //{ - // ascention = ascention - Math.PI; - //} - // 0 -1.0 return new Vector2d((((ascention + Math.PI) / (2.0 * Math.PI)) % 1.0f), ((declination + (Math.PI / 2.0)) / (Math.PI))); - return Vector2d.Create((((ascention + Math.PI) % (2.0 * Math.PI))), ((declination + (Math.PI / 2.0)))); - - } - public Vector2d ToRaDec() - { - Vector2d point = ToSpherical(); - point.X = point.X / Math.PI * 12; - point.Y = (point.Y / Math.PI * 180) - 90; - - //if (point.X == double.NaN || point.Y == double.NaN) - //{ - // point.X = point.Y = 0; - //} - return point; - } - - - - - public double DistanceToLine(Vector3d x1, Vector3d x2) - { - Vector3d t1 = Vector3d.SubtractVectors(x2, x1); - Vector3d t2 = Vector3d.SubtractVectors(x1, this); - Vector3d t3 = Vector3d.Cross(t1, t2); - double d1 = t3.Length(); - Vector3d t4 = Vector3d.SubtractVectors(x2, x1); - double d2 = t4.Length(); - return d1 / d2; - - } - - - internal void TransformByMatrics(Matrix3d lookAtAdjust) - { - Vector3d temp = lookAtAdjust.Transform(this); - this.X = temp.X; - this.Y = temp.Y; - this.Z = temp.Z; - } - - internal static Vector3d TransformCoordinate(Vector3d vector3d, Matrix3d mat) - { - return mat.Transform(vector3d); - } - - } - public class Vector2d - { - public double X; - public double Y; - public Vector2d() - { - } - - public static Vector2d Lerp(Vector2d left, Vector2d right, double interpolater) - { - //if (Math.Abs(left.X - right.X) > 12) - //{ - // if (left.X > right.X) - // { - // right.X += 24; - // } - // else - // { - // left.X += 24; - // } - //} - return Vector2d.Create(left.X * (1 - interpolater) + right.X * interpolater, left.Y * (1 - interpolater) + right.Y * interpolater); - - } - - static public Vector2d CartesianToSpherical2(Vector3d vector) - { - double rho = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z); - double longitude = Math.Atan2(vector.Z, vector.X); - double latitude = Math.Asin(vector.Y / rho); - - return Vector2d.Create(longitude / Math.PI * 180.0, latitude / Math.PI * 180.0); - - } - - public double Distance3d(Vector2d pointB) - { - Vector3d pnt1 = Coordinates.GeoTo3dDouble(pointB.Y, pointB.X); - Vector3d pnt2 = Coordinates.GeoTo3dDouble(this.Y, this.X); - - Vector3d pntDiff = Vector3d.SubtractVectors(pnt1, pnt2); - - return pntDiff.Length() / Math.PI * 180; - } - - public static Vector2d Average3d(Vector2d left, Vector2d right) - { - Vector3d pntLeft = Coordinates.GeoTo3dDouble(left.Y, left.X); - Vector3d pntRight = Coordinates.GeoTo3dDouble(right.Y, right.X); - - Vector3d pntOut = Vector3d.AddVectors(pntLeft, pntRight); - pntOut.Multiply(.5); - pntOut.Normalize(); - - return CartesianToSpherical2(pntOut); - - } - - public double Length - { - get - { - return (Math.Sqrt(X * X + Y * Y)); - } - } - - //public static Vector2d Subtract(Vector2d vec) - //{ - // return Vector2d.Create(-vec.X, -vec.Y); - - //} - - public static Vector2d Create(double x, double y) - { - Vector2d temp = new Vector2d(); - - temp.X = x; - temp.Y = y; - return temp; - } - - public static Vector2d Subtract(Vector2d left, Vector2d right) - { - return Vector2d.Create(left.X - right.X, left.Y - right.Y); - } - public void Normalize() - { - double length = this.Length; - if (length != 0) - { - X /= length; - Y /= length; - } - } - - public void Extend(double factor) - { - X = X * factor; - Y = Y * factor; - } - - //internal static Vector2d Subtract(Vector2d v1, Vector2d v2) - //{ - // return Vector2d.Create(v1.X - v2.X, v1.Y - v2.Y); - //} - } - - public class Matrix3d - { - private double _m11; - private double _m12; - private double _m13; - private double _m14; - private double _m21; - private double _m22; - private double _m23; - private double _m24; - private double _m31; - private double _m32; - private double _m33; - private double _m34; - private double _offsetX; - private double _offsetY; - private double _offsetZ; - private double _m44; - private bool _isNotKnownToBeIdentity; - - private static readonly Matrix3d s_identity; - - public Matrix3d() - { - } - - public static Matrix3d Create(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) - { - Matrix3d temp = new Matrix3d(); - temp._m11 = m11; - temp._m12 = m12; - temp._m13 = m13; - temp._m14 = m14; - temp._m21 = m21; - temp._m22 = m22; - temp._m23 = m23; - temp._m24 = m24; - temp._m31 = m31; - temp._m32 = m32; - temp._m33 = m33; - temp._m34 = m34; - temp._offsetX = offsetX; - temp._offsetY = offsetY; - temp._offsetZ = offsetZ; - temp._m44 = m44; - temp._isNotKnownToBeIdentity = true; - - return temp; - } - - public Matrix3d Clone() - { - Matrix3d tmp = new Matrix3d(); - tmp.Set(this); - return tmp; - } - - - - public static Matrix3d Identity - { - get - { - Matrix3d temp = new Matrix3d(); - temp.Set(s_identity); - return temp; - } - } - - public void SetIdentity() - { - this.Set(s_identity); - } - - public void Set(Matrix3d mat) - { - this._m11 = mat._m11; - this._m12 = mat._m12; - this._m13 = mat._m13; - this._m14 = mat._m14; - this._m21 = mat._m21; - this._m22 = mat._m22; - this._m23 = mat._m23; - this._m24 = mat._m24; - this._m31 = mat._m31; - this._m32 = mat._m32; - this._m33 = mat._m33; - this._m34 = mat._m34; - this._offsetX = mat._offsetX; - this._offsetY = mat._offsetY; - this._offsetZ = mat._offsetZ; - this._m44 = mat._m44; - this._isNotKnownToBeIdentity = true; - } - - public float[] FloatArray() - { - float[] array = new float[16]; - - array[0] = (float)_m11; - array[1] = (float)_m12; - array[2] = (float)_m13; - array[3] = (float)_m14; - array[4] = (float)_m21; - array[5] = (float)_m22; - array[6] = (float)_m23; - array[7] = (float)_m24; - array[8] = (float)_m31; - array[9] = (float)_m32; - array[10] = (float)_m33; - array[11] = (float)_m34; - array[12] = (float)_offsetX; - array[13] = (float)_offsetY; - array[14] = (float)_offsetZ; - array[15] = (float)_m44; - - return array; - - } - - public bool IsIdentity - { - get - { - if (this.IsDistinguishedIdentity) - { - return true; - } - if (((((this._m11 == 1) && (this._m12 == 0)) && ((this._m13 == 0) && (this._m14 == 0))) && (((this._m21 == 0) && (this._m22 == 1)) && ((this._m23 == 0) && (this._m24 == 0)))) && ((((this._m31 == 0) && (this._m32 == 0)) && ((this._m33 == 1) && (this._m34 == 0))) && (((this._offsetX == 0) && (this._offsetY == 0)) && ((this._offsetZ == 0) && (this._m44 == 1))))) - { - this.IsDistinguishedIdentity = true; - return true; - } - return false; - } - } - - public void Prepend(Matrix3d matrix) - { - Set(MultiplyMatrix(matrix,this)); - } - - public void Append(Matrix3d matrix) - { - this.Multiply(matrix); - } - - //public void Rotate(Quaternion quaternion) - //{ - // Vector3d center = new Vector3d(); - // this *= CreateRotationMatrix(ref quaternion, ref center); - //} - - //public void RotatePrepend(Quaternion quaternion) - //{ - // Vector3d center = new Vector3d(); - // this = CreateRotationMatrix(ref quaternion, ref center) * this; - //} - - //public void RotateAt(Quaternion quaternion, Vector3d center) - //{ - // this *= CreateRotationMatrix(ref quaternion, ref center); - //} - - //public void RotateAtPrepend(Quaternion quaternion, Vector3d center) - //{ - // this = CreateRotationMatrix(ref quaternion, ref center) * this; - //} - - public void Scale(Vector3d scale) - { - if (this.IsDistinguishedIdentity) - { - this.SetScaleMatrix( scale); - } - else - { - this._m11 *= scale.X; - this._m12 *= scale.Y; - this._m13 *= scale.Z; - this._m21 *= scale.X; - this._m22 *= scale.Y; - this._m23 *= scale.Z; - this._m31 *= scale.X; - this._m32 *= scale.Y; - this._m33 *= scale.Z; - this._offsetX *= scale.X; - this._offsetY *= scale.Y; - this._offsetZ *= scale.Z; - } - } - - public void ScalePrepend(Vector3d scale) - { - if (this.IsDistinguishedIdentity) - { - this.SetScaleMatrix( scale); - } - else - { - this._m11 *= scale.X; - this._m12 *= scale.X; - this._m13 *= scale.X; - this._m14 *= scale.X; - this._m21 *= scale.Y; - this._m22 *= scale.Y; - this._m23 *= scale.Y; - this._m24 *= scale.Y; - this._m31 *= scale.Z; - this._m32 *= scale.Z; - this._m33 *= scale.Z; - this._m34 *= scale.Z; - } - } - - public void ScaleAt(Vector3d scale, Vector3d center) - { - if (this.IsDistinguishedIdentity) - { - this.SetScaleMatrixCenter( scale, center); - } - else - { - double num = this._m14 * center.X; - this._m11 = num + (scale.X * (this._m11 - num)); - num = this._m14 * center.Y; - this._m12 = num + (scale.Y * (this._m12 - num)); - num = this._m14 * center.Z; - this._m13 = num + (scale.Z * (this._m13 - num)); - num = this._m24 * center.X; - this._m21 = num + (scale.X * (this._m21 - num)); - num = this._m24 * center.Y; - this._m22 = num + (scale.Y * (this._m22 - num)); - num = this._m24 * center.Z; - this._m23 = num + (scale.Z * (this._m23 - num)); - num = this._m34 * center.X; - this._m31 = num + (scale.X * (this._m31 - num)); - num = this._m34 * center.Y; - this._m32 = num + (scale.Y * (this._m32 - num)); - num = this._m34 * center.Z; - this._m33 = num + (scale.Z * (this._m33 - num)); - num = this._m44 * center.X; - this._offsetX = num + (scale.X * (this._offsetX - num)); - num = this._m44 * center.Y; - this._offsetY = num + (scale.Y * (this._offsetY - num)); - num = this._m44 * center.Z; - this._offsetZ = num + (scale.Z * (this._offsetZ - num)); - } - } - - public void ScaleAtPrepend(Vector3d scale, Vector3d center) - { - if (this.IsDistinguishedIdentity) - { - this.SetScaleMatrixCenter( scale, center); - } - else - { - double num3 = center.X - (center.X * scale.X); - double num2 = center.Y - (center.Y * scale.Y); - double num = center.Z - (center.Z * scale.Z); - this._offsetX += ((this._m11 * num3) + (this._m21 * num2)) + (this._m31 * num); - this._offsetY += ((this._m12 * num3) + (this._m22 * num2)) + (this._m32 * num); - this._offsetZ += ((this._m13 * num3) + (this._m23 * num2)) + (this._m33 * num); - this._m44 += ((this._m14 * num3) + (this._m24 * num2)) + (this._m34 * num); - this._m11 *= scale.X; - this._m12 *= scale.X; - this._m13 *= scale.X; - this._m14 *= scale.X; - this._m21 *= scale.Y; - this._m22 *= scale.Y; - this._m23 *= scale.Y; - this._m24 *= scale.Y; - this._m31 *= scale.Z; - this._m32 *= scale.Z; - this._m33 *= scale.Z; - this._m34 *= scale.Z; - } - } - - public void Translate(Vector3d offset) - { - if (this.IsDistinguishedIdentity) - { - this.SetTranslationMatrix( offset); - } - else - { - this._m11 += this._m14 * offset.X; - this._m12 += this._m14 * offset.Y; - this._m13 += this._m14 * offset.Z; - this._m21 += this._m24 * offset.X; - this._m22 += this._m24 * offset.Y; - this._m23 += this._m24 * offset.Z; - this._m31 += this._m34 * offset.X; - this._m32 += this._m34 * offset.Y; - this._m33 += this._m34 * offset.Z; - this._offsetX += this._m44 * offset.X; - this._offsetY += this._m44 * offset.Y; - this._offsetZ += this._m44 * offset.Z; - } - } - - public void TranslatePrepend(Vector3d offset) - { - if (this.IsDistinguishedIdentity) - { - this.SetTranslationMatrix( offset); - } - else - { - this._offsetX += ((this._m11 * offset.X) + (this._m21 * offset.Y)) + (this._m31 * offset.Z); - this._offsetY += ((this._m12 * offset.X) + (this._m22 * offset.Y)) + (this._m32 * offset.Z); - this._offsetZ += ((this._m13 * offset.X) + (this._m23 * offset.Y)) + (this._m33 * offset.Z); - this._m44 += ((this._m14 * offset.X) + (this._m24 * offset.Y)) + (this._m34 * offset.Z); - } - } - - public static Matrix3d MultiplyMatrix(Matrix3d matrix1, Matrix3d matrix2) - { - if (matrix1.IsDistinguishedIdentity) - { - return matrix2; - } - if (matrix2.IsDistinguishedIdentity) - { - return matrix1; - } - return Matrix3d.Create((((matrix1._m11 * matrix2._m11) + (matrix1._m12 * matrix2._m21)) + (matrix1._m13 * matrix2._m31)) + (matrix1._m14 * matrix2._offsetX), (((matrix1._m11 * matrix2._m12) + (matrix1._m12 * matrix2._m22)) + (matrix1._m13 * matrix2._m32)) + (matrix1._m14 * matrix2._offsetY), (((matrix1._m11 * matrix2._m13) + (matrix1._m12 * matrix2._m23)) + (matrix1._m13 * matrix2._m33)) + (matrix1._m14 * matrix2._offsetZ), (((matrix1._m11 * matrix2._m14) + (matrix1._m12 * matrix2._m24)) + (matrix1._m13 * matrix2._m34)) + (matrix1._m14 * matrix2._m44), (((matrix1._m21 * matrix2._m11) + (matrix1._m22 * matrix2._m21)) + (matrix1._m23 * matrix2._m31)) + (matrix1._m24 * matrix2._offsetX), (((matrix1._m21 * matrix2._m12) + (matrix1._m22 * matrix2._m22)) + (matrix1._m23 * matrix2._m32)) + (matrix1._m24 * matrix2._offsetY), (((matrix1._m21 * matrix2._m13) + (matrix1._m22 * matrix2._m23)) + (matrix1._m23 * matrix2._m33)) + (matrix1._m24 * matrix2._offsetZ), (((matrix1._m21 * matrix2._m14) + (matrix1._m22 * matrix2._m24)) + (matrix1._m23 * matrix2._m34)) + (matrix1._m24 * matrix2._m44), (((matrix1._m31 * matrix2._m11) + (matrix1._m32 * matrix2._m21)) + (matrix1._m33 * matrix2._m31)) + (matrix1._m34 * matrix2._offsetX), (((matrix1._m31 * matrix2._m12) + (matrix1._m32 * matrix2._m22)) + (matrix1._m33 * matrix2._m32)) + (matrix1._m34 * matrix2._offsetY), (((matrix1._m31 * matrix2._m13) + (matrix1._m32 * matrix2._m23)) + (matrix1._m33 * matrix2._m33)) + (matrix1._m34 * matrix2._offsetZ), (((matrix1._m31 * matrix2._m14) + (matrix1._m32 * matrix2._m24)) + (matrix1._m33 * matrix2._m34)) + (matrix1._m34 * matrix2._m44), (((matrix1._offsetX * matrix2._m11) + (matrix1._offsetY * matrix2._m21)) + (matrix1._offsetZ * matrix2._m31)) + (matrix1._m44 * matrix2._offsetX), (((matrix1._offsetX * matrix2._m12) + (matrix1._offsetY * matrix2._m22)) + (matrix1._offsetZ * matrix2._m32)) + (matrix1._m44 * matrix2._offsetY), (((matrix1._offsetX * matrix2._m13) + (matrix1._offsetY * matrix2._m23)) + (matrix1._offsetZ * matrix2._m33)) + (matrix1._m44 * matrix2._offsetZ), (((matrix1._offsetX * matrix2._m14) + (matrix1._offsetY * matrix2._m24)) + (matrix1._offsetZ * matrix2._m34)) + (matrix1._m44 * matrix2._m44)); - } - - - public Vector3d Transform(Vector3d point) - { - Vector3d temp = new Vector3d(); - if (!this.IsDistinguishedIdentity) - { - double x = point.X; - double y = point.Y; - double z = point.Z; - temp.X = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; - temp.Y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; - temp.Z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - if (!this.IsAffine) - { - double num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - temp.X /= num4; - temp.Y /= num4; - temp.Z /= num4; - } - } - - return temp; - } - - internal void TransformTo(Vector3d input, Vector3d output) - { - output.X = (((input.X * this._m11) + (input.Y * this._m21)) + (input.Z * this._m31)) + this._offsetX; - output.Y = (((input.X * this._m12) + (input.Y * this._m22)) + (input.Z * this._m32)) + this._offsetY; - output.Z = (((input.X * this._m13) + (input.Y * this._m23)) + (input.Z * this._m33)) + this._offsetZ; - - double num4 = (((input.X * this._m14) + (input.Y * this._m24)) + (input.Z * this._m34)) + this._m44; - output.X /= num4; - output.Y /= num4; - output.Z /= num4; - } - //internal void TransformTo(Vector3d input, Vector3d output) - //{ - // if (!this.IsDistinguishedIdentity) - // { - // double x = input.X; - // double y = input.Y; - // double z = input.Z; - // output.X = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; - // output.Y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; - // output.Z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - // if (!this.IsAffine) - // { - // double num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - // output.X /= num4; - // output.Y /= num4; - // output.Z /= num4; - // } - // } - //} - public void TransformArray(Vector3d[] points) - { - if (points != null) - { - for (int i = 0; i < points.Length; i++) - { - this.MultiplyPoint( points[i]); - } - } - } - - public void ProjectArrayToScreen(Vector3d[] input, Vector3d[] output) - { - if (input != null && output != null) - { - bool affine = this.IsAffine; - for (int i = 0; i < input.Length; i++) - { - double x = input[i].X; - double y = input[i].Y; - double z = input[i].Z; - if (affine) - { - output[i].X = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) ); - output[i].Y = (((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) ); - output[i].Z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - } - else - { - double num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - output[i].X = ((((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4) ) ; - output[i].Y = ((((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4) ) ; - output[i].Z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; - } - } - } - } - - public Vector3d ProjectToScreen(Vector3d input, double width, double height) - { - Vector3d output = new Vector3d(); - double x = input.X; - double y = input.Y; - double z = input.Z; - if (this.IsAffine) - { - output.X = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) + .5) * width; - output.Y = (-((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) + .5) * height; - output.Z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - } - else - { - double num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - output.X = ((((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4) + .5) * width; ; - output.Y = (-(((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4) + .5) * height; ; - output.Z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; - } - return output; - } - - - - //public Vector3d Transform(Vector3d vector) - //{ - // this.MultiplyVector(ref vector); - // return vector; - //} - - //public void Transform(Vector3d[] vectors) - //{ - // if (vectors != null) - // { - // for (int i = 0; i < vectors.Length; i++) - // { - // this.MultiplyVector(ref vectors[i]); - // } - // } - //} - - public bool IsAffine - { - get - { - if (this.IsDistinguishedIdentity) - { - return true; - } - if (((this._m14 == 0) && (this._m24 == 0)) && (this._m34 == 0)) - { - return (this._m44 == 1); - } - return false; - } - } - - public double Determinant - { - get - { - if (this.IsDistinguishedIdentity) - { - return 1; - } - if (this.IsAffine) - { - return this.GetNormalizedAffineDeterminant(); - } - double num6 = (this._m13 * this._m24) - (this._m23 * this._m14); - double num5 = (this._m13 * this._m34) - (this._m33 * this._m14); - double num4 = (this._m13 * this._m44) - (this._offsetZ * this._m14); - double num3 = (this._m23 * this._m34) - (this._m33 * this._m24); - double num2 = (this._m23 * this._m44) - (this._offsetZ * this._m24); - double num = (this._m33 * this._m44) - (this._offsetZ * this._m34); - double num10 = ((this._m22 * num5) - (this._m32 * num6)) - (this._m12 * num3); - double num9 = ((this._m12 * num2) - (this._m22 * num4)) + (this._offsetY * num6); - double num8 = ((this._m32 * num4) - (this._offsetY * num5)) - (this._m12 * num); - double num7 = ((this._m22 * num) - (this._m32 * num2)) + (this._offsetY * num3); - return ((((this._offsetX * num10) + (this._m31 * num9)) + (this._m21 * num8)) + (this._m11 * num7)); - } - } - - public bool HasInverse - { - get - { - return !DoubleUtilities.IsZero(this.Determinant); - } - } - public void Invert() - { - if (!this.InvertCore()) - { - return; - - } - } - - public void Transpose() - { - Matrix3d that = new Matrix3d(); - that.Set(this); - - this._m12 = that._m21; - this._m13 = that._m31; - this._m14 = that._offsetX; - this._m23 = that._m32; - this._m24 = that._offsetY; - this._m34 = that._offsetZ; - this._m21 = that._m12; - this._m31 = that._m13; - this._offsetX = that._m14; - this._m32 = that._m23; - this._offsetY = that._m24; - this._offsetZ = that._m34; - - } - - //private static void Swap(ref double a, ref double b) - //{ - // double temp = a; - // a = b; - // b = temp; - //} - - public double M11 - { - get - { - if (this.IsDistinguishedIdentity) - { - return 1; - } - return this._m11; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m11 = value; - } - } - - public double M12 - { - get - { - return this._m12; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m12 = value; - } - } - - public double M13 - { - get - { - return this._m13; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m13 = value; - } - } - - public double M14 - { - get - { - return this._m14; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m14 = value; - } - } - - public double M21 - { - get - { - return this._m21; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m21 = value; - } - } - public double M22 - { - get - { - if (this.IsDistinguishedIdentity) - { - return 1; - } - return this._m22; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m22 = value; - } - } - public double M23 - { - get - { - return this._m23; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m23 = value; - } - } - public double M24 - { - get - { - return this._m24; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m24 = value; - } - } - public double M31 - { - get - { - return this._m31; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m31 = value; - } - } - public double M32 - { - get - { - return this._m32; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m32 = value; - } - } - public double M33 - { - get - { - if (this.IsDistinguishedIdentity) - { - return 1; - } - return this._m33; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m33 = value; - } - } - public double M34 - { - get - { - return this._m34; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m34 = value; - } - } - - public double M41 - { - get - { - return OffsetX; - } - set - { - OffsetX = value; - } - } - - public double M42 - { - get - { - return OffsetY; - } - set - { - OffsetY = value; - } - } - - public double M43 - { - get - { - return OffsetZ; - } - set - { - OffsetZ = value; - } - } - - public double OffsetX - { - get - { - return this._offsetX; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._offsetX = value; - } - } - public double OffsetY - { - get - { - return this._offsetY; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._offsetY = value; - } - } - public double OffsetZ - { - get - { - return this._offsetZ; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._offsetZ = value; - } - } - public double M44 - { - get - { - if (this.IsDistinguishedIdentity) - { - return 1; - } - return this._m44; - } - set - { - if (this.IsDistinguishedIdentity) - { - Set(s_identity); - this.IsDistinguishedIdentity = false; - } - this._m44 = value; - } - } - private void SetScaleMatrix( Vector3d scale) - { - this._m11 = scale.X; - this._m22 = scale.Y; - this._m33 = scale.Z; - this._m44 = 1; - this.IsDistinguishedIdentity = false; - } - - private void SetScaleMatrixCenter( Vector3d scale, Vector3d center) - { - this._m11 = scale.X; - this._m22 = scale.Y; - this._m33 = scale.Z; - this._m44 = 1; - this._offsetX = center.X - (center.X * scale.X); - this._offsetY = center.Y - (center.Y * scale.Y); - this._offsetZ = center.Z - (center.Z * scale.Z); - this.IsDistinguishedIdentity = false; - } - - private void SetTranslationMatrix( Vector3d offset) - { - this._m11 = this._m22 = this._m33 = this._m44 = 1; - this._offsetX = offset.X; - this._offsetY = offset.Y; - this._offsetZ = offset.Z; - this.IsDistinguishedIdentity = false; - } - - //internal static Matrix3d CreateRotationMatrix(ref Quaternion quaternion, ref Vector3d center) - //{ - // Matrix3d matrixd = s_identity; - // matrixd.IsDistinguishedIdentity = false; - // double num12 = quaternion.X + quaternion.X; - // double num2 = quaternion.Y + quaternion.Y; - // double num = quaternion.Z + quaternion.Z; - // double num11 = quaternion.X * num12; - // double num10 = quaternion.X * num2; - // double num9 = quaternion.X * num; - // double num8 = quaternion.Y * num2; - // double num7 = quaternion.Y * num; - // double num6 = quaternion.Z * num; - // double num5 = quaternion.W * num12; - // double num4 = quaternion.W * num2; - // double num3 = quaternion.W * num; - // matrixd._m11 = 1 - (num8 + num6); - // matrixd._m12 = num10 + num3; - // matrixd._m13 = num9 - num4; - // matrixd._m21 = num10 - num3; - // matrixd._m22 = 1 - (num11 + num6); - // matrixd._m23 = num7 + num5; - // matrixd._m31 = num9 + num4; - // matrixd._m32 = num7 - num5; - // matrixd._m33 = 1 - (num11 + num8); - // if (((center.X != 0) || (center.Y != 0)) || (center.Z != 0)) - // { - // matrixd._offsetX = (((-center.X * matrixd._m11) - (center.Y * matrixd._m21)) - (center.Z * matrixd._m31)) + center.X; - // matrixd._offsetY = (((-center.X * matrixd._m12) - (center.Y * matrixd._m22)) - (center.Z * matrixd._m32)) + center.Y; - // matrixd._offsetZ = (((-center.X * matrixd._m13) - (center.Y * matrixd._m23)) - (center.Z * matrixd._m33)) + center.Z; - // } - // return matrixd; - //} - - private void MultiplyPoint( Vector3d point) - { - if (!this.IsDistinguishedIdentity) - { - double x = point.X; - double y = point.Y; - double z = point.Z; - point.X = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; - point.Y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; - point.Z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - if (!this.IsAffine) - { - double num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - point.X /= num4; - point.Y /= num4; - point.Z /= num4; - } - } - } - - public void MultiplyVector( Vector3d vector) - { - if (!this.IsDistinguishedIdentity) - { - double x = vector.X; - double y = vector.Y; - double z = vector.Z; - vector.X = ((x * this._m11) + (y * this._m21)) + (z * this._m31); - vector.Y = ((x * this._m12) + (y * this._m22)) + (z * this._m32); - vector.Z = ((x * this._m13) + (y * this._m23)) + (z * this._m33); - } - } - - private double GetNormalizedAffineDeterminant() - { - double num3 = (this._m12 * this._m23) - (this._m22 * this._m13); - double num2 = (this._m32 * this._m13) - (this._m12 * this._m33); - double num = (this._m22 * this._m33) - (this._m32 * this._m23); - return (((this._m31 * num3) + (this._m21 * num2)) + (this._m11 * num)); - } - - private bool NormalizedAffineInvert() - { - double num11 = (this._m12 * this._m23) - (this._m22 * this._m13); - double num10 = (this._m32 * this._m13) - (this._m12 * this._m33); - double num9 = (this._m22 * this._m33) - (this._m32 * this._m23); - double num8 = ((this._m31 * num11) + (this._m21 * num10)) + (this._m11 * num9); - if (DoubleUtilities.IsZero(num8)) - { - return false; - } - double num20 = (this._m21 * this._m13) - (this._m11 * this._m23); - double num19 = (this._m11 * this._m33) - (this._m31 * this._m13); - double num18 = (this._m31 * this._m23) - (this._m21 * this._m33); - double num7 = (this._m11 * this._m22) - (this._m21 * this._m12); - double num6 = (this._m11 * this._m32) - (this._m31 * this._m12); - double num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); - double num4 = (this._m21 * this._m32) - (this._m31 * this._m22); - double num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); - double num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); - double num17 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); - double num16 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); - double num15 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); - double num14 = num7; - double num13 = -num6; - double num12 = num4; - double num = 1 / num8; - this._m11 = num9 * num; - this._m12 = num10 * num; - this._m13 = num11 * num; - this._m21 = num18 * num; - this._m22 = num19 * num; - this._m23 = num20 * num; - this._m31 = num12 * num; - this._m32 = num13 * num; - this._m33 = num14 * num; - this._offsetX = num15 * num; - this._offsetY = num16 * num; - this._offsetZ = num17 * num; - return true; - } - - - private bool InvertCore() - { - if (!this.IsDistinguishedIdentity) - { - if (this.IsAffine) - { - return this.NormalizedAffineInvert(); - } - double num7 = (this._m13 * this._m24) - (this._m23 * this._m14); - double num6 = (this._m13 * this._m34) - (this._m33 * this._m14); - double num5 = (this._m13 * this._m44) - (this._offsetZ * this._m14); - double num4 = (this._m23 * this._m34) - (this._m33 * this._m24); - double num3 = (this._m23 * this._m44) - (this._offsetZ * this._m24); - double num2 = (this._m33 * this._m44) - (this._offsetZ * this._m34); - double num12 = ((this._m22 * num6) - (this._m32 * num7)) - (this._m12 * num4); - double num11 = ((this._m12 * num3) - (this._m22 * num5)) + (this._offsetY * num7); - double num10 = ((this._m32 * num5) - (this._offsetY * num6)) - (this._m12 * num2); - double num9 = ((this._m22 * num2) - (this._m32 * num3)) + (this._offsetY * num4); - double num8 = (((this._offsetX * num12) + (this._m31 * num11)) + (this._m21 * num10)) + (this._m11 * num9); - if (DoubleUtilities.IsZero(num8)) - { - return false; - } - double num24 = ((this._m11 * num4) - (this._m21 * num6)) + (this._m31 * num7); - double num23 = ((this._m21 * num5) - (this._offsetX * num7)) - (this._m11 * num3); - double num22 = ((this._m11 * num2) - (this._m31 * num5)) + (this._offsetX * num6); - double num21 = ((this._m31 * num3) - (this._offsetX * num4)) - (this._m21 * num2); - num7 = (this._m11 * this._m22) - (this._m21 * this._m12); - num6 = (this._m11 * this._m32) - (this._m31 * this._m12); - num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); - num4 = (this._m21 * this._m32) - (this._m31 * this._m22); - num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); - num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); - double num20 = ((this._m13 * num4) - (this._m23 * num6)) + (this._m33 * num7); - double num19 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); - double num18 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); - double num17 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); - double num16 = ((this._m24 * num6) - (this._m34 * num7)) - (this._m14 * num4); - double num15 = ((this._m14 * num3) - (this._m24 * num5)) + (this._m44 * num7); - double num14 = ((this._m34 * num5) - (this._m44 * num6)) - (this._m14 * num2); - double num13 = ((this._m24 * num2) - (this._m34 * num3)) + (this._m44 * num4); - double num = 1 / num8; - this._m11 = num9 * num; - this._m12 = num10 * num; - this._m13 = num11 * num; - this._m14 = num12 * num; - this._m21 = num21 * num; - this._m22 = num22 * num; - this._m23 = num23 * num; - this._m24 = num24 * num; - this._m31 = num13 * num; - this._m32 = num14 * num; - this._m33 = num15 * num; - this._m34 = num16 * num; - this._offsetX = num17 * num; - this._offsetY = num18 * num; - this._offsetZ = num19 * num; - this._m44 = num20 * num; - } - return true; - } - - public static Matrix3d LookAtLH(Vector3d cameraPosition, Vector3d cameraTarget, Vector3d cameraUpVector) - { - - Vector3d zaxis = Vector3d.SubtractVectors(cameraTarget, cameraPosition); - zaxis.Normalize(); - Vector3d xaxis = Vector3d.Cross(cameraUpVector, zaxis); - xaxis.Normalize(); - Vector3d yaxis = Vector3d.Cross(zaxis, xaxis); - - Matrix3d mat = Matrix3d.Create(xaxis.X, yaxis.X, zaxis.X, 0, xaxis.Y, yaxis.Y, zaxis.Y, 0, xaxis.Z, yaxis.Z, zaxis.Z, 0, -Vector3d.Dot(xaxis, cameraPosition), -Vector3d.Dot(yaxis, cameraPosition), -Vector3d.Dot(zaxis, cameraPosition), 1); - return mat; - } - - private static Matrix3d CreateIdentity() - { - Matrix3d matrixd = Matrix3d.Create(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - matrixd.IsDistinguishedIdentity = true; - return matrixd; - } - - private bool IsDistinguishedIdentity - { - get - { - return !this._isNotKnownToBeIdentity; - } - set - { - this._isNotKnownToBeIdentity = !value; - } - } - //public static bool operator ==(Matrix3d matrix1, Matrix3d matrix2) - //{ - // if (matrix1.IsDistinguishedIdentity || matrix2.IsDistinguishedIdentity) - // { - // return (matrix1.IsIdentity == matrix2.IsIdentity); - // } - // if (((((matrix1.M11 == matrix2.M11) && (matrix1.M12 == matrix2.M12)) && ((matrix1.M13 == matrix2.M13) && (matrix1.M14 == matrix2.M14))) && (((matrix1.M21 == matrix2.M21) && (matrix1.M22 == matrix2.M22)) && ((matrix1.M23 == matrix2.M23) && (matrix1.M24 == matrix2.M24)))) && ((((matrix1.M31 == matrix2.M31) && (matrix1.M32 == matrix2.M32)) && ((matrix1.M33 == matrix2.M33) && (matrix1.M34 == matrix2.M34))) && (((matrix1.OffsetX == matrix2.OffsetX) && (matrix1.OffsetY == matrix2.OffsetY)) && (matrix1.OffsetZ == matrix2.OffsetZ)))) - // { - // return (matrix1.M44 == matrix2.M44); - // } - // return false; - //} - - //public static bool operator !=(Matrix3d matrix1, Matrix3d matrix2) - //{ - // return !(matrix1 == matrix2); - //} - - public static bool Equals(Matrix3d matrix1, Matrix3d matrix2) - { - if (matrix1.IsDistinguishedIdentity || matrix2.IsDistinguishedIdentity) - { - return (matrix1.IsIdentity == matrix2.IsIdentity); - } - if ((((matrix1.M11==(matrix2.M11) && matrix1.M12==(matrix2.M12)) && (matrix1.M13==(matrix2.M13) && matrix1.M14==(matrix2.M14))) && ((matrix1.M21==(matrix2.M21) && matrix1.M22==(matrix2.M22)) && (matrix1.M23==(matrix2.M23) && matrix1.M24==(matrix2.M24)))) && (((matrix1.M31==(matrix2.M31) && matrix1.M32==(matrix2.M32)) && (matrix1.M33==(matrix2.M33) && matrix1.M34==(matrix2.M34))) && ((matrix1.OffsetX==(matrix2.OffsetX) && matrix1.OffsetY==(matrix2.OffsetY)) && matrix1.OffsetZ==(matrix2.OffsetZ)))) - { - return matrix1.M44==(matrix2.M44); - } - return false; - } - - //public override bool Equals(object o) - //{ - // if ((o == null) || !(o is Matrix3d)) - // { - // return false; - // } - // Matrix3d matrixd = (Matrix3d)o; - // return Equals(this, matrixd); - //} - - //public bool Equals(Matrix3d value) - //{ - // return Equals(this, value); - //} - - //public override int GetHashCode() - //{ - // if (this.IsDistinguishedIdentity) - // { - // return 0; - // } - // return (((((((((((((((this.M11.GetHashCode() ^ this.M12.GetHashCode()) ^ this.M13.GetHashCode()) ^ this.M14.GetHashCode()) ^ this.M21.GetHashCode()) ^ this.M22.GetHashCode()) ^ this.M23.GetHashCode()) ^ this.M24.GetHashCode()) ^ this.M31.GetHashCode()) ^ this.M32.GetHashCode()) ^ this.M33.GetHashCode()) ^ this.M34.GetHashCode()) ^ this.OffsetX.GetHashCode()) ^ this.OffsetY.GetHashCode()) ^ this.OffsetZ.GetHashCode()) ^ this.M44.GetHashCode()); - //} - - //public override string ToString() - //{ - // return this.ConvertToString(null, null); - //} - - //string IFormattable.ToString(string format, IFormatProvider provider) - //{ - // return this.ConvertToString(format, provider); - //} - - //private string ConvertToString(string format, IFormatProvider provider) - //{ - // if (this.IsIdentity) - // { - // return "Identity"; - // } - // char numericListSeparator = ','; - // return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}{0}{7:" + format + "}{0}{8:" + format + "}{0}{9:" + format + "}{0}{10:" + format + "}{0}{11:" + format + "}{0}{12:" + format + "}{0}{13:" + format + "}{0}{14:" + format + "}{0}{15:" + format + "}{0}{16:" + format + "}", new object[] { - // numericListSeparator, this._m11, this._m12, this._m13, this._m14, this._m21, this._m22, this._m23, this._m24, this._m31, this._m32, this._m33, this._m34, this._offsetX, this._offsetY, this._offsetZ, - // this._m44 - // }); - //} - - public static Matrix3d FromMatrix2d(Matrix2d mat) - { - Matrix3d mat3d = Matrix3d.CreateIdentity(); - - mat3d.M11 = mat.M11; - mat3d.M12 = mat.M12; - mat3d.M13 = mat.M13; - mat3d.M21 = mat.M21; - mat3d.M22 = mat.M22; - mat3d.M23 = mat.M23; - mat3d.M31 = mat.M31; - mat3d.M32 = mat.M32; - mat3d.M33 = mat.M33; - mat3d._isNotKnownToBeIdentity = true; - - return mat3d; - } - - - static Matrix3d() - { - s_identity = CreateIdentity(); - } - - public static Matrix3d RotationYawPitchRoll(double heading, double pitch, double roll) - { - Matrix3d matX = RotationX(pitch); - Matrix3d matY = RotationY(heading); - Matrix3d matZ = RotationZ(roll); - - return Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(matY, matX), matZ); - } - - internal static Matrix3d RotationY(double p) - { - double v = p; - - Matrix3d matNew = Matrix3d.Identity; - matNew._m11 = Math.Cos(v); - matNew._m22 = 1; - matNew._m31 = Math.Sin(v); - matNew._m13 = -Math.Sin(v); - matNew._m33 = Math.Cos(v); - matNew._isNotKnownToBeIdentity = true; - return matNew; - } - - internal static Matrix3d RotationX(double p) - { - double v = p; - - Matrix3d matNew = Matrix3d.Identity; - matNew._m11 = 1; - matNew._m22 = Math.Cos(v); - matNew._m32 = -Math.Sin(v); - matNew._m23 = Math.Sin(v); - matNew._m33 = Math.Cos(v); - matNew._isNotKnownToBeIdentity = true; - return matNew; - } - internal static Matrix3d RotationZ(double p) - { - double v = p; - - Matrix3d matNew = Matrix3d.Identity; - matNew._m11 = Math.Cos(v); - matNew._m21 = -Math.Sin(v); - matNew._m12 = Math.Sin(v); - matNew._m22 = Math.Cos(v); - matNew._m33 = 1; - matNew._isNotKnownToBeIdentity = true; - return matNew; - } - internal static Matrix3d Scaling(double x, double y, double z) - { - Matrix3d matNew = Matrix3d.Identity; - matNew._m11 = x; - matNew._m22 = y; - matNew._m33 = z; - matNew._isNotKnownToBeIdentity = true; - return matNew; - } - - internal static Matrix3d TranslationXYZ(double x, double y, double z) - { - Matrix3d matNew = Matrix3d.Identity; - matNew.OffsetX = x; - matNew.OffsetY = y; - matNew.OffsetZ = z; - matNew._isNotKnownToBeIdentity = true; - return matNew; - } - - internal void Multiply(Matrix3d mat) - { - Set(Matrix3d.MultiplyMatrix(this, mat)); - } - - public static Matrix3d PerspectiveFovLH(double fieldOfViewY, double aspectRatio, double znearPlane, double zfarPlane) - { - double h = 1 / Math.Tan(fieldOfViewY / 2); - double w = h / aspectRatio; - - return Matrix3d.Create(w, 0, 0, 0, 0, h, 0, 0, 0, 0, zfarPlane / (zfarPlane - znearPlane), 1, 0, 0, -znearPlane * zfarPlane / (zfarPlane - znearPlane), 0); - } - - public static Matrix3d PerspectiveOffCenterLH(double left, double right, double bottom, double top, double znearPlane, double zfarPlane) - { - return Matrix3d.Create( - 2 * znearPlane / (right - left), 0, 0, 0, - 0, 2 * znearPlane / (top - bottom), 0, 0, - (left + right) / (left - right), (top + bottom) / (bottom - top), zfarPlane / (zfarPlane - znearPlane), 1, - 0, 0, znearPlane * zfarPlane / (znearPlane - zfarPlane), 0 - - ); - } - - public static Matrix3d InvertMatrix(Matrix3d matrix3d) - { - Matrix3d mat = matrix3d.Clone(); - mat.Invert(); - return mat; - } - - public static Matrix3d Translation(Vector3d vector3d) - { - return Matrix3d.TranslationXYZ(vector3d.X, vector3d.Y, vector3d.Z); - } - - static public Matrix3d GetMapMatrix(Coordinates center, double fieldWidth, double fieldHeight, double rotation) - { - double offsetX = 0; - double offsetY = 0; - - offsetX = -(((center.Lng + 180 - (fieldWidth / 2)) / 360)); - offsetY = -((1 - ((center.Lat + 90 + (fieldHeight / 2)) / 180))); - - Matrix2d mat = new Matrix2d(); - - double scaleX = 0; - double scaleY = 0; - - scaleX = 360 / fieldWidth; - scaleY = 180 / fieldHeight; - mat = Matrix2d.Multiply(mat, Matrix2d.Translation(offsetX, offsetY)); - mat = Matrix2d.Multiply(mat, Matrix2d.Scaling(scaleX, scaleY)); - if (rotation != 0) - { - mat = Matrix2d.Multiply(mat,Matrix2d.Translation(-.5, -.5)); - mat = Matrix2d.Multiply(mat,Matrix2d.Rotation(rotation)); - mat = Matrix2d.Multiply(mat,Matrix2d.Translation(.5, .5)); - } - - - - return Matrix3d.FromMatrix2d(mat); - } - - - } - - public class Matrix2d - { - public double M11 = 1; - public double M12; - public double M13; - public double M21; - public double M22 = 1; - public double M23; - public double M31; - public double M32; - public double M33 = 1; - - public Matrix2d() - { - } - public static Matrix2d Create(double m11, double m12, double m13, double m21, double m22, double m23, double m31, double m32, double m33) - { - Matrix2d mat = new Matrix2d(); - mat.M11 = m11; - mat.M12 = m12; - mat.M13 = m13; - mat.M21 = m21; - mat.M22 = m22; - mat.M23 = m23; - mat.M31 = m31; - mat.M32 = m32; - mat.M33 = m33; - - return mat; - } - - public static Matrix2d Rotation(double angle) - { - Matrix2d mat = new Matrix2d(); - mat.M11 = Math.Cos(angle); - mat.M21 = -Math.Sin(angle); - mat.M12 = Math.Sin(angle); - mat.M22 = Math.Cos(angle); - return mat; - } - - public static Matrix2d Translation(double x, double y) - { - Matrix2d mat = new Matrix2d(); - mat.M31 = x; - mat.M32 = y; - - return mat; - } - - public static Matrix2d Scaling(double x, double y) - { - Matrix2d mat = new Matrix2d(); - mat.M11 = x; - mat.M22 = y; - return mat; - } - - public static Matrix2d Multiply(Matrix2d matrix1, Matrix2d matrix2) - { - - return Matrix2d.Create - ( - (((matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21)) + (matrix1.M13 * matrix2.M31)), - (((matrix1.M11 * matrix2.M12) + (matrix1.M12 * matrix2.M22)) + (matrix1.M13 * matrix2.M32)), - (((matrix1.M11 * matrix2.M13) + (matrix1.M12 * matrix2.M23)) + (matrix1.M13 * matrix2.M33)), - (((matrix1.M21 * matrix2.M11) + (matrix1.M22 * matrix2.M21)) + (matrix1.M23 * matrix2.M31)), - (((matrix1.M21 * matrix2.M12) + (matrix1.M22 * matrix2.M22)) + (matrix1.M23 * matrix2.M32)), - (((matrix1.M21 * matrix2.M13) + (matrix1.M22 * matrix2.M23)) + (matrix1.M23 * matrix2.M33)), - (((matrix1.M31 * matrix2.M11) + (matrix1.M32 * matrix2.M21)) + (matrix1.M33 * matrix2.M31)), - (((matrix1.M31 * matrix2.M12) + (matrix1.M32 * matrix2.M22)) + (matrix1.M33 * matrix2.M32)), - (((matrix1.M31 * matrix2.M13) + (matrix1.M32 * matrix2.M23)) + (matrix1.M33 * matrix2.M33)) - ); - } - - public static Matrix2d RotateAt(double angle, Vector2d pnt) - { - Matrix2d matT0 = Matrix2d.Translation(-pnt.X, -pnt.Y); - Matrix2d matR = Matrix2d.Rotation(angle); - Matrix2d matT1 = Matrix2d.Translation(pnt.X, pnt.Y); - - return Multiply(Multiply(matT0, matR), matT1); - } - - internal void TransformPoints(Vector2d[] points) - { - foreach (Vector2d pnt in points) - { - MultiplyPoint(pnt); - } - } - public void MultiplyPoint(Vector2d point) - { - - double x = point.X; - double y = point.Y; - point.X = (((x * this.M11) + (y * this.M21)) + this.M31); - point.Y = (((x * this.M12) + (y * this.M22)) + this.M32); - } - } - - public static class DoubleUtilities - { - private const double Epsilon = 2.2204460492503131E-50; - - public static bool IsZero(double value) - { - //return false; - return (Math.Abs(value) < Epsilon); - } - - public static bool IsOne(double value) - { - return (Math.Abs(value - 1) < Epsilon); - } - - public static double RadiansToDegrees(double radians) - { - return radians * 180 / Math.PI; - } - - public static double DegreesToRadians(double degrees) - { - return degrees * Math.PI / 180; - } - - public static double Clamp(double x, double min, double max) - { - return Math.Max(min, Math.Min(x, max)); - } - } - public class PlaneD - { - public double A; - public double B; - public double C; - public double D; - - public PlaneD(double valuePointA, double valuePointB, double valuePointC, double valuePointD) - { - this.A = valuePointA; - this.B = valuePointB; - this.C = valuePointC; - this.D = valuePointD; - } - - //public override bool Equals(object compare); - //public static bool operator ==(Plane left, Plane right); - // public static bool operator !=(Plane left, Plane right); - // public override int GetHashCode(); - // public Plane(); - // public static Plane Empty { get; } - // public override string ToString(); - // public static float DotNormal(Plane p, Vector3 v); - public void Normalize() - { - double length = Math.Sqrt(A * A + B * B + C * C); - - A /= length; - B /= length; - C /= length; - D /= length; - - - //Vector3d vector = new Vector3d(A, B, C); - //vector.Normalize(); - //A = vector.X; - //B = vector.Y; - //C = vector.Z; - } - - // public static Plane Normalize(Plane p); - // public static Vector3 IntersectLine(Plane p, Vector3 v1, Vector3 v2); - // public static Plane FromPointNormal(Vector3 point, Vector3 normal); - // public static Plane FromPoints(Vector3 p1, Vector3 p2, Vector3 p3); - // public void Transform(Matrix m); - // public static Plane Transform(Plane p, Matrix m); - // public void Scale(float s); - // public static Plane Scale(Plane p, float s); - // public float Dot(Vector3 v); - public double Dot(Vector4d v) - { - //return ((((planeRef[4] * *(((float*) (&v + 4)))) + (planeRef[8] * *(((float*) (&v + 8))))) + (planeRef[12] * *(((float*) (&v + 12))))) + (planeRef[0] * *(((float*) &v)))); - return B * v.Y + C * v.Z + D * v.W + A * v.X; - } - - - } - public class Vector4d - { - public Vector4d(double valueX, double valueY, double valueZ, double valueW) - { - this.X = valueX; - this.Y = valueY; - this.Z = valueZ; - this.W = valueW; - } - public double X; - public double Y; - public double Z; - public double W; - } - - public class PositionNormalTexturedX2 - { - // Summary: - // Retrieves the Microsoft.DirectX.Direct3D.VertexFormats for the current custom - // vertex. - //public const VertexFormats Format = VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture2; - public double X; - // - // Summary: - // Retrieves or sets the y component of the position. - public double Y; - // - // Summary: - // Retrieves or sets the z component of the position. - public double Z; - // Summary: - // Retrieves or sets the nx component of the vertex normal. - public double Nx; - // - // Summary: - // Retrieves or sets the ny component of the vertex normal. - public double Ny; - // - // Summary: - // Retrieves or sets the nz component of the vertex normal. - public double Nz; - // - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv; - // - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu1; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv1; - // - // Summary: - // Retrieves or sets the x component of the position. - - - // - // Summary: - // Initializes a new instance of the PositionNormalTexturedX2 - // class. - // - // Parameters: - // pos: - // A Microsoft.DirectX.Vector3 object that contains the vertex position. - // - // nor: - // A Microsoft.DirectX.Vector3 object that contains the vertex normal data. - // - // u: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - - public PositionNormalTexturedX2() - { - } - - public static PositionNormalTexturedX2 Create2UV(Vector3d pos, Vector3d nor, double u, double v, double u1, double v1) - { - PositionNormalTexturedX2 temp = new PositionNormalTexturedX2(); - temp.X = pos.X; - temp.Y = pos.Y; - temp.Z = pos.Z; - temp.Nx = nor.X; - temp.Ny = nor.Y; - temp.Nz = nor.Z; - temp.Tu = u; - temp.Tv = v; - temp.Tu1 = u1; - temp.Tv1 = v1; - - return temp; - } - - public static PositionNormalTexturedX2 Create(Vector3d pos, Vector3d nor, double u, double v) - { - PositionNormalTexturedX2 temp = new PositionNormalTexturedX2(); - temp.X = pos.X; - temp.Y = pos.Y; - temp.Z = pos.Z; - temp.Nx = nor.X; - temp.Ny = nor.Y; - temp.Nz = nor.Z; - temp.Tu = u; - temp.Tv = v; - Coordinates result = Coordinates.CartesianToSpherical2(nor); - temp.Tu1 = (float)((result.Lng + 180.0) / 360.0); - temp.Tv1 = (float)(1 - ((result.Lat + 90.0) / 180.0)); - - return temp; - } - - - public double Lat - { - get { return (1 - Tv1) * 180 - 90; } - set { Tv1 = (float)(1 - ((value + 90.0) / 180.0)); } - } - - public double Lng - { - get { return Tu1 * 360 - 180; } - set { Tu1 = (float)((value + 180.0) / 360.0); } - } - - - // - // Summary: - // Initializes a new instance of the PositionNormalTexturedX2 - // class. - // - // Parameters: - // xvalue: - // Floating-point value that represents the x coordinate of the position. - // - // yvalue: - // Floating-point value that represents the y coordinate of the position. - // - // zvalue: - // Floating-point value that represents the z coordinate of the position. - // - // nxvalue: - // Floating-point value that represents the nx coordinate of the vertex normal. - // - // nyvalue: - // Floating-point value that represents the ny coordinate of the vertex normal. - // - // nzvalue: - // Floating-point value that represents the nz coordinate of the vertex normal. - // - // u: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - public static PositionNormalTexturedX2 CreateLong2UV(float xvalue, float yvalue, float zvalue, float nxvalue, float nyvalue, float nzvalue, float u, float v, float u1, float v1) - { - PositionNormalTexturedX2 temp = new PositionNormalTexturedX2(); - temp.X = xvalue; - temp.Y = yvalue; - temp.Z = zvalue; - temp.Nx = nxvalue; - temp.Ny = nyvalue; - temp.Nz = nzvalue; - temp.Tu = u; - temp.Tv = v; - temp.Tu1 = u1; - temp.Tv1 = v1; - return temp; - } - public PositionNormalTexturedX2 CreateLong(float xvalue, float yvalue, float zvalue, float nxvalue, float nyvalue, float nzvalue, float u, float v) - { - PositionNormalTexturedX2 temp = new PositionNormalTexturedX2(); - temp.X = xvalue; - temp.Y = yvalue; - temp.Z = zvalue; - temp.Nx = nxvalue; - temp.Ny = nyvalue; - temp.Nz = nzvalue; - temp.Tu = u; - temp.Tv = v; - Coordinates result = Coordinates.CartesianToSpherical2(Vector3d.Create(Nx, Ny, Nz)); - temp.Tu1 = (float)((result.Lng + 180.0) / 360.0); - temp.Tv1 = (float)(1 - ((result.Lat + 90.0) / 180.0)); - return temp; - } - // Summary: - // Retrieves or sets the vertex normal data. - public Vector3d Normal - { - get - { - return Vector3d.Create(Nx, Ny, Nz); - } - set - { - Nx = value.X; - Ny = value.Y; - Nz = value.Z; - } - } - // - // Summary: - // Retrieves or sets the vertex position. - public Vector3d Position - { - get - { - return Vector3d.Create(X, Y, Y); - } - set - { - X = value.X; - Y = value.Y; - Z = value.Z; - } - } - // - // Summary: - // Retrieves the size of the PositionNormalTexturedX2 - // structure. - public static int StrideSize - { - get - { - return 40; - } - - } - - // Summary: - // Obtains a string representation of the current instance. - // - // Returns: - // String that represents the object. - public override string ToString() - { - return string.Format( - "X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}", - X, Y, Z, Nx, Ny, Nz, Tu, Tv, Tu1, Tv1 - ); - } - } - - public class PositionNormalTextured - { - // Summary: - // Retrieves the Microsoft.DirectX.Direct3D.VertexFormats for the current custom - // vertex. - //public const VertexFormats Format = VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture2; - public double X; - // - // Summary: - // Retrieves or sets the y component of the position. - public double Y; - // - // Summary: - // Retrieves or sets the z component of the position. - public double Z; - // Summary: - // Retrieves or sets the nx component of the vertex normal. - public double Nx; - // - // Summary: - // Retrieves or sets the ny component of the vertex normal. - public double Ny; - // - // Summary: - // Retrieves or sets the nz component of the vertex normal. - public double Nz; - // - // Summary: - // Retrieves or sets the u component of the texture coordinate. - public double Tu; - // - // Summary: - // Retrieves or sets the v component of the texture coordinate. - public double Tv; - // - // Summary: - // Retrieves or sets the u component of the texture coordinate. - - - // - // Summary: - // Initializes a new instance of the PositionNormalTexturedX2 - // class. - // - // Parameters: - // pos: - // A Microsoft.DirectX.Vector3 object that contains the vertex position. - // - // nor: - // A Microsoft.DirectX.Vector3 object that contains the vertex normal data. - // - // u: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - - public PositionNormalTextured() - { - } - - public static PositionNormalTextured CreateShort(Vector3d pos, Vector3d nor, double u, double v) - { - PositionNormalTextured temp = new PositionNormalTextured(); - temp.X = pos.X; - temp.Y = pos.Y; - temp.Z = pos.Z; - temp.Nx = nor.X; - temp.Ny = nor.Y; - temp.Nz = nor.Z; - temp.Tu = u; - temp.Tv = v; - return temp; - } - - internal static PositionNormalTextured Create(float x, float y, float z, int nx, int ny, int nz, int tu, int tv) - { - PositionNormalTextured temp = new PositionNormalTextured(); - temp.X = x; - temp.Y = y; - temp.Z = z; - temp.Nx = nx; - temp.Ny = ny; - temp.Nz = nz; - temp.Tu = tu; - temp.Tv = tv; - return temp; - } - - - - // - // Summary: - // Initializes a new instance of the PositionNormalTexturedX2 - // class. - // - // Parameters: - // xvalue: - // Floating-point value that represents the x coordinate of the position. - // - // yvalue: - // Floating-point value that represents the y coordinate of the position. - // - // zvalue: - // Floating-point value that represents the z coordinate of the position. - // - // nxvalue: - // Floating-point value that represents the nx coordinate of the vertex normal. - // - // nyvalue: - // Floating-point value that represents the ny coordinate of the vertex normal. - // - // nzvalue: - // Floating-point value that represents the nz coordinate of the vertex normal. - // - // u: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - // - // v: - // Floating-point value that represents the PositionNormalTexturedX2.#ctor() - // component of the texture coordinate. - - public PositionNormalTexturedX2 CreateLong(float xvalue, float yvalue, float zvalue, float nxvalue, float nyvalue, float nzvalue, float u, float v) - { - PositionNormalTexturedX2 temp = new PositionNormalTexturedX2(); - temp.X = xvalue; - temp.Y = yvalue; - temp.Z = zvalue; - temp.Nx = nxvalue; - temp.Ny = nyvalue; - temp.Nz = nzvalue; - temp.Tu = u; - temp.Tv = v; - return temp; - } - - - public static PositionNormalTextured CreateUV(Vector3d pos, Vector3d nor, Vector2d uv) - { - PositionNormalTextured temp = new PositionNormalTextured(); - temp.X = pos.X; - temp.Y = pos.Y; - temp.Z = pos.Z; - temp.Nx = nor.X; - temp.Ny = nor.Y; - temp.Nz = nor.Z; - temp.Tu = uv.X; - temp.Tv = uv.Y; - return temp; - } - - - // Summary: - // Retrieves or sets the vertex normal data. - public Vector3d Normal - { - get - { - return Vector3d.Create(Nx, Ny, Nz); - } - set - { - Nx = value.X; - Ny = value.Y; - Nz = value.Z; - } - } - - - // - // Summary: - // Retrieves or sets the vertex position. - public Vector3d Position - { - get - { - return Vector3d.Create(X, Y, Z); - } - set - { - X = value.X; - Y = value.Y; - Z = value.Z; - } - } - - - // Summary: - // Obtains a string representation of the current instance. - // - // Returns: - // String that represents the object. - public override string ToString() - { - return string.Format( - "X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}", - X, Y, Z, Nx, Ny, Nz, Tu, Tv - ); - } - } - - public class SphereHull - { - public SphereHull() - { - } - - public Vector3d Center; - public double Radius; - - internal static SphereHull Create(Vector3d Center, double Radius) - { - SphereHull temp = new SphereHull(); - temp.Center = Center; - temp.Radius = Radius; - return temp; - } - } - - - public class ConvexHull - { - public static SphereHull FindEnclosingSphereFast(Vector3d[] points) - - { - SphereHull result = new SphereHull(); - //Find the center of all points. - - int count = points.Length; - - Vector3d center = Vector3d.Zero; - for (int i = 0; i radius) - { - radius = distance; - } - } - - - //Find the real distance from the DistanceSquared. - - radius = Math.Sqrt(radius); - - //Construct the sphere. - result.Center = center; - result.Radius = radius; - return result; - } - - - public static SphereHull FindEnclosingSphere(Vector3d[] list) - { - Vector3d Center = new Vector3d(); - double Radius = 0; - - int count = list.Length; - int i; - double dx; - double dy; - double dz; - double rad_sq; - double xspan; - double yspan; - double zspan; - double maxspan; - double old_to_p; - double old_to_p_sq; - double old_to_new; - Vector3d xmin = new Vector3d(); - Vector3d xmax = new Vector3d(); - Vector3d ymin = new Vector3d(); - Vector3d ymax = new Vector3d(); - Vector3d zmin = new Vector3d(); - Vector3d zmax = new Vector3d(); - Vector3d dia1 = new Vector3d(); - Vector3d dia2 = new Vector3d(); - - - // FIRST PASS: find 6 minima/maxima points - xmin.X = ymin.Y = zmin.Z = 100000000; // initialize for min/max compare - xmax.X = ymax.Y = zmax.Z = -1000000000; - for (i = 0; i < count; i++) - { - Vector3d current = list[i]; - // his ith point. - if (current.X < xmin.X) - xmin = current; // New xminimum point - if (current.X > xmax.X) - xmax = current; - if (current.Y < ymin.Y) - ymin = current; - if (current.Y > ymax.Y) - ymax = current; - if (current.Z < zmin.Z) - zmin = current; - if (current.Z > zmax.Z) - zmax = current; - } - // Set xspan = distance between the 2 points xmin & xmax (squared) - dx = xmax.X - xmin.X; - dy = xmax.Y - xmin.Y; - dz = xmax.Z - xmin.Z; - xspan = dx * dx + dy * dy + dz * dz; - - // Same for y & z spans - dx = ymax.X - ymin.X; - dy = ymax.Y - ymin.Y; - dz = ymax.Z - ymin.Z; - yspan = dx * dx + dy * dy + dz * dz; - - dx = zmax.X - zmin.X; - dy = zmax.Y - zmin.Y; - dz = zmax.Z - zmin.Z; - zspan = dx * dx + dy * dy + dz * dz; - - dia1 = xmin; // assume xspan biggest - dia2 = xmax; - maxspan = xspan; - if (yspan > maxspan) - { - maxspan = yspan; - dia1 = ymin; - dia2 = ymax; - } - if (zspan > maxspan) - { - dia1 = zmin; - dia2 = zmax; - } - - - // dia1,dia2 is a diameter of initial sphere - // calc initial center - Center.X = (dia1.X + dia2.X) / 2.0; - Center.Y = (dia1.Y + dia2.Y) / 2.0; - Center.Z = (dia1.Z + dia2.Z) / 2.0; - // calculate initial radius**2 and radius - dx = dia2.X - Center.X; // x component of radius vector - dy = dia2.Y - Center.Y; // y component of radius vector - dz = dia2.Z - Center.Z; // z component of radius vector - rad_sq = dx * dx + dy * dy + dz * dz; - Radius = Math.Sqrt(rad_sq); - - // SECOND PASS: increment current sphere - - for (i = 0; i < count; i++) - { - Vector3d current = list[i]; // load global struct caller_p - // with his ith point. - dx = current.X - Center.X; - dy = current.Y - Center.Y; - dz = current.Z - Center.Z; - old_to_p_sq = dx * dx + dy * dy + dz * dz; - if (old_to_p_sq > rad_sq) // do r**2 test first - { // this point is outside of current sphere - old_to_p = Math.Sqrt(old_to_p_sq); - // calc radius of new sphere - Radius = (Radius + old_to_p) / 2.0; - rad_sq = Radius * Radius; // for next r**2 compare - old_to_new = old_to_p - Radius; - // calc center of new sphere - Center.X = (Radius * Center.X + old_to_new * current.X) / old_to_p; - Center.Y = (Radius * Center.Y + old_to_new * current.Y) / old_to_p; - Center.Z = (Radius * Center.Z + old_to_new * current.Z) / old_to_p; - // Suppress if desired - //Console.Write("\n New sphere: cen,rad = {0:f} {1:f} {2:f} {3:f}", cen.X, cen.Y, cen.Z, rad); - } - } - - return SphereHull.Create(Center, Radius); - - }// end of find_bounding_sphere() - - //public static void FindEnclosingCircle(Vector2d[] list, out Vector2d cen, out double rad) - //{ - // cen = new Vector2d(); - // int count = list.Length; - // int i; - // double dx; - // double dy; - // double rad_sq; - // double xspan; - // double yspan; - // double maxspan; - // double old_to_p; - // double old_to_p_sq; - // double old_to_new; - // Vector2d xmin = new Vector2d(); - // Vector2d xmax = new Vector2d(); - // Vector2d ymin = new Vector2d(); - // Vector2d ymax = new Vector2d(); - // Vector2d dia1 = new Vector2d(); - // Vector2d dia2 = new Vector2d(); - - - // // FIRST PASS: find 6 minima/maxima points - // xmin.X = ymin.Y = 100000000; // initialize for min/max compare - // xmax.X = ymax.Y = -1000000000; - // for (i = 0; i < count; i++) - // { - // Vector2d current = list[i]; - // // his ith point. - // if (current.X < xmin.X) - // xmin = current; // New xminimum point - // if (current.X > xmax.X) - // xmax = current; - // if (current.Y < ymin.Y) - // ymin = current; - // if (current.Y > ymax.Y) - // ymax = current; - - // } - // // Set xspan = distance between the 2 points xmin & xmax (squared) - // dx = xmax.X - xmin.X; - // dy = xmax.Y - xmin.Y; - // xspan = dx * dx + dy * dy; - - // // Same for y & z spans - // dx = ymax.X - ymin.X; - // dy = ymax.Y - ymin.Y; - // yspan = dx * dx + dy * dy; - - // dia1 = xmin; // assume xspan biggest - // dia2 = xmax; - // maxspan = xspan; - // if (yspan > maxspan) - // { - // maxspan = yspan; - // dia1 = ymin; - // dia2 = ymax; - // } - - - // // dia1,dia2 is a diameter of initial sphere - // // calc initial center - // cen.X = (dia1.X + dia2.X) / 2.0; - // cen.Y = (dia1.Y + dia2.Y) / 2.0; - // // calculate initial radius**2 and radius - // dx = dia2.X - cen.X; // x component of radius vector - // dy = dia2.Y - cen.Y; // y component of radius vector - // rad_sq = dx * dx + dy * dy; - // rad = Math.Sqrt(rad_sq); - - // // SECOND PASS: increment current sphere - - // for (i = 0; i < count; i++) - // { - // Vector2d current = list[i]; // load global struct caller_p - // // with his ith point. - // dx = current.X - cen.X; - // dy = current.Y - cen.Y; - // old_to_p_sq = dx * dx + dy * dy; - // if (old_to_p_sq > rad_sq) // do r**2 test first - // { // this point is outside of current sphere - // old_to_p = Math.Sqrt(old_to_p_sq); - // // calc radius of new sphere - // rad = (rad + old_to_p) / 2.0; - // rad_sq = rad * rad; // for next r**2 compare - // old_to_new = old_to_p - rad; - // // calc center of new sphere - // cen.X = (rad * cen.X + old_to_new * current.X) / old_to_p; - // cen.Y = (rad * cen.Y + old_to_new * current.Y) / old_to_p; - // } - // } - //}// end of find_bounding_circle() - } -} diff --git a/engine/csharp_ref/EquirectangularTile.cs b/engine/csharp_ref/EquirectangularTile.cs deleted file mode 100644 index d01c7855..00000000 --- a/engine/csharp_ref/EquirectangularTile.cs +++ /dev/null @@ -1,403 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - -namespace wwtlib -{ - - public class EquirectangularTile : Tile - { - double tileDegrees; - bool topDown = true; - - - protected void ComputeBoundingSphere() - { - if (!topDown) - { - ComputeBoundingSphereBottomsUp(); - return; - } - - tileDegrees = this.dataset.BaseTileDegrees / (Math.Pow(2, this.Level)); - - double latMin = (90 - (((double)this.tileY) * tileDegrees)); - double latMax = (90 - (((double)(this.tileY + 1)) * tileDegrees)); - double lngMin = (((double)this.tileX * tileDegrees) - 180.0); - double lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - - double latCenter = (latMin + latMax) / 2.0; - double lngCenter = (lngMin + lngMax) / 2.0; - - this.sphereCenter = (Vector3d)GeoTo3d(latCenter, lngCenter, false); - TopLeft = (Vector3d)GeoTo3d(latMin, lngMin, false); - BottomRight = (Vector3d)GeoTo3d(latMax, lngMax, false); - TopRight = (Vector3d)GeoTo3d(latMin, lngMax, false); - BottomLeft = (Vector3d)GeoTo3d(latMax, lngMin, false); - - Vector3d distVect = (Vector3d)GeoTo3d(latMin, lngMin, false); - distVect.Subtract(sphereCenter); - this.sphereRadius = distVect.Length(); - tileDegrees = lngMax - lngMin; - } - - //public override bool IsTileBigEnough(RenderContext renderContext) - //{ - // double arcPixels = tileDegrees / 256 * 900; - // return (renderContext.FovScale < arcPixels); - - //} - - - protected void ComputeBoundingSphereBottomsUp() - { - double tileDegrees = (double)this.dataset.BaseTileDegrees / ((double)Math.Pow(2, this.Level)); - - - double latMin = (-90 + (((double)(this.tileY + 1)) * tileDegrees)); - double latMax = (-90 + (((double)this.tileY) * tileDegrees)); - double lngMin = (((double)this.tileX * tileDegrees) - 180.0); - double lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - - double latCenter = (latMin + latMax) / 2.0; - double lngCenter = (lngMin + lngMax) / 2.0; - - this.sphereCenter = (Vector3d)GeoTo3d(latCenter, lngCenter, false); - - TopLeft = (Vector3d)GeoTo3d(latMin, lngMin, false); - BottomRight = (Vector3d)GeoTo3d(latMax, lngMax, false); - TopRight = (Vector3d)GeoTo3d(latMin, lngMax, false); - BottomLeft = (Vector3d)GeoTo3d(latMax, lngMin, false); - Vector3d distVect = TopLeft; - distVect.Subtract(sphereCenter); - this.sphereRadius = distVect.Length(); - tileDegrees = lngMax - lngMin; - } - int subDivisionLevel = 1; - - public override bool CreateGeometry(RenderContext renderContext) - { - base.CreateGeometry(renderContext); - if (renderContext.gl == null) - { - if (dataset.DataSetType == ImageSetType.Earth || dataset.DataSetType == ImageSetType.Planet) - { - subDivisionLevel = Math.Max(2, (4 - Level) * 2); - } - } - else - { - subDivisionLevel = 32; - } - - try - { - for (int i = 0; i < 4; i++) - { - RenderTriangleLists[i] = new List(); - } - - if (!topDown) - { - return CreateGeometryBottomsUp(renderContext); - } - double lat, lng; - - int index = 0; - double tileDegrees = this.dataset.BaseTileDegrees / (Math.Pow(2, this.Level)); - - double latMin = (90 - (((double)this.tileY) * tileDegrees)); - double latMax = (90 - (((double)(this.tileY + 1)) * tileDegrees)); - double lngMin = (((double)this.tileX * tileDegrees) - 180.0); - double lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - double tileDegreesX = lngMax - lngMin; - double tileDegreesY = latMax - latMin; - - - TopLeft = (Vector3d)GeoTo3d(latMin, lngMin, false); - BottomRight = (Vector3d)GeoTo3d(latMax, lngMax, false); - TopRight = (Vector3d)GeoTo3d(latMin, lngMax, false); - BottomLeft = (Vector3d)GeoTo3d(latMax, lngMin, false); - - - // Create a vertex buffer - PositionTexture[] verts = new PositionTexture[(subDivisionLevel + 1) * (subDivisionLevel + 1)]; // Lock the buffer (which will return our structs) - int x, y; - - double textureStep = 1.0f / subDivisionLevel; - for (y = 0; y <= subDivisionLevel; y++) - { - if (y != subDivisionLevel) - { - lat = latMin + (textureStep * tileDegreesY * y); - } - else - { - lat = latMax; - } - for (x = 0; x <= subDivisionLevel; x++) - { - - if (x != subDivisionLevel) - { - lng = lngMin + (textureStep * tileDegreesX * x); - } - else - { - lng = lngMax; - } - index = y * (subDivisionLevel + 1) + x; - verts[index] = PositionTexture.CreatePos(GeoTo3d(lat, lng, false), x * textureStep, y * textureStep); - } - } - TriangleCount = (subDivisionLevel) * (subDivisionLevel) * 2; - - int quarterDivisions = subDivisionLevel / 2; - int part = 0; - - if (renderContext.gl == null) - { - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - index = 0; - for (int y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (int x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - //index = ((y1 * quarterDivisions * 6) + 6 * x1); - // First triangle in quad - - PositionTexture p1; - PositionTexture p2; - PositionTexture p3; - - p1 = verts[(y1 * (subDivisionLevel + 1) + x1)]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - RenderTriangleLists[part].Add(RenderTriangle.Create(p1, p3, p2, texture, Level)); - - // Second triangle in quad - p1 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))]; - RenderTriangleLists[part].Add(RenderTriangle.Create(p1, p3, p2, texture, Level)); - - } - } - part++; - } - } - } - else - { - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(verts.Length * 5); - float[] buffer = (float[])(object)f32array; - index = 0; - foreach (PositionTexture pt in verts) - { - index = AddVertex(buffer, index, pt); - } - - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - Uint16Array ui16array = new Uint16Array(TriangleCount * 3); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - - index = 0; - for (int y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (int x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - // First triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - - // Second triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))); - } - } - - IndexBuffers[part] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, IndexBuffers[part]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - - part++; - } - } - } - } - catch - { - } - return true; - } - - private bool CreateGeometryBottomsUp(RenderContext renderContext) - { - - double lat, lng; - - int index = 0; - double tileDegrees = this.dataset.BaseTileDegrees / (Math.Pow(2, this.Level)); - - - double latMin = (-90 + (((double)(this.tileY+1)) * tileDegrees)); - double latMax = (-90 + (((double)this.tileY) * tileDegrees)); - double lngMin = (((double)this.tileX * tileDegrees) - 180.0); - double lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - double tileDegreesX = lngMax - lngMin; - double tileDegreesY = latMax - latMin; - // Create a vertex buffer - PositionTexture[] verts = new PositionTexture[(subDivisionLevel + 1) * (subDivisionLevel + 1)]; // Lock the buffer (which will return our structs) - int x, y; - - double textureStep = 1.0f / subDivisionLevel; - for (y = 0; y <= subDivisionLevel; y++) - { - if (y != subDivisionLevel) - { - lat = latMin + (textureStep * tileDegreesY * y); - } - else - { - lat = latMax; - } - for (x = 0; x <= subDivisionLevel; x++) - { - - if (x != subDivisionLevel) - { - lng = lngMin + (textureStep * tileDegreesX * x); - } - else - { - lng = lngMax; - } - index = y * (subDivisionLevel + 1) + x; - verts[index] = PositionTexture.CreatePos(GeoTo3d(lat, lng, false), x * textureStep, y * textureStep); - } - } - TriangleCount = (subDivisionLevel) * (subDivisionLevel) * 2; - - int quarterDivisions = subDivisionLevel / 2; - int part = 0; - if (renderContext.gl == null) - { - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - index = 0; - for (int y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (int x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - //index = ((y1 * quarterDivisions * 6) + 6 * x1); - // First triangle in quad - - PositionTexture p1; - PositionTexture p2; - PositionTexture p3; - - p1 = verts[(y1 * (subDivisionLevel + 1) + x1)]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - RenderTriangleLists[part].Add(RenderTriangle.Create(p1, p3, p2, texture, Level)); - - // Second triangle in quad - p1 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))]; - RenderTriangleLists[part].Add(RenderTriangle.Create(p1, p3, p2, texture, Level)); - - } - } - part++; - } - } - } - else - { - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(verts.Length * 5); - float[] buffer = (float[])(object)f32array; - index = 0; - foreach (PositionTexture pt in verts) - { - index = AddVertex(buffer, index, pt); - } - - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - Uint16Array ui16array = new Uint16Array(TriangleCount * 3); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - - index = 0; - - for (int y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (int x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - // First triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - - // Second triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))); - } - } - - IndexBuffers[part] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, IndexBuffers[part]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - - part++; - } - } - } - - - return true; - } - - public EquirectangularTile() - { - } - - public static EquirectangularTile Create(int level, int x, int y, Imageset dataset, Tile parent) - { - EquirectangularTile temp = new EquirectangularTile(); - temp.Parent = parent; - temp.Level = level; - temp.tileX = x; - temp.tileY = y; - temp.dataset = dataset; - temp.topDown = !dataset.BottomsUp; - temp.ComputeBoundingSphere(); - return temp; - } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/FastMath.cs b/engine/csharp_ref/FastMath.cs deleted file mode 100644 index 411672e2..00000000 --- a/engine/csharp_ref/FastMath.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -namespace wwtlib -{ - /** - * Code from Healpix Java package - */ - public class FastMath - { - private static double mulsign(double x, double y) - { return FastMath.sign(y) * x; } - - /** Checks if the argument is a NaN or not. */ - private static bool isnan(double d) - { return d != d; } - - /** Checks if the argument is either positive or negative infinity. */ - private static bool isinf(double d) - { return Math.Abs(d) == Double.PositiveInfinity; } - - private static double sign(double d) { - if (d == 0) - { - return 0; - } - return d > 0 ? 1 : -1; - } - - private static double atanhelper(double s) - { - double t = s * s; - double u = -1.88796008463073496563746e-05; - u = u * t + (0.000209850076645816976906797); - u = u * t + (-0.00110611831486672482563471); - u = u * t + (0.00370026744188713119232403); - u = u * t + (-0.00889896195887655491740809); - u = u * t + (0.016599329773529201970117); - u = u * t + (-0.0254517624932312641616861); - u = u * t + (0.0337852580001353069993897); - u = u * t + (-0.0407629191276836500001934); - u = u * t + (0.0466667150077840625632675); - u = u * t + (-0.0523674852303482457616113); - u = u * t + (0.0587666392926673580854313); - u = u * t + (-0.0666573579361080525984562); - u = u * t + (0.0769219538311769618355029); - u = u * t + (-0.090908995008245008229153); - u = u * t + (0.111111105648261418443745); - u = u * t + (-0.14285714266771329383765); - u = u * t + (0.199999999996591265594148); - u = u * t + (-0.333333333333311110369124); - - return u * t * s + s; - } - - private static double atan2k(double y, double x) - { - double q = 0; - - if (x < 0) { x = -x; q = -2; } - if (y > x) { double t = x; x = y; y = -t; q += 1; } - - return atanhelper(y / x) + q * (Math.PI / 2); - } - - /** This method calculates the arc tangent of y/x in radians, using - the signs of the two arguments to determine the quadrant of the - result. The results may have maximum error of 2 ulps. */ - public static double atan2(double y, double x) - { - double r = atan2k(Math.Abs(y), x); - - r = mulsign(r, x); - if (isinf(x) || x == 0) - r = Math.PI / 2 - (isinf(x) ? (sign(x) * (Math.PI / 2)) : 0); - if (isinf(y)) - r = Math.PI / 2 - (isinf(x) ? (sign(x) * (Math.PI * 1 / 4)) : 0); - if (y == 0) - r = (sign(x) == -1 ? Math.PI : 0); - return isnan(x) || isnan(y) ? Double.NaN : mulsign(r, y); - } - - /** This method calculates the arc sine of x in radians. The return - value is in the range [-pi/2, pi/2]. The results may have - maximum error of 3 ulps. */ - public static double asin(double d) - { return mulsign(atan2k(Math.Abs(d), Math.Sqrt((1 + d) * (1 - d))), d); } - - /** This method calculates the arc cosine of x in radians. The - return value is in the range [0, pi]. The results may have - maximum error of 3 ulps. */ - public static double acos(double d) - { - return mulsign(atan2k(Math.Sqrt((1 + d) * (1 - d)), Math.Abs(d)), d) - + (d < 0 ? Math.PI : 0); - } - - /** Returns the arc tangent of an angle. The results may have - maximum error of 2 ulps. */ - public static double atan(double s) - { - int q = 0; - if (s < 0) { s = -s; q = 2; } - if (s > 1) { s = 1.0 / s; q |= 1; } - - double t = atanhelper(s); - - if ((q & 1) != 0) t = 1.570796326794896557998982 - t; - if ((q & 2) != 0) t = -t; - - return t; - } - - private static readonly double PI4_A = .7853981554508209228515625; - private static readonly double PI4_B - = .794662735614792836713604629039764404296875e-8; - private static readonly double PI4_C - = .306161699786838294306516483068750264552437361480769e-16; - private static readonly double M_1_PI = 0.3183098861837906715377675267450287; - - private static double sincoshelper(double d) - { - double s = d * d; - double u = -7.97255955009037868891952e-18; - u = u * s + 2.81009972710863200091251e-15; - u = u * s - 7.64712219118158833288484e-13; - u = u * s + 1.60590430605664501629054e-10; - u = u * s - 2.50521083763502045810755e-08; - u = u * s + 2.75573192239198747630416e-06; - u = u * s - 0.000198412698412696162806809; - u = u * s + 0.00833333333333332974823815; - u = u * s - 0.166666666666666657414808; - return s * u * d + d; - } - - /** Returns the trigonometric sine of an angle. The results may - have maximum error of 2 ulps. */ - public static double sin(double d) - { - double u = d * M_1_PI; - long q = Math.Floor(u < 0 ? u - 0.5 : u + 0.5); - - double x = 4d * q; - d -= x * PI4_A; - d -= x * PI4_B; - d -= x * PI4_C; - - if ((q & 1) != 0) d = -d; - - return sincoshelper(d); - } - - /** Returns the trigonometric cosine of an angle. The results may - have maximum error of 2 ulps. */ - public static double cos(double d) - { - double u = d * M_1_PI - 0.5; - long q = 1 + 2 * Math.Floor(u < 0 ? u - 0.5 : u + 0.5); - - double x = 2d * q; - d -= x * PI4_A; - d -= x * PI4_B; - d -= x * PI4_C; - - if ((q & 2) == 0) d = -d; - - return sincoshelper(d); - } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/FitsProperties.cs b/engine/csharp_ref/FitsProperties.cs deleted file mode 100644 index 66a378e1..00000000 --- a/engine/csharp_ref/FitsProperties.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace wwtlib -{ - public enum ScaleTypes { - Linear = 0, - Log = 1, - Power = 2, - SquareRoot = 3, - HistogramEqualization = 4 - }; - - public class FitsProperties - { - public double BZero = 0; - public double BScale = 1; - public bool ContainsBlanks = false; - public double BlankValue = double.MinValue; - public double MaxVal = double.MinValue; - public double MinVal = double.MaxValue; - public double UpperCut = double.MinValue; - public double LowerCut = double.MaxValue; - public bool TransparentBlack = false; - public string ColorMapName = "viridis"; - public ScaleTypes ScaleType = ScaleTypes.Linear; - - // This field exists to support non-HiPS tiled FITS imagesets. We need a - // mechanism to notify callers when the top-level tile is loaded, - // because only after that has happened is it possible to set up - // trustworthy values for properties like LowerCut here. *HiPS* tiled - // FITS imagesets don't need this because they have a separate top-level - // "properties" file that can be used to trigger a callback. - // - // We need to load the top-level tile to properly set up the properties - // here because (1) they can't be determined well from the level-0 tile - // data alone, (2) we want to give the dataset author a chance to - // customize them, and (3) the tiled FITS data-loaders don't calculate - // min/max from the data for performance reasons. And we'd prefer not to - // add the relevant values to the ImageSet XML definition. - // - // Anyway, the tangent tile image loading code will cause this action to - // be triggered when the level-0 tile loads successfully. It would make - // sense to also trigger this action for when a non-tiled FITS file is - // loaded, but in that use case the existing WcsLoaded callback - // suffices. The tiling framework already uses WcsLoaded so for that - // case we need to add this extra hook. - public Action OnMainImageLoaded = null; - public bool MainImageLoadedEventHasFired = false; - - public FitsProperties() - { - } - - // See description of the OnMainImageLoaded field. This method exists to - // help non-HiPS tiled FITS datasets notify callers when the initial - // data have loaded and these FitsProperties can be trusted. - internal void FireMainImageLoaded(FitsImage image) - { - if (OnMainImageLoaded != null && !MainImageLoadedEventHasFired) { - MainImageLoadedEventHasFired = true; - OnMainImageLoaded(image); - } - } - } -} diff --git a/engine/csharp_ref/Folder.cs b/engine/csharp_ref/Folder.cs deleted file mode 100644 index 54b17c4d..00000000 --- a/engine/csharp_ref/Folder.cs +++ /dev/null @@ -1,751 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Net; - - -namespace wwtlib -{ - - public partial class Folder : IThumbnail - { - public override string ToString() - { - return nameField; - } - - public Folder Parent = null; - - public bool IsProxy = false; - - private bool versionDependent = false; - - public bool VersionDependent - { - get { return versionDependent; } - set - { - versionDependent = value; - foreach (Folder folder in folders) - { - folder.VersionDependent = versionDependent; - } - } - } - - bool readOnly = true; - - public bool ReadOnly - { - get { return readOnly; } - set { readOnly = value; } - } - - bool dirty = false; - - - public bool Dirty - { - get { return dirty; } - set { dirty = value; } - } - - WebFile webFile; - Action onComplete; - Action onError; - - public void LoadFromUrlWithErrorCallback(string url, Action complete, Action onError) - { - this.onError = onError; - this.LoadFromUrl(url, complete); - } - - public void LoadFromUrl(string url, Action complete) - { - onComplete = complete; - - webFile = new WebFile(URLHelpers.singleton.rewrite(url, URLRewriteMode.OriginRelative)); - webFile.OnStateChange = LoadData; - webFile.Send(); - - } - - private void LoadData() - { - if (webFile.State == StateType.Error) - { - Script.Literal("console.error({0})", webFile.Message); - if(onError != null) - { - onError(); - } - } - else if (webFile.State == StateType.Received) - { - XmlNode node = Util.SelectSingleNode(webFile.GetXml(), "Folder"); - - if (node == null) - { - XmlDocument doc = webFile.GetXml(); - if (doc != null) - { - node = Util.SelectSingleNode(doc, "Folder"); - } - } - - if (node != null) - { - ClearChildren(); - ParseXML(node); - } - if (onComplete != null) - { - onComplete(); - } - } - } - - private void ClearChildren() - { - folders.Clear(); - tours.Clear(); - places.Clear(); - Imagesets.Clear(); - } - - - //public static Folder LoadFromXML(XmlNode node) - //{ - // Folder temp = new Folder(); - - // temp.ParseXML(node); - - // return temp; - //} - - private void ParseXML(XmlNode node) - { - if (node.Attributes.GetNamedItem("Name") != null) - { - nameField = node.Attributes.GetNamedItem("Name").Value; - } - else - { - nameField = ""; - } - if (node.Attributes.GetNamedItem("Url") != null) - { - urlField = node.Attributes.GetNamedItem("Url").Value; - } - - if (node.Attributes.GetNamedItem("Thumbnail") != null) - { - thumbnailUrlField = node.Attributes.GetNamedItem("Thumbnail").Value; - } - - // load Children - - foreach (XmlNode child in node.ChildNodes) - { - switch (child.Name) - { - case "Folder": - Folder temp = new Folder(); - temp.Parent = this; - //if (Parent != null && IsProxy) - //{ - // temp.Parent = Parent.Parent; - //} - temp.ParseXML(child); - folders.Add(temp); - break; - case "Place": - places.Add(Place.FromXml(child)); - break; - case "ImageSet": - Imagesets.Add(Imageset.FromXMLNode(child)); - break; - case "Tour": - Tours.Add(Tour.FromXml(child)); - break; - } - } - - - //bool Browseable { get; set; } - //System.Collections.Generic.List Folders { get; set; } - //FolderGroup Group { get; set; } - //System.Collections.Generic.List Imagesets { get; set; } - //long MSRCommunityId { get; set; } - //long MSRComponentId { get; set; } - //string Name { get; set; } - //long Permission { get; set; } - //System.Collections.Generic.List Places { get; set; } - //bool ReadOnly { get; set; } - //string RefreshInterval { get; set; } - //FolderRefreshType RefreshType { get; set; } - //bool RefreshTypeSpecified { get; set; } - //bool Searchable { get; set; } - //string SubType { get; set; } - //string ThumbnailUrl { get; set; } - //System.Collections.Generic.List Tours { get; set; } - //FolderType Type { get; set; } - //string Url { get; set; } - } - - public void AddChildFolder(Folder child) - { - folders.Add(child); - dirty = true; - } - - public void RemoveChildFolder(Folder child) - { - folders.Remove(child); - dirty = true; - } - - public void AddChildPlace(Place child) - { - places.Add(child); - dirty = true; - } - - public void RemoveChildPlace(Place child) - { - places.Remove(child); - dirty = true; - } - - ImageElement thumbnail = null; - - public ImageElement Thumbnail - { - get - { - - return thumbnail; - } - set - { - - thumbnail = value; - } - } - - Rectangle bounds; - - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - - - public bool IsImage - { - get { return false; } - } - - - public bool IsTour - { - get { return false; } - } - - - public bool IsFolder - { - get { return true; } - } - - - public bool IsCloudCommunityItem - { - get - { - return communityIdField != 0 || this.permissionField > 0; - } - } - private Folder proxyFolder = null; - - public void Refresh() - { - if (proxyFolder == null) - { - proxyFolder = new Folder(); - proxyFolder.IsProxy = true; - proxyFolder.Parent = Parent; - } - - //Also listening to errors, to make sure clients do not wait forever in the case of a 404 or similar. - //Especially useful for recursive downloads, where potentially dozens of URL's are downloaded. - //In case of errors during downloads, the clients will have an empty folder during the callback. - proxyFolder.LoadFromUrlWithErrorCallback(urlField, childReadyCallback, childReadyCallback); - childReadyCallback = null; - } - - private Date lastUpdate = new Date(); - - Action childReadyCallback; - - public void ChildLoadCallback(Action callback) - { - childReadyCallback = callback; - - List temp = Children; - - if (proxyFolder == null) - { - callback(); - } - - - } - List childList = new List(); - public List Children - { - get - { - if (String.IsNullOrEmpty(urlField)) - { - childList.Clear(); - - if (Parent != null) - { - FolderUp folderUp = new FolderUp(); - //if (this.IsProxy) - //{ - // folderUp.Parent = Parent.Parent; - //} - //else - { - folderUp.Parent = Parent; - } - childList.Add(folderUp); - } - - if (Folders != null) - { - foreach (Folder folder in Folders) - { - childList.Add(folder); - } - } - if (Imagesets != null) - { - foreach (Imageset imset in Imagesets) - { - childList.Add(imset); - } - } - if (Places != null) - { - foreach (Place place in Places) - { - childList.Add(place); - } - } - if (Tours != null) - { - foreach (Tour tour in Tours) - { - childList.Add(tour); - } - } - - - return childList; - } - else - { - int ts = (lastUpdate - Date.Now)/1000; - // TOdo add add Move Complete Auto Update - // todo add URL formating for Ambient Parameters - // TODO remove true when perth fixes refresh type on server - if (RefreshType == FolderRefreshType.ConditionalGet || proxyFolder == null || - (this.RefreshType == FolderRefreshType.Interval && (int.Parse(refreshIntervalField) < ts))) - { - Refresh(); - } - - if (proxyFolder != null) - { - return proxyFolder.Children; - } - else - { - return null; - } - - } - } - } - - - - private List itemsField = new List(); - private List imagesets = new List(); - private List tours = new List(); - private List folders = new List(); - private List places = new List(); - - - private string nameField; - - private FolderGroup groupField; - - private string urlField; - - private string thumbnailUrlField; - - private FolderRefreshType refreshTypeField; - - private bool refreshTypeFieldSpecified; - - private string refreshIntervalField; - - private bool browseableField = true; - - private bool browseableFieldSpecified; - - private bool searchableField = false; - - private FolderType typeField; - - private string subTypeField; - - - /// - /// - - long communityIdField = 0; - - public long MSRCommunityId - { - get { return communityIdField; } - set { communityIdField = value; } - } - - long componentIdField = 0; - - public long MSRComponentId - { - get { return componentIdField; } - set { componentIdField = value; } - } - - long permissionField = 0; - - public long Permission - { - get { return permissionField; } - set { permissionField = value; } - } - - - public List Folders - { - get - { - return folders; - } - set - { - folders = value; - } - } - - - public List Places - { - get - { - return places; - } - set - { - places = value; - } - } - - - public List Imagesets - { - get - { - return imagesets; - } - set - { - imagesets = value; - } - } - - - - public List Tours - { - get - { - return this.tours; - } - set - { - this.tours = value; - } - } - - /// - - public string Name - { - get - { - if (this.nameField == null) - { - return ""; - } - else - { - return this.nameField; - } - } - set - { - this.nameField = value; - } - } - - /// - - public FolderGroup Group - { - get - { - return this.groupField; - } - set - { - this.groupField = value; - } - } - - public string Url - { - get - { - return this.urlField; - } - set - { - this.urlField = value; - } - } - - public string ThumbnailUrl - { - get - { - if (string.IsNullOrEmpty(thumbnailUrlField)) - { - return URLHelpers.singleton.engineAssetUrl("thumb_folder.jpg"); - } - - return this.thumbnailUrlField; - } - set - { - this.thumbnailUrlField = value; - } - } - - /// - - public FolderRefreshType RefreshType - { - get - { - return this.refreshTypeField; - } - set - { - this.refreshTypeField = value; - RefreshTypeSpecified = true; - } - } - - - public bool RefreshTypeSpecified - { - get - { - return this.refreshTypeFieldSpecified; - } - set - { - this.refreshTypeFieldSpecified = value; - } - } - - - public string RefreshInterval - { - get - { - return this.refreshIntervalField; - } - set - { - this.refreshIntervalField = value; - } - } - - /// - - public bool Browseable - { - get - { - return this.browseableField; - } - set - { - this.browseableField = value; - browseableFieldSpecified = true; - } - } - - - public bool BrowseableSpecified - { - get - { - return this.browseableFieldSpecified; - } - set - { - this.browseableFieldSpecified = value; - } - } - - /// - - public bool Searchable - { - get - { - return this.searchableField; - } - set - { - this.searchableField = value; - } - } - - /// - - public FolderType Type - { - get - { - return this.typeField; - } - set - { - this.typeField = value; - } - } - - /// - - public string SubType - { - get - { - return this.subTypeField; - } - set - { - this.subTypeField = value; - } - } - } - - - - public enum FolderGroup - { - - /// - Explorer = 0, - - /// - Tour = 1, - - /// - Search = 2, - - /// - Constellation = 3, - - /// - View = 4, - - /// - GoTo = 5, - - /// - Community = 6, - - /// - Context = 7, - - /// - VoTable = 8, - - /// - ImageStack = 9 - } - - - public enum FolderRefreshType - { - - /// - Interval = 0, - - /// - ConditionalGet = 1, - - /// - ViewChange = 2, - } - - - - public enum FolderType - { - - /// - Earth = 0, - - /// - Planet = 1, - - /// - Sky = 2, - - /// - Panorama = 3, - } -} diff --git a/engine/csharp_ref/FolderBrowser.cs b/engine/csharp_ref/FolderBrowser.cs deleted file mode 100644 index 521dfd23..00000000 --- a/engine/csharp_ref/FolderBrowser.cs +++ /dev/null @@ -1,681 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class FolderBrowser - { - public FolderBrowser() - { - } - - public CanvasElement Canvas; - List items = new List(); - - public static FolderBrowser Create() - { - FolderBrowser temp = new FolderBrowser(); - - temp.Height = 85; - temp.Width = 1920; - temp.Canvas = (CanvasElement)Document.CreateElement("canvas"); - temp.Canvas.Width = temp.Width; - temp.Canvas.Height = temp.Height; - //temp.Canvas.Style.MarginBottom = "0"; - temp.Setup(); - temp.LoadImages(); - - return temp; - } - - public int Top = 10; - public int Left = 10; - - public void Setup() - { - Canvas.AddEventListener("click", OnClick, false); - Canvas.AddEventListener("dblclick", OnDoubleClick, false); - Canvas.AddEventListener("mousemove", OnMouseMove, false); - Canvas.AddEventListener("mouseup", OnMouseUp, false); - Canvas.AddEventListener("mousedown", OnMouseDown, false); - Canvas.AddEventListener("touchstart", OnTouchStart, false); - Canvas.AddEventListener("touchmove", OnTouchMove, false); - Canvas.AddEventListener("touchend", OnTouchEnd, false); - Canvas.AddEventListener("mouseout", OnMouseUp, false); - } - - int indexTouchDown = -1; - public void OnTouchStart(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - mouseDown = true; - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - - indexTouchDown = GetItemIndexFromCursor(Vector2d.Create(ev.TargetTouches[0].PageX, ev.TargetTouches[0].PageY)); - - } - - public void OnTouchMove(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - if (mouseDown) - { - double curX = ev.TargetTouches[0].PageX - lastX; - - double curY = ev.TargetTouches[0].PageY - lastY; - if (mouseDown) - { - dragging = true; - } - - if (!dragging) - { - int newHover = GetItemIndexFromCursor(Vector2d.Create(ev.TargetTouches[0].PageX, ev.TargetTouches[0].PageY)); - if (hoverItem != newHover) - { - hoverItem = newHover; - //if (ItemHover != null) - //{ - // if (hoverItem > -1) - // { - // ItemHover.Invoke(this, items[hoverItem]); - // } - // else - // { - // ItemHover.Invoke(this, null); - // } - //} - } - } - else - { - int tiles = (int)Math.Round(((ev.TargetTouches[0].PageX - lastX) + startOffset) / HorzSpacing); - int offset = (int)Math.Round(((ev.TargetTouches[0].PageX - lastX) + startOffset) - (tiles * HorzSpacing)); - - startOffset = offset; - startIndex -= tiles; - if (startIndex < 0) - { - startOffset -= (HorzSpacing * startIndex); - startIndex = 0; - } - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - } - Refresh(); - - - } - } - - public void OnTouchEnd(ElementEvent e) - { - - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - if (dragging) - { - dragging = false; - ignoreClick = true; - } - else if (indexTouchDown > -1 && mouseDown) - { - HandleClick(indexTouchDown); - } - startOffset = 0; - mouseDown = false; - Refresh(); - } - - - public void OnClick(ElementEvent e) - { - if (!ignoreClick) - { - int index = GetItemIndexFromCursor(Vector2d.Create(e.OffsetX, e.OffsetY)); - HandleClick(index); - - } - else - { - ignoreClick = false; - } - } - - private void HandleClick(int index) - { - if (index > -1) - { - if (items[index] is Place) - { - //Place place = (Place)items[index]; - //if (place.BackgroundImageSet != null) - //{ - // WWTControl.Singleton.RenderContext.BackgroundImageset = place.BackgroundImageSet; - //} - - //if (place.StudyImageset != null) - //{ - // // WWTControl.Singleton.RenderContext.ForegroundImageSet = place.StudyImageset; - // WWTControl.Singleton.RenderContext.ForegroundImageset = place.StudyImageset; - - - //} - //if (!(place.Lat == 0 && place.Lng == 0)) - //{ - // WWTControl.Singleton.RenderContext.ViewCamera = place.CamParams; - //} - Place place = (Place)items[index]; - - WWTControl.Singleton.GotoTarget(place, false, false, true); - - - - return; - } - - if (items[index] is Imageset) - { - Imageset imageset = (Imageset)items[index]; - - WWTControl.Singleton.RenderContext.BackgroundImageset = imageset; - return; - - - } - - if (items[index] is Tour) - { - Tour tour = (Tour)items[index]; - - WWTControl.Singleton.PlayTour(tour.TourUrl); - return; - - - } - - - if (items[index] is Folder) - { - Folder folder = (Folder)items[index]; - startIndex = 0; - folder.ChildLoadCallback(delegate { items = folder.Children; Refresh(); }); - return; - } - - if (items[index] is FolderUp) - { - FolderUp folderUp = (FolderUp)items[index]; - if (folderUp.Parent != null) - { - startIndex = 0; - folderUp.Parent.ChildLoadCallback(delegate { items = folderUp.Parent.Children; Refresh(); }); - } - return; - } - } - return; - } - - public void OnDoubleClick(ElementEvent e) - { - RenderTriangle.RenderingOn = !RenderTriangle.RenderingOn; - } - - public void OnGestureChange(ElementEvent e) - { - GestureEvent g = (GestureEvent)e; - mouseDown = false; - double delta = g.Scale; - - // if (delta > 1 && Math.Abs(delta - 1) > .05) - - } - - - - - bool mouseDown = false; - double lastX; - double lastY; - public void OnMouseDown(ElementEvent e) - { - mouseDown = true; - lastX = Mouse.OffsetX(Canvas, e); - lastY = Mouse.OffsetY(Canvas, e); - } - - public void OnMouseMove(ElementEvent e) - { - - if (mouseDown) - { - dragging = true; - } - - if (!dragging) - { - int newHover = GetItemIndexFromCursor(Vector2d.Create(Mouse.OffsetX(Canvas, e), Mouse.OffsetY(Canvas, e))); - if (hoverItem != newHover) - { - hoverItem = newHover; - //if (ItemHover != null) - //{ - // if (hoverItem > -1) - // { - // ItemHover.Invoke(this, items[hoverItem]); - // } - // else - // { - // ItemHover.Invoke(this, null); - // } - //} - } - } - else - { - int tiles = (int)Math.Round(((Mouse.OffsetX(Canvas, e) - lastX) + startOffset) / HorzSpacing); - int offset = (int)Math.Round(((Mouse.OffsetX(Canvas, e) - lastX) + startOffset) - (tiles * HorzSpacing)); - - startOffset = offset; - startIndex -= tiles; - if (startIndex < 0) - { - startOffset -= (HorzSpacing * startIndex); - startIndex = 0; - } - lastX = Mouse.OffsetX(Canvas, e); - lastY = Mouse.OffsetY(Canvas, e); - } - Refresh(); - - } - - bool ignoreClick = false; - public void OnMouseUp(ElementEvent e) - { - if (dragging) - { - //startIndex = (int)Math.Round(Math.Max(0, (int)startIndex - startOffset / horzMultiple)); - startOffset = 0; - dragging = false; - ignoreClick = true; - } - - - mouseDown = false; - Refresh(); - - } - - public void LoadImages() - { - if (!ImagesLoaded && !downloading) - { - ImageLoadCount = 0; - ImagesLoaded = false; - downloading = true; - bmpBackground = (ImageElement)Document.CreateElement("img"); - bmpBackground.Src = "images/thumbBackground.png"; - bmpBackground.AddEventListener("load", delegate(ElementEvent e) - { - ImageLoadCount++; - if (ImageLoadCount == 5) - { - downloading = false; - ImagesLoaded = true; - Refresh(); - } - }, false); - - bmpBackgroundHover = (ImageElement)Document.CreateElement("img"); - bmpBackgroundHover.Src = "images/thumbBackgroundHover.png"; - bmpBackgroundHover.AddEventListener("load", delegate(ElementEvent e) - { - ImageLoadCount++; - if (ImageLoadCount == 5) - { - downloading = false; - ImagesLoaded = true; - Refresh(); - } - }, false); - bmpBackgroundWide = (ImageElement)Document.CreateElement("img"); - bmpBackgroundWide.Src = "images/thumbBackgroundWide.png"; - bmpBackgroundWide.AddEventListener("load", delegate(ElementEvent e) - { - ImageLoadCount++; - if (ImageLoadCount == 5) - { - downloading = false; - ImagesLoaded = true; - Refresh(); - } - }, false); - bmpBackgroundWideHover = (ImageElement)Document.CreateElement("img"); - bmpBackgroundWideHover.Src = "images/thumbBackgroundWideHover.png"; - bmpBackgroundWideHover.AddEventListener("load", delegate(ElementEvent e) - { - ImageLoadCount++; - if (ImageLoadCount == 5) - { - downloading = false; - ImagesLoaded = true; - Refresh(); - } - }, false); - bmpDropInsertMarker = (ImageElement)Document.CreateElement("img"); - bmpDropInsertMarker.Src = "images/dragInsertMarker.png"; - bmpDropInsertMarker.AddEventListener("load", delegate(ElementEvent e) - { - ImageLoadCount++; - if (ImageLoadCount == 5) - { - downloading = false; - ImagesLoaded = true; - Refresh(); - } - }, false); - } - } - static bool downloading = false; - static bool ImagesLoaded = false; - static int ImageLoadCount = 0; - static ImageElement bmpBackground; - static ImageElement bmpBackgroundHover; - static ImageElement bmpBackgroundWide; - static ImageElement bmpBackgroundWideHover; - static ImageElement bmpDropInsertMarker; - - ThumbnailSize thumbnailSize = ThumbnailSize.Small; - - public ThumbnailSize ThumbnailSize - { - get { return thumbnailSize; } - set - { - thumbnailSize = value; - switch (value) - { - case ThumbnailSize.Big: - HorzSpacing = 180; - VertSpacing = 75; - ThumbHeight = 65; - ThumbWidth = 180; - break; - case ThumbnailSize.Small: - HorzSpacing = 110; - VertSpacing = 75; - ThumbHeight = 65; - ThumbWidth = 110; - break; - } - UpdatePaginator(); - Refresh(); - } - } - - public void Refresh() - { - if (Width != Window.InnerWidth) - { - Width = Window.InnerWidth; - Canvas.Width = Canvas.Width; - } - Paint(); - } - - int HorzSpacing = 110; - int VertSpacing = 75; - int ThumbHeight = 65; - int ThumbWidth = 110; - float horzMultiple = 110; - int rowCount = 1; - - public int RowCount - { - get { return rowCount; } - set - { - if (rowCount != value) - { - rowCount = value; - UpdatePaginator(); - } - } - } - - private void UpdatePaginator() - { - - } - int colCount = 6; - - public int ColCount - { - get { return colCount; } - set - { - if (colCount != value) - { - colCount = value; - UpdatePaginator(); - } - } - } - bool dragging = false; - int startIndex = 0; - int startOffset = 0; - int selectedItem = -1; - int hoverItem = -1; - - public int ItemsPerPage - { - get - { - return rowCount * colCount; - } - } - - - - public int CurrentPage - { - get - { - return startIndex / ItemsPerPage; - } - } - - public bool showAddButton = false; - - public int PageCount - { - get - { - return Math.Max(1, ((items.Count + ItemsPerPage - 1) + (showAddButton ? 1 : 0)) / ItemsPerPage); - } - } - public int Width; - public int Height; - - const int buffer = 10; - - public void Paint() - { - - CanvasContext2D g = (CanvasContext2D)Canvas.GetContext(Rendering.Render2D); - g.FillStyle = "rgb(20, 22, 31)"; - g.FillRect(0, 0, Width, Height); - if (!ImagesLoaded) - { - return; - } - int netHeight = (Height - buffer * 2); - int netWidth = (Width - buffer * 2); - RowCount = Math.Round(Math.Max(netHeight / ThumbHeight, 1)); - ColCount = Math.Round(Math.Max(netWidth / HorzSpacing, 1)); - - horzMultiple = ((float)netWidth + 13) / (float)ColCount; - - startIndex = Math.Round((startIndex / ItemsPerPage) * ItemsPerPage); - - Rectangle rectf; - int index = startIndex; - for (int y = 0; y < rowCount; y++) - { - for (int x = 0; x < colCount; x++) - { - if (index >= items.Count) - { - - if (items.Count == 0 || showAddButton) - { - rectf = Rectangle.Create(Left + x * horzMultiple + 3f + startOffset, Top + y * VertSpacing, ThumbWidth - 10, 60); - g.DrawImage(thumbnailSize == ThumbnailSize.Big ? bmpBackgroundWide : bmpBackground, (int)((float)x * horzMultiple) + startOffset, y * VertSpacing); - - - //g.FillText(emptyText, rectf.X,rectf,Y, rectf.Width); - //g.DrawString(showAddButton ? addText : emptyText, UiTools.StandardRegular, (addButtonHover && showAddButton) ? UiTools.YellowTextBrush : UiTools.StadardTextBrush, rectf, UiTools.StringFormatCenterCenter); - - } - break; - } - - - - - rectf = Rectangle.Create(Left + x * horzMultiple + 3 + startOffset, Top + y * VertSpacing, ThumbWidth - 14, 60); - //Brush textBrush = UiTools.StadardTextBrush; - string textBrush = "white"; - - if (index == hoverItem || (index == selectedItem && hoverItem == -1)) - { - g.DrawImage(thumbnailSize == ThumbnailSize.Big ? bmpBackgroundWideHover : bmpBackgroundHover, Left + (int)((float)x * horzMultiple) + startOffset, Top + y * VertSpacing); - textBrush = "yellow"; - } - else - { - g.DrawImage(thumbnailSize == ThumbnailSize.Big ? bmpBackgroundWide : bmpBackground, Left + (int)((float)x * horzMultiple) + startOffset, Top + y * VertSpacing); - } - - (items[index]).Bounds = Rectangle.Create((int)(Left + x * horzMultiple) + startOffset, Top + (int)(y * VertSpacing), (int)horzMultiple, (int)VertSpacing); - try - { - ImageElement bmpThumb = items[index].Thumbnail; - if (bmpThumb != null) - { - - g.DrawImage(bmpThumb, Left + (int)(x * horzMultiple) + 2 + startOffset, Top + y * VertSpacing + 3); - - g.StrokeStyle = "rgb(0,0,0)"; - g.Rect(Left + (int)((float)x * horzMultiple) + 2 + startOffset, Top + y * VertSpacing + 3, items[index].Thumbnail.Width, items[index].Thumbnail.Height); - } - else - { - items[index].Thumbnail = (ImageElement)Document.CreateElement("img"); - items[index].Thumbnail.Src = items[index].ThumbnailUrl; - items[index].Thumbnail.AddEventListener("load", delegate(ElementEvent e) { Refresh(); }, false); - } - - } - // TODO FIX this! - catch - { - } - - //if (((IThumbnail)items[index]).IsImage) - //{ - // g.DrawImage(Properties.Resources.InsertPictureHS, (int)((float)x * horzMultiple) + 79, y * VertSpacing + 1); - //} - //if (((IThumbnail)items[index]).IsTour) - //{ - // g.DrawImage(Properties.Resources.TourIcon, (int)((float)x * horzMultiple) + 79, y * VertSpacing + 1); - //} - //g.DrawString(((IThumbnail), UiTools.StandardRegular, textBrush, rectf, UiTools.StringFormatThumbnails); - g.FillStyle = textBrush; - g.StrokeStyle = textBrush; - g.LineWidth = 1; - g.Font = "normal 8pt Arial"; - g.FillText(items[index].Name, rectf.X, rectf.Y + rectf.Height, rectf.Width); - //g.FillText(items[index].Name, 10, 10); - index++; - } - if (index >= items.Count) - { - break; - } - } - } - - bool addButtonHover = false; - public bool imageClicked = false; - private int GetItemIndexFromCursor(Vector2d testPointIn) - { - Vector2d testPoint = Vector2d.Create(testPointIn.X + Left, testPointIn.Y + Top); - - imageClicked = false; - int index = -1; - int xpos = (int)((float)testPoint.X / horzMultiple); - int xPart = (int)((float)testPoint.X % horzMultiple); - if (xpos >= colCount) - { - return -1; - } - if (xpos < 0) - { - return -1; - } - - int ypos = (int)(testPoint.Y / VertSpacing); - int yPart = (int)(testPoint.Y % VertSpacing); - if (ypos >= rowCount) - { - return -1; - } - - if (ypos < 0) - { - return -1; - } - - index = startIndex + ypos * colCount + xpos; - - if (index == items.Count) - { - addButtonHover = true; - } - else - { - addButtonHover = false; - } - - if (index > items.Count-1) - { - return -1; - } - - if (((IThumbnail)items[index]).IsImage && yPart < 16 && xPart > 78) - { - imageClicked = true; - } - - return index; - } - - internal void AddItems(List list) - { - items = list; - } - - - } - public enum ThumbnailSize { Small=0, Big=1 }; - -} diff --git a/engine/csharp_ref/FolderUp.cs b/engine/csharp_ref/FolderUp.cs deleted file mode 100644 index 5ae85076..00000000 --- a/engine/csharp_ref/FolderUp.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - - -namespace wwtlib -{ - public class FolderUp : IThumbnail - { - public FolderUp() - { - } - - #region IThumbnail Members - - public string Name - { - get { return "Up Level"; } - } - - - public Folder Parent = null; - - ImageElement thumbnail; - public System.Html.ImageElement Thumbnail - { - get - { - return thumbnail; - } - set - { - thumbnail = value; - } - } - - public string ThumbnailUrl - { - get - { - return URLHelpers.singleton.engineAssetUrl("thumb_folderup.jpg"); - } - - set {} - } - Rectangle bounds = new Rectangle(); - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - public bool IsImage - { - get { return false; } - } - - public bool IsTour - { - get { return false; } - } - - public bool IsFolder - { - get { return false; } - } - - public bool IsCloudCommunityItem - { - get { return false; } - } - - public bool ReadOnly - { - get { return false; } - } - - public List Children - { - get - { - if (Parent == null) - { - return new List(); - } - else - { - return Parent.Children; - } - } - } - #endregion - } -} diff --git a/engine/csharp_ref/Fxyf.cs b/engine/csharp_ref/Fxyf.cs deleted file mode 100644 index be1d3c88..00000000 --- a/engine/csharp_ref/Fxyf.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; - -namespace wwtlib -{ - - public class Fxyf : HealpixTables - { - - /** x-coordinate within the basis pixel, range [0.0;1.0] */ - public double fx; - /** y-coordinate within the basis pixel, range [0.0;1.0] */ - public double fy; - /** index of the HEALPix basis pixel, range [0;11] */ - public int face; - public Fxyf() - { - - } - public static Fxyf Create(double x, double y, int f) - { - Fxyf temp = new Fxyf(); - temp.fx = x; - temp.fy = y; - temp.face = f; - return temp; - } - - private static readonly double halfpi = Math.PI / 2d; - - private static readonly double inv_halfpi = 2d / Math.PI; - - private static readonly double twothird = 2d / 3d; - - private static Fxyf FromHploc(Hploc loc) - { - Fxyf temp = new Fxyf(); - double z = loc.z, phi = loc.phi; - - double za = Math.Abs(z); - double tt = HealpixUtils.fmodulo((phi * Fxyf.inv_halfpi), 4.0);// in [0,4) - - if (za <= Fxyf.twothird) // Equatorial region - { - double temp1 = 0.5 + tt; - double temp2 = z * 0.75; - double jp = temp1 - temp2; // index of ascending edge line - double jm = temp1 + temp2; // index of descending edge line - long ifp = (long)jp; // in {0,4} - long ifm = (long)jm; - long face_num = (ifp == ifm) ? (ifp | 4) : ((ifp < ifm) ? ifp : (ifm + 8)); - temp.fx = HealpixUtils.fmodulo(jm, 1d); - temp.fy = 1d - HealpixUtils.fmodulo(jp, 1d); - temp.face = (int)face_num; - } - else // polar region, za > 2/3 - { - int ntt = Math.Min(3, (int)tt); - double tp = tt - ntt; - double tmp; - if ((za < 0.99) || (!loc.have_sth)) - { - tmp = Math.Sqrt(3 * (1 - za)); - } else - { - tmp = loc.sth / Math.Sqrt((1d + za) / 3d); - } - - double jp = tp * tmp; // increasing edge line index - double jm = (1.0 - tp) * tmp; // decreasing edge line index - if (jp >= 1d) jp = 1d; // for points too close to the boundary - if (jm >= 1d) jm = 1d; - if (z >= 0) - { temp.fx = 1d - jm; temp.fy = 1d - jp; temp.face = ntt; } - else - { temp.fx = jp; temp.fy = jm; temp.face = ntt + 8; } - } - return temp; - } - - public static Fxyf FromVector(Vector3d v) - { - return Fxyf.FromHploc(Hploc.Create(v)); - } - - protected Hploc toHploc() - { - Hploc loc = new Hploc(); - double jr = jrll[face] - fx - fy; - - double nr; double tmp; - if (jr < 1) - { - nr = jr; - tmp = nr * nr / 3d; - loc.z = 1 - tmp; - if (loc.z > 0.99) { loc.sth = Math.Sqrt(tmp * (2d - tmp)); loc.have_sth = true; } - } - else if (jr > 3) - { - nr = 4 - jr; - tmp = nr * nr / 3d; - loc.z = tmp - 1; - if (loc.z < -0.99) { loc.sth = Math.Sqrt(tmp * (2d - tmp)); loc.have_sth = true; } - } - else - { - nr = 1; - loc.z = (2 - jr) * 2d / 3d; - } - - tmp = jpll[face] * nr + fx - fy; - if (tmp < 0) tmp += 8; - if (tmp >= 8) tmp -= 8; - loc.phi = (nr < 1e-15) ? 0 : (0.5 * Fxyf.halfpi * tmp) / nr; - return loc; - } - public Vector3d toVec3() - { return toHploc().toVec3(); } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/Graphics/GlBuffers.cs b/engine/csharp_ref/Graphics/GlBuffers.cs deleted file mode 100644 index d709a3d9..00000000 --- a/engine/csharp_ref/Graphics/GlBuffers.cs +++ /dev/null @@ -1,463 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - - -namespace wwtlib -{ - public class ShortIndexBuffer - { - public WebGLBuffer Buffer; - - public ShortIndexBuffer(Uint16Array indexes) - { - Buffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, Buffer); - Tile.PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, indexes, GL.STATIC_DRAW); - } - } - - public class IndexBuffer : IDisposable - { - public WebGLBuffer Buffer; - - public IndexBuffer(Uint32Array indexes) - { - Buffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, Buffer); - Tile.PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, indexes, GL.STATIC_DRAW); - } - - public void Dispose() - { - Tile.PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - Tile.PrepDevice.deleteBuffer(Buffer); - Buffer = null; - } - - } - - public class VertexBufferBase : IDisposable - { - public WebGLBuffer VertexBuffer; - - public void Dispose() - { - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, null); - Tile.PrepDevice.deleteBuffer(VertexBuffer); - VertexBuffer = null; - } - } - - - - public class PositionVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionVertexBuffer(int count) - { - Count = count; - } - - Vector3d[] verts = null; - - public Vector3d[] Lock() - { - verts = new Vector3d[Count]; - return verts; - } - - - public void Unlock() - { - - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 3); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (Vector3d pt in verts) - { - buffer[index++] = (float)pt.X; - buffer[index++] = (float)pt.Y; - buffer[index++] = (float)pt.Z; - - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - class PositionTextureVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionTextureVertexBuffer(int count) - { - Count = count; - } - - public static PositionTextureVertexBuffer Create(PositionTexture[] data) - { - PositionTextureVertexBuffer buffer = new PositionTextureVertexBuffer(data.Length); - buffer.verts = data; - buffer.Unlock(); - return buffer; - } - - PositionTexture[] verts = null; - - public PositionTexture[] Lock() - { - verts = new PositionTexture[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 5); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionTexture pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - public class PositionNormalTexturedVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionNormalTexturedVertexBuffer(int count) - { - Count = count; - } - - public static PositionNormalTexturedVertexBuffer Create(PositionNormalTextured[] data) - { - PositionNormalTexturedVertexBuffer buffer = new PositionNormalTexturedVertexBuffer(data.Length); - buffer.verts = data; - buffer.Unlock(); - return buffer; - } - - PositionNormalTextured[] verts = null; - - public PositionNormalTextured[] Lock() - { - verts = new PositionNormalTextured[Count]; - return verts; - } - - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 8); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionNormalTextured pt in verts) - { - buffer[index++] = (float)pt.X; - buffer[index++] = (float)pt.Y; - buffer[index++] = (float)pt.Z; - buffer[index++] = (float)pt.Nx; - buffer[index++] = (float)pt.Ny; - buffer[index++] = (float)pt.Nz; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - public class PositionNormalTexturedTangentVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionNormalTexturedTangentVertexBuffer(int count) - { - Count = count; - } - - public static PositionNormalTexturedTangentVertexBuffer Create(PositionNormalTexturedTangent[] data) - { - PositionNormalTexturedTangentVertexBuffer buffer = new PositionNormalTexturedTangentVertexBuffer(data.Length); - buffer.verts = data; - buffer.Unlock(); - return buffer; - } - - PositionNormalTexturedTangent[] verts = null; - - public PositionNormalTexturedTangent[] Lock() - { - verts = new PositionNormalTexturedTangent[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 11); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionNormalTexturedTangent pt in verts) - { - buffer[index++] = (float)pt.X; - buffer[index++] = (float)pt.Y; - buffer[index++] = (float)pt.Z; - buffer[index++] = (float)pt.Nx; - buffer[index++] = (float)pt.Ny; - buffer[index++] = (float)pt.Nz; - buffer[index++] = (float)pt.Tanx; - buffer[index++] = (float)pt.Tany; - buffer[index++] = (float)pt.Tanz; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - class KeplerVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public KeplerVertexBuffer(int count) - { - Count = count; - } - - KeplerVertex[] verts = null; - - public KeplerVertex[] Lock() - { - verts = new KeplerVertex[Count]; - return verts; - } - - public static KeplerVertexBuffer Create(List items) - { - KeplerVertexBuffer tmp = new KeplerVertexBuffer(items.Count); - tmp.verts = (KeplerVertex[])(object)items; - return tmp; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 19); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (KeplerVertex pt in verts) - { - buffer[index++] = (float)pt.ABC.X; - buffer[index++] = (float)pt.ABC.Y; - buffer[index++] = (float)pt.ABC.Z; - buffer[index++] = (float)pt.abc1.X; - buffer[index++] = (float)pt.abc1.Y; - buffer[index++] = (float)pt.abc1.Z; - buffer[index++] = (float)pt.PointSize; - buffer[index++] = (float)pt.Color.R/255; - buffer[index++] = (float)pt.Color.G/255; - buffer[index++] = (float)pt.Color.B/255; - buffer[index++] = (float)pt.Color.A/255; - buffer[index++] = (float)pt.w; - buffer[index++] = (float)pt.e; - buffer[index++] = (float)pt.n; - buffer[index++] = (float)pt.T; - buffer[index++] = (float)pt.a; - buffer[index++] = (float)pt.z; - buffer[index++] = (float)pt.orbitPos; - buffer[index++] = (float)pt.orbits; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - class TimeSeriesLineVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public TimeSeriesLineVertexBuffer(int count) - { - Count = count; - } - - TimeSeriesLineVertex[] verts = null; - - public TimeSeriesLineVertex[] Lock() - { - verts = new TimeSeriesLineVertex[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 9); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (TimeSeriesLineVertex pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - class TimeSeriesPointVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public TimeSeriesPointVertexBuffer(int count) - { - Count = count; - } - - TimeSeriesPointVertex[] verts = null; - - public TimeSeriesPointVertex[] Lock() - { - verts = new TimeSeriesPointVertex[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 10); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (TimeSeriesPointVertex pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - buffer[index++] = (float)pt.PointSize; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - - public void Dispose() // compiler wants "new" keyword here, but ScriptSharp doesn't support it - { - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, null); - Tile.PrepDevice.deleteBuffer(VertexBuffer); - VertexBuffer = null; - } - } - - class PositionColoredVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionColoredVertexBuffer(int count) - { - Count = count; - } - - PositionColored[] verts = null; - - public PositionColored[] Lock() - { - verts = new PositionColored[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 7); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionColored pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } - - class PositionColoredTexturedVertexBuffer : VertexBufferBase - { - public int Count = 0; - - public PositionColoredTexturedVertexBuffer(int count) - { - Count = count; - } - - PositionColoredTextured[] verts = null; - - public PositionColoredTextured[] Lock() - { - verts = new PositionColoredTextured[Count]; - return verts; - } - - public void Unlock() - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(Count * 9); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionColoredTextured pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - } - } -} diff --git a/engine/csharp_ref/Graphics/Primatives3d.cs b/engine/csharp_ref/Graphics/Primatives3d.cs deleted file mode 100644 index caaef2bd..00000000 --- a/engine/csharp_ref/Graphics/Primatives3d.cs +++ /dev/null @@ -1,1185 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - - -namespace wwtlib -{ - - public class Dates - { - - public Dates(double start, double end) - { - StartDate = start; - EndDate = end; - } - public double StartDate; - public double EndDate; - - public Dates Copy() - { - return new Dates(this.StartDate, this.EndDate); - } - public static Dates Empty() - { - return new Dates(0, 0); - } - } - - - public class SimpleLineList - { - public SimpleLineList() - { - } - - - bool zBuffer = true; - - public bool DepthBuffered - { - get { return zBuffer; } - set { zBuffer = value; } - } - - List linePoints = new List(); - - public void AddLine(Vector3d v1, Vector3d v2) - { - - linePoints.Add(v1); - linePoints.Add(v2); - EmptyLineBuffer(); - - } - - public void Clear() - { - linePoints.Clear(); - EmptyLineBuffer(); - } - - bool usingLocalCenter = false; - Vector3d localCenter; - public bool Sky = true; - public bool aaFix = true; - public bool Pure2D = false; - public Matrix3d ViewTransform = Matrix3d.Identity; - - public void DrawLines(RenderContext renderContext, float opacity, Color color) - { - if (linePoints.Count < 2) - { - return; - } - - InitLineBuffer(renderContext); - - int count = linePoints.Count; - - if (renderContext.gl == null) - { - Vector3d viewPoint = Vector3d.TransformCoordinate(renderContext.ViewPoint, ViewTransform); - - - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - - ctx.StrokeStyle = color.ToString(); - ctx.LineWidth = 2; - ctx.Alpha = .25; - Vector3d firstPoint = new Vector3d(); - Vector3d secondPoint = new Vector3d(); - for (int i = 0; i < count; i += 2) - { - firstPoint = renderContext.WVP.Transform(linePoints[i]); - secondPoint = renderContext.WVP.Transform(linePoints[i + 1]); - if (Vector3d.Dot(linePoints[i], viewPoint) > .60) - { - ctx.BeginPath(); - ctx.MoveTo(firstPoint.X, firstPoint.Y); - ctx.LineTo(secondPoint.X, secondPoint.Y); - - - ctx.Stroke(); - - } - } - ctx.Restore(); - } - else - { - foreach (PositionVertexBuffer lineBuffer in lineBuffers) - { - if (Pure2D) - { - SimpleLineShader2D.Use(renderContext, lineBuffer.VertexBuffer, color, zBuffer); - } - else - { - SimpleLineShader.Use(renderContext, lineBuffer.VertexBuffer, color, zBuffer); - } - renderContext.gl.drawArrays(GL.LINES, 0, lineBuffer.Count); - } - } - } - - - - //List lineBufferBindings = new List(); - - List lineBuffers = new List(); - List lineBufferCounts = new List(); - - - public bool UseLocalCenters = false; - void InitLineBuffer(RenderContext renderContext) - { - if (renderContext.gl != null) - { - if (lineBuffers.Count == 0) - { - int count = linePoints.Count; - - PositionVertexBuffer lineBuffer = null; - - - Vector3d[] linePointList = null; - localCenter = new Vector3d(); - if (DepthBuffered) - { - // compute the local center.. - foreach (Vector3d point in linePoints) - { - localCenter.Add(point); - - } - localCenter.X /= count; - localCenter.Y /= count; - localCenter.Z /= count; - } - - int countLeft = count; - int index = 0; - int counter = 0; - Vector3d temp; - - foreach (Vector3d point in linePoints) - { - if (counter >= 100000 || linePointList == null) - { - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - int thisCount = Math.Min(100000, countLeft); - - countLeft -= thisCount; - lineBuffer = new PositionVertexBuffer(thisCount); - - linePointList = (Vector3d[])lineBuffer.Lock(); // Lock the buffer (which will return our structs) - - lineBuffers.Add(lineBuffer); - lineBufferCounts.Add(thisCount); - counter = 0; - } - - if (UseLocalCenters) - { - temp = Vector3d.SubtractVectors(point, localCenter); - linePointList[counter] = temp; - } - else - { - linePointList[counter] = point; - } - index++; - counter++; - } - - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - - } - } - } - - void EmptyLineBuffer() - { - - - } - - } - - public class OrbitLineList - { - public OrbitLineList() - { - } - - - bool zBuffer = true; - - public bool DepthBuffered - { - get { return zBuffer; } - set { zBuffer = value; } - } - - List linePoints = new List(); - List lineColors = new List(); - public void AddLine(Vector3d v1, Vector3d v2, Color c1, Color c2) - { - - linePoints.Add(v1); - lineColors.Add(c1); - linePoints.Add(v2); - lineColors.Add(c2); - EmptyLineBuffer(); - - } - - public void Clear() - { - linePoints.Clear(); - EmptyLineBuffer(); - } - - Vector3d localCenter; - public bool Sky = true; - public bool aaFix = true; - - public Matrix3d ViewTransform = Matrix3d.Identity; - - public void DrawLines(RenderContext renderContext, float opacity, Color color) - { - if (linePoints.Count < 2) - { - return; - } - - InitLineBuffer(renderContext); - - int count = linePoints.Count; - - - foreach (PositionColoredVertexBuffer lineBuffer in lineBuffers) - { - OrbitLineShader.Use(renderContext, lineBuffer.VertexBuffer, color); - renderContext.gl.drawArrays(GL.LINES, 0, lineBuffer.Count); - } - } - - List lineBuffers = new List(); - List lineBufferCounts = new List(); - - - public bool UseLocalCenters = false; - void InitLineBuffer(RenderContext renderContext) - { - if (renderContext.gl != null) - { - if (lineBuffers.Count == 0) - { - int count = linePoints.Count; - - PositionColoredVertexBuffer lineBuffer = null; - - - PositionColored[] linePointList = null; - localCenter = new Vector3d(); - if (DepthBuffered) - { - // compute the local center.. - foreach (Vector3d point in linePoints) - { - localCenter.Add(point); - - } - localCenter.X /= count; - localCenter.Y /= count; - localCenter.Z /= count; - } - - int countLeft = count; - int index = 0; - int counter = 0; - Vector3d temp; - - foreach (Vector3d point in linePoints) - { - if (counter >= 100000 || linePointList == null) - { - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - int thisCount = Math.Min(100000, countLeft); - - countLeft -= thisCount; - lineBuffer = new PositionColoredVertexBuffer(thisCount); - - linePointList = lineBuffer.Lock(); // Lock the buffer (which will return our structs) - - lineBuffers.Add(lineBuffer); - lineBufferCounts.Add(thisCount); - counter = 0; - } - - if (UseLocalCenters) - { - temp = Vector3d.SubtractVectors(point, localCenter); - linePointList[counter] = new PositionColored(temp, lineColors[index]); - } - else - { - linePointList[counter] = new PositionColored(point, lineColors[index]); - } - index++; - counter++; - } - - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - } - } - } - - void EmptyLineBuffer() - { - foreach (PositionColoredVertexBuffer lineBuffer in lineBuffers) - { - lineBuffer.Dispose(); - } - lineBuffers.Clear(); - } - } - - - public class LineList - { - public LineList() - { - } - bool zBuffer = true; - - public bool DepthBuffered - { - get { return zBuffer; } - set { zBuffer = value; } - } - public bool TimeSeries = false; - public bool ShowFarSide = true; - public bool Sky = false; - public double Decay = 0; - public bool UseNonRotatingFrame = false; - public double JNow = 0; - - List linePoints = new List(); - List lineColors = new List(); - List lineDates = new List(); - public void AddLine(Vector3d v1, Vector3d v2, Color color, Dates date) - { - - linePoints.Add(v1); - linePoints.Add(v2); - lineColors.Add(color); - lineDates.Add(date); - EmptyLineBuffer(); - - } - - public void AddLineNoDate(Vector3d v1, Vector3d v2, Color color) - { - - linePoints.Add(v1); - linePoints.Add(v2); - lineColors.Add(color); - lineDates.Add(new Dates(0,0)); - EmptyLineBuffer(); - - } - - public void Clear() - { - linePoints.Clear(); - lineColors.Clear(); - lineDates.Clear(); - } - bool usingLocalCenter = true; - Vector3d localCenter; - public void DrawLines(RenderContext renderContext, float opacity) - { - if (linePoints.Count < 2 || opacity <= 0) - { - return; - } - if (renderContext.gl == null) - { - //todo draw with HTML5 - } - else - { - InitLineBuffer(); - - foreach (TimeSeriesLineVertexBuffer lineBuffer in lineBuffers) - { - LineShaderNormalDates.Use(renderContext, lineBuffer.VertexBuffer, Color.FromArgb(255, 255, 255, 255), zBuffer, (float)JNow, TimeSeries ? (float)Decay : 0); - renderContext.gl.drawArrays(GL.LINES, 0, lineBuffer.Count); - } - } - - } - - List lineBuffers = new List(); - List lineBufferCounts = new List(); - - void InitLineBuffer() - { - if (lineBuffers.Count == 0) - { - int count = linePoints.Count; - - TimeSeriesLineVertexBuffer lineBuffer = null; - - - TimeSeriesLineVertex[] linePointList = null; - //localCenter = new Vector3d(); - //if (DepthBuffered) - //{ - // // compute the local center.. - // foreach (Vector3d point in linePoints) - // { - // localCenter.Add(point); - - // } - // localCenter.X /= count; - // localCenter.Y /= count; - // localCenter.Z /= count; - //} - - int countLeft = count; - int index = 0; - int counter = 0; - Vector3d temp; - - foreach (Vector3d point in linePoints) - { - if (counter >= 100000 || linePointList == null) - { - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - int thisCount = Math.Min(100000, countLeft); - - countLeft -= thisCount; - lineBuffer = new TimeSeriesLineVertexBuffer(thisCount); - - linePointList = (TimeSeriesLineVertex[])lineBuffer.Lock(); // Lock the buffer (which will return our structs) - - lineBuffers.Add(lineBuffer); - lineBufferCounts.Add(thisCount); - counter = 0; - } - int div2 = (int)(index / 2); - - temp = point; // -localCenter; - linePointList[counter] = new TimeSeriesLineVertex(); - linePointList[counter].Position = temp; - linePointList[counter].Normal = point; - linePointList[counter].Tu = (float)lineDates[div2].StartDate; - linePointList[counter].Tv = (float)lineDates[div2].EndDate; - linePointList[counter].Color = lineColors[div2]; - index++; - counter++; - } - - if (lineBuffer != null) - { - lineBuffer.Unlock(); - } - - } - } - - void EmptyLineBuffer() - { - //if (lineBuffers != null) - //{ - // foreach (TimeSeriesLineVertexBuffer11 lineBuffer in lineBuffers) - // { - // lineBuffer.Dispose(); - // GC.SuppressFinalize(lineBuffer); - // } - // lineBuffers.Clear(); - // lineBufferCounts.Clear(); - //} - - } - } - - - public enum CullMode { None = 0, CounterClockwise = 2,Clockwise =1 }; - - public class TriangleList - { - public TriangleList() - { - - } - - List trianglePoints = new List(); - List triangleColors = new List(); - List triangleDates = new List(); - - public bool TimeSeries = false; - public bool ShowFarSide = false; - public bool Sky = false; - public bool DepthBuffered = true; - public bool WriteZbuffer = false; - public double Decay = 0; - - public bool AutoTime = true; - public double JNow = 0; - bool dataToDraw = false; - - public void AddTriangle(Vector3d v1, Vector3d v2, Vector3d v3, Color color, Dates date) - { - trianglePoints.Add(v1); - trianglePoints.Add(v2); - trianglePoints.Add(v3); - triangleColors.Add(color); - triangleDates.Add(date); - EmptyTriangleBuffer(); - } - - public void AddSubdividedTriangles(Vector3d v1, Vector3d v2, Vector3d v3, Color color, Dates date, int subdivisions) - { - subdivisions--; - - if (subdivisions < 0) - { - AddTriangle(v1, v2, v3, color, date); - } - else - { - Vector3d v12; - Vector3d v23; - Vector3d v31; - - v12 = Vector3d.MidPointByLength(v1, v2); - v23 = Vector3d.MidPointByLength(v2, v3); - v31 = Vector3d.MidPointByLength(v3, v1); - - // Add 1st - AddSubdividedTriangles(v1, v12, v31, color, date, subdivisions); - // Add 2nd - AddSubdividedTriangles(v12, v23, v31, color, date, subdivisions); - // Add 3rd - AddSubdividedTriangles(v12, v2, v23, color, date, subdivisions); - // Add 4th - AddSubdividedTriangles(v23, v3, v31, color, date, subdivisions); - - } - } - - public void AddQuad(Vector3d v1, Vector3d v2, Vector3d v3, Vector3d v4, Color color, Dates date) - { - trianglePoints.Add(v1); - trianglePoints.Add(v3); - trianglePoints.Add(v2); - trianglePoints.Add(v2); - trianglePoints.Add(v3); - trianglePoints.Add(v4); - triangleColors.Add(color); - triangleDates.Add(date); - triangleColors.Add(color); - triangleDates.Add(date); - EmptyTriangleBuffer(); - } - - - public void Clear() - { - - triangleColors.Clear(); - trianglePoints.Clear(); - triangleDates.Clear(); - EmptyTriangleBuffer(); - - } - void EmptyTriangleBuffer() - { - //if (triangleBuffers != null) - //{ - // foreach (TimeSeriesLineVertexBuffer11 buf in triangleBuffers) - // { - // buf.Dispose(); - // GC.SuppressFinalize(buf); - // } - // triangleBuffers.Clear(); - // triangleBufferCounts.Clear(); - // dataToDraw = false; - //} - - } - - List triangleBuffers = new List(); - List triangleBufferCounts = new List(); - - void InitTriangleBuffer() - { - - if (triangleBuffers.Count == 0) - { - int count = trianglePoints.Count; - - TimeSeriesLineVertexBuffer triangleBuffer = null; - - TimeSeriesLineVertex[] triPointList = null; - int countLeft = count; - int index = 0; - int counter = 0; - foreach (Vector3d point in trianglePoints) - { - if (counter >= 90000 || triangleBuffer == null) - { - if (triangleBuffer != null) - { - triangleBuffer.Unlock(); - } - int thisCount = Math.Min(90000, countLeft); - - countLeft -= thisCount; - triangleBuffer = new TimeSeriesLineVertexBuffer(thisCount); - - triangleBuffers.Add(triangleBuffer); - triangleBufferCounts.Add(thisCount); - triPointList = (TimeSeriesLineVertex[])triangleBuffer.Lock(); // Lock the buffer (which will return our structs) - counter = 0; - } - - triPointList[counter] = new TimeSeriesLineVertex(); - triPointList[counter].Position = point; - triPointList[counter].Normal = point; - int div3 = (int)(index / 3); - - triPointList[counter].Color = triangleColors[div3]; - triPointList[counter].Tu = (float)triangleDates[div3].StartDate; - triPointList[counter].Tv = (float)triangleDates[div3].EndDate; - index++; - counter++; - } - if (triangleBuffer != null) - { - triangleBuffer.Unlock(); - } - - triangleColors.Clear(); - triangleDates.Clear(); - trianglePoints.Clear(); - - dataToDraw = true; - } - - } - - - - public void Draw(RenderContext renderContext, float opacity, CullMode cull) - { - if (trianglePoints.Count < 1 && !dataToDraw) - { - return; - } - - - - //renderContext.DepthStencilMode = DepthBuffered ? (WriteZbuffer ? DepthStencilMode.ZReadWrite : DepthStencilMode.ZReadOnly) : DepthStencilMode.Off; - - //renderContext.devContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; - - //switch (cull) - //{ - // case CullMode.Clockwise: - // renderContext.setRasterizerState(TriangleCullMode.CullClockwise); - // break; - // case CullMode.CounterClockwise: - // renderContext.setRasterizerState(TriangleCullMode.CullCounterClockwise); - // break; - // case CullMode.None: - // renderContext.setRasterizerState(TriangleCullMode.Off); - // break; - // default: - // break; - //} - - - //if (AutoTime) - //{ - // DateTime baseDate = new DateTime(2010, 1, 1, 12, 00, 00); - // LineShaderNormalDates.Constants.JNow = (float)(SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate)); - //} - //else - //{ - // LineShaderNormalDates.Constants.JNow = (float)JNow; - //} - - //LineShaderNormalDates.Constants.Sky = 0; - //LineShaderNormalDates.Constants.ShowFarSide = ShowFarSide ? 1 : 0; - //if (TimeSeries) - //{ - // LineShaderNormalDates.Constants.Decay = (float)Decay; - //} - //else - //{ - // LineShaderNormalDates.Constants.Decay = 0; - //} - //LineShaderNormalDates.Constants.Opacity = opacity; - //LineShaderNormalDates.Constants.CameraPosition = new SharpDX.Vector4(Vector3d.TransformCoordinate(renderContext.CameraPosition, Matrix3d.Invert(renderContext.World)).Vector311, 1); - - //SharpDX.Matrix mat = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11; - //mat.Transpose(); - - //LineShaderNormalDates.Constants.WorldViewProjection = mat; - - //LineShaderNormalDates.Use(renderContext.devContext); - - //foreach (TimeSeriesLineVertexBuffer vertBuffer in triangleBuffers) - //{ - // renderContext.SetVertexBuffer(vertBuffer); - // renderContext.devContext.Draw(vertBuffer.Count, 0); - //} - - if (renderContext.gl == null) - { - //todo implement HTML5 version - } - else - { - - InitTriangleBuffer(); - foreach (TimeSeriesLineVertexBuffer triBuffer in triangleBuffers) - { - LineShaderNormalDates.Use(renderContext, triBuffer.VertexBuffer, Color.FromArgb(255, 255, 255, 255), DepthBuffered, (float)JNow, TimeSeries ? (float)Decay : 0); - renderContext.gl.drawArrays(GL.TRIANGLES, 0, triBuffer.Count); - } - } - } - } - - public class TriangleFanList - { - - public TriangleFanList() - { - } - bool zBuffer = true; - - public bool DepthBuffered - { - get { return zBuffer; } - set { zBuffer = value; } - } - public bool TimeSeries = false; - public double Decay = 0; - public double JNow = 0; - - List> shapes = new List>(); - List colors = new List(); - List dates = new List(); - public void AddShape(List shapePoints, Color color, Dates date) - { - shapes.Add(shapePoints); - colors.Add(color); - dates.Add(date); - } - - public void Draw(RenderContext renderContext, float opacity) - { - if (opacity <= 0) - { - return; - } - if (renderContext.gl != null) - { - InitBuffer(); - - foreach (TimeSeriesLineVertexBuffer buffer in buffers) - { - LineShaderNormalDates.Use(renderContext, buffer.VertexBuffer, Color.FromArgb(255, 255, 255, 255), zBuffer, (float)JNow, TimeSeries ? (float)Decay : 0); - renderContext.gl.drawArrays(GL.TRIANGLE_FAN, 0, buffer.Count); - } - } - - } - - List buffers = new List(); - List bufferCounts = new List(); - - void InitBuffer() - { - if (buffers.Count != shapes.Count) - { - buffers.Clear(); - - int index = 0; - - foreach (List shape in shapes) - { - TimeSeriesLineVertexBuffer buffer = new TimeSeriesLineVertexBuffer(shape.Count); - - TimeSeriesLineVertex[] pointList = (TimeSeriesLineVertex[])buffer.Lock(); // Lock the buffer (which will return our structs) - - buffers.Add(buffer); - bufferCounts.Add(shape.Count); - int counter = 0; - foreach (Vector3d point in shape) - { - pointList[counter] = new TimeSeriesLineVertex(); - pointList[counter].Position = point; - pointList[counter].Tu = (float)dates[index].StartDate; - pointList[counter].Tv = (float)dates[index].EndDate; - pointList[counter].Color = colors[index]; - counter++; - } - index++; - if (buffer != null) - { - buffer.Unlock(); - } - } - - } - } - } - - public class PointList - { - public PointList(RenderContext device) - { - this.device = device; - } - - RenderContext device; - List points = new List(); - List colors = new List(); - List dates = new List(); - List sizes = new List(); - public bool TimeSeries = false; - public bool ShowFarSide = false; - public bool Sky = false; - public bool DepthBuffered = true; - public double Decay = 0; - public double scale = 1; - public bool AutoTime = true; - public double JNow = 0; - bool dataToDraw = false; - - public void AddPoint(Vector3d v1, Color color, Dates date, float size) - { - points.Add(v1); - colors.Add(color.Clone()); - dates.Add(date); - sizes.Add(size); - EmptyPointBuffer(); - } - - - public void Clear() - { - - colors.Clear(); - points.Clear(); - dates.Clear(); - sizes.Clear(); - EmptyPointBuffer(); - - } - Vector3d[] transformedList; - Vector3d[] worldList; - - void EmptyPointBuffer() - { - foreach (TimeSeriesPointVertexBuffer pointBuffer in pointBuffers) - { - pointBuffer.Dispose(); - } - pointBuffers.Clear(); - init = false; - } - - public List items = new List(); - - ImageElement starProfile; - - public static Texture starTexture = null; - bool imageReady = false; - bool init = false; - public float MinSize = 2.0f; - List pointBuffers = new List(); - List pointBufferCounts = new List(); - //const double jBase = 2455198.0; - void InitBuffer(RenderContext renderContext) - { - if (!init) - { - if (renderContext.gl == null) - { - starProfile = (ImageElement)Document.CreateElement("img"); - starProfile.AddEventListener("load", delegate (ElementEvent e) - { - imageReady = true; - }, false); - - starProfile.Src = URLHelpers.singleton.engineAssetUrl("StarProfileAlpha.png"); - - worldList = new Vector3d[points.Count]; - transformedList = new Vector3d[points.Count]; - - int index = 0; - foreach (Vector3d pnt in points) - { - // todo filter by date - DataItem item = new DataItem(); - item.Location = pnt; - item.Tranformed = new Vector3d(); - item.Size = sizes[index]; - item.Color = colors[index]; - worldList[index] = item.Location; - transformedList[index] = item.Tranformed; - items.Add(item); - index++; - } - } - else - { - if (pointBuffers.Count == 0) - { - if (starTexture == null) - { - starTexture = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("StarProfileAlpha.png")); - } - - int count = this.points.Count; - - TimeSeriesPointVertexBuffer pointBuffer = null; - TimeSeriesPointVertex[] pointList = null; - - int countLeft = count; - int index = 0; - int counter = 0; - foreach (Vector3d point in points) - { - if (counter >= 100000 || pointList == null) - { - if (pointBuffer != null) - { - pointBuffer.Unlock(); - } - int thisCount = Math.Min(100000, countLeft); - - countLeft -= thisCount; - pointBuffer = new TimeSeriesPointVertexBuffer(thisCount); - - pointList = (TimeSeriesPointVertex[])pointBuffer.Lock(); // Lock the buffer (which will return our structs) - - pointBuffers.Add(pointBuffer); - pointBufferCounts.Add(thisCount); - counter = 0; - } - pointList[counter] = new TimeSeriesPointVertex(); - pointList[counter].Position = point; - pointList[counter].PointSize = sizes[index]; - pointList[counter].Tu = (float)(dates[index].StartDate); - pointList[counter].Tv = (float)(dates[index].EndDate); - pointList[counter].Color = colors[index]; - index++; - counter++; - } - - if (pointBuffer != null) - { - pointBuffer.Unlock(); - } - } - } - - init = true; - } - } - - public void Draw(RenderContext renderContext, float opacity, bool cull) - { - InitBuffer(renderContext); - - - - - if (renderContext.gl == null) - { - if (!imageReady) - { - return; - } - renderContext.Device.Save(); - - renderContext.WVP.ProjectArrayToScreen(worldList, transformedList); - CanvasContext2D ctx = renderContext.Device; - ctx.Alpha = .4; - - double width = renderContext.Width; - double height = renderContext.Height; - - Vector3d viewPoint = Vector3d.MakeCopy(renderContext.ViewPoint); - - double scaleFactor = renderContext.FovScale / 100; - foreach (DataItem item in items) - { - // todo filter by date - - // if (Vector3d.Dot(viewPoint, item.Location) < 0) - if (item.Tranformed.Z < 1) - { - double x = item.Tranformed.X; - double y = item.Tranformed.Y; - double size = .1 * item.Size / scaleFactor; - double half = size / 2; - if (x > -half && x < width + half && y > -half && y < height + half) - { - //ctx.DrawImage(starProfile, x - size / 2, y - size / 2, size, size); - - ctx.BeginPath(); - // ctx.FillStyle = "rgb(200,0,0)"; - ctx.FillStyle = item.Color.ToFormat(); - ctx.Arc(x, y, size, 0, Math.PI * 2, true); - ctx.Fill(); - } - } - - } - - renderContext.Device.Restore(); - } - else - { - Vector3d zero = new Vector3d(); - Matrix3d matInv = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - matInv.Invert(); - Vector3d cam = Vector3d.TransformCoordinate(zero, matInv); - - foreach (TimeSeriesPointVertexBuffer pointBuffer in pointBuffers) - { - TimeSeriesPointSpriteShader.Use( - renderContext, pointBuffer.VertexBuffer, starTexture.Texture2d, - Color.FromArgb(255 * opacity, 255, 255, 255), DepthBuffered, (float)(this.JNow), - this.TimeSeries ? (float)Decay : 0, cam, (float)(scale * (renderContext.Height / 960)), MinSize, ShowFarSide, Sky - ); - - renderContext.gl.drawArrays(GL.POINTS, 0, pointBuffer.Count); - } - - // renderContext.gl.disable(0x8642); - } - } - - public void DrawTextured(RenderContext renderContext, WebGLTexture texture, float opacity) - { - InitBuffer(renderContext); - - Vector3d zero = new Vector3d(); - Matrix3d matInv = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - matInv.Invert(); - Vector3d cam = Vector3d.TransformCoordinate(zero, matInv); - - foreach (TimeSeriesPointVertexBuffer pointBuffer in pointBuffers) - { - TimeSeriesPointSpriteShader.Use( - renderContext, pointBuffer.VertexBuffer, texture, - Color.FromArgb(255*opacity, 255, 255, 255), DepthBuffered, (float)(this.JNow), - (float)Decay, cam, (float)(scale * (renderContext.Height / 960)), MinSize, ShowFarSide, Sky - ); - - renderContext.gl.drawArrays(GL.POINTS, 0, pointBuffer.Count); - } - } - } - - public class TimeSeriesLineVertex - { - public Vector3d Position = new Vector3d(); - public Vector3d Normal = new Vector3d(); - public Color color; - public Color Color - { - get - { - return color; - } - set - { - color = value; - } - } - public float Tu; - public float Tv; - public static TimeSeriesLineVertex Create(Vector3d position, Vector3d normal, float time, Color color) - { - TimeSeriesLineVertex temp = new TimeSeriesLineVertex(); - - temp.Position = position; - temp.Normal = normal; - temp.Tu = time; - temp.Tv = 0; - temp.color = color; - - return temp; - } - } - - public enum PointScaleTypes { Linear=0, Power=1, Log=2, Constant=3, StellarMagnitude=4 }; - public class TimeSeriesPointVertex - { - public Vector3d Position; - public float PointSize; - public Color color; - public Color Color - { - get - { - return color; - } - set - { - color = value; - } - } - public float Tu; - public float Tv; - public static TimeSeriesPointVertex Create(Vector3d position, float size, float time, Color color) - { - TimeSeriesPointVertex tmp = new TimeSeriesPointVertex(); - - tmp.Position = position; - tmp.PointSize = size; - tmp.Tu = time; - tmp.Tv = 0; - tmp.color = color; - return tmp; - - } - } - - -} diff --git a/engine/csharp_ref/Graphics/Shaders.cs b/engine/csharp_ref/Graphics/Shaders.cs deleted file mode 100644 index 9a1eab79..00000000 --- a/engine/csharp_ref/Graphics/Shaders.cs +++ /dev/null @@ -1,2779 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - - -namespace wwtlib -{ - - public class SimpleLineShader - { - public SimpleLineShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static WebGLUniformLocation lineColorLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision highp float; \n" + - " uniform vec4 lineColor; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = lineColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " } \n" + - " \n"; - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor, bool useDepth) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform4f(lineColorLoc, lineColor.R / 255, lineColor.G / 255, lineColor.B / 255, 1); - if (renderContext.Space || !useDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - - gl.enableVertexAttribArray(vertLoc); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 0, 0); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - public class SimpleLineShader2D - { - public SimpleLineShader2D() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static WebGLUniformLocation lineColorLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision highp float; \n" + - " uniform vec4 lineColor; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = lineColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = vec4(aVertexPosition, 1.0); \n" + - " } \n" + - " \n"; - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor, bool useDepth) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniform4f(lineColorLoc, lineColor.R / 255, lineColor.G / 255, lineColor.B / 255, 1); - if (renderContext.Space || !useDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - - gl.enableVertexAttribArray(vertLoc); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 0, 0); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - public class OrbitLineShader - { - public OrbitLineShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int colorLoc; - public static WebGLUniformLocation lineColorLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision highp float; \n" + - " uniform vec4 lineColor; \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = lineColor * vColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec4 aVertexColor; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vColor = aVertexColor; \n" + - " } \n" + - " \n"; - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - colorLoc = gl.getAttribLocation(prog, "aVertexColor"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform4f(lineColorLoc, lineColor.R / 255, lineColor.G / 255, lineColor.B / 255, 1); - if (renderContext.Space) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(colorLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 28, 0); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 28, 12); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - - public class LineShaderNormalDates - { - public LineShaderNormalDates() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int colorLoc; - public static int timeLoc; - public static WebGLUniformLocation lineColorLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation jNowLoc; - public static WebGLUniformLocation decayLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision highp float; \n" + - " uniform vec4 lineColor; \n" + - " varying lowp vec4 vColor; \n" + - " void main(void) \n" + - " { \n" + - " gl_FragColor = lineColor * vColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec4 aVertexColor; \n" + - " attribute vec2 aTime; \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " uniform float jNow; \n" + - " uniform float decay; \n" + - " \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) \n" + - " { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " float dAlpha = 1.0; \n" + - " if ( decay > 0.0) \n" + - " { \n" + - " dAlpha = 1.0 - ((jNow - aTime.y) / decay); \n " + - " if (dAlpha > 1.0 ) \n" + - " { \n" + - " dAlpha = 1.0; \n" + - " } \n" + - " } \n" + - " if (jNow < aTime.x && decay > 0.0) \n" + - " { \n" + - " vColor = vec4(1, 1, 1, 1); \n" + - " } \n" + - " else \n" + - " { \n" + - " vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha * aVertexColor.a); \n" + - " } \n" + - " } \n" + - " \n"; - - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - colorLoc = gl.getAttribLocation(prog, "aVertexColor"); - timeLoc = gl.getAttribLocation(prog, "aTime"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - jNowLoc = gl.getUniformLocation(prog, "jNow"); - decayLoc = gl.getUniformLocation(prog, "decay"); - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor, bool zBuffer, float jNow, float decay) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform4f(lineColorLoc, lineColor.R / 255, lineColor.G / 255, lineColor.B / 255, 1); - gl.uniform1f(jNowLoc, jNow); - gl.uniform1f(decayLoc, decay); - - if (zBuffer) - { - gl.enable(GL.DEPTH_TEST); - } - else - { - gl.disable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(colorLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 36, 0); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 36, 12); - gl.vertexAttribPointer(timeLoc, 2, GL.FLOAT, false, 36, 28); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - - public class TimeSeriesPointSpriteShader - { - public TimeSeriesPointSpriteShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int colorLoc; - public static int pointSizeLoc; - public static int timeLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation jNowLoc; - public static WebGLUniformLocation decayLoc; - public static WebGLUniformLocation lineColorLoc; - public static WebGLUniformLocation cameraPosLoc; - public static WebGLUniformLocation scaleLoc; - public static WebGLUniformLocation minSizeLoc; - public static WebGLUniformLocation skyLoc; - public static WebGLUniformLocation showFarSideLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " uniform vec4 lineColor; \n" + - " varying lowp vec4 vColor; \n" + - " uniform sampler2D uSampler; \n" + - " void main(void) \n" + - " { \n" + - " vec4 texColor; \n" + - " texColor = texture2D(uSampler, gl_PointCoord); \n" + - " \n" + - " \n" + - " gl_FragColor = lineColor * vColor * texColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec4 aVertexColor; \n" + - " attribute vec2 aTime; \n" + - " attribute float aPointSize; \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " uniform float jNow; \n" + - " uniform vec3 cameraPosition; \n" + - " uniform float decay; \n" + - " uniform float scale; \n" + - " uniform float minSize; \n" + - " uniform float sky; \n" + - " uniform float showFarSide; \n" + - " \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) \n" + - " { \n" + - " float dotCam = dot( normalize(cameraPosition-aVertexPosition), normalize(aVertexPosition)); \n" + - " float dist = distance(aVertexPosition, cameraPosition); \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " float dAlpha = 1.0; \n" + - " if ( decay > 0.0) \n" + - " { \n" + - " dAlpha = 1.0 - ((jNow - aTime.y) / decay); \n " + - " if (dAlpha > 1.0 ) \n" + - " { \n" + - " dAlpha = 1.0; \n" + - " } \n" + - " } \n" + - " if ( showFarSide == 0.0 && (dotCam * sky) < 0.0 || (jNow < aTime.x && decay > 0.0)) \n" + - " { \n" + - " vColor = vec4(0.0, 0.0, 0.0, 0.0); \n" + - " } \n" + - " else \n" + - " { \n" + - " vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha); \n" + - " } \n" + - " float lSize = scale; \n" + - " if (scale < 0.0) \n" + - " { \n" + - " lSize = -scale; \n" + - " dist = 1.0; \n" + - " } \n" + - " gl_PointSize = max(minSize, (lSize * ( aPointSize ) / dist)); \n" + - " } \n" + - " \n"; - - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - object compilationLog = gl.getShaderInfoLog(vert); - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - colorLoc = gl.getAttribLocation(prog, "aVertexColor"); - pointSizeLoc = gl.getAttribLocation(prog, "aPointSize"); - timeLoc = gl.getAttribLocation(prog, "aTime"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - jNowLoc = gl.getUniformLocation(prog, "jNow"); - decayLoc = gl.getUniformLocation(prog, "decay"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - cameraPosLoc = gl.getUniformLocation(prog, "cameraPosition"); - scaleLoc = gl.getUniformLocation(prog, "scale"); - skyLoc = gl.getUniformLocation(prog, "sky"); - showFarSideLoc = gl.getUniformLocation(prog, "showFarSide"); - minSizeLoc = gl.getUniformLocation(prog, "minSize"); - - gl.enable(GL.BLEND); - - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLTexture texture, Color lineColor, bool zBuffer, float jNow, float decay, Vector3d camera, float scale, float minSize, bool showFarSide, bool sky) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform1i(sampLoc, 0); - gl.uniform1f(jNowLoc, jNow); - gl.uniform1f(decayLoc, decay); - gl.uniform4f(lineColorLoc, lineColor.R / 255f, lineColor.G / 255f, lineColor.B / 255f, lineColor.A / 255f); - gl.uniform3f(cameraPosLoc, (float)camera.X, (float)camera.Y, (float)camera.Z); - gl.uniform1f(scaleLoc, scale); - gl.uniform1f(minSizeLoc, minSize); - gl.uniform1f(showFarSideLoc, showFarSide ? 1 : 0); - gl.uniform1f(skyLoc, sky ? -1 : 1); - if (zBuffer) - { - gl.enable(GL.DEPTH_TEST); - } - else - { - gl.disable(GL.DEPTH_TEST); - } - //gl.enable(0x8642); - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(colorLoc); - gl.enableVertexAttribArray(pointSizeLoc); - gl.enableVertexAttribArray(timeLoc); - - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 40, 0); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 40, 12); - gl.vertexAttribPointer(pointSizeLoc, 1, GL.FLOAT, false, 40, 36); - gl.vertexAttribPointer(timeLoc, 2, GL.FLOAT, false, 40, 28); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - } - } - - public class KeplerPointSpriteShader - { - public KeplerPointSpriteShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - public static int ABCLoc; - public static int abcLoc1; - public static int pointSizeLoc; - public static int colorLoc; - public static int weLoc; - public static int nTLoc; - public static int azLoc; - public static int orbitLoc; - - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation jNowLoc; - public static WebGLUniformLocation cameraPosLoc; - public static WebGLUniformLocation mmLoc; - public static WebGLUniformLocation lineColorLoc; - public static WebGLUniformLocation scaleLoc; - public static WebGLUniformLocation minSizeLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation opacityLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " uniform vec4 lineColor; \n" + - " varying lowp vec4 vColor; \n" + - " uniform sampler2D uSampler; \n" + - " void main(void) \n" + - " { \n" + - " vec4 texColor; \n" + - " texColor = texture2D(uSampler, gl_PointCoord); \n" + - " \n" + - " \n" + - " gl_FragColor = lineColor * vColor * texColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 ABC; \n" + - " attribute vec3 abc; \n" + - " attribute float PointSize; \n" + - " attribute vec4 Color; \n" + - " attribute vec2 we; \n" + - " attribute vec2 nT; \n" + - " attribute vec2 az; \n" + - " attribute vec2 orbit; \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " uniform float jNow; \n" + - " uniform vec3 cameraPosition; \n" + - " uniform float MM; \n" + - " uniform float scaling; \n" + - " uniform float minSize; \n" + - " uniform float opacity; \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) \n" + - " { \n" + - " float M = nT.x * (jNow - nT.y) * 0.01745329251994; \n" + - " float e = we.y; \n" + - " float a = az.x; \n" + - " float PI = 3.1415926535897932384; \n" + - " float w = we.x* 0.01745329251994; \n" + - " float F = 1.0; \n" + - " if (M < 0.0) \n" + - " F = -1.0; \n" + - " M = abs(M) / (2.0 * PI); \n" + - " M = (M - float(int(M)))*2.0 *PI *F; \n" + - " if (MM != 0.0) \n" + - " { \n" + - " M = MM + (1.0- orbit.x) *2.0 *PI; \n" + - " if (M > (2.0*PI)) \n" + - " M = M - (2.0*PI); \n" + - " } \n" + - " \n" + - " if (M < 0.0) \n" + - " M += 2.0 *PI; \n" + - " F = 1.0; \n" + - " if (M > PI) \n" + - " F = -1.0; \n" + - " if (M > PI) \n" + - " M = 2.0 *PI - M; \n" + - " \n" + - " float E = PI / 2.0; \n" + - " float scale = PI / 4.0; \n" + - " for (int i =0; i<23; i++) \n" + - " { \n" + - " float R = E - e *sin(E); \n" + - " if (M > R) \n" + - " E += scale; \n" + - " else \n" + - " E -= scale; \n" + - " scale /= 2.0; \n" + - " } \n" + - " E = E * F; \n" + - " \n" + - " float v = 2.0 * atan(sqrt((1.0 + e) / (1.0 -e )) * tan(E/2.0)); \n" + - " float r = a * (1.0-e * cos(E)); \n" + - " \n" + - " vec4 pnt; \n" + - " pnt.x = r * abc.x * sin(ABC.x + w + v); \n" + - " pnt.z = r * abc.y * sin(ABC.y + w + v); \n" + - " pnt.y = r * abc.z * sin(ABC.z + w + v); \n" + - " pnt.w = 1.0; \n" + - " \n" + - " float dist = distance(pnt.xyz, cameraPosition.xyz); \n" + - " gl_Position = uPMatrix * uMVMatrix * pnt; \n" + - " vColor.a = opacity * (1.0-(orbit.x)); \n" + - " vColor.r = Color.r; \n" + - " vColor.g = Color.g; \n" + - " vColor.b = Color.b; \n" + - " gl_PointSize = max(minSize, scaling * (PointSize / dist)); \n" + - " } \n"; - - - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - object compilationLog = gl.getShaderInfoLog(vert); - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - abcLoc1 = gl.getAttribLocation(prog, "abc"); - ABCLoc = gl.getAttribLocation(prog, "ABC"); - pointSizeLoc = gl.getAttribLocation(prog, "PointSize"); - colorLoc = gl.getAttribLocation(prog, "Color"); - weLoc = gl.getAttribLocation(prog, "we"); - nTLoc = gl.getAttribLocation(prog, "nT"); - azLoc = gl.getAttribLocation(prog, "az"); - orbitLoc = gl.getAttribLocation(prog, "orbit"); - - - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - jNowLoc = gl.getUniformLocation(prog, "jNow"); - cameraPosLoc = gl.getUniformLocation(prog, "cameraPosition"); - mmLoc = gl.getUniformLocation(prog, "MM"); - scaleLoc = gl.getUniformLocation(prog, "scaling"); - minSizeLoc = gl.getUniformLocation(prog, "minSize"); - lineColorLoc = gl.getUniformLocation(prog, "lineColor"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - gl.enable(GL.BLEND); - - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, Matrix3d worldView, WebGLBuffer vertex, WebGLTexture texture, Color lineColor, float opacity, bool zBuffer, float jNow, float MM, Vector3d camera, float scale, float minSize) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - gl.uniformMatrix4fv(mvMatLoc, false, worldView.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform1i(sampLoc, 0); - gl.uniform1f(jNowLoc, jNow); - gl.uniform1f(mmLoc, MM); - gl.uniform4f(lineColorLoc, lineColor.R / 255f, lineColor.G / 255f, lineColor.B / 255f, lineColor.A / 255f); - gl.uniform1f(opacityLoc, opacity); - gl.uniform3f(cameraPosLoc, (float)camera.X, (float)camera.Y, (float)camera.Z); - gl.uniform1f(scaleLoc, scale); - gl.uniform1f(minSizeLoc, minSize); - if (zBuffer) - { - gl.enable(GL.DEPTH_TEST); - } - else - { - gl.disable(GL.DEPTH_TEST); - } - - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - - gl.enableVertexAttribArray(ABCLoc); - gl.enableVertexAttribArray(abcLoc1); - gl.enableVertexAttribArray(colorLoc); - gl.enableVertexAttribArray(pointSizeLoc); - gl.enableVertexAttribArray(weLoc); - gl.enableVertexAttribArray(nTLoc); - gl.enableVertexAttribArray(azLoc); - gl.enableVertexAttribArray(orbitLoc); - - gl.enableVertexAttribArray(weLoc); - gl.vertexAttribPointer(ABCLoc, 3, GL.FLOAT, false, 76, 0); - gl.vertexAttribPointer(abcLoc1, 3, GL.FLOAT, false, 76, 12); - gl.vertexAttribPointer(pointSizeLoc, 1, GL.FLOAT, false, 76, 24); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 76, 28); - gl.vertexAttribPointer(weLoc, 2, GL.FLOAT, false, 76, 44); - gl.vertexAttribPointer(nTLoc, 2, GL.FLOAT, false, 76, 52); - gl.vertexAttribPointer(azLoc, 2, GL.FLOAT, false, 76, 60); - gl.vertexAttribPointer(orbitLoc, 2, GL.FLOAT, false, 76, 68); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - } - } - - public class EllipseShader - { - public EllipseShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - public static int AngleLoc; - - - public static WebGLUniformLocation matWVPLoc; - public static WebGLUniformLocation matPositionLoc; - public static WebGLUniformLocation positionNowLoc; - public static WebGLUniformLocation colorLoc; - public static WebGLUniformLocation opacityLoc; - public static WebGLUniformLocation semiMajorAxisLoc; - public static WebGLUniformLocation eccentricityLoc; - public static WebGLUniformLocation eccentricAnomalyLoc; - - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " varying lowp vec4 vColor; \n" + - " void main(void) \n" + - " { \n" + - " gl_FragColor = vColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 Angle; \n" + - " uniform mat4 matWVP; \n" + - " uniform mat4 matPosition; \n" + - " uniform vec3 positionNow; \n" + - " uniform float semiMajorAxis; \n" + - " uniform float eccentricity; \n" + - " uniform vec4 color; \n" + - " uniform float eccentricAnomaly; \n" + - // " uniform float opacity; \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) \n" + - " { \n" + - " float fade = (1.0 - Angle.x); \n" + - " float PI = 3.1415927; \n" + - " float E = eccentricAnomaly - Angle.x * 2.0 * PI; \n" + - " vec2 semiAxes = vec2(1.0, sqrt(1.0 - eccentricity * eccentricity)) * semiMajorAxis; \n" + - " vec2 planePos = semiAxes * vec2(cos(E) - eccentricity, sin(E)); \n" + - " if (Angle.x == 0.0) \n" + - " gl_Position = matPosition * vec4(positionNow, 1.0); \n" + - " else \n" + - " gl_Position = matWVP * vec4(planePos.x, planePos.y, 0.0, 1.0); \n" + - " vColor = vec4(color.rgb, fade * color.a); \n" + - " } \n"; - - - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - object compilationLog = gl.getShaderInfoLog(vert); - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - AngleLoc = gl.getAttribLocation(prog, "Angle"); - - matWVPLoc = gl.getUniformLocation(prog, "matWVP"); - matPositionLoc = gl.getUniformLocation(prog, "matPosition"); - positionNowLoc = gl.getUniformLocation(prog, "positionNow"); - colorLoc = gl.getUniformLocation(prog, "color"); - // opacityLoc = gl.getUniformLocation(prog, "opacity"); - semiMajorAxisLoc = gl.getUniformLocation(prog, "semiMajorAxis"); - eccentricityLoc = gl.getUniformLocation(prog, "eccentricity"); - eccentricAnomalyLoc = gl.getUniformLocation(prog, "eccentricAnomaly"); - - gl.enable(GL.BLEND); - - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use( - RenderContext renderContext, float semiMajorAxis, float eccentricity, float eccentricAnomaly, - Color lineColor, float opacity, Matrix3d world, Vector3d positionNow) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d WVPPos = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(world, renderContext.View), renderContext.Projection); - Matrix3d WVP = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View), renderContext.Projection); - - gl.uniformMatrix4fv(matWVPLoc, false, WVP.FloatArray()); - gl.uniformMatrix4fv(matPositionLoc, false, WVPPos.FloatArray()); - gl.uniform3f(positionNowLoc, (float)positionNow.X, (float)positionNow.Y, (float)positionNow.Z); - gl.uniform4f(colorLoc, lineColor.R / 255f, lineColor.G / 255f, lineColor.B / 255f, lineColor.A / 255f); - // gl.uniform1f(opacityLoc, opacity); - gl.uniform1f(semiMajorAxisLoc, semiMajorAxis); - gl.uniform1f(eccentricityLoc, eccentricity); - gl.uniform1f(eccentricAnomalyLoc, eccentricAnomaly); - - - // gl.enable(GL.DEPTH_TEST); - gl.disable(GL.DEPTH_TEST); - - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - //gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - //gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - - gl.enableVertexAttribArray(AngleLoc); - - gl.vertexAttribPointer(AngleLoc, 3, GL.FLOAT, false, 0, 0); - gl.lineWidth(1.0f); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - } - } - - public class ModelShader - { - public ModelShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int normalLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation sunLoc; - public static WebGLUniformLocation opacityLoc; - public static WebGLUniformLocation minBrightnessLoc; - public static WebGLUniformLocation atmosphereColorLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " uniform float opacity; \n" + - " uniform vec3 uSunPosition; \n" + - " uniform float uMinBrightness; \n" + - " uniform vec3 uAtmosphereColor; \n" + - " \n" + - " void main(void) { \n" + - " vec3 normal = normalize(vNormal); \n" + - " vec3 camVN = normalize(vCamVector); \n" + - " vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n" + - " float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n" + - " float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n" + - " atm = (dt > uMinBrightness) ? atm : 0.0; \n" + - " if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n" + - " vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " gl_FragColor = col * opacity; \n" + - " gl_FragColor.rgb *= dt; \n" + - " gl_FragColor.rgb += atm * uAtmosphereColor; \n" + //vec3( .25, .61, .85); - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec3 aNormal; \n" + - " attribute vec2 aTextureCoord; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); \n" + - " vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); \n" + - " vTextureCoord = aTextureCoord; \n" + - " vNormal = normalT; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - normalLoc = gl.getAttribLocation(prog, "aNormal"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - sunLoc = gl.getUniformLocation(prog, "uSunPosition"); - minBrightnessLoc = gl.getUniformLocation(prog, "uMinBrightness"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - atmosphereColorLoc = gl.getUniformLocation(prog, "uAtmosphereColor"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - public static Vector3d SunPosition = Vector3d.Create(-1, -1, -1); - public static float MinLightingBrightness = 1.0f; - - public static Color AtmosphereColor = Color.FromArgb(0, 0, 0, 0); - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth, int stride) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - gl.uniform1f(minBrightnessLoc, renderContext.Lighting ? MinLightingBrightness : 1.0f); - - if (renderContext.Lighting) - { - gl.uniform3f(atmosphereColorLoc, AtmosphereColor.R / 255.0f, AtmosphereColor.G / 255.0f, AtmosphereColor.B / 255.0f); - } - else - { - gl.uniform3f(atmosphereColorLoc, 0f, 0f, 0f); - } - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - SunPosition.Normalize(); - - Matrix3d mvInv = renderContext.View.Clone(); - mvInv.M41 = 0; - mvInv.M42 = 0; - mvInv.M43 = 0; - mvInv.M44 = 1; - Vector3d sp = Vector3d.TransformCoordinate(SunPosition, mvInv); - sp.Normalize(); - - - gl.uniform3f(sunLoc, (float)sp.X, (float)sp.Y, (float)sp.Z); - - gl.uniform1i(sampLoc, 0); - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(normalLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, stride, 0); - gl.vertexAttribPointer(normalLoc, 3, GL.FLOAT, false, stride, 12); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, stride, stride - 8); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - public class ModelShaderTan - { - public ModelShaderTan() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int normalLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation sunLoc; - public static WebGLUniformLocation opacityLoc; - public static WebGLUniformLocation minBrightnessLoc; - public static WebGLUniformLocation atmosphereColorLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " uniform float opacity; \n" + - " uniform vec3 uSunPosition; \n" + - " uniform float uMinBrightness; \n" + - " uniform vec3 uAtmosphereColor; \n" + - " \n" + - " void main(void) { \n" + - " vec3 normal = normalize(vNormal); \n" + - " vec3 camVN = normalize(vCamVector); \n" + - " vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n" + - " float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n" + - " float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n" + - " atm = (dt > uMinBrightness) ? atm : 0.0; \n" + - " if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n" + - " vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " gl_FragColor = col * opacity; \n" + - " gl_FragColor.rgb *= dt; \n" + - " gl_FragColor.rgb += atm * uAtmosphereColor; \n" + //vec3( .25, .61, .85); - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec3 aNormal; \n" + - " attribute vec2 aTextureCoord; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); \n" + - " vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); \n" + - " vTextureCoord = aTextureCoord; \n" + - " vNormal = normalT; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - normalLoc = gl.getAttribLocation(prog, "aNormal"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - sunLoc = gl.getUniformLocation(prog, "uSunPosition"); - minBrightnessLoc = gl.getUniformLocation(prog, "uMinBrightness"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - atmosphereColorLoc = gl.getUniformLocation(prog, "uAtmosphereColor"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - public static Vector3d SunPosition = Vector3d.Create(-1, -1, -1); - public static float MinLightingBrightness = 1.0f; - - public static Color AtmosphereColor = Color.FromArgb(0, 0, 0, 0); - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth, int stride) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - gl.uniform1f(minBrightnessLoc, renderContext.Lighting ? MinLightingBrightness : 1.0f); - - if (renderContext.Lighting) - { - gl.uniform3f(atmosphereColorLoc, AtmosphereColor.R / 255.0f, AtmosphereColor.G / 255.0f, AtmosphereColor.B / 255.0f); - } - else - { - gl.uniform3f(atmosphereColorLoc, 0f, 0f, 0f); - } - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - SunPosition.Normalize(); - - Matrix3d mvInv = renderContext.View.Clone(); - mvInv.M41 = 0; - mvInv.M42 = 0; - mvInv.M43 = 0; - mvInv.M44 = 1; - Vector3d sp = Vector3d.TransformCoordinate(SunPosition, mvInv); - sp.Normalize(); - - - gl.uniform3f(sunLoc, -(float)sp.X, -(float)sp.Y, -(float)sp.Z); - - gl.uniform1i(sampLoc, 0); - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(normalLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, stride, 0); - gl.vertexAttribPointer(normalLoc, 3, GL.FLOAT, false, stride, 12); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, stride, stride - 8); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - - - public class TileShader - { - public TileShader() - { - - } - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation centerScreenLoc; - public static WebGLUniformLocation centerWorldLoc; - public static WebGLUniformLocation sunLoc; - public static WebGLUniformLocation opacityLoc; - public static WebGLUniformLocation minBrightnessLoc; - public static WebGLUniformLocation atmosphereColorLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " uniform float opacity; \n" + - " uniform vec3 uSunPosition; \n" + - " uniform float uMinBrightness; \n" + - " uniform vec3 uAtmosphereColor; \n" + - " \n" + - " void main(void) { \n" + - " vec3 normal = normalize(vNormal); \n" + - " vec3 camVN = normalize(vCamVector); \n" + - " vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n" + - " float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n" + - " float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n" + - " atm = (dt > uMinBrightness) ? atm : 0.0; \n" + - " if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n" + - " vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " gl_FragColor = col * opacity; \n" + - " gl_FragColor.rgb *= dt; \n" + - " gl_FragColor.rgb += atm * uAtmosphereColor; \n" + //vec3( .25, .61, .85); - " } \n"; - - - String vertexShaderText = @" - attribute vec3 aVertexPosition; - attribute vec2 aTextureCoord; - - uniform mat4 uMVMatrix; - uniform mat4 uPMatrix; - uniform vec3 uCenterScreen; - uniform vec3 uCenterWorld; - - varying vec2 vTextureCoord; - varying vec3 vNormal; - varying vec3 vCamVector; - - void main(void) { - vec3 normal; - if(length(uCenterWorld) > 0.00001){ - gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0); - vCamVector = normalize((mat3(uMVMatrix) * (aVertexPosition + uCenterWorld)).xyz); - normal = normalize(aVertexPosition + uCenterWorld); - } else { - gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); - vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); - normal = normalize(aVertexPosition); - } - vec3 normalT = normalize(mat3(uMVMatrix) * normal); - vTextureCoord = aTextureCoord; - vNormal = normalT; - }"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - centerScreenLoc = gl.getUniformLocation(prog, "uCenterScreen"); - centerWorldLoc = gl.getUniformLocation(prog, "uCenterWorld"); - sunLoc = gl.getUniformLocation(prog, "uSunPosition"); - minBrightnessLoc = gl.getUniformLocation(prog, "uMinBrightness"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - atmosphereColorLoc = gl.getUniformLocation(prog, "uAtmosphereColor"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - public static Vector3d SunPosition = Vector3d.Create(-1, -1, -1); - public static float MinLightingBrightness = 1.0f; - - public static Color AtmosphereColor = Color.FromArgb(0, 0, 0, 0); - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth, Vector3d centerWorld) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - gl.uniform1f(minBrightnessLoc, renderContext.Lighting ? MinLightingBrightness : 1.0f); - - if (renderContext.Lighting) - { - gl.uniform3f(atmosphereColorLoc, AtmosphereColor.R / 255.0f, AtmosphereColor.G / 255.0f, AtmosphereColor.B / 255.0f); - } - else - { - gl.uniform3f(atmosphereColorLoc, 0f, 0f, 0f); - } - gl.uniform3f(centerWorldLoc, (float)centerWorld.X, (float)centerWorld.Y, (float)centerWorld.Z); - - // This would be clearer by making the 'centerWorld' parameter optional. Unfortunately, that's not allowed in C# 2.0 - if (centerWorld.LengthSq() > 0.001) - { - Matrix3d wvp = Matrix3d.MultiplyMatrix(mvMat, renderContext.Projection); - Vector3d centerScreen = wvp.Transform(centerWorld); - gl.uniform3f(centerScreenLoc, (float)centerScreen.X, (float)centerScreen.Y, (float)centerScreen.Z); - } - else - { - gl.uniform3f(centerScreenLoc, 0, 0, 0); - } - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - SunPosition.Normalize(); - - Matrix3d mvInv = renderContext.View.Clone(); - mvInv.M41 = 0; - mvInv.M42 = 0; - mvInv.M43 = 0; - mvInv.M44 = 1; - Vector3d sp = Vector3d.TransformCoordinate(SunPosition, mvInv); - sp.Normalize(); - - - gl.uniform3f(sunLoc, -(float)sp.X, -(float)sp.Y, -(float)sp.Z); - - gl.uniform1i(sampLoc, 0); - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - - public class FitsShader - { - public FitsShader() - { - - } - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation centerScreenLoc; - public static WebGLUniformLocation colorLoc; - public static WebGLUniformLocation blank; - public static WebGLUniformLocation bzero; - public static WebGLUniformLocation bscale; - public static WebGLUniformLocation minLoc; - public static WebGLUniformLocation maxLoc; - public static WebGLUniformLocation transparentBlackLoc; - public static WebGLUniformLocation containsBlanksLoc; - public static WebGLUniformLocation scalingLocation; - public static WebGLUniformLocation opacityLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = @"#version 300 es - precision mediump float; - in vec2 vTextureCoord; - in vec3 vNormal; - in vec3 vCamVector; - out vec4 fragmentColor; - - uniform sampler2D uSampler; - uniform sampler2D colorSampler; - uniform float blank; - uniform float bzero; - uniform float bscale; - uniform float min; - uniform float max; - uniform bool containsBlanks; - uniform bool transparentBlack; - uniform int scaleType; - uniform float opacity; - - bool isNaN(float value) { - // See https://stackoverflow.com/questions/9446888/best-way-to-detect-nans-in-opengl-shaders - // PKGW also finds that we need `value != value` on his Dell laptop running - // Chrome on Linux. - return (value != value) || !(value < 0.0 || 0.0 < value || value == 0.0); - } - - void main(void) { - //FITS images are flipped on the y axis - vec4 color = texture(uSampler, vec2(vTextureCoord.x, 1.0 - vTextureCoord.y)); - if(isNaN(color.r) || (containsBlanks && abs(blank - color.r) < 0.00000001)){ - fragmentColor = vec4(0.0, 0.0, 0.0, 0.0); - } else { - float physicalValue = (bzero + bscale * color.r - min) / (max - min); - if(transparentBlack && physicalValue <= 0.0){ - fragmentColor = vec4(0.0, 0.0, 0.0, 0.0); - return; - } - - physicalValue = clamp(physicalValue, 0.0, 1.0); - - switch(scaleType){ - case 1: - physicalValue = log(physicalValue * 255.0 + 1.0 ) / log(256.0); - break; - case 2: - physicalValue = physicalValue * physicalValue; - break; - case 3: - physicalValue = sqrt(physicalValue); - break; - } - vec4 colorFromColorMapper = texture(colorSampler, vec2(physicalValue, 0.5)); - fragmentColor = vec4(colorFromColorMapper.rgb, opacity); - } - } - "; - - String vertexShaderText = @"#version 300 es - in vec3 aVertexPosition; - in vec2 aTextureCoord; - - uniform mat4 uMVMatrix; - uniform mat4 uPMatrix; - uniform vec3 uCenterScreen; - - out vec2 vTextureCoord; - - void main(void) { - if(length(uCenterScreen) > 0.0000001) { - gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0); - } else { - gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); - } - vTextureCoord = aTextureCoord; - } - "; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - Script.Literal("console.log({0})", errorF); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - Script.Literal("console.log({0})", errorV); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - colorLoc = gl.getUniformLocation(prog, "colorSampler"); - centerScreenLoc = gl.getUniformLocation(prog, "uCenterScreen"); - blank = gl.getUniformLocation(prog, "blank"); - bzero = gl.getUniformLocation(prog, "bzero"); - bscale = gl.getUniformLocation(prog, "bscale"); - minLoc = gl.getUniformLocation(prog, "min"); - maxLoc = gl.getUniformLocation(prog, "max"); - transparentBlackLoc = gl.getUniformLocation(prog, "transparentBlack"); - containsBlanksLoc = gl.getUniformLocation(prog, "containsBlanks"); - scalingLocation = gl.getUniformLocation(prog, "scaleType"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - public static float BlankValue = 0f; - public static float BScale = 1f; - public static float BZero = 0f; - public static float Min = 0f; - public static float Max = 0f; - public static bool TransparentBlack = false; - public static bool ContainsBlanks = false; - public static int ScaleType = 0; - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth, Vector3d centerWorld) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - - // This would be clearer by making the 'centerWorld' parameter optional. Unfortunately, that's not allowed in C# 2.0 - if (centerWorld.LengthSq() > 0.001) - { - Matrix3d wvp = Matrix3d.MultiplyMatrix(mvMat, renderContext.Projection); - Vector3d centerScreen = wvp.Transform(centerWorld); - gl.uniform3f(centerScreenLoc, (float)centerScreen.X, (float)centerScreen.Y, (float)centerScreen.Z); - } - else - { - gl.uniform3f(centerScreenLoc, 0, 0, 0); - } - - gl.uniform1i(sampLoc, 0); - gl.uniform1i(colorLoc, 1); - - gl.uniform1f(blank, BlankValue); - gl.uniform1f(bzero, BZero); - gl.uniform1f(bscale, BScale); - gl.uniform1f(minLoc, Min); - gl.uniform1f(maxLoc, Max); - gl.uniform1i(transparentBlackLoc, TransparentBlack); - gl.uniform1i(containsBlanksLoc, ContainsBlanks); - gl.uniform1i(scalingLocation, ScaleType); - - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - - public class ImageShader - { - public ImageShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation opacityLoc; - - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " uniform float opacity; \n" + - - " \n" + - " void main(void) { \n" + - " vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " gl_FragColor = col * opacity; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec2 aTextureCoord; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vTextureCoord = aTextureCoord; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - - gl.uniform1i(sampLoc, 0); - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - - public class ImageShader2 - { - public ImageShader2() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - public static WebGLUniformLocation opacityLoc; - - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " uniform float opacity; \n" + - - " \n" + - " void main(void) { \n" + - " vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " gl_FragColor = col * opacity; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec2 aTextureCoord; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec3 vNormal; \n" + - " varying vec3 vCamVector; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vTextureCoord = aTextureCoord; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - if ((int)stat == 0) - { - object errorF = gl.getShaderInfoLog(frag); - } - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - if ((int)stat1 == 0) - { - object errorV = gl.getShaderInfoLog(vert); - } - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - opacityLoc = gl.getUniformLocation(prog, "opacity"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture, float opacity, bool noDepth) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - gl.uniform1f(opacityLoc, opacity); - - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - - gl.uniform1i(sampLoc, 0); - if (renderContext.Space || noDepth) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 32, 0); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 32, 24); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index); - gl.enable(GL.BLEND); - - if (noDepth) - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE); - } - else - { - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - } - - - public class SpriteShader - { - public SpriteShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static int colorLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying lowp vec4 vColor; \n" + - " uniform sampler2D uSampler; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * vColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec2 aTextureCoord; \n" + - " attribute lowp vec4 aColor; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec4 vColor; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vTextureCoord = aTextureCoord; \n" + - " vColor = aColor; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - colorLoc = gl.getAttribLocation(prog, "aColor"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLTexture texture) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform1i(sampLoc, 0); - - gl.disable(GL.DEPTH_TEST); - - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.enableVertexAttribArray(colorLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 36, 0); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 36, 12); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 36, 28); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - public class ShapeSpriteShader - { - public ShapeSpriteShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static int colorLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying lowp vec4 vColor; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = vColor; \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute lowp vec4 aColor; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " varying vec4 vColor; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vColor = aColor; \n" + - " } \n" + - " \n"; - - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - colorLoc = gl.getAttribLocation(prog, "aColor"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - - gl.disable(GL.DEPTH_TEST); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - public static void Use(RenderContext renderContext, WebGLBuffer vertex) - { - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform1i(sampLoc, 0); - - gl.disable(GL.DEPTH_TEST); - - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.enableVertexAttribArray(colorLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 36, 0); - gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 36, 12); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } - - public class TextShader - { - public TextShader() - { - - } - - internal static WebGLShader frag; - internal static WebGLShader vert; - - - public static int vertLoc; - public static int textureLoc; - public static WebGLUniformLocation projMatLoc; - public static WebGLUniformLocation mvMatLoc; - public static WebGLUniformLocation sampLoc; - - public static bool initialized = false; - public static void Init(RenderContext renderContext) - { - GL gl = renderContext.gl; - - String fragShaderText = - " precision mediump float; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " \n" + - " uniform sampler2D uSampler; \n" + - " \n" + - " void main(void) { \n" + - " gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" + - " } \n"; - - - String vertexShaderText = - " attribute vec3 aVertexPosition; \n" + - " attribute vec2 aTextureCoord; \n" + - " \n" + - " uniform mat4 uMVMatrix; \n" + - " uniform mat4 uPMatrix; \n" + - " \n" + - " varying vec2 vTextureCoord; \n" + - " \n" + - " \n" + - " void main(void) { \n" + - " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n" + - " vTextureCoord = aTextureCoord; \n" + - " } \n" + - " \n"; - frag = gl.createShader(GL.FRAGMENT_SHADER); - gl.shaderSource(frag, fragShaderText); - gl.compileShader(frag); - - object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS); - - - vert = gl.createShader(GL.VERTEX_SHADER); - gl.shaderSource(vert, vertexShaderText); - gl.compileShader(vert); - object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS); - - prog = gl.createProgram(); - - gl.attachShader(prog, vert); - gl.attachShader(prog, frag); - gl.linkProgram(prog); - object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS); - - - gl.useProgram(prog); - - vertLoc = gl.getAttribLocation(prog, "aVertexPosition"); - textureLoc = gl.getAttribLocation(prog, "aTextureCoord"); - projMatLoc = gl.getUniformLocation(prog, "uPMatrix"); - mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix"); - sampLoc = gl.getUniformLocation(prog, "uSampler"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - initialized = true; - } - - private static WebGLProgram prog = null; - - //todo add color rendering - public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLTexture texture) - { - if (texture == null) - { - texture = Texture.GetEmpty(); - } - - GL gl = renderContext.gl; - if (gl != null) - { - if (!initialized) - { - Init(renderContext); - } - - gl.useProgram(prog); - - Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - - gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray()); - gl.uniform1i(sampLoc, 0); - if (renderContext.Space) - { - gl.disable(GL.DEPTH_TEST); - } - else - { - gl.enable(GL.DEPTH_TEST); - } - - - - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(GL.ARRAY_BUFFER, vertex); - - gl.enableVertexAttribArray(vertLoc); - gl.enableVertexAttribArray(textureLoc); - gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0); - gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12); - gl.activeTexture(GL.TEXTURE0); - gl.bindTexture(GL.TEXTURE_2D, texture); - gl.enable(GL.BLEND); - gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); - } - } - } -} diff --git a/engine/csharp_ref/Graphics/Sprite2d.cs b/engine/csharp_ref/Graphics/Sprite2d.cs deleted file mode 100644 index 6bf1fd93..00000000 --- a/engine/csharp_ref/Graphics/Sprite2d.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - -namespace wwtlib -{ - - class Sprite2d - { - public void Draw(RenderContext renderContext, PositionColoredTextured[] points, int count, - Texture texture, bool triangleStrips, double opacity) - { - if (VertexBuffer == null) - { - Create(points); - } - else - { - Update(points); - } - - if (texture == null) - { - ShapeSpriteShader.Use(renderContext, VertexBuffer); - renderContext.gl.drawArrays(triangleStrips ? GL.TRIANGLE_STRIP : GL.TRIANGLES, 0, points.Length); - - } - else - { - SpriteShader.Use(renderContext, VertexBuffer, texture != null ? texture.Texture2d : null); - renderContext.gl.drawArrays(triangleStrips ? GL.TRIANGLE_STRIP : GL.TRIANGLES, 0, points.Length); - } - } - - public WebGLBuffer VertexBuffer; - public int vertCount = 0; - - public void Create(PositionColoredTextured[] verts) - { - VertexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(verts.Length * 9); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionColoredTextured pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.DYNAMIC_DRAW); - } - public void Update(PositionColoredTextured[] verts) - { - if (vertCount < verts.Length) - { - Tile.PrepDevice.deleteBuffer(VertexBuffer); - Create(verts); - return; - } - - Tile.PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(verts.Length * 9); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionColoredTextured pt in verts) - { - buffer[index++] = (float)pt.Position.X; - buffer[index++] = (float)pt.Position.Y; - buffer[index++] = (float)pt.Position.Z; - buffer[index++] = (float)pt.Color.R / 255.0f; - buffer[index++] = (float)pt.Color.G / 255.0f; - buffer[index++] = (float)pt.Color.B / 255.0f; - buffer[index++] = (float)pt.Color.A / 255.0f; - buffer[index++] = (float)pt.Tu; - buffer[index++] = (float)pt.Tv; - } - - Tile.PrepDevice.bufferSubData(GL.ARRAY_BUFFER, 0, (WebGLArray)(Object)f32array ); - } - } -} diff --git a/engine/csharp_ref/Graphics/Tessellator.cs b/engine/csharp_ref/Graphics/Tessellator.cs deleted file mode 100644 index 242ab43c..00000000 --- a/engine/csharp_ref/Graphics/Tessellator.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using System.Collections.Generic; - - -namespace wwtlib -{ - public class Tessellator - { - public static List TesselateSimplePoly(List inputList) - { - List results = new List(); - - Tessellator tess = new Tessellator(); - - tess.Process(inputList, results); - - return results; - } - - - private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) - { - pntA.Normalize(); - pntB.Normalize(); - Vector3d cross = Vector3d.Cross(pntA, pntB); - - double dot = Vector3d.Dot(cross, pntTest); - - return dot > 0; - } - - private bool InsideTriangle(Vector3d pntA, Vector3d pntB, Vector3d pntC, Vector3d pntTest) - { - if (!IsLeftOfHalfSpace(pntA, pntB, pntTest)) - { - return false; - } - if (!IsLeftOfHalfSpace(pntB, pntC, pntTest)) - { - return false; - } - if (!IsLeftOfHalfSpace(pntC, pntA, pntTest)) - { - return false; - } - - return true; - } - - - bool CanClipEar(List poly, int u, int v, int w, int n, int[] verts) - { - int p; - - Vector3d a = poly[verts[u]].Copy(); - Vector3d b = poly[verts[v]].Copy(); - Vector3d c = poly[verts[w]].Copy(); - Vector3d P; - - Vector3d d = Vector3d.SubtractVectors(b, a); - d.Normalize(); - Vector3d e = Vector3d.SubtractVectors(b , c); - e.Normalize(); - - Vector3d g = Vector3d.Cross(d, e); - - Vector3d bn = b.Copy(); - bn.Normalize(); - - //Determin if convex edge - if (Vector3d.Dot(g, bn) > 0) - { - return false; - } - - - // Check for any interecting vertexies that would invalidate this ear - for (p = 0; p < n; p++) - { - if ((p == u) || (p == v) || (p == w)) - { - continue; - } - - P = poly[verts[p]].Copy(); - - // don;t Clip earth if other intersecting vertex - if (InsideTriangle(a, b, c, P)) - { - return false; - } - } - - return true; - } - - - public bool Process(List poly, List result) - { - - int n = poly.Count; - if (poly.Count < 3) - { - return false; - } - - int[] verts = new int[poly.Count]; - - - for (int i = 0; i < n; i++) - { - verts[i] = i; - } - - int nv = n; - - - int count = 2 * nv; - - for (int m = 0, v = nv - 1; nv > 2; ) - { - - if (0 >= (count--)) - { - // not enough ears to clip. Non-Simple Polygon - return false; - } - - - int u = v; - if (nv <= u) - { - u = 0; - } - - v = u + 1; - if (nv <= v) - { - v = 0; - } - - int w = v + 1; - if (nv <= w) - { - w = 0; - } - - if (CanClipEar(poly, u, v, w, nv, verts)) - { - int s, t; - - result.Add(verts[u]); - result.Add(verts[v]); - result.Add(verts[w]); - - m++; - - // remove clipped ear - for (s = v, t = v + 1; t < nv; s++, t++) - { - verts[s] = verts[t]; - } - nv--; - - count = 2 * nv; - } - } - return true; - } - } -} diff --git a/engine/csharp_ref/Graphics/Texture.cs b/engine/csharp_ref/Graphics/Texture.cs deleted file mode 100644 index d4e2a059..00000000 --- a/engine/csharp_ref/Graphics/Texture.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - -namespace wwtlib -{ - public class Texture : IDisposable - { - public ImageElement ImageElement = null; - public WebGLTexture Texture2d = null; - - public static WebGLTexture empty = null; - - public static WebGLTexture GetEmpty() - { - if (empty == null) - { - empty = Tile.PrepDevice.createTexture(); - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, empty); - Tile.PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 1, 1, 0, GL.RGBA, GL.UNSIGNED_BYTE, (System.Html.WebGLArray)(object)(new Uint8Array(new Byte[] { 0, 0, 0, 0 }))); - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, null); - } - - return empty; - } - - public Texture() - { - - } - - public static Texture FromUrl(string url) - { - Texture tex = new Texture(); - tex.Load(url); - - return tex; - } - - bool Downloading = false; - bool Ready = false; - bool Errored = false; - - public string URL = ""; - - public void CleanUp() - { - ImageElement = null; - Tile.PrepDevice.deleteTexture(Texture2d); - - } - - public void Dispose() - { - CleanUp(); - } - - public void Load(string url) - { - URL = url; - Script.Literal("if (typeof document === \"undefined\") { return; }"); - if (!Downloading) - { - Downloading = true; - ImageElement = (ImageElement)Document.CreateElement("img"); - CrossDomainImage xdomimg = (CrossDomainImage)(object)ImageElement; - - ImageElement.AddEventListener("load", delegate(ElementEvent e) - { - Ready = true; - Downloading = false; - Errored = false; - MakeTexture(); - }, false); - - ImageElement.AddEventListener("error", delegate(ElementEvent e) - { - if (!ImageElement.HasAttribute("proxyattempt")) - { - ImageElement.SetAttribute("proxyattempt", true); - string new_url = URLHelpers.singleton.activateProxy(URL); - - if (new_url != null) { // null => don't bother: we know that the proxy won't help - ImageElement.Src = new_url; - return; - } - } - - Downloading = false; - Ready = false; - Errored = true; - }, false); - - xdomimg.crossOrigin = "anonymous"; - ImageElement.Src = URL; - } - } - - public void MakeTexture() - { - if ( Tile.PrepDevice != null) - { - // PrepDevice.pixelStorei(GL.UNPACK_FLIP_Y_WEBGL, 1); - - try - { - Texture2d = Tile.PrepDevice.createTexture(); - - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, Texture2d); - - ImageElement image = ImageElement; - - // Before we bind resize to a power of two if nessesary so we can MIPMAP - if (!IsPowerOfTwo(ImageElement.Height) | !IsPowerOfTwo(ImageElement.Width)) - { - CanvasElement temp = (CanvasElement)Document.CreateElement("canvas"); - temp.Height = FitPowerOfTwo(image.Height); - temp.Width = FitPowerOfTwo(image.Width); - CanvasContext2D ctx = (CanvasContext2D)temp.GetContext(Rendering.Render2D); - ctx.DrawImage(image, 0, 0, temp.Width, temp.Height); - //Substitute the resized image - image = (ImageElement)(Element)temp; - } - - - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, image); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_NEAREST); - Tile.PrepDevice.generateMipmap(GL.TEXTURE_2D); - - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, null); - } - catch - { - Errored = true; - - } - } - } - - - public static bool IsPowerOfTwo(int val) - { - return (val & (val - 1)) == 0; - } - - public static int FitPowerOfTwo(int val) - { - val--; - - for(int i = 1; i<32;i<<=1) - { - val = val | val >> i; - } - return val + 1; - } - - - } -} diff --git a/engine/csharp_ref/Grids.cs b/engine/csharp_ref/Grids.cs deleted file mode 100644 index f41ec30d..00000000 --- a/engine/csharp_ref/Grids.cs +++ /dev/null @@ -1,1416 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - - - -namespace wwtlib -{ - public class Grids - { - - static PositionTextureVertexBuffer galaxyImageVertexBuffer; - static WebGLBuffer galaxyImageIndexBuffer = null; - static int galaxyImageTriangleCount = 0; - static Texture milkyWayImage = null; - - private static void CreateGalaxyImage(RenderContext renderContext) - { - if (milkyWayImage == null) - { - milkyWayImage = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("milkywaybar.jpg")); - } - - - int subdivs = 50; - - double lat, lng; - - int index = 0; - double latMin = 64; - double latMax = -64; - double lngMin = -64; - double lngMax = 64; - - //// Create a vertex buffer - galaxyImageVertexBuffer = new PositionTextureVertexBuffer((subdivs + 1) * (subdivs + 1)); - PositionTexture[] verts = (PositionTexture[])galaxyImageVertexBuffer.Lock(); - - int x1, y1; - double latDegrees = latMax - latMin; - double lngDegrees = lngMax - lngMin; - double scaleFactor = 60800000.0; - double ecliptic = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI; - Vector3d point; - - double textureStepX = 1.0f / subdivs; - double textureStepY = 1.0f / subdivs; - for (y1 = 0; y1 <= subdivs; y1++) - { - - if (y1 != subdivs) - { - lat = latMax - (textureStepY * latDegrees * (double)y1); - } - else - { - lat = latMin; - } - - for (x1 = 0; x1 <= subdivs; x1++) - { - if (x1 != subdivs) - { - lng = lngMin + (textureStepX * lngDegrees * (double)x1); - } - else - { - lng = lngMax; - } - index = y1 * (subdivs + 1) + x1; - point = Vector3d.Create(lng * scaleFactor, 0, (lat - 28) * scaleFactor); - point.RotateY(213.0 / 180 * Math.PI); - point.RotateZ((-62.87175) / 180 * Math.PI); - point.RotateY((-192.8595083) / 180 * Math.PI); - point.RotateX(ecliptic); - verts[index] = PositionTexture.CreatePosRaw(point, (float)(1f - x1 * textureStepX), (float)(/*1f - */(y1 * textureStepY))); - //verts[index].Position = point; - //verts[index].Tu = (float)(1f - x1 * textureStepX); - //verts[index].Tv = (float)(/*1f - */(y1 * textureStepY)); - } - } - galaxyImageVertexBuffer.Unlock(); - galaxyImageTriangleCount = (subdivs) * (subdivs) * 2; - Uint16Array ui16array = new Uint16Array(subdivs * subdivs * 6); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - - for (y1 = 0; y1 < subdivs; y1++) - { - for (x1 = 0; x1 < subdivs; x1++) - { - index = (y1 * subdivs * 6) + 6 * x1; - // First triangle in quad - indexArray[index] = (ushort)(y1 * (subdivs + 1) + x1); - indexArray[index + 2] = (ushort)((y1 + 1) * (subdivs + 1) + x1); - indexArray[index + 1] = (ushort)(y1 * (subdivs + 1) + (x1 + 1)); - - // Second triangle in quad - indexArray[index + 3] = (ushort)(y1 * (subdivs + 1) + (x1 + 1)); - indexArray[index + 5] = (ushort)((y1 + 1) * (subdivs + 1) + x1); - indexArray[index + 4] = (ushort)((y1 + 1) * (subdivs + 1) + (x1 + 1)); - } - } - galaxyImageIndexBuffer = Tile.PrepDevice.createBuffer(); - Tile.PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, galaxyImageIndexBuffer); - Tile.PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - } - - public static void DrawGalaxyImage(RenderContext renderContext, float opacity) - { - if (galaxyImageIndexBuffer == null) - { - CreateGalaxyImage(renderContext); - } - - // renderContext.setRasterizerState(TriangleCullMode.Off); - // renderContext.BlendMode = BlendMode.Additive; - - double zoom = renderContext.ViewCamera.Zoom; - double log = Math.Log(Math.Max(1, zoom)) / Math.Log(4); - double distAlpha = ((log) - 14) * 128; - - int alpha = (int)(Math.Min(255, (int)Math.Max(0, distAlpha)) * opacity); - - // renderContext.Device.ImmediateContext.PixelShader.SetShaderResource(0, milkyWayImage.ResourceView); - //renderContext.SetupBasicEffect(BasicEffect.TextureColorOpacity, opacity, Color.FromArgb(alpha, alpha, alpha, alpha)); - //if (galaxyImageInputLayout == null) - //{ - // galaxyImageInputLayout = new SharpDX.Direct3D11.InputLayout(device, renderContext.Shader.InputSignature, new[] - // { - // new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0), - // new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0), - // }); - //} - - //renderContext.Device.ImmediateContext.InputAssembler.InputLayout = galaxyImageInputLayout; - //renderContext.SetVertexBuffer(galaxyImageVertexBuffer); - //renderContext.SetIndexBuffer(galaxyImageIndexBuffer); - //device.ImmediateContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; - //renderContext.PreDraw(); - //device.ImmediateContext.DrawIndexed(galaxyImageTriangleCount * 3, 0, 0); - - - ImageShader.Use(renderContext, galaxyImageVertexBuffer.VertexBuffer, galaxyImageIndexBuffer, milkyWayImage.Texture2d, (float)opacity, true); - renderContext.gl.drawElements(GL.TRIANGLES, galaxyImageTriangleCount * 3, GL.UNSIGNED_SHORT, 0); - } - - public static void DrawStars3D(RenderContext renderContext, float opacity) - { - double zoom = renderContext.ViewCamera.Zoom; - - double distAlpha = Math.Max(Math.Min(255, (Math.Log(zoom) - 15.5) * 40.8), 0); - - int alpha = Math.Min(255, Math.Max(0, (int)distAlpha)); - if (alpha > 254) - { - return; - } - - - alpha = (int)((255 - alpha) * opacity); - - if (starSprites == null) - { - InitStarVertexBuffer(renderContext); - } - - if (starSprites != null) - { - starSprites.Draw(renderContext, alpha / 255.0f, false); - } - } - - static PointList starSprites = null; - - static int starCount = 0; - static bool starsDownloading = false; - - public static void InitStarVertexBuffer(RenderContext renderContext) - { - if (!starsDownloading && !WWTControl.Singleton.FreestandingMode) - { - GetStarFile(URLHelpers.singleton.coreStaticUrl("wwtweb/catalog.aspx?Q=hipparcos")); - starsDownloading = true; - } - - if (starSprites == null && starCount > 0) - { - double ecliptic = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI; - - int count = stars.Count; - starCount = count; - - starSprites = new PointList(renderContext); - starSprites.DepthBuffered = false; - starSprites.ShowFarSide = true; - foreach (Star star in stars) - { - Vector3d pos = Coordinates.RADecTo3dAu(star.RA, star.Dec, star.Distance); - pos.RotateX(ecliptic); - star.Position = pos; - double radDec = (1200000) / Math.Pow(1.6, star.AbsoluteMagnitude); - starSprites.AddPoint(pos, star.Col, new Dates(0, 1), (float)radDec * 100); - } - } - } - - static List stars = null; - static Dictionary hipparcosIndex = new Dictionary(); - static double limitingMagnitude = 16; - static public void InitializeStarDB(string text) - { - - if (stars == null) - { - if (stars == null) - { - stars = new List(); - string[] rows = text.Split("\r\n"); - Star star; - foreach (string row in rows) - { - string line = row; - - star = new Star(line); - if (star.Magnitude < limitingMagnitude && star.Par > .001) - { - stars.Add(star); - hipparcosIndex[star.ID] = star; - } - } - - //// Write Binary file - //DumpStarBinaryFile(@"c:\hip.bin"); - starCount = stars.Count; - } - } - } - - static WebFile webFileStar; - - public static void GetStarFile(string url) - { - webFileStar = new WebFile(url); - webFileStar.OnStateChange = StarFileStateChange; - webFileStar.Send(); - } - - public static void StarFileStateChange() - { - if (webFileStar.State == StateType.Error) - { - Script.Literal("alert({0})", webFileStar.Message); - } - else if (webFileStar.State == StateType.Received) - { - InitializeStarDB(webFileStar.GetText()); - } - - } - - static WebFile webFileGalaxy; - - public static void GetGalaxyFile(string url) - { - webFileGalaxy = new WebFile(url); - webFileGalaxy.ResponseType = "blob"; - webFileGalaxy.OnStateChange = GalaxyFileStateChange; - webFileGalaxy.Send(); - } - - public static void GalaxyFileStateChange() - { - if (webFileGalaxy.State == StateType.Error) - { - Script.Literal("alert({0})", webFileGalaxy.Message); - } - else if (webFileGalaxy.State == StateType.Received) - { - System.Html.Data.Files.Blob mainBlob = (System.Html.Data.Files.Blob)webFileGalaxy.GetBlob(); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e) - { - BinaryReader br = new BinaryReader(new Uint8Array(chunck.Result)); - - - InitializeCosmos(br); - }; - chunck.ReadAsArrayBuffer(mainBlob); - } - } - - - static PointList[] cosmosSprites; - static Texture[] galaxyTextures = null; - static int[] galaxyVertexCounts = null; - static bool largeSet = true; - static bool cosmosReady = false; - public static void DrawCosmos3D(RenderContext renderContext, float opacity) - { - GL device = renderContext.gl; - double zoom = renderContext.ViewCamera.Zoom; - double distAlpha = ((Math.Log(Math.Max(1, zoom)) / Math.Log(4)) - 15.5) * 90; - - int alpha = Math.Min(255, Math.Max(0, (int)distAlpha)); - - if (alpha < 3) - { - return; - } - - InitCosmosVertexBuffer(); - - if (galaxyTextures == null) - { - if (largeSet) - { - galaxyTextures = new Texture[256]; - for (int i = 0; i < 256; i++) - { - string num = i.ToString(); - - while (num.Length < 4) - { - num = "0" + num; - } - - string name = string.Format(URLHelpers.singleton.engineAssetUrl("galimg/gal_{0}.jpg"), num); - - galaxyTextures[i] = Planets.LoadPlanetTexture(name); - - } - } - } - - if (cosmosReady) - { - int count = 256; - for (int i = 0; i < count; i++) - { - - //cosmosSprites[i].MinPointSize = 1; - cosmosSprites[i].DrawTextured(renderContext, galaxyTextures[i].Texture2d, (alpha * opacity) / 255.0f); - // cosmosSprites[i].Draw(renderContext, (alpha * opacity) / 255.0f, false); - } - } - - } - - - public static void InitCosmosVertexBuffer() - { - - if (cosmosSprites == null) - { - DownloadCosmosFile(); - } - - } - - private static void CreateCosmosVertexBuffer(RenderContext renderContext) - { - GL device = Tile.PrepDevice; - - int bucketCount = 256; - - if (cosmosSprites != null) - { - for (int ij = 0; ij < bucketCount; ij++) - { - if (cosmosSprites[ij] != null) - { - cosmosSprites[ij] = null; - } - } - } - cosmosSprites = null; - double ecliptic = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI; - cosmosSprites = new PointList[bucketCount]; - - int[] indexList = new int[bucketCount]; - for (int i = 0; i < bucketCount; i++) - { - int count = galaxyVertexCounts[i]; - cosmosSprites[i] = new PointList(renderContext); - cosmosSprites[i].DepthBuffered = false; - cosmosSprites[i].ShowFarSide = true; - indexList[i] = 0; - } - - foreach (Galaxy galaxy in cosmos) - { - int bucket = galaxy.eTypeBucket; - int index = indexList[bucket]; - - Vector3d pos = Coordinates.RADecTo3dAu(galaxy.RA, galaxy.Dec, (galaxy.Distance * UiTools.AuPerParsec * 1000000.0) / .73); - pos.RotateX(ecliptic); - galaxy.Position = pos; - cosmosSprites[bucket].AddPoint(pos, Colors.White, new Dates(0, 1), (float)(1000000000f * galaxy.Size * 100)); - indexList[bucket]++; - } - - cosmosReady = true; - } - - - static List cosmos = null; - public static void InitializeCosmos(BinaryReader br) - { - int max = (int)Math.Pow(100, 2.849485002); - - if (cosmos == null) - { - galaxyVertexCounts = new int[largeSet ? 256 : 20]; - if (cosmos == null) - { - cosmos = new List(); - - Galaxy galaxy; - try - { - int count = 0; - while (br.Position < br.Length) - { - galaxy = new Galaxy(br); - cosmos.Add(galaxy); - galaxyVertexCounts[galaxy.eTypeBucket]++; - count++; - } - } - catch - { - } - br.Close(); - } - - CreateCosmosVertexBuffer(WWTControl.Singleton.RenderContext); - } - } - - static bool downloadingGalaxy = false; - - internal static bool DownloadCosmosFile() - { - if (!downloadingGalaxy && !WWTControl.Singleton.FreestandingMode) - { - GetGalaxyFile(URLHelpers.singleton.coreStaticUrl("wwtweb/catalog.aspx?Q=cosmosnewbin")); - downloadingGalaxy = true; - } - return false; - } - - - static SimpleLineList equLineList; - public static bool DrawEquitorialGrid(RenderContext renderContext, float opacity, Color drawColor) - { - if (equLineList == null) - { - equLineList = new SimpleLineList(); - equLineList.DepthBuffered = false; - - for (double hour = 0; hour < 24; hour++) - { - for (double dec = -80; dec < 80; dec += 2) - { - equLineList.AddLine(Coordinates.RADecTo3dAu(hour, dec, 1), Coordinates.RADecTo3dAu(hour, dec + 2, 1)); - } - } - - - for (double dec = -80; dec <= 80; dec += 10) - { - for (double hour = 0; hour < 23.8; hour += .2) - { - - equLineList.AddLine(Coordinates.RADecTo3dAu(hour, dec, 1), Coordinates.RADecTo3dAu(hour + .2, dec, 1)); - //todo fix for color bright - } - } - - - int counter = 0; - for (double ra = 0; ra < 24; ra += .25) - { - double dec = 0.5; - - switch (counter % 4) - { - case 0: - counter++; - continue; - case 3: - case 1: - dec = .25; - break; - } - counter++; - - equLineList.AddLine(Coordinates.RADecTo3dAu(ra, dec, 1), Coordinates.RADecTo3dAu(ra, -dec, 1)); - } - counter = 0; - for (double ra = 0; ra < 24; ra += 3) - { - counter = 0; - for (double dec = -80; dec <= 80; dec += 1) - { - double width = 0.5 / 30; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - width = .5 / 15; - break; - } - - counter++; - - equLineList.AddLine(Coordinates.RADecTo3dAu(ra + width, dec, 1), Coordinates.RADecTo3dAu(ra - width, dec, 1)); - } - } - } - - equLineList.DrawLines(renderContext, opacity, drawColor); - - return true; - } - - - static Text3dBatch EquTextBatch; - public static bool DrawEquitorialGridText(RenderContext renderContext, float opacity, Color drawColor) - { - MakeEquitorialGridText(); - - EquTextBatch.Draw(renderContext, opacity, drawColor); - return true; - } - - private static void MakeEquitorialGridText() - { - if (EquTextBatch == null) - { - EquTextBatch = new Text3dBatch(30); - int index = 0; - - for (int ra = 0; ra < 24; ra++) - { - string text = ra.ToString() + " hr"; - if (ra < 10) - { - text = " " + ra.ToString() + " hr"; - } - - EquTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(ra + 0.005, 0.4, 1), Coordinates.RADecTo3dAu(ra + 0.005, 0.5, 1), text, 45, .00018)); - } - - index = 0; - for (double ra = 0; ra < 24; ra += 3) - { - - for (double dec = -80; dec <= 80; dec += 10) - { - if (dec == 0) - { - continue; - } - string text = dec.ToString(); - if (dec > 0) - { - text = " +" + dec.ToString(); - EquTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(ra, dec - .4, 1), Coordinates.RADecTo3dAu(ra, dec - .3, 1), text, 45, .00018)); - } - else - { - text = " - " + text.Substr(1); - EquTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(ra, dec + .4, 1), Coordinates.RADecTo3dAu(ra, dec + .5, 1), text, 45, .00018)); - } - - index++; - } - } - } - } - - - static int EclipticCount = 0; - static int EclipticYear = 0; - - static double[] monthDays = new double[] { 31, 28.2421, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - static string[] monthNames = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; - - static SimpleLineList eclipticOverviewLineList; - - - public static bool DrawEcliptic(RenderContext renderContext, float opacity, Color drawColor) - { - Color col = drawColor; - - int year = SpaceTimeController.Now.GetUTCFullYear(); - - if (eclipticOverviewLineList == null || year != EclipticYear) - { - - - if (eclipticOverviewLineList != null) - { - eclipticOverviewLineList.Clear(); - eclipticOverviewLineList = null; - } - - EclipticYear = year; - double obliquity = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow); - Matrix3d mat = Matrix3d.RotationX((-obliquity / 360.0 * (Math.PI * 2))); - - - double daysPerYear = 365.25; - - - - if (DT.IsLeap(year, true)) - { - monthDays[1] = 29; - - daysPerYear = 366; - } - else - { - monthDays[1] = 28; - daysPerYear = 365; - } - int count = 2 * (int)daysPerYear; - EclipticCount = (int)daysPerYear; - double jYear = SpaceTimeController.UtcToJulian(new Date(year, 0, 1, 12, 0, 0)); - - - int index = 0; - double d = 0; - - eclipticOverviewLineList = new SimpleLineList(); - eclipticOverviewLineList.DepthBuffered = false; - for (int m = 0; m < 12; m++) - { - int daysThisMonth = (int)monthDays[m]; - for (int i = 0; i < daysThisMonth; i++) - { - AstroRaDec sunRaDec = Planets.GetPlanetLocationJD("Sun", jYear); - - COR sunEcliptic = CT.Eq2Ec(sunRaDec.RA, sunRaDec.Dec, obliquity); - - d = sunEcliptic.X; - - double width = .005f; - if (i == 0) - { - width = .01f; - } - double dd = d;// +180; - - eclipticOverviewLineList.AddLine( - Vector3d.TransformCoordinate(Vector3d.Create((Math.Cos((dd * Math.PI * 2.0) / 360)), - width, - (Math.Sin((dd * Math.PI * 2.0) / 360))), mat), - Vector3d.TransformCoordinate(Vector3d.Create((Math.Cos((dd * Math.PI * 2.0) / 360)), - -width, - (Math.Sin((dd * Math.PI * 2.0) / 360))), mat) - ); - - - index++; - jYear += 1; - } - d += monthDays[m]; - } - - } - - - eclipticOverviewLineList.DrawLines(renderContext, opacity, drawColor); - return true; - } - - static int EclipticTextYear = 0; - static Text3dBatch EclipOvTextBatch; - public static bool DrawEclipticText(RenderContext renderContext, float opacity, Color drawColor) - { - MakeEclipticText(); - - EclipOvTextBatch.Draw(renderContext, opacity, drawColor); - - return true; - } - - private static void MakeEclipticText() - { - int year = SpaceTimeController.Now.GetUTCFullYear(); - - if (EclipOvTextBatch == null) - { - EclipOvTextBatch = new Text3dBatch(80); - - EclipticTextYear = year; - double obliquity = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow); - Matrix3d mat = Matrix3d.RotationX((-obliquity / 360.0 * (Math.PI * 2))); - - double daysPerYear = 365.25; - - if (DT.IsLeap(year, true)) - { - monthDays[1] = 29; - - daysPerYear = 366; - } - else - { - monthDays[1] = 28; - daysPerYear = 365; - } - int count = 2 * (int)daysPerYear; - EclipticCount = (int)daysPerYear; - double jYear = SpaceTimeController.UtcToJulian(new Date(year, 0, 1, 12, 0, 0)); - - - int index = 0; - double d = 0; - - for (int m = 0; m < 12; m++) - { - int daysThisMonth = (int)monthDays[m]; - for (int i = 0; i < daysThisMonth; i++) - { - AstroRaDec sunRaDec = Planets.GetPlanetLocationJD("Sun", jYear); - - COR sunEcliptic = CT.Eq2Ec(sunRaDec.RA, sunRaDec.Dec, obliquity); - - d = sunEcliptic.X; - - double dd = d;// +180; - - if (i == Math.Floor(daysThisMonth / 2.0)) - { - Vector3d center = Vector3d.TransformCoordinate(Vector3d.Create((Math.Cos((dd * Math.PI * 2.0) / 360)), - .025f, - (Math.Sin((dd * Math.PI * 2.0) / 360))), mat); - Vector3d up = Vector3d.TransformCoordinate(Vector3d.Create((Math.Cos((dd * Math.PI * 2.0) / 360)), - .045f, - (Math.Sin((dd * Math.PI * 2.0) / 360))), mat); - up.Subtract(center); - - up.Normalize(); - EclipOvTextBatch.Add(new Text3d(center, up, monthNames[m], 80, .000159375)); - - } - - - index++; - - index++; - jYear += 1; - } - d += monthDays[m]; - } - } - } - - - static SimpleLineList precLineList; - - static Text3dBatch PrecTextBatch; - public static bool DrawPrecessionChart(RenderContext renderContext, float opacity, Color drawColor) - { - MakePrecessionChart(); - - PrecTextBatch.Draw(renderContext, opacity, drawColor); - - precLineList.DrawLines(renderContext, opacity, drawColor); - - return true; - } - - private static void MakePrecessionChart() - { - double obliquity = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow); - Matrix3d mat = Matrix3d.RotationX((obliquity / 360.0 * (Math.PI * 2))); - Color col = Colors.White; - if (precLineList == null) - { - precLineList = new SimpleLineList(); - precLineList.DepthBuffered = false; - - for (double l = 0; l < 360; l++) - { - double b = 90 - obliquity; - precLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu((l + 1) / 15, b, 1), mat)); - } - - for (double l = -12000; l < 13000; l += 2000) - { - - double b = 90 - obliquity; - double p = -((l - 2000) / 25772 * 24) - 6; - precLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(p, b - .5, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(p, b + .5, 1), mat)); - } - } - if (PrecTextBatch == null) - { - PrecTextBatch = new Text3dBatch(50); - - for (double l = -12000; l < 13000; l += 2000) - { - double b = 90 - obliquity + 3; - - double p = -((l - 2000) / 25772 * 24) - 6; - string text = l.ToString(); - - if (l == 0) - { - b = 90 - obliquity + 2; - text = "1 CE"; - } - else if (l < 0) - { - - text = " " + (Math.Abs(l).ToString()) + " BCE"; - } - else - { - text = (Math.Abs(l).ToString()) + " CE"; - } - - if (text.Length == 9) - { - text = " " + text; - } - - PrecTextBatch.Add(new Text3d(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(p, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(p + .01, b, 1), mat), text, 75, .00015)); - } - } - return; - } - - static SimpleLineList altAzLineList; - public static bool DrawAltAzGrid(RenderContext renderContext, float opacity, Color drawColor) - { - - - Coordinates zenithAltAz = new Coordinates(0, 0); - Coordinates zenith = Coordinates.HorizonToEquitorial(zenithAltAz, SpaceTimeController.Location, SpaceTimeController.Now); - - double raPart = -((zenith.RA + 6) / 24.0 * (Math.PI * 2)); - double decPart = -(((zenith.Dec)) / 360.0 * (Math.PI * 2)); - string raText = Coordinates.FormatDMS(zenith.RA); - Matrix3d mat = Matrix3d.RotationY((float)-raPart); - mat.Multiply(Matrix3d.RotationX((float)decPart)); - mat.Invert(); - - if (altAzLineList == null) - { - altAzLineList = new SimpleLineList(); - altAzLineList.DepthBuffered = false; - - for (double l = 0; l < 360; l += 10) - { - for (double b = -80; b < 80; b += 2) - { - altAzLineList.AddLine(Coordinates.RADecTo3dAu(l / 15, b, 1), Coordinates.RADecTo3dAu(l / 15, b + 2, 1)); - } - } - - for (double b = -80; b <= 80; b += 10) - { - for (double l = 0; l < 360; l += 5) - { - altAzLineList.AddLine(Coordinates.RADecTo3dAu(l / 15, b, 1), Coordinates.RADecTo3dAu((l + 5) / 15, b, 1)); - } - } - - int counter = 0; - for (double l = 0; l < 360; l += 1) - { - - double b = 0.25; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - b = .5; - break; - } - counter++; - - altAzLineList.AddLine(Coordinates.RADecTo3dAu(l / 15, b, 1), Coordinates.RADecTo3dAu(l / 15, -b, 1)); - } - - counter = 0; - for (double l = 0; l < 360; l += 90) - { - counter = 0; - for (double b = -80; b <= 80; b += 1) - { - double width = 0.5 / 2; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - width = .5; - break; - } - counter++; - - altAzLineList.AddLine(Coordinates.RADecTo3dAu((l + width) / 15, b, 1), Coordinates.RADecTo3dAu((l - width) / 15, b, 1)); - } - } - } - - Matrix3d matOldWorld = renderContext.World.Clone(); - Matrix3d matOldWorldBase = renderContext.WorldBase.Clone(); - renderContext.WorldBase = Matrix3d.MultiplyMatrix(mat, renderContext.World); - renderContext.World = renderContext.WorldBase.Clone(); - renderContext.MakeFrustum(); - - altAzLineList.ViewTransform = Matrix3d.InvertMatrix(mat); - - altAzLineList.DrawLines(renderContext, opacity, drawColor); - - renderContext.WorldBase = matOldWorldBase; - renderContext.World = matOldWorld; - renderContext.MakeFrustum(); - return true; - } - - static Text3dBatch AltAzTextBatch; - public static bool DrawAltAzGridText(RenderContext renderContext, float opacity, Color drawColor) - { - Coordinates zenithAltAz = new Coordinates(0, 0); - Coordinates zenith = Coordinates.HorizonToEquitorial(zenithAltAz, SpaceTimeController.Location, SpaceTimeController.Now); - - double raPart = -((zenith.RA - 6) / 24.0 * (Math.PI * 2)); - double decPart = -(((zenith.Dec)) / 360.0 * (Math.PI * 2)); - string raText = Coordinates.FormatDMS(zenith.RA); - Matrix3d mat = Matrix3d.RotationY((float)-raPart - Math.PI); - mat.Multiply(Matrix3d.RotationX((float)decPart)); - mat.Invert(); - - MakeAltAzGridText(); - - - Matrix3d matOldWorld = renderContext.World.Clone(); - Matrix3d matOldWorldBase = renderContext.WorldBase.Clone(); - - renderContext.WorldBase = Matrix3d.MultiplyMatrix(mat, renderContext.World); - renderContext.World = renderContext.WorldBase.Clone(); - renderContext.MakeFrustum(); - - AltAzTextBatch.ViewTransform = Matrix3d.InvertMatrix(mat); - AltAzTextBatch.Draw(renderContext, opacity, drawColor); - - renderContext.WorldBase = matOldWorldBase; - renderContext.World = matOldWorld; - renderContext.MakeFrustum(); - return true; - } - - private static void MakeAltAzGridText() - { - Color drawColor = Colors.White; - - int index = 0; - if (AltAzTextBatch == null) - { - AltAzTextBatch = new Text3dBatch(30); - for (double l = 0; l < 360; l += 10) - { - string text = " " + l.ToString(); - if (l < 10) - { - text = " " + l.ToString(); - } - else if (l < 100) - { - text = " " + l.ToString(); - } - double lc = 360 - l; - AltAzTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(lc / 15 - 6, .4, 1), Coordinates.RADecTo3dAu(lc / 15 - 6, .5, 1), text, 75, .00018)); - } - - index = 0; - for (double l = 0; l < 360; l += 90) - { - - for (double b = -80; b <= 80; b += 10) - { - if (b == 0) - { - continue; - } - string text = b.ToString(); - if (b > 0) - { - text = " +" + b.ToString(); - AltAzTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(l / 15, b - .4, 1), Coordinates.RADecTo3dAu(l / 15, b - .3, 1), text, 75, .00018)); - } - else - { - text = " - " + text.Substr(1); - AltAzTextBatch.Add(new Text3d(Coordinates.RADecTo3dAu(l / 15, b + .4, 1), Coordinates.RADecTo3dAu(l / 15, b + .5, 1), text, 75, .00018)); - } - index++; - } - } - } - return; - } - - static SimpleLineList eclipticLineList; - - public static bool DrawEclipticGrid(RenderContext renderContext, float opacity, Color drawColor) - { - if (eclipticLineList == null) - { - eclipticLineList = new SimpleLineList(); - eclipticLineList.DepthBuffered = false; - - double obliquity = Coordinates.MeanObliquityOfEcliptic(2451545); - Matrix3d mat = Matrix3d.RotationX((-obliquity / 360.0 * (Math.PI * 2))); - - - for (double l = 0; l < 360; l += 10) - { - for (double b = -80; b < 80; b += 2) - { - eclipticLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b + 2, 1), mat)); - } - } - - for (double b = -80; b <= 80; b += 10) - { - for (double l = 0; l < 360; l += 5) - { - eclipticLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu((l + 5) / 15, b, 1), mat)); - } - } - - int counter = 0; - for (double l = 0; l < 360; l += 1) - { - - double b = 0.25; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - b = .5; - break; - } - counter++; - - eclipticLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, -b, 1), mat)); - - } - - counter = 0; - for (double l = 0; l < 360; l += 90) - { - counter = 0; - for (double b = -80; b <= 80; b += 1) - { - double width = 0.5 / 2; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - width = .5; - break; - } - counter++; - - eclipticLineList.AddLine(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu((l + width) / 15, b, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu((l - width) / 15, b, 1), mat)); - } - } - } - - eclipticLineList.DrawLines(renderContext, opacity, drawColor); - - return true; - } - static Text3dBatch EclipticTextBatch; - public static bool DrawEclipticGridText(RenderContext renderContext, float opacity, Color drawColor) - { - MakeEclipticGridText(); - - EclipticTextBatch.Draw(renderContext, opacity, drawColor); - - return true; - } - - private static void MakeEclipticGridText() - { - Color drawColor = Colors.White; - double obliquity = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow); - Matrix3d mat = Matrix3d.RotationX((float)(-obliquity / 360.0 * (Math.PI * 2))); - - if (EclipticTextBatch == null) - { - EclipticTextBatch = new Text3dBatch(30); - for (double l = 0; l < 360; l += 10) - { - string text = " " + l.ToString(); - if (l < 10) - { - text = " " + l.ToString(); - } - else if (l < 100) - { - text = " " + l.ToString(); - } - EclipticTextBatch.Add(new Text3d(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, .4, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, .5, 1), mat), text, 75, .00018)); - } - - for (double l = 0; l < 360; l += 90) - { - - for (double b = -80; b <= 80; b += 10) - { - if (b == 0) - { - continue; - } - string text = b.ToString(); - if (b > 0) - { - text = " +" + b.ToString(); - EclipticTextBatch.Add(new Text3d(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b - .4, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b - .3, 1), mat), text, 75, .00018)); - } - else - { - text = " - " + text.Substr(1); - EclipticTextBatch.Add(new Text3d(Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b + .4, 1), mat), Vector3d.TransformCoordinate(Coordinates.RADecTo3dAu(l / 15, b + .5, 1), mat), text, 75, .00018)); - } - } - } - } - return; - } - - static SimpleLineList galLineList; - - public static bool DrawGalacticGrid(RenderContext renderContext, float opacity, Color drawColor) - { - if (galLineList == null) - { - galLineList = new SimpleLineList(); - galLineList.DepthBuffered = false; - - for (double l = 0; l < 360; l += 10) - { - for (double b = -80; b < 80; b += 2) - { - galLineList.AddLine(Coordinates.GalacticTo3dDouble(l, b), Coordinates.GalacticTo3dDouble(l, b + 2)); - } - } - - for (double b = -80; b <= 80; b += 10) - { - for (double l = 0; l < 360; l += 5) - { - galLineList.AddLine(Coordinates.GalacticTo3dDouble(l, b), Coordinates.GalacticTo3dDouble(l + 5, b)); - } - } - - int counter = 0; - for (double l = 0; l < 360; l += 1) - { - - double b = 0.25; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - b = .5; - break; - } - counter++; - - galLineList.AddLine(Coordinates.GalacticTo3dDouble(l, b), Coordinates.GalacticTo3dDouble(l, -b)); - } - - counter = 0; - for (double l = 0; l < 360; l += 90) - { - counter = 0; - for (double b = -80; b <= 80; b += 1) - { - double width = 0.5 / 2; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - width = .5; - break; - } - counter++; - - galLineList.AddLine(Coordinates.GalacticTo3dDouble(l + width, b), Coordinates.GalacticTo3dDouble(l - width, b)); - } - } - } - - galLineList.DrawLines(renderContext, opacity, drawColor); - - return true; - } - static Text3dBatch GalTextBatch; - public static bool DrawGalacticGridText(RenderContext renderContext, float opacity, Color drawColor) - { - MakeGalacticGridText(); - - GalTextBatch.Draw(renderContext, opacity, drawColor); - return true; - } - - private static void MakeGalacticGridText() - { - if (GalTextBatch == null) - { - - GalTextBatch = new Text3dBatch(30); - for (int l = 0; l < 360; l += 10) - { - string text = " " + l.ToString(); - if (l < 10) - { - text = " " + l.ToString(); - } - else if (l < 100) - { - text = " " + l.ToString(); - } - GalTextBatch.Add(new Text3d(Coordinates.GalacticTo3dDouble(l, 0.4), Coordinates.GalacticTo3dDouble(l, 0.5), text, 75, .00018)); - } - - for (double l = 0; l < 360; l += 90) - { - - for (double b = -80; b <= 80; b += 10) - { - if (b == 0) - { - continue; - } - string text = b.ToString(); - if (b > 0) - { - text = " +" + b.ToString(); - GalTextBatch.Add(new Text3d(Coordinates.GalacticTo3dDouble(l, b - .4), Coordinates.GalacticTo3dDouble(l, b - .3), text, 75, .00018)); - } - else - { - text = " - " + text.Substr(1); - GalTextBatch.Add(new Text3d(Coordinates.GalacticTo3dDouble(l, b + .4), Coordinates.GalacticTo3dDouble(l, b + .5), text, 75, .00018)); - } - } - } - } - } - - /// - /// Planet Grids - /// - static SimpleLineList planetLineList; - - public static bool DrawPlanetGrid(RenderContext renderContext, float opacity, Color drawColor) - { - if (planetLineList == null) - { - planetLineList = new SimpleLineList(); - planetLineList.DepthBuffered = true; - - Color col = drawColor; - for (double lng = 0; lng < 360; lng += 10) - { - for (double lat = -80; lat < 80; lat += 2) - { - planetLineList.AddLine(Coordinates.GeoTo3dDouble(lat, lng), Coordinates.GeoTo3dDouble(lat + 2, lng)); - } - } - - for (double lat = -80; lat <= 80; lat += 10) - { - for (double l = 0; l < 360; l += 5) - { - planetLineList.AddLine(Coordinates.GeoTo3dDouble(lat, l), Coordinates.GeoTo3dDouble(lat, l + 5)); - } - } - - int counter = 0; - for (double lng = 0; lng < 360; lng += 1) - { - - double lat = 0.25; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - lat = .5; - break; - } - counter++; - - planetLineList.AddLine(Coordinates.GeoTo3dDouble(lat, lng), Coordinates.GeoTo3dDouble(-lat, lng)); - } - - counter = 0; - for (double lng = 0; lng < 360; lng += 90) - { - counter = 0; - for (double b = -80; b <= 80; b += 1) - { - double width = 0.5 / 2; - switch (counter % 10) - { - case 0: - counter++; - continue; - case 5: - width = .5; - break; - } - counter++; - - planetLineList.AddLine(Coordinates.GeoTo3dDouble(b, lng + width), Coordinates.GeoTo3dDouble(b, lng - width)); - } - } - } - planetLineList.aaFix = false; - planetLineList.DepthBuffered = true; - planetLineList.Sky = false; - planetLineList.DrawLines(renderContext, opacity, drawColor); - - return true; - } - static Text3dBatch PlanetTextBatch; - public static bool DrawPlanetGridText(RenderContext renderContext, float opacity, Color drawColor) - { - MakePlanetGridText(); - - PlanetTextBatch.Draw(renderContext, opacity, drawColor); - return true; - } - - private static void MakePlanetGridText() - { - if (PlanetTextBatch == null) - { - - PlanetTextBatch = new Text3dBatch(80); - for (int lng = -180; lng < 180; lng += 10) - { - string text = " " + lng.ToString(); - if (lng < 10) - { - text = " " + lng.ToString(); - } - else if (lng < 100) - { - text = " " + lng.ToString(); - } - PlanetTextBatch.Add(new Text3d(Coordinates.GeoTo3dDouble(0.4, lng), Coordinates.GeoTo3dDouble(0.5, lng), text, -80, .00006)); - } - - for (double lng = 0; lng < 360; lng += 90) - { - - for (double lat = -80; lat <= 80; lat += 10) - { - if (lat == 0) - { - continue; - } - string text = lat.ToString(); - if (lat > 0) - { - text = " +" + lat.ToString(); - PlanetTextBatch.Add(new Text3d(Coordinates.GeoTo3dDouble(lat - .4, lng), Coordinates.GeoTo3dDouble(lat - .3, lng), text, -80, .00006)); - } - else - { - text = " - " + text.Substring(1); - PlanetTextBatch.Add(new Text3d(Coordinates.GeoTo3dDouble(lat + .4, lng), Coordinates.GeoTo3dDouble(lat + .5, lng), text, -80, .00006)); - } - } - } - } - } - - // end planet Grids - - } -} diff --git a/engine/csharp_ref/HealpixTables.cs b/engine/csharp_ref/HealpixTables.cs deleted file mode 100644 index 89ec2b69..00000000 --- a/engine/csharp_ref/HealpixTables.cs +++ /dev/null @@ -1,98 +0,0 @@ -namespace wwtlib -{ - - public class HealpixTables - { - static readonly public short[] ctab ={ - 0,1,256,257,2,3,258,259,512,513,768,769,514,515,770,771,4,5,260,261,6,7,262, - 263,516,517,772,773,518,519,774,775,1024,1025,1280,1281,1026,1027,1282,1283, - 1536,1537,1792,1793,1538,1539,1794,1795,1028,1029,1284,1285,1030,1031,1286, - 1287,1540,1541,1796,1797,1542,1543,1798,1799,8,9,264,265,10,11,266,267,520, - 521,776,777,522,523,778,779,12,13,268,269,14,15,270,271,524,525,780,781,526, - 527,782,783,1032,1033,1288,1289,1034,1035,1290,1291,1544,1545,1800,1801,1546, - 1547,1802,1803,1036,1037,1292,1293,1038,1039,1294,1295,1548,1549,1804,1805, - 1550,1551,1806,1807,2048,2049,2304,2305,2050,2051,2306,2307,2560,2561,2816, - 2817,2562,2563,2818,2819,2052,2053,2308,2309,2054,2055,2310,2311,2564,2565, - 2820,2821,2566,2567,2822,2823,3072,3073,3328,3329,3074,3075,3330,3331,3584, - 3585,3840,3841,3586,3587,3842,3843,3076,3077,3332,3333,3078,3079,3334,3335, - 3588,3589,3844,3845,3590,3591,3846,3847,2056,2057,2312,2313,2058,2059,2314, - 2315,2568,2569,2824,2825,2570,2571,2826,2827,2060,2061,2316,2317,2062,2063, - 2318,2319,2572,2573,2828,2829,2574,2575,2830,2831,3080,3081,3336,3337,3082, - 3083,3338,3339,3592,3593,3848,3849,3594,3595,3850,3851,3084,3085,3340,3341, - 3086,3087,3342,3343,3596,3597,3852,3853,3598,3599,3854,3855 }; - static readonly public short[] utab ={ - 0,1,4,5,16,17,20,21,64,65,68,69,80,81,84,85,256,257,260,261,272,273,276,277, - 320,321,324,325,336,337,340,341,1024,1025,1028,1029,1040,1041,1044,1045,1088, - 1089,1092,1093,1104,1105,1108,1109,1280,1281,1284,1285,1296,1297,1300,1301, - 1344,1345,1348,1349,1360,1361,1364,1365,4096,4097,4100,4101,4112,4113,4116, - 4117,4160,4161,4164,4165,4176,4177,4180,4181,4352,4353,4356,4357,4368,4369, - 4372,4373,4416,4417,4420,4421,4432,4433,4436,4437,5120,5121,5124,5125,5136, - 5137,5140,5141,5184,5185,5188,5189,5200,5201,5204,5205,5376,5377,5380,5381, - 5392,5393,5396,5397,5440,5441,5444,5445,5456,5457,5460,5461,16384,16385,16388, - 16389,16400,16401,16404,16405,16448,16449,16452,16453,16464,16465,16468,16469, - 16640,16641,16644,16645,16656,16657,16660,16661,16704,16705,16708,16709,16720, - 16721,16724,16725,17408,17409,17412,17413,17424,17425,17428,17429,17472,17473, - 17476,17477,17488,17489,17492,17493,17664,17665,17668,17669,17680,17681,17684, - 17685,17728,17729,17732,17733,17744,17745,17748,17749,20480,20481,20484,20485, - 20496,20497,20500,20501,20544,20545,20548,20549,20560,20561,20564,20565,20736, - 20737,20740,20741,20752,20753,20756,20757,20800,20801,20804,20805,20816,20817, - 20820,20821,21504,21505,21508,21509,21520,21521,21524,21525,21568,21569,21572, - 21573,21584,21585,21588,21589,21760,21761,21764,21765,21776,21777,21780,21781, - 21824,21825,21828,21829,21840,21841,21844,21845 }; - - // coordinate of the lowest corner of each face - static public byte[] jrll = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4 }; - static readonly public byte[] jpll = { 1, 3, 5, 7, 0, 2, 4, 6, 1, 3, 5, 7 }; - - static readonly public short[] xoffset = { -1, -1, 0, 1, 1, 1, 0, -1 }; - static readonly public short[] yoffset = { 0, 1, 1, 1, 0, -1, -1, -1 }; - //static readonly public short[,] facearray = - // { { 8, 9,10,11,-1,-1,-1,-1,10,11, 8, 9 }, // S - // { 5, 6, 7, 4, 8, 9,10,11, 9,10,11, 8 }, // SE - // { -1,-1,-1,-1, 5, 6, 7, 4,-1,-1,-1,-1 }, // E - // { 4, 5, 6, 7,11, 8, 9,10,11, 8, 9,10 }, // SW - // { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11 }, // center - // { 1, 2, 3, 0, 0, 1, 2, 3, 5, 6, 7, 4 }, // NE - // { -1,-1,-1,-1, 7, 4, 5, 6,-1,-1,-1,-1 }, // W - // { 3, 0, 1, 2, 3, 0, 1, 2, 4, 5, 6, 7 }, // NW - // { 2, 3, 0, 1,-1,-1,-1,-1, 0, 1, 2, 3 } }; // N - //static readonly public byte[,] swaparray = - // { { 0,0,3 }, // S - // { 0,0,6 }, // SE - // { 0,0,0 }, // E - // { 0,0,5 }, // SW - // { 0,0,0 }, // center - // { 5,0,0 }, // NE - // { 0,0,0 }, // W - // { 6,0,0 }, // NW - // { 3,0,0 } }; // N - - // static readonly protected List swap_cycle = new List() - // { - - // }; - - // static readonly protected int[,] swap_cycle = new int[,] { - //{}, - //{0,1,8,12,16,21,40}, - //{0,1,2,40,114}, - //{0,4,160,263}, - //{0,4,30,49,51,87,526,1027,1105,1387,1807,2637}, - //{0,8,10,18,39,74,146,307,452,4737}, - //{0,1,2,7,9,17,80,410,1526,1921,32859,33566,38931}, - //{0,5,6,10,12,24,27,95,372,494,924,1409,3492,4248,9137,66043,103369,156899}, - //{0,1,2,3,4,45,125,351,697,24337,102940,266194,341855,419857}, - //{0,1,2,3,9,16,1705,2082,2126,8177,12753,15410,52642,80493,83235,88387,99444, - // 1675361,2495125}, - //{0,2,6,8,9,11,20,50,93,152,183,2137,13671,44794,486954,741908,4803258, - // 5692573}, - //{0,1,5,6,44,53,470,2847,3433,4906,13654,14710,400447,1797382,2744492, - // 18775974,23541521}, - //{0,4,9,10,16,33,83,117,318,451,5759,10015,128975,171834,211256,347608, - // 1278690,2154097,2590798,3427694,5581717,21012301,27023976,72522811, - // 95032729,139166747,171822389}, - //{0,5,10,267,344,363,2968,3159,9083,18437,76602,147614,1246902,1593138, - // 2035574,6529391,9511830,11340287,29565945,281666026,677946848} }; - //} - } -} \ No newline at end of file diff --git a/engine/csharp_ref/HealpixTile.cs b/engine/csharp_ref/HealpixTile.cs deleted file mode 100644 index 83c8f127..00000000 --- a/engine/csharp_ref/HealpixTile.cs +++ /dev/null @@ -1,877 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - -namespace wwtlib -{ - - public class HealpixTile : Tile - { - public readonly int ipix; - - protected double[] demArray; - protected WebGLBuffer[] indexBuffer = new WebGLBuffer[4]; - - private List vertexList = null; - private readonly int nside; - private readonly int tileIndex = 0; - private readonly int face; - private readonly int faceX = 0; - private readonly int faceY = 0; - private int step; - private string url; - private bool subDivided = false; - private readonly List> catalogRows = new List>(); - private WebFile catalogData; - private static readonly Matrix3d galacticMatrix = Matrix3d.Create( - -0.0548755604024359, -0.4838350155267381, -0.873437090247923, 0, - -0.8676661489811610, 0.4559837762325372, -0.1980763734646737, 0, - 0.4941094279435681, 0.7469822444763707, -0.4448296299195045, 0, - 0, 0, 0, 1); - - public String URL - { - get - { - if (url == null) - { - url = GetUrl(dataset, Level, tileX, tileY); - return url; - } - else - { - return url; - } - } - } - - public HealpixTile(int level, int x, int y, Imageset dataset, Tile parent) - { - this.Level = level; - this.tileX = x; - this.tileY = y; - this.dataset = dataset; - DemEnabled = false; - if (level == 0) - { - this.nside = 4; - } - else - { - this.nside = Math.Pow(2, level + 1); - } - - if (parent == null) - { - this.face = x * 4 + y; - this.ipix = this.face; - } - else - { - this.Parent = parent; - HealpixTile parentTile = (HealpixTile)parent; - this.face = parentTile.face; - this.tileIndex = parentTile.tileIndex * 4 + y * 2 + x; - this.ipix = this.face * nside * nside / 4 + this.tileIndex; - this.faceX = parentTile.faceX * 2 + x; - this.faceY = parentTile.faceY * 2 + y; - } - - IsCatalogTile = dataset.HipsProperties.Properties.ContainsKey("dataproduct_type") - && dataset.HipsProperties.Properties["dataproduct_type"].ToLowerCase() == "catalog"; - // All healpix is inside out - //insideOut = true; - ComputeBoundingSphere(); - } - - private void ComputeBoundingSphere() - { - SetStep(); - CreateGeometry(null); - - Vector3d[] pointList = new Vector3d[vertexList.Count]; - for (int i = 0; i < vertexList.Count; i++) - { - pointList[i] = vertexList[i].Position; - } - CalcSphere(pointList); - SetCorners(); - } - - public override bool CreateGeometry(RenderContext renderContext) - { - if (vertexList != null) - { - return true; - } - vertexList = new List(); - - PopulateVertexList(vertexList, step); - - if (dataset.HipsProperties.Properties.ContainsKey("hips_frame") - && dataset.HipsProperties.Properties["hips_frame"] == "galactic") - { - for (int i = 0; i < vertexList.Count; i++) - { - PositionTexture vert = vertexList[i]; - galacticMatrix.MultiplyVector(vert.Position); - } - } - - - TriangleCount = step * step / 2; - Uint16Array ui16array = new Uint16Array(3 * TriangleCount); - UInt16[] indexArray = (UInt16[])(object)ui16array; - - if (!subDivided) - { - //if (vertexList == null) - //{ - // createGeometry(); - //} - - try - { - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(vertexList.Count * 5); - float[] buffer = (float[])(object)f32array; - int index = 0; - - foreach (PositionTexture vert in vertexList) - { - index = AddVertex(buffer, index, vert); - - } - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - - - - index = 0; - int offset = vertexList.Count / (4 * step); - - //0 0 = left - //1 0 = top - //1 1 = right - SetIndexBufferForQuadrant(indexArray, 0, 1); - if (step > 1) - { - SetIndexBufferForQuadrant(indexArray, 0, 0); - SetIndexBufferForQuadrant(indexArray, 1, 1); - SetIndexBufferForQuadrant(indexArray, 1, 0); - } - - } - catch (Exception exception) - { - - } - - //ReturnBuffers(); - } - - return true; - } - - private void SetIndexBufferForQuadrant(ushort[] indexArray, int x, int y) - { - int index = 0; - for (int i = x * step / 2; i < (step / 2) * (x + 1); i++) - { - for (int j = y * step / 2; j < (step / 2) * (y + 1); j++) - { - indexArray[index++] = (UInt16)(i * (step + 1) + j); - indexArray[index++] = (UInt16)(1 + i * (step + 1) + j); - indexArray[index++] = (UInt16)(step + 1 + i * (step + 1) + j); - indexArray[index++] = (UInt16)(1 + i * (step + 1) + j); - indexArray[index++] = (UInt16)(step + 1 + i * (step + 1) + j); - indexArray[index++] = (UInt16)(step + 2 + i * (step + 1) + j); - - } - } - ProcessIndexBuffer(indexArray, x * 2 + y); - } - - private string GetUrl(Imageset dataset, int level, int x, int y) - { - string extension = GetHipsFileExtension(); - - int tileTextureIndex = -1; - if (level == 0) - { - tileTextureIndex = this.face; - } - else - { - tileTextureIndex = this.face * nside * nside / 4 + this.tileIndex; - } - StringBuilder sb = new StringBuilder(); - - int subDirIndex = Math.Floor(tileTextureIndex / 10000) * 10000; - - return String.Format(dataset.Url, level.ToString(), subDirIndex.ToString(), tileTextureIndex.ToString() + extension); - } - - private string GetHipsFileExtension() - { - // The extension will contain either a space-separated list of types - // or a single type. We currently match preferred filetypes - // greedily. The extension must be exactly ".fits" in order to - // render correctly -- not only because of the greedy matching here, - // but because there are other parts of the code that check for an - // exact match. - - //prioritize transparent Png over other image formats - if (dataset.Extension.ToLowerCase().IndexOf("png") > -1) - { - return ".png"; - } - - // Check for either type - if (dataset.Extension.ToLowerCase().IndexOf("jpeg") > -1 || dataset.Extension.ToLowerCase().IndexOf("jpg") > -1) - { - return ".jpg"; - } - - if (dataset.Extension.ToLowerCase().IndexOf("tsv") > -1) - { - return ".tsv"; - } - - if (dataset.Extension.ToLowerCase().IndexOf("fits") > -1) - { - return ".fits"; - } - - //default to most common - return ".jpg"; - } - - - public override bool IsTileBigEnough(RenderContext renderContext) - { - if(dataset.DataSetType == ImageSetType.Planet) - { - double arcPixels = (180 / (Math.Pow(2, Level) * 4)); - return (renderContext.FovScale < arcPixels); - } else - { - double arcPixels = (3600 / (Math.Pow(2, Level) * 4)); - return (renderContext.FovScale < arcPixels); - } - } - - private Vector3d[] Boundaries(int x, int y, int step) - { - int nside = step * Math.Pow(2, Level); - Vector3d[] points = new Vector3d[4]; - Xyf xyf = Xyf.Create(x + faceX * step, y + faceY * step, face); - double dc = 0.5 / nside; - double xc = (xyf.ix + 0.5) / nside; - double yc = (xyf.iy + 0.5) / nside; - - points[0] = Fxyf.Create(xc + dc, yc + dc, xyf.face).toVec3(); - points[1] = Fxyf.Create(xc - dc, yc + dc, xyf.face).toVec3(); - points[2] = Fxyf.Create(xc - dc, yc - dc, xyf.face).toVec3(); - points[3] = Fxyf.Create(xc + dc, yc - dc, xyf.face).toVec3(); - - return points; - } - - - private void SetCorners() - { - Xyf xyf = Xyf.Create(tileX, tileY, face); - double dc = 0.5 / nside; - double xc = (xyf.ix + 0.5) / nside; - double yc = (xyf.iy + 0.5) / nside; - - TopLeft = Fxyf.Create(xc + dc, yc + dc, xyf.face).toVec3(); - BottomLeft = Fxyf.Create(xc - dc, yc + dc, xyf.face).toVec3(); - BottomRight = Fxyf.Create(xc - dc, yc - dc, xyf.face).toVec3(); - TopRight = Fxyf.Create(xc + dc, yc - dc, xyf.face).toVec3(); - } - - public override bool Draw3D(RenderContext renderContext, double opacity) - { - if (IsCatalogTile) - { - DrawCatalogTile(renderContext, opacity); - return true; - } - RenderedGeneration = CurrentRenderGeneration; - TilesTouched++; - - InViewFrustum = true; - bool onlyDrawChildren = false; - - if (!ReadyToRender) - { - if (!errored) - { - TileCache.AddTileToQueue(this); - return false; - } - - if (errored && Level < 3) //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv - { - onlyDrawChildren = true; - } - else - { - return false; - } - } - - - //if (!CreateGeometry(renderContext)) - //{ - // if (Level > 2) - // { - // return false; - // } - //} - - int partCount = this.TriangleCount; - TrianglesRendered += partCount; - - bool anythingToRender = false; - bool childRendered = false; - int childIndex = 0; - for (int y1 = 0; y1 < 2; y1++) - { - for (int x1 = 0; x1 < 2; x1++) - { - if (Level < dataset.Levels) - { - // make children - if (children[childIndex] == null) - { - children[childIndex] = TileCache.GetTile(Level + 1, x1, y1, dataset, this); - } - - if (children[childIndex].IsTileInFrustum(renderContext.Frustum)) - { - InViewFrustum = true; - if (children[childIndex].IsTileBigEnough(renderContext) || onlyDrawChildren) - { - //renderChildPart[childIndex].TargetState = true; - renderChildPart[childIndex].TargetState = !children[childIndex].Draw3D(renderContext, opacity); - if (renderChildPart[childIndex].TargetState) - { - childRendered = true; - } - } - else - { - renderChildPart[childIndex].TargetState = true; - } - } - else - { - renderChildPart[childIndex].TargetState = renderChildPart[childIndex].State = false; - } - } - else - { - renderChildPart[childIndex].State = true; - } - - ////if(childIndex != 0) - ////{ - //// renderChildPart[childIndex].TargetState = true; - //// anythingToRender = true; - ////} - - if (renderChildPart[childIndex].State == true) - { - anythingToRender = true; - } - - childIndex++; - } - } - - if (childRendered || anythingToRender) - { - RenderedAtOrBelowGeneration = CurrentRenderGeneration; - if (Parent != null) - { - Parent.RenderedAtOrBelowGeneration = RenderedAtOrBelowGeneration; - } - } - if (!anythingToRender) - { - return true; - } - - if (!CreateGeometry(renderContext)) - { - return false; - } - - if (onlyDrawChildren) - { - return true; - } - - TilesInView++; - - for (int i = 0; i < 4; i++) - { - if (renderChildPart[i].TargetState) - { - RenderPart(renderContext, i, opacity / 100, false); - } - } - - return true; - } - - public void DrawCatalogTile(RenderContext renderContext, double opacity) - { - RenderedGeneration = CurrentRenderGeneration; - TilesTouched++; - - InViewFrustum = true; - bool onlyDrawChildren = false; - - if (!ReadyToRender) - { - if (!errored) - { - TileCache.AddTileToQueue(this); - return; - } - - if (errored && Level < 3) //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv - { - onlyDrawChildren = true; - } - else - { - return; - } - } - - bool anyChildInFrustum = false; - int childIndex = 0; - for (int y1 = 0; y1 < 2; y1++) - { - for (int x1 = 0; x1 < 2; x1++) - { - if (Level < dataset.Levels) - { - if (children[childIndex] == null) - { - children[childIndex] = TileCache.GetTile(Level + 1, x1, y1, dataset, this); - } - - if (children[childIndex].IsTileInFrustum(renderContext.Frustum)) - { - InViewFrustum = true; - anyChildInFrustum = true; - if (children[childIndex].IsTileBigEnough(renderContext) || onlyDrawChildren) - { - ((HealpixTile)children[childIndex]).DrawCatalogTile(renderContext, opacity); - } - else - { - ((HealpixTile)children[childIndex]).RemoveCatalogTile(); - } - } - else - { - ((HealpixTile)children[childIndex]).RemoveCatalogTile(); - } - } - - childIndex++; - } - } - if (Level == 0 && !anyChildInFrustum && !onlyDrawChildren) - { - RemoveCatalogTile(); - } - else if (anyChildInFrustum) - { - TilesInView++; - AddCatalogTile(); - } - } - - public void RemoveCatalogTile() - { - dataset.HipsProperties.CatalogSpreadSheetLayer.RemoveTileRows(Key, catalogRows); - } - - private void AddCatalogTile() - { - dataset.HipsProperties.CatalogSpreadSheetLayer.AddTileRows(Key, catalogRows); - } - - private void ExtractCatalogTileRows() - { - bool headerRemoved = false; - foreach (string line in catalogData.GetText().Split("\n")) - { - if (!line.StartsWith("#") && !headerRemoved) - { - headerRemoved = true; - continue; - } - - if (!line.StartsWith("#")) - { - List rowData = UiTools.SplitString(line, dataset.HipsProperties.CatalogSpreadSheetLayer.Table.Delimiter); - catalogRows.Add(rowData); - } - } - } - - - public bool GetDataInView(RenderContext renderContext, bool limit, CatalogSpreadSheetLayer catalogSpreadSheetLayer) - { - if (!ReadyToRender) - { - if (!errored) - { - RequestImage(); - if (limit) - { - return false; - } - } - else if (Level >= 3) //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv - { - return true; - } - } - - bool allChildrenReady = true; - bool anyChildInFrustum = false; - int childIndex = 0; - for (int y1 = 0; y1 < 2; y1++) - { - for (int x1 = 0; x1 < 2; x1++) - { - if (Level < dataset.Levels) - { - if (children[childIndex] == null) - { - children[childIndex] = TileCache.GetTile(Level + 1, x1, y1, dataset, this); - } - - if (children[childIndex].IsTileInFrustum(renderContext.Frustum)) - { - anyChildInFrustum = true; - allChildrenReady = allChildrenReady && ((HealpixTile)children[childIndex]).GetDataInView(renderContext, limit, catalogSpreadSheetLayer); - } - } - - childIndex++; - } - } - if (anyChildInFrustum) - { - catalogSpreadSheetLayer.AddTileRows(Key, catalogRows); - } - return allChildrenReady && !Downloading; - } - - private void SetStep() - { - if (IsCatalogTile) - { - step = 2; - } - else - { - switch (Level) - { - case 0: - case 1: - case 2: - case 3: - case 4: - step = 16; - break; - case 5: - step = 8; - break; - case 6: - step = 4; - break; - default: - step = 2; - break; - } - } - } - - public override void RequestImage() - { - if (IsCatalogTile) - { - if (!Downloading && !ReadyToRender) - { - Downloading = true; - catalogData = new WebFile(this.URL); - catalogData.OnStateChange = LoadCatalogData; - catalogData.Send(); - } - } - else - { - base.RequestImage(); - } - - } - - private void LoadCatalogData() - { - if (catalogData.State == StateType.Error) - { - RequestPending = false; - Downloading = false; - errored = true; - TileCache.RemoveFromQueue(this.Key, true); - } - else if (catalogData.State == StateType.Received) - { - ExtractCatalogTileRows(); - texReady = true; - Downloading = false; - errored = false; - ReadyToRender = true; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - } - } - - public override WebGLBuffer GetIndexBuffer(int index, int accomidation) - { - return indexBuffer[index]; - } - - private void CalcSphere(Vector3d[] list) - { - SphereHull result = ConvexHull.FindEnclosingSphere(list); - - sphereCenter = result.Center; - sphereRadius = result.Radius; - } - - public override bool IsPointInTile(double lat, double lng) - { - if (Level == 0) - { - return true; - } - - if (Level == 1) - { - if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1)) - { - return true; - } - if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1)) - { - return true; - } - if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0)) - { - return true; - } - if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0)) - { - return true; - } - } - - Vector3d testPoint = Coordinates.GeoTo3dDouble(lat, lng); - bool top = IsLeftOfHalfSpace(TopLeft, TopRight, testPoint); - bool right = IsLeftOfHalfSpace(TopRight, BottomRight, testPoint); - bool bottom = IsLeftOfHalfSpace(BottomRight, BottomLeft, testPoint); - bool left = IsLeftOfHalfSpace(BottomLeft, TopLeft, testPoint); - - if (top && right && bottom && left) - { - return true; - } - return false; ; - } - - private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) - { - pntA.Normalize(); - pntB.Normalize(); - Vector3d cross = Vector3d.Cross(pntA, pntB); - - double dot = Vector3d.Dot(cross, pntTest); - - return dot > 0; - } - - public override double GetSurfacePointAltitude(double lat, double lng, bool meters) - { - - if (Level < lastDeepestLevel) - { - foreach (Tile child in children) - { - if (child != null) - { - if (child.IsPointInTile(lat, lng)) - { - double retVal = child.GetSurfacePointAltitude(lat, lng, meters); - if (retVal != 0) - { - return retVal; - } - else - { - break; - } - } - } - } - } - return GetAltitudeFromLatLng(lat, lng, meters); - } - - private double GetAltitudeFromLatLng(double lat, double lng, bool meters) - { - Vector3d testPoint = Coordinates.GeoTo3dDouble(lat, lng); - Vector2d uv = DistanceCalc.GetUVFromInnerPoint(TopLeft, TopRight, BottomLeft, BottomRight, testPoint); - - // Get 4 samples and interpolate - double uud = Math.Max(0, Math.Min(16, (uv.X * 16))); - double vvd = Math.Max(0, Math.Min(16, (uv.Y * 16))); - - int uu = Math.Max(0, Math.Min(15, (int)(uv.X * 16))); - int vv = Math.Max(0, Math.Min(15, (int)(uv.Y * 16))); - - double ha = uud - uu; - double va = vvd - vv; - - if (demArray != null) - { - // 4 nearest neighbors - double ul = demArray[uu + 17 * vv]; - double ur = demArray[(uu + 1) + 17 * vv]; - double ll = demArray[uu + 17 * (vv + 1)]; - double lr = demArray[(uu + 1) + 17 * (vv + 1)]; - - double top = ul * (1 - ha) + ha * ur; - double bottom = ll * (1 - ha) + ha * lr; - double val = top * (1 - va) + va * bottom; - - return val / (meters ? 1 : DemScaleFactor); - } - - return demAverage / (meters ? 1 : DemScaleFactor); - } - - private void ProcessIndexBuffer(UInt16[] indexArray, int part) - { - indexBuffer[part] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, indexBuffer[part]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, (Uint16Array)(object)indexArray, GL.STATIC_DRAW); - } - - public override void CleanUp(bool removeFromParent) - { - base.CleanUp(removeFromParent); - ReturnBuffers(); - subDivided = false; - } - - private void ReturnBuffers() - { - if (vertexList != null) - { - vertexList = null; - } - } - - - /* - * Vertices distributed in a grid pattern like the example below - * Example for pattern with step set to 4 - * 24 - * 19 23 - * 14 18 22 - * 9 13 17 21 - * 4 8 12 16 20 - * 3 7 11 15 - * 2 6 10 - * 1 5 - * 0 - * - */ - private void PopulateVertexList(PositionTexture[] vertexList, int step) - { - - for (int i = 0; i < step; i += 2) - { - for (int j = 0; j < step; j += 2) - { - Vector3d[] points = this.Boundaries(j, i, step); - - vertexList[i * (step + 1) + j] = PositionTexture.CreatePos(points[2], (1 / step) * i, (1 / step) * j); - vertexList[i * (step + 1) + j + 1] = PositionTexture.CreatePos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j] = PositionTexture.CreatePos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.CreatePos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - if (j + 2 >= step && step > 1) - { - j = step - 1; - points = this.Boundaries(j, i, step); - vertexList[i * (step + 1) + step] = PositionTexture.CreatePos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); - vertexList[(i + 1) * (step + 1) + step] = PositionTexture.CreatePos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - } - } - } - if (step > 1) - { - VertexOfLastRow(vertexList, step); - } - } - - private void VertexOfLastRow(PositionTexture[] vertexList, int step) - { - int i = step - 1; - - for (int j = 0; j < step; j += 2) - { - Vector3d[] points = this.Boundaries(j, i, step); - vertexList[(i + 1) * (step + 1) + j] = PositionTexture.CreatePos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.CreatePos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - if (j + 2 >= step) - { - j = step - 1; - points = this.Boundaries(j, i, step); - vertexList[(i + 1) * (step + 1) + step] = PositionTexture.CreatePos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - } - } - } - } - - public class Xyf - { - public int ix; - public int iy; - public int face; - public Xyf() { } - public static Xyf Create(int x, int y, int f) - { - Xyf temp = new Xyf(); - temp.ix = x; - temp.iy = y; - temp.face = f; - return temp; - } - } - -} \ No newline at end of file diff --git a/engine/csharp_ref/HealpixUtils.cs b/engine/csharp_ref/HealpixUtils.cs deleted file mode 100644 index bdf24dda..00000000 --- a/engine/csharp_ref/HealpixUtils.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; - -namespace wwtlib -{ - public class HealpixUtils - { - static public void check(bool cond, String errtxt) - { - if (!cond) throw new Exception(errtxt); - } - - /** Integer square root. - */ - static public int isqrt(long arg) - { - long res = (long)Math.Sqrt(((double)arg) + 0.5); - if (arg < (1L << 50)) return (int)res; - if (res * res > arg) - --res; - else if ((res + 1) * (res + 1) <= arg) - ++res; - return (int)res; - } - - /** Computes the cosine of the angular distance between two z, phi positions - on the unit sphere. */ - static public double cosdist_zphi(double z1, double phi1, - double z2, double phi2) - { - return z1 * z2 + FastMath.cos(phi1 - phi2) * Math.Sqrt((1.0 - z1 * z1) * (1.0 - z2 * z2)); - } - /** Computes the cosine of the angular distance between two z, phi positions - on the unit sphere. */ - //static public double cosdist_zphi(Zphi zp1, Zphi zp2) - //{ return cosdist_zphi(zp1.z, zp1.phi, zp2.z, zp2.phi); } - - - static public double fmodulo(double v1, double v2) - { - if (v1 >= 0) - return (v1 < v2) ? v1 : v1 % v2; - double tmp = v1 % v2 + v2; - return (tmp == v2) ? 0d : tmp; - } - - //static public bool approx(float a, float b, float epsilon) - //{ return Math.Abs(a - b) < (epsilon * Math.Abs(b)); } - //static public bool approx(double a, double b, double epsilon) - //{ return Math.Abs(a - b) < (epsilon * Math.Abs(b)); } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/HipsProperties.cs b/engine/csharp_ref/HipsProperties.cs deleted file mode 100644 index 116db20b..00000000 --- a/engine/csharp_ref/HipsProperties.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace wwtlib -{ - - public class HipsProperties - { - public Dictionary Properties { get { return properties; } } - public CatalogSpreadSheetLayer CatalogSpreadSheetLayer - { - get { return catalogSpreadSheetLayer; } - set { catalogSpreadSheetLayer = value; } - } - - public VoTable CatalogColumnInfo - { - get { return catalogColumnInfo; } - set { catalogColumnInfo = value; } - } - - public bool DownloadComplete { get { return downloadComplete; } } - - private Dictionary properties = new Dictionary(); - private VoTable catalogColumnInfo = null; - private CatalogSpreadSheetLayer catalogSpreadSheetLayer = new CatalogSpreadSheetLayer(); - - private bool downloadComplete = false; - private WebFile webFile; - private readonly string url; - private string datasetName; - private Action onDownloadComplete; - - public Imageset dataset; - - public HipsProperties (Imageset dataset) - { - this.dataset = dataset; - this.datasetName = dataset.Name; - url = dataset.Url; - if (url.ToLowerCase().IndexOf("norder") > -1) - { - url = url.Substring(0, url.ToLowerCase().IndexOf("norder")); - } - - url += "properties"; - - Download(); - } - - private void Download() - { - webFile = new WebFile(url); - webFile.OnStateChange = OnPropertiesDownloadComplete; - webFile.Send(); - } - - private void OnPropertiesDownloadComplete() - { - if (webFile.State == StateType.Received) - { - ParseProperties(webFile.GetText()); - if (Properties.ContainsKey("dataproduct_type") && Properties["dataproduct_type"].ToLowerCase() == "catalog") - { - catalogColumnInfo = VoTable.LoadFromUrl(url.Replace("/properties", "/metadata.xml"), OnCatalogMetadataDownloadComplete); - } else - { - if (Properties.ContainsKey("hips_data_range")) - { - string hips_data_range = Properties["hips_data_range"]; - this.dataset.FitsProperties.MinVal = Double.Parse(hips_data_range.Split(" ")[0]); - this.dataset.FitsProperties.MaxVal = Double.Parse(hips_data_range.Split(" ")[1]); - this.dataset.FitsProperties.LowerCut = this.dataset.FitsProperties.MinVal; - this.dataset.FitsProperties.UpperCut = this.dataset.FitsProperties.MaxVal; - } - if (Properties.ContainsKey("hips_pixel_cut")) - { - string hips_pixel_cut = Properties["hips_pixel_cut"]; - this.dataset.FitsProperties.LowerCut = Double.Parse(hips_pixel_cut.Split(" ")[0]); - this.dataset.FitsProperties.UpperCut = Double.Parse(hips_pixel_cut.Split(" ")[1]); - if(!Properties.ContainsKey("hips_data_range")) - { - this.dataset.FitsProperties.MinVal = this.dataset.FitsProperties.LowerCut; - this.dataset.FitsProperties.MaxVal = this.dataset.FitsProperties.UpperCut; - } - - - } - downloadComplete = true; - if(onDownloadComplete != null) - { - onDownloadComplete.Invoke(); - } - } - } - } - - private void OnCatalogMetadataDownloadComplete () - { - catalogSpreadSheetLayer.UseHeadersFromVoTable(catalogColumnInfo); - catalogSpreadSheetLayer.Name = datasetName; - catalogSpreadSheetLayer.ID = Guid.CreateFrom(datasetName); - LayerManager.AddSpreadsheetLayer(CatalogSpreadSheetLayer, "Sky"); - downloadComplete = true; - if (onDownloadComplete != null) - { - onDownloadComplete.Invoke(); - } - } - - public void SetDownloadCompleteListener(Action listener) - { - this.onDownloadComplete = listener; - } - - private void ParseProperties(string data) - { - string[] lines = data.Split('\n'); - - foreach (string line in lines) - { - if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#")) - { - string[] parts = line.Split('='); - if (parts.Length == 2) - { - string key = parts[0].Trim(); - string val = parts[1].Trim(); - if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(val)) - { - Properties[key] = val; - } - } - } - } - } - } -} diff --git a/engine/csharp_ref/Hploc.cs b/engine/csharp_ref/Hploc.cs deleted file mode 100644 index 92e61d50..00000000 --- a/engine/csharp_ref/Hploc.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; - -namespace wwtlib -{ - public class Hploc - { - public double z; - public double phi; - public double sth; - public bool have_sth; - - public Hploc() { } - public static Hploc Create(Vector3d v) - { - Hploc temp = new Hploc(); - - double xl = 1 / v.Length(); - temp.z = v.Z * xl; - temp.phi = FastMath.atan2(v.Y, v.X); - if (Math.Abs(temp.z) > 0.99) - { - temp.sth = Math.Sqrt(v.X * v.X + v.Y * v.Y) * xl; - temp.have_sth = true; - } - return temp; - } - - public Vector3d toVec3() - { - double st; - if (have_sth) - { - st = sth; - } - else - { - st = Math.Sqrt((1.0 - z) * (1.0 + z)); - } - - double x = st * FastMath.cos(phi); - double y = st * FastMath.sin(phi); - return Vector3d.Create(x, z, y); - //Reversed the Z and Y axes - } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/IFolder.cs b/engine/csharp_ref/IFolder.cs deleted file mode 100644 index 1a4b6bdd..00000000 --- a/engine/csharp_ref/IFolder.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -namespace wwtlib -{ - interface IFolder - { - bool Browseable { get; set; } - System.Collections.Generic.List Folders { get; set; } - FolderGroup Group { get; set; } - System.Collections.Generic.List Imagesets { get; set; } - long MSRCommunityId { get; set; } - long MSRComponentId { get; set; } - string Name { get; set; } - long Permission { get; set; } - System.Collections.Generic.List Places { get; set; } - bool ReadOnly { get; set; } - string RefreshInterval { get; set; } - FolderRefreshType RefreshType { get; set; } - bool RefreshTypeSpecified { get; set; } - bool Searchable { get; set; } - string SubType { get; set; } - string ThumbnailUrl { get; set; } - System.Collections.Generic.List Tours { get; set; } - FolderType Type { get; set; } - string Url { get; set; } - } -} diff --git a/engine/csharp_ref/IIThumbnail.cs b/engine/csharp_ref/IIThumbnail.cs deleted file mode 100644 index 951bd8e5..00000000 --- a/engine/csharp_ref/IIThumbnail.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - -namespace wwtlib -{ - public interface IThumbnail - { - string Name { get; } - ImageElement Thumbnail { get; set; } - string ThumbnailUrl { get; set; } - Rectangle Bounds { get; set; } - bool IsImage { get; } - bool IsTour { get; } - bool IsFolder { get; } - bool IsCloudCommunityItem { get; } - bool ReadOnly { get; } - List Children { get; } - } - - -} diff --git a/engine/csharp_ref/IImageSet.cs b/engine/csharp_ref/IImageSet.cs deleted file mode 100644 index 7fe95bbf..00000000 --- a/engine/csharp_ref/IImageSet.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace wwtlib -{ - //public interface IImageSet - //{ - // string DemUrl { get; set; } - // BandPass BandPass { get; set; } - // int BaseLevel { get; set; } - // double BaseTileDegrees { get; set; } - // bool BottomsUp { get; set; } - // double CenterX { get; set; } - // double CenterY { get; set; } - // string CreditsText { get; set; } - // string CreditsUrl { get; set; } - // ImageSetType DataSetType { get; set; } - // bool DefaultSet { get; set; } - // bool ElevationModel { get; set; } - // string Extension { get; set; } - // bool Generic { get; set; } - // int GetHashCode(); - // int ImageSetID { get; set; } - // bool IsMandelbrot { get; } - // int Levels { get; set; } - // Matrix3d Matrix { get; set; } - // bool Mercator { get; set; } - // string Name { get; set; } - // double OffsetX { get; set; } - // double OffsetY { get; set; } - // ProjectionType Projection { get; set; } - // string QuadTreeTileMap { get; set; } - // double Rotation { get; set; } - // bool Sparse { get; set; } - // IImageSet StockImageSet { get; } - // string ThumbnailUrl { get; set; } - // string Url { get; set; } - // double WidthFactor { get; set; } - // // WcsImage WcsImage { get; set; } - // double MeanRadius { get; set; } - // string ReferenceFrame { get; set; } - //} - - public enum ProjectionType { Mercator = 0, Equirectangular = 1, Tangent = 2, Tan = 2, Toast = 3, Spherical = 4, SkyImage = 5, Plotted = 6, Healpix = 7 }; - public enum ImageSetType { Earth = 0, Planet = 1, Sky = 2, Panorama = 3, SolarSystem = 4, Sandbox = 5}; - public enum BandPass { Gamma = 0, XRay = 1, Ultraviolet = 2, Visible = 3, HydrogenAlpha = 4, IR = 4, Microwave = 5, Radio = 6, VisibleNight = 6 }; -} diff --git a/engine/csharp_ref/IPlace.cs b/engine/csharp_ref/IPlace.cs deleted file mode 100644 index 2eade877..00000000 --- a/engine/csharp_ref/IPlace.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Html; -using System.Collections.Generic; -namespace wwtlib -{ - - public enum Classification - { - Star = 1, - Supernova = 2, - BlackHole = 4, - NeutronStar = 8, - DoubleStar = 16, - MultipleStars = 32, - Asterism = 64, - Constellation = 128, - OpenCluster = 256, - GlobularCluster = 512, - NebulousCluster = 1024, - Nebula = 2048, - EmissionNebula = 4096, - PlanetaryNebula = 8192, - ReflectionNebula = 16384, - DarkNebula = 32768, - GiantMolecularCloud = 65536, - SupernovaRemnant = 131072, - InterstellarDust = 262144, - Quasar = 524288, - Galaxy = 1048576, - SpiralGalaxy = 2097152, - IrregularGalaxy = 4194304, - EllipticalGalaxy = 8388608, - Knot = 16777216, - PlateDefect = 33554432, - ClusterOfGalaxies = 67108864, - OtherNGC = 134217728, - Unidentified = 268435456, - SolarSystem = 536870912, - Unfiltered = 1073741823, - Stellar = 63, - StellarGroupings = 2032, - Nebulae = 523264, - Galactic = 133693440, - Other = 436207616 - }; - - - public interface IPlace - { - // IThumnnail - string Name { get; } - ImageElement Thumbnail { get; set; } - string ThumbnailUrl { get; set; } - Rectangle Bounds { get; set; } - bool IsImage { get; } - bool IsTour { get; } - bool IsFolder { get; } - bool IsCloudCommunityItem { get; } - bool ReadOnly { get; } - List Children { get; } - - - // IPlace - Imageset BackgroundImageset { get; set; } - Imageset StudyImageset { get; set; } - CameraParameters CamParams { get; set; } - double Dec { get; set; } - double Lat { get; set; } - double Lng { get; set; } - Vector3d Location3d { get; } - string[] Names { get; set; } - double Opacity { get; set; } - double RA { get; set; } - double ZoomLevel { get; set; } - double SearchDistance { get; set; } - Classification Classification { get; set; } - ImageSetType Type { get; set; } - string Constellation { get; set; } - double Magnitude { get; set; } - double Distance { get; set; } - string Url { get; set; } - SolarSystemObjects Target { get; set; } - object Tag { get; set; } - } -} diff --git a/engine/csharp_ref/IUIController.cs b/engine/csharp_ref/IUIController.cs deleted file mode 100644 index efbf6cda..00000000 --- a/engine/csharp_ref/IUIController.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - - -namespace wwtlib -{ - public interface IUiController - { - void Render(RenderContext renderContext); - bool MouseDown(object sender, ElementEvent e); - bool MouseUp(object sender, ElementEvent e); - bool MouseMove(object sender, ElementEvent e); - bool MouseClick(object sender, ElementEvent e); - bool Click(object sender, ElementEvent e); - bool MouseDoubleClick(object sender, ElementEvent e); - bool KeyDown(object sender, ElementEvent e); - bool KeyUp(object sender, ElementEvent e); - bool Hover(Vector2d pnt); - } -} diff --git a/engine/csharp_ref/IViewMover.cs b/engine/csharp_ref/IViewMover.cs deleted file mode 100644 index 7bb68056..00000000 --- a/engine/csharp_ref/IViewMover.cs +++ /dev/null @@ -1,329 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - public interface IViewMover - { - bool Complete { get; } - CameraParameters CurrentPosition { get; } - Date CurrentDateTime { get; } - Action Midpoint { get; set;} - double MoveTime { get; } - } - - public class ViewMoverKenBurnsStyle : IViewMover - { - public InterpolationType InterpolationType = InterpolationType.Linear; - // public bool Dampened = false; - public bool FastDirectionMove = false; - CameraParameters from; - CameraParameters to; - - Date fromDateTime; - Date toDateTime; - Date fromTime; - double toTargetTime = 0; - int dateTimeSpan; - public ViewMoverKenBurnsStyle(CameraParameters from, CameraParameters to, double time, Date fromDateTime, Date toDateTime, InterpolationType type) - { - InterpolationType = type; - - if (Math.Abs(from.Lng - to.Lng) > 180) - { - if (from.Lng > to.Lng) - { - from.Lng -= 360; - } - else - { - from.Lng += 360; - } - } - - this.fromDateTime = fromDateTime; - this.toDateTime = toDateTime; - - dateTimeSpan = toDateTime - fromDateTime; - - this.from = from.Copy(); - this.to = to.Copy(); - fromTime = SpaceTimeController.MetaNow; - toTargetTime = time; - - } - bool complete = false; - bool midpointFired = false; - public bool Complete - { - get - { - //Int64 elapsed = HiResTimer.TickCount - fromTime; - //double elapsedSeconds = ((double)elapsed) / HiResTimer.Frequency; - //return (elapsedSeconds > toTargetTime); - return complete; - } - } - public CameraParameters CurrentPosition - { - get - { - int elapsed = SpaceTimeController.MetaNow - fromTime; - double elapsedSeconds = ((double)elapsed) / 1000; - - double alpha = elapsedSeconds / (toTargetTime ); - - if (!midpointFired && alpha >= .5) - { - midpointFired = true; - - if (midpoint != null) - { - midpoint(); - } - } - if (alpha >= 1.0) - { - alpha = 1.0; - complete = true; - return to.Copy(); - } - if (Settings.Active.GalacticMode && WWTControl.Singleton.RenderContext.Space) - { - return CameraParameters.InterpolateGreatCircle(from, to, alpha, InterpolationType, FastDirectionMove); - } - return CameraParameters.Interpolate(from, to, alpha, InterpolationType, FastDirectionMove); - } - } - - public Date CurrentDateTime - { - get - { - int elapsed = SpaceTimeController.MetaNow - fromTime; - double elapsedSeconds = ((double)elapsed) / 1000; - - double alpha = elapsedSeconds / (toTargetTime); - - double delta = (dateTimeSpan) * alpha; - - Date retDate = new Date(fromDateTime.GetTime() + (int)delta); - - return retDate; - } - } - - Action midpoint; - - public Action Midpoint - { - get - { - return midpoint; - } - set - { - midpoint = value; - } - } - - - public double MoveTime - { - get { return toTargetTime; } - } - - - } - - class ViewMoverSlew : IViewMover - { - CameraParameters from; - CameraParameters fromTop; - CameraParameters to; - CameraParameters toTop; - Date fromTime; - double upTargetTime = 0; - double downTargetTime = 0; - double toTargetTime = 0; - double upTimeFactor = .6; - double downTimeFactor = .6; - double travelTimeFactor = 7.0; - public static ViewMoverSlew Create(CameraParameters from, CameraParameters to) - { - ViewMoverSlew temp = new ViewMoverSlew(); - temp.Init(from, to); - return temp; - } - - public ViewMoverSlew() - { - } - - public static ViewMoverSlew CreateUpDown(CameraParameters from, CameraParameters to, double upDowFactor) - { - ViewMoverSlew temp = new ViewMoverSlew(); - temp.upTimeFactor = temp.downTimeFactor = upDowFactor; - temp.Init(from.Copy(), to.Copy()); - return temp; - } - - public void Init(CameraParameters from, CameraParameters to) - { - if (Math.Abs(from.Lng - to.Lng) > 180) - { - if (from.Lng > to.Lng) - { - from.Lng -= 360; - } - else - { - from.Lng += 360; - } - } - - if (to.Zoom <= 0) - { - to.Zoom = 360; - } - if (from.Zoom <= 0) - { - from.Zoom = 360; - } - this.from = from; - this.to = to; - fromTime = SpaceTimeController.MetaNow; - double zoomUpTarget = 360.0; - double travelTime; - - double lngDist = Math.Abs(from.Lng - to.Lng); - double latDist = Math.Abs(from.Lat - to.Lat); - double distance = Math.Sqrt(latDist * latDist + lngDist * lngDist); - - - zoomUpTarget = (distance / 3) * 20; - if (zoomUpTarget > 360.0) - { - zoomUpTarget = 360.0; - } - - if (zoomUpTarget < from.Zoom) - { - zoomUpTarget = from.Zoom; - } - - travelTime = (distance / 180.0) * (360 / zoomUpTarget) * travelTimeFactor; - - double rotateTime = Math.Max(Math.Abs(from.Angle - to.Angle), Math.Abs(from.Rotation - to.Rotation)) ; - - - double logDistUp = Math.Max(Math.Abs(Util.LogN(zoomUpTarget, 2) - Util.LogN(from.Zoom, 2)), rotateTime); - upTargetTime = upTimeFactor * logDistUp; - downTargetTime = upTargetTime + travelTime; - double logDistDown = Math.Abs(Util.LogN(zoomUpTarget, 2) - Util.LogN(to.Zoom, 2)); - toTargetTime = downTargetTime + Math.Max((downTimeFactor * logDistDown),rotateTime); - - fromTop = from.Copy(); - fromTop.Zoom = zoomUpTarget; - fromTop.Angle = (from.Angle + to.Angle) / 2.0; //todo make short wrap arounds.. - fromTop.Rotation = (from.Rotation + to.Rotation) / 2.0; - toTop = to.Copy(); - toTop.Zoom = fromTop.Zoom; - toTop.Angle = fromTop.Angle; - toTop.Rotation = fromTop.Rotation; - - } - - bool midpointFired = false; - bool complete = false; - public bool Complete - { - get - { - //Int64 elapsed = HiResTimer.TickCount - fromTime; - //double elapsedSeconds = ((double)elapsed) / HiResTimer.Frequency; - //return (elapsedSeconds > toTargetTime); - return complete; - } - } - public CameraParameters CurrentPosition - { - get - { - int elapsed = SpaceTimeController.MetaNow - fromTime; - double elapsedSeconds = ((double)elapsed) / 1000; - - if (elapsedSeconds < upTargetTime) - { - // Log interpolate from from to fromTop - return CameraParameters.Interpolate(from, fromTop, elapsedSeconds / upTargetTime, InterpolationType.EaseInOut, false); - } - else if (elapsedSeconds < downTargetTime) - { - elapsedSeconds -= upTargetTime; - if (Settings.Active.GalacticMode && WWTControl.Singleton.RenderContext.Space) - { - return CameraParameters.InterpolateGreatCircle(fromTop, toTop, elapsedSeconds / (downTargetTime - upTargetTime), InterpolationType.EaseInOut, false); - } - // interpolate linear fromTop and toTop - return CameraParameters.Interpolate(fromTop, toTop, elapsedSeconds / (downTargetTime - upTargetTime), InterpolationType.EaseInOut, false); - } - else - { - if (!midpointFired ) - { - midpointFired = true; - - if (midpoint != null) - { - midpoint(); - } - - } - elapsedSeconds -= downTargetTime; - // Interpolate log from toTop and to - double alpha = elapsedSeconds / (toTargetTime - downTargetTime); - if (alpha > 1.0) - { - alpha = 1.0; - complete = true; - return to.Copy(); - } - return CameraParameters.Interpolate(toTop, to, alpha, InterpolationType.EaseInOut, false); - } - } - } - - public Date CurrentDateTime - { - get - { - SpaceTimeController.UpdateClock(); - return SpaceTimeController.Now; - } - } - - Action midpoint; - - public Action Midpoint - { - get - { - return midpoint; - } - set - { - midpoint = value; - } - } - - public double MoveTime - { - get { return toTargetTime; } - } - } -} - - diff --git a/engine/csharp_ref/ImageSetHelper.cs b/engine/csharp_ref/ImageSetHelper.cs deleted file mode 100644 index 93c33cd1..00000000 --- a/engine/csharp_ref/ImageSetHelper.cs +++ /dev/null @@ -1,812 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace wwtlib -{ - public class ImageSetHelper : IImageSet - { - - - public static string GetTileKey(IImageSet imageset, int level, int x, int y) - { - return imageset.ImageSetID.ToString() + @"\" + level.ToString() + @"\" + y.ToString() + "_" + x.ToString(); - } - - public static Tile GetNewTile(IImageSet imageset, int level, int x, int y, Tile parent) - { - - switch (imageset.Projection) - { - //case ProjectionType.Mercator: - // { - // MercatorTile newTile = new MercatorTile(level, x, y, imageset, parent); - // return newTile; - // } - //case ProjectionType.Equirectangular: - // { - // return new EquirectangularTile(level, x, y, imageset, parent); - // } - //case ProjectionType.Spherical: - // { - // return new SphericalTile(level, x, y, imageset, parent); - // } - default: - case ProjectionType.Toast: - { - return ToastTile.Create(level, x, y, imageset, parent); - } - //case ProjectionType.SkyImage: - // { - // return new SkyImageTile(level, x, y, imageset, parent); - // } - //case ProjectionType.Plotted: - // { - // return new PlotTile(level, x, y, imageset, parent); - // } - - //case ProjectionType.Tangent: - // { - // TangentTile newTile = new TangentTile(level, x, y, imageset, parent); - // return newTile; - // } - } - - } - - ProjectionType projection; - - public ProjectionType Projection - { - get { return projection; } - set { projection = value; } - } - - private string referenceFrame; - - public string ReferenceFrame - { - get - { - return referenceFrame; - } - set - { - referenceFrame = value; - } - } - - int imageSetID; - public int ImageSetID - { - get - { - return imageSetID; - } - set - { - imageSetID = value; - } - } - - double baseTileDegrees; - public double BaseTileDegrees - { - get - { - return baseTileDegrees; - } - set - { - baseTileDegrees = value; - } - } - - double widthFactor = 1; - - public double WidthFactor - { - get { return widthFactor; } - set { widthFactor = value; } - } - - public int GetHashCode() - { - - return Util.GetHashCode(Url); - } - - protected string url; - public string Url - { - get - { - return url; - } - set - { - url = value; - } - } - - protected string demUrl = ""; - public string DemUrl - { - get - { - if (String.IsNullOrEmpty(demUrl) && projection == ProjectionType.Mercator) - { - - return "http://ecn.t{S}.tiles.virtualearth.net/tiles/d{Q}.elv?g=1&n=z"; - } - return demUrl; - } - set - { - demUrl = value; - } - } - - string extension; - public string Extension - { - get - { - return extension; - } - set - { - extension = value; - } - } - - int levels; - public int Levels - { - get - { - return levels; - } - set - { - levels = value; - } - } - bool mercator; - bool bottomsUp; - - public bool BottomsUp - { - get { return bottomsUp; } - set { bottomsUp = value; } - } - - public bool Mercator - { - get { return mercator; } - set { mercator = value; } - } - //private int tileSize = 256; - - //public int TileSize - //{ - // get { return tileSize; } - // set { tileSize = value; } - //} - int baseLevel = 1; - - public int BaseLevel - { - get { return baseLevel; } - set { baseLevel = value; } - } - - string quadTreeTileMap = "0123"; - - public string QuadTreeTileMap - { - get { return quadTreeTileMap; } - set { quadTreeTileMap = value; } - } - double centerX = 0; - - public double CenterX - { - get { return centerX; } - set - { - if (centerX != value) - { - centerX = value; - ComputeMatrix(); - } - } - } - double centerY = 0; - - public double CenterY - { - get { return centerY; } - set - { - if (centerY != value) - { - centerY = value; - ComputeMatrix(); - } - } - } - double rotation = 0; - - public double Rotation - { - get { return rotation; } - set - { - if (rotation != value) - { - rotation = value; - ComputeMatrix(); - } - } - } - - private double meanRadius; - - public double MeanRadius - { - get { return meanRadius; } - set { meanRadius = value; } - } - - - ImageSetType dataSetType = ImageSetType.Earth; - BandPass bandPass = BandPass.Visible; - - public BandPass BandPass - { - get { return bandPass; } - set { bandPass = value; } - } - - public ImageSetType DataSetType - { - get { return dataSetType; } - set { dataSetType = value; } - } - /* - node.Attributes[""].Value, - Convert.ToDouble(node.Attributes[""].Value), - Convert.ToInt32(node.Attributes[""].Value), - - - * */ - string altUrl = ""; - - public string AltUrl - { - get { return altUrl; } - set { altUrl = value; } - } - bool singleImage = false; - - public bool SingleImage - { - get { return singleImage; } - set { singleImage = value; } - } - - - //public static ImageSetHelper FromXMLNode(XmlNode node) - //{ - // try - // { - // ImageSetType type = ImageSetType.Sky; - - - - // ProjectionType projection = ProjectionType.Tangent; - // if (node.Attributes["DataSetType"] != null) - // { - // type = (ImageSetType)Enum.Parse(typeof(ImageSetType), node.Attributes["DataSetType"].Value.ToString()); - // } - // //switch (node.Attributes["DataSetType"].Value.ToString().ToLower()) - // //{ - // // case "earth": - // // type = DataSetType.Earth; - // // break; - // // case "planet": - // // type = DataSetType.Planet; - // // break; - // // case "sky": - // // type = DataSetType.Sky; - // // break; - // //} - // BandPass bandPass = BandPass.Visible; - - // if (node.Attributes["BandPass"] != null) - // { - // bandPass = (BandPass) Enum.Parse(typeof(BandPass),node.Attributes["BandPass"].Value.ToString()); - // } - // int wf = 1; - // if (node.Attributes["WidthFactor"] != null) - // { - // wf = Convert.ToInt32(node.Attributes["WidthFactor"].Value); - // } - - // if (node.Attributes["Generic"] == null || !Convert.ToBoolean(node.Attributes["Generic"].Value.ToString())) - // { - - // switch (node.Attributes["Projection"].Value.ToString().ToLower()) - // { - // case "tan": - // case "tangent": - // projection = ProjectionType.Tangent; - // break; - // case "mercator": - // projection = ProjectionType.Mercator; - // break; - // case "equirectangular": - // projection = ProjectionType.Equirectangular; - // break; - // case "toast": - // projection = ProjectionType.Toast; - // break; - // case "spherical": - // projection = ProjectionType.Spherical; - // break; - // case "plotted": - // projection = ProjectionType.Plotted; - // break; - // case "skyimage": - // projection = ProjectionType.SkyImage; - // break; - // } - - // string fileType = node.Attributes["FileType"].Value.ToString(); - // if (!fileType.StartsWith(".")) - // { - // fileType = "." + fileType; - // } - - // //string url = node.Attributes["Url"].Value.ToString(); - // //int index = url.IndexOf("hst/") + 4; - // //int end = url.Substring(index).IndexOf("/"); - - // //string oldDir = @"c:\tilecache\" + url.Substring(index, end ); - // //string newDir = @"c:\tilecache\" + Math.Abs(node.Attributes["Url"].Value.ToString().GetHashCode()).ToString(); - - // //if (Directory.Exists(oldDir)) - // //{ - // // Directory.Move(oldDir, newDir); - // //} - // string thumbnailUrl; - - // XmlNode thumbUrl = node["ThumbnailUrl"]; - // thumbnailUrl = thumbUrl.InnerText; - - // bool stockSet = false; - // bool elevationModel = false; - - // if (node.Attributes["StockSet"] != null) - // { - // stockSet = Convert.ToBoolean(node.Attributes["StockSet"].Value.ToString()); - // } - - // if (node.Attributes["ElevationModel"] != null) - // { - // elevationModel = Convert.ToBoolean(node.Attributes["ElevationModel"].Value.ToString()); - // } - - // string demUrl = ""; - // if (node.Attributes["DemUrl"] != null) - // { - // demUrl = node.Attributes["DemUrl"].Value.ToString(); - // } - - // string alturl = ""; - - // if (node.Attributes["AltUrl"] != null) - // { - // alturl = node.Attributes["AltUrl"].Value.ToString(); - // } - - - // double offsetX = 0; - - // if (node.Attributes["OffsetX"] != null) - // { - // offsetX = Convert.ToDouble(node.Attributes["OffsetX"].Value.ToString()); - // } - - // double offsetY = 0; - - // if (node.Attributes["OffsetY"] != null) - // { - // offsetY = Convert.ToDouble(node.Attributes["OffsetY"].Value.ToString()); - // } - - // string creditText = ""; - - // XmlNode credits = node["Credits"]; - - // if (credits != null) - // { - // creditText = credits.InnerText; - // } - - // string creditsUrl = ""; - - // credits = node["CreditsUrl"]; - - // if (credits != null) - // { - // creditsUrl = credits.InnerText; - // } - - // double meanRadius = 0; - - // if (node.Attributes["MeanRadius"] != null) - // { - // meanRadius = Convert.ToDouble(node.Attributes["MeanRadius"].Value.ToString()); - // } - // string referenceFrame = null; - // if (node.Attributes["ReferenceFrame"] != null) - // { - // referenceFrame = node.Attributes["ReferenceFrame"].Value; - // } - - - // return new ImageSetHelper(node.Attributes["Name"].Value.ToString(), node.Attributes["Url"].Value.ToString(), type, bandPass, projection, Math.Abs(node.Attributes["Url"].Value.ToString().GetHashCode()), Convert.ToInt32(node.Attributes["BaseTileLevel"].Value), Convert.ToInt32(node.Attributes["TileLevels"].Value), 256, Convert.ToDouble(node.Attributes["BaseDegreesPerTile"].Value), fileType, Convert.ToBoolean(node.Attributes["BottomsUp"].Value.ToString()), node.Attributes["QuadTreeMap"].Value.ToString(), Convert.ToDouble(node.Attributes["CenterX"].Value), Convert.ToDouble(node.Attributes["CenterY"].Value), Convert.ToDouble(node.Attributes["Rotation"].Value), Convert.ToBoolean(node.Attributes["Sparse"].Value.ToString()), thumbnailUrl, stockSet, elevationModel, wf, offsetX, offsetY, creditText, creditsUrl, demUrl, alturl, meanRadius, referenceFrame); - // } - // else - // { - // return new ImageSetHelper(type, bandPass); - // } - - // } - // catch - // { - // return null; - // } - //} - - //public static void SaveToXml(System.Xml.XmlTextWriter xmlWriter, IImageSet imageset, string alternateUrl) - //{ - // xmlWriter.WriteStartElement("ImageSet"); - - // xmlWriter.WriteAttributeString("Generic", imageset.Generic.ToString()); - // xmlWriter.WriteAttributeString("DataSetType", imageset.DataSetType.ToString()); - // xmlWriter.WriteAttributeString("BandPass", imageset.BandPass.ToString()); - // if (!imageset.Generic) - // { - // xmlWriter.WriteAttributeString("Name", imageset.Name); - - // if (String.IsNullOrEmpty(alternateUrl)) - // { - // xmlWriter.WriteAttributeString("Url", imageset.Url); - // } - // else - // { - // xmlWriter.WriteAttributeString("Url", alternateUrl); - // } - // xmlWriter.WriteAttributeString("DemUrl", imageset.DemUrl); - // xmlWriter.WriteAttributeString("BaseTileLevel", imageset.BaseLevel.ToString()); - // xmlWriter.WriteAttributeString("TileLevels", imageset.Levels.ToString()); - // xmlWriter.WriteAttributeString("BaseDegreesPerTile", imageset.BaseTileDegrees.ToString()); - // xmlWriter.WriteAttributeString("FileType", imageset.Extension); - // xmlWriter.WriteAttributeString("BottomsUp", imageset.BottomsUp.ToString()); - // xmlWriter.WriteAttributeString("Projection", imageset.Projection.ToString()); - // xmlWriter.WriteAttributeString("QuadTreeMap", imageset.QuadTreeTileMap); - // xmlWriter.WriteAttributeString("CenterX", imageset.CenterX.ToString()); - // xmlWriter.WriteAttributeString("CenterY", imageset.CenterY.ToString()); - // xmlWriter.WriteAttributeString("OffsetX", imageset.OffsetX.ToString()); - // xmlWriter.WriteAttributeString("OffsetY", imageset.OffsetY.ToString()); - // xmlWriter.WriteAttributeString("Rotation", imageset.Rotation.ToString()); - // xmlWriter.WriteAttributeString("Sparse", imageset.Sparse.ToString()); - // xmlWriter.WriteAttributeString("ElevationModel", imageset.ElevationModel.ToString()); - // xmlWriter.WriteAttributeString("StockSet", imageset.DefaultSet.ToString()); - // xmlWriter.WriteAttributeString("WidthFactor", imageset.WidthFactor.ToString()); - // xmlWriter.WriteAttributeString("MeanRadius", imageset.MeanRadius.ToString()); - // xmlWriter.WriteAttributeString("ReferenceFrame", imageset.ReferenceFrame); - // if (String.IsNullOrEmpty(alternateUrl)) - // { - // xmlWriter.WriteElementString("ThumbnailUrl", imageset.ThumbnailUrl); - // } - // else - // { - // xmlWriter.WriteElementString("ThumbnailUrl", imageset.Url); - // } - // } - // xmlWriter.WriteEndElement(); - //} - - public override string ToString() - { - if (DefaultSet) - { - return name + " *"; - } - else - { - return name; - } - } - - //todo figure out the place for this... - public IImageSet StockImageSet - { - get - { - if (generic || !defaultSet) - { - return this; - } - else - { - return ImageSetHelper.CreateGeneric(this.DataSetType, this.BandPass); - } - } - } - - //public static bool operator ==(ImageSet left, ImageSet right) - //{ - // if (left == right ) - // { - // return true; - // } - // if (left == null ^ right == null) - // { - // return false; - // } - // return (left.Url.GetHashCode() == right.Url.GetHashCode()); - //} - - //public static bool operator !=(ImageSet left, ImageSet right) - //{ - // if (left == right ) - // { - // return false; - // } - // if ( left == null ^ right == null) - // { - // return true; - // } - - // return (left.Url.GetHashCode() != right.Url.GetHashCode()); - //} - - //public static bool operator ==(ImageSet o1, ImageSet o2) - //{ - // return (Object)o1 == null ? (Object)o2 == null : o1.Equals(o2); - //} - //public static bool operator !=(ImageSet o1, ImageSet o2) - //{ - // return (Object)o1 != null ? (Object)o2 != null : !o1.Equals(o2); - //} - - - - public bool Equals(object obj) - { - if (obj == null) - { - return false; - } - if (!(obj is IImageSet)) - { - return false; - } - IImageSet b = (IImageSet)obj; - - return (Util.GetHashCode(b.Url) == Util.GetHashCode(this.Url) && b.DataSetType == this.DataSetType && b.BandPass == this.BandPass && b.Generic == this.Generic); - - } - - private Matrix3d matrix; - - public Matrix3d Matrix - { - get - { - if (!matrixComputed) - { - ComputeMatrix(); - } - return matrix; - } - set { matrix = value; } - } - bool matrixComputed = false; - private void ComputeMatrix() - { - matrixComputed = true; - matrix = Matrix3d.Identity; - matrix.Multiply(Matrix3d.RotationX((((Rotation)) / 180f * Math.PI))); - matrix.Multiply(Matrix3d.RotationZ(((CenterY) / 180f * Math.PI))); - matrix.Multiply(Matrix3d.RotationY((((360 - CenterX) + 180) / 180f * Math.PI))); - } - - private string name = ""; - - public string Name - { - get { return name; } - set { name = value; } - } - private bool sparse = false; - - public bool Sparse - { - get { return sparse; } - set { sparse = value; } - } - private string thumbnailUrl = ""; - - public string ThumbnailUrl - { - get { return thumbnailUrl; } - set { thumbnailUrl = value; } - } - private bool generic; - - public bool Generic - { - get { return generic; } - set { generic = value; } - } - - public ImageSetHelper() - { - } - - public static ImageSetHelper CreateGeneric(ImageSetType dataSetType, BandPass bandPass) - { - ImageSetHelper temp = new ImageSetHelper(); - temp.generic = true; - temp.name = "Generic"; - temp.sparse = false; - temp.dataSetType = dataSetType; - temp.bandPass = bandPass; - temp.quadTreeTileMap = ""; - temp.url = ""; - temp.levels = 0; - temp.baseTileDegrees = 0; - temp.imageSetID = 0; - temp.extension = ""; - temp.projection = ProjectionType.Equirectangular; - temp.bottomsUp = false; - temp.baseLevel = 0; - temp.mercator = (temp.projection == ProjectionType.Mercator); - temp.centerX = 0; - temp.centerY = 0; - temp.rotation = 0; - //todo add scale - temp.thumbnailUrl = ""; - - temp.matrix = Matrix3d.Identity; - temp.matrix.Multiply(Matrix3d.RotationX((((temp.Rotation)) / 180f * Math.PI))); - temp.matrix.Multiply(Matrix3d.RotationZ(((temp.CenterY) / 180f * Math.PI))); - temp.matrix.Multiply(Matrix3d.RotationY((((360 - temp.CenterX) + 180) / 180f * Math.PI))); - - return temp; - } - - bool defaultSet = false; - bool elevationModel = false; - - public bool ElevationModel - { - get { return elevationModel; } - set { elevationModel = value; } - } - public bool DefaultSet - { - get { return defaultSet; } - set { defaultSet = value; } - } - - double offsetX = 0; - - public double OffsetX - { - get { return offsetX; } - set { offsetX = value; } - } - - - double offsetY = 0; - - public double OffsetY - { - get { return offsetY; } - set { offsetY = value; } - } - - - string creditsText; - - public string CreditsText - { - get { return creditsText; } - set { creditsText = value; } - } - string creditsUrl; - - public string CreditsUrl - { - get { return creditsUrl; } - set { creditsUrl = value; } - } - - public bool IsMandelbrot - { - get - { - return false; - } - } - - - public static ImageSetHelper Create(string name, string url, ImageSetType dataSetType, BandPass bandPass, ProjectionType projection, int imageSetID, int baseLevel, int levels, int tileSize, double baseTileDegrees, string extension, bool bottomsUp, string quadTreeMap, double centerX, double centerY, double rotation, bool sparse, string thumbnailUrl, bool defaultSet, bool elevationModel, int wf, double offsetX, double offsetY, string credits, string creditsUrl, string demUrlIn, string alturl, double meanRadius, string referenceFrame) - { - ImageSetHelper temp = new ImageSetHelper(); - - temp.ReferenceFrame = referenceFrame; - temp.MeanRadius = meanRadius; - temp.altUrl = alturl; - temp.demUrl = demUrlIn; - temp.creditsText = credits; - temp.creditsUrl = creditsUrl; - temp.offsetY = offsetY; - temp.offsetX = offsetX; - temp.widthFactor = wf; - temp.elevationModel = elevationModel; - temp.defaultSet = defaultSet; - temp.name = name; - temp.sparse = sparse; - temp.dataSetType = dataSetType; - temp.bandPass = bandPass; - temp.quadTreeTileMap = quadTreeMap; - temp.url = url; - temp.levels = levels; - temp.baseTileDegrees = baseTileDegrees; - temp.imageSetID = imageSetID; - temp.extension = extension; - temp.projection = projection; - temp.bottomsUp = bottomsUp; - temp.baseLevel = baseLevel; - temp.mercator = (projection == ProjectionType.Mercator); - temp.centerX = centerX; - temp.centerY = centerY; - temp.rotation = rotation; - temp.thumbnailUrl = thumbnailUrl; - temp.ComputeMatrix(); - - return temp; - } - - - - // URL parameters - //{0} ImageSetID - //{1} level - //{2} x tile id - //{3} y tile id - //{4} quadtree address (VE style) - //{5} quadtree address (Google maps style) - //{6} top left corner RA - //{7} top left corner Dec - //{8} bottom right corner RA - //{9} bottom right corner dec - //{10} bottom left corner RA - //{11} bottom left corner dec - //{12} top right corner RA - //{13} top right corner dec - - - - - - } -} diff --git a/engine/csharp_ref/Imageset.cs b/engine/csharp_ref/Imageset.cs deleted file mode 100644 index 8c45b889..00000000 --- a/engine/csharp_ref/Imageset.cs +++ /dev/null @@ -1,1070 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using System.Html; - -namespace wwtlib -{ - public class Imageset : IThumbnail - { - // This is probably an `object` and not `WcsImage` for historical reasons? - private object wcsImage; - - public object WcsImage - { - get { return wcsImage; } - set { wcsImage = value; } - } - - public static string GetTileKey(Imageset imageset, int level, int x, int y, Tile parent) - { - if (imageset.Projection == ProjectionType.Healpix && parent != null) - { - int ipix = ((HealpixTile)parent).ipix * 4 + y * 2 + x; - return imageset.ImageSetID.ToString() + @"\" + level.ToString() + @"\" + ipix.ToString(); - } - return imageset.ImageSetID.ToString() + @"\" + level.ToString() + @"\" + y.ToString() + "_" + x.ToString(); - } - - public static Tile GetNewTile(Imageset imageset, int level, int x, int y, Tile parent) - { - - switch (imageset.Projection) - { - case ProjectionType.Mercator: - { - MercatorTile newTile = MercatorTile.Create(level, x, y, imageset, parent); - return newTile; - } - case ProjectionType.Equirectangular: - { - return EquirectangularTile.Create(level, x, y, imageset, parent); - } - //case ProjectionType.Spherical: - // { - // return new SphericalTile(level, x, y, imageset, parent); - // } - default: - case ProjectionType.Toast: - { - return ToastTile.Create(level, x, y, imageset, parent); - } - case ProjectionType.SkyImage: - { - return new SkyImageTile(level, x, y, imageset, parent); - } - case ProjectionType.Plotted: - { - return PlotTile.Create(level, x, y, imageset, parent); - } - case ProjectionType.Healpix: - { - if (imageset.HipsProperties == null) - { - imageset.HipsProperties = new HipsProperties(imageset); - } - if (imageset.HipsProperties.DownloadComplete) - { - return new HealpixTile(level, x, y, imageset, parent); - } else - { - return null; - } - } - - case ProjectionType.Tangent: - { - TangentTile newTile = new TangentTile(level, x, y, imageset, parent); - return newTile; - } - } - - } - - ProjectionType projection; - - public ProjectionType Projection - { - get { return projection; } - set { projection = value; } - } - - private string referenceFrame; - - public string ReferenceFrame - { - get - { - return referenceFrame; - } - set - { - referenceFrame = value; - } - } - - int imageSetID; - public int ImageSetID - { - get - { - return imageSetID; - } - set - { - imageSetID = value; - } - } - - double baseTileDegrees; - public double BaseTileDegrees - { - get - { - return baseTileDegrees; - } - set - { - baseTileDegrees = value; - } - } - - double widthFactor = 1; - - public double WidthFactor - { - get { return widthFactor; } - set { widthFactor = value; } - } - - public int GetHashCode() - { - - return Util.GetHashCode(Url); - } - - protected string url; - public string Url - { - get - { - return url; - } - set - { - url = value; - } - } - - protected string demUrl = ""; - public string DemUrl - { - get - { - if (String.IsNullOrEmpty(demUrl) && projection == ProjectionType.Mercator && !WWTControl.Singleton.FreestandingMode) - { - return URLHelpers.singleton.coreStaticUrl("wwtweb/BingDemTile.aspx?Q={0},{1},{2}"); - } - return demUrl; - } - set - { - demUrl = value; - } - } - - string extension; - public string Extension - { - get - { - return extension; - } - set - { - extension = value; - } - } - - int levels; - public int Levels - { - get - { - return levels; - } - set - { - levels = value; - } - } - bool mercator; - bool bottomsUp; - - public bool BottomsUp - { - get { return bottomsUp; } - set { bottomsUp = value; } - } - - public bool Mercator - { - get { return mercator; } - set { mercator = value; } - } - //private int tileSize = 256; - - //public int TileSize - //{ - // get { return tileSize; } - // set { tileSize = value; } - //} - int baseLevel = 1; - - public int BaseLevel - { - get { return baseLevel; } - set { baseLevel = value; } - } - - string quadTreeTileMap = "0123"; - - public string QuadTreeTileMap - { - get { return quadTreeTileMap; } - set { quadTreeTileMap = value; } - } - double centerX = 0; - - public double CenterX - { - get { return centerX; } - set - { - if (centerX != value) - { - centerX = value; - ComputeMatrix(); - } - } - } - double centerY = 0; - - public double CenterY - { - get { return centerY; } - set - { - if (centerY != value) - { - centerY = value; - ComputeMatrix(); - } - } - } - double rotation = 0; - - public double Rotation - { - get { return rotation; } - set - { - if (rotation != value) - { - rotation = value; - ComputeMatrix(); - } - } - } - - private double meanRadius; - - public double MeanRadius - { - get { return meanRadius; } - set { meanRadius = value; } - } - - - ImageSetType dataSetType = ImageSetType.Earth; - BandPass bandPass = BandPass.Visible; - - public BandPass BandPass - { - get { return bandPass; } - set { bandPass = value; } - } - - public ImageSetType DataSetType - { - get { return dataSetType; } - set { dataSetType = value; } - } - /* - node.Attributes.GetNamedItem("").Value, - Convert.ToDouble(node.Attributes.GetNamedItem("").Value), - Convert.ToInt32(node.Attributes.GetNamedItem("").Value), - - - * */ - string altUrl = ""; - - public string AltUrl - { - get { return altUrl; } - set { altUrl = value; } - } - bool singleImage = false; - - public bool SingleImage - { - get { return singleImage; } - set { singleImage = value; } - } - - HipsProperties hipsProperties; - - public HipsProperties HipsProperties - { - get { return hipsProperties; } - set { hipsProperties = value; } - } - - FitsProperties fitsProperties = new FitsProperties(); - - public FitsProperties FitsProperties - { - get { return fitsProperties; } - set { fitsProperties = value; } - } - - public static Imageset FromXMLNode(XmlNode node) - { - try - { - ImageSetType type = ImageSetType.Sky; - - ProjectionType projection = ProjectionType.Tangent; - - if (node.Attributes.GetNamedItem("DataSetType") != null) - { - type = (ImageSetType)Enums.Parse("ImageSetType", node.Attributes.GetNamedItem("DataSetType").Value); - } - - BandPass bandPass = BandPass.Visible; - - bandPass = (BandPass)Enums.Parse("BandPass",node.Attributes.GetNamedItem("BandPass").Value); - - int wf = 1; - if (node.Attributes.GetNamedItem("WidthFactor") != null) - { - wf = int.Parse(node.Attributes.GetNamedItem("WidthFactor").Value); - } - - if (node.Attributes.GetNamedItem("Generic") == null || !bool.Parse(node.Attributes.GetNamedItem("Generic").Value.ToString())) - { - projection = (ProjectionType)Enums.Parse("ProjectionType", node.Attributes.GetNamedItem("Projection").Value); - - string fileType = node.Attributes.GetNamedItem("FileType").Value.ToString(); - if (!fileType.StartsWith(".")) - { - fileType = "." + fileType; - } - - - string thumbnailUrl = ""; - - XmlNode thumbUrl = Util.SelectSingleNode(node, "ThumbnailUrl"); - if (thumbUrl != null) - { - if (string.IsNullOrEmpty(thumbUrl.InnerText)) - { - ChromeNode cn = (ChromeNode)(object)thumbUrl; - thumbnailUrl = cn.TextContent; - } - else - { - thumbnailUrl = thumbUrl.InnerText; - } - } - - bool stockSet = false; - bool elevationModel = false; - - if (node.Attributes.GetNamedItem("StockSet") != null) - { - stockSet = bool.Parse(node.Attributes.GetNamedItem("StockSet").Value.ToString()); - } - - if (node.Attributes.GetNamedItem("ElevationModel") != null) - { - elevationModel = bool.Parse(node.Attributes.GetNamedItem("ElevationModel").Value.ToString()); - } - - string demUrl = ""; - if (node.Attributes.GetNamedItem("DemUrl") != null) - { - demUrl = node.Attributes.GetNamedItem("DemUrl").Value.ToString(); - } - - string alturl = ""; - - if (node.Attributes.GetNamedItem("AltUrl") != null) - { - alturl = node.Attributes.GetNamedItem("AltUrl").Value.ToString(); - } - - - double offsetX = 0; - - if (node.Attributes.GetNamedItem("OffsetX") != null) - { - offsetX = double.Parse(node.Attributes.GetNamedItem("OffsetX").Value.ToString()); - } - - double offsetY = 0; - - if (node.Attributes.GetNamedItem("OffsetY") != null) - { - offsetY = double.Parse(node.Attributes.GetNamedItem("OffsetY").Value.ToString()); - } - - string creditText = ""; - - XmlNode credits = Util.SelectSingleNode(node, "Credits"); - - if (credits != null) - { - creditText = Util.GetInnerText(credits); - } - - string creditsUrl = ""; - - credits = Util.SelectSingleNode(node, "CreditsUrl"); - - if (credits != null) - { - creditsUrl = Util.GetInnerText(credits); - } - - double meanRadius = 0; - - if (node.Attributes.GetNamedItem("MeanRadius") != null) - { - meanRadius = double.Parse(node.Attributes.GetNamedItem("MeanRadius").Value.ToString()); - } - - string referenceFrame = null; - if (node.Attributes.GetNamedItem("ReferenceFrame") != null) - { - referenceFrame = node.Attributes.GetNamedItem("ReferenceFrame").Value; - } - - string name = ""; - if (node.Attributes.GetNamedItem("Name") != null) - { - name = node.Attributes.GetNamedItem("Name").Value.ToString(); - } - - string url = ""; - if (node.Attributes.GetNamedItem("Url") != null) - { - url = node.Attributes.GetNamedItem("Url").Value.ToString(); - } - - int baseTileLevel = 0; - if (node.Attributes.GetNamedItem("BaseTileLevel") != null) - { - baseTileLevel = int.Parse(node.Attributes.GetNamedItem("BaseTileLevel").Value.ToString()); - } - - int tileLevels = 0; - if (node.Attributes.GetNamedItem("TileLevels") != null) - { - tileLevels = int.Parse(node.Attributes.GetNamedItem("TileLevels").Value.ToString()); - } - - double baseDegreesPerTile = 0; - - if (node.Attributes.GetNamedItem("BaseDegreesPerTile") != null) - { - baseDegreesPerTile = double.Parse(node.Attributes.GetNamedItem("BaseDegreesPerTile").Value.ToString()); - } - - - bool bottomsUp = false; - - - if (node.Attributes.GetNamedItem("BottomsUp") != null) - { - bottomsUp = bool.Parse(node.Attributes.GetNamedItem("BottomsUp").Value.ToString()); - } - - string quadTreeMap = ""; - if (node.Attributes.GetNamedItem("QuadTreeMap") != null) - { - quadTreeMap = node.Attributes.GetNamedItem("QuadTreeMap").Value.ToString(); - } - - double centerX = 0; - - if (node.Attributes.GetNamedItem("CenterX") != null) - { - centerX = double.Parse(node.Attributes.GetNamedItem("CenterX").Value.ToString()); - } - - double centerY = 0; - - if (node.Attributes.GetNamedItem("CenterY") != null) - { - centerY = double.Parse(node.Attributes.GetNamedItem("CenterY").Value.ToString()); - } - - double rotation = 0; - - if (node.Attributes.GetNamedItem("Rotation") != null) - { - rotation = double.Parse(node.Attributes.GetNamedItem("Rotation").Value.ToString()); - } - - bool sparse = false; - - if (node.Attributes.GetNamedItem("Sparse") != null) - { - sparse = bool.Parse(node.Attributes.GetNamedItem("Sparse").Value.ToString()); - } - - return Imageset.Create(name, url, - type, bandPass, projection, Math.Abs(Util.GetHashCode(url)), - baseTileLevel, tileLevels, - 256, baseDegreesPerTile, fileType, - bottomsUp, quadTreeMap, - centerX, centerY, - rotation, sparse, - thumbnailUrl, stockSet, elevationModel, wf, offsetX, offsetY, creditText, creditsUrl, demUrl, alturl, meanRadius, referenceFrame); - } - else - { - return Imageset.CreateGeneric(type, bandPass); - } - - } - catch - { - return null; - } - } - - public static void SaveToXml(XmlTextWriter xmlWriter, Imageset imageset, string alternateUrl) - { - xmlWriter.WriteStartElement("ImageSet"); - - xmlWriter.WriteAttributeString("Generic", imageset.Generic.ToString()); - xmlWriter.WriteAttributeString("DataSetType", Enums.ToXml("ImageSetType", (int)imageset.DataSetType)); - xmlWriter.WriteAttributeString("BandPass", Enums.ToXml("BandPass", (int)imageset.BandPass)); - if (!imageset.Generic) - { - xmlWriter.WriteAttributeString("Name", imageset.Name); - - if (String.IsNullOrEmpty(alternateUrl)) - { - xmlWriter.WriteAttributeString("Url", imageset.Url); - } - else - { - xmlWriter.WriteAttributeString("Url", alternateUrl); - } - xmlWriter.WriteAttributeString("DemUrl", imageset.DemUrl); - xmlWriter.WriteAttributeString("BaseTileLevel", imageset.BaseLevel.ToString()); - xmlWriter.WriteAttributeString("TileLevels", imageset.Levels.ToString()); - xmlWriter.WriteAttributeString("BaseDegreesPerTile", imageset.BaseTileDegrees.ToString()); - xmlWriter.WriteAttributeString("FileType", imageset.Extension); - xmlWriter.WriteAttributeString("BottomsUp", imageset.BottomsUp.ToString()); - xmlWriter.WriteAttributeString("Projection", Enums.ToXml("ProjectionType", (int)imageset.Projection)); - xmlWriter.WriteAttributeString("QuadTreeMap", imageset.QuadTreeTileMap); - xmlWriter.WriteAttributeString("CenterX", imageset.CenterX.ToString()); - xmlWriter.WriteAttributeString("CenterY", imageset.CenterY.ToString()); - xmlWriter.WriteAttributeString("OffsetX", imageset.OffsetX.ToString()); - xmlWriter.WriteAttributeString("OffsetY", imageset.OffsetY.ToString()); - xmlWriter.WriteAttributeString("Rotation", imageset.Rotation.ToString()); - xmlWriter.WriteAttributeString("Sparse", imageset.Sparse.ToString()); - xmlWriter.WriteAttributeString("ElevationModel", imageset.ElevationModel.ToString()); - xmlWriter.WriteAttributeString("StockSet", imageset.DefaultSet.ToString()); - xmlWriter.WriteAttributeString("WidthFactor", imageset.WidthFactor.ToString()); - xmlWriter.WriteAttributeString("MeanRadius", imageset.MeanRadius.ToString()); - xmlWriter.WriteAttributeString("ReferenceFrame", imageset.ReferenceFrame); - if (String.IsNullOrEmpty(alternateUrl)) - { - xmlWriter.WriteElementString("ThumbnailUrl", imageset.ThumbnailUrl); - } - else - { - xmlWriter.WriteElementString("ThumbnailUrl", imageset.Url); - } - } - xmlWriter.WriteEndElement(); - } - - public override string ToString() - { - if (DefaultSet) - { - return name + " *"; - } - else - { - return name; - } - } - - //todo figure out the place for this... - public Imageset StockImageSet - { - get - { - if (generic || !defaultSet) - { - return this; - } - else - { - return Imageset.CreateGeneric(this.DataSetType, this.BandPass); - } - } - } - - //public static bool operator ==(ImageSet left, ImageSet right) - //{ - // if (left == right ) - // { - // return true; - // } - // if (left == null ^ right == null) - // { - // return false; - // } - // return (left.Url.GetHashCode() == right.Url.GetHashCode()); - //} - - //public static bool operator !=(ImageSet left, ImageSet right) - //{ - // if (left == right ) - // { - // return false; - // } - // if ( left == null ^ right == null) - // { - // return true; - // } - - // return (left.Url.GetHashCode() != right.Url.GetHashCode()); - //} - - //public static bool operator ==(ImageSet o1, ImageSet o2) - //{ - // return (Object)o1 == null ? (Object)o2 == null : o1.Equals(o2); - //} - //public static bool operator !=(ImageSet o1, ImageSet o2) - //{ - // return (Object)o1 != null ? (Object)o2 != null : !o1.Equals(o2); - //} - - - - public bool Equals(object obj) - { - if (obj == null) - { - return false; - } - if (!(obj is Imageset)) - { - return false; - } - Imageset b = (Imageset)obj; - - return (Util.GetHashCode(b.Url) == Util.GetHashCode(this.Url) && b.DataSetType == this.DataSetType && b.BandPass == this.BandPass && b.Generic == this.Generic); - - } - - private Matrix3d matrix; - - public Matrix3d Matrix - { - get - { - if (!matrixComputed) - { - ComputeMatrix(); - } - return matrix; - } - set { matrix = value; } - } - bool matrixComputed = false; - private void ComputeMatrix() - { - matrixComputed = true; - matrix = Matrix3d.Identity; - matrix.Multiply(Matrix3d.RotationX((((Rotation)) / 180f * Math.PI))); - matrix.Multiply(Matrix3d.RotationZ(((CenterY) / 180f * Math.PI))); - matrix.Multiply(Matrix3d.RotationY((((360 - CenterX) ) / 180f * Math.PI))); - } - - private string name = ""; - - public string Name - { - get { return name; } - set { name = value; } - } - private bool sparse = false; - - public bool Sparse - { - get { return sparse; } - set { sparse = value; } - } - private string thumbnailUrl = ""; - - public string ThumbnailUrl - { - get { return thumbnailUrl; } - set { thumbnailUrl = value; } - } - private bool generic; - - public bool Generic - { - get { return generic; } - set { generic = value; } - } - - public Imageset() - { - } - - public static Imageset CreateGeneric(ImageSetType dataSetType, BandPass bandPass) - { - Imageset temp = new Imageset(); - temp.generic = true; - temp.name = "Generic"; - temp.sparse = false; - temp.dataSetType = dataSetType; - temp.bandPass = bandPass; - temp.quadTreeTileMap = ""; - temp.url = ""; - temp.levels = 0; - temp.baseTileDegrees = 0; - temp.imageSetID = 0; - temp.extension = ""; - temp.projection = ProjectionType.Equirectangular; - temp.bottomsUp = false; - temp.baseLevel = 0; - temp.mercator = (temp.projection == ProjectionType.Mercator); - temp.centerX = 0; - temp.centerY = 0; - temp.rotation = 0; - //todo add scale - temp.thumbnailUrl = ""; - - temp.matrix = Matrix3d.Identity; - temp.matrix.Multiply(Matrix3d.RotationX((((temp.Rotation)) / 180f * Math.PI))); - temp.matrix.Multiply(Matrix3d.RotationZ(((temp.CenterY) / 180f * Math.PI))); - temp.matrix.Multiply(Matrix3d.RotationY((((360 - temp.CenterX) + 180) / 180f * Math.PI))); - - return temp; - } - - bool defaultSet = false; - bool elevationModel = false; - - public bool ElevationModel - { - get { return elevationModel; } - set { elevationModel = value; } - } - public bool DefaultSet - { - get { return defaultSet; } - set { defaultSet = value; } - } - - double offsetX = 0; - - public double OffsetX - { - get { return offsetX; } - set { offsetX = value; } - } - - - double offsetY = 0; - - public double OffsetY - { - get { return offsetY; } - set { offsetY = value; } - } - - - string creditsText; - - public string CreditsText - { - get { return creditsText; } - set { creditsText = value; } - } - string creditsUrl; - - public string CreditsUrl - { - get { return creditsUrl; } - set { creditsUrl = value; } - } - - public bool IsMandelbrot - { - get - { - return false; - } - } - - // Calculate either the X or Y coordinate of the estimated image center. - // - // This estimate has some important limitations. First, because images - // might contain transparent regions, the "center" of the image that a - // user will perceive might have nothing to do with the center of the - // image bitmap. For instance, imagine that the bitmap is 100x100 but - // that everything is transparent except for 10x10 pixels in the - // top-left corner. We don't know anything about the "barycenter" of the - // image here, so we can't account for that. - // - // Second, for untiled SkyImage imagesets, to properly compute the - // bitmap center we need its dimensions, which simply aren't available - // here. All we can do is guess a "reasonable" image size. - // - // For these reasons, this method should be avoided when possible. The - // preferred way to "know" the location of an image's center is to wrap - // the image in a Place object, which can just specify the exact - // coordinates and zoom level too. - // - // Even disregarding the above, it's non-trivial to locate the image - // center because of the OffsetX/Y parameters and potential rotation of - // the image's coordinate system relative to the sky. - private double CalcViewCenterCoordinate(bool isX) - { - double rot = Coordinates.DegreesToRadians(rotation); - double crot = Math.Cos(rot); - double srot = Math.Sin(rot); - - double dx = 0, dy = 0; - - if (Levels > 0) { - dx = -offsetX; - dy = offsetY; - } else { - // This is the part where we need the image's dimensions to - // be able to compute the center coordinate correctly. Since - // we don't have that information, we just guess :-( - double effWidth = 800; - double effHeight = 800; - - dx = (offsetX - effWidth / 2) * baseTileDegrees; - dy = (effHeight / 2 - offsetY) * baseTileDegrees; - } - - if (bottomsUp) { - dx = -dx; - } - - if (isX) { - return centerX + dx * crot + dy * srot; - } else { - return centerY - dx * srot + dy * crot; - } - } - - public double ViewCenterX - { - get { - if (WcsImage != null) { - return ((WcsImage) WcsImage).ViewCenterX; - } else { - return CalcViewCenterCoordinate(true); - } - } - } - - public double ViewCenterY - { - get { - if (WcsImage != null) { - return ((WcsImage) WcsImage).ViewCenterY; - } else { - return CalcViewCenterCoordinate(false); - } - } - } - - public static Imageset Create(string name, string url, ImageSetType dataSetType, BandPass bandPass, ProjectionType projection, int imageSetID, int baseLevel, int levels, int tileSize, double baseTileDegrees, string extension, bool bottomsUp, string quadTreeMap, double centerX, double centerY, double rotation, bool sparse, string thumbnailUrl, bool defaultSet, bool elevationModel, int wf, double offsetX, double offsetY, string credits, string creditsUrl, string demUrlIn, string alturl, double meanRadius, string referenceFrame) - { - Imageset temp = new Imageset(); - - temp.SetInitialParameters(name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame); - - return temp; - } - - public void SetInitialParameters(string name, string url, ImageSetType dataSetType, BandPass bandPass, ProjectionType projection, int imageSetID, int baseLevel, int levels, double baseTileDegrees, string extension, bool bottomsUp, string quadTreeMap, double centerX, double centerY, double rotation, bool sparse, string thumbnailUrl, bool defaultSet, bool elevationModel, int wf, double offsetX, double offsetY, string credits, string creditsUrl, string demUrlIn, string alturl, double meanRadius, string referenceFrame) - { - this.ReferenceFrame = referenceFrame; - this.MeanRadius = meanRadius; - this.altUrl = alturl; - this.demUrl = demUrlIn; - this.creditsText = credits; - this.creditsUrl = creditsUrl; - this.offsetY = offsetY; - this.offsetX = offsetX; - this.widthFactor = wf; - this.elevationModel = elevationModel; - this.defaultSet = defaultSet; - this.name = name; - this.sparse = sparse; - this.dataSetType = dataSetType; - this.bandPass = bandPass; - this.quadTreeTileMap = quadTreeMap; - this.url = url; - this.levels = levels; - this.baseTileDegrees = baseTileDegrees; - this.imageSetID = imageSetID; - this.extension = extension; - this.projection = projection; - this.bottomsUp = bottomsUp; - this.baseLevel = baseLevel; - this.mercator = (projection == ProjectionType.Mercator); - this.centerX = centerX; - this.centerY = centerY; - this.rotation = rotation; - this.thumbnailUrl = thumbnailUrl; - this.ComputeMatrix(); - } - - // Ideally, imagesets will be associated with Places that specify - // exactly how the view should be set up when "going to" them, but - // sometimes (especially research datasets) we're interested in deriving - // a reasonable zoom setting without that extra information. The returned value - // isn't going to be perfect but it should hopefully be OK. - - private const double FOV_FACTOR = 1.7; - - internal double GuessZoomSetting(double currentZoom) - { - double zoom = currentZoom; - - // ScriptSharp has an issue here. Maybe because we have a field name - // matching a class name? Right now the only implementation of - // WcsImage is FitsImage so we can get away with this: - WcsImage aswcs = this.wcsImage as FitsImage; - - if (Projection == ProjectionType.SkyImage) { - // Untiled SkyImage: basetiledegrees is degrees per pixel - if (aswcs != null) { - zoom = BaseTileDegrees * aswcs.SizeY * 6 * FOV_FACTOR; - } - } else if (aswcs != null) { - zoom = aswcs.ScaleY * aswcs.SizeY * 6 * FOV_FACTOR; - } else { - // Tiled. basetiledegrees is angular height of whole image after - // power-of-2 padding. - zoom = BaseTileDegrees * 6 * FOV_FACTOR; - } - - // Only zoom in, not out. Usability-wise this tends to make the most - // sense. - - if (zoom > currentZoom) { - zoom = currentZoom; - } - - return zoom; - } - - // URL parameters - //{0} ImageSetID - //{1} level - //{2} x tile id - //{3} y tile id - //{4} quadtree address (VE style) - //{5} quadtree address (Google maps style) - //{6} top left corner RA - //{7} top left corner Dec - //{8} bottom right corner RA - //{9} bottom right corner dec - //{10} bottom left corner RA - //{11} bottom left corner dec - //{12} top right corner RA - //{13} top right corner dec - - #region IThumbnail Members - - ImageElement thumbnail; - public System.Html.ImageElement Thumbnail - { - get - { - return thumbnail; - } - set - { - thumbnail = value; - } - } - Rectangle bounds; - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - public bool IsImage - { - get { return true; } - } - - public bool IsTour - { - get { return false; } - } - - public bool IsFolder - { - get { return false; } - } - - public bool IsCloudCommunityItem - { - get { return false; } - } - - public bool ReadOnly - { - get { return false; } - } - - public List Children - { - get { return new List(); } - } - - #endregion - } -} diff --git a/engine/csharp_ref/Imports.cs b/engine/csharp_ref/Imports.cs deleted file mode 100644 index b6e551fc..00000000 --- a/engine/csharp_ref/Imports.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -public static class Imports -{ - - /* It would ideal to use a helper function to generate the string literals here - given the library name, but Script.Literal requires a constant string. - It's not possible to create a constant string via interpolation until C# 10. - */ - static Imports() - { - // pako - Script.Literal("let pako"); - Script.Literal("if (typeof window !== \"undefined\" && \"pako\" in window) {"); - Script.Literal(" pako = window[\"pako\"]"); - Script.Literal("} else {"); - Script.Literal(" import('pako').then(function(result) { pako = result; })"); - Script.Literal("}"); - - // uuid - Script.Literal("let uuid"); - Script.Literal("if (typeof window !== \"undefined\" && \"uuid\" in window) {"); - Script.Literal(" uuid = window[\"uuid\"]"); - Script.Literal("} else {"); - Script.Literal(" import('uuid').then(function(result) { uuid = result; })"); - Script.Literal("}"); - } -} diff --git a/engine/csharp_ref/KeplerVertex.cs b/engine/csharp_ref/KeplerVertex.cs deleted file mode 100644 index c1e29964..00000000 --- a/engine/csharp_ref/KeplerVertex.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - - - -namespace wwtlib -{ - - - public class KeplerVertex - { - - public Vector3d ABC = new Vector3d(); - public Vector3d abc1 = new Vector3d(); - public float PointSize; - public Color Color; - - public float w; - public float e; - public float n; - public float T; - public float a; - public float z; - public float orbitPos; - public float orbits; - - static double sine = .0; - static double cose = 1; - static double degrad = Math.PI / 180; - - - - public static int baseDate = (int)SpaceTimeController.UtcToJulian(Date.Now); - public void Fill(EOE ee) - { - double F = Math.Cos(ee.omega * degrad); - double sinOmega = Math.Sin(ee.omega * degrad); - double cosi = Math.Cos(ee.i * degrad); - double sini = Math.Sin(ee.i * degrad); - double G = sinOmega * cose; - double H = sinOmega * sine; - double P = -sinOmega * cosi; - double Q = (F * cosi * cose) - (sini * sine); - double R = (F * cosi * sine) + (sini * cose); - - double checkA = (F * F) + (G * G) + (H * H);// Should be 1.0 - double checkB = (P * P) + (Q * Q) + (R * R); // should be 1.0 as well - - ABC.X = (float)Math.Atan2(F, P); - ABC.Y = (float)Math.Atan2(G, Q); - ABC.Z = (float)Math.Atan2(H, R); - - abc1.X = (float)Math.Sqrt((F * F) + (P * P)); - abc1.Y = (float)Math.Sqrt((G * G) + (Q * Q)); - abc1.Z = (float)Math.Sqrt((H * H) + (R * R)); - - PointSize = .1f; - if (ee.a < 2.5) - { - Color = Colors.White; - } - else if (ee.a < 2.83) - { - Color = Colors.Red; - } - else if (ee.a < 2.96) - { - Color = Colors.Green; - } - else if (ee.a < 3.3) - { - Color = Colors.Magenta; - } - else if (ee.a < 5) - { - Color = Colors.Cyan; - } - else if (ee.a < 10) - { - Color = Colors.Yellow; - PointSize = .9f; - } - else - { - Color = Colors.White; - PointSize = 8f; - } - w = (float)ee.w; - e = (float)ee.e; - if (ee.n == 0) - { - n = (float)((0.9856076686 / (ee.a * Math.Sqrt(ee.a)))); - } - else - { - n = (float)ee.n; - } - T = (float)(ee.T - baseDate); - a = (float)ee.a; - z = 0; - - orbitPos = 0; - orbits = 0; - - } - } -} \ No newline at end of file diff --git a/engine/csharp_ref/Layers/ColorMapContainer.cs b/engine/csharp_ref/Layers/ColorMapContainer.cs deleted file mode 100644 index c5787818..00000000 --- a/engine/csharp_ref/Layers/ColorMapContainer.cs +++ /dev/null @@ -1,654 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - -namespace wwtlib -{ - - public class ColorMapContainer - { - - // This class is intended to be used to store colormaps. It does not handle any - // interpolation and when using FindClosestColor it will simply check which - // color is closest to the requested value. Therefore, continuous colormaps should - // be created by providing a sufficient number of colors (ideally 256 or more). - - public List colors = new List(); - public static Dictionary ColorTextures = new Dictionary(); - - public static ColorMapContainer FromArgbList(List> color_list) - { - - // Class method to create a new colormap from a list of [a, r, g, b] lists. - - ColorMapContainer temp = new ColorMapContainer(); - foreach (List color in color_list) - { - temp.colors.Add(Color.FromArgb(color[0], color[1], color[2], color[3])); - } - return temp; - } - - public static ColorMapContainer FromStringList(List color_list) - { - - // Class method to create a new colormap from a list of strings. - - ColorMapContainer temp = new ColorMapContainer(); - foreach (string color in color_list) - { - temp.colors.Add(Color.Load(color)); - } - return temp; - } - - public Color FindClosestColor(float value) - { - // Given a floating-point value in the range 0 to 1, find the color that is the - // closest to it. - - int index; - - if (value <= 0) { - return colors[0]; - } else if (value >= 1) { - return colors[colors.Count - 1]; - } else { - index = (int)(value * colors.Count); - return colors[index]; - } - - } - - public static ColorMapContainer FromNamedColormap(string name) - { - if (name == null) { - return null; - } - - // Names are chosen to match matplotlib (which explains why some - // are less-than-ideal). - switch (name.ToLowerCase()) - { - case "viridis": - return Viridis; - case "plasma": - return Plasma; - case "inferno": - return Inferno; - case "magma": - return Magma; - case "cividis": - return Cividis; - case "greys": // this is 0=>white, 1=>black - return Greys; - case "gray": - return Gray; // this is 0=>black, 1=>white - case "purples": - return Purples; - case "blues": - return Blues; - case "greens": - return Greens; - case "oranges": - return Oranges; - case "reds": - return Reds; - case "rdylbu": - return RdYlBu; - } - return null; - } - - - private static WebGLTexture GetTextureFromName(GL gl, string name) - { - WebGLTexture texture = ColorTextures[name]; - if (texture == null) - { - ColorMapContainer colorMapContainer = FromNamedColormap(name); - if (colorMapContainer != null) - { - texture = InitColorTexture(gl, colorMapContainer); - ColorTextures[name.ToLowerCase()] = texture; - } - } - - return texture; - } - - public static void BindColorMapTexture(GL gl, string colorMapName) - { - WebGLTexture texture = GetTextureFromName(gl, colorMapName); - if (texture == null) - { - texture = GetTextureFromName(gl, "gray"); - } - gl.activeTexture(GL.TEXTURE1); - gl.bindTexture(GL.TEXTURE_2D, texture); - } - - private static WebGLTexture InitColorTexture(GL gl, ColorMapContainer colorMapContainer) - { - WebGLTexture colorTexture = gl.createTexture(); - gl.activeTexture(GL.TEXTURE1); - - gl.bindTexture(GL.TEXTURE_2D, colorTexture); - gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE); - gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE); - - Uint8Array colorBuffer = ExtractColorArray(colorMapContainer.colors); - - gl.texImage2D(GL.TEXTURE_2D, 0, GL.RGB8, colorBuffer.length / 3, 1, 0, GL.RGB, GL.UNSIGNED_BYTE, colorBuffer); - gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST); - gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST); - return colorTexture; - } - - private static Uint8Array ExtractColorArray(List colors) - { - int index = 0; - Uint8Array colorBuffer = new Uint8Array(colors.Count * 3); - foreach (Color color in colors) - { - colorBuffer[index++] = (byte)color.R; - colorBuffer[index++] = (byte)color.G; - colorBuffer[index++] = (byte)color.B; - } - return colorBuffer; - } - - // The colormaps below were produced using the following Python code: - // - // import numpy as np - // from matplotlib import cm - // from matplotlib.colors import to_hex - // from textwrap import wrap, indent - // - // TEMPLATE = """ - // public static ColorMapContainer {name} = ColorMapContainer.FromStringList(new List( - // {colors} - // )); - // """ - // - // TEMPLATE_CASE = """ - // case "{name_lower}": - // return {name};""" - // COLORMAPS = ["viridis", "plasma", "inferno", "magma", "cividis", - // "Greys", "gray", "Purples", "Blues", "Greens", "Oranges", "Reds", "RdYlBu"] - // - // named_code = "" - // case_code = "" - // - // for name in COLORMAPS: - // cmap = cm.get_cmap(name) - // x = np.linspace(0.5 / 256, 255.5/256, 256) - // colors = ", ".join(['"{0}"'.format(to_hex(c)) for c in cmap(x)]) - // pretty_name = name[0].upper() + name[1:] - // named_code += TEMPLATE.format(name=pretty_name, colors=indent('\n'.join(wrap(colors, 90)), " " * 10)) - // case_code += TEMPLATE_CASE.format(name=pretty_name, name_lower=name.lower()) - // - // named_code = indent(named_code, " " * 8) - // - // print(named_code) - // print('-' * 72) - // print(case_code) - - public static ColorMapContainer Viridis = ColorMapContainer.FromStringList(new List( - "#440154", "#440256", "#450457", "#450559", "#46075a", "#46085c", "#460a5d", "#460b5e", - "#470d60", "#470e61", "#471063", "#471164", "#471365", "#481467", "#481668", "#481769", - "#48186a", "#481a6c", "#481b6d", "#481c6e", "#481d6f", "#481f70", "#482071", "#482173", - "#482374", "#482475", "#482576", "#482677", "#482878", "#482979", "#472a7a", "#472c7a", - "#472d7b", "#472e7c", "#472f7d", "#46307e", "#46327e", "#46337f", "#463480", "#453581", - "#453781", "#453882", "#443983", "#443a83", "#443b84", "#433d84", "#433e85", "#423f85", - "#424086", "#424186", "#414287", "#414487", "#404588", "#404688", "#3f4788", "#3f4889", - "#3e4989", "#3e4a89", "#3e4c8a", "#3d4d8a", "#3d4e8a", "#3c4f8a", "#3c508b", "#3b518b", - "#3b528b", "#3a538b", "#3a548c", "#39558c", "#39568c", "#38588c", "#38598c", "#375a8c", - "#375b8d", "#365c8d", "#365d8d", "#355e8d", "#355f8d", "#34608d", "#34618d", "#33628d", - "#33638d", "#32648e", "#32658e", "#31668e", "#31678e", "#31688e", "#30698e", "#306a8e", - "#2f6b8e", "#2f6c8e", "#2e6d8e", "#2e6e8e", "#2e6f8e", "#2d708e", "#2d718e", "#2c718e", - "#2c728e", "#2c738e", "#2b748e", "#2b758e", "#2a768e", "#2a778e", "#2a788e", "#29798e", - "#297a8e", "#297b8e", "#287c8e", "#287d8e", "#277e8e", "#277f8e", "#27808e", "#26818e", - "#26828e", "#26828e", "#25838e", "#25848e", "#25858e", "#24868e", "#24878e", "#23888e", - "#23898e", "#238a8d", "#228b8d", "#228c8d", "#228d8d", "#218e8d", "#218f8d", "#21908d", - "#21918c", "#20928c", "#20928c", "#20938c", "#1f948c", "#1f958b", "#1f968b", "#1f978b", - "#1f988b", "#1f998a", "#1f9a8a", "#1e9b8a", "#1e9c89", "#1e9d89", "#1f9e89", "#1f9f88", - "#1fa088", "#1fa188", "#1fa187", "#1fa287", "#20a386", "#20a486", "#21a585", "#21a685", - "#22a785", "#22a884", "#23a983", "#24aa83", "#25ab82", "#25ac82", "#26ad81", "#27ad81", - "#28ae80", "#29af7f", "#2ab07f", "#2cb17e", "#2db27d", "#2eb37c", "#2fb47c", "#31b57b", - "#32b67a", "#34b679", "#35b779", "#37b878", "#38b977", "#3aba76", "#3bbb75", "#3dbc74", - "#3fbc73", "#40bd72", "#42be71", "#44bf70", "#46c06f", "#48c16e", "#4ac16d", "#4cc26c", - "#4ec36b", "#50c46a", "#52c569", "#54c568", "#56c667", "#58c765", "#5ac864", "#5cc863", - "#5ec962", "#60ca60", "#63cb5f", "#65cb5e", "#67cc5c", "#69cd5b", "#6ccd5a", "#6ece58", - "#70cf57", "#73d056", "#75d054", "#77d153", "#7ad151", "#7cd250", "#7fd34e", "#81d34d", - "#84d44b", "#86d549", "#89d548", "#8bd646", "#8ed645", "#90d743", "#93d741", "#95d840", - "#98d83e", "#9bd93c", "#9dd93b", "#a0da39", "#a2da37", "#a5db36", "#a8db34", "#aadc32", - "#addc30", "#b0dd2f", "#b2dd2d", "#b5de2b", "#b8de29", "#bade28", "#bddf26", "#c0df25", - "#c2df23", "#c5e021", "#c8e020", "#cae11f", "#cde11d", "#d0e11c", "#d2e21b", "#d5e21a", - "#d8e219", "#dae319", "#dde318", "#dfe318", "#e2e418", "#e5e419", "#e7e419", "#eae51a", - "#ece51b", "#efe51c", "#f1e51d", "#f4e61e", "#f6e620", "#f8e621", "#fbe723", "#fde725" - )); - - public static ColorMapContainer Plasma = ColorMapContainer.FromStringList(new List( - "#0d0887", "#100788", "#130789", "#16078a", "#19068c", "#1b068d", "#1d068e", "#20068f", - "#220690", "#240691", "#260591", "#280592", "#2a0593", "#2c0594", "#2e0595", "#2f0596", - "#310597", "#330597", "#350498", "#370499", "#38049a", "#3a049a", "#3c049b", "#3e049c", - "#3f049c", "#41049d", "#43039e", "#44039e", "#46039f", "#48039f", "#4903a0", "#4b03a1", - "#4c02a1", "#4e02a2", "#5002a2", "#5102a3", "#5302a3", "#5502a4", "#5601a4", "#5801a4", - "#5901a5", "#5b01a5", "#5c01a6", "#5e01a6", "#6001a6", "#6100a7", "#6300a7", "#6400a7", - "#6600a7", "#6700a8", "#6900a8", "#6a00a8", "#6c00a8", "#6e00a8", "#6f00a8", "#7100a8", - "#7201a8", "#7401a8", "#7501a8", "#7701a8", "#7801a8", "#7a02a8", "#7b02a8", "#7d03a8", - "#7e03a8", "#8004a8", "#8104a7", "#8305a7", "#8405a7", "#8606a6", "#8707a6", "#8808a6", - "#8a09a5", "#8b0aa5", "#8d0ba5", "#8e0ca4", "#8f0da4", "#910ea3", "#920fa3", "#9410a2", - "#9511a1", "#9613a1", "#9814a0", "#99159f", "#9a169f", "#9c179e", "#9d189d", "#9e199d", - "#a01a9c", "#a11b9b", "#a21d9a", "#a31e9a", "#a51f99", "#a62098", "#a72197", "#a82296", - "#aa2395", "#ab2494", "#ac2694", "#ad2793", "#ae2892", "#b02991", "#b12a90", "#b22b8f", - "#b32c8e", "#b42e8d", "#b52f8c", "#b6308b", "#b7318a", "#b83289", "#ba3388", "#bb3488", - "#bc3587", "#bd3786", "#be3885", "#bf3984", "#c03a83", "#c13b82", "#c23c81", "#c33d80", - "#c43e7f", "#c5407e", "#c6417d", "#c7427c", "#c8437b", "#c9447a", "#ca457a", "#cb4679", - "#cc4778", "#cc4977", "#cd4a76", "#ce4b75", "#cf4c74", "#d04d73", "#d14e72", "#d24f71", - "#d35171", "#d45270", "#d5536f", "#d5546e", "#d6556d", "#d7566c", "#d8576b", "#d9586a", - "#da5a6a", "#da5b69", "#db5c68", "#dc5d67", "#dd5e66", "#de5f65", "#de6164", "#df6263", - "#e06363", "#e16462", "#e26561", "#e26660", "#e3685f", "#e4695e", "#e56a5d", "#e56b5d", - "#e66c5c", "#e76e5b", "#e76f5a", "#e87059", "#e97158", "#e97257", "#ea7457", "#eb7556", - "#eb7655", "#ec7754", "#ed7953", "#ed7a52", "#ee7b51", "#ef7c51", "#ef7e50", "#f07f4f", - "#f0804e", "#f1814d", "#f1834c", "#f2844b", "#f3854b", "#f3874a", "#f48849", "#f48948", - "#f58b47", "#f58c46", "#f68d45", "#f68f44", "#f79044", "#f79143", "#f79342", "#f89441", - "#f89540", "#f9973f", "#f9983e", "#f99a3e", "#fa9b3d", "#fa9c3c", "#fa9e3b", "#fb9f3a", - "#fba139", "#fba238", "#fca338", "#fca537", "#fca636", "#fca835", "#fca934", "#fdab33", - "#fdac33", "#fdae32", "#fdaf31", "#fdb130", "#fdb22f", "#fdb42f", "#fdb52e", "#feb72d", - "#feb82c", "#feba2c", "#febb2b", "#febd2a", "#febe2a", "#fec029", "#fdc229", "#fdc328", - "#fdc527", "#fdc627", "#fdc827", "#fdca26", "#fdcb26", "#fccd25", "#fcce25", "#fcd025", - "#fcd225", "#fbd324", "#fbd524", "#fbd724", "#fad824", "#fada24", "#f9dc24", "#f9dd25", - "#f8df25", "#f8e125", "#f7e225", "#f7e425", "#f6e626", "#f6e826", "#f5e926", "#f5eb27", - "#f4ed27", "#f3ee27", "#f3f027", "#f2f227", "#f1f426", "#f1f525", "#f0f724", "#f0f921" - )); - - public static ColorMapContainer Inferno = ColorMapContainer.FromStringList(new List( - "#000004", "#010005", "#010106", "#010108", "#02010a", "#02020c", "#02020e", "#030210", - "#040312", "#040314", "#050417", "#060419", "#07051b", "#08051d", "#09061f", "#0a0722", - "#0b0724", "#0c0826", "#0d0829", "#0e092b", "#10092d", "#110a30", "#120a32", "#140b34", - "#150b37", "#160b39", "#180c3c", "#190c3e", "#1b0c41", "#1c0c43", "#1e0c45", "#1f0c48", - "#210c4a", "#230c4c", "#240c4f", "#260c51", "#280b53", "#290b55", "#2b0b57", "#2d0b59", - "#2f0a5b", "#310a5c", "#320a5e", "#340a5f", "#360961", "#380962", "#390963", "#3b0964", - "#3d0965", "#3e0966", "#400a67", "#420a68", "#440a68", "#450a69", "#470b6a", "#490b6a", - "#4a0c6b", "#4c0c6b", "#4d0d6c", "#4f0d6c", "#510e6c", "#520e6d", "#540f6d", "#550f6d", - "#57106e", "#59106e", "#5a116e", "#5c126e", "#5d126e", "#5f136e", "#61136e", "#62146e", - "#64156e", "#65156e", "#67166e", "#69166e", "#6a176e", "#6c186e", "#6d186e", "#6f196e", - "#71196e", "#721a6e", "#741a6e", "#751b6e", "#771c6d", "#781c6d", "#7a1d6d", "#7c1d6d", - "#7d1e6d", "#7f1e6c", "#801f6c", "#82206c", "#84206b", "#85216b", "#87216b", "#88226a", - "#8a226a", "#8c2369", "#8d2369", "#8f2469", "#902568", "#922568", "#932667", "#952667", - "#972766", "#982766", "#9a2865", "#9b2964", "#9d2964", "#9f2a63", "#a02a63", "#a22b62", - "#a32c61", "#a52c60", "#a62d60", "#a82e5f", "#a92e5e", "#ab2f5e", "#ad305d", "#ae305c", - "#b0315b", "#b1325a", "#b3325a", "#b43359", "#b63458", "#b73557", "#b93556", "#ba3655", - "#bc3754", "#bd3853", "#bf3952", "#c03a51", "#c13a50", "#c33b4f", "#c43c4e", "#c63d4d", - "#c73e4c", "#c83f4b", "#ca404a", "#cb4149", "#cc4248", "#ce4347", "#cf4446", "#d04545", - "#d24644", "#d34743", "#d44842", "#d54a41", "#d74b3f", "#d84c3e", "#d94d3d", "#da4e3c", - "#db503b", "#dd513a", "#de5238", "#df5337", "#e05536", "#e15635", "#e25734", "#e35933", - "#e45a31", "#e55c30", "#e65d2f", "#e75e2e", "#e8602d", "#e9612b", "#ea632a", "#eb6429", - "#eb6628", "#ec6726", "#ed6925", "#ee6a24", "#ef6c23", "#ef6e21", "#f06f20", "#f1711f", - "#f1731d", "#f2741c", "#f3761b", "#f37819", "#f47918", "#f57b17", "#f57d15", "#f67e14", - "#f68013", "#f78212", "#f78410", "#f8850f", "#f8870e", "#f8890c", "#f98b0b", "#f98c0a", - "#f98e09", "#fa9008", "#fa9207", "#fa9407", "#fb9606", "#fb9706", "#fb9906", "#fb9b06", - "#fb9d07", "#fc9f07", "#fca108", "#fca309", "#fca50a", "#fca60c", "#fca80d", "#fcaa0f", - "#fcac11", "#fcae12", "#fcb014", "#fcb216", "#fcb418", "#fbb61a", "#fbb81d", "#fbba1f", - "#fbbc21", "#fbbe23", "#fac026", "#fac228", "#fac42a", "#fac62d", "#f9c72f", "#f9c932", - "#f9cb35", "#f8cd37", "#f8cf3a", "#f7d13d", "#f7d340", "#f6d543", "#f6d746", "#f5d949", - "#f5db4c", "#f4dd4f", "#f4df53", "#f4e156", "#f3e35a", "#f3e55d", "#f2e661", "#f2e865", - "#f2ea69", "#f1ec6d", "#f1ed71", "#f1ef75", "#f1f179", "#f2f27d", "#f2f482", "#f3f586", - "#f3f68a", "#f4f88e", "#f5f992", "#f6fa96", "#f8fb9a", "#f9fc9d", "#fafda1", "#fcffa4" - )); - - public static ColorMapContainer Magma = ColorMapContainer.FromStringList(new List( - "#000004", "#010005", "#010106", "#010108", "#020109", "#02020b", "#02020d", "#03030f", - "#030312", "#040414", "#050416", "#060518", "#06051a", "#07061c", "#08071e", "#090720", - "#0a0822", "#0b0924", "#0c0926", "#0d0a29", "#0e0b2b", "#100b2d", "#110c2f", "#120d31", - "#130d34", "#140e36", "#150e38", "#160f3b", "#180f3d", "#19103f", "#1a1042", "#1c1044", - "#1d1147", "#1e1149", "#20114b", "#21114e", "#221150", "#241253", "#251255", "#271258", - "#29115a", "#2a115c", "#2c115f", "#2d1161", "#2f1163", "#311165", "#331067", "#341069", - "#36106b", "#38106c", "#390f6e", "#3b0f70", "#3d0f71", "#3f0f72", "#400f74", "#420f75", - "#440f76", "#451077", "#471078", "#491078", "#4a1079", "#4c117a", "#4e117b", "#4f127b", - "#51127c", "#52137c", "#54137d", "#56147d", "#57157e", "#59157e", "#5a167e", "#5c167f", - "#5d177f", "#5f187f", "#601880", "#621980", "#641a80", "#651a80", "#671b80", "#681c81", - "#6a1c81", "#6b1d81", "#6d1d81", "#6e1e81", "#701f81", "#721f81", "#732081", "#752181", - "#762181", "#782281", "#792282", "#7b2382", "#7c2382", "#7e2482", "#802582", "#812581", - "#832681", "#842681", "#862781", "#882781", "#892881", "#8b2981", "#8c2981", "#8e2a81", - "#902a81", "#912b81", "#932b80", "#942c80", "#962c80", "#982d80", "#992d80", "#9b2e7f", - "#9c2e7f", "#9e2f7f", "#a02f7f", "#a1307e", "#a3307e", "#a5317e", "#a6317d", "#a8327d", - "#aa337d", "#ab337c", "#ad347c", "#ae347b", "#b0357b", "#b2357b", "#b3367a", "#b5367a", - "#b73779", "#b83779", "#ba3878", "#bc3978", "#bd3977", "#bf3a77", "#c03a76", "#c23b75", - "#c43c75", "#c53c74", "#c73d73", "#c83e73", "#ca3e72", "#cc3f71", "#cd4071", "#cf4070", - "#d0416f", "#d2426f", "#d3436e", "#d5446d", "#d6456c", "#d8456c", "#d9466b", "#db476a", - "#dc4869", "#de4968", "#df4a68", "#e04c67", "#e24d66", "#e34e65", "#e44f64", "#e55064", - "#e75263", "#e85362", "#e95462", "#ea5661", "#eb5760", "#ec5860", "#ed5a5f", "#ee5b5e", - "#ef5d5e", "#f05f5e", "#f1605d", "#f2625d", "#f2645c", "#f3655c", "#f4675c", "#f4695c", - "#f56b5c", "#f66c5c", "#f66e5c", "#f7705c", "#f7725c", "#f8745c", "#f8765c", "#f9785d", - "#f9795d", "#f97b5d", "#fa7d5e", "#fa7f5e", "#fa815f", "#fb835f", "#fb8560", "#fb8761", - "#fc8961", "#fc8a62", "#fc8c63", "#fc8e64", "#fc9065", "#fd9266", "#fd9467", "#fd9668", - "#fd9869", "#fd9a6a", "#fd9b6b", "#fe9d6c", "#fe9f6d", "#fea16e", "#fea36f", "#fea571", - "#fea772", "#fea973", "#feaa74", "#feac76", "#feae77", "#feb078", "#feb27a", "#feb47b", - "#feb67c", "#feb77e", "#feb97f", "#febb81", "#febd82", "#febf84", "#fec185", "#fec287", - "#fec488", "#fec68a", "#fec88c", "#feca8d", "#fecc8f", "#fecd90", "#fecf92", "#fed194", - "#fed395", "#fed597", "#fed799", "#fed89a", "#fdda9c", "#fddc9e", "#fddea0", "#fde0a1", - "#fde2a3", "#fde3a5", "#fde5a7", "#fde7a9", "#fde9aa", "#fdebac", "#fcecae", "#fceeb0", - "#fcf0b2", "#fcf2b4", "#fcf4b6", "#fcf6b8", "#fcf7b9", "#fcf9bb", "#fcfbbd", "#fcfdbf" - )); - - public static ColorMapContainer Cividis = ColorMapContainer.FromStringList(new List( - "#00224e", "#00234f", "#002451", "#002553", "#002554", "#002656", "#002758", "#002859", - "#00285b", "#00295d", "#002a5f", "#002a61", "#002b62", "#002c64", "#002c66", "#002d68", - "#002e6a", "#002e6c", "#002f6d", "#00306f", "#003070", "#003170", "#003171", "#013271", - "#053371", "#083370", "#0c3470", "#0f3570", "#123570", "#143670", "#163770", "#18376f", - "#1a386f", "#1c396f", "#1e3a6f", "#203a6f", "#213b6e", "#233c6e", "#243c6e", "#263d6e", - "#273e6e", "#293f6e", "#2a3f6d", "#2b406d", "#2d416d", "#2e416d", "#2f426d", "#31436d", - "#32436d", "#33446d", "#34456c", "#35456c", "#36466c", "#38476c", "#39486c", "#3a486c", - "#3b496c", "#3c4a6c", "#3d4a6c", "#3e4b6c", "#3f4c6c", "#404c6c", "#414d6c", "#424e6c", - "#434e6c", "#444f6c", "#45506c", "#46516c", "#47516c", "#48526c", "#49536c", "#4a536c", - "#4b546c", "#4c556c", "#4d556c", "#4e566c", "#4f576c", "#50576c", "#51586d", "#52596d", - "#535a6d", "#545a6d", "#555b6d", "#555c6d", "#565c6d", "#575d6d", "#585e6d", "#595e6e", - "#5a5f6e", "#5b606e", "#5c616e", "#5d616e", "#5e626e", "#5e636f", "#5f636f", "#60646f", - "#61656f", "#62656f", "#636670", "#646770", "#656870", "#656870", "#666970", "#676a71", - "#686a71", "#696b71", "#6a6c71", "#6b6d72", "#6c6d72", "#6c6e72", "#6d6f72", "#6e6f73", - "#6f7073", "#707173", "#717274", "#727274", "#727374", "#737475", "#747475", "#757575", - "#767676", "#777776", "#777777", "#787877", "#797977", "#7a7a78", "#7b7a78", "#7c7b78", - "#7d7c78", "#7e7c78", "#7e7d78", "#7f7e78", "#807f78", "#817f78", "#828079", "#838179", - "#848279", "#858279", "#868379", "#878478", "#888578", "#898578", "#8a8678", "#8b8778", - "#8c8878", "#8d8878", "#8e8978", "#8f8a78", "#908b78", "#918b78", "#928c78", "#928d78", - "#938e78", "#948e77", "#958f77", "#969077", "#979177", "#989277", "#999277", "#9a9376", - "#9b9476", "#9c9576", "#9d9576", "#9e9676", "#9f9775", "#a09875", "#a19975", "#a29975", - "#a39a74", "#a49b74", "#a59c74", "#a69c74", "#a79d73", "#a89e73", "#a99f73", "#aaa073", - "#aba072", "#aca172", "#ada272", "#aea371", "#afa471", "#b0a571", "#b1a570", "#b3a670", - "#b4a76f", "#b5a86f", "#b6a96f", "#b7a96e", "#b8aa6e", "#b9ab6d", "#baac6d", "#bbad6d", - "#bcae6c", "#bdae6c", "#beaf6b", "#bfb06b", "#c0b16a", "#c1b26a", "#c2b369", "#c3b369", - "#c4b468", "#c5b568", "#c6b667", "#c7b767", "#c8b866", "#c9b965", "#cbb965", "#ccba64", - "#cdbb63", "#cebc63", "#cfbd62", "#d0be62", "#d1bf61", "#d2c060", "#d3c05f", "#d4c15f", - "#d5c25e", "#d6c35d", "#d7c45c", "#d9c55c", "#dac65b", "#dbc75a", "#dcc859", "#ddc858", - "#dec958", "#dfca57", "#e0cb56", "#e1cc55", "#e2cd54", "#e4ce53", "#e5cf52", "#e6d051", - "#e7d150", "#e8d24f", "#e9d34e", "#ead34c", "#ebd44b", "#edd54a", "#eed649", "#efd748", - "#f0d846", "#f1d945", "#f2da44", "#f3db42", "#f5dc41", "#f6dd3f", "#f7de3e", "#f8df3c", - "#f9e03a", "#fbe138", "#fce236", "#fde334", "#fee434", "#fee535", "#fee636", "#fee838" - )); - - public static ColorMapContainer Greys = ColorMapContainer.FromStringList(new List( - "#ffffff", "#ffffff", "#fefefe", "#fefefe", "#fdfdfd", "#fdfdfd", "#fcfcfc", "#fcfcfc", - "#fbfbfb", "#fbfbfb", "#fafafa", "#fafafa", "#f9f9f9", "#f9f9f9", "#f8f8f8", "#f8f8f8", - "#f7f7f7", "#f7f7f7", "#f7f7f7", "#f6f6f6", "#f6f6f6", "#f5f5f5", "#f5f5f5", "#f4f4f4", - "#f4f4f4", "#f3f3f3", "#f3f3f3", "#f2f2f2", "#f2f2f2", "#f1f1f1", "#f1f1f1", "#f0f0f0", - "#f0f0f0", "#efefef", "#eeeeee", "#eeeeee", "#ededed", "#ececec", "#ececec", "#ebebeb", - "#eaeaea", "#e9e9e9", "#e9e9e9", "#e8e8e8", "#e7e7e7", "#e7e7e7", "#e6e6e6", "#e5e5e5", - "#e4e4e4", "#e4e4e4", "#e3e3e3", "#e2e2e2", "#e1e1e1", "#e1e1e1", "#e0e0e0", "#dfdfdf", - "#dfdfdf", "#dedede", "#dddddd", "#dcdcdc", "#dcdcdc", "#dbdbdb", "#dadada", "#dadada", - "#d9d9d9", "#d8d8d8", "#d7d7d7", "#d6d6d6", "#d5d5d5", "#d4d4d4", "#d4d4d4", "#d3d3d3", - "#d2d2d2", "#d1d1d1", "#d0d0d0", "#cfcfcf", "#cecece", "#cdcdcd", "#cccccc", "#cccccc", - "#cbcbcb", "#cacaca", "#c9c9c9", "#c8c8c8", "#c7c7c7", "#c6c6c6", "#c5c5c5", "#c5c5c5", - "#c4c4c4", "#c3c3c3", "#c2c2c2", "#c1c1c1", "#c0c0c0", "#bfbfbf", "#bebebe", "#bebebe", - "#bdbdbd", "#bbbbbb", "#bababa", "#b9b9b9", "#b8b8b8", "#b6b6b6", "#b5b5b5", "#b4b4b4", - "#b3b3b3", "#b2b2b2", "#b0b0b0", "#afafaf", "#aeaeae", "#adadad", "#ababab", "#aaaaaa", - "#a9a9a9", "#a8a8a8", "#a7a7a7", "#a5a5a5", "#a4a4a4", "#a3a3a3", "#a2a2a2", "#a0a0a0", - "#9f9f9f", "#9e9e9e", "#9d9d9d", "#9c9c9c", "#9a9a9a", "#999999", "#989898", "#979797", - "#959595", "#949494", "#939393", "#929292", "#919191", "#909090", "#8f8f8f", "#8e8e8e", - "#8d8d8d", "#8c8c8c", "#8a8a8a", "#898989", "#888888", "#878787", "#868686", "#858585", - "#848484", "#838383", "#828282", "#818181", "#7f7f7f", "#7e7e7e", "#7d7d7d", "#7c7c7c", - "#7b7b7b", "#7a7a7a", "#797979", "#787878", "#777777", "#767676", "#757575", "#737373", - "#727272", "#717171", "#707070", "#6f6f6f", "#6e6e6e", "#6d6d6d", "#6c6c6c", "#6b6b6b", - "#6a6a6a", "#696969", "#686868", "#676767", "#666666", "#656565", "#646464", "#636363", - "#626262", "#616161", "#606060", "#5f5f5f", "#5e5e5e", "#5d5d5d", "#5c5c5c", "#5b5b5b", - "#5a5a5a", "#585858", "#575757", "#565656", "#555555", "#545454", "#535353", "#525252", - "#515151", "#505050", "#4e4e4e", "#4d4d4d", "#4b4b4b", "#4a4a4a", "#484848", "#474747", - "#464646", "#444444", "#434343", "#414141", "#404040", "#3f3f3f", "#3d3d3d", "#3c3c3c", - "#3a3a3a", "#393939", "#383838", "#363636", "#353535", "#333333", "#323232", "#303030", - "#2f2f2f", "#2e2e2e", "#2c2c2c", "#2b2b2b", "#292929", "#282828", "#272727", "#252525", - "#242424", "#232323", "#222222", "#212121", "#1f1f1f", "#1e1e1e", "#1d1d1d", "#1c1c1c", - "#1b1b1b", "#1a1a1a", "#181818", "#171717", "#161616", "#151515", "#141414", "#131313", - "#111111", "#101010", "#0f0f0f", "#0e0e0e", "#0d0d0d", "#0c0c0c", "#0a0a0a", "#090909", - "#080808", "#070707", "#060606", "#050505", "#030303", "#020202", "#010101", "#000000" - )); - - public static ColorMapContainer Gray = ColorMapContainer.FromStringList(new List( - "#000000", "#010101", "#020202", "#030303", "#040404", "#050505", "#060606", "#070707", - "#080808", "#090909", "#0a0a0a", "#0b0b0b", "#0c0c0c", "#0d0d0d", "#0e0e0e", "#0f0f0f", - "#101010", "#111111", "#121212", "#131313", "#141414", "#151515", "#161616", "#171717", - "#181818", "#191919", "#1a1a1a", "#1b1b1b", "#1c1c1c", "#1d1d1d", "#1e1e1e", "#1f1f1f", - "#202020", "#212121", "#222222", "#232323", "#242424", "#252525", "#262626", "#272727", - "#282828", "#292929", "#2a2a2a", "#2b2b2b", "#2c2c2c", "#2d2d2d", "#2e2e2e", "#2f2f2f", - "#303030", "#313131", "#323232", "#333333", "#343434", "#353535", "#363636", "#373737", - "#383838", "#393939", "#3a3a3a", "#3b3b3b", "#3c3c3c", "#3d3d3d", "#3e3e3e", "#3f3f3f", - "#404040", "#414141", "#424242", "#434343", "#444444", "#454545", "#464646", "#474747", - "#484848", "#494949", "#4a4a4a", "#4b4b4b", "#4c4c4c", "#4d4d4d", "#4e4e4e", "#4f4f4f", - "#505050", "#515151", "#525252", "#535353", "#545454", "#555555", "#565656", "#575757", - "#585858", "#595959", "#5a5a5a", "#5b5b5b", "#5c5c5c", "#5d5d5d", "#5e5e5e", "#5f5f5f", - "#606060", "#616161", "#626262", "#636363", "#646464", "#656565", "#666666", "#676767", - "#686868", "#696969", "#6a6a6a", "#6b6b6b", "#6c6c6c", "#6d6d6d", "#6e6e6e", "#6f6f6f", - "#707070", "#717171", "#727272", "#737373", "#747474", "#757575", "#767676", "#777777", - "#787878", "#797979", "#7a7a7a", "#7b7b7b", "#7c7c7c", "#7d7d7d", "#7e7e7e", "#7f7f7f", - "#808080", "#818181", "#828282", "#838383", "#848484", "#858585", "#868686", "#878787", - "#888888", "#898989", "#8a8a8a", "#8b8b8b", "#8c8c8c", "#8d8d8d", "#8e8e8e", "#8f8f8f", - "#909090", "#919191", "#929292", "#939393", "#949494", "#959595", "#969696", "#979797", - "#989898", "#999999", "#9a9a9a", "#9b9b9b", "#9c9c9c", "#9d9d9d", "#9e9e9e", "#9f9f9f", - "#a0a0a0", "#a1a1a1", "#a2a2a2", "#a3a3a3", "#a4a4a4", "#a5a5a5", "#a6a6a6", "#a7a7a7", - "#a8a8a8", "#a9a9a9", "#aaaaaa", "#ababab", "#acacac", "#adadad", "#aeaeae", "#afafaf", - "#b0b0b0", "#b1b1b1", "#b2b2b2", "#b3b3b3", "#b4b4b4", "#b5b5b5", "#b6b6b6", "#b7b7b7", - "#b8b8b8", "#b9b9b9", "#bababa", "#bbbbbb", "#bcbcbc", "#bdbdbd", "#bebebe", "#bfbfbf", - "#c0c0c0", "#c1c1c1", "#c2c2c2", "#c3c3c3", "#c4c4c4", "#c5c5c5", "#c6c6c6", "#c7c7c7", - "#c8c8c8", "#c9c9c9", "#cacaca", "#cbcbcb", "#cccccc", "#cdcdcd", "#cecece", "#cfcfcf", - "#d0d0d0", "#d1d1d1", "#d2d2d2", "#d3d3d3", "#d4d4d4", "#d5d5d5", "#d6d6d6", "#d7d7d7", - "#d8d8d8", "#d9d9d9", "#dadada", "#dbdbdb", "#dcdcdc", "#dddddd", "#dedede", "#dfdfdf", - "#e0e0e0", "#e1e1e1", "#e2e2e2", "#e3e3e3", "#e4e4e4", "#e5e5e5", "#e6e6e6", "#e7e7e7", - "#e8e8e8", "#e9e9e9", "#eaeaea", "#ebebeb", "#ececec", "#ededed", "#eeeeee", "#efefef", - "#f0f0f0", "#f1f1f1", "#f2f2f2", "#f3f3f3", "#f4f4f4", "#f5f5f5", "#f6f6f6", "#f7f7f7", - "#f8f8f8", "#f9f9f9", "#fafafa", "#fbfbfb", "#fcfcfc", "#fdfdfd", "#fefefe", "#ffffff" - )); - - public static ColorMapContainer Purples = ColorMapContainer.FromStringList(new List( - "#fcfbfd", "#fcfbfd", "#fbfafc", "#fbfafc", "#faf9fc", "#faf9fc", "#faf8fb", "#f9f8fb", - "#f9f7fb", "#f8f7fb", "#f8f7fa", "#f8f6fa", "#f7f6fa", "#f7f5fa", "#f6f5f9", "#f6f4f9", - "#f5f4f9", "#f5f4f9", "#f5f3f8", "#f4f3f8", "#f4f2f8", "#f3f2f8", "#f3f1f7", "#f3f1f7", - "#f2f0f7", "#f2f0f7", "#f1f0f6", "#f1eff6", "#f1eff6", "#f0eef6", "#f0eef5", "#efedf5", - "#efedf5", "#eeecf5", "#eeecf4", "#edebf4", "#ecebf4", "#eceaf3", "#ebe9f3", "#eae9f3", - "#eae8f2", "#e9e8f2", "#e8e7f2", "#e8e6f2", "#e7e6f1", "#e6e5f1", "#e6e5f1", "#e5e4f0", - "#e4e3f0", "#e4e3f0", "#e3e2ef", "#e2e2ef", "#e2e1ef", "#e1e0ee", "#e0e0ee", "#e0dfee", - "#dfdfed", "#dedeed", "#dedded", "#ddddec", "#dcdcec", "#dcdcec", "#dbdbec", "#dadaeb", - "#dadaeb", "#d9d9ea", "#d8d8ea", "#d7d7e9", "#d6d6e9", "#d5d5e9", "#d4d4e8", "#d3d3e8", - "#d2d2e7", "#d1d2e7", "#d0d1e6", "#cfd0e6", "#cecfe5", "#cecee5", "#cdcde4", "#cccce4", - "#cbcbe3", "#cacae3", "#c9c9e2", "#c8c8e2", "#c7c8e1", "#c6c7e1", "#c5c6e1", "#c4c5e0", - "#c3c4e0", "#c2c3df", "#c1c2df", "#c0c1de", "#bfc0de", "#bebfdd", "#bebedd", "#bdbedc", - "#bcbddc", "#bbbbdb", "#babadb", "#b9b9da", "#b8b8d9", "#b7b7d9", "#b6b6d8", "#b5b5d7", - "#b4b4d7", "#b3b3d6", "#b2b2d5", "#b1b1d5", "#b0afd4", "#afaed4", "#aeadd3", "#aeacd2", - "#adabd2", "#acaad1", "#aba9d0", "#aaa8d0", "#a9a7cf", "#a8a6cf", "#a7a4ce", "#a6a3cd", - "#a5a2cd", "#a4a1cc", "#a3a0cb", "#a29fcb", "#a19eca", "#a09dca", "#9f9cc9", "#9e9bc8", - "#9e9ac8", "#9d99c7", "#9c98c7", "#9b97c6", "#9a96c6", "#9995c6", "#9894c5", "#9793c5", - "#9692c4", "#9591c4", "#9490c3", "#9390c3", "#928fc3", "#918ec2", "#908dc2", "#8f8cc1", - "#8e8bc1", "#8e8ac0", "#8d89c0", "#8c88bf", "#8b87bf", "#8a86bf", "#8986be", "#8885be", - "#8784bd", "#8683bd", "#8582bc", "#8481bc", "#8380bb", "#827fbb", "#817ebb", "#807dba", - "#807cba", "#7f7bb9", "#7e79b8", "#7d78b7", "#7d77b7", "#7c75b6", "#7b74b5", "#7b72b4", - "#7a71b4", "#7970b3", "#796eb2", "#786db2", "#776cb1", "#776ab0", "#7669af", "#7567af", - "#7566ae", "#7465ad", "#7363ad", "#7262ac", "#7261ab", "#715faa", "#705eaa", "#705ca9", - "#6f5ba8", "#6e5aa8", "#6e58a7", "#6d57a6", "#6c55a5", "#6c54a5", "#6b53a4", "#6a51a3", - "#6950a3", "#694fa2", "#684da1", "#674ca1", "#674ba0", "#66499f", "#65489f", "#65479e", - "#64459e", "#63449d", "#63439c", "#62429c", "#61409b", "#613f9a", "#603e9a", "#5f3c99", - "#5e3b98", "#5e3a98", "#5d3897", "#5c3797", "#5c3696", "#5b3495", "#5a3395", "#5a3294", - "#593093", "#582f93", "#582e92", "#572c92", "#562b91", "#552a90", "#552890", "#54278f", - "#53268f", "#53258e", "#52238d", "#51228d", "#51218c", "#50208c", "#4f1f8b", "#4f1d8b", - "#4e1c8a", "#4d1b89", "#4d1a89", "#4c1888", "#4c1788", "#4b1687", "#4a1587", "#4a1486", - "#491285", "#481185", "#481084", "#470f84", "#460d83", "#460c83", "#450b82", "#440a82", - "#440981", "#430780", "#420680", "#42057f", "#41047f", "#40027e", "#40017e", "#3f007d" - )); - - public static ColorMapContainer Blues = ColorMapContainer.FromStringList(new List( - "#f7fbff", "#f6faff", "#f5fafe", "#f5f9fe", "#f4f9fe", "#f3f8fe", "#f2f8fd", "#f2f7fd", - "#f1f7fd", "#f0f6fd", "#eff6fc", "#eef5fc", "#eef5fc", "#edf4fc", "#ecf4fb", "#ebf3fb", - "#eaf3fb", "#eaf2fb", "#e9f2fa", "#e8f1fa", "#e7f1fa", "#e7f0fa", "#e6f0f9", "#e5eff9", - "#e4eff9", "#e3eef9", "#e3eef8", "#e2edf8", "#e1edf8", "#e0ecf8", "#dfecf7", "#dfebf7", - "#deebf7", "#ddeaf7", "#dceaf6", "#dce9f6", "#dbe9f6", "#dae8f6", "#d9e8f5", "#d9e7f5", - "#d8e7f5", "#d7e6f5", "#d6e6f4", "#d6e5f4", "#d5e5f4", "#d4e4f4", "#d3e4f3", "#d3e3f3", - "#d2e3f3", "#d1e2f3", "#d0e2f2", "#d0e1f2", "#cfe1f2", "#cee0f2", "#cde0f1", "#cddff1", - "#ccdff1", "#cbdef1", "#cadef0", "#caddf0", "#c9ddf0", "#c8dcf0", "#c7dcef", "#c7dbef", - "#c6dbef", "#c4daee", "#c3daee", "#c2d9ee", "#c1d9ed", "#bfd8ed", "#bed8ec", "#bdd7ec", - "#bcd7eb", "#bad6eb", "#b9d6ea", "#b8d5ea", "#b7d4ea", "#b5d4e9", "#b4d3e9", "#b3d3e8", - "#b2d2e8", "#b0d2e7", "#afd1e7", "#aed1e7", "#add0e6", "#abd0e6", "#aacfe5", "#a9cfe5", - "#a8cee4", "#a6cee4", "#a5cde3", "#a4cce3", "#a3cce3", "#a1cbe2", "#a0cbe2", "#9fcae1", - "#9dcae1", "#9cc9e1", "#9ac8e0", "#99c7e0", "#97c6df", "#95c5df", "#94c4df", "#92c4de", - "#91c3de", "#8fc2de", "#8dc1dd", "#8cc0dd", "#8abfdd", "#89bedc", "#87bddc", "#85bcdc", - "#84bcdb", "#82bbdb", "#81badb", "#7fb9da", "#7db8da", "#7cb7da", "#7ab6d9", "#79b5d9", - "#77b5d9", "#75b4d8", "#74b3d8", "#72b2d8", "#71b1d7", "#6fb0d7", "#6dafd7", "#6caed6", - "#6aaed6", "#69add5", "#68acd5", "#66abd4", "#65aad4", "#64a9d3", "#63a8d3", "#61a7d2", - "#60a7d2", "#5fa6d1", "#5da5d1", "#5ca4d0", "#5ba3d0", "#5aa2cf", "#58a1cf", "#57a0ce", - "#56a0ce", "#549fcd", "#539ecd", "#529dcc", "#519ccc", "#4f9bcb", "#4e9acb", "#4d99ca", - "#4b98ca", "#4a98c9", "#4997c9", "#4896c8", "#4695c8", "#4594c7", "#4493c7", "#4292c6", - "#4191c6", "#4090c5", "#3f8fc5", "#3e8ec4", "#3d8dc4", "#3c8cc3", "#3b8bc2", "#3a8ac2", - "#3989c1", "#3888c1", "#3787c0", "#3686c0", "#3585bf", "#3484bf", "#3383be", "#3282be", - "#3181bd", "#3080bd", "#2f7fbc", "#2e7ebc", "#2d7dbb", "#2c7cba", "#2b7bba", "#2a7ab9", - "#2979b9", "#2777b8", "#2676b8", "#2575b7", "#2474b7", "#2373b6", "#2272b6", "#2171b5", - "#2070b4", "#206fb4", "#1f6eb3", "#1e6db2", "#1d6cb1", "#1c6bb0", "#1c6ab0", "#1b69af", - "#1a68ae", "#1967ad", "#1966ad", "#1865ac", "#1764ab", "#1663aa", "#1562a9", "#1561a9", - "#1460a8", "#135fa7", "#125ea6", "#125da6", "#115ca5", "#105ba4", "#0f5aa3", "#0e59a2", - "#0e58a2", "#0d57a1", "#0c56a0", "#0b559f", "#0a549e", "#0a539e", "#09529d", "#08519c", - "#08509b", "#084f99", "#084e98", "#084d96", "#084c95", "#084b93", "#084a91", "#084990", - "#08488e", "#08478d", "#08468b", "#08458a", "#084488", "#084387", "#084285", "#084184", - "#084082", "#083e81", "#083d7f", "#083c7d", "#083b7c", "#083a7a", "#083979", "#083877", - "#083776", "#083674", "#083573", "#083471", "#083370", "#08326e", "#08316d", "#08306b" - )); - - public static ColorMapContainer Greens = ColorMapContainer.FromStringList(new List( - "#f7fcf5", "#f6fcf4", "#f6fcf4", "#f5fbf3", "#f5fbf2", "#f4fbf2", "#f4fbf1", "#f3faf0", - "#f2faf0", "#f2faef", "#f1faee", "#f1faee", "#f0f9ed", "#f0f9ec", "#eff9ec", "#eff9eb", - "#eef8ea", "#edf8ea", "#edf8e9", "#ecf8e8", "#ecf8e8", "#ebf7e7", "#ebf7e7", "#eaf7e6", - "#e9f7e5", "#e9f7e5", "#e8f6e4", "#e8f6e3", "#e7f6e3", "#e7f6e2", "#e6f5e1", "#e5f5e1", - "#e5f5e0", "#e4f5df", "#e3f4de", "#e2f4dd", "#e1f3dc", "#e0f3db", "#dff3da", "#def2d9", - "#ddf2d8", "#dcf2d7", "#dbf1d6", "#dbf1d5", "#daf0d4", "#d9f0d3", "#d8f0d2", "#d7efd1", - "#d6efd0", "#d5efcf", "#d4eece", "#d3eecd", "#d2edcc", "#d1edcb", "#d0edca", "#cfecc9", - "#ceecc8", "#cdecc7", "#ccebc6", "#cbebc5", "#cbeac4", "#caeac3", "#c9eac2", "#c8e9c1", - "#c7e9c0", "#c6e8bf", "#c4e8bd", "#c3e7bc", "#c2e7bb", "#c1e6ba", "#c0e6b9", "#bee5b8", - "#bde5b6", "#bce4b5", "#bbe4b4", "#bae3b3", "#b8e3b2", "#b7e2b1", "#b6e2af", "#b5e1ae", - "#b4e1ad", "#b2e0ac", "#b1e0ab", "#b0dfaa", "#afdfa8", "#aedea7", "#acdea6", "#abdda5", - "#aadda4", "#a9dca3", "#a8dca2", "#a7dba0", "#a5db9f", "#a4da9e", "#a3da9d", "#a2d99c", - "#a0d99b", "#9fd899", "#9ed798", "#9cd797", "#9bd696", "#99d595", "#98d594", "#97d492", - "#95d391", "#94d390", "#92d28f", "#91d28e", "#90d18d", "#8ed08b", "#8dd08a", "#8bcf89", - "#8ace88", "#88ce87", "#87cd86", "#86cc85", "#84cc83", "#83cb82", "#81ca81", "#80ca80", - "#7fc97f", "#7dc87e", "#7cc87c", "#7ac77b", "#79c67a", "#78c679", "#76c578", "#75c477", - "#73c476", "#72c375", "#70c274", "#6ec173", "#6dc072", "#6bc072", "#6abf71", "#68be70", - "#66bd6f", "#65bd6f", "#63bc6e", "#62bb6d", "#60ba6c", "#5eb96b", "#5db96b", "#5bb86a", - "#5ab769", "#58b668", "#56b567", "#55b567", "#53b466", "#52b365", "#50b264", "#4eb264", - "#4db163", "#4bb062", "#4aaf61", "#48ae60", "#46ae60", "#45ad5f", "#43ac5e", "#42ab5d", - "#40aa5d", "#3fa95c", "#3fa85b", "#3ea75a", "#3da65a", "#3ca559", "#3ba458", "#3aa357", - "#39a257", "#38a156", "#37a055", "#369f54", "#359e53", "#349d53", "#339c52", "#329b51", - "#319a50", "#309950", "#2f984f", "#2f974e", "#2e964d", "#2d954d", "#2c944c", "#2b934b", - "#2a924a", "#29914a", "#289049", "#278f48", "#268e47", "#258d47", "#248c46", "#238b45", - "#228a44", "#218944", "#208843", "#1f8742", "#1e8741", "#1d8640", "#1c8540", "#1a843f", - "#19833e", "#18823d", "#17813d", "#16803c", "#157f3b", "#147e3a", "#137d39", "#127c39", - "#117b38", "#107a37", "#0e7936", "#0d7836", "#0c7735", "#0b7734", "#0a7633", "#097532", - "#087432", "#077331", "#067230", "#05712f", "#03702e", "#026f2e", "#016e2d", "#006d2c", - "#006c2c", "#006b2b", "#00692a", "#00682a", "#006729", "#006529", "#006428", "#006328", - "#006227", "#006027", "#005f26", "#005e26", "#005c25", "#005b25", "#005a24", "#005924", - "#005723", "#005622", "#005522", "#005321", "#005221", "#005120", "#005020", "#004e1f", - "#004d1f", "#004c1e", "#004a1e", "#00491d", "#00481d", "#00471c", "#00451c", "#00441b" - )); - - public static ColorMapContainer Oranges = ColorMapContainer.FromStringList(new List( - "#fff5eb", "#fff5ea", "#fff4e9", "#fff4e8", "#fff3e7", "#fff3e6", "#fff2e6", "#fff2e5", - "#fff1e4", "#fff1e3", "#fff0e2", "#fff0e1", "#ffefe0", "#ffefdf", "#ffeede", "#ffeedd", - "#feeddc", "#feeddc", "#feeddb", "#feecda", "#feecd9", "#feebd8", "#feebd7", "#feead6", - "#feead5", "#fee9d4", "#fee9d3", "#fee8d2", "#fee8d2", "#fee7d1", "#fee7d0", "#fee6cf", - "#fee6ce", "#fee5cc", "#fee5cb", "#fee4ca", "#fee3c8", "#fee2c7", "#fee2c6", "#fee1c4", - "#fee0c3", "#fee0c1", "#fedfc0", "#fedebf", "#fedebd", "#feddbc", "#fedcbb", "#fedcb9", - "#fddbb8", "#fddab6", "#fdd9b5", "#fdd9b4", "#fdd8b2", "#fdd7b1", "#fdd7af", "#fdd6ae", - "#fdd5ad", "#fdd5ab", "#fdd4aa", "#fdd3a9", "#fdd3a7", "#fdd2a6", "#fdd1a4", "#fdd1a3", - "#fdd0a2", "#fdcfa0", "#fdce9e", "#fdcd9c", "#fdcb9b", "#fdca99", "#fdc997", "#fdc895", - "#fdc794", "#fdc692", "#fdc590", "#fdc48f", "#fdc38d", "#fdc28b", "#fdc189", "#fdc088", - "#fdbf86", "#fdbe84", "#fdbd83", "#fdbb81", "#fdba7f", "#fdb97d", "#fdb87c", "#fdb77a", - "#fdb678", "#fdb576", "#fdb475", "#fdb373", "#fdb271", "#fdb170", "#fdb06e", "#fdaf6c", - "#fdae6a", "#fdad69", "#fdac67", "#fdab66", "#fda965", "#fda863", "#fda762", "#fda660", - "#fda55f", "#fda45d", "#fda35c", "#fda25a", "#fda159", "#fda057", "#fd9f56", "#fd9e54", - "#fd9d53", "#fd9c51", "#fd9b50", "#fd9a4e", "#fd994d", "#fd984b", "#fd974a", "#fd9649", - "#fd9547", "#fd9446", "#fd9344", "#fd9243", "#fd9141", "#fd9040", "#fd8f3e", "#fd8e3d", - "#fd8c3b", "#fc8b3a", "#fc8a39", "#fc8937", "#fb8836", "#fb8735", "#fb8634", "#fa8532", - "#fa8331", "#f98230", "#f9812e", "#f9802d", "#f87f2c", "#f87e2b", "#f87d29", "#f77b28", - "#f77a27", "#f67925", "#f67824", "#f67723", "#f57622", "#f57520", "#f5741f", "#f4721e", - "#f4711c", "#f3701b", "#f36f1a", "#f36e19", "#f26d17", "#f26c16", "#f26b15", "#f16913", - "#f16813", "#f06712", "#ef6612", "#ee6511", "#ee6410", "#ed6310", "#ec620f", "#eb610f", - "#eb600e", "#ea5f0e", "#e95e0d", "#e85d0c", "#e75c0c", "#e75b0b", "#e65a0b", "#e5590a", - "#e4580a", "#e45709", "#e35608", "#e25508", "#e15407", "#e15307", "#e05206", "#df5106", - "#de5005", "#de4e05", "#dd4d04", "#dc4c03", "#db4b03", "#db4a02", "#da4902", "#d94801", - "#d84801", "#d64701", "#d54601", "#d34601", "#d14501", "#d04501", "#ce4401", "#cd4401", - "#cb4302", "#c94202", "#c84202", "#c64102", "#c54102", "#c34002", "#c14002", "#c03f02", - "#be3f02", "#bd3e02", "#bb3d02", "#b93d02", "#b83c02", "#b63c02", "#b53b02", "#b33b02", - "#b13a03", "#b03903", "#ae3903", "#ad3803", "#ab3803", "#a93703", "#a83703", "#a63603", - "#a53603", "#a43503", "#a23503", "#a13403", "#a03403", "#9f3303", "#9e3303", "#9c3203", - "#9b3203", "#9a3103", "#993103", "#973003", "#963003", "#952f03", "#942f03", "#932f03", - "#912e04", "#902e04", "#8f2d04", "#8e2d04", "#8c2c04", "#8b2c04", "#8a2b04", "#892b04", - "#882a04", "#862a04", "#852904", "#842904", "#832804", "#812804", "#802704", "#7f2704" - )); - - public static ColorMapContainer Reds = ColorMapContainer.FromStringList(new List( - "#fff5f0", "#fff4ef", "#fff4ee", "#fff3ed", "#fff2ec", "#fff2eb", "#fff1ea", "#fff0e9", - "#fff0e8", "#ffefe8", "#ffeee7", "#ffeee6", "#ffede5", "#ffece4", "#ffece3", "#ffebe2", - "#feeae1", "#feeae0", "#fee9df", "#fee8de", "#fee8dd", "#fee7dc", "#fee7db", "#fee6da", - "#fee5d9", "#fee5d8", "#fee4d8", "#fee3d7", "#fee3d6", "#fee2d5", "#fee1d4", "#fee1d3", - "#fee0d2", "#fedfd0", "#fedecf", "#fedccd", "#fedbcc", "#fedaca", "#fed9c9", "#fed8c7", - "#fdd7c6", "#fdd5c4", "#fdd4c2", "#fdd3c1", "#fdd2bf", "#fdd1be", "#fdd0bc", "#fdcebb", - "#fdcdb9", "#fdccb8", "#fdcbb6", "#fdcab5", "#fdc9b3", "#fdc7b2", "#fdc6b0", "#fdc5ae", - "#fcc4ad", "#fcc3ab", "#fcc2aa", "#fcc1a8", "#fcbfa7", "#fcbea5", "#fcbda4", "#fcbca2", - "#fcbba1", "#fcb99f", "#fcb89e", "#fcb79c", "#fcb69b", "#fcb499", "#fcb398", "#fcb296", - "#fcb095", "#fcaf93", "#fcae92", "#fcad90", "#fcab8f", "#fcaa8d", "#fca98c", "#fca78b", - "#fca689", "#fca588", "#fca486", "#fca285", "#fca183", "#fca082", "#fc9e80", "#fc9d7f", - "#fc9c7d", "#fc9b7c", "#fc997a", "#fc9879", "#fc9777", "#fc9576", "#fc9474", "#fc9373", - "#fc9272", "#fc9070", "#fc8f6f", "#fc8e6e", "#fc8d6d", "#fc8b6b", "#fc8a6a", "#fc8969", - "#fc8767", "#fc8666", "#fc8565", "#fc8464", "#fc8262", "#fc8161", "#fc8060", "#fc7f5f", - "#fb7d5d", "#fb7c5c", "#fb7b5b", "#fb7a5a", "#fb7858", "#fb7757", "#fb7656", "#fb7555", - "#fb7353", "#fb7252", "#fb7151", "#fb7050", "#fb6e4e", "#fb6d4d", "#fb6c4c", "#fb6b4b", - "#fb694a", "#fa6849", "#fa6648", "#fa6547", "#f96346", "#f96245", "#f96044", "#f85f43", - "#f85d42", "#f75c41", "#f75b40", "#f7593f", "#f6583e", "#f6563d", "#f6553c", "#f5533b", - "#f5523a", "#f4503a", "#f44f39", "#f44d38", "#f34c37", "#f34a36", "#f34935", "#f24734", - "#f24633", "#f14432", "#f14331", "#f14130", "#f0402f", "#f03f2e", "#f03d2d", "#ef3c2c", - "#ee3a2c", "#ed392b", "#ec382b", "#eb372a", "#ea362a", "#e93529", "#e83429", "#e63328", - "#e53228", "#e43027", "#e32f27", "#e22e27", "#e12d26", "#e02c26", "#de2b25", "#dd2a25", - "#dc2924", "#db2824", "#da2723", "#d92523", "#d82422", "#d72322", "#d52221", "#d42121", - "#d32020", "#d21f20", "#d11e1f", "#d01d1f", "#cf1c1f", "#ce1a1e", "#cc191e", "#cb181d", - "#ca181d", "#c9181d", "#c8171c", "#c7171c", "#c5171c", "#c4161c", "#c3161b", "#c2161b", - "#c1161b", "#bf151b", "#be151a", "#bd151a", "#bc141a", "#bb141a", "#b91419", "#b81419", - "#b71319", "#b61319", "#b51318", "#b31218", "#b21218", "#b11218", "#b01217", "#af1117", - "#ad1117", "#ac1117", "#ab1016", "#aa1016", "#a91016", "#a81016", "#a60f15", "#a50f15", - "#a30f15", "#a10e15", "#9f0e14", "#9d0d14", "#9c0d14", "#9a0c14", "#980c13", "#960b13", - "#940b13", "#920a13", "#900a12", "#8e0912", "#8c0912", "#8a0812", "#880811", "#860811", - "#840711", "#820711", "#800610", "#7e0610", "#7c0510", "#7a0510", "#79040f", "#77040f", - "#75030f", "#73030f", "#71020e", "#6f020e", "#6d010e", "#6b010e", "#69000d", "#67000d" - )); - - public static ColorMapContainer RdYlBu = ColorMapContainer.FromStringList(new List( - "#a50026", "#a70226", "#a90426", "#ab0626", "#ad0826", "#af0926", "#b10b26", "#b30d26", - "#b50f26", "#b71126", "#b91326", "#bb1526", "#bd1726", "#be1827", "#c01a27", "#c21c27", - "#c41e27", "#c62027", "#c82227", "#ca2427", "#cc2627", "#ce2827", "#d02927", "#d22b27", - "#d42d27", "#d62f27", "#d83128", "#d93429", "#da362a", "#db382b", "#dc3b2c", "#dd3d2d", - "#de402e", "#e0422f", "#e14430", "#e24731", "#e34933", "#e44c34", "#e54e35", "#e65036", - "#e75337", "#e95538", "#ea5739", "#eb5a3a", "#ec5c3b", "#ed5f3c", "#ee613e", "#ef633f", - "#f16640", "#f26841", "#f36b42", "#f46d43", "#f47044", "#f57245", "#f57547", "#f57748", - "#f67a49", "#f67c4a", "#f67f4b", "#f7814c", "#f7844e", "#f8864f", "#f88950", "#f88c51", - "#f98e52", "#f99153", "#f99355", "#fa9656", "#fa9857", "#fa9b58", "#fb9d59", "#fba05b", - "#fba35c", "#fca55d", "#fca85e", "#fcaa5f", "#fdad60", "#fdaf62", "#fdb164", "#fdb366", - "#fdb567", "#fdb769", "#fdb96b", "#fdbb6d", "#fdbd6f", "#fdbf71", "#fdc173", "#fdc374", - "#fdc576", "#fdc778", "#fec87a", "#feca7c", "#fecc7e", "#fece7f", "#fed081", "#fed283", - "#fed485", "#fed687", "#fed889", "#feda8a", "#fedc8c", "#fede8e", "#fee090", "#fee192", - "#fee294", "#fee496", "#fee597", "#fee699", "#fee79b", "#fee99d", "#feea9f", "#feeba1", - "#feeca2", "#feeda4", "#feefa6", "#fff0a8", "#fff1aa", "#fff2ac", "#fff3ad", "#fff5af", - "#fff6b1", "#fff7b3", "#fff8b5", "#fffab7", "#fffbb9", "#fffcba", "#fffdbc", "#fffebe", - "#feffc0", "#fdfec2", "#fcfec5", "#fbfdc7", "#fafdc9", "#f8fccb", "#f7fcce", "#f6fbd0", - "#f5fbd2", "#f3fbd4", "#f2fad6", "#f1fad9", "#f0f9db", "#eff9dd", "#edf8df", "#ecf8e2", - "#ebf7e4", "#eaf7e6", "#e9f6e8", "#e7f6eb", "#e6f5ed", "#e5f5ef", "#e4f4f1", "#e2f4f4", - "#e1f3f6", "#e0f3f8", "#def2f7", "#dcf1f7", "#daf0f6", "#d8eff6", "#d6eef5", "#d4edf4", - "#d1ecf4", "#cfebf3", "#cdeaf3", "#cbe9f2", "#c9e8f2", "#c7e7f1", "#c5e6f0", "#c3e5f0", - "#c1e4ef", "#bfe3ef", "#bde2ee", "#bbe1ed", "#b9e0ed", "#b6dfec", "#b4deec", "#b2ddeb", - "#b0dcea", "#aedbea", "#acdae9", "#aad8e9", "#a8d6e8", "#a6d5e7", "#a3d3e6", "#a1d1e5", - "#9fd0e4", "#9dcee3", "#9bcce2", "#99cae1", "#97c9e0", "#94c7df", "#92c5de", "#90c3dd", - "#8ec2dc", "#8cc0db", "#8abeda", "#87bdd9", "#85bbd9", "#83b9d8", "#81b7d7", "#7fb6d6", - "#7db4d5", "#7ab2d4", "#78b0d3", "#76afd2", "#74add1", "#72abd0", "#70a9cf", "#6ea6ce", - "#6da4cc", "#6ba2cb", "#69a0ca", "#679ec9", "#659bc8", "#6399c7", "#6297c6", "#6095c4", - "#5e93c3", "#5c90c2", "#5a8ec1", "#588cc0", "#578abf", "#5588be", "#5385bd", "#5183bb", - "#4f81ba", "#4d7fb9", "#4b7db8", "#4a7ab7", "#4878b6", "#4676b5", "#4574b3", "#4471b2", - "#436fb1", "#426cb0", "#416aaf", "#4167ad", "#4065ac", "#3f62ab", "#3e60aa", "#3e5ea8", - "#3d5ba7", "#3c59a6", "#3b56a5", "#3a54a4", "#3a51a2", "#394fa1", "#384ca0", "#374a9f", - "#36479e", "#36459c", "#35429b", "#34409a", "#333d99", "#333b97", "#323896", "#313695" - )); - - } - -} diff --git a/engine/csharp_ref/Layers/FitsImage.cs b/engine/csharp_ref/Layers/FitsImage.cs deleted file mode 100644 index 15bd3031..00000000 --- a/engine/csharp_ref/Layers/FitsImage.cs +++ /dev/null @@ -1,567 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -using System.Html.Data.Files; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public delegate void WcsLoaded(WcsImage wcsImage); - public class FitsImage : WcsImage - { - public bool errored = false; - public int NumAxis = 0; - public int[] AxisSize; - public Float32Array dataUnit; - public int[] Histogram; - public int HistogramMaxCount; - public Blob sourceBlob = null; - public FitsProperties fitsProperties; - - protected readonly Dictionary header = new Dictionary(); - protected const float NaN = 0f / 0f; - protected int position = 0; - protected int BufferSize = 1; - protected Imageset dataset; - - private readonly WcsLoaded callBack; - private WebFile webFile; - private bool parseSuccessful = false; - - public FitsImage(Imageset dataset, string file, Blob blob, WcsLoaded callMeBack) - { - this.dataset = dataset; - this.fitsProperties = dataset.FitsProperties; - callBack = callMeBack; - filename = file; - if (blob != null) - { - ReadFromBlob(blob); - } - else - { - GetFile(file); - } - } - - public void GetFile(string url) - { - webFile = new WebFile(url); - webFile.ResponseType = "blob"; - webFile.OnStateChange = FileStateChange; - webFile.Send(); - } - - public void FileStateChange() - { - if (webFile.State == StateType.Error) - { - errored = true; - if (callBack != null) - { - callBack.Invoke(this); - } - - } - else if (webFile.State == StateType.Received) - { - Blob mainBlob = webFile.GetBlob(); - ReadFromBlob(mainBlob); - } - } - - private void ReadFromBlob(Blob blob) - { - sourceBlob = blob; - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e) - { - ReadFromBin(new DataView(chunck.Result)); - errored = !parseSuccessful; - if (callBack != null) - { - callBack.Invoke(this); - } - }; - chunck.ReadAsArrayBuffer(blob); - } - - private string ReadByteString(DataView dataView, int count) - { - string data = ""; - for (int i = 0; i < count; i++) - { - data += string.FromCharCode(dataView.getUint8(this.position)); - this.position++; - } - return data; - } - - private bool ValidateFitsSimple(DataView dataView) - { - string data = this.ReadByteString(dataView, 8); - string keyword = data.TrimEnd(); - this.position -= 8; - return keyword.ToUpperCase() == "SIMPLE"; - } - - public virtual void ReadFromBin(DataView dataView) - { - if (!ValidateFitsSimple(dataView)) - { - Script.Literal("console.log('The requested file is not a valid FITS file.')"); - return; - } - - bool foundEnd = false; - - while (!foundEnd) - { - for (int i = 0; i < 36; i++) - { - string data = this.ReadByteString(dataView, 80); - - if (!foundEnd) - { - string keyword = data.Substring(0, 8).TrimEnd(); - string[] values = data.Substring(10).Split("/"); - if (keyword.ToUpperCase() == "END") - { - foundEnd = true; - // Check for XTENSION - i++; - data = this.ReadByteString(dataView, 80); - while (String.IsNullOrWhiteSpace(data)) - { - i++; - data = this.ReadByteString(dataView, 80); - } - keyword = data.Substring(0, 8).TrimEnd(); - if (keyword.ToUpperCase() == "XTENSION") - { - // We have additional headers - foundEnd = false; - } - else - { - // Rewind these 80 bytes which could be data - this.position -= 80; - } - } - else - { - AddKeyword(keyword, values); - } - } - - } - } - - if (!foundEnd) - { - Script.Literal("console.log('Unable to parse requested FITS file.')"); - return; - } - - NumAxis = Int32.Parse(header["NAXIS"]); - - if (header.ContainsKey("BLANK")) - { - fitsProperties.BlankValue = Double.Parse(header["BLANK"]); - fitsProperties.ContainsBlanks = true; - } - - if (header.ContainsKey("BZERO")) - { - fitsProperties.BZero = Double.Parse(header["BZERO"]); - } - - if (header.ContainsKey("BSCALE")) - { - fitsProperties.BScale = Double.Parse(header["BSCALE"]); - } - - AxisSize = new int[NumAxis]; - - for (int axis = 0; axis < NumAxis; axis++) - { - AxisSize[axis] = Int32.Parse(header[string.Format("NAXIS{0}", axis + 1)]); - BufferSize *= AxisSize[axis]; - } - - int bitpix = Int32.Parse(header["BITPIX"]); - - this.ReadDataUnit(dataView, bitpix); - - if (NumAxis > 1) - { - sizeX = AxisSize[0]; - sizeY = AxisSize[1]; - Histogram = ComputeHistogram(256); - HistogramMaxCount = Histogram[256]; - } - - ComputeWcs(); - - parseSuccessful = true; - } - - - private void AddKeyword(string keyword, string[] values) - { - if (keyword != "CONTINUE" && keyword != "COMMENT" && keyword != "HISTORY" && !String.IsNullOrEmpty(keyword)) - { - try - { - if (header.ContainsKey(keyword)) - { - header[keyword] = values[0].Trim(); - } - else - { - header[keyword.ToUpperCase()] = values[0].Trim(); - } - } - catch - { - } - } - } - - protected virtual void ReadDataUnit(DataView dataView, int bitpix) - { - dataUnit = new Float32Array(this.BufferSize); - switch (bitpix) - { - case -64: - ReadDataUnitFloat64(dataView); - break; - case -32: - ReadDataUnitFloat32(dataView); - break; - case 8: - ReadDataUnitUint8(dataView); - break; - case 16: - ReadDataUnitInt16(dataView); - break; - case 32: - ReadDataUnitInt32(dataView); - break; - case 64: - // 64 bit integers not supported by Safari - Script.Literal("console.log('64 bit integer FITS are not yet supported')"); - //ReadDataUnitInt64(dataView); - break; - } - - } - - protected virtual void ReadDataUnitFloat64(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getFloat64(this.position, false); - double physicalValue = dataUnit[i] * fitsProperties.BScale + fitsProperties.BZero; - if (fitsProperties.MinVal > physicalValue) - { - fitsProperties.MinVal = physicalValue; - } - if (fitsProperties.MaxVal < physicalValue) - { - fitsProperties.MaxVal = physicalValue; - } - i++; - this.position += 8; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - - } - - protected virtual void ReadDataUnitFloat32(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getFloat32(this.position, false); - double physicalValue = dataUnit[i] * fitsProperties.BScale + fitsProperties.BZero; - if (fitsProperties.MinVal > physicalValue) - { - fitsProperties.MinVal = physicalValue; - } - if (fitsProperties.MaxVal < physicalValue) - { - fitsProperties.MaxVal = physicalValue; - } - i++; - this.position += 4; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - protected virtual void ReadDataUnitUint8(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getUint8(this.position); - if (fitsProperties.MinVal > dataUnit[i]) - { - fitsProperties.MinVal = dataUnit[i]; - } - if (fitsProperties.MaxVal < dataUnit[i]) - { - fitsProperties.MaxVal = dataUnit[i]; - } - i++; - this.position += 1; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - protected virtual void ReadDataUnitInt16(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getInt16(this.position, false); - if (fitsProperties.MinVal > dataUnit[i]) - { - fitsProperties.MinVal = dataUnit[i]; - } - if (fitsProperties.MaxVal < dataUnit[i]) - { - fitsProperties.MaxVal = dataUnit[i]; - } - i++; - this.position += 2; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - - protected virtual void ReadDataUnitInt32(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getInt32(this.position, false); - if (fitsProperties.MinVal > dataUnit[i]) - { - fitsProperties.MinVal = dataUnit[i]; - } - if (fitsProperties.MaxVal < dataUnit[i]) - { - fitsProperties.MaxVal = dataUnit[i]; - } - i++; - this.position += 4; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - - protected virtual void ComputeWcs() - { - if (header.ContainsKey("CROTA2")) - { - rotation = double.Parse(header["CROTA2"].Trim()); - hasRotation = true; - - } - - if (header.ContainsKey("CDELT1")) - { - scaleX = double.Parse(header["CDELT1"].Trim()); - - if (header.ContainsKey("CDELT2")) - { - scaleY = double.Parse(header["CDELT2"].Trim()); - hasScale = true; - } - } - - if (header.ContainsKey("CRPIX1")) - { - // In FITS/ WCS, pixel coordinates are 1 - based and integer pixel - // coordinates land on pixel centers. Therefore in standard FITS - // orientation, where the "first" pixel is at the lower-left, the - // lower-left corner of the image has pixel coordinate (0.5, 0.5). For - // the WWT offset parameters, the lower-left corner of the image has - // coordinate (0, 0). - referenceX = double.Parse(header["CRPIX1"].Trim()) - 0.5; - - if (header.ContainsKey("CRPIX2")) - { - referenceY = double.Parse(header["CRPIX2"].Trim()) - 0.5; - hasPixel = true; - } - } - bool galactic = false; - bool tan = false; - - if (header.ContainsKey("CTYPE1")) - { - if (header["CTYPE1"].IndexOf("GLON-") > -1) - { - galactic = true; - tan = true; - } - if (header["CTYPE2"].IndexOf("GLAT-") > -1) - { - galactic = true; - tan = true; - } - - if (header["CTYPE1"].IndexOf("-TAN") > -1) - { - tan = true; - } - if (header["CTYPE1"].IndexOf("-SIN") > -1) - { - tan = true; - } - } - - if (!tan) - { - throw new System.Exception("Only TAN projected images are supported: "); - } - - hasSize = true; - - if (header.ContainsKey("CRVAL1")) - { - centerX = Double.Parse(header["CRVAL1"].Trim()); - - if (header.ContainsKey("CRVAL2")) - { - centerY = double.Parse(header["CRVAL2"].Trim()); - hasLocation = true; - } - } - - if (galactic) - { - double[] result = Coordinates.GalactictoJ2000(centerX, centerY); - centerX = result[0]; - centerY = result[1]; - } - - if (header.ContainsKey("CD1_1") && header.ContainsKey("CD1_2") - && header.ContainsKey("CD2_1") && header.ContainsKey("CD2_2")) - { - cd1_1 = double.Parse(header["CD1_1"].Trim()); - cd1_2 = double.Parse(header["CD1_2"].Trim()); - cd2_1 = double.Parse(header["CD2_1"].Trim()); - cd2_2 = double.Parse(header["CD2_2"].Trim()); - if (!hasRotation) - { - CalculateRotationFromCD(); - } - if (!hasScale) - { - CalculateScaleFromCD(); - } - hasScale = true; - hasRotation = true; - } - - - ValidWcs = hasScale && hasRotation && hasPixel && hasLocation; - } - - // Modify the FitsProperties object to apply any settings stored in this - // FITS image's header keywords. This mechanism gives us a way to set up - // the rendering of a tiled FITS image through keywords set on its - // level-0 tile file. - // - // I'm not aware of any standard, or even standard-ish, headers to - // define these settings, so we'll roll our own here. - public void ApplyDisplaySettings() - { - // TODO for tiled FITS: distinguish between datamin in this one tile, - // and datamin across the full, un-downsampled original imagery. - - if (header.ContainsKey("DATAMIN")) { - fitsProperties.LowerCut = double.Parse(header["DATAMIN"].Trim()); - fitsProperties.MinVal = fitsProperties.LowerCut; - } - - if (header.ContainsKey("DATAMAX")) { - fitsProperties.UpperCut = double.Parse(header["DATAMAX"].Trim()); - fitsProperties.MaxVal = fitsProperties.UpperCut; - } - - if (header.ContainsKey("PXCUTMIN")) { - // Override DATAMIN - fitsProperties.LowerCut = double.Parse(header["PXCUTMIN"].Trim()); - } - - if (header.ContainsKey("PXCUTMAX")) { - // Override DATAMAX - fitsProperties.UpperCut = double.Parse(header["PXCUTMAX"].Trim()); - } - } - - public int[] ComputeHistogram(int count) - { - int[] histogram = new int[count + 1]; - - for (int i = 0; i < count + 1; i++) - { - histogram[i] = 0; - } - - PopulateHistogram(histogram); - int maxCounter = 1; - foreach (int val in histogram) - { - if (val > maxCounter) - { - maxCounter = val; - } - } - histogram[count] = maxCounter; - return histogram; - } - - protected virtual void PopulateHistogram(int[] histogram) - { - int buckets = histogram.Length; - - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - for (int i = 0; i < dataUnit.length; i++) - { - if (!(dataUnit[i] == NaN)) - { - histogram[Math.Min(buckets - 1, (int)((fitsProperties.BZero + fitsProperties.BScale * dataUnit[i] - fitsProperties.MinVal) / factor))]++; - } - } - } - - public void DrawHistogram(CanvasContext2D ctx) - { - ctx.ClearRect(0, 0, 255, 150); - ctx.BeginPath(); - ctx.StrokeStyle = "rgba(255,255,255,255)"; - double logMax = Math.Log(HistogramMaxCount); - for (int i = 0; i < Histogram.Length; i++) - { - double height = Math.Log(Histogram[i]) / logMax; - if (height < 0) - { - height = 0; - } - - ctx.MoveTo(i, 150); - ctx.LineTo(i, 150 - (height * 150)); - ctx.Stroke(); - } - - } - } -} diff --git a/engine/csharp_ref/Layers/FitsImageJs.cs b/engine/csharp_ref/Layers/FitsImageJs.cs deleted file mode 100644 index 92617aed..00000000 --- a/engine/csharp_ref/Layers/FitsImageJs.cs +++ /dev/null @@ -1,729 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Net; -using System.Html.Data.Files; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public enum DataTypes { ByteT = 0, Int16T = 1, Int32T = 2, FloatT = 3, DoubleT = 4, None = 5 }; - - //Legacy class to support JS parsing until Safari supports WebGL 2.0 - //Use FitsImage.cs if possible - public class FitsImageJs : FitsImage - { - public DataTypes DataType = DataTypes.None; - - private bool color = false; - private object DataBuffer; - - public FitsImageJs(Imageset dataset, string file, Blob blob, WcsLoaded callMeBack) : base (dataset, file, blob, callMeBack) - { - } - public bool isTiledFits = false; - public static FitsImageJs CreateTiledFits(Imageset dataset, string file, WcsLoaded callMeBack) - { - FitsImageJs fits = new FitsImageJs(dataset, file, null, callMeBack); - fits.isTiledFits = true; - return fits; - } - - public override void ReadFromBin(DataView dataView) - { - base.ReadFromBin(dataView); - if (NumAxis == 3) - { - if (AxisSize[2] == 3) - { - color = true; - } - } - } - - protected override void ReadDataUnit(DataView dataView, int bitpix) - { - BinaryReader br = new BinaryReader(new Uint8Array(dataView.buffer)); - br.position = position; - switch (bitpix) - { - case -64: - DataType = DataTypes.DoubleT; - ReadDataUnitFloat64(br); - break; - case -32: - DataType = DataTypes.FloatT; - ReadDataUnitFloat32(br); - break; - case 8: - DataType = DataTypes.ByteT; - ReadDataUnitUint8(br); - break; - case 16: - DataType = DataTypes.Int16T; - ReadDataUnitInt16(br); - break; - case 32: - DataType = DataTypes.Int32T; - ReadDataUnitInt32(br); - break; - } - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - - private void ReadDataUnitUint8(BinaryReader br) - { - byte[] buffer = new byte[BufferSize]; - DataBuffer = buffer; - for (int i = 0; i < BufferSize; i++) - { - buffer[i] = br.ReadByte(); - if (fitsProperties.MinVal > (double)buffer[i]) - { - fitsProperties.MinVal = (double)buffer[i]; - } - if (fitsProperties.MaxVal < (double)buffer[i]) - { - fitsProperties.MaxVal = (double)buffer[i]; - } - } - } - - private void ReadDataUnitInt16(BinaryReader br) - { - short[] buffer = new Int16[BufferSize]; - DataBuffer = buffer; - for (int i = 0; i < BufferSize; i++) - { - buffer[i] = (short)((br.ReadSByte() * 256) + (short)br.ReadByte()); - if (fitsProperties.MinVal > (double)buffer[i]) - { - fitsProperties.MinVal = (double)buffer[i]; - } - if (fitsProperties.MaxVal < (double)buffer[i]) - { - fitsProperties.MaxVal = (double)buffer[i]; - } - } - } - - private void ReadDataUnitInt32(BinaryReader br) - { - int[] buffer = new int[BufferSize]; - DataBuffer = buffer; - for (int i = 0; i < BufferSize; i++) - { - buffer[i] = (br.ReadSByte() << 24) + (br.ReadSByte() << 16) + (br.ReadSByte() << 8) + br.ReadByte(); - if (fitsProperties.MinVal > (double)buffer[i]) - { - fitsProperties.MinVal = (double)buffer[i]; - } - if (fitsProperties.MaxVal < (double)buffer[i]) - { - fitsProperties.MaxVal = (double)buffer[i]; - } - } - } - - private void ReadDataUnitFloat32(BinaryReader br) - { - float[] buffer = new float[BufferSize]; - DataBuffer = buffer; - Uint8Array part = new Uint8Array(4); - for (int i = 0; i < BufferSize; i++) - { - part[3] = br.ReadByte(); - part[2] = br.ReadByte(); - part[1] = br.ReadByte(); - part[0] = br.ReadByte(); - - buffer[i] = (new Float32Array(part.buffer, 0, 1))[0]; - - if (fitsProperties.MinVal > (double)buffer[i]) - { - fitsProperties.MinVal = (double)buffer[i]; - } - if (fitsProperties.MaxVal < (double)buffer[i]) - { - fitsProperties.MaxVal = (double)buffer[i]; - } - } - } - - private void ReadDataUnitFloat64(BinaryReader br) - { - double[] buffer = new double[BufferSize]; - Uint8Array part = new Uint8Array(8); - DataBuffer = buffer; - for (int i = 0; i < BufferSize; i++) - { - part[7] = br.ReadByte(); - part[6] = br.ReadByte(); - part[5] = br.ReadByte(); - part[4] = br.ReadByte(); - part[3] = br.ReadByte(); - part[2] = br.ReadByte(); - part[1] = br.ReadByte(); - part[0] = br.ReadByte(); - buffer[i] = (new Float64Array(part.buffer, 0, 1))[0]; - - if (fitsProperties.MinVal > (double)buffer[i]) - { - fitsProperties.MinVal = (double)buffer[i]; - } - if (fitsProperties.MaxVal < (double)buffer[i]) - { - fitsProperties.MaxVal = (double)buffer[i]; - } - } - } - - override public Bitmap GetBitmap() - { - if (fitsProperties.UpperCut == 0 && fitsProperties.LowerCut == 0) - { - fitsProperties.LowerCut = fitsProperties.MinVal; - fitsProperties.UpperCut = fitsProperties.MaxVal; - } - - return GetScaledBitmap(fitsProperties.LowerCut, fitsProperties.UpperCut, fitsProperties.ScaleType, 0, fitsProperties.ColorMapName); - } - - public Bitmap GetScaledBitmap(double min, double max, ScaleTypes scaleType, int z, string colorMapperName) - { - ScaleMap scale; - fitsProperties.ScaleType = scaleType; - fitsProperties.LowerCut = min; - fitsProperties.UpperCut = max; - fitsProperties.ColorMapName = colorMapperName; - - ColorMapContainer colorMapper = ColorMapContainer.FromNamedColormap(colorMapperName); - - switch (scaleType) - { - default: - case ScaleTypes.Linear: - scale = new ScaleLinear(min, max); - break; - case ScaleTypes.Log: - scale = new ScaleLog(min, max); - break; - case ScaleTypes.Power: - scale = new ScalePow(min, max); - break; - case ScaleTypes.SquareRoot: - scale = new ScaleSqrt(min, max); - break; - case ScaleTypes.HistogramEqualization: - scale = new HistogramEqualization(this, min, max); - break; - } - - try - { - switch (DataType) - { - case DataTypes.ByteT: - return GetBitmapByte(min, max, scale, 0, colorMapper); - case DataTypes.Int16T: - return GetBitmapShort(min, max, scale, 0, colorMapper); - case DataTypes.Int32T: - return GetBitmapInt(min, max, scale, 0, colorMapper); - case DataTypes.FloatT: - return GetBitmapFloat(min, max, scale, 0, colorMapper); - case DataTypes.DoubleT: - return GetBitmapDouble(min, max, scale, 0, colorMapper); - case DataTypes.None: - default: - return Bitmap.Create(100, 100); - } - } - catch - { - return Bitmap.Create(10, 10); - } - } - - private void SetPixelWithColorMap(Bitmap bmp, int x, int y, Byte val, ColorMapContainer colorMapper) { - if (colorMapper == null) { - bmp.SetPixel(x, y, val, val, val, (fitsProperties.TransparentBlack && val == 0) ? 0 : 255); - return; - } - - float pixel_value = (float)val / 255; - if (pixel_value != pixel_value) { - // The above test is an unpleasant way of checking if - // pixel_value is NaN, since ScriptSharp seems not to support - // Float.IsNaN(). This case "can't happen" in C#, but due to - // JavaScript's numerical model, it *can* in the transpiled - // SDK. - bmp.SetPixel(x, y, 0, 0, 0, 0); - return; - } - - Color pixel_color = colorMapper.FindClosestColor(pixel_value); - bmp.SetPixel(x, y, (int)pixel_color.R, (int)pixel_color.G, (int)pixel_color.B, (fitsProperties.TransparentBlack && val == 0) ? 0 : 255); - } - - private Bitmap GetBitmapByte(double min, double max, ScaleMap scale, int z, ColorMapContainer colorMapper) - { - byte[] buf = (byte[])DataBuffer; - double factor = max - min; - int stride = AxisSize[0]; - int page = AxisSize[0] * AxisSize[1] * z; - Bitmap bmp = Bitmap.Create(AxisSize[0], AxisSize[1]); - - for (int y = 0; y < AxisSize[1]; y++) - { - int indexY = ((AxisSize[1] - 1) - y); - - for (int x = 0; x < AxisSize[0]; x++) - { - if (color) - { - int datR = buf[(x + indexY * stride)]; - int datG = buf[(x + indexY * stride) + page]; - int datB = buf[(x + indexY * stride) + page * 2]; - if (fitsProperties.ContainsBlanks && (double)datR == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - int r = scale.Map(datR); - int g = scale.Map(datG); - int b = scale.Map(datB); - bmp.SetPixel(x, y, r, g, b, 255); - } - } - else - { - int dataValue = buf[x + indexY * stride + page]; - if (fitsProperties.ContainsBlanks && (double)dataValue == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - Byte val = scale.Map(dataValue); - SetPixelWithColorMap(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - } - - private Bitmap GetBitmapDouble(double min, double max, ScaleMap scale, int z, ColorMapContainer colorMapper) - { - double[] buf = (double[])DataBuffer; - double factor = max - min; - int stride = AxisSize[0]; - int page = AxisSize[0] * AxisSize[1] * z ; - Bitmap bmp = Bitmap.Create(AxisSize[0], AxisSize[1]); - - for (int y = 0; y < AxisSize[1]; y++) - { - int indexY = ((AxisSize[1] - 1) - y); - for (int x = 0; x < AxisSize[0]; x++) - { - if (color) - { - double datR = buf[(x + indexY * stride)]; - double datG = buf[(x + indexY * stride) + page]; - double datB = buf[(x + indexY * stride) + page * 2]; - if (fitsProperties.ContainsBlanks && (double)datR == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - int r = scale.Map(datR); - int g = scale.Map(datG); - int b = scale.Map(datB); - bmp.SetPixel(x, y, r, g, b, 255); - } - } - else - { - double dataValue = buf[x + indexY * stride + page]; - if (fitsProperties.ContainsBlanks && (double)dataValue == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - Byte val = scale.Map(dataValue); - SetPixelWithColorMap(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - } - - private Bitmap GetBitmapFloat(double min, double max, ScaleMap scale, int z, ColorMapContainer colorMapper) - { - float[] buf = (float[])DataBuffer; - double factor = max - min; - int stride = AxisSize[0]; - int page = AxisSize[0] * AxisSize[1] * z; - Bitmap bmp = Bitmap.Create(AxisSize[0], AxisSize[1]); - - for (int y = 0; y < AxisSize[1]; y++) - { - int indexY = ((AxisSize[1] - 1) - y); - for (int x = 0; x < AxisSize[0]; x++) - { - if (color) - { - double datR = buf[(x + indexY * stride)]; - double datG = buf[(x + indexY * stride) + page]; - double datB = buf[(x + indexY * stride) + page * 2]; - if (fitsProperties.ContainsBlanks && (double)datR == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - int r = scale.Map(datR); - int g = scale.Map(datG); - int b = scale.Map(datB); - bmp.SetPixel(x, y, r, g, b, 255); - } - } - else - { - double dataValue = buf[x + indexY * stride + page]; - if (fitsProperties.ContainsBlanks && (double)dataValue == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - Byte val = scale.Map(dataValue); - SetPixelWithColorMap(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - } - - private Bitmap GetBitmapInt(double min, double max, ScaleMap scale, int z, ColorMapContainer colorMapper) - { - int[] buf = (int[])DataBuffer; - double factor = max - min; - int stride = AxisSize[0]; - int page = AxisSize[0] * AxisSize[1] * z; - Bitmap bmp = Bitmap.Create(AxisSize[0], AxisSize[1]); - - for (int y = 0; y < AxisSize[1]; y++) - { - int indexY = ((AxisSize[1] - 1) - y); - for (int x = 0; x < AxisSize[0]; x++) - { - if (color) - { - int datR = buf[(x + indexY * stride)]; - int datG = buf[(x + indexY * stride) + page]; - int datB = buf[(x + indexY * stride) + page * 2]; - if (fitsProperties.ContainsBlanks && (double)datR == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - int r = scale.Map(datR); - int g = scale.Map(datG); - int b = scale.Map(datB); - bmp.SetPixel(x, y, r, g, b, 255); - } - } - else - { - int dataValue = buf[x + indexY * stride + page]; - if (fitsProperties.ContainsBlanks && (double)dataValue == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - Byte val = scale.Map(dataValue); - SetPixelWithColorMap(bmp, x, y, val, colorMapper); - } - } - } - } - - return bmp; - } - public Bitmap GetBitmapShort(double min, double max, ScaleMap scale, int z, ColorMapContainer colorMapper) - { - short[] buf = (short[])DataBuffer; - double factor = max - min; - int stride = AxisSize[0]; - int page = AxisSize[0] * AxisSize[1] * z; - Bitmap bmp = Bitmap.Create(AxisSize[0], AxisSize[1]); - - for (int y = 0; y < AxisSize[1]; y++) - { - int indexY = ((AxisSize[1] - 1) - y); - - for (int x = 0; x < AxisSize[0]; x++) - { - if (color) - { - int datR = buf[(x + indexY * stride)]; - int datG = buf[(x + indexY * stride) + page]; - int datB = buf[(x + indexY * stride) + page * 2]; - if (fitsProperties.ContainsBlanks && (double)datR == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - int r = scale.Map(datR); - int g = scale.Map(datG); - int b = scale.Map(datB); - bmp.SetPixel(x, y, r, g, b, 255); - } - } - else - { - int dataValue = buf[x + indexY * stride + page]; - if (fitsProperties.ContainsBlanks && (double)dataValue == fitsProperties.BlankValue) - { - bmp.SetPixel(x, y, 0, 0, 0, 0); - } - else - { - Byte val = scale.Map(dataValue); - SetPixelWithColorMap(bmp, x, y, val, colorMapper); - } - } - - } - } - return bmp; - } - - protected override void ComputeWcs() - { - if (!isTiledFits) - { - base.ComputeWcs(); - } - } - - protected override void PopulateHistogram(int[] histogram) - { - switch (DataType) - { - case DataTypes.ByteT: - PopulateHistogramByte(histogram); - break; - case DataTypes.Int16T: - PopulateHistogramInt16(histogram); - break; - case DataTypes.Int32T: - PopulateHistogramInt32(histogram); - break; - case DataTypes.FloatT: - PopulateHistogramFloat(histogram); - break; - case DataTypes.DoubleT: - PopulateHistogramDouble(histogram); - break; - } - } - - private void PopulateHistogramDouble(int[] histogram) - { - int buckets = histogram.Length; - double[] buf = (double[])DataBuffer; - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - foreach (double val in buf) - { - if (!(val == double.NaN)) - { - histogram[Math.Min(buckets - 1, (int)((val - fitsProperties.MinVal) / factor))]++; - } - } - } - - private void PopulateHistogramFloat(int[] histogram) - { - int buckets = histogram.Length; - float[] buf = (float[])DataBuffer; - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - foreach (float val in buf) - { - if (!(val == NaN)) - { - histogram[Math.Min(buckets - 1, (int)((val - fitsProperties.MinVal) / factor))]++; - } - } - } - - private void PopulateHistogramInt32(int[] histogram) - { - int buckets = histogram.Length; - Int32[] buf = (Int32[])DataBuffer; - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - foreach (Int32 val in buf) - { - histogram[Math.Min(buckets - 1, (int)((val - fitsProperties.MinVal) / factor))]++; - } - } - - private void PopulateHistogramInt16(int[] histogram) - { - int buckets = histogram.Length; - short[] buf = (short[])DataBuffer; - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - foreach (Int16 val in buf) - { - histogram[Math.Min(buckets - 1, (int)((val - fitsProperties.MinVal) / factor))]++; - } - } - - private void PopulateHistogramByte(int[] histogram) - { - int buckets = histogram.Length; - Byte[] buf = (Byte[])DataBuffer; - double factor = (fitsProperties.MaxVal - fitsProperties.MinVal) / buckets; - - foreach (Byte val in buf) - { - histogram[Math.Min(buckets - 1, (int)((val - fitsProperties.MinVal) / factor))]++; - } - } - - } - - - public abstract class ScaleMap - { - public abstract byte Map(double val); - } - - public class ScaleLinear : ScaleMap - { - double min; - double max; - double factor; - double logFactor; - public ScaleLinear(double min, double max) - { - this.min = min; - this.max = max; - factor = max - min; - } - - public override byte Map(double val) - { - return (Byte)Math.Min(255, Math.Max(0, (int)((double)(val - min) / factor * 255))); - } - } - - public class ScaleLog : ScaleMap - { - double min; - double max; - double factor; - double logFactor; - public ScaleLog(double min, double max) - { - this.min = min; - this.max = max; - factor = max - min; - logFactor = 255 / Math.Log(255); - } - - public override byte Map(double val) - { - return (Byte)Math.Min(255, Math.Max(0, (int)((double)Math.Log((val - min) / factor * 255) * logFactor))); - } - } - - public class ScalePow : ScaleMap - { - double min; - double max; - double factor; - double powFactor; - public ScalePow(double min, double max) - { - this.min = min; - this.max = max; - factor = max - min; - powFactor = 255 / Math.Pow(255, 2); - } - - public override byte Map(double val) - { - return (Byte)Math.Min(255, Math.Max(0, (int)((double)Math.Pow((val - min) / factor * 255, 2) * powFactor))); - } - } - - public class ScaleSqrt : ScaleMap - { - double min; - double max; - double factor; - double sqrtFactor; - public ScaleSqrt(double min, double max) - { - this.min = min; - this.max = max; - factor = max - min; - sqrtFactor = 255 / Math.Sqrt(255); - } - - public override byte Map(double val) - { - return (Byte)Math.Min(255, Math.Max(0, (int)((double)Math.Sqrt((val - min) / factor * 255) * sqrtFactor))); - } - } - - public class HistogramEqualization : ScaleMap - { - double min; - double max; - double factor; - int[] Histogram; - int maxHistogramValue = 1; - Byte[] lookup; - const int buckets = 10000; - public HistogramEqualization(FitsImageJs image, double min, double max) - { - this.min = min; - this.max = max; - factor = max - min; - Histogram = image.ComputeHistogram(buckets); - maxHistogramValue = Histogram[buckets]; - lookup = new Byte[buckets]; - int totalCounts = (int)(image.SizeX * image.SizeY); - int sum = 0; - for (int i = 0; i < buckets; i++) - { - sum += Histogram[i]; - lookup[i] = (Byte)(Math.Min(255, ((sum * 255.0)) / totalCounts) + .5); - } - } - - public override byte Map(double val) - { - return (Byte)lookup[Math.Min(buckets - 1, Math.Max(0, (int)((double)(val - min) / factor * (buckets - 1.0))))]; - } - } -} diff --git a/engine/csharp_ref/Layers/FitsImageTile.cs b/engine/csharp_ref/Layers/FitsImageTile.cs deleted file mode 100644 index a631bb3b..00000000 --- a/engine/csharp_ref/Layers/FitsImageTile.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -using System.Html.Data.Files; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class FitsImageTile : FitsImage - { - public FitsImageTile(Imageset dataset, string file, WcsLoaded callMeBack) : base(dataset, file, null, callMeBack) - { - } - - // Min & Max are already known for pyramid FITS. - // To improve performance, the below per pixel methods are overriden - protected override void ReadDataUnitFloat64(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getFloat64(this.position, false); - i++; - this.position += 8; - } - } - - protected override void ReadDataUnitFloat32(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getFloat32(this.position, false); - i++; - this.position += 4; - } - } - protected override void ReadDataUnitUint8(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getUint8(this.position); - i++; - this.position += 1; - } - } - protected override void ReadDataUnitInt16(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getInt16(this.position, false); - i++; - this.position += 2; - } - } - - protected override void ReadDataUnitInt32(DataView dataView) - { - int i = 0; - while (this.position < dataView.byteLength) - { - dataUnit[i] = dataView.getInt32(this.position, false); - i++; - this.position += 4; - } - } - - protected override void ComputeWcs() - { - } - - } -} diff --git a/engine/csharp_ref/Layers/GreatCircleRouteLayer.cs b/engine/csharp_ref/Layers/GreatCircleRouteLayer.cs deleted file mode 100644 index b44b62d7..00000000 --- a/engine/csharp_ref/Layers/GreatCircleRouteLayer.cs +++ /dev/null @@ -1,236 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public class GreatCirlceRouteLayer : Layer - { - - public override string GetTypeName() - { - return "TerraViewer.GreatCirlceRouteLayer"; - } - - TriangleList triangleList = null; - public override void CleanUp() - { - if (triangleList != null) - { - triangleList.Clear(); - } - triangleList = null; - base.CleanUp(); - } - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - if (triangleList == null) - { - InitializeRoute(renderContext); - } - triangleList.JNow = percentComplete / 100; - triangleList.Draw(renderContext, opacity * this.Opacity, CullMode.CounterClockwise); - - - return true; - } - - private void InitializeRoute(RenderContext renderContext) - { - triangleList = new TriangleList(); - triangleList.Decay = 1000; - triangleList.Sky = this.Astronomical; - triangleList.TimeSeries = true; - triangleList.DepthBuffered = false; - triangleList.AutoTime = false; - - int steps = 500; - - Vector3d start = Coordinates.GeoTo3dDouble(latStart, lngStart); - Vector3d end = Coordinates.GeoTo3dDouble(latEnd, lngEnd); - Vector3d dir = Vector3d.SubtractVectors(end, start); - dir.Normalize(); - - Vector3d startNormal = start; - startNormal.Normalize(); - - Vector3d left = Vector3d.Cross(startNormal, dir); - Vector3d right = Vector3d.Cross(dir, startNormal); - left.Normalize(); - right.Normalize(); - - left.Multiply(.001 * width); - right.Multiply(.001 * width); - - Vector3d lastLeft = new Vector3d(); - Vector3d lastRight = new Vector3d(); - bool firstTime = true; - for (int i = 0; i <= steps; i++) - { - Vector3d v = Vector3d.Lerp(start, end, i / (float)steps); - v.Normalize(); - // v.Multiply(1.1); - Vector3d cl = v; - Vector3d cr = v; - - cl.Add(left); - cr.Add(right); - - if (!firstTime) - { - triangleList.AddQuad(lastRight, lastLeft, cr, cl, Color, new Dates(i / (float)steps, 2)); - } - else - { - firstTime = false; - } - - lastLeft = cl; - lastRight = cr; - - - } - - } - - public override double[] GetParams() - { - return new double[] { percentComplete }; - - } - - public override string[] GetParamNames() - { - return new string[] { "Percentage" }; - } - - public override void SetParams(double[] paramList) - { - if (paramList.Length > 0) - { - percentComplete = paramList[0]; - } - } - - private double latStart = 0; - - - public double LatStart - { - get { return latStart; } - set - { - if (latStart != value) - { - latStart = value; - version++; - } - } - } - private double lngStart = 0; - - - public double LngStart - { - get { return lngStart; } - set - { - if (lngStart != value) - { - lngStart = value; - version++; - } - } - } - private double latEnd = 0; - - - public double LatEnd - { - get { return latEnd; } - set - { - if (latEnd != value) - { - latEnd = value; - version++; - } - } - } - private double lngEnd = 0; - - - public double LngEnd - { - get { return lngEnd; } - set - { - if (lngEnd != value) - { - lngEnd = value; - version++; - } - } - } - - private double width = 4; - - - public double Width - { - get { return width; } - set - { - if (width != value) - { - width = value; - version++; - } - } - } - - private double percentComplete = 100; - - - public double PercentComplete - { - get { return percentComplete; } - set - { - if (percentComplete != value) - { - percentComplete = value; - version++; - } - } - } - - public override void WriteLayerProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteAttributeString("LatStart", LatStart.ToString()); - xmlWriter.WriteAttributeString("LngStart", LngStart.ToString()); - xmlWriter.WriteAttributeString("LatEnd", LatEnd.ToString()); - xmlWriter.WriteAttributeString("LngEnd", LngEnd.ToString()); - xmlWriter.WriteAttributeString("Width", Width.ToString()); - xmlWriter.WriteAttributeString("PercentComplete", PercentComplete.ToString()); - - } - - public override void InitializeFromXml(XmlNode node) - { - latStart = double.Parse(node.Attributes.GetNamedItem("LatStart").Value); - lngStart = double.Parse(node.Attributes.GetNamedItem("LngStart").Value); - latEnd = double.Parse(node.Attributes.GetNamedItem("LatEnd").Value); - lngEnd = double.Parse(node.Attributes.GetNamedItem("LngEnd").Value); - width = double.Parse(node.Attributes.GetNamedItem("Width").Value); - percentComplete = double.Parse(node.Attributes.GetNamedItem("PercentComplete").Value); - } - } -} diff --git a/engine/csharp_ref/Layers/GridLayer.cs b/engine/csharp_ref/Layers/GridLayer.cs deleted file mode 100644 index 3f14e015..00000000 --- a/engine/csharp_ref/Layers/GridLayer.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class GridLayer : Layer - { - public GridLayer() - { - - } - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - Grids.DrawPlanetGrid(renderContext, opacity * Opacity, Color); - Grids.DrawPlanetGridText(renderContext, opacity * Opacity, Color); - return true; - } - } -} diff --git a/engine/csharp_ref/Layers/ISSLayer.cs b/engine/csharp_ref/Layers/ISSLayer.cs deleted file mode 100644 index 0726b214..00000000 --- a/engine/csharp_ref/Layers/ISSLayer.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Data.Files; - -namespace wwtlib -{ - delegate void BackInitDelegate(); - - public class ISSLayer : Object3dLayer - { - public ISSLayer() - { - ID = ISSGuid; - } - - public static Guid ISSGuid = Guid.FromString("00000001-0002-0003-0405-060708090a0b"); - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - if (object3d == null && issmodel == null) - { - if (!loading) - { - Matrix3d worldView = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - Vector3d v = worldView.Transform(Vector3d.Empty); - double scaleFactor = Math.Sqrt(worldView.M11 * worldView.M11 + worldView.M22 * worldView.M22 + worldView.M33 * worldView.M33); - double dist = v.Length(); - double radius = scaleFactor; - - // Calculate pixelsPerUnit which is the number of pixels covered - // by an object 1 AU at the distance of the planet center from - // the camera. This calculation works regardless of the projection - // type. - int viewportHeight = (int)renderContext.Height; - double p11 = renderContext.Projection.M11; - double p34 = renderContext.Projection.M34; - double p44 = renderContext.Projection.M44; - - - double w = Math.Abs(p34) * dist + p44; - float pixelsPerUnit = (float)(p11 / w) * viewportHeight; - float radiusInPixels = (float)(radius * pixelsPerUnit); - if (radiusInPixels > 0.5f) - { - LoadBackground(); - } - } - - } - - object3d = issmodel; - return base.Draw(renderContext, opacity, flat); - } - - //todo need to synce the ISS settings to settings.active thru keeping copy of last setting & enabled state and setting the other to match when changed. - //public override bool Enabled - //{ - // get - // { - // return base.Enabled = Settings.Active.ShowISSModel; - // } - // set - // { - // Properties.Settings.Default.ShowISSModel = base.Enabled = value; - // } - //} - - public override LayerUI GetPrimaryUI() - { - return null; - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - return; - } - - public override void LoadData(TourDocument doc, string filename) - { - return; - } - public override void CleanUp() - { - // base.CleanUp(); - } - - static bool loading = false; - - static Object3d issmodel = null; - static TourDocument doc = null; - - public static void LoadBackground() - { - // The ISS frame cannot be created in freestanding mode, so I'm not - // sure if this function will even get called, but just in case, we - // make sure to noop if we're in freestanding mode. - if (loading || WWTControl.Singleton.FreestandingMode) - { - return; - } - - loading = true; - string url = URLHelpers.singleton.coreStaticUrl("data/iss.wtt"); - - doc = TourDocument.FromUrlRaw(url, - delegate - { - CreateSpaceStation(); - }); - } - - public static void CreateSpaceStation() - { - doc.Id = "28016047-97a9-4b33-a226-cd820262a151"; - string filename = "0c10ae54-b6da-4282-bfda-f34562d403bc.3ds"; - - Object3d o3d = new Object3d(doc, filename, true, false, true, Colors.White); - if (o3d != null) - { - o3d.ISSLayer = true; - issmodel = o3d; - } - } - } -} diff --git a/engine/csharp_ref/Layers/ImageSetLayer.cs b/engine/csharp_ref/Layers/ImageSetLayer.cs deleted file mode 100644 index 605b7b99..00000000 --- a/engine/csharp_ref/Layers/ImageSetLayer.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class ImageSetLayer : Layer - { - Imageset imageSet = null; - - public Imageset ImageSet - { - get { return imageSet; } - set { imageSet = value; } - } - - string extension = ".txt"; - - public ImageSetLayer() - { - } - - public static ImageSetLayer Create(Imageset set) - { - ImageSetLayer isl = new ImageSetLayer(); - isl.imageSet = set; - return isl; - } - - bool overrideDefaultLayer = false; - - public bool OverrideDefaultLayer - { - get { return overrideDefaultLayer; } - set { overrideDefaultLayer = value; } - } - - public FitsImage GetFitsImage() - { - return imageSet.WcsImage as FitsImage; - } - - // Test whether our underlying imagery is FITS based. - // - // This can come in two flavors: a single FITS image, or tiled FITS. - // Note that even though the FileType/Extension field can currently - // specify multiple file formats, the rendering code requires that the - // extension is exactly ".fits" for FITS rendering to kick in. - bool IsFitsImageset() { - bool hasFitsExt = imageSet.Extension == ".fits"; - return imageSet.WcsImage is FitsImage || (imageSet.WcsImage == null && hasFitsExt); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode imageSetNode = Util.SelectSingleNode(node, "ImageSet"); - - imageSet = Imageset.FromXMLNode(imageSetNode); - - - if (node.Attributes.GetNamedItem("Extension") != null) - { - extension = node.Attributes.GetNamedItem("Extension").Value; - } - - if (node.Attributes.GetNamedItem("ScaleType") != null) - { - ImageSet.FitsProperties.ScaleType = (ScaleTypes)Enums.Parse("ScaleTypes", node.Attributes.GetNamedItem("ScaleType").Value); - } - - if (node.Attributes.GetNamedItem("MinValue") != null) - { - ImageSet.FitsProperties.MinVal = double.Parse(node.Attributes.GetNamedItem("MinValue").Value); - ImageSet.FitsProperties.LowerCut = node.Attributes.GetNamedItem("LowerCut") != null - ? double.Parse(node.Attributes.GetNamedItem("LowerCut").Value) : ImageSet.FitsProperties.MinVal; - } - - if (node.Attributes.GetNamedItem("MaxValue") != null) - { - ImageSet.FitsProperties.MaxVal = double.Parse(node.Attributes.GetNamedItem("MaxValue").Value); - ImageSet.FitsProperties.UpperCut = node.Attributes.GetNamedItem("UpperCut") != null - ? double.Parse(node.Attributes.GetNamedItem("UpperCut").Value) : ImageSet.FitsProperties.MaxVal; - } - - if (node.Attributes.GetNamedItem("ColorMapperName") != null) - { - ImageSet.FitsProperties.ColorMapName = node.Attributes.GetNamedItem("ColorMapperName").Value; - } - - if (node.Attributes.GetNamedItem("OverrideDefault") != null) - { - overrideDefaultLayer = bool.Parse(node.Attributes.GetNamedItem("OverrideDefault").Value); - } - - } - - bool loaded = false; - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - if (!loaded) - { - return false; - } - //if (!flat) - //{ - // renderContext.setRasterizerState(TriangleCullMode.CullClockwise); - //} - renderContext.WorldBase = renderContext.World; - renderContext.ViewBase = renderContext.View; - renderContext.MakeFrustum(); - renderContext.DrawImageSet(imageSet, this.Opacity * opacity * 100); - return true; - - } - - public override void WriteLayerProperties(XmlTextWriter xmlWriter) - { - if (imageSet.WcsImage != null) - { - if (IsFitsImageset()) - { - extension = ".fit"; - } - else - { - extension = ".png"; - } - - xmlWriter.WriteAttributeString("Extension", extension); - } - - if (IsFitsImageset()) - { - xmlWriter.WriteAttributeString("ScaleType", Enums.ToXml("ScaleTypes", (int)imageSet.FitsProperties.ScaleType)); - xmlWriter.WriteAttributeString("MinValue", imageSet.FitsProperties.MinVal.ToString()); - xmlWriter.WriteAttributeString("MaxValue", imageSet.FitsProperties.MaxVal.ToString()); - xmlWriter.WriteAttributeString("LowerCut", imageSet.FitsProperties.LowerCut.ToString()); - xmlWriter.WriteAttributeString("UpperCut", imageSet.FitsProperties.UpperCut.ToString()); - - if (imageSet.FitsProperties.ColorMapName != null) { - xmlWriter.WriteAttributeString("ColorMapperName", imageSet.FitsProperties.ColorMapName); - } - } - - xmlWriter.WriteAttributeString("OverrideDefault", overrideDefaultLayer.ToString()); - - Imageset.SaveToXml(xmlWriter, imageSet, ""); - base.WriteLayerProperties(xmlWriter); - } - - public override string GetTypeName() - { - return "TerraViewer.ImageSetLayer"; - } - - public override void CleanUp() - { - base.CleanUp(); - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - if (imageSet.WcsImage is FitsImage) - { - string fName = ((WcsImage)imageSet.WcsImage).Filename; - string fileName = fc.TempDirectory + string.Format("{0}\\{1}{2}", fc.PackageID, this.ID.ToString(), extension); - fc.AddFile(fileName, ((FitsImage)imageSet.WcsImage).sourceBlob); - } - } - - public override string[] GetParamNames() - { - return base.GetParamNames(); - } - - public override double[] GetParams() - { - return base.GetParams(); - } - - public override void SetParams(double[] paramList) - { - base.SetParams(paramList); - } - - public void SetImageScale(ScaleTypes scaleType, double min, double max) - { - Script.Literal("console.warn('SetImageScale is considered deprecated. Use setImageScaleRaw or setImageScalePhysical instead.')"); - SetImageScaleRaw(scaleType, min, max); - } - - public void SetImageScaleRaw(ScaleTypes scaleType, double min, double max) - { - ImageSet.FitsProperties.LowerCut = min; - ImageSet.FitsProperties.UpperCut = max; - ImageSet.FitsProperties.ScaleType = scaleType; - - if (imageSet.WcsImage is FitsImageJs) - { - Histogram.UpdateScale(this, scaleType, min, max); - } - } - - public void SetImageScalePhysical(ScaleTypes scaleType, double min, double max) - { - double newMin = min; - double newMax = max; - - if (IsFitsImageset()) - { - newMin = (newMin - imageSet.FitsProperties.BZero) / imageSet.FitsProperties.BScale; - newMax = (newMax - imageSet.FitsProperties.BZero) / imageSet.FitsProperties.BScale; - } - - SetImageScaleRaw(scaleType, newMin, newMax); - } - - public void SetImageZ(double z) - { - if (IsFitsImageset()) - { - Histogram.UpdateImage(this, z); - } - } - - public string ColorMapperName - { - get { - return ImageSet.FitsProperties.ColorMapName; } - set - { - if (ColorMapContainer.FromNamedColormap(value) == null) - throw new Exception("Invalid colormap name"); - - version++; - - if (IsFitsImageset()) - { - if (RenderContext.UseGlVersion2) - { - imageSet.FitsProperties.ColorMapName = value; - } - else - { - Histogram.UpdateColorMapper(this, value); - } - } - } - } - - public ColorMapContainer ColorMapper - { - get - { - if (ImageSet.FitsProperties.ColorMapName == null) { - return null; - } else { - return ColorMapContainer.FromNamedColormap(ImageSet.FitsProperties.ColorMapName); - } - } - } - - public override void LoadData(TourDocument tourDoc, string filename) - { - if (extension.ToLowerCase().StartsWith(".fit")) - { - System.Html.Data.Files.Blob blob = tourDoc.GetFileBlob(filename.Replace(".txt", extension)); - FitsImage fi; - - if (RenderContext.UseGlVersion2) - { - fi = new FitsImage(imageSet, "image.fit", blob, DoneLoading); - } - else - { - fi = new FitsImageJs(imageSet, "image.fit", blob, DoneLoading); - } - - imageSet.WcsImage = fi; - } - else - { - loaded = true; - } - - } - - public void DoneLoading(WcsImage wcsImage) - { - loaded = true; - } - } -} diff --git a/engine/csharp_ref/Layers/Layer.cs b/engine/csharp_ref/Layers/Layer.cs deleted file mode 100644 index 96c653d4..00000000 --- a/engine/csharp_ref/Layers/Layer.cs +++ /dev/null @@ -1,727 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - - //[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method)] - //public class LayerProperty : System.Attribute - //{ - - // public LayerProperty() - // { - - // } - //} - - - - public enum AltUnits { Meters=1, Feet=2, Inches=3, Miles=4, Kilometers=5, AstronomicalUnits=6, LightYears=7, Parsecs=8, MegaParsecs=9, Custom=10 }; - - public enum FadeType { FadeIn=1, FadeOut=2, Both=3, None=4 }; - public abstract class Layer - { - public virtual LayerUI GetPrimaryUI() - { - return null; - } - - public Guid ID = Guid.NewGuid(); - - public bool LoadedFromTour = false; - - public TourDocument tourDocument = null; - - public string GetFileStreamUrl(string filename) - { - if (tourDocument != null) - { - return tourDocument.GetFileStream(filename); - } - return null; - } - - protected float opacity = 1.0f; - - public virtual float Opacity - { - get - { - return opacity; - } - set - { - if (opacity != value) - { - version++; - opacity = value; - } - - } - } - - public bool opened = false; - public virtual bool Opened - { - get - { - return opened; - } - set - { - if (opened != value) - { - version++; - opened = value; - } - } - } - - private Date startTime = Date.Parse("01/01/1900"); - - public Date StartTime - { - get { return startTime; } - set - { - if (startTime != value) - { - version++; - startTime = value; - } - } - } - private Date endTime = Date.Parse("01/01/2100"); - - - - public Date EndTime - { - get { return endTime; } - set - { - if (endTime != value) - { - version++; - endTime = value; - } - } - } - - private double fadeSpan = 0; - - - public double FadeSpan - { - get { return fadeSpan; } - set - { - version++; - fadeSpan = value; - } - } - - private FadeType fadeType = FadeType.None; - - - public FadeType FadeType - { - get { return fadeType; } - set { - if (fadeType != value) - { - Version++; - fadeType = value; - } - } - } - protected int version = 0; - - - public int Version - { - get { return version; } - set { version = value; } - } - - public virtual Place FindClosest(Coordinates target, float distance, Place closestPlace, bool astronomical) - { - return closestPlace; - } - - public virtual bool HoverCheckScreenSpace(Vector2d cursor) - { - return false; - } - - public virtual bool ClickCheckScreenSpace(Vector2d cursor) - { - return false; - } - - - public virtual bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - return true; - } - - public virtual bool PreDraw(RenderContext renderContext, float opacity) - { - return true; - } - - public virtual bool UpdateData(object data, bool purgeOld, bool purgeAll, bool hasHeader) - { - return true; - } - - // "UpdateData" used to be named this. We add this function as a - // compatibility shim just in case there's some JavaScript out there - // still using the old name. - public bool UpadteData(object data, bool purgeOld, bool purgeAll, bool hasHeader) - { - return UpdateData(data, purgeOld, purgeAll, hasHeader); - } - - public virtual bool CanCopyToClipboard() - { - return false; - } - - public virtual void CopyToClipboard() - { - return; - } - - public virtual double[] GetParams() - { - double[] paramList = new double[5]; - paramList[0] = color.R / 255; - paramList[1] = color.G / 255; - paramList[2] = color.B / 255; - paramList[3] = color.A / 255; - paramList[4] = opacity; - - - return paramList; - } - - public virtual void SetParams(double[] paramList) - { - if (paramList.Length == 5) - { - opacity = (float)paramList[4]; - color = Color.FromArgb((byte)(paramList[3] * 255), (byte)(paramList[0] * 255), (byte)(paramList[1] * 255), (byte)(paramList[2] * 255)); - } - } - - public virtual string[] GetParamNames() - { - - return new string[] { "Color.Red", "Color.Green", "Color.Blue", "Color.Alpha", "Opacity" }; - } - - public virtual object GetEditUI() - { - return this as IUiController; - } - - public virtual void CleanUp() - { - } - - private string name; - - public virtual string Name - { - get { return name; } - set - { - if (name != value) - { - version++; - name = value; - } - } - } - - public override string ToString() - { - return name; - } - - protected string referenceFrame; - - public string ReferenceFrame - { - get { return referenceFrame; } - set { referenceFrame = value; } - } - - //public bool SetProp(string name, string value) - //{ - // Type thisType = this.GetType(); - // PropertyInfo pi = thisType.GetProperty(name); - // bool safeToSet = false; - // Type layerPropType = typeof(LayerProperty); - // object[] attributes = pi.GetCustomAttributes(false); - // foreach (object var in attributes) - // { - // if (var.GetType() == layerPropType) - // { - // safeToSet = true; - // break; - // } - // } - - // if (safeToSet) - // { - // //Convert.ChangeType( - // if (pi.PropertyType.BaseType == typeof(Enum)) - // { - // pi.SetValue(this, Enum.Parse(pi.PropertyType, value, true), null); - // } - // else if (pi.PropertyType == typeof(TimeSpan)) - // { - // pi.SetValue(this, TimeSpan.Parse(value), null); - // } - // else if (pi.PropertyType == typeof(Vector3d)) - // { - // pi.SetValue(this, Vector3d.Parse(value), null); - // } - // else - // { - // // todo fix this - // // pi.SetValue(this, Convert.ChangeType(value, pi.PropertyType), null); - // } - // } - - - // return safeToSet; - //} - - //public bool SetProps(string xml) - //{ - // XDocument doc = XDocument.Parse(xml); - - - - // XElement root = doc.Element("LayerApi"); - - // XElement LayerNode = root.Element("Layer"); - // foreach (XAttribute attrib in LayerNode.Attributes()) - // { - // if (attrib.Name == "Class") - // { - // continue; - // } - // if (!SetProp(attrib.Name.ToString(), attrib.Value)) - // { - // return false; - // } - // } - - // return true; - //} - - //public string GetProp(string name) - //{ - // Type thisType = this.GetType(); - // PropertyInfo pi = thisType.GetProperty(name); - // bool safeToGet = false; - // Type layerPropType = typeof(LayerProperty); - // object[] attributes = pi.GetCustomAttributes(false); - // foreach (object var in attributes) - // { - // if (var.GetType() == layerPropType) - // { - // safeToGet = true; - // break; - // } - // } - - // if (safeToGet) - // { - // return pi.GetValue(this, null).ToString(); - // } - - - // return null; - //} - - public string GetProps() - { - //MemoryStream ms = new MemoryStream(); - //using (XmlTextWriter xmlWriter = new XmlTextWriter(ms, System.Text.Encoding.UTF8)) - //{ - // xmlWriter.Formatting = Formatting.Indented; - // xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - // xmlWriter.WriteStartElement("LayerApi"); - // xmlWriter.WriteElementString("Status", "Success"); - // xmlWriter.WriteStartElement("Layer"); - // xmlWriter.WriteAttributeString("Class", this.GetType().ToString().Replace("TerraViewer.","")); - - - // Type thisType = this.GetType(); - // PropertyInfo[] properties = thisType.GetProperties(); - - // Type layerPropType = typeof(LayerProperty); - - // foreach (PropertyInfo pi in properties) - // { - // bool safeToGet = false; - - // object[] attributes = pi.GetCustomAttributes(false); - // foreach (object var in attributes) - // { - // if (var.GetType() == layerPropType) - // { - // safeToGet = true; - // break; - // } - // } - - // if (safeToGet) - // { - // xmlWriter.WriteAttributeString(pi.Name, pi.GetValue(this, null).ToString()); - // } - - // } - // xmlWriter.WriteEndElement(); - // xmlWriter.WriteFullEndElement(); - // xmlWriter.Close(); - - //} - //byte[] data = ms.GetBuffer(); - //return Encoding.UTF8.GetString(data); - return ""; - } - - protected Color color = Colors.White; - - public virtual Color Color - { - get { return color; } - set - { - if (color != value) - { - color = value; - version++; - } - - } - } - - public virtual void ColorChanged() - { - } - - public virtual string ColorValue - { - get - { - return Color.ToString(); - } - set - { - Color = Color.FromName(value); - } - } - - // private bool enabled = true; - - - public bool Enabled = true; - //{ - // get { return enabled; } - // set - // { - // if (enabled != value) - // { - // version++; - // enabled = value; - // } - // //todo notify of change - // } - //} - - // Add named accessor functions so that we can support `enabled` as a - // "setting" in our TypeScript framework, without breaking anything that - // might rely on Enabled being a true bool. - - public bool get_enabled() { - return Enabled; - } - - public bool set_enabled(bool value) { - Enabled = value; - return value; - } - - protected bool astronomical = false; - - public bool Astronomical - { - get { return astronomical; } - set - { - if (astronomical != value) - { - version++; - astronomical = value; - } - } - } - - // - //public virtual string[] Header - //{ - // get - // { - // return null; - // } - - //} - /* Save Load support - * - */ - public virtual string GetTypeName() - { - return "TerraViewer.Layer"; - } - - - public virtual void SaveToXml(XmlTextWriter xmlWriter) - { - //todo write - xmlWriter.WriteStartElement("Layer"); - xmlWriter.WriteAttributeString("Id", ID.ToString()); - xmlWriter.WriteAttributeString("Type", GetTypeName()); - xmlWriter.WriteAttributeString("Name", Name); - xmlWriter.WriteAttributeString("ReferenceFrame", referenceFrame); - xmlWriter.WriteAttributeString("Color", color.Save()); - xmlWriter.WriteAttributeString("Opacity", opacity.ToString()); - xmlWriter.WriteAttributeString("StartTime", Util.XMLDate(StartTime)); - xmlWriter.WriteAttributeString("EndTime", Util.XMLDate(EndTime)); - xmlWriter.WriteAttributeString("FadeSpan", FadeSpan.ToString()); - xmlWriter.WriteAttributeString("FadeType", FadeType.ToString()); - - WriteLayerProperties(xmlWriter); - - xmlWriter.WriteEndElement(); - } - - public virtual void WriteLayerProperties(XmlTextWriter xmlWriter) - { - return; - } - - public virtual void InitializeFromXml(XmlNode node) - { - - } - - public static Layer FromXml(XmlNode layerNode, bool someFlag) - { - string layerClassName = layerNode.Attributes.GetNamedItem("Type").Value.ToString(); - - string overLayType = layerClassName.Replace("TerraViewer.",""); - if (overLayType == null) - { - return null; - } - - Layer newLayer = null; - - switch (overLayType) - { - case "SpreadSheetLayer": - newLayer = new SpreadSheetLayer(); - break; - case "GreatCirlceRouteLayer": - newLayer = new GreatCirlceRouteLayer(); - break; - case "GridLayer": - newLayer = new GridLayer(); - break; - case "ImageSetLayer": - newLayer = new ImageSetLayer(); - break; - case "Object3dLayer": - newLayer = new Object3dLayer(); - break; - case "OrbitLayer": - newLayer = new OrbitLayer(); - break; - case "VoTableLayer": - newLayer = new VoTableLayer(); - break; - default: - return null; - } - - //Force inheritance. - // TODO: Understand why this breaks in SS .8 - //Script.Literal("for(var method in this){\n /*if (({}).toString.call(this[method]).match(/\\s([a-zA-Z]+)/)[1].toLowerCase() == 'function'){\n*/ newLayer[method] = this[method];/*\n}*/\n}"); - - newLayer.InitFromXml(layerNode); - - return newLayer; - } - - public virtual void InitFromXml(XmlNode node) - { - ID = Guid.FromString(node.Attributes.GetNamedItem("Id").Value); - Name = node.Attributes.GetNamedItem("Name").Value; - referenceFrame = node.Attributes.GetNamedItem("ReferenceFrame").Value; - color = Color.Load(node.Attributes.GetNamedItem("Color").Value); - opacity = Single.Parse(node.Attributes.GetNamedItem("Opacity").Value); - - if (node.Attributes.GetNamedItem("StartTime") != null) - { - StartTime = new Date(node.Attributes.GetNamedItem("StartTime").Value); - } - - if (node.Attributes.GetNamedItem("EndTime") != null) - { - EndTime = new Date(node.Attributes.GetNamedItem("EndTime").Value); - } - - if (node.Attributes.GetNamedItem("FadeSpan") != null) - { - FadeSpan = Util.ParseTimeSpan((node.Attributes.GetNamedItem("FadeSpan").Value)); - } - - if (node.Attributes.GetNamedItem("FadeType") != null) - { - switch (node.Attributes.GetNamedItem("FadeType").Value) - { - case "In": - FadeType = FadeType.FadeIn; - break; - case "Out": - FadeType = FadeType.FadeOut; - break; - case "Both": - FadeType = FadeType.Both; - break; - case "None": - FadeType = FadeType.None; - break; - default: - break; - } - } - - InitializeFromXml(node); - } - - - - public virtual void LoadData(TourDocument doc, string filename) - { - return; - } - - public virtual void AddFilesToCabinet(FileCabinet fc) - { - return; - } - - public void GetStringFromGzipBlob(System.Html.Data.Files.Blob blob, GzipStringReady dataReady) - { - - // This method decompresses a blob into a string, and if the string cannot be decompressed - // due to an invalid header, we assume the blob is not compressed and return the string - // as-is. - - FileReader reader = new FileReader(); - reader.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e) - { - string result = ""; - try - { - result = (string)Script.Literal("pako.inflate(e.target.result, { to: 'string' })"); - } - catch (Exception err) - { - string errString = err.ToString(); - if (errString == "incorrect header check" || errString == "unknown compression method") - { - try - { - result = (string)Script.Literal("String.fromCharCode.apply(null, new Uint8Array(e.target.result))"); - } - catch (Exception error) - { - throw error; - } - } - else - { - throw err; - } - } - dataReady(result); - }; - reader. ReadAsArrayBuffer(blob); - } - - - } - - public delegate void GzipStringReady(string data); - - class LayerCollection : Layer - { - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - return base.Draw(renderContext, opacity, false); - } - - - - } - //public class MarkerPlot - //{ - // public Texture Texture; - // public VertexBuffer VertexBuffer = null; - // public int PointCount = 0; - - // public MarkerPlot() - // { - // } - - // public MarkerPlot(Texture texture, VertexBuffer vertexBuffer, int pointCount) - // { - // Texture = texture; - // VertexBuffer = vertexBuffer; - // PointCount = pointCount; - // } - - //} - - public class DomainValue - { - - public DomainValue(string text, int markerIndex) - { - Text = text; - MarkerIndex = markerIndex; - } - - public string Text; - public int MarkerIndex = 4; - public object CustomMarker = null; - - } - - -} diff --git a/engine/csharp_ref/Layers/LayerManager.cs b/engine/csharp_ref/Layers/LayerManager.cs deleted file mode 100644 index 87348b54..00000000 --- a/engine/csharp_ref/Layers/LayerManager.cs +++ /dev/null @@ -1,2626 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class LayerManager - { - static int version = 0; - - public static int Version - { - get { return LayerManager.version; } - set { LayerManager.version = value; } - } - - static FrameWizard _frameWizardDialog = new FrameWizard(); - public static FrameWizard FrameWizardDialog - { - get { return _frameWizardDialog; } - } - - static DataVizWizard _dataVizWizardDialog = new DataVizWizard(); - public static DataVizWizard DataVizWizardDialog - { - get { return _dataVizWizardDialog; } - } - - static ReferenceFrameProps _referenceFramePropsDialog = new ReferenceFrameProps(); - public static ReferenceFrameProps ReferenceFramePropsDialog - { - get { return _referenceFramePropsDialog; } - } - - static GreatCircleDialog _greatCircleDialog = new GreatCircleDialog(); - public static GreatCircleDialog GreatCircleDlg - { - get { return _greatCircleDialog; } - } - - static bool tourLayers = false; - - public static bool TourLayers - { - get { return LayerManager.tourLayers; } - set - { - if (LayerManager.tourLayers != value && value == false) - { - ClearLayers(); - LayerManager.tourLayers = value; - LoadTree(); - } - else if (LayerManager.tourLayers != value && value == true) - { - LayerManager.tourLayers = value; - InitLayers(); - } - - } - } - - public static void LoadTree() - { - if (WWTControl.scriptInterface != null) - { - WWTControl.scriptInterface.RefreshLayerManagerNow(); - } - } - - - - static Dictionary layerMaps = new Dictionary(); - static Dictionary layerMapsTours = new Dictionary(); - - public static Dictionary LayerMaps - { - get - { - if (TourLayers) - { - return LayerManager.layerMapsTours; - } - else - { - return LayerManager.layerMaps; - } - } - set - { - if (TourLayers) - { - LayerManager.layerMapsTours = value; - } - else - { - LayerManager.layerMaps = value; - } - } - } - - private static Dictionary allMaps = new Dictionary(); - private static Dictionary allMapsTours = new Dictionary(); - - public static Dictionary AllMaps - { - get - { - if (TourLayers) - { - return LayerManager.allMapsTours; - } - else - { - return LayerManager.allMaps; - } - } - set - { - if (TourLayers) - { - LayerManager.allMapsTours = value; - } - else - { - LayerManager.allMaps = value; - } - } - } - - static string currentMap = "Earth"; - - public static string CurrentMap - { - get { return LayerManager.currentMap; } - set { LayerManager.currentMap = value; } - } - - private static Dictionary layerList = new Dictionary(); - static Dictionary layerListTours = new Dictionary(); - - public static Dictionary LayerList - { - get - { - if (TourLayers) - { - return LayerManager.layerListTours; - } - else - { - return LayerManager.layerList; - } - } - set - { - if (TourLayers) - { - LayerManager.layerListTours = value; - } - else - { - LayerManager.layerList = value; - } - } - } - - // This function *can* be called multiple times safely, but it only - // needs to be called once upon app startup. The `InitLayers` function - // can be called more than once, if/when the `TourLayers` setting is - // toggled. - static public void OneTimeInitialization() - { - if (webFileMoons == null) { - GetMoonFile(URLHelpers.singleton.engineAssetUrl("moons.txt")); - } - - PushPin.TriggerLoadSprite(); - } - - static string moonfile = ""; - - static public void InitLayers() - { - ClearLayers(); - - LayerMap iss = null; - bool doISS = !TourLayers && !WWTControl.Singleton.FreestandingMode; - - if (doISS) - { - iss = new LayerMap("ISS", ReferenceFrames.Custom); - iss.Frame.Epoch = SpaceTimeController.TwoLineDateToJulian("10184.51609218"); - iss.Frame.SemiMajorAxis = 6728829.41; - iss.Frame.ReferenceFrameType = ReferenceFrameTypes.Orbital; - iss.Frame.Inclination = 51.6442; - iss.Frame.LongitudeOfAscendingNode = 147.0262; - iss.Frame.Eccentricity = .0009909; - iss.Frame.MeanAnomolyAtEpoch = 325.5563; - iss.Frame.MeanDailyMotion = 360 * 15.72172655; - iss.Frame.ArgumentOfPeriapsis = 286.4623; - iss.Frame.Scale = 1; - iss.Frame.SemiMajorAxisUnits = AltUnits.Meters; - iss.Frame.MeanRadius = 130; - iss.Frame.Oblateness = 0; - iss.Frame.ShowOrbitPath = true; - - string[] isstle = new string[0]; - - //This is downloaded now on startup - string url = URLHelpers.singleton.coreDynamicUrl("wwtweb/isstle.aspx"); - - WebFile webFile; - - webFile = new WebFile(url); - //webFile.ResponseType = "text"; - webFile.OnStateChange = delegate - { - if (webFile.State == StateType.Received) - { - string data = webFile.GetText(); - isstle = data.Split("\n"); - if (isstle.Length > 1) - { - iss.Frame.FromTLE(isstle[0], isstle[1], 398600441800000); - } - } - }; - - webFile.Send(); - iss.Enabled = true; - } - - LayerMaps["Sun"] = new LayerMap("Sun", ReferenceFrames.Sun); - LayerMaps["Sun"].AddChild(new LayerMap("Mercury", ReferenceFrames.Mercury)); - LayerMaps["Sun"].AddChild(new LayerMap("Venus", ReferenceFrames.Venus)); - LayerMaps["Sun"].AddChild(new LayerMap("Earth", ReferenceFrames.Earth)); - LayerMaps["Sun"].ChildMaps["Earth"].AddChild(new LayerMap("Moon", ReferenceFrames.Moon)); - - if (doISS) - { - LayerMaps["Sun"].ChildMaps["Earth"].AddChild(iss); - } - - //LayerMaps["Sun"].ChildMaps["Earth"].AddChild(ol); - //LayerMaps["Sun"].ChildMaps["Earth"].AddChild(l1); - //LayerMaps["Sun"].ChildMaps["Earth"].AddChild(l2); - - LayerMaps["Sun"].AddChild(new LayerMap("Mars", ReferenceFrames.Mars)); - LayerMaps["Sun"].AddChild(new LayerMap("Jupiter", ReferenceFrames.Jupiter)); - LayerMaps["Sun"].ChildMaps["Jupiter"].AddChild(new LayerMap("Io", ReferenceFrames.Io)); - LayerMaps["Sun"].ChildMaps["Jupiter"].AddChild(new LayerMap("Europa", ReferenceFrames.Europa)); - LayerMaps["Sun"].ChildMaps["Jupiter"].AddChild(new LayerMap("Ganymede", ReferenceFrames.Ganymede)); - LayerMaps["Sun"].ChildMaps["Jupiter"].AddChild(new LayerMap("Callisto", ReferenceFrames.Callisto)); - LayerMaps["Sun"].AddChild(new LayerMap("Saturn", ReferenceFrames.Saturn)); - LayerMaps["Sun"].AddChild(new LayerMap("Uranus", ReferenceFrames.Uranus)); - LayerMaps["Sun"].AddChild(new LayerMap("Neptune", ReferenceFrames.Neptune)); - LayerMaps["Sun"].AddChild(new LayerMap("Pluto", ReferenceFrames.Pluto)); - - AddMoons(moonfile); - - LayerMaps["Sky"] = new LayerMap("Sky", ReferenceFrames.Sky); - LayerMaps["Sun"].Open = true; - allMaps = new Dictionary(); - - AddAllMaps(LayerMaps, null); - - if (doISS) - { - AddIss(); - } - - version++; - LoadTree(); - } - - static void AddIss() - { - ISSLayer layer = new ISSLayer(); - - layer.Name = Language.GetLocalizedText(1314, "ISS Model (Toshiyuki Takahei)"); - layer.Enabled = Settings.Active.ShowISSModel; - LayerList[layer.ID] = layer; - layer.ReferenceFrame = "ISS"; - AllMaps["ISS"].Layers.Add(layer); - AllMaps["ISS"].Open = true; - } - - private static void AddAllMaps(Dictionary maps, String parent) - { - foreach (String key in maps.Keys) - { - LayerMap map = maps[key]; - map.Frame.Parent = parent; - AllMaps[map.Name] = map; - AddAllMaps(map.ChildMaps, map.Name); - } - } - - private static void ClearLayers() - { - foreach (Guid key in LayerList.Keys) - { - Layer layer = LayerList[key]; - layer.CleanUp(); - } - - LayerList.Clear(); - LayerMaps.Clear(); - } - - - static WebFile webFileMoons; - - public static void GetMoonFile(string url) - { - webFileMoons = new WebFile(url); - webFileMoons.OnStateChange = MoonFileStateChange; - webFileMoons.Send(); - } - - public static void MoonFileStateChange() - { - if (webFileMoons.State == StateType.Error) - { - Script.Literal("alert({0})", webFileMoons.Message); - } - else if (webFileMoons.State == StateType.Received) - { - moonfile = webFileMoons.GetText(); - InitLayers(); - } - - } - - private static void AddMoons(string file) - { - - string[] data = file.Split("\r\n"); - - bool first = true; - foreach (string line in data) - { - if (first) - { - first = false; - continue; - } - string[] parts = line.Split("\t"); - if (parts.Length > 16) - { - string planet = parts[0]; - LayerMap frame = new LayerMap(parts[2], ReferenceFrames.Custom); - frame.Frame.SystemGenerated = true; - frame.Frame.Epoch = double.Parse(parts[1]); - frame.Frame.SemiMajorAxis = double.Parse(parts[3]) * 1000; - frame.Frame.ReferenceFrameType = ReferenceFrameTypes.Orbital; - frame.Frame.Inclination = double.Parse(parts[7]); - frame.Frame.LongitudeOfAscendingNode = double.Parse(parts[8]); - frame.Frame.Eccentricity = double.Parse(parts[4]); - frame.Frame.MeanAnomolyAtEpoch = double.Parse(parts[6]); - frame.Frame.MeanDailyMotion = double.Parse(parts[9]); - frame.Frame.ArgumentOfPeriapsis = double.Parse(parts[5]); - frame.Frame.Scale = 1; - frame.Frame.SemiMajorAxisUnits = AltUnits.Meters; - frame.Frame.MeanRadius = double.Parse(parts[16]) * 1000; - frame.Frame.RotationalPeriod = double.Parse(parts[17]); - frame.Frame.ShowAsPoint = false; - frame.Frame.ShowOrbitPath = true; - frame.Frame.RepresentativeColor = Color.FromArgb(255, 175, 216, 230); - frame.Frame.Oblateness = 0; - - LayerMaps["Sun"].ChildMaps[planet].AddChild(frame); - - } - } - } - - public static VoTableLayer AddVoTableLayer(VoTable table, string title) - { - return LayerManager.AddVoTableLayerWithPlotType(table, title, PlotTypes.Circle); - } - - public static VoTableLayer AddVoTableLayerWithPlotType(VoTable table, string title, PlotTypes plotType) - { - VoTableLayer layer = VoTableLayer.Create(table, plotType); - layer.Name = title; - layer.Astronomical = true; - layer.ReferenceFrame = "Sky"; - LayerList[layer.ID] = layer; - AllMaps["Sky"].Layers.Add(layer); - AllMaps["Sky"].Open = true; - layer.Enabled = true; - version++; - LoadTree(); - - return layer; - } - - public static ImageSetLayer AddImageSetLayer(Imageset imageset, string title) - { - ImageSetLayer layer = ImageSetLayer.Create(imageset); - return AddFitsImageSetLayer(layer, title); - } - - public static ImageSetLayer AddImageSetLayerCallback(Imageset imageset, string title, ImagesetLoaded callback) - { - ImageSetLayer layer = ImageSetLayer.Create(imageset); - - // The tile rendering codepaths require that "Extension" is exactly - // .fits -- multiple extensions are not currently supported. - - bool isNonHipsTiledFits = - imageset.Extension == ".fits" && - layer.GetFitsImage() == null && - imageset.Projection != ProjectionType.Healpix; - - // The goal here is to fire the callback once the initial imageset - // data have loaded. In particular, for FITS-type imagesets, we - // inevitably need to download some data in order to figure out - // parameters like FitsProperties.LowerCut. - // - // At the moment, this is only wired up correctly for non-HiPS tiled - // FITS. In a pretty egregious hack, the OnMainImageLoaded callback - // below will be fired once the level-0 FITS tile is loaded. We - // basically needed to add this new callback hook because there - // wasn't any other way to get something to fire when the level-0 - // tile data actually arrive. - // - // HiPS FITS datasets will *eventually* get the right FitsProperties - // because the fetch of the HipsProperties data sets this up. (This - // is triggered by the HipsProperties constructor, used in - // Imageset.GetNewTile.) But the timing of the callback here is - // uncorrelated with that process. The same is broadly true for - // untiled FITS. This function should be improved to make sure that - // the callback argument gets fired at the right time for such - // datasets. - - if (isNonHipsTiledFits) { - imageset.FitsProperties.OnMainImageLoaded = delegate (FitsImage image) { - image.ApplyDisplaySettings(); - if (callback != null) { - callback(layer); - } - }; - } - - AddFitsImageSetLayer(layer, title); - - // For everything not yet handled, just trigger the callback now, if - // needed. - if (callback != null && (!isNonHipsTiledFits || imageset.FitsProperties.MainImageLoadedEventHasFired)) { - callback(layer); - } - - return layer; - } - - // This method is somewhat misnamed - there's nothing FITS-specific about it. - public static ImageSetLayer AddFitsImageSetLayer(ImageSetLayer layer, string title) - { - layer.DoneLoading(null); - layer.Name = title; - layer.Astronomical = true; - layer.ReferenceFrame = "Sky"; - LayerList[layer.ID] = layer; - AllMaps["Sky"].Layers.Add(layer); - AllMaps["Sky"].Open = true; - layer.Enabled = true; - version++; - LoadTree(); - return layer; - } - - public static string GetNextFitsName() - { - return getNextName("Fits Image"); - } - - public static string GetNextImageSetName() - { - return getNextName("Image Set"); - } - - private static string getNextName(string type){ - int currentNumber = 0; - foreach (string key in AllMaps.Keys) - { - foreach (Layer layer in AllMaps[key].Layers) - { - if (layer.Name.StartsWith(type + " ")) - { - string number = layer.Name.Replace(type + " ", ""); - try - { - int num = Int32.Parse(number); - if (num > currentNumber) - { - currentNumber = num; - } - } - catch - { - - } - } - } - } - - return string.Format("{0} {1}", type, currentNumber + 1); - } - - internal static void CloseAllTourLoadedLayers() - { - List purgeTargets = new List(); - foreach (Guid key in LayerList.Keys) - { - Layer layer = LayerList[key]; - if (layer.LoadedFromTour) - { - purgeTargets.Add(layer.ID); - } - } - - foreach (Guid guid in purgeTargets) - { - DeleteLayerByID(guid, true, false); - } - - List purgeMapsNames = new List(); - - foreach (String key in AllMaps.Keys) - { - LayerMap map = AllMaps[key]; - - if (map.LoadedFromTour && map.Layers.Count == 0) - { - purgeMapsNames.Add(map.Name); - } - } - - foreach (string name in purgeMapsNames) - { - PurgeLayerMapDeep(AllMaps[name], true); - } - - - - Version++; - LoadTree(); - - } - - public static void PurgeLayerMapDeep(LayerMap target, bool topLevel) - { - - foreach (Layer layer in target.Layers) - { - LayerManager.DeleteLayerByID(layer.ID, false, false); - } - - target.Layers.Clear(); - - foreach (string key in target.ChildMaps.Keys) - { - LayerMap map = target.ChildMaps[key]; - PurgeLayerMapDeep(map, false); - } - - target.ChildMaps.Clear(); - if (topLevel) - { - if (!String.IsNullOrEmpty(target.Frame.Parent)) - { - if (AllMaps.ContainsKey(target.Frame.Parent)) - { - AllMaps[target.Frame.Parent].ChildMaps.Remove(target.Name); - } - } - else - { - if (LayerMaps.ContainsKey(target.Name)) - { - LayerMaps.Remove(target.Name); - } - } - } - AllMaps.Remove(target.Name); - version++; - } - - - internal static void CleanAllTourLoadedLayers() - { - foreach (Guid key in LayerList.Keys) - { - Layer layer = LayerList[key]; - if (layer.LoadedFromTour) - { - //todo We may want to copy layers into a temp directory later, for now we are just leaving the layer data files in the temp tour directory. - layer.LoadedFromTour = false; - } - } - } - - // Merged layers from Tour Player Alternate universe into the real layer manager layers list - public static void MergeToursLayers() - { - - tourLayers = false; - bool OverWrite = false; - bool CollisionChecked = false; - - foreach (String key in allMapsTours.Keys) - { - LayerMap map = allMapsTours[key]; - if (!allMaps.ContainsKey(map.Name)) - { - LayerMap newMap = new LayerMap(map.Name, ReferenceFrames.Custom); - newMap.Frame = map.Frame; - newMap.LoadedFromTour = true; - LayerManager.AllMaps[newMap.Name] = newMap; - } - } - ConnectAllChildren(); - foreach (Guid key in layerListTours.Keys) - { - Layer layer = layerListTours[key]; - - if (LayerList.ContainsKey(layer.ID)) - { - if (!CollisionChecked) - { - //todo add UI in the future with possibility of OverWrite = false - OverWrite = true; - CollisionChecked = true; - } - - if (OverWrite) - { - LayerManager.DeleteLayerByID(layer.ID, true, false); - } - } - - if (!LayerList.ContainsKey(layer.ID)) - { - if (AllMaps.ContainsKey(layer.ReferenceFrame)) - { - LayerList[layer.ID] = layer; - - AllMaps[layer.ReferenceFrame].Layers.Add(layer); - } - } - else - { - layer.CleanUp(); - } - } - - layerListTours.Clear(); - allMapsTours.Clear(); - layerMapsTours.Clear(); - LoadTree(); - } - - public static void ConnectAllChildren() - { - foreach (String key in AllMaps.Keys) - { - LayerMap map = AllMaps[key]; - if (String.IsNullOrEmpty(map.Frame.Parent) && !LayerMaps.ContainsKey(map.Frame.Name)) - { - LayerMaps[map.Name] = map; - } - else if (!String.IsNullOrEmpty(map.Frame.Parent) && AllMaps.ContainsKey(map.Frame.Parent)) - { - if (!AllMaps[map.Frame.Parent].ChildMaps.ContainsKey(map.Frame.Name)) - { - AllMaps[map.Frame.Parent].ChildMaps[map.Frame.Name] = map; - map.Parent = AllMaps[map.Frame.Parent]; - } - } - } - } - - public static bool DeleteLayerByID(Guid ID, bool removeFromParent, bool updateTree) - { - if (LayerList.ContainsKey(ID)) - { - Layer layer = LayerList[ID]; - layer.CleanUp(); - if (removeFromParent) - { - AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - } - LayerList.Remove(ID); - version++; - if (updateTree) - { - LoadTree(); - } - return true; - } - else - { - return false; - } - - } - - internal static FrameTarget GetFrameTarget(RenderContext renderContext, string TrackingFrame) - { - - FrameTarget target = new FrameTarget(); - - Vector3d targetPoint = Vector3d.Empty; - - target.Target = Vector3d.Empty; - target.Matrix = Matrix3d.Identity; - - if (!AllMaps.ContainsKey(TrackingFrame)) - { - return target; - } - - List mapList = new List(); - - LayerMap current = AllMaps[TrackingFrame]; - - mapList.Add(current); - - while (current.Frame.Reference == ReferenceFrames.Custom) - { - current = current.Parent; - mapList.Insert(0, current); - } - - Matrix3d matOld = renderContext.World.Clone(); - Matrix3d matOldNonRotating = renderContext.WorldBaseNonRotating; - Matrix3d matOldBase = renderContext.WorldBase; - double oldNominalRadius = renderContext.NominalRadius; - - foreach (LayerMap map in mapList) - { - if (map.Frame.Reference != ReferenceFrames.Custom && map.Frame.Reference != ReferenceFrames.Sandbox) - { - - Planets.SetupPlanetMatrix(renderContext, (int)Enums.Parse("SolarSystemObjects", map.Frame.Name), Vector3d.Empty, false); - } - else - { - map.ComputeFrame(renderContext); - if (map.Frame.useRotatingParentFrame()) - { - renderContext.World = Matrix3d.MultiplyMatrix(map.Frame.WorldMatrix, renderContext.World); - } - else - { - renderContext.World = Matrix3d.MultiplyMatrix(map.Frame.WorldMatrix, renderContext.WorldBaseNonRotating); - - } - if (map.Frame.ReferenceFrameType == ReferenceFrameTypes.Synodic) - { - renderContext.WorldBaseNonRotating = renderContext.World.Clone(); - } - - renderContext.NominalRadius = map.Frame.MeanRadius; - } - } - - targetPoint = renderContext.World.Transform(targetPoint); - - Vector3d lookAt = renderContext.World.Transform(Vector3d.Create(0, 0, 1)); - - Vector3d lookUp = Vector3d.SubtractVectors(renderContext.World.Transform(Vector3d.Create(0, 1, 0)), targetPoint); - - - lookUp.Normalize(); - - - target.Matrix = Matrix3d.LookAtLH(new Vector3d(), Vector3d.SubtractVectors(lookAt, targetPoint), lookUp); - - - renderContext.NominalRadius = oldNominalRadius; - renderContext.World = matOld; - renderContext.WorldBaseNonRotating = matOldNonRotating; - renderContext.WorldBase = matOldBase; - - - - target.Target = targetPoint; - return target; - } - - internal static void PrepTourLayers() - { - if (TourPlayer.Playing) - { - TourPlayer player = (TourPlayer)WWTControl.Singleton.uiController; - if (player != null) - { - TourDocument tour = player.Tour; - - if (tour.CurrentTourStop != null) - { - player.UpdateTweenPosition(-1); - - - if (!tour.CurrentTourStop.KeyFramed) - { - tour.CurrentTourStop.UpdateLayerOpacity(); - foreach (Guid key in tour.CurrentTourStop.Layers.Keys) - { - LayerInfo info = tour.CurrentTourStop.Layers[key]; - - if (LayerList.ContainsKey(info.ID)) - { - LayerList[info.ID].Opacity = info.FrameOpacity; - LayerList[info.ID].SetParams(info.FrameParams); - } - } - } - } - } - } - } - - - internal static void Draw(RenderContext renderContext, float opacity, bool astronomical, string referenceFrame, bool nested, bool cosmos) - { - - - if (!AllMaps.ContainsKey(referenceFrame)) - { - return; - } - - - - LayerMap thisMap = AllMaps[referenceFrame]; - - if (!thisMap.Enabled || (thisMap.ChildMaps.Count == 0 && thisMap.Layers.Count == 0 && !(thisMap.Frame.ShowAsPoint || thisMap.Frame.ShowOrbitPath))) - { - return; - } - if (TourPlayer.Playing) - { - TourPlayer player = (TourPlayer)WWTControl.Singleton.uiController; - if (player != null) - { - TourDocument tour = player.Tour; - if (tour.CurrentTourStop != null) - { - player.UpdateTweenPosition(-1); - tour.CurrentTourStop.UpdateLayerOpacity(); - - foreach (Guid key in tour.CurrentTourStop.Layers.Keys) - { - LayerInfo info = tour.CurrentTourStop.Layers[key]; - - if (LayerList.ContainsKey(info.ID)) - { - LayerList[info.ID].Opacity = info.FrameOpacity; - LayerList[info.ID].SetParams(info.FrameParams); - } - } - } - } - } - - Matrix3d matOld = renderContext.World; - Matrix3d matOldNonRotating = renderContext.WorldBaseNonRotating; - double oldNominalRadius = renderContext.NominalRadius; - if (thisMap.Frame.Reference == ReferenceFrames.Custom | thisMap.Frame.Reference == ReferenceFrames.Custom) - { - thisMap.ComputeFrame(renderContext); - if (thisMap.Frame.ReferenceFrameType != ReferenceFrameTypes.Orbital && thisMap.Frame.ReferenceFrameType != ReferenceFrameTypes.Trajectory) - //if (true) - { - renderContext.World = Matrix3d.MultiplyMatrix(thisMap.Frame.WorldMatrix, renderContext.World); - } - else - { - renderContext.World = Matrix3d.MultiplyMatrix(thisMap.Frame.WorldMatrix, renderContext.WorldBaseNonRotating); - - } - renderContext.NominalRadius = thisMap.Frame.MeanRadius; - } - - - - if (thisMap.Frame.ShowAsPoint) - { - - // todo Draw point planet... - // Planets.DrawPointPlanet(renderContext.Device, new Vector3d(0, 0, 0), (float).2, thisMap.Frame.RepresentativeColor, true); - - } - - - - for (int pass = 0; pass < 2; pass++) - { - foreach (Layer layer in AllMaps[referenceFrame].Layers) - { - if ((pass == 0 && layer is ImageSetLayer) || (pass == 1 && !(layer is ImageSetLayer))) - { - bool skipLayer = false; - if (pass == 0) - { - // Skip default image set layer so that it's not drawn twice - skipLayer = !astronomical && ((ImageSetLayer)layer).OverrideDefaultLayer; - } - - if (layer.Enabled && !skipLayer) // && astronomical == layer.Astronomical) - { - double layerStart = SpaceTimeController.UtcToJulian(layer.StartTime); - double layerEnd = SpaceTimeController.UtcToJulian(layer.EndTime); - double fadeIn = SpaceTimeController.UtcToJulian(layer.StartTime) - ((layer.FadeType == FadeType.FadeIn || layer.FadeType == FadeType.Both) ? (layer.FadeSpan / 864000000) : 0); - double fadeOut = SpaceTimeController.UtcToJulian(layer.EndTime) + ((layer.FadeType == FadeType.FadeOut || layer.FadeType == FadeType.Both) ? (layer.FadeSpan / 864000000) : 0); - - if (SpaceTimeController.JNow > fadeIn && SpaceTimeController.JNow < fadeOut) - { - float fadeOpacity = 1; - if (SpaceTimeController.JNow < layerStart) - { - fadeOpacity = (float)((SpaceTimeController.JNow - fadeIn) / (layer.FadeSpan / 864000000)); - } - - if (SpaceTimeController.JNow > layerEnd) - { - fadeOpacity = (float)((fadeOut - SpaceTimeController.JNow) / (layer.FadeSpan / 864000000)); - } - layer.Astronomical = astronomical; - - if (layer is SpreadSheetLayer) - { - SpreadSheetLayer tsl = layer as SpreadSheetLayer; - tsl.Draw(renderContext, opacity * fadeOpacity, cosmos); - } - else - { - layer.Draw(renderContext, opacity * fadeOpacity, cosmos); - } - } - } - } - } - } - if (nested) - { - foreach (string key in AllMaps[referenceFrame].ChildMaps.Keys) - { - LayerMap map = AllMaps[referenceFrame].ChildMaps[key]; - if (!(map is LayerMap)) - { - continue; - } - if (map.Enabled && map.Frame.ShowOrbitPath && Settings.Active.SolarSystemOrbits && Settings.Active.SolarSystemMinorOrbits) - { - if (map.Frame.ReferenceFrameType == ReferenceFrameTypes.Orbital) - { - if (map.Frame.Orbit == null) - { - map.Frame.Orbit = new Orbit(map.Frame.Elements, 360, map.Frame.RepresentativeColor, 1, (float)map.Parent.Frame.MeanRadius); - } - Matrix3d matSaved = renderContext.World; - renderContext.World = Matrix3d.MultiplyMatrix(thisMap.Frame.WorldMatrix, renderContext.WorldBaseNonRotating); - - map.Frame.Orbit.Draw3D(renderContext, 1f * .5f, Vector3d.Create(0, 0, 0)); - renderContext.World = matSaved; - } - else if (map.Frame.ReferenceFrameType == ReferenceFrameTypes.Trajectory) - { - //todo add trajectories back - //if (map.Frame.trajectoryLines == null) - //{ - // map.Frame.trajectoryLines = new LineList(renderContext.Device); - // map.Frame.trajectoryLines.ShowFarSide = true; - // map.Frame.trajectoryLines.UseNonRotatingFrame = true; - - // int count = map.Frame.Trajectory.Count - 1; - // for (int i = 0; i < count; i++) - // { - // Vector3d pos1 = map.Frame.Trajectory[i].Position; - // Vector3d pos2 = map.Frame.Trajectory[i + 1].Position; - // pos1.Multiply(1 / renderContext.NominalRadius); - // pos2.Multiply(1 / renderContext.NominalRadius); - // map.Frame.trajectoryLines.AddLine(pos1, pos2, map.Frame.RepresentativeColor, new Dates()); - // } - //} - //Matrix3D matSaved = renderContext.World; - //renderContext.World = thisMap.Frame.WorldMatrix * renderContext.WorldBaseNonRotating; - - //map.Frame.trajectoryLines.DrawLines(renderContext, Earth3d.MainWindow.showMinorOrbits.Opacity * .25f); - //renderContext.World = matSaved; - } - } - - if ((map.Frame.Reference == ReferenceFrames.Custom || map.Frame.Reference == ReferenceFrames.Identity)) - { - Draw(renderContext, opacity, astronomical, map.Name, nested, cosmos); - } - } - } - renderContext.NominalRadius = oldNominalRadius; - renderContext.World = matOld; - renderContext.WorldBaseNonRotating = matOldNonRotating; - } - - internal static Dictionary GetVisibleLayerList(Dictionary previous) - { - Dictionary list = new Dictionary(); - - foreach (Guid key in LayerList.Keys) - { - Layer layer = LayerList[key]; - if (layer.Enabled) - { - LayerInfo info = new LayerInfo(); - info.StartOpacity = info.EndOpacity = layer.Opacity; - info.ID = layer.ID; - info.StartParams = layer.GetParams(); - - - if (previous.ContainsKey(info.ID)) - { - info.EndOpacity = previous[info.ID].EndOpacity; - info.EndParams = previous[info.ID].EndParams; - } - else - { - info.EndParams = layer.GetParams(); - } - list[layer.ID] = info; - } - } - return list; - } - - public static void SetVisibleLayerList(Dictionary list) - { - foreach (Guid key in LayerList.Keys) - { - Layer layer = LayerList[key]; - layer.Enabled = list.ContainsKey(layer.ID); - try - { - if (layer.Enabled) - { - layer.Opacity = list[layer.ID].FrameOpacity; - layer.SetParams(list[layer.ID].FrameParams); - } - } - catch - { - } - } - //SyncLayerState(); - } - - //todo remove the stuff from draw that is redundant once predraw has run - internal static void PreDraw(RenderContext renderContext, float opacity, bool astronomical, string referenceFrame, bool nested) - { - - - if (!AllMaps.ContainsKey(referenceFrame)) - { - return; - } - - - - LayerMap thisMap = AllMaps[referenceFrame]; - - if (thisMap.ChildMaps.Count == 0 && thisMap.Layers.Count == 0) - { - return; - } - if (TourPlayer.Playing) - { - TourPlayer player = (TourPlayer)WWTControl.Singleton.uiController as TourPlayer; - if (player != null) - { - TourDocument tour = player.Tour; - if (tour.CurrentTourStop != null) - { - player.UpdateTweenPosition(-1); - tour.CurrentTourStop.UpdateLayerOpacity(); - foreach (Guid key in tour.CurrentTourStop.Layers.Keys) - { - LayerInfo info = tour.CurrentTourStop.Layers[key]; - if (LayerList.ContainsKey(info.ID)) - { - LayerList[info.ID].Opacity = info.FrameOpacity; - LayerList[info.ID].SetParams(info.FrameParams); - } - } - - } - } - } - - Matrix3d matOld = renderContext.World; - Matrix3d matOldNonRotating = renderContext.WorldBaseNonRotating; - double oldNominalRadius = renderContext.NominalRadius; - if (thisMap.Frame.Reference == ReferenceFrames.Custom) - { - thisMap.ComputeFrame(renderContext); - if (thisMap.Frame.ReferenceFrameType != ReferenceFrameTypes.Orbital) - //if (true) - { - renderContext.World = Matrix3d.MultiplyMatrix(thisMap.Frame.WorldMatrix, renderContext.World); - } - else - { - renderContext.World = Matrix3d.MultiplyMatrix(thisMap.Frame.WorldMatrix, renderContext.WorldBaseNonRotating); - - } - renderContext.NominalRadius = thisMap.Frame.MeanRadius; - } - - - - for (int pass = 0; pass < 2; pass++) - { - foreach (Layer layer in AllMaps[referenceFrame].Layers) - { - if ((pass == 0 && layer is ImageSetLayer) || (pass == 1 && !(layer is ImageSetLayer))) - { - if (layer.Enabled) // && astronomical == layer.Astronomical) - { - double layerStart = SpaceTimeController.UtcToJulian(layer.StartTime); - double layerEnd = SpaceTimeController.UtcToJulian(layer.EndTime); - double fadeIn = SpaceTimeController.UtcToJulian(layer.StartTime) - ((layer.FadeType == FadeType.FadeIn || layer.FadeType == FadeType.Both) ? (layer.FadeSpan / 864000000) : 0); - double fadeOut = SpaceTimeController.UtcToJulian(layer.EndTime) + ((layer.FadeType == FadeType.FadeOut || layer.FadeType == FadeType.Both) ? (layer.FadeSpan / 864000000) : 0); - - if (SpaceTimeController.JNow > fadeIn && SpaceTimeController.JNow < fadeOut) - { - float fadeOpacity = 1; - if (SpaceTimeController.JNow < layerStart) - { - fadeOpacity = (float)((SpaceTimeController.JNow - fadeIn) / (layer.FadeSpan / 864000000)); - } - - if (SpaceTimeController.JNow > layerEnd) - { - fadeOpacity = (float)((fadeOut - SpaceTimeController.JNow) / (layer.FadeSpan / 864000000)); - } - if (thisMap.Frame.Reference == ReferenceFrames.Sky) - { - layer.Astronomical = true; - } - layer.PreDraw(renderContext, opacity * fadeOpacity); - } - } - } - - } - } - if (nested) - { - foreach (string key in AllMaps[referenceFrame].ChildMaps.Keys) - { - LayerMap map = AllMaps[referenceFrame].ChildMaps[key]; - if ((map.Frame.Reference == ReferenceFrames.Custom || map.Frame.Reference == ReferenceFrames.Identity)) - { - PreDraw(renderContext, opacity, astronomical, map.Name, nested); - } - } - } - renderContext.NominalRadius = oldNominalRadius; - renderContext.World = matOld; - renderContext.WorldBaseNonRotating = matOldNonRotating; - } - - - - public static void Add(Layer layer, bool updateTree) - { - if (!LayerList.ContainsKey(layer.ID)) - { - if (AllMaps.ContainsKey(layer.ReferenceFrame)) - { - LayerList[layer.ID] = layer; - - AllMaps[layer.ReferenceFrame].Layers.Add(layer); - version++; - if (updateTree) - { - LoadTree(); - } - } - } - } - - static ContextMenuStrip contextMenu; - static object selectedLayer = null; - static Vector2d lastMenuClick = new Vector2d(); - - static public void layerSelectionChanged(object selected) - { - selectedLayer = selected; - - if (selectedLayer != null) - { - //if (selectedLayer as ITimeSeriesDescription != null) - //{ - // timeScrubber.Maximum = 1000; - // ITimeSeriesDescription iTimeSeries = layerTree.SelectedNode.Tag as ITimeSeriesDescription; - - // timeSeries.Checked = iTimeSeries.IsTimeSeries; - // if (iTimeSeries.SeriesStartTime.ToString("HH:mm:ss") == "00:00:00") - // { - // startDate.Text = iTimeSeries.SeriesStartTime.ToString("yyyy/MM/dd"); - // } - // else - // { - // startDate.Text = iTimeSeries.SeriesStartTime.ToString("yyyy/MM/dd HH:mm:ss"); - // } - - // if (iTimeSeries.SeriesEndTime.ToString("HH:mm:ss") == "00:00:00") - // { - // endDate.Text = iTimeSeries.SeriesEndTime.ToString("yyyy/MM/dd"); - // } - // else - // { - // endDate.Text = iTimeSeries.SeriesEndTime.ToString("yyyy/MM/dd HH:mm:ss"); - // } - - // return; - //} - //else - - if (selectedLayer is LayerMap) - { - LayerMap map = selectedLayer as LayerMap; - if (map != null) - { - CurrentMap = map.Name; - } - } - else - { - ImageSetLayer layer = selectedLayer as ImageSetLayer; - if (layer != null && layer.ImageSet.WcsImage is FitsImage) - { - //WWTControl.scriptInterface.SetTimeSlider("left", "0"); - //WWTControl.scriptInterface.SetTimeSlider("right", (layer.GetFitsImage().Depth - 1).ToString()); - //WWTControl.scriptInterface.SetTimeSlider("title", "Velocity"); - //Histogram.UpdateImage(layer, timeScrubber.Value); - //timeSeries.Checked = false; - //startDate.Text = "0"; - //timeScrubber.Maximum = layer.FitsImage.Depth - 1; - ////timeScrubber.Value = layer.FitsImage.min layer.FitsImage.lastBitmapZ; - //endDate.Text = timeScrubber.Maximum.ToString(); - return; - } - } - } - - //timeSeries.Checked = false; - - WWTControl.scriptInterface.SetTimeSlider("left", ""); - WWTControl.scriptInterface.SetTimeSlider("right", ""); - WWTControl.scriptInterface.SetTimeSlider("title", Language.GetLocalizedText(667, "Time Scrubber")); - } - - //Fits time slider not implemented for webgl engine (only Windows version) - static public void SetTimeSliderValue(double pos) - { - ImageSetLayer layer = selectedLayer as ImageSetLayer; - if (layer != null && layer.ImageSet.WcsImage is FitsImage) - { - //WWTControl.scriptInterface.SetTimeSlider("title", layer.GetFitsImage().GetZDescription()); - } - } - - static public void showLayerMenu(object selected, int x, int y) - { - lastMenuClick = Vector2d.Create(x, y); - selectedLayer = selected; - - if (selected is LayerMap) - { - CurrentMap = ((LayerMap)selected).Name; - } - else if (selected is Layer) - { - CurrentMap = ((Layer)selected).ReferenceFrame; - } - - - //if (layer is LayerMap) - //{ - - // contextMenu = new ContextMenuStrip(); - - // ToolStripMenuItem add = ToolStripMenuItem.Create(Language.GetLocalizedText(1291, "Scale/Histogram")); - - // ToolStripSeparator sep1 = new ToolStripSeparator(); - - // addGirdLayer.Click = addGirdLayer_Click; - - // contextMenu.Items.Add(scaleMenu); - - // contextMenu.Show(Vector2d.Create(x, y)); - //} - //else if (layer is ImageSetLayer) - //{ - // contextMenu = new ContextMenuStrip(); - - // ToolStripMenuItem scaleMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1291, "Scale/Histogram")); - - // ToolStripSeparator sep1 = new ToolStripSeparator(); - - // scaleMenu.Click = scaleMenu_click; - - // contextMenu.Items.Add(scaleMenu); - - // contextMenu.Show(Vector2d.Create(x, y)); - //} - - if (((selected is Layer) && !(selected is SkyOverlays))) - { - Layer selectedLayer = (Layer)selected; - - contextMenu = new ContextMenuStrip(); - ToolStripMenuItem renameMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(225, "Rename")); - ToolStripMenuItem Expand = ToolStripMenuItem.Create(Language.GetLocalizedText(981, "Expand")); - ToolStripMenuItem Collapse = ToolStripMenuItem.Create(Language.GetLocalizedText(982, "Collapse")); - ToolStripMenuItem copyMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(428, "Copy")); - ToolStripMenuItem deleteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(167, "Delete")); - ToolStripMenuItem saveMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(960, "Save...")); - ToolStripMenuItem publishMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(983, "Publish to Community...")); - ToolStripMenuItem colorMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(458, "Color/Opacity")); - ToolStripMenuItem opacityMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(305, "Opacity")); - - ToolStripMenuItem propertiesMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(20, "Properties")); - ToolStripMenuItem scaleMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1291, "Scale/Histogram")); - ToolStripMenuItem lifeTimeMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(683, "Lifetime")); - ToolStripSeparator spacer1 = new ToolStripSeparator(); - ToolStripMenuItem top = ToolStripMenuItem.Create(Language.GetLocalizedText(684, "Move to Top")); - ToolStripMenuItem up = ToolStripMenuItem.Create(Language.GetLocalizedText(685, "Move Up")); - ToolStripMenuItem down = ToolStripMenuItem.Create(Language.GetLocalizedText(686, "Move Down")); - ToolStripMenuItem bottom = ToolStripMenuItem.Create(Language.GetLocalizedText(687, "Move to Bottom")); - ToolStripMenuItem showViewer = ToolStripMenuItem.Create(Language.GetLocalizedText(957, "VO Table Viewer")); - - ToolStripSeparator spacer2 = new ToolStripSeparator(); - - - ToolStripMenuItem defaultImageset = ToolStripMenuItem.Create(Language.GetLocalizedText(1294, "Background Image Set")); - - - top.Click = top_Click; - up.Click = up_Click; - down.Click = down_Click; - bottom.Click = bottom_Click; - saveMenu.Click = saveMenu_Click; - publishMenu.Click = publishMenu_Click; - Expand.Click = Expand_Click; - Collapse.Click = Collapse_Click; - copyMenu.Click = copyMenu_Click; - colorMenu.Click = colorMenu_Click; - deleteMenu.Click = deleteMenu_Click; - renameMenu.Click = renameMenu_Click; - propertiesMenu.Click = propertiesMenu_Click; - scaleMenu.Click = scaleMenu_click; - - - defaultImageset.Click = defaultImageset_Click; - - - - - opacityMenu.Click = opacityMenu_Click; - lifeTimeMenu.Click = lifeTimeMenu_Click; - showViewer.Click = showViewer_Click; - contextMenu.Items.Add(renameMenu); - - if (!selectedLayer.Opened && selectedLayer.GetPrimaryUI() != null && selectedLayer.GetPrimaryUI().HasTreeViewNodes) - { - contextMenu.Items.Add(Expand); - - } - - if (selectedLayer.Opened) - { - contextMenu.Items.Add(Collapse); - } - - - if (selectedLayer.CanCopyToClipboard()) - { - //contextMenu.Items.Add(copyMenu); - } - - contextMenu.Items.Add(deleteMenu); - //contextMenu.Items.Add(saveMenu); - - //if (Earth3d.IsLoggedIn) - //{ - // contextMenu.Items.Add(publishMenu); - //} - - contextMenu.Items.Add(spacer2); - contextMenu.Items.Add(colorMenu); - //contextMenu.Items.Add(opacityMenu); - - // ToDo Should we have this only show up in layers under Identity Reference Frames? - //contextMenu.Items.Add(lifeTimeMenu); - - - if (selected is ImageSetLayer) - { - contextMenu.Items.Add(defaultImageset); - - ImageSetLayer isl = selected as ImageSetLayer; - defaultImageset.Checked = isl.OverrideDefaultLayer; - } - /*selected is Object3dLayer || selected is GroundOverlayLayer || selected is OrbitLayer */ - if (selected is SpreadSheetLayer || selected is GreatCirlceRouteLayer) - { - contextMenu.Items.Add(propertiesMenu); - } - - if (selected is VoTableLayer) - { - contextMenu.Items.Add(showViewer); - } - - if (selected is ImageSetLayer) - { - ImageSetLayer isl = selected as ImageSetLayer; - // if (isl.FitsImage != null) - { - contextMenu.Items.Add(scaleMenu); - } - } - - if (AllMaps[selectedLayer.ReferenceFrame].Layers.Count > 1) - { - contextMenu.Items.Add(spacer1); - contextMenu.Items.Add(top); - contextMenu.Items.Add(up); - contextMenu.Items.Add(down); - contextMenu.Items.Add(bottom); - } - - - contextMenu.Show(Vector2d.Create(x, y)); - } - else if (selected is LayerMap) - { - LayerMap map = selected as LayerMap; - bool sandbox = map.Frame.Reference.ToString() == "Sandbox"; - bool Dome = map.Frame.Name == "Dome"; - bool Sky = map.Frame.Name == "Sky"; - - if (Dome) - { - return; - } - contextMenu = new ContextMenuStrip(); - ToolStripMenuItem trackFrame = ToolStripMenuItem.Create(Language.GetLocalizedText(1298, "Track this frame")); - ToolStripMenuItem goTo = ToolStripMenuItem.Create(Language.GetLocalizedText(1299, "Fly Here")); - ToolStripMenuItem showOrbit = ToolStripMenuItem.Create("Show Orbit"); - ToolStripMenuItem newMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(674, "New Reference Frame")); - ToolStripMenuItem newLayerGroupMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(675, "New Layer Group")); - ToolStripMenuItem addMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(166, "Add")); - ToolStripMenuItem newLight = ToolStripMenuItem.Create("Add Light"); - ToolStripMenuItem addFeedMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(956, "Add OData/table feed as Layer")); - ToolStripMenuItem addWmsLayer = ToolStripMenuItem.Create(Language.GetLocalizedText(987, "New WMS Layer")); - ToolStripMenuItem addGridLayer = ToolStripMenuItem.Create(Language.GetLocalizedText(1300, "New Lat/Lng Grid")); - ToolStripMenuItem addGreatCircle = ToolStripMenuItem.Create(Language.GetLocalizedText(988, "New Great Circle")); - ToolStripMenuItem importTLE = ToolStripMenuItem.Create(Language.GetLocalizedText(989, "Import Orbital Elements")); - ToolStripMenuItem addMpc = ToolStripMenuItem.Create(Language.GetLocalizedText(1301, "Add Minor Planet")); - ToolStripMenuItem deleteFrameMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(167, "Delete")); - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(425, "Paste")); - ToolStripMenuItem addToTimeline = ToolStripMenuItem.Create(Language.GetLocalizedText(1290, "Add to Timeline")); - ToolStripMenuItem addKeyframe = ToolStripMenuItem.Create(Language.GetLocalizedText(1280, "Add Keyframe")); - - ToolStripMenuItem popertiesMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(20, "Properties")); - ToolStripMenuItem saveMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(990, "Save Layers")); - ToolStripMenuItem publishLayers = ToolStripMenuItem.Create(Language.GetLocalizedText(991, "Publish Layers to Community")); - ToolStripSeparator spacer1 = new ToolStripSeparator(); - ToolStripSeparator spacer0 = new ToolStripSeparator(); - ToolStripSeparator spacer2 = new ToolStripSeparator(); - ToolStripMenuItem asReferenceFrame = ToolStripMenuItem.Create("As Reference Frame"); - ToolStripMenuItem asOrbitalLines = ToolStripMenuItem.Create("As Orbital Line"); - - - trackFrame.Click = trackFrame_Click; - goTo.Click = goTo_Click; - asReferenceFrame.Click = addMpc_Click; - asOrbitalLines.Click = AsOrbitalLines_Click; - // Ad Sub Menus - addMpc.DropDownItems.Add(asReferenceFrame); - addMpc.DropDownItems.Add(asOrbitalLines); - - - - - addMenu.Click = addMenu_Click; - // newLight.Click = newLight_Click; - - newLayerGroupMenu.Click = newLayerGroupMenu_Click; - pasteMenu.Click = pasteLayer_Click; - newMenu.Click = newMenu_Click; - deleteFrameMenu.Click = deleteFrameMenu_Click; - popertiesMenu.Click = FramePropertiesMenu_Click; - // addWmsLayer.Click = addWmsLayer_Click; - // importTLE.Click = importTLE_Click; - addGreatCircle.Click = addGreatCircle_Click; - // saveMenu.Click = SaveLayers_Click; - // publishLayers.Click = publishLayers_Click; - addGridLayer.Click = addGirdLayer_Click; - - - ToolStripMenuItem convertToOrbit = ToolStripMenuItem.Create("Extract Orbit Layer"); - // convertToOrbit.Click = ConvertToOrbit_Click; - - - if (map.Frame.Reference != ReferenceFrames.Identity) - { - if (WWTControl.Singleton.SolarSystemMode | WWTControl.Singleton.SandboxMode) //&& Control.ModifierKeys == Keys.Control) - { - bool spacerNeeded = false; - if (map.Frame.Reference != ReferenceFrames.Custom && !WWTControl.Singleton.SandboxMode) - { - // fly to - if (!Sky) - { - //contextMenu.Items.Add(goTo); - //spacerNeeded = true; - } - - try - { - string name = map.Frame.Reference.ToString(); - if (name != "Sandbox") - { - SolarSystemObjects ssObj = (SolarSystemObjects)Enums.Parse("SolarSystemObjects", name); - int id = (int)ssObj; - - int bit = (int)Math.Pow(2, id); - - showOrbit.Checked = (Settings.Active.PlanetOrbitsFilter & bit) != 0; - showOrbit.Click = showOrbitPlanet_Click; - showOrbit.Tag = bit.ToString(); - } - } - catch - { - } - } - else - { - // track - if (!sandbox && !Sky) - { - contextMenu.Items.Add(trackFrame); - spacerNeeded = true; - } - showOrbit.Checked = map.Frame.ShowOrbitPath; - showOrbit.Click = showOrbit_Click; - } - - if (spacerNeeded) - { - contextMenu.Items.Add(spacer2); - } - - if (!Sky && !sandbox) - { - contextMenu.Items.Add(showOrbit); - - contextMenu.Items.Add(spacer0); - } - - if (map.Frame.Reference.ToString() == "Sandbox") - { - contextMenu.Items.Add(newLight); - } - } - - if (!Sky) - { - contextMenu.Items.Add(newMenu); - } - //contextMenu.Items.Add(newLayerGroupMenu); - - } - - //contextMenu.Items.Add(addMenu); - //contextMenu.Items.Add(addFeedMenu); - if (!Sky) - { - contextMenu.Items.Add(addGreatCircle); - contextMenu.Items.Add(addGridLayer); - } - - if ((map.Frame.Reference != ReferenceFrames.Identity && map.Frame.Name == "Sun") || - (map.Frame.Reference == ReferenceFrames.Identity && map.Parent != null && map.Parent.Frame.Name == "Sun")) - { - contextMenu.Items.Add(addMpc); - } - - if (map.Frame.Reference == ReferenceFrames.Custom && map.Frame.ReferenceFrameType == ReferenceFrameTypes.Orbital && map.Parent != null && map.Parent.Frame.Name == "Sun") - { - //contextMenu.Items.Add(convertToOrbit); - } - - - if (!Sky) - { - //contextMenu.Items.Add(addWmsLayer); - } - - - contextMenu.Items.Add(pasteMenu); - - - if (map.Frame.Reference == ReferenceFrames.Identity) - { - contextMenu.Items.Add(deleteFrameMenu); - } - - if (map.Frame.Reference == ReferenceFrames.Custom) - { - contextMenu.Items.Add(deleteFrameMenu); - - contextMenu.Items.Add(popertiesMenu); - - } - - //if (!Sky) - { - contextMenu.Items.Add(spacer1); - } - //contextMenu.Items.Add(saveMenu); - //if (Earth3d.IsLoggedIn) - //{ - // contextMenu.Items.Add(publishLayers); - //} - - - contextMenu.Show(Vector2d.Create(x, y)); - } - //else if (selectedLayer is LayerUITreeNode) - //{ - // LayerUITreeNode node = selectedLayer as LayerUITreeNode; - // contextMenu = new ContextMenuStrip(); - - // Layer layer = GetParentLayer(layerTree.SelectedNode); - - // if (layer != null) - // { - // LayerUI ui = layer.GetPrimaryUI(); - // List items = ui.GetNodeContextMenu(node); - - // if (items != null) - // { - // foreach (LayerUIMenuItem item in items) - // { - // ToolStripMenuItem menuItem = ToolStripMenuItem.Create(item.Name); - // menuItem.Tag = item; - // menuItem.Click = menuItem_Click; - // contextMenu.Items.Add(menuItem); - - // if (item.SubMenus != null) - // { - // foreach (LayerUIMenuItem subItem in item.SubMenus) - // { - // ToolStripMenuItem subMenuItem = ToolStripMenuItem.Create(subItem.Name); - // subMenuItem.Tag = subItem; - // subMenuItem.Click = menuItem_Click; - // menuItem.DropDownItems.Add(subMenuItem); - // } - // } - // } - // contextMenu.Show(Cursor.Position); - // } - - - // } - //} - } - - static void publishMenu_Click(object sender, EventArgs e) - { - - //if (Earth3d.IsLoggedIn) - //{ - - // Layer target = (Layer)selectedLayer; - - // string name = target.Name + ".wwtl"; - // string filename = Path.GetTempFileName(); - - // LayerContainer layers = new LayerContainer(); - // layers.SoloGuid = target.ID; - - // layers.SaveToFile(filename); - // layers.Dispose(); - // GC.SuppressFinalize(layers); - // EOCalls.InvokePublishFile(filename, name); - // File.Delete(filename); - - // Earth3d.RefreshCommunity(); - - //} - } - - static void addGirdLayer_Click(object sender, EventArgs e) - { - GridLayer layer = new GridLayer(); - - layer.Enabled = true; - layer.Name = "Lat-Lng Grid"; - LayerList[layer.ID] = layer; - layer.ReferenceFrame = currentMap; - - AllMaps[currentMap].Layers.Add(layer); - AllMaps[currentMap].Open = true; - version++; - LoadTree(); - - } - - static void trackFrame_Click(object sender, EventArgs e) - { - LayerMap target = (LayerMap)selectedLayer; - - WWTControl.Singleton.RenderContext.SolarSystemTrack = SolarSystemObjects.Custom; - WWTControl.Singleton.RenderContext.TrackingFrame = target.Name; - WWTControl.Singleton.RenderContext.ViewCamera.Zoom = WWTControl.Singleton.RenderContext.TargetCamera.Zoom = .000000001; - - - } - - static void goTo_Click(object sender, EventArgs e) - { - //LayerMap target = (LayerMap)selectedLayer; - - //IPlace place = Catalogs.FindCatalogObjectExact(target.Frame.Reference.ToString()); - //if (place != null) - //{ - // WWTControl.Singleton.GotoTarget(place, false, false, true); - //} - } - - static void saveMenu_Click(object sender, EventArgs e) - { - //Layer layer = (Layer)selectedLayer; - //SaveFileDialog saveDialog = new SaveFileDialog(); - //saveDialog.Filter = Language.GetLocalizedText(993, "WorldWide Telescope Layer File(*.wwtl)") + "|*.wwtl"; - //saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - //saveDialog.AddExtension = true; - //saveDialog.DefaultExt = ".wwtl"; - //saveDialog.FileName = layer.Name + ".wwtl"; - //if (saveDialog.ShowDialog() == DialogResult.OK) - //{ - // // Todo add dialog for dynamic content options. - // LayerContainer layers = new LayerContainer(); - // layers.SoloGuid = layer.ID; - // layers.SaveToFile(saveDialog.FileName); - // layers.Dispose(); - // GC.SuppressFinalize(layers); - //} - } - static void Expand_Click(object sender, EventArgs e) - { - //Layer selectedLayer = (Layer)selectedLayer; - //selectedLayer.Opened = true; - //LoadLayerChildren(selectedLayer, layerTree.SelectedNode); - //layerTree.SelectedNode.Expand(); - //version++; - } - - static void Collapse_Click(object sender, EventArgs e) - { - // selectedLayer.Opened = false; - //todo update UIO - } - - static void copyMenu_Click(object sender, EventArgs e) - { - if (selectedLayer != null && selectedLayer is Layer) - { - Layer node = (Layer)selectedLayer; - node.CopyToClipboard(); - } - } - - static void newLayerGroupMenu_Click(object sender, EventArgs e) - { - //bool badName = true; - //string name = Language.GetLocalizedText(676, "Enter Layer Group Name"); - //while (badName) - //{ - // SimpleInput input = new SimpleInput(name, Language.GetLocalizedText(238, "Name"), Language.GetLocalizedText(677, "Layer Group"), 100); - // if (input.ShowDialog() == DialogResult.OK) - // { - // name = input.ResultText; - // if (!AllMaps.ContainsKey(name)) - // { - // MakeLayerGroup(name); - // version++; - // badName = false; - // LoadTreeLocal(); - // } - // else - // { - // UiTools.ShowMessageBox(Language.GetLocalizedText(1374, "Choose a unique name"), Language.GetLocalizedText(676, "Enter Layer Group Name")); - // } - // } - // else - // { - // badName = false; - // } - //} - } - - - static private void ImportTLEFile(string filename) - { - //LayerMap target = (LayerMap)selectedLayer; - //ImportTLEFile(filename, target); - } - - static private void MakeLayerGroupNow(string name) - { - LayerMap target = (LayerMap)selectedLayer; - MakeLayerGroup(name, target); - } - - private static void MakeLayerGroup(string name, LayerMap target) - { - ReferenceFrame frame = new ReferenceFrame(); - frame.Name = name; - frame.Reference = ReferenceFrames.Identity; - LayerMap newMap = new LayerMap(frame.Name, ReferenceFrames.Identity); - newMap.Frame = frame; - newMap.Frame.SystemGenerated = false; - target.AddChild(newMap); - - newMap.Frame.Parent = target.Name; - AllMaps[frame.Name] = newMap; - version++; - } - - static void lifeTimeMenu_Click(object sender, EventArgs e) - { - //if (selectedLayer is Layer) - //{ - // LayerLifetimeProperties props = new LayerLifetimeProperties(); - // props.Target = (Layer)selectedLayer; - // if (props.ShowDialog() == DialogResult.OK) - // { - // // This might be moot - // props.Target.CleanUp(); - // } - //} - - } - - static void deleteFrameMenu_Click(object sender, EventArgs e) - { - //LayerMap target = (LayerMap)selectedLayer; - //if (UiTools.ShowMessageBox(Language.GetLocalizedText(678, "This will delete this reference frame and all nested reference frames and layers. Do you want to continue?"), Language.GetLocalizedText(680, "Delete Reference Frame"), MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes) - //{ - // PurgeLayerMapDeep(target, true); - // version++; - // LoadTreeLocal(); - //} - - - } - - static void FramePropertiesMenu_Click(object sender, EventArgs e) - { - LayerMap target = (LayerMap)selectedLayer; - LayerManager.ReferenceFramePropsDialog.Show(target.Frame, e); - - } - - - - static void newMenu_Click(object sender, EventArgs e) - { - ReferenceFrame frame = new ReferenceFrame(); - LayerManager.FrameWizardDialog.Show(frame, e); - } - - public static void referenceFrameWizardFinished(ReferenceFrame frame) - { - LayerMap target = (LayerMap)selectedLayer; - LayerMap newMap = new LayerMap(frame.Name, ReferenceFrames.Custom); - if (!AllMaps.ContainsKey(frame.Name)) - { - newMap.Frame = frame; - - target.AddChild(newMap); - newMap.Frame.Parent = target.Name; - AllMaps[frame.Name] = newMap; - version++; - LoadTree(); - } - } - - - public static bool PasteFromTle(string[] lines, ReferenceFrame frame) - { - - string line1 = ""; - string line2 = ""; - for (int i = 0; i < lines.Length; i++) - { - lines[i] = lines[i].Trim(); - if (lines[i].Length == 69 && ReferenceFrame.IsTLECheckSumGood(lines[i])) - { - if (line1.Length == 0 && lines[i].Substring(0, 1) == "1") - { - line1 = lines[i]; - } - if (line2.Length == 0 && lines[i].Substring(0, 1) == "2") - { - line2 = lines[i]; - } - } - } - - if (line1.Length == 69 && line2.Length == 69) - { - frame.FromTLE(line1, line2, 398600441800000); - return true; - - } - return false; - - } - - - static void opacityMenu_Click(object sender, EventArgs e) - { - //OpacityPopup popup = new OpacityPopup(); - //popup.Target = (Layer)selectedLayer; - //popup.Location = Cursor.Position; - //popup.StartPosition = FormStartPosition.Manual; - //popup.Show(); - - } - - static void defaultImageset_Click(object sender, EventArgs e) - { - ImageSetLayer isl = selectedLayer as ImageSetLayer; - isl.OverrideDefaultLayer = !isl.OverrideDefaultLayer; - } - - static void propertiesMenu_Click(object sender, EventArgs e) - { - - if (selectedLayer is SpreadSheetLayer) - { - SpreadSheetLayer target = (SpreadSheetLayer)selectedLayer; - DataVizWizardDialog.Show(target, e); - // DataWizard.ShowPropertiesSheet(target); - - // target.CleanUp(); - // LoadTree(); - } - //else if (selectedLayer is SpreadSheetLayer || selectedLayer is Object3dLayer) - //{ - // Object3dProperties props = new Object3dProperties(); - // props.layer = (Object3dLayer)selectedLayer; - // // props.ShowDialog(); - // props.Owner = Earth3d.MainWindow; - // props.Show(); - //} - //else if (selectedLayer is GroundOverlayLayer) - //{ - // GroundOverlayProperties props = new GroundOverlayProperties(); - // props.Overlay = ((GroundOverlayLayer)selectedLayer).Overlay; - // props.OverlayLayer = ((GroundOverlayLayer)selectedLayer); - // props.Owner = Earth3d.MainWindow; - // props.Show(); - //} - if (selectedLayer is GreatCirlceRouteLayer) - { - - GreatCircleDlg.Show((GreatCirlceRouteLayer)selectedLayer, new EventArgs()); - - } - } - - static void renameMenu_Click(object sender, EventArgs e) - { - Layer layer = (Layer)selectedLayer; - SimpleInput input = new SimpleInput(Language.GetLocalizedText(225, "Rename"), Language.GetLocalizedText(228, "New Name"), layer.Name, 32); - - input.Show(lastMenuClick, delegate () - { - if (!string.IsNullOrEmpty(input.Text)) - { - layer.Name = input.Text; - version++; - LoadTree(); - } - }); - - - } - - static void colorMenu_Click(object sender, EventArgs e) - { - Layer layer = (Layer)selectedLayer; - - ColorPicker picker = new ColorPicker(); - if (layer.Color != null) - { - picker.Color = layer.Color; - } - picker.CallBack = delegate - { - layer.Color = picker.Color; - }; - - picker.Show(e); - } - - static void addMenu_Click(object sender, EventArgs e) - { - //bool overridable = false; - //if ( selectedLayer is LayerMap) - //{ - // LayerMap map = selectedLayer as LayerMap; - // if (map.Frame.reference == ReferenceFrames.Custom) - // { - // overridable = true; - // } - //} - //Earth3d.LoadLayerFile(overridable); - - } - - - static void deleteMenu_Click(object sender, EventArgs e) - { - DeleteSelectedLayer(); - } - - static private void DeleteSelectedLayer() - { - if (selectedLayer != null && selectedLayer is Layer) - { - Layer node = (Layer)selectedLayer; - - LayerList.Remove(node.ID); - AllMaps[CurrentMap].Layers.Remove(node); - node.CleanUp(); - node.Version++; - LoadTree(); - version++; - } - } - - static public void scaleMenu_click(object sender, EventArgs e) - { - ImageSetLayer isl = selectedLayer as ImageSetLayer; - - if (isl != null) - { - Histogram hist = new Histogram(); - hist.image = isl.GetFitsImage(); - hist.layer = isl; - hist.Show(Vector2d.Create(200, 200)); - } - } - - static void showViewer_Click(object sender, EventArgs e) - { - if (selectedLayer is VoTableLayer) - { - VoTableLayer layer = selectedLayer as VoTableLayer; - WWTControl.scriptInterface.DisplayVoTableLayer(layer); - } - } - - static void bottom_Click(object sender, EventArgs e) - { - Layer layer = selectedLayer as Layer; - if (layer != null) - { - AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - AllMaps[layer.ReferenceFrame].Layers.Add(layer); - } - version++; - LoadTree(); - } - - static void down_Click(object sender, EventArgs e) - { - Layer layer = selectedLayer as Layer; - if (layer != null) - { - int index = AllMaps[layer.ReferenceFrame].Layers.LastIndexOf(layer); - if (index < (AllMaps[layer.ReferenceFrame].Layers.Count - 1)) - { - AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - AllMaps[layer.ReferenceFrame].Layers.Insert(index + 1, layer); - } - } - version++; - LoadTree(); - } - - static void up_Click(object sender, EventArgs e) - { - Layer layer = selectedLayer as Layer; - if (layer != null) - { - int index = AllMaps[layer.ReferenceFrame].Layers.LastIndexOf(layer); - if (index > 0) - { - AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - AllMaps[layer.ReferenceFrame].Layers.Insert(index - 1, layer); - } - } - version++; - LoadTree(); - } - - static void top_Click(object sender, EventArgs e) - { - Layer layer = selectedLayer as Layer; - if (layer != null) - { - AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - AllMaps[layer.ReferenceFrame].Layers.Insert(0, layer); - } - version++; - LoadTree(); - } - - - static void pasteLayer_Click(object sender, EventArgs e) - { - //ClipbaordDelegate clip = delegate (string clipText) - //{ - // CreateSpreadsheetLayer(CurrentMap, "Clipboard", clipText); - //}; - DataVizWizardDialog.Show(CurrentMap, e); - - //Navigator.Clipboard.ReadText().Then(clip); - - - //IDataObject dataObject = Clipboard.GetDataObject(); - //if (dataObject.GetDataPresent(DataFormats.UnicodeText)) - //{ - // string[] formats = dataObject.GetFormats(); - // object data = dataObject.GetData(DataFormats.UnicodeText); - // if (data is String) - // { - // string layerName = "Pasted Layer"; - - // SpreadSheetLayer layer = new SpreadSheetLayer((string)data, true); - // layer.Enabled = true; - // layer.Name = layerName; - - // if (DataWizard.ShowWizard(layer) == DialogResult.OK) - // { - // LayerList.Add(layer.ID, layer); - // layer.ReferenceFrame = CurrentMap; - // AllMaps[CurrentMap].Layers.Add(layer); - // AllMaps[CurrentMap].Open = true; - // version++; - // LoadTree(); - - // } - // } - //} - - } - public static SpreadSheetLayer CreateSpreadsheetLayer(string frame, string name, string data) - { - SpreadSheetLayer layer = new SpreadSheetLayer(); - layer.LoadFromString(data, false, false, false, true); - layer.Name = name; - LayerManager.AddSpreadsheetLayer(layer, frame); - return layer; - } - - public static void AddSpreadsheetLayer(SpreadSheetLayer layer, string frame) - { - layer.Enabled = true; - layer.ReferenceFrame = frame; - Add(layer, true); - } - - static void showOrbitPlanet_Click(object sender, EventArgs e) - { - try - { - int bit = int.Parse(((ToolStripMenuItem)sender).Tag.ToString()); - - // Flip the state - if ((Settings.GlobalSettings.PlanetOrbitsFilter & bit) == 0) - { - Settings.GlobalSettings.PlanetOrbitsFilter |= bit; - } - else - { - Settings.GlobalSettings.PlanetOrbitsFilter &= ~bit; - } - - } - catch - { - } - } - - static void showOrbit_Click(object sender, EventArgs e) - { - // Flip the state - LayerMap map = selectedLayer as LayerMap; - - map.Frame.ShowOrbitPath = !map.Frame.ShowOrbitPath; - } - - static void addGreatCircle_Click(object sender, EventArgs e) - { - AddGreatCircleLayer(); - } - - - static void addMpc_Click(object sender, EventArgs e) - { - LayerMap target = (LayerMap)selectedLayer; - SimpleInput input = new SimpleInput(Language.GetLocalizedText(1302, "Minor planet name or designation"), Language.GetLocalizedText(238, "Name"), "", 32); - bool retry = false; - do - { - if (input.ShowDialog() == DialogResult.OK) - { - if (target.ChildMaps.ContainsKey(input.Text)) - { - retry = true; - //UiTools.ShowMessageBox("That Name already exists"); - } - else - { - try - { - GetMpc(input.Text, target); - retry = false; - } - catch - { - retry = true; - // UiTools.ShowMessageBox(Language.GetLocalizedText(1303, "The designation was not found or the MPC service was unavailable")); - } - } - } - else - { - retry = false; - } - } while (retry); - return; - } - - static private void AsOrbitalLines_Click(object sender, EventArgs e) - { - LayerMap target = (LayerMap)selectedLayer; - SimpleInput input = new SimpleInput(Language.GetLocalizedText(1302, "Minor planet name or designation"), Language.GetLocalizedText(238, "Name"), "", 32); - - input.Show(Cursor.Position, delegate () - { - if (target.ChildMaps.ContainsKey(input.Text)) - { - - // UiTools.ShowMessageBox("That Name already exists"); - } - else - { - GetMpcAsTLE(input.Text, target); - } - }); - } - - static void GetMpcAsTLE(string id, LayerMap target) - { - WebFile file = new WebFile("https://www.minorplanetcenter.net/db_search/show_object?object_id=" + id); - - file.OnStateChange = delegate () - { - if (file.State != StateType.Received) - { - return; - } - - string data = file.GetText(); - - - int startform = data.IndexOf("show-orbit-button"); - - int lastForm = data.IndexOf("/form", startform); - - string formpart = data.Substring(startform, lastForm); - - string name = id; - - ReferenceFrame frame = new ReferenceFrame(); - - frame.Oblateness = 0; - frame.ShowOrbitPath = true; - frame.ShowAsPoint = true; - - frame.Epoch = SpaceTimeController.UtcToJulian(Date.Parse(GetValueByID(formpart, "epoch").Substring(0, 10))); - frame.SemiMajorAxis = double.Parse(GetValueByID(formpart, "a")) * UiTools.KilometersPerAu * 1000; - frame.ReferenceFrameType = ReferenceFrameTypes.Orbital; - frame.Inclination = double.Parse(GetValueByID(formpart, "incl")); - frame.LongitudeOfAscendingNode = double.Parse(GetValueByID(formpart, "node")); - frame.Eccentricity = double.Parse(GetValueByID(formpart, "e")); - frame.MeanAnomolyAtEpoch = double.Parse(GetValueByID(formpart, "m")); - frame.MeanDailyMotion = ELL.MeanMotionFromSemiMajorAxis(double.Parse(GetValueByID(formpart, "a"))); - frame.ArgumentOfPeriapsis = double.Parse(GetValueByID(formpart, "peri")); - frame.Scale = 1; - frame.SemiMajorAxisUnits = AltUnits.Meters; - frame.MeanRadius = 10; - frame.Oblateness = 0; - - String TLE = name + "\n" + frame.ToTLE(); - LoadOrbitsFile(id, TLE, target.Name); - - LoadTree(); - }; - file.Send(); - - } - - //string ConvertToTLE(LayerMap map) - //{ - - // LayerMap target = map.Parent; - - // ReferenceFrame frame = map.Frame; - // string name = frame.Name; - - // String TLE = name + "\n" + frame.ToTLE(); - - // String filename = Path.GetTempPath() + "\\" + name; - - // File.WriteAllText(filename, TLE); - - // LoadOrbitsFile(filename, target.Name); - - // LoadTree(); - - // return null; - //} - - - static void GetMpc(string id, LayerMap target) - { - - WebFile file = new WebFile("https://www.minorplanetcenter.net/db_search/show_object?object_id=" + id); - - file.OnStateChange = delegate () - { - string data = file.GetText(); - - - int startform = data.IndexOf("show-orbit-button"); - - int lastForm = data.IndexOf("/form", startform); - - string formpart = data.Substring(startform, lastForm); - - string name = id; - - LayerMap orbit = new LayerMap(name.Trim(), ReferenceFrames.Custom); - - - orbit.Frame.Oblateness = 0; - orbit.Frame.ShowOrbitPath = true; - orbit.Frame.ShowAsPoint = true; - - orbit.Frame.Epoch = SpaceTimeController.UtcToJulian(Date.Parse(GetValueByID(formpart, "epoch").Substring(0, 10))); - orbit.Frame.SemiMajorAxis = double.Parse(GetValueByID(formpart, "a")) * UiTools.KilometersPerAu * 1000; - orbit.Frame.ReferenceFrameType = ReferenceFrameTypes.Orbital; - orbit.Frame.Inclination = double.Parse(GetValueByID(formpart, "incl")); - orbit.Frame.LongitudeOfAscendingNode = double.Parse(GetValueByID(formpart, "node")); - orbit.Frame.Eccentricity = double.Parse(GetValueByID(formpart, "e")); - orbit.Frame.MeanAnomolyAtEpoch = double.Parse(GetValueByID(formpart, "m")); - orbit.Frame.MeanDailyMotion = ELL.MeanMotionFromSemiMajorAxis(double.Parse(GetValueByID(formpart, "a"))); - orbit.Frame.ArgumentOfPeriapsis = double.Parse(GetValueByID(formpart, "peri")); - orbit.Frame.Scale = 1; - orbit.Frame.SemiMajorAxisUnits = AltUnits.Meters; - orbit.Frame.MeanRadius = 10; - orbit.Frame.Oblateness = 0; - - if (!AllMaps[target.Name].ChildMaps.ContainsKey(name.Trim())) - { - AllMaps[target.Name].AddChild(orbit); - } - - AllMaps[orbit.Name] = orbit; - - orbit.Frame.Parent = target.Name; - - MakeLayerGroup("Minor Planet", orbit); - - LoadTree(); - }; - - } - - static string GetValueByID(string data, string id) - { - - int valStart = data.IndexOf("id=\"" + id + "\""); - valStart = data.IndexOf("value=", valStart) + 7; - int valEnd = data.IndexOf("\"", valStart); - return data.Substr(valStart, valEnd - valStart); - } - - private static void AddGreatCircleLayer() - { - - GreatCirlceRouteLayer layer = new GreatCirlceRouteLayer(); - CameraParameters camera = WWTControl.Singleton.RenderContext.ViewCamera; - layer.LatStart = camera.Lat; - layer.LatEnd = camera.Lat - 5; - layer.LngStart = camera.Lng; - layer.LngEnd = camera.Lng + 5; - layer.Width = 4; - layer.Enabled = true; - layer.Name = Language.GetLocalizedText(1144, "Great Circle Route"); - LayerList[layer.ID] = layer; - layer.ReferenceFrame = currentMap; - AllMaps[currentMap].Layers.Add(layer); - AllMaps[currentMap].Open = true; - version++; - LoadTree(); - - GreatCircleDlg.Show(layer, new EventArgs()); - - } - - internal static Layer LoadOrbitsFile(string name, string data, string currentMap) - { - OrbitLayer layer = new OrbitLayer(); - //todo fix this - layer.LoadString(data); - layer.Enabled = true; - layer.Name = name; - LayerList[layer.ID] = layer; - layer.ReferenceFrame = currentMap; - AllMaps[currentMap].Layers.Add(layer); - AllMaps[currentMap].Open = true; - version++; - LoadTree(); - return layer; - } - - - - } - public class LayerMap - { - public LayerMap(string name, ReferenceFrames reference) - { - Name = name; - Frame.Reference = reference; - double radius = 6371000; - - switch (reference) - { - case ReferenceFrames.Sky: - break; - case ReferenceFrames.Ecliptic: - break; - case ReferenceFrames.Galactic: - break; - case ReferenceFrames.Sun: - radius = 696000000; - break; - case ReferenceFrames.Mercury: - radius = 2439700; - break; - case ReferenceFrames.Venus: - radius = 6051800; - break; - case ReferenceFrames.Earth: - radius = 6371000; - break; - case ReferenceFrames.Mars: - radius = 3390000; - break; - case ReferenceFrames.Jupiter: - radius = 69911000; - break; - case ReferenceFrames.Saturn: - radius = 58232000; - break; - case ReferenceFrames.Uranus: - radius = 25362000; - break; - case ReferenceFrames.Neptune: - radius = 24622000; - break; - case ReferenceFrames.Pluto: - radius = 1161000; - break; - case ReferenceFrames.Moon: - radius = 1737100; - break; - case ReferenceFrames.Io: - radius = 1821500; - break; - case ReferenceFrames.Europa: - radius = 1561000; - break; - case ReferenceFrames.Ganymede: - radius = 2631200; - break; - case ReferenceFrames.Callisto: - radius = 2410300; - break; - case ReferenceFrames.Custom: - break; - case ReferenceFrames.Identity: - break; - default: - break; - } - Frame.MeanRadius = radius; - - } - public Dictionary ChildMaps = new Dictionary(); - public void AddChild(LayerMap child) - { - child.Parent = this; - ChildMaps[child.Name] = child; - } - - public LayerMap Parent = null; - public List Layers = new List(); - public bool Open = false; - public bool Enabled = true; - public bool LoadedFromTour = false; - public string Name - { - get { return Frame.Name; } - set { Frame.Name = value; } - } - - - public ReferenceFrame Frame = new ReferenceFrame(); - public void ComputeFrame(RenderContext renderContext) - { - if (Frame.Reference == ReferenceFrames.Custom) - { - Frame.ComputeFrame(renderContext); - - } - - } - - public override string ToString() - { - return Name; - } - - - } - //public enum ReferenceFrames { Earth = 0, Helocentric = 1, Equatorial = 2, Ecliptic = 3, Galactic = 4, Moon = 5, Mercury = 6, Venus = 7, Mars = 8, Jupiter = 9, Saturn = 10, Uranus = 11, Neptune = 12, Custom = 13 }; - - - public enum ReferenceFrames - { - Sky = 0, - Ecliptic = 1, - Galactic = 2, - Sun = 3, - Mercury = 4, - Venus = 5, - Earth = 6, - Mars = 7, - Jupiter = 8, - Saturn = 9, - Uranus = 10, - Neptune = 11, - Pluto = 12, - Moon = 13, - Io = 14, - Europa = 15, - Ganymede = 16, - Callisto = 17, - Custom = 18, - Identity = 19, - Sandbox = 20 - }; - - public class SkyOverlays - { - - } - - public class GroundOverlayLayer - { - } - - - public class FrameTarget - { - public Vector3d Target; - public Matrix3d Matrix; - } -} diff --git a/engine/csharp_ref/Layers/LayerUI.cs b/engine/csharp_ref/Layers/LayerUI.cs deleted file mode 100644 index 0cd0f0c7..00000000 --- a/engine/csharp_ref/Layers/LayerUI.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class LayerUI - { - static Type type = null; - - - - virtual public bool HasTreeViewNodes - { - get - { - return false; - } - } - - virtual public List GetTreeNodes() - { - return null; - } - - - virtual public List GetNodeContextMenu(LayerUITreeNode node) - { - return null; - } - - virtual public void SetUICallbacks( IUIServicesCallbacks callbacks) - { - } - } - - public interface IUIServicesCallbacks - { - void ShowRowData(Dictionary rowData); - } - - public delegate void MenuItemSelectedDelegate( LayerUIMenuItem item); - - public class LayerUIMenuItem - { - private String name; - - public String Name - { - get { return name; } - set { name = value; } - } - private object tag = null; - - public object Tag - { - get { return tag; } - set { tag = value; } - } - - private bool isChecked = false; - - public bool Checked - { - get { return isChecked; } - set { isChecked = value; } - } - - private bool isEnabled = true; - - public bool Enabled - { - get { return isEnabled; } - set { isEnabled = value; } - } - - - public event MenuItemSelectedDelegate MenuItemSelected; - - public void FireMenuItemSelected() - { - if (MenuItemSelected != null) - { - MenuItemSelected.Invoke(this); - } - } - - List subMenus = null; - public List SubMenus - { - get - { - if (subMenus == null) - { - subMenus = new List(); - } - return subMenus; - } - } - } - - public delegate void LayerUITreeNodeCheckedDelegate(LayerUITreeNode node, bool newState); - public delegate void LayerUITreeNodeUpdatedDelegate(LayerUITreeNode node); - public delegate void LayerUITreeNodeSelectedDelegate(LayerUITreeNode node); - public delegate void LayerUITreeNodeActivatedDelegate(LayerUITreeNode node); - - public class LayerUITreeNode - { - public event LayerUITreeNodeCheckedDelegate NodeChecked; - - public void FireNodeChecked(bool newState) - { - if (NodeChecked != null) - { - NodeChecked.Invoke(this, newState); - } - } - - public event LayerUITreeNodeUpdatedDelegate NodeUpdated; - - public void FireNodeUpdated() - { - if (NodeUpdated != null) - { - NodeUpdated.Invoke(this); - } - } - - public event LayerUITreeNodeSelectedDelegate NodeSelected; - - public void FireNodeSelected() - { - if (NodeSelected != null) - { - NodeSelected.Invoke(this); - } - } - public event LayerUITreeNodeActivatedDelegate NodeActivated; - - public void FireNodeActivated() - { - if (NodeActivated != null) - { - NodeActivated.Invoke(this); - } - } - - private String name; - - public String Name - { - get { return name; } - set - { - if (name != value) - { - name = value; - FireNodeUpdated(); - } - } - } - - private LayerUITreeNode parent = null; - - public LayerUITreeNode Parent - { - get { return parent; } - set { parent = value; } - } - - private int level = 0; - - public int Level - { - get { return level; } - set { level = value; } - } - - - private object tag; - - public object Tag - { - get { return tag; } - set { tag = value; } - } - - private object referenceTag; - - public object ReferenceTag - { - get { return referenceTag; } - set { referenceTag = value; } - } - - private bool open; - - public bool Opened - { - get { return open; } - set - { - if (open != value) - { - open = value; - FireNodeUpdated(); - } - } - } - private bool isChecked; - - public bool Checked - { - get { return isChecked; } - set - { - if (isChecked != value) - { - isChecked = value; - FireNodeUpdated(); - } - } - } - - private bool bold = false; - - public bool Bold - { - get { return bold; } - set - { - if (bold != value) - { - bold = value; - FireNodeUpdated(); - } - } - } - private Color color = Colors.White; - - public Color Color - { - get { return color; } - set - { - if (color != value) - { - color = value; - FireNodeUpdated(); - } - } - } - - - public LayerUITreeNode Add(string name) - { - LayerUITreeNode node = new LayerUITreeNode(); - node.Name = name; - node.Parent = this; - node.Level = this.Level + 1; - Nodes.Add(node); - return node; - } - - List nodes = null; - public List Nodes - { - get - { - if (nodes == null) - { - nodes = new List(); - } - return nodes; - } - } - } -} diff --git a/engine/csharp_ref/Layers/Object3d.cs b/engine/csharp_ref/Layers/Object3d.cs deleted file mode 100644 index ece17e7f..00000000 --- a/engine/csharp_ref/Layers/Object3d.cs +++ /dev/null @@ -1,3739 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Data.Files; - -namespace wwtlib -{ - enum Draging { None = 0, X = 1, Y = 2, Z = 3, HP = 4, PR = 5, RH = 6, HP1 = 7, PR1 = 8, RH1 = 9, Scale = 10 }; - public class Object3dLayer : Layer, IUiController - { - - Object3dLayerUI primaryUI = null; - public override LayerUI GetPrimaryUI() - { - if (primaryUI == null) - { - primaryUI = new Object3dLayerUI(this); - } - - return primaryUI; - } - - - public Object3d object3d; - - double heading = 0; - bool flipV = true; - - // //[LayerProperty] - public bool FlipV - { - get { return flipV; } - set - { - if (flipV != value) - { - flipV = value; - if (object3d != null) - { - object3d.FlipV = flipV; - object3d.Reload(); - } - version++; - } - } - } - - bool flipHandedness = false; - - //[LayerProperty] - public bool FlipHandedness - { - get { return flipHandedness; } - set - { - if (flipHandedness != value) - { - flipHandedness = value; - if (object3d != null) - { - object3d.FlipHandedness = flipHandedness; - object3d.Reload(); - } - version++; - } - } - } - - - - - bool smooth = true; - - //[LayerProperty] - public bool Smooth - { - get { return smooth; } - set - { - if (smooth != value) - { - smooth = value; - if (object3d != null) - { - object3d.Smooth = smooth; - object3d.Reload(); - } - version++; - } - } - } - - bool twoSidedGeometry = false; - - //[LayerProperty] - public bool TwoSidedGeometry - { - get { return twoSidedGeometry; } - set - { - if (twoSidedGeometry != value) - { - twoSidedGeometry = value; - version++; - } - } - } - - //[LayerProperty] - public double Heading - { - get { return heading; } - set - { - if (heading != value) - { - version++; - heading = value; - } - } - } - double pitch = 0; - - //[LayerProperty] - public double Pitch - { - get { return pitch; } - set - { - if (pitch != value) - { - version++; - pitch = value; - } - } - } - double roll = 0; - - //[LayerProperty] - public double Roll - { - get { return roll; } - set - { - if (roll != value) - { - version++; - roll = value; - } - } - } - Vector3d scale = Vector3d.Create(1, 1, 1); - - //[LayerProperty] - public Vector3d Scale - { - get { return scale; } - set - { - if (scale != value) - { - version++; - scale = value; - } - } - } - Vector3d translate = Vector3d.Create(0, 0, 0); - - //[LayerProperty] - public Vector3d Translate - { - get { return translate; } - set - { - if (translate != value) - { - version++; - translate = value; - } - } - } - - - public Object3dLayer() - { - } - - int lightID = 0; - - //[LayerProperty] - public int LightID - { - get { return lightID; } - set { lightID = value; } - } - - - - bool dirty = false; - public override void CleanUp() - { - //if (object3d != null) - //{ - // object3d.Dispose(); - //} - //object3d = null; - dirty = true; - } - - public override void ColorChanged() - { - if (object3d != null) - { - object3d.Color = Color; - //object3d.Reload(); - } - } - - public bool ObjType = false; - - public override void WriteLayerProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteAttributeString("FlipV", FlipV.ToString()); - xmlWriter.WriteAttributeString("FlipHandedness", FlipHandedness.ToString()); - xmlWriter.WriteAttributeString("Smooth", Smooth.ToString()); - xmlWriter.WriteAttributeString("TwoSidedGeometry", TwoSidedGeometry.ToString()); - xmlWriter.WriteAttributeString("Heading", Heading.ToString()); - xmlWriter.WriteAttributeString("Pitch", Pitch.ToString()); - xmlWriter.WriteAttributeString("Roll", Roll.ToString()); - xmlWriter.WriteAttributeString("Scale", Scale.ToString()); - xmlWriter.WriteAttributeString("Translate", Translate.ToString()); - xmlWriter.WriteAttributeString("LightID", LightID.ToString()); - xmlWriter.WriteAttributeString("Obj", ObjType.ToString()); - - } - - public override double[] GetParams() - { - double[] paramList = new double[14]; - paramList[0] = heading; - paramList[1] = pitch; - paramList[2] = roll; - paramList[3] = scale.X; - paramList[4] = scale.Y; - paramList[5] = scale.Z; - paramList[6] = translate.X; - paramList[7] = translate.Y; - paramList[8] = translate.Z; - paramList[9] = Color.R / 255; - paramList[10] = Color.G / 255; - paramList[11] = Color.B / 255; - paramList[12] = Color.A / 255; - paramList[13] = Opacity; - - return paramList; - } - - public override string[] GetParamNames() - { - return new string[] { "Heading", "Pitch", "Roll", "Scale.X", "Scale.Y", "Scale.Z", "Translate.X", "Translate.Y", "Translate.Z", "Colors.Red", "Colors.Green", "Colors.Blue", "Colors.Alpha", "Opacity" }; - } - - //public override BaseTweenType[] GetParamTypes() - //{ - // return new BaseTweenType[] { BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Power, BaseTweenType.Power, BaseTweenType.Power, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear }; - //} - - public override void SetParams(double[] paramList) - { - if (paramList.Length == 14) - { - heading = paramList[0]; - pitch = paramList[1]; - roll = paramList[2]; - scale.X = paramList[3]; - scale.Y = paramList[4]; - scale.Z = paramList[5]; - translate.X = paramList[6]; - translate.Y = paramList[7]; - translate.Z = paramList[8]; - - Opacity = (float)paramList[13]; - Color color = Color.FromArgb((int)(paramList[12] * 255), (int)(paramList[9] * 255), (int)(paramList[10] * 255), (int)(paramList[11] * 255)); - Color = color; - - } - - } - - public event EventHandler PropertiesChanged; - - public void FireChanged() - { - if (PropertiesChanged != null) - { - PropertiesChanged.Invoke(this, new EventArgs()); - } - } - - public override object GetEditUI() - { - return this as IUiController; - } - - public override void InitializeFromXml(XmlNode node) - { - FlipV = Boolean.Parse(node.Attributes.GetNamedItem("FlipV").Value); - - if (node.Attributes.GetNamedItem("FlipHandedness") != null) - { - FlipHandedness = Boolean.Parse(node.Attributes.GetNamedItem("FlipHandedness").Value); - } - else - { - FlipHandedness = false; - } - - if (node.Attributes.GetNamedItem("Smooth") != null) - { - Smooth = Boolean.Parse(node.Attributes.GetNamedItem("Smooth").Value); - } - else - { - Smooth = true; - } - - if (node.Attributes.GetNamedItem("TwoSidedGeometry") != null) - { - TwoSidedGeometry = Boolean.Parse(node.Attributes.GetNamedItem("TwoSidedGeometry").Value); - } - else - { - TwoSidedGeometry = false; - } - - if (node.Attributes.GetNamedItem("Obj") != null) - { - ObjType = Boolean.Parse(node.Attributes.GetNamedItem("Obj").Value); - } - else - { - ObjType = false; - } - - Heading = double.Parse(node.Attributes.GetNamedItem("Heading").Value); - Pitch = double.Parse(node.Attributes.GetNamedItem("Pitch").Value); - Roll = double.Parse(node.Attributes.GetNamedItem("Roll").Value); - Scale = Vector3d.Parse(node.Attributes.GetNamedItem("Scale").Value); - Translate = Vector3d.Parse(node.Attributes.GetNamedItem("Translate").Value); - - if (node.Attributes.GetNamedItem("LightID") != null) - { - LightID = int.Parse(node.Attributes.GetNamedItem("LightID").Value); - } - } - - static TriangleList TranslateUI = null; - static LineList TranslateUILines = null; - - static TriangleList ScaleUI = null; - - //public static SimpleLineList11 sketch = null; - static void InitTranslateUI() - { - TranslateUILines = new LineList(); - TranslateUILines.TimeSeries = false; - TranslateUILines.DepthBuffered = false; - TranslateUILines.ShowFarSide = true; - - TranslateUI = new TriangleList(); - TranslateUI.DepthBuffered = false; - TranslateUI.TimeSeries = false; - TranslateUI.WriteZbuffer = false; - - double twoPi = Math.PI * 2; - double step = twoPi / 45; - double rad = .05; - - // X - - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(1 - rad * 4, 0, 0); - Vector3d pnt2 = Vector3d.Create(1 - rad * 4, Math.Cos(a) * rad, Math.Sin(a) * rad); - Vector3d pnt3 = Vector3d.Create(1 - rad * 4, Math.Cos(a + step) * rad, Math.Sin(a + step) * rad); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Colors.Red, Dates.Empty()); - } - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(1, 0, 0); - Vector3d pnt3 = Vector3d.Create(1 - rad * 4, Math.Cos(a) * rad, Math.Sin(a) * rad); - Vector3d pnt2 = Vector3d.Create(1 - rad * 4, Math.Cos(a + step) * rad, Math.Sin(a + step) * rad); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Color.FromArgb(255, 255, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - } - - TranslateUILines.AddLine(Vector3d.Create(0, 0, 0), Vector3d.Create(1, 0, 0), Colors.Red, Dates.Empty()); - - // Y - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(0, 1 - rad * 4, 0); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a) * rad, 1 - rad * 4, Math.Sin(a) * rad); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a + step) * rad, 1 - rad * 4, Math.Sin(a + step) * rad); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Colors.Green, Dates.Empty()); - } - - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(0, 1, 0); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a) * rad, 1 - rad * 4, Math.Sin(a) * rad); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step) * rad, 1 - rad * 4, Math.Sin(a + step) * rad); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Color.FromArgb(255, Math.Max(0, (int)(Math.Sin(a) * 128)), 255, Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - } - - TranslateUILines.AddLine(Vector3d.Create(0, 0, 0), Vector3d.Create(0, 1, 0), Colors.Green, Dates.Empty()); - - // Z - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(0, 0, 1 - rad * 4); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a) * rad, Math.Sin(a) * rad, 1 - rad * 4); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step) * rad, Math.Sin(a + step) * rad, 1 - rad * 4); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Colors.Blue, Dates.Empty()); - } - - for (double a = 0; a < twoPi; a += step) - { - Vector3d pnt1 = Vector3d.Create(0, 0, 1); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a) * rad, Math.Sin(a) * rad, 1 - rad * 4); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a + step) * rad, Math.Sin(a + step) * rad, 1 - rad * 4); - TranslateUI.AddTriangle(pnt1, pnt2, pnt3, Color.FromArgb(255, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128)), 255), Dates.Empty()); - } - - TranslateUILines.AddLine(Vector3d.Create(0, 0, 0), Vector3d.Create(0, 0, 1), Colors.Blue, Dates.Empty()); - InitRotateUI(); - InitScaleUI(); - } - - static void InitScaleUI() - { - ScaleUI = new TriangleList(); - ScaleUI.DepthBuffered = false; - ScaleUI.TimeSeries = false; - ScaleUI.WriteZbuffer = false; - - double twoPi = Math.PI * 2; - double step = twoPi / 45; - double rad = .05; - - // X - - MakeCube(ScaleUI, Vector3d.Create(1 - rad * 2, 0, 0), rad * 2, Colors.Red); - MakeCube(ScaleUI, Vector3d.Create(0, 1 - rad * 2, 0), rad * 2, Colors.Green); - MakeCube(ScaleUI, Vector3d.Create(0, 0, 1 - rad * 2), rad * 2, Colors.Blue); - - } - - static void MakeCube(TriangleList tl, Vector3d center, double size, Color color) - { - - Color dark = Color.FromArgb(255, (int)(color.R * .6), (color.G), (int)(color.B * .6)); - Color med = Color.FromArgb(255, (int)(color.R * .8), (int)(color.G * .8), (int)(color.B * .8)); - - - tl.AddQuad( - Vector3d.Create(center.X + size, center.Y + size, center.Z + size), - Vector3d.Create(center.X + size, center.Y + size, center.Z - size), - Vector3d.Create(center.X - size, center.Y + size, center.Z + size), - Vector3d.Create(center.X - size, center.Y + size, center.Z - size), - color, Dates.Empty()); - - tl.AddQuad( - Vector3d.Create(center.X + size, center.Y - size, center.Z + size), - Vector3d.Create(center.X - size, center.Y - size, center.Z + size), - Vector3d.Create(center.X + size, center.Y - size, center.Z - size), - Vector3d.Create(center.X - size, center.Y - size, center.Z - size), - color, Dates.Empty()); - - - tl.AddQuad( - Vector3d.Create(center.X - size, center.Y + size, center.Z + size), - Vector3d.Create(center.X - size, center.Y + size, center.Z - size), - Vector3d.Create(center.X - size, center.Y - size, center.Z + size), - Vector3d.Create(center.X - size, center.Y - size, center.Z - size), - dark, Dates.Empty()); - - tl.AddQuad( - Vector3d.Create(center.X + size, center.Y + size, center.Z + size), - Vector3d.Create(center.X + size, center.Y - size, center.Z + size), - Vector3d.Create(center.X + size, center.Y + size, center.Z - size), - Vector3d.Create(center.X + size, center.Y - size, center.Z - size), - dark, Dates.Empty()); - - tl.AddQuad( - Vector3d.Create(center.X + size, center.Y + size, center.Z + size), - Vector3d.Create(center.X - size, center.Y + size, center.Z + size), - Vector3d.Create(center.X + size, center.Y - size, center.Z + size), - Vector3d.Create(center.X - size, center.Y - size, center.Z + size), - med, Dates.Empty()); - - tl.AddQuad( - Vector3d.Create(center.X + size, center.Y + size, center.Z - size), - Vector3d.Create(center.X + size, center.Y - size, center.Z - size), - Vector3d.Create(center.X - size, center.Y + size, center.Z - size), - Vector3d.Create(center.X - size, center.Y - size, center.Z - size), - med, Dates.Empty()); - - } - - static TriangleList RotateUi = null; - - static void InitRotateUI() - { - RotateUi = new TriangleList(); - RotateUi.DepthBuffered = false; - RotateUi.TimeSeries = false; - RotateUi.WriteZbuffer = false; - - double twoPi = Math.PI * 2; - double step = twoPi / 40; - double rad = .05; - int index = 0; - - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(rad * (start ? 0 : (end ? 1.5 : 1)), Math.Cos(a), Math.Sin(a)); - Vector3d pnt2 = Vector3d.Create(-rad * (start ? 0 : (end ? 1.5 : 1)), Math.Cos(a), Math.Sin(a)); - Vector3d pnt3 = Vector3d.Create(rad * (start ? 1.5 : (end ? 0 : 1)), Math.Cos(a + step), Math.Sin(a + step)); - Vector3d pnt4 = Vector3d.Create(-rad * (start ? 1.5 : (end ? 0 : 1)), Math.Cos(a + step), Math.Sin(a + step)); - RotateUi.AddQuad(pnt1, pnt3, pnt2, pnt4, Color.FromArgbColor(192, Colors.Red), Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,192, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - - index = 0; - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(Math.Cos(a), Math.Sin(a), rad * (start ? 0 : (end ? 1.5 : 1))); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a), Math.Sin(a), -rad * (start ? 0 : (end ? 1.5 : 1))); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step), Math.Sin(a + step), rad * (start ? 1.5 : (end ? 0 : 1))); - Vector3d pnt4 = Vector3d.Create(Math.Cos(a + step), Math.Sin(a + step), -rad * (start ? 1.5 : (end ? 0 : 1))); - RotateUi.AddQuad(pnt1, pnt3, pnt2, pnt4, Color.FromArgbColor(192, Colors.Blue), Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,192, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - - index = 0; - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(Math.Cos(a), rad * (start ? 0 : (end ? 1.5 : 1)), Math.Sin(a)); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a), -rad * (start ? 0 : (end ? 1.5 : 1)), Math.Sin(a)); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step), rad * (start ? 1.5 : (end ? 0 : 1)), Math.Sin(a + step)); - Vector3d pnt4 = Vector3d.Create(Math.Cos(a + step), -rad * (start ? 1.5 : (end ? 0 : 1)), Math.Sin(a + step)); - RotateUi.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgbColor(192, Colors.Green), Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,192, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - - // X - index = 0; - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(-rad * (start ? 0 : (end ? 1.5 : 1)), Math.Cos(a), Math.Sin(a)); - Vector3d pnt2 = Vector3d.Create(rad * (start ? 0 : (end ? 1.5 : 1)), Math.Cos(a), Math.Sin(a)); - Vector3d pnt3 = Vector3d.Create(-rad * (start ? 1.5 : (end ? 0 : 1)), Math.Cos(a + step), Math.Sin(a + step)); - Vector3d pnt4 = Vector3d.Create(rad * (start ? 1.5 : (end ? 0 : 1)), Math.Cos(a + step), Math.Sin(a + step)); - RotateUi.AddQuad(pnt1, pnt3, pnt2, pnt4, Colors.Red, Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,255, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - - - - //Y - index = 0; - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(Math.Cos(a), Math.Sin(a), -rad * (start ? 0 : (end ? 1.5 : 1))); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a), Math.Sin(a), rad * (start ? 0 : (end ? 1.5 : 1))); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step), Math.Sin(a + step), -rad * (start ? 1.5 : (end ? 0 : 1))); - Vector3d pnt4 = Vector3d.Create(Math.Cos(a + step), Math.Sin(a + step), rad * (start ? 1.5 : (end ? 0 : 1))); - RotateUi.AddQuad(pnt1, pnt3, pnt2, pnt4, Colors.Blue, Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,255, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - - - - //Z - index = 0; - for (double a = 0; a < twoPi; a += step) - { - bool start = (index % 10) == 0; - bool end = ((index + 1) % 10) == 0; - Vector3d pnt1 = Vector3d.Create(Math.Cos(a), -rad * (start ? 0 : (end ? 1.5 : 1)), Math.Sin(a)); - Vector3d pnt2 = Vector3d.Create(Math.Cos(a), rad * (start ? 0 : (end ? 1.5 : 1)), Math.Sin(a)); - Vector3d pnt3 = Vector3d.Create(Math.Cos(a + step), -rad * (start ? 1.5 : (end ? 0 : 1)), Math.Sin(a + step)); - Vector3d pnt4 = Vector3d.Create(Math.Cos(a + step), rad * (start ? 1.5 : (end ? 0 : 1)), Math.Sin(a + step)); - RotateUi.AddQuad(pnt1, pnt2, pnt3, pnt4, Colors.Green, Dates.Empty()); - //TranslateUI.AddQuad(pnt1, pnt2, pnt3, pnt4, Color.FromArgb(255,255, Math.Max(0, (int)(Math.Sin(a) * 128)), Math.Max(0, (int)(Math.Sin(a) * 128))), Dates.Empty()); - index++; - } - } - - - Vector2d xHandle = new Vector2d(); - Vector2d yHandle = new Vector2d(); - Vector2d zHandle = new Vector2d(); - - Vector2d[] hprHandles = new Vector2d[6]; - - double uiScale = 1; - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - Matrix3d oldWorld = renderContext.World; - Matrix3d rotation = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.RotationZ(-roll / 180f * Math.PI), Matrix3d.RotationX(-pitch / 180f * Math.PI)), Matrix3d.RotationY(heading / 180f * Math.PI)); - - renderContext.World = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(rotation, Matrix3d.Scaling(scale.X, scale.Y, scale.Z)), Matrix3d.Translation(translate)), oldWorld); - renderContext.TwoSidedLighting = TwoSidedGeometry; - //todo renderContext.setRasterizerState(TwoSidedGeometry ? TriangleCullMode.Off : TriangleCullMode.CullCounterClockwise); - - Planets.DrawPointPlanet(renderContext, new Vector3d(), 1.0, Colors.Red, false); - if (lightID > 0) - { - //draw light - - // Planets.DrawPointPlanet(renderContext, Vector3d.Create(), 1, Color, false, 1.0f); - } - else - { - if (object3d != null) - { - object3d.Color = Color; - object3d.Render(renderContext, opacity * Opacity); - } - } - //todo renderContext.setRasterizerState(TriangleCullMode.CullCounterClockwise); - renderContext.TwoSidedLighting = false; - - - //todo enable edit UI - - //if (showEditUi) - //{ - // if (lightID > 0) - // { - // //draw light - - // Planets.DrawPointPlanet(renderContext, new Vector3d(), 1, Color, false, 1.0f); - // } - - // DepthStencilMode oldDepthMode = renderContext.DepthStencilMode = DepthStencilMode.Off; - // renderContext.World = Matrix3d.Translation(translate) * oldWorld; - - // Matrix3d wvp = renderContext.World * renderContext.View * renderContext.Projection; - - // Vector3d vc = Vector3d.Create(0, 0, 0); - // Vector3d vc1 = Vector3d.Create(.001, 0, 0); - // Vector3d vc2 = Vector3d.Create(0, .001, 0); - // Vector3d vc3 = Vector3d.Create(0, 0, .001); - // Vector3d vs = Vector3d.TransformCoordinate(vc, wvp); - // Vector3d vs1 = Vector3d.TransformCoordinate(vc1, wvp); - // Vector3d vs2 = Vector3d.TransformCoordinate(vc2, wvp); - // Vector3d vs3 = Vector3d.TransformCoordinate(vc3, wvp); - - // Vector2d vsa = Vector2d.Create(vs.X, vs.Y); - // Vector2d vsa1 = Vector2d.Subtract(Vector2d.Create(vs1.X, vs1.Y),vsa); - // Vector2d vsa2 = Vector2d.Subtract(Vector2d.Create(vs2.X, vs2.Y),vsa); - // Vector2d vsa3 = Vector2d.Subtract(Vector2d.Create(vs3.X, vs3.Y),vsa); - - // uiScale = .0003 / Math.Sqrt((vsa1.Length * vsa1.Length + vsa2.Length * vsa2.Length + vsa3.Length * vsa3.Length)); - - // Matrix3d matUIScale = Matrix3d.Scaling(uiScale, uiScale, uiScale); - - // renderContext.World = matUIScale * renderContext.World; - - // wvp = renderContext.World * renderContext.View * renderContext.Projection; - - - // vc1 = Vector3d.Create(.9, 0, 0); - // vc2 = Vector3d.Create(0, .9, 0); - // vc3 = Vector3d.Create(0, 0, .9); - // vs = Vector3d.TransformCoordinate(vc, wvp); - // vs1 = Vector3d.TransformCoordinate(vc1, wvp); - // vs2 = Vector3d.TransformCoordinate(vc2, wvp); - // vs3 = Vector3d.TransformCoordinate(vc3, wvp); - - // double h = renderContext.ViewPort.Height; - // double w = renderContext.ViewPort.Width; - - // xHandle = Vector2d.Create((vs1.X + 1) * w / 2, h - ((vs1.Y + 1) * h / 2)); - // yHandle = Vector2d.Create((vs2.X + 1) * w / 2, h - ((vs2.Y + 1) * h / 2)); - // zHandle = Vector2d.Create((vs3.X + 1) * w / 2, h - ((vs3.Y + 1) * h / 2)); - - - // // draw UI - // if (TranslateUI == null) - // { - // InitTranslateUI(); - - // } - - // bool showTranslate = Control.ModifierKeys != Keys.Control && Control.ModifierKeys != Keys.Shift; - // bool showRotate = Control.ModifierKeys == Keys.Control; - // bool showScale = Control.ModifierKeys == Keys.Shift; - - // if (showTranslate) - // { - // TranslateUILines.DrawLines(renderContext, 1.0f); - - // TranslateUI.Draw(renderContext, 1.0f, TriangleList.CullMode.Clockwise); - // } - // else - // { - // if (showScale) - // { - // TranslateUILines.DrawLines(renderContext, 1.0f); - // ScaleUI.Draw(renderContext, 1.0f, TriangleList.CullMode.Clockwise); - // } - // else - // { - // xHandle = Vector2d.Create(-1000, 0); - // yHandle = Vector2d.Create(-1000, 0); - // zHandle = Vector2d.Create(-1000, 0); - // } - // } - - // renderContext.World = rotation * renderContext.World; - - // if (showRotate) - // { - // wvp = renderContext.World * renderContext.View * renderContext.Projection; - - // Vector3d[] hprPoints = new Vector3d[] - // { - // Vector3d.Create(0,0,1), - // Vector3d.Create(0,0,-1), - // Vector3d.Create(0,1,0), - // Vector3d.Create(0,-1,0), - // Vector3d.Create(-1,0,0), - // Vector3d.Create(1,0,0) - // }; - // hprHandles = new Vector2d[6]; - // for (int i = 0; i < 6; i++) - // { - // Vector3d vt = Vector3d.TransformCoordinate(hprPoints[i], wvp); - // hprHandles[i] = Vector2d.Create((vt.X + 1) * w / 2, h - ((vt.Y + 1) * h / 2)); - // } - - // RotateUi.Draw(renderContext, 1.0f, TriangleList.CullMode.Clockwise); - // } - // else - // { - // hprHandles = new Vector2d[0]; - // } - - - - - // oldDepthMode = renderContext.DepthStencilMode = oldDepthMode; - - // //restore matrix - // renderContext.World = oldWorld; - // showEditUi = false; - //} - renderContext.World = oldWorld; - - return true; - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - // Add files to cabinet - //if (object3d != null) - //{ - // string fName = object3d.Filename; - - // bool copy = true; - // //bool copy = !fName.Contains(ID.ToString()); - // string ext = ObjType ? "obj" : "3ds"; - // string fileName = fc.TempDirectory + string.Format("{0}\\{1}.{2}", fc.PackageID, this.ID.ToString(), ext); - // string path = fName.Substring(0, fName.LastIndexOf('\\') + 1); - // string path2 = fileName.Substring(0, fileName.LastIndexOf('\\') + 1); - - // if (copy) - // { - // if (!Directory.Exists(path2)) - // { - // Directory.CreateDirectory(path2); - // } - // if (File.Exists(fName) && !File.Exists(fileName)) - // { - // File.Copy(fName, fileName); - // } - - // foreach (string meshfile in object3d.meshFilenames) - // { - // if (!String.IsNullOrEmpty(meshfile)) - // { - // string textureFilename = fc.TempDirectory + string.Format("{0}\\{1}", fc.PackageID, meshfile); - // string mFilename = path + "\\" + meshfile; - // string newfilename = Object3d.FindFile(mFilename); - // if (string.IsNullOrEmpty(newfilename)) - // { - // newfilename = Object3d.FindFileFuzzy(mFilename); - // } - - - - // if (File.Exists(newfilename) && !File.Exists(textureFilename)) - // { - // File.Copy(newfilename, textureFilename); - // } - // } - // } - // } - - // if (File.Exists(fileName)) - // { - // fc.AddFile(fileName); - // } - - // foreach (string meshfile in object3d.meshFilenames) - // { - // if (!string.IsNullOrEmpty(meshfile)) - // { - // string textureFilename = fc.TempDirectory + string.Format("{0}\\{1}", fc.PackageID, meshfile); - // fc.AddFile(textureFilename); - // } - // } - //} - } - - public override void LoadData(TourDocument doc, string filename) - { - // ObjType = true; - - if (filename.ToLowerCase().EndsWith(".obj")) - { - ObjType = true; - } - - if (lightID == 0) - { - if (ObjType) - { - object3d = new Object3d(doc, filename.Replace(".txt", ".obj"), FlipV, flipHandedness, true, Color); - } - else - { - object3d = new Object3d(doc, filename.Replace(".txt", ".3ds"), FlipV, flipHandedness, true, Color); - } - } - } - - public Vector2d PointToView(Vector2d pnt) - { - double clientHeight = WWTControl.Singleton.RenderContext.Height; - double clientWidth = WWTControl.Singleton.RenderContext.Width; - double viewWidth = (WWTControl.Singleton.RenderContext.Width / WWTControl.Singleton.RenderContext.Height) * 1116f; - double x = (((double)pnt.X) / ((double)clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - double y = ((double)pnt.Y) / clientHeight * 1116; - - return Vector2d.Create(x, y); - } - - public void Render(RenderContext renderEngine) - { - showEditUi = true; - return; - } - bool showEditUi = false; - public void PreRender(RenderContext renderEngine) - { - showEditUi = true; - return; - } - - - - Draging dragMode = Draging.None; - - Vector2d pntDown = new Vector2d(); - double valueOnDown = 0; - double valueOnDown2 = 0; - - double hitDist = 20; - - public bool MouseDown(object sender, ElementEvent e) - { - Vector2d location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - - pntDown = location; - - Vector2d pnt = location; - - if (e.ShiftKey) - { - if ((Vector2d.Subtract(pnt, xHandle)).Length < hitDist) - { - dragMode = Draging.Scale; - valueOnDown = this.scale.X; - return true; - } - - if ((Vector2d.Subtract(pnt, yHandle)).Length < hitDist) - { - dragMode = Draging.Scale; - valueOnDown = this.scale.Y; - return true; - } - - if ((Vector2d.Subtract(pnt, zHandle)).Length < hitDist) - { - dragMode = Draging.Scale; - valueOnDown = this.scale.Z; - return true; - } - } - else - { - if ((Vector2d.Subtract(pnt, xHandle)).Length < hitDist) - { - dragMode = Draging.X; - valueOnDown = this.translate.X; - return true; - } - - if ((Vector2d.Subtract(pnt, yHandle)).Length < hitDist) - { - dragMode = Draging.Y; - valueOnDown = this.translate.Y; - return true; - } - - if ((Vector2d.Subtract(pnt, zHandle)).Length < hitDist) - { - dragMode = Draging.Z; - valueOnDown = this.translate.Z; - return true; - } - } - - for (int i = 0; i < hprHandles.Length; i++) - { - if ((Vector2d.Subtract(pnt, hprHandles[i])).Length < hitDist) - { - switch (i) - { - case 0: - dragMode = Draging.HP; - valueOnDown = this.heading; - valueOnDown2 = this.pitch; - return true; - case 1: - dragMode = Draging.HP1; - valueOnDown = this.heading; - valueOnDown2 = this.pitch; - return true; - case 2: - dragMode = Draging.PR; - valueOnDown = this.pitch; - valueOnDown2 = this.roll; - return true; - case 3: - dragMode = Draging.PR1; - valueOnDown = this.pitch; - valueOnDown2 = this.roll; - return true; - case 4: - dragMode = Draging.RH; - valueOnDown = this.roll; - valueOnDown2 = this.heading; - return true; - case 5: - dragMode = Draging.RH1; - valueOnDown = this.roll; - valueOnDown2 = this.heading; - return true; - default: - break; - } - } - } - - return false; - } - - public bool MouseUp(object sender, ElementEvent e) - { - if (dragMode != Draging.None) - { - dragMode = Draging.None; - lockPreferedAxis = false; - return true; - } - return false; - } - - bool lockPreferedAxis = false; - bool preferY = false; - - public bool MouseMove(object sender, ElementEvent e) - { - - Vector2d location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - - if (dragMode != Draging.None) - { - double dist = 0; - double distX = location.X - pntDown.X; - double distY = -(location.Y - pntDown.Y); - - if (lockPreferedAxis) - { - if (preferY) - { - dist = distY; - preferY = true; - Cursor.Current = Cursors.SizeNS; - } - else - { - dist = distX; - preferY = false; - Cursor.Current = Cursors.SizeWE; - } - } - else - { - if (Math.Abs(distX) > Math.Abs(distY)) - { - dist = distX; - preferY = false; - } - else - { - dist = distY; - preferY = true; - } - if (dist > 5) - { - lockPreferedAxis = true; - } - } - - switch (dragMode) - { - case Draging.None: - break; - case Draging.X: - this.translate.X = valueOnDown + (12 * uiScale * (dist / WWTControl.Singleton.RenderContext.Width)); - break; - case Draging.Y: - this.translate.Y = valueOnDown + (12 * uiScale * (dist / WWTControl.Singleton.RenderContext.Width)); - break; - case Draging.Z: - this.translate.Z = valueOnDown + (12 * uiScale * (dist / WWTControl.Singleton.RenderContext.Width)); - break; - case Draging.HP: - this.heading = valueOnDown - distX / 4; - this.pitch = valueOnDown2 + distY / 4; - break; - case Draging.PR: - this.pitch = valueOnDown + distY / 4; - this.roll = valueOnDown2 - distX / 4; - break; - case Draging.RH: - this.roll = valueOnDown + distY / 4; - this.heading = valueOnDown2 - distX / 4; - break; - case Draging.HP1: - this.heading = valueOnDown - distX / 4; - this.pitch = valueOnDown2 - distY / 4; - break; - case Draging.PR1: - this.pitch = valueOnDown + distY / 4; - this.roll = valueOnDown2 + distX / 4; - break; - case Draging.RH1: - this.roll = valueOnDown - distY / 4; - this.heading = valueOnDown2 - distX / 4; - break; - case Draging.Scale: - this.scale.X = this.scale.Y = this.scale.Z = valueOnDown * Math.Pow(2, (dist / 100)); - break; - default: - break; - } - FireChanged(); - return true; - } - else - { - Vector2d pnt = location; - - - if ((Vector2d.Subtract(pnt, xHandle)).Length < hitDist) - { - Cursor.Current = Cursors.SizeAll; - return true; - } - - if ((Vector2d.Subtract(pnt, yHandle)).Length < hitDist) - { - Cursor.Current = Cursors.SizeAll; - return true; - } - - if ((Vector2d.Subtract(pnt, zHandle)).Length < hitDist) - { - Cursor.Current = Cursors.SizeAll; - return true; - } - - for (int i = 0; i < hprHandles.Length; i++) - { - if ((Vector2d.Subtract(pnt, hprHandles[i])).Length < hitDist) - { - Cursor.Current = Cursors.SizeAll; - return true; - } - } - } - - return false; - } - - public bool MouseClick(object sender, ElementEvent e) - { - - - return false; - } - - public bool Click(object sender, ElementEvent e) - { - return false; - } - - public bool MouseDoubleClick(object sender, ElementEvent e) - { - return false; - } - - public bool KeyDown(object sender, ElementEvent e) - { - return false; - } - - public bool KeyUp(object sender, ElementEvent e) - { - return false; - } - - public bool Hover(Vector2d pnt) - { - return false; - } - } - - public class Group - { - public int startIndex; - public int indexCount; - public int materialIndex; - } - - public class Mesh : IDisposable - { - public void Dispose() - { - if (vertexBuffer != null) - { - vertexBuffer.Dispose(); - vertexBuffer = null; - } - - if (tangentVertexBuffer != null) - { - tangentVertexBuffer.Dispose(); - tangentVertexBuffer = null; - } - - if (indexBuffer != null) - { - indexBuffer.Dispose(); - indexBuffer = null; - } - } - - public Mesh() - { - - } - - public static Mesh Create(PositionNormalTextured[] vertices, int[] indices) - { - Mesh mesh = new Mesh(); - mesh.vertices = vertices; - mesh.indices = indices; - - Vector3d[] points = new Vector3d[vertices.Length]; - for (int i = 0; i < vertices.Length; ++i) - points[i] = vertices[i].Position; - mesh.BoundingSphere = ConvexHull.FindEnclosingSphereFast(points); - return mesh; - } - - //public Mesh(PositionNormalTextured[] vertices, int[] indices) - //{ - // this.vertices = vertices; - - // this.indices = new uint[indices.Length]; - // for (int c = 0; c < indices.Length; c++) - // { - // this.indices[c] = (uint)indices[c]; - // } - - // Vector3d[] points = new Vector3d[vertices.Length]; - // for (int i = 0; i < vertices.Length; ++i) - // points[i] = vertices[i].Position; - // boundingSphere = ConvexHull.FindEnclosingSphere(points); - //} - - // Create a mesh from vertices with tangents, for use with a normal map - public static Mesh CreateTangent(PositionNormalTexturedTangent[] vertices, int[] indices) - { - Mesh mesh = new Mesh(); - - mesh.tangentVertices = vertices; - mesh.indices = indices; - - Vector3d[] points = new Vector3d[mesh.tangentVertices.Length]; - for (int i = 0; i < mesh.tangentVertices.Length; ++i) - points[i] = mesh.tangentVertices[i].Position; - mesh.BoundingSphere = ConvexHull.FindEnclosingSphereFast(points); - - return mesh; - } - - //public void setMaterialGroups(Group[] groups) - //{ - // attributeGroups = groups; - //} - - public void setObjects(List objects) - { - this.objects = objects; - } - - // Convert the vertex data to a GPU vertex buffer - public void commitToDevice() - { - if (vertices != null) - { - vertexBuffer = PositionNormalTexturedVertexBuffer.Create(vertices); - } - else if (tangentVertices != null) - { - tangentVertexBuffer = PositionNormalTexturedTangentVertexBuffer.Create(tangentVertices); - } - - indexBuffer = new IndexBuffer(new Uint32Array((object)indices)); - } - - public void beginDrawing(RenderContext renderContext) - { - if (vertexBuffer != null) - { - renderContext.SetVertexBuffer(vertexBuffer); - } - else if (tangentVertexBuffer != null) - { - renderContext.SetVertexBuffer(tangentVertexBuffer); - } - - if (indexBuffer != null) - { - renderContext.SetIndexBuffer(indexBuffer); - } - - // SharpDX.Direct3D11.DeviceContext devContext = renderContext.Device.ImmediateContext; - // devContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; - } - - public void drawSubset(RenderContext renderContext, int materialIndex) - { - if (indexBuffer == null || objects == null) - { - return; - } - - //var vertexLayout = PlanetShader.StandardVertexLayout.PositionNormalTex; - //if (tangentVertexBuffer != null) - //{ - // vertexLayout = PlanetShader.StandardVertexLayout.PositionNormalTexTangent; - //} - - //SharpDX.Direct3D11.DeviceContext devContext = renderContext.Device.ImmediateContext; - //devContext.InputAssembler.InputLayout = renderContext.Shader.inputLayout(vertexLayout); - - - DrawHierarchy(objects, materialIndex, renderContext, 0); - } - - public void DrawHierarchy(List nodes, int materialIndex, RenderContext renderContext, int depth) - { - if (depth > 1212) - { - return; - } - foreach (ObjectNode node in nodes) - { - if (node.DrawGroup != null && node.Enabled) - { - foreach (Group group in node.DrawGroup) - { - if (group.materialIndex == materialIndex) - { - - renderContext.gl.drawElements(GL.TRIANGLES, group.indexCount, GL.UNSIGNED_INT, group.startIndex*4); - } - } - } - DrawHierarchy(node.Children, materialIndex, renderContext, depth + 1); - } - } - - public PositionNormalTexturedVertexBuffer vertexBuffer; - public PositionNormalTexturedTangentVertexBuffer tangentVertexBuffer; - public IndexBuffer indexBuffer; - - // Only one of these two will be non-null - public PositionNormalTextured[] vertices; - public PositionNormalTexturedTangent[] tangentVertices; - public int[] indices; - - public SphereHull BoundingSphere = new SphereHull(); - - //Group[] attributeGroups; - List objects; - - public List Objects - { - get { return objects; } - set { objects = value; } - } - } - - - - - class VertexPosition - { - public Vector3d position; - public uint index; - }; - - public class Object3d - { - public bool FlipHandedness = false; - public bool FlipV = true; - public bool Smooth = true; - public string Filename; - Mesh mesh = null; // Our mesh object in sysmem - List meshMaterials = new List(); // Materials for our mesh - List meshTextures = new List(); // Textures for our mesh - List meshSpecularTextures = new List(); // Specular textures for our mesh - List meshNormalMaps = new List(); // Normal maps for our mesh - public List meshFilenames = new List(); // filenames for meshes - - public Color Color = Colors.White; - - - //public static Object3d LoadFromModelFileFromUrl(string url) - //{ - // int hash = url.GetHashCode(); - - // Object3d model = null; - - // string path = Properties.Settings.Default.CahceDirectory + @"mdl\" + hash.ToString() + @"\"; - // string filename = path + hash + ".mdl"; - // if (!Directory.Exists(path)) - // { - // Directory.CreateDirectory(path); - // } - - // if (!File.Exists(filename)) - // { - // DataSetManager.DownloadFile(url, filename, false, true); - // } - // string objFile = ""; - - // using (Stream s = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) - // { - // ZipArchive zip = new ZipArchive(s); - // foreach (ZipEntry zFile in zip.Files) - // { - // Stream output = File.Open(path + zFile.Filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None); - // Stream input = zFile.GetFileStream(); - // CopyStream(input, output); - // input.Close(); - // output.Close(); - // input.Dispose(); - // output.Dispose(); - // if (zFile.Filename.ToLower().EndsWith(".obj")) - // { - // objFile = path + zFile.Filename; - // } - // } - // } - - // if (File.Exists(objFile)) - // { - // Object3d o3d = new Object3d(objFile, true, false, true, Colors.White); - // if (o3d != null) - // { - // model = o3d; - // } - // } - - // return model; - //} - - //public static void CopyStream(Stream input, Stream output) - //{ - // byte[] buffer = new byte[8192]; - // int len; - // while ((len = input.Read(buffer, 0, buffer.Length)) > 0) - // { - // output.Write(buffer, 0, len); - // } - //} - - public Object3d(TourDocument tourDoc, string filename, bool flipV, bool flipHandedness, bool smooth, Color color) - { - Color = color; - Smooth = smooth; - FlipV = flipV; - FlipHandedness = flipHandedness; - Filename = filename; - if (Filename.ToLowerCase().EndsWith(".obj")) - { - LoadMeshFromObj(tourDoc,Filename); - } - else - { - LoadMeshFrom3ds(tourDoc, Filename, 1.0f); - } - } - - internal void Reload() - { - if (!ISSLayer) - { - Dispose(); - if (Filename.ToLowerCase().EndsWith(".obj")) - { - LoadMeshFromObj(tourDocument, Filename); - } - - else - { - LoadMeshFrom3ds(tourDocument, Filename, 1.0f); - } - } - } - - private static int CompareVector3(Vector3d v0, Vector3d v1) - { - if (v0.X < v1.X) - { - return -1; - } - else if (v0.X > v1.X) - { - return 1; - } - else if (v0.Y < v1.Y) - { - return -1; - } - else if (v0.Y > v1.Y) - { - return 1; - } - else if (v0.Z < v1.Z) - { - return -1; - } - else if (v0.Z > v1.Z) - { - return 1; - } - else - { - return 0; - } - } - - private static int CompareVector(Vector2d v0, Vector2d v1) - { - if (v0.X < v1.X) - { - return -1; - } - else if (v0.X > v1.X) - { - return 1; - } - else if (v0.Y < v1.Y) - { - return -1; - } - else if (v0.Y > v1.Y) - { - return 1; - } - else - { - return 0; - } - } - - - // Calculate per-vertex normals by averaging face normals. Normals of adjacent faces with an - // angle of greater than crease angle are not included in the average. CalculateVertexNormalsMerged - // is slower than the other normal generation method, CalculateVertexNormals, but it produces better - // results. Vertices with identical positions (bot possibly different texture coordinates) are treated - // as the same vertex for purposes of normal calculation. This allows smooth normals across texture - // wrap seams. - // - // This method returns an array of vertex normals, one for each index in the index list - private Vector3d[] CalculateVertexNormalsMerged(List vertexList, List indexList, double creaseAngleRad) - { - if (vertexList.Count == 0) - { - return null; - } - - int vertexCount = vertexList.Count; - int triangleCount = Math.Floor(indexList.Count / 3); - - // Create a list of vertices sorted by their positions. This will be used to - // produce a list of vertices with unique positions. - List vertexPositions = new List(); - for (int vertexIndex = 0; vertexIndex < vertexList.Count; ++vertexIndex) - { - VertexPosition vp = new VertexPosition(); - //todo11 this should be native.. - vp.position = vertexList[vertexIndex].Position; - vp.index = (uint)vertexIndex; - vertexPositions.Add(vp); - } - - vertexPositions.Sort(delegate (VertexPosition v0, VertexPosition v1) { return CompareVector3(v0.position, v1.position); }); - // vertexMap will map a vertex index to the index of a vertex with a unique position - int[] vertexMap = new int[vertexPositions.Count]; - int uniqueVertexCount = 0; - for (int vertexIndex = 0; vertexIndex < vertexPositions.Count; vertexIndex++) - { - if (vertexIndex == 0 || CompareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position) != 0) - { - ++uniqueVertexCount; - } - vertexMap[vertexPositions[vertexIndex].index] = uniqueVertexCount - 1; - } - - int[] vertexInstanceCounts = new int[uniqueVertexCount]; - for(int i=0; i< uniqueVertexCount; i++ ) - { - vertexInstanceCounts[i] = 0; - } - - foreach (int vertexIndex in indexList) - { - int uniqueIndex = vertexMap[vertexIndex]; - vertexInstanceCounts[uniqueIndex]++; - } - - // vertexInstances contains the list of faces each vertex is referenced in - int[][] vertexInstances = new int[uniqueVertexCount][]; - - for (int i = 0; i < uniqueVertexCount; ++i) - { - int count = vertexInstanceCounts[i]; - if (count > 0) - { - vertexInstances[i] = new int[count]; - for(int j =0; j< count; j++) - { - vertexInstances[i][j] = 0; - } - } - } - - // For each vertex, record all faces which include it - for (int i = 0; i < indexList.Count; ++i) - { - int faceIndex = Math.Floor(i / 3); - int uniqueIndex = vertexMap[indexList[i]]; - vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; - } - - // At this point, vertexInstanceCounts should contain nothing but zeroes - - // Compute normals for all faces - Vector3d[] faceNormals = new Vector3d[triangleCount]; - for (int i = 0; i < triangleCount; ++i) - { - // The face normal is just the cross product of the two edge vectors - int i0 = indexList[i * 3 + 0]; - int i1 = indexList[i * 3 + 1]; - int i2 = indexList[i * 3 + 2]; - Vector3d edge0 = Vector3d.SubtractVectors(vertexList[i1].Position, vertexList[i0].Position); - Vector3d edge1 = Vector3d.SubtractVectors(vertexList[i2].Position, vertexList[i1].Position); - faceNormals[i] = Vector3d.Cross(edge0, edge1); - - faceNormals[i].Normalize(); - } - - // Finally, average the face normals - int newVertexCount = triangleCount * 3; - Vector3d[] vertexNormals = new Vector3d[newVertexCount]; - float cosCreaseAngle = Math.Min(0.9999f, (float)Math.Cos(creaseAngleRad)); - for (int i = 0; i < newVertexCount; ++i) - { - int vertexIndex = indexList[i]; - int uniqueIndex = vertexMap[vertexIndex]; - Vector3d faceNormal = faceNormals[Math.Floor(i / 3)]; - - Vector3d sum = new Vector3d(); - foreach (int faceIndex in vertexInstances[uniqueIndex]) - { - Vector3d n = faceNormals[faceIndex]; - if (Vector3d.Dot(faceNormal, n) > cosCreaseAngle) - { - sum.Add(n); - } - } - - vertexNormals[i] = sum; - vertexNormals[i].Normalize(); - } - - return vertexNormals; - } - - - // Calculate tangent vectors at each vertex. The 'face tangent' is a direction in the plane of the - // triangle and parallel to the direction of increasing tex coord u, i.e. the partial derivative - // with respect to u of the triangle's plane equation expressed in terms of the texture coordinate - // (u, v). Partial derivatives of the triangles containing a vertex are averaged to compute the - // vertex tangent. Faces are not included in the when the angle formed with the test face is - // greater than the crease angle, or when the texture texture coordinates are not continuous. - // - // This method returns an array of vertex normals, one for each index in the index list - private Vector3d[] CalculateVertexTangents(List vertexList, List indexList, float creaseAngleRad) - { - if (vertexList.Count == 0) - { - return null; - } - - int vertexCount = vertexList.Count; - int triangleCount = Math.Floor(indexList.Count / 3); - - // Create a list of vertices sorted by their positions. This will be used to - // produce a list of vertices with unique positions. - List vertexPositions = new List(); - for (int vertexIndex = 0; vertexIndex < vertexList.Count; ++vertexIndex) - { - VertexPosition vp = new VertexPosition(); - vp.position = vertexList[vertexIndex].Position; - vp.index = (uint)vertexIndex; - vertexPositions.Add(vp); - } - - vertexPositions.Sort(delegate (VertexPosition v0, VertexPosition v1) { return CompareVector3(v0.position, v1.position); }); - - // vertexMap will map a vertex index to the index of a vertex with a unique position - uint[] vertexMap = new uint[vertexPositions.Count]; - int uniqueVertexCount = 0; - for (int vertexIndex = 0; vertexIndex < vertexPositions.Count; vertexIndex++) - { - if (vertexIndex == 0 || CompareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position) != 0) - { - ++uniqueVertexCount; - } - vertexMap[vertexPositions[vertexIndex].index] = (uint)(uniqueVertexCount - 1); - } - - int[] vertexInstanceCounts = new int[uniqueVertexCount]; - for (int i = 0; i < uniqueVertexCount; i++) - { - vertexInstanceCounts[i] = 0; - } - - foreach (int vertexIndex in indexList) - { - uint uniqueIndex = vertexMap[vertexIndex]; - vertexInstanceCounts[uniqueIndex]++; - } - - // vertexInstances contains the list of faces each vertex is referenced in - int[][] vertexInstances = new int[uniqueVertexCount][]; - for (int i = 0; i < uniqueVertexCount; ++i) - { - int count = vertexInstanceCounts[i]; - if (count > 0) - { - vertexInstances[i] = new int[count]; - for (int j = 0; j < count; j++) - { - vertexInstances[i][j] = 0; - } - } - } - - // For each vertex, record all faces which include it - for (int i = 0; i < indexList.Count; ++i) - { - int faceIndex = Math.Floor(i / 3); - uint uniqueIndex = vertexMap[indexList[i]]; - vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; - } - - // At this point, vertexInstanceCounts should contain nothing but zeroes - - // Compute partial derivatives for all faces - Vector3d[] partials = new Vector3d[triangleCount]; - for (int i = 0; i < triangleCount; ++i) - { - PositionNormalTextured v0 = vertexList[(int)indexList[i * 3 + 0]]; - PositionNormalTextured v1 = vertexList[(int)indexList[i * 3 + 1]]; - PositionNormalTextured v2 = vertexList[(int)indexList[i * 3 + 2]]; - Vector3d edge0 = Vector3d.SubtractVectors(v1.Position, v0.Position); - Vector3d edge1 = Vector3d.SubtractVectors(v2.Position, v0.Position); - double m00 = v1.Tu - v0.Tu; - double m01 = v1.Tv - v0.Tv; - double m10 = v2.Tu - v0.Tu; - double m11 = v2.Tv - v0.Tv; - - double determinant = m00 * m11 - m01 * m10; - if (Math.Abs(determinant) < 1.0e-6f) - { - // No unique vector; just select one of the edges - if (edge0.LengthSq() > 0.0f) - { - partials[i] = edge0; - partials[i].Normalize(); - } - else - { - // Degenerate edge; just use the unit x vector - partials[i] = Vector3d.Create(1.0f, 0.0f, 0.0f); - } - } - else - { - // Matrix n is the inverse of m - double invDeterminant = 1.0f / determinant; - double n00 = m11 * invDeterminant; - double n01 = -m01 * invDeterminant; - double n10 = -m10 * invDeterminant; - double n11 = m00 * invDeterminant; - - partials[i] = Vector3d.AddVectors(Vector3d.MultiplyScalar(edge0, n00), Vector3d.MultiplyScalar(edge1, n01)); - partials[i].Normalize(); - } - } - - // Finally, average the partial derivatives - int newVertexCount = triangleCount * 3; - Vector3d[] tangents = new Vector3d[newVertexCount]; - float cosCreaseAngle = Math.Min(0.9999f, (float)Math.Cos(creaseAngleRad)); - for (int i = 0; i < newVertexCount; ++i) - { - uint vertexIndex = indexList[i]; - uint uniqueIndex = vertexMap[(int)vertexIndex]; - Vector3d du = partials[Math.Floor(i / 3)]; - - Vector3d sum = new Vector3d(); - foreach (int faceIndex in vertexInstances[uniqueIndex]) - { - Vector3d T = partials[faceIndex]; - if (Vector3d.Dot(du, T) > cosCreaseAngle) - { - sum.Add(T); - } - } - - Vector3d N = vertexList[(int)vertexIndex].Normal; - - // Make the tangent orthogonal to the vertex normal - tangents[i] = Vector3d.SubtractVectors(sum, Vector3d.MultiplyScalar(N, Vector3d.Dot(N, sum))); - tangents[i].Normalize(); - } - - return tangents; - } - - - // Calculate per-vertex normals by averaging face normals. Normals of adjacent faces with an - // angle of greater than crease angle are not included in the average. - // - // This method returns an array of vertex normals, one for each index in the index list - private Vector3d[] CalculateVertexNormals(List vertexList, List indexList, float creaseAngleRad) - { - int vertexCount = vertexList.Count; - int triangleCount = Math.Floor(indexList.Count / 3); - - // vertexInstanceCounts contains the number of times each vertex is referenced in the mesh - int[] vertexInstanceCounts = new int[vertexCount]; - foreach (int vertexIndex in indexList) - { - vertexInstanceCounts[vertexIndex]++; - } - - // vertexInstances contains the list of faces each vertex is referenced in - int[][] vertexInstances = new int[vertexCount][]; - for (int i = 0; i < vertexCount; ++i) - { - int count = vertexInstanceCounts[i]; - if (count > 0) - { - vertexInstances[i] = new int[count]; - } - } - - // For each vertex, record all faces which include it - for (int i = 0; i < indexList.Count; ++i) - { - int faceIndex = Math.Floor(i / 3); - int vertexIndex = indexList[i]; - vertexInstances[vertexIndex][--vertexInstanceCounts[vertexIndex]] = faceIndex; - } - - // At this point, vertexInstanceCounts should contain nothing but zeroes - - // Compute normals for all faces - Vector3d[] faceNormals = new Vector3d[triangleCount]; - for (int i = 0; i < triangleCount; ++i) - { - // The face normal is just the cross product of the two edge vectors - int i0 = indexList[i * 3 + 0]; - int i1 = indexList[i * 3 + 1]; - int i2 = indexList[i * 3 + 2]; - Vector3d edge0 = Vector3d.SubtractVectors(vertexList[i1].Position, vertexList[i0].Position); - Vector3d edge1 = Vector3d.SubtractVectors(vertexList[i2].Position, vertexList[i1].Position); - faceNormals[i] = Vector3d.Cross(edge0, edge1); - - faceNormals[i].Normalize(); - } - - // Finally, average the face normals - int newVertexCount = triangleCount * 3; - Vector3d[] vertexNormals = new Vector3d[newVertexCount]; - float cosCreaseAngle = Math.Min(0.9999f, (float)Math.Cos(creaseAngleRad)); - for (int i = 0; i < newVertexCount; ++i) - { - int vertexIndex = indexList[i]; - Vector3d faceNormal = faceNormals[Math.Floor(i / 3)]; - - Vector3d sum = new Vector3d(); - foreach (int faceIndex in vertexInstances[vertexIndex]) - { - Vector3d n = faceNormals[faceIndex]; - if (Vector3d.Dot(faceNormal, n) > cosCreaseAngle) - { - sum.Add(n); - } - } - - vertexNormals[i] = sum; - vertexNormals[i].Normalize(); - } - - return vertexNormals; - } - - // Add textures to ensure that we have as many textures as - private void addMaterial(Material material) - { - meshMaterials.Add(material); - while (meshTextures.Count < meshMaterials.Count) - { - meshTextures.Add(null); - } - - while (meshSpecularTextures.Count < meshMaterials.Count) - { - meshSpecularTextures.Add(null); - } - - while (meshNormalMaps.Count < meshMaterials.Count) - { - meshNormalMaps.Add(null); - } - } - - // Load a color chunk from a 3ds file - // Colors may be stored in a 3ds file either as 3 floats or 3 bytes - private Color LoadColorChunk(BinaryReader br) - { - ushort chunkID = br.ReadUInt16(); - uint chunkLength = br.ReadUInt32(); - Color color = Colors.Black; - - if ((chunkID == 0x0010 || chunkID == 0x0013) && chunkLength == 18) - { - // Need to guard against values outside of [0, 1], otherwise Colors.FromArgb - // will throw an exception. - float r = Math.Max(0.0f, Math.Min(1.0f, br.ReadSingle())); - float g = Math.Max(0.0f, Math.Min(1.0f, br.ReadSingle())); - float b = Math.Max(0.0f, Math.Min(1.0f, br.ReadSingle())); - color = Color.FromArgb(255, (int)(255.0f * r), (int)(255.0f * g), (int)(255.0f * b)); - } - else if ((chunkID == 0x0011 || chunkID == 0x0012) && chunkLength == 9) - { - color = Color.FromArgb(255, br.ReadByte(), br.ReadByte(), br.ReadByte()); - } - else - { - // Unknown color block; ignore it - br.ReadBytes((int)chunkLength - 6); - } - - return color; - } - - - // Load a percentage chunk from a 3ds file - // A percentage may be stored as either a float or a 16-bit integer - private float LoadPercentageChunk(BinaryReader br) - { - ushort chunkID = br.ReadUInt16(); - uint chunkLength = br.ReadUInt32(); - float percentage = 0.0f; - - if (chunkID == 0x0030 && chunkLength == 8) - { - percentage = br.ReadUInt16(); - } - else if (chunkID == 0x0031 && chunkLength == 10) - { - percentage = br.ReadSingle(); - } - else - { - // Unknown percentage block; ignore it - br.ReadBytes((int)chunkLength - 6); - } - - return percentage; - } - - - - Dictionary TextureCache = new Dictionary(); - - string[] matFiles = new string[0]; - int matFileIndex = 0; - private void LoadMeshFromObj(TourDocument doc, string filename) - { - this.Filename = filename; - tourDocument = doc; - - - Blob blob = doc.GetFileBlob(filename); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (FileProgressEvent e) - { - matFiles = ReadObjMaterialsFromBin(chunck.Result as string); - matFileIndex = 0; - // pass data to LoadMatLib. It will chain load all the material files, then load the obj from this data - hack for having no synchronous blob reading in javascript - LoadMatLib(chunck.Result as string); - - //this is delay loaded when mat files are all read. - //ReadObjFromBin(chunck.Result as string); - - }; - chunck.ReadAsText(blob); - } - - private string[] ReadObjMaterialsFromBin(string data) - { - List matFiles = new List(); - - string[] lines = data.Split("\n"); - { - - foreach (string lineraw in lines) - { - string line = lineraw.Replace(" ", " "); - - string[] parts = line.Trim().Split(" "); - - if (parts.Length > 0) - { - switch (parts[0]) - { - case "mtllib": - { - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - string matFile = path + parts[1]; - matFiles.Add(matFile); - - //LoadMatLib(matFile); - } - break; - } - } - } - } - - return matFiles; - } - - private void ReadObjFromBin(string data) - { - bool objectFound = false; - //Dictionary objectTable = new Dictionary(); - List objects = new List(); - ObjectNode currentObject = new ObjectNode(); - currentObject.Name = "Default"; - - int triangleCount = 0; - int vertexCount = 0; - - // List matGroups = new List(); - - List vertexList = new List(); - List vertList = new List(); - List normList = new List(); - List uvList = new List(); - - vertList.Add(new Vector3d()); - normList.Add(new Vector3d()); - uvList.Add(new Vector2d()); - - - List indexList = new List(); - List attribList = new List(); - List applyLists = new List(); - List applyListsIndex = new List(); - List materialNames = new List(); - int currentMaterialIndex = -1; - Material currentMaterial = new Material(); - Group currentGroup = new Group(); - - - int currentIndex = 0; - - - //initialize the default material - - currentMaterial = new Material(); - currentMaterial.Diffuse = Color; - currentMaterial.Ambient = Color; - currentMaterial.Specular = Colors.White; - currentMaterial.SpecularSharpness = 30.0f; - currentMaterial.Opacity = 1.0f; - currentMaterial.IsDefault = true; - - //initialize the group - currentGroup.startIndex = 0; - currentGroup.indexCount = 0; - currentGroup.materialIndex = 0; - - string[] lines = data.Split("\n"); - { - - foreach(string lineraw in lines) - { - string line = lineraw.Replace(" ", " "); - - string[] parts = line.Trim().Split(" "); - - if (parts.Length > 0) - { - switch (parts[0]) - { - case "mtllib": - // We have to pre-load these now in JavaScript, since we can't synchronously load the file and we need file contents to interpret the rest of this file - //{ - // string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - // string matFile = path + parts[1]; - // LoadMatLib(matFile); - //} - break; - case "usemtl": - string materialName = parts[1]; - if (matLib.ContainsKey(materialName)) - { - if (currentMaterialIndex == -1 && currentIndex > 0) - { - addMaterial(currentMaterial); - currentMaterialIndex++; - } - - if (currentMaterialIndex > -1) - { - currentGroup.indexCount = currentIndex - currentGroup.startIndex; - // matGroups.Add(currentGroup); - currentObject.DrawGroup.Add(currentGroup); - } - - currentMaterialIndex++; - - if (matLib.ContainsKey(materialName)) - { - currentMaterial = matLib[materialName]; - - - if (textureLib.ContainsKey(materialName)) - { - try - { - if (!TextureCache.ContainsKey(textureLib[materialName])) - { - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - - Texture tex = tourDocument.GetCachedTexture2d(path + textureLib[materialName]); - if (tex != null) - { - meshFilenames.Add(textureLib[materialName]); - TextureCache[textureLib[materialName]] = tex; - } - } - meshTextures.Add(TextureCache[textureLib[materialName]]); - } - catch - { - } - } - - addMaterial(currentMaterial); - - currentGroup = new Group(); - currentGroup.startIndex = currentIndex; - currentGroup.indexCount = 0; - currentGroup.materialIndex = currentMaterialIndex; - } - } - - break; - case "v": - vertexCount++; - if (FlipHandedness) - { - vertList.Add(Vector3d.Create(-float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3]))); - } - else - { - vertList.Add(Vector3d.Create(float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3]))); - } - break; - case "vn": - if (FlipHandedness) - { - normList.Add(Vector3d.Create(-float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3]))); - } - else - { - normList.Add(Vector3d.Create(float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3]))); - } - break; - case "vt": - uvList.Add(Vector2d.Create(float.Parse(parts[1]), FlipV ? (1 - float.Parse(parts[2])) : float.Parse(parts[2]))); - break; - case "g": - case "o": - if (objectFound) - { - if (currentMaterialIndex > -1) - { - currentGroup.indexCount = currentIndex - currentGroup.startIndex; - // matGroups.Add(currentGroup); - currentObject.DrawGroup.Add(currentGroup); - currentGroup = new Group(); - currentGroup.startIndex = currentIndex; - currentGroup.indexCount = 0; - currentGroup.materialIndex = currentMaterialIndex; - } - currentObject = new ObjectNode(); - } - - objectFound = true; - if (parts.Length > 1) - { - currentObject.Name = parts[1]; - } - else - { - currentObject.Name = "Unnamed"; - } - objects.Add(currentObject); - //if (!objectTable.ContainsKey(currentObject.Name)) - //{ - // objectTable.Add(currentObject.Name, currentObject); - //} - break; - case "f": - int[] indexiesA = GetIndexies(parts[1]); - int[] indexiesB = GetIndexies(parts[2]); - int[] indexiesC = GetIndexies(parts[3]); - - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); - - if (FlipHandedness) - { - indexList.Add(currentIndex); - indexList.Add(currentIndex + 2); - indexList.Add(currentIndex + 1); - } - else - { - indexList.Add(currentIndex); - indexList.Add(currentIndex + 1); - indexList.Add(currentIndex + 2); - - } - - triangleCount++; - currentIndex += 3; - //bool flip = true; - if (parts.Length > 4) - { - int partIndex = 4; - - while (partIndex < (parts.Length)) - { - if (FlipHandedness) - { - indexiesA = GetIndexies(parts[1]); - indexiesC = GetIndexies(parts[partIndex]); - indexiesB = GetIndexies(parts[partIndex - 1]); - } - else - { - indexiesA = GetIndexies(parts[1]); - indexiesB = GetIndexies(parts[partIndex - 1]); - indexiesC = GetIndexies(parts[partIndex]); - } - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); - vertexList.Add(PositionNormalTextured.CreateUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); - - - indexList.Add(currentIndex); - indexList.Add(currentIndex + 1); - indexList.Add(currentIndex + 2); - triangleCount++; - - currentIndex += 3; - partIndex++; - } - } - break; - } - } - } - } - - if (!objectFound) - { - // add the default object - objects.Add(currentObject); - } - - if (currentMaterialIndex == -1 && currentIndex > 0) - { - addMaterial(currentMaterial); - currentMaterialIndex++; - } - - if (currentMaterialIndex > -1) - { - currentGroup.indexCount = (int)(currentIndex - currentGroup.startIndex); - currentObject.DrawGroup.Add(currentGroup); - } - - if (normList.Count < 2) - { - double degtorag = Math.PI / 180; - double creaseAngleRad = (Smooth ? 170.0f * degtorag : 45.0f * degtorag); - - Vector3d[] vertexNormals = CalculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); - List newVertexList = new List(); - int newVertexCount = indexList.Count; - - for (int vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) - { - PositionNormalTextured v = vertexList[indexList[vertexIndex]]; - v.Normal = vertexNormals[vertexIndex]; - newVertexList.Add(v); - } - - vertexList = newVertexList; - } - - mesh = Mesh.Create(vertexList, indexList); - ObjectNode rootDummy = new ObjectNode(); - rootDummy.Name = "Root"; - rootDummy.Parent = null; - rootDummy.Level = -1; - rootDummy.DrawGroup = null; - rootDummy.Children = objects; - - Objects = new List(); - Objects.Add(rootDummy); - - - mesh.setObjects(Objects); - - //List objects = new List(); - - //ObjectNode node = new ObjectNode(); - //node.Name = "Default"; - //node.DrawGroup = matGroups; - //objects.Add(node); - //mesh.setObjects(objects); - //Objects = objects; - - - mesh.commitToDevice(); - - dirty = false; - readyToRender = true; - } - - //private Texture LoadTexture(string filename) - //{ - // if (!File.Exists(filename)) - // { - // string newfilename = FindFile(filename); - // if (string.IsNullOrEmpty(newfilename)) - // { - // newfilename = FindFileFuzzy(filename); - // } - - // filename = newfilename; - // } - - // if (string.IsNullOrEmpty(filename)) - // { - // return null; - // } - - // return Texture.FromFile(RenderContext.PrepDevice, filename); - //} - - //public static string FindFileFuzzy(string filename) - //{ - // filename = filename.ToLower(); - // string path = filename.Substring(0, filename.LastIndexOf('\\') + 1); - // string file = filename.Substring(filename.LastIndexOf("\\") + 1); - // if (file.Contains(".")) - // { - // file = file.Substring(0, file.LastIndexOf('.') ); - // } - - // string ext = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); - - // foreach (string f in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)) - // { - // string fb = f.Substring(f.LastIndexOf("\\") + 1).ToLower(); - // string fe = ""; - // string ff = ""; - // if (f.Contains(".")) - // { - // fe = fb.Substring(fb.LastIndexOf(".") + 1); - // ff = fb.Substring(0, fb.LastIndexOf(".")); - // } - // if (string.Compare(file, 0, ff, 0, file.Length) == 0 && ((fe == ext) || (fe == "png") || (fe == "tif") || (fe == "tiff") || (fe == "bmp") || (fe == "jpg") || (fe == "jpeg") || (fe == "tga") || (fe == "jfif") || (fe == "rla"))) - // { - // return f; - // } - // } - - - // //foreach (string dir in Directory.GetDirectories(path)) - // //{ - // // string child = dir + @"\" + file; - // // if (File.Exists(child)) - // // { - // // return child; - // // } - // // FindFileFuzzy(child); - // //} - - // return null; - //} - - //public static string FindFile(string filename) - //{ - // string path = filename.Substring(0, filename.LastIndexOf('\\') + 1); - // string file = filename.Substring(filename.LastIndexOf("\\") + 1); - - // foreach (string dir in Directory.GetDirectories(path)) - // { - // string child = dir + @"\" + file; - // if (File.Exists(child)) - // { - // return child; - // } - // FindFile(child); - // } - - // return null; - //} - - public List Objects = new List(); - - Dictionary matLib = new Dictionary(); - Dictionary textureLib = new Dictionary(); - void LoadMatLib(string data) - { - if (matFileIndex < matFiles.Length) - { - - string filename = matFiles[matFileIndex++]; - - Blob blob = tourDocument.GetFileBlob(filename); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (FileProgressEvent e) - { - ReadMatLibFromBin(chunck.Result as string); - - LoadMatLib(data); - }; - chunck.ReadAsText(blob); - } - else - { - ReadObjFromBin(data); - } - } - - private void ReadMatLibFromBin(string data) - { - - - - try - { - Material currentMaterial = new Material(); - string materialName = ""; - - matLib = new Dictionary(); - textureLib = new Dictionary(); - - - string[] lines = data.Split("\n"); - { - - foreach (string lineraw in lines) - { - string line = lineraw; - - string[] parts = line.Trim().Split(" "); - - if (parts.Length > 0) - { - switch (parts[0]) - { - case "newmtl": - if (!string.IsNullOrEmpty(materialName)) - { - matLib[materialName] = currentMaterial; - } - - currentMaterial = new Material(); - currentMaterial.Diffuse = Colors.White; - currentMaterial.Ambient = Colors.White; - currentMaterial.Specular = Colors.Black; - currentMaterial.SpecularSharpness = 30.0f; - currentMaterial.Opacity = 1.0f; - materialName = parts[1]; - break; - case "Ka": - currentMaterial.Ambient = Color.FromArgb(255, (int)(Math.Min(float.Parse(parts[1]) * 255, 255)), (int)(Math.Min(float.Parse(parts[2]) * 255, 255)), (int)(Math.Min(float.Parse(parts[3]) * 255, 255))); - break; - case "map_Kd": - //ENDURE TEXTURES ARE NOT BLACK! - currentMaterial.Diffuse = Colors.White; - - string textureFilename = parts[1]; - for (int i = 2; i < parts.Length; i++) - { - textureFilename += " " + parts[i]; - } - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - - textureFilename = textureFilename.Replace("/", "\\"); - if (textureFilename.IndexOf("\\") != -1) - { - textureFilename = textureFilename.Substring(textureFilename.LastIndexOf("\\") + 1); - } - - //if (File.Exists(path + "\\" + textureFilename)) - { - //textureLib.Add(materialName, path + "\\" + textureFilename); - textureLib[materialName] = textureFilename; - } - break; - case "Kd": - currentMaterial.Diffuse = Color.FromArgb(255, (int)(Math.Min(float.Parse(parts[1]) * 255, 255)), (int)(Math.Min(float.Parse(parts[2]) * 255, 255)), (int)(Math.Min(float.Parse(parts[3]) * 255, 255))); - break; - case "Ks": - currentMaterial.Specular = Color.FromArgb(255, (int)(Math.Min(float.Parse(parts[1]) * 255, 255)), (int)(Math.Min(float.Parse(parts[2]) * 255, 255)), (int)(Math.Min(float.Parse(parts[3]) * 255, 255))); - break; - case "d": - // Where does this map? - currentMaterial.Opacity = float.Parse(parts[1]); - break; - case "Tr": - // Where does this map? - currentMaterial.Opacity = 1 - float.Parse(parts[1]); - break; - - case "illum": - // Where does this map? - int illuminationMode = int.Parse(parts[1]); - break; - - case "sharpness": - currentMaterial.SpecularSharpness = float.Parse(parts[1]); - break; - case "Ns": - currentMaterial.SpecularSharpness = 1.0f + 2 * float.Parse(parts[1]); - currentMaterial.SpecularSharpness = Math.Max(10.0f, currentMaterial.SpecularSharpness); - break; - } - } - } - } - - if (!string.IsNullOrEmpty(materialName)) - { - matLib[materialName] = currentMaterial; - } - } - catch - { - } - } - - int[] GetIndexies(string data) - { - string[] parts = data.Trim().Split('/'); - int[] indecies = new int[3]; - - if (string.IsNullOrEmpty(data)) - { - return indecies; - } - - if (parts.Length > 0) - { - indecies[0] = int.Parse(parts[0]); - } - if (parts.Length > 1) - { - if (string.IsNullOrEmpty(parts[1])) - { - indecies[1] = 0; - } - else - { - indecies[1] = int.Parse(parts[1]); - } - } - if (parts.Length > 2) - { - indecies[2] = int.Parse(parts[2]); - } - - return indecies; - } - - TourDocument tourDocument = null; - - private void LoadMeshFrom3ds(TourDocument doc, string filename, float scale) - { - tourDocument = doc; - - Blob blob = doc.GetFileBlob(filename); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (FileProgressEvent e) - { - Read3dsFromBin(new BinaryReader(new Uint8Array(chunck.Result)), scale); - - }; - chunck.ReadAsArrayBuffer(blob); - } - private void Read3dsFromBin(BinaryReader br, float scale) - { - // Force garbage collection to ensure that unmanaged resources are released. - // Temporary workaround until unmanaged resource leak is identified - - int i; - - ushort sectionID; - uint sectionLength; - - string name = ""; - string material = ""; - int triangleCount = 0; - int vertexCount = 0; - List vertexList = new List(); - List indexList = new List(); - List attribList = new List(); - //List applyLists = new List(); - //List applyListsIndex = new List(); - List materialNames = new List(); - int currentMaterialIndex = -1; - Material currentMaterial = new Material(); - int attributeID = 0; - - int count = 0; - UInt16 lastID = 0; - bool exit = false; - bool normalMapFound = false; - - float offsetX = 0; - float offsetY = 0; - float offsetZ = 0; - List objects = new List(); - ObjectNode currentObject = null; - List objHierarchy = new List(); - List objNames = new List(); - Dictionary objectTable = new Dictionary(); - - int dummyCount = 0; - - //using (Stream fs = new FileStream(filename, FileMode.Open)) - { - // BinaryReader br = new BinaryReader(fs); - long length = br.Length - 1; - - - int startMapIndex = 0; - int startTriangleIndex = 0; - while (br.Position < length && !exit) //Loop to scan the whole file - { - sectionID = br.ReadUInt16(); - sectionLength = br.ReadUInt32(); - - - switch (sectionID) - { - - //This section the begining of the file - case 0x4d4d: - break; - - // This section marks the edit section containing the 3d models (3d3d get it? very punny!) - case 0x3d3d: - break; - - // Object section contains meshes, etc. - case 0x4000: - name = ""; - Byte b; - do - { - b = br.ReadByte(); - if (b > 0) - { - name += string.FromCharCode(b); - } - - } while (b != 0); - - currentObject = new ObjectNode(); - currentObject.Name = name; - objects.Add(currentObject); - if (!objectTable.ContainsKey(currentObject.Name)) - { - objectTable[currentObject.Name] = currentObject; - } - - break; - - // Marks the start of a mesh section - case 0x4100: - startMapIndex = vertexList.Count; - startTriangleIndex = Math.Floor(indexList.Count / 3); - break; - - // This section has the vertex list.. Maps to Vertext buffer in Direct3d - case 0x4110: - vertexCount = br.ReadUInt16(); - - for (i = 0; i < vertexCount; i++) - { - float x = br.ReadSingle() - offsetX; - float y = br.ReadSingle() - offsetY; - float z = br.ReadSingle() - offsetZ; - - PositionNormalTextured vert = PositionNormalTextured.Create(x * scale, z * scale, y * scale, 0, 0, 0, 0, 0); - vertexList.Add(vert); - } - break; - - // This section is a tiangle index list. Maps to Index Buffer in Direct3d - case 0x4120: - { - int triCount = br.ReadUInt16(); - triangleCount += triCount; - - for (i = 0; i < triCount; i++) - { - int aa = br.ReadUInt16() + startMapIndex; - int bb = br.ReadUInt16() + startMapIndex; - int cc = br.ReadUInt16() + startMapIndex; - indexList.Add(cc); - indexList.Add(bb); - indexList.Add(aa); - UInt16 flags = br.ReadUInt16(); - } - } - break; - - // Material for face from start face to triCount - case 0x4130: - { - material = ""; - i = 0; - byte b1; - do - { - b1 = br.ReadByte(); - if (b1 > 0) - { - material += string.FromCharCode(b1); - } - - i++; - } while (b1 != 0); - int triCount = br.ReadUInt16(); - int[] applyList = new int[triCount]; - - attributeID = GetMaterialID(material, materialNames); - - for (i = 0; i < triCount; i++) - { - applyList[i] = br.ReadUInt16() + startTriangleIndex; - } - currentObject.ApplyLists.Add(applyList); - currentObject.ApplyListsIndex.Add(attributeID); - - } - break; - - // Section for UV texture maps - case 0x4140: - count = br.ReadUInt16(); - for (i = 0; i < count; i++) - { - PositionNormalTextured vert = vertexList[startMapIndex + i]; - Vector2d texCoord = Vector2d.Create(br.ReadSingle(), FlipV ? (1.0f - br.ReadSingle()) : (br.ReadSingle())); - vertexList[startMapIndex + i] = PositionNormalTextured.CreateUV(vert.Position, new Vector3d(), texCoord); - } - break; - - - // Section for Smoothing Groups - //case 0x4150: - // count = br.ReadUInt16(); - // for (i = 0; i < count; i++) - // { - // CustomVertex.PositionNormalTextured vert = vertexList[startMapIndex + i]; - // vertexList[startMapIndex + i] = new CustomVertex.PositionNormalTextured(vert.Position, Vector3d.Create(0,0,0), br.ReadSingle(), FlipV ? (1.0f - br.ReadSingle() ) : (br.ReadSingle())); - // } - // break; - case 0x4160: - float[] mat = new float[12]; - for (i = 0; i < 12; i++) - { - mat[i] = br.ReadSingle(); - } - //offsetX = mat[9]; - //offsetY = mat[11]; - //offsetZ = mat[10]; - - if (objectTable.ContainsKey(name)) - { - objectTable[name].LocalMat = Matrix3d.Create( - mat[0], mat[1], mat[2], 0, - mat[3], mat[4], mat[5], 0, - mat[6], mat[7], mat[8], 0, - mat[9], mat[10], mat[11], 1); - - objectTable[name].LocalMat.Invert(); - - //objectTable[name].PivotPoint = Vector3d.Create(mat[9]*mat[0],mat[10]*mat[1],mat[11]*mat[2]); - } - - break; - // Materials library section - case 0xAFFF: - break; - // Material Name - case 0xA000: - { - string matName = ""; - i = 0; - byte b2; - do - { - b2 = br.ReadByte(); - if (b2 > 0) - { - - matName += string.FromCharCode(b2); - } - - i++; - } while (b2 != 0); - materialNames.Add(matName); - - if (currentMaterialIndex > -1) - { - addMaterial(currentMaterial); - } - - currentMaterialIndex++; - - currentMaterial = new Material(); - currentMaterial.Diffuse = Colors.White; - currentMaterial.Ambient = Colors.White; - currentMaterial.Specular = Colors.Black; - currentMaterial.SpecularSharpness = 30.0f; - currentMaterial.Opacity = 1.0f; - } - break; - - // Ambient color - case 0xA010: - currentMaterial.Ambient = LoadColorChunk(br); - break; - - // Diffuse color - case 0xA020: - currentMaterial.Diffuse = LoadColorChunk(br); - break; - - // Specular color - case 0xA030: - currentMaterial.Specular = LoadColorChunk(br); - break; - - // Specular power - case 0xA040: - // This is just a reasonable guess at the mapping from percentage to - // specular exponent used by 3D Studio. - currentMaterial.SpecularSharpness = 1.0f + 2 * LoadPercentageChunk(br); - - // Minimum sharpness of 10 enforced here because of bad specular exponents - // in ISS model. - // TODO: Fix ISS and permit lower specular exponents here - currentMaterial.SpecularSharpness = Math.Max(10.0f, currentMaterial.SpecularSharpness); - break; - - //Texture map file - case 0xA200: - break; - - // Texture file name - case 0xA300: - { - string textureFilename = ""; - i = 0; - byte b2; - do - { - b2 = br.ReadByte(); - if (b2 > 0) - { - textureFilename += string.FromCharCode(b2); - } - - i++; - } while (b2 != 0); - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - try - { - Texture tex = tourDocument.GetCachedTexture2d(path + textureFilename); - - if (tex != null) - { - meshTextures.Add(tex); - meshFilenames.Add(textureFilename); - - // The ISS model has black for the diffuse color; to work around this - // we'll set the diffuse color to white when there's a texture present. - // The correct fix is to modify the 3ds model of ISS. - currentMaterial.Diffuse = Colors.White; - } - else - { - meshTextures.Add(null); - } - } - catch - { - meshTextures.Add(null); - } - } - break; - - - // Bump map - case 0xA230: - { - float percentage = LoadPercentageChunk(br); - - int nameId = br.ReadUInt16(); - uint nameBlockLength = br.ReadUInt32(); - string textureFilename = ""; - i = 0; - byte b2; - do - { - b2 = br.ReadByte(); - if (b2 > 0) - { - textureFilename += string.FromCharCode(b2); - } - - i++; - } while (b2 != 0); - - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - try - { - Texture tex = tourDocument.GetCachedTexture2d(path + textureFilename); - - if (tex != null) - { - meshNormalMaps.Add(tex); - meshFilenames.Add(textureFilename); - - // Indicate that we have a normal map so that we know to generate tangent vectors for the mesh - normalMapFound = true; - } - else - { - meshNormalMaps.Add(null); - } - - } - catch - { - meshNormalMaps.Add(null); - } - } - - break; - - // Specular map - case 0xA204: - { - float strength = LoadPercentageChunk(br); - - int nameId = br.ReadUInt16(); - uint nameBlockLength = br.ReadUInt32(); - string textureFilename = ""; - i = 0; - byte b2; - do - { - b2 = br.ReadByte(); - if (b2 > 0) - { - textureFilename += string.FromCharCode(b2); - } - - i++; - } while (b2 != 0); - - string path = Filename.Substring(0, Filename.LastIndexOf('\\') + 1); - try - { - Texture tex = tourDocument.GetCachedTexture2d(path + textureFilename); - if (tex != null) - { - meshSpecularTextures.Add(tex); - meshFilenames.Add(textureFilename); - - // Set the current specular color from the specular texture strength - int gray = (int)(255.99f * strength / 100.0f); - currentMaterial.Specular = Color.FromArgb(255, gray, gray, gray); - } - else - { - meshSpecularTextures.Add(null); - } - } - catch - { - meshSpecularTextures.Add(null); - } - } - - break; - case 0xB000: - break; - case 0xB002: - break; - case 0xB010: - { - name = ""; - i = 0; - byte b1; - do - { - b1 = br.ReadByte(); - if (b1 > 0) - { - name += string.FromCharCode(b1); - } - - i++; - } while (b1 != 0); - int dum1 = (int)br.ReadUInt16(); - int dum2 = (int)br.ReadUInt16(); - int level = (int)br.ReadUInt16(); - - if (level == 65535) - { - level = -1; - } - if (name.StartsWith("$")) - { - dummyCount++; - - } - else - { - objNames.Add(name); - } - objHierarchy.Add(level); - - if (objectTable.ContainsKey(name)) - { - - objectTable[name].Level = level; - } - } - break; - case 0xB011: - { - name = ""; - i = 0; - byte b1; - do - { - b1 = br.ReadByte(); - if (b1 > 0) - { - name += string.FromCharCode(b1); - } - - i++; - } while (b1 != 0); - objNames.Add("$$$" + name); - } - break; - case 0xB013: - //pivot point - float[] points = new float[3]; - for (i = 0; i < 3; i++) - { - points[i] = br.ReadSingle(); - } - - - if (objectTable.ContainsKey(name)) - { - objectTable[name].PivotPoint = Vector3d.Create(-points[0], -points[1], -points[2]); - } - break; - case 0xB020: - { - float[] pos = new float[8]; - for (i = 0; i < 8; i++) - { - pos[i] = br.ReadSingle(); - } - - } - break; - - // If we don't recognize a section then jump over it. Subract the header from the section length - default: - br.SeekRelative((int)(sectionLength - 6)); - break; - } - lastID = sectionID; - } - br.Close(); - if (currentMaterialIndex > -1) - { - addMaterial(currentMaterial); - } - } - - ////debug - - //for ( i = 0; i < 99; i++) - //{ - // System.Diagnostics.Debug.WriteLine(objNames[i]); - //} - - //foreach (ObjectNode node in objects) - //{ - // System.Diagnostics.Debug.WriteLine(node.Name); - //} - - ////debug - - - - - // Generate vertex normals - - // Vertex normals are computed by averaging the normals of all faces - // with an angle between them less than the crease angle. By setting - // the crease angle to 0 degrees, the model will have a faceted appearance. - // Right now, the smooth flag selects between one of two crease angles, - // but some smoothing is always applied. - double degtorag = Math.PI / 180; - double creaseAngleRad = (Smooth ? 70.0f * degtorag : 45.0f * degtorag); - - Vector3d[] vertexNormals = CalculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); - List newVertexList = new List(); - int newVertexCount = triangleCount * 3; - - for (int vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) - { - PositionNormalTextured v = vertexList[indexList[vertexIndex]]; - v.Normal = vertexNormals[vertexIndex]; - newVertexList.Add(v); - } - - - // Use the triangle mesh and material assignments to create a single - // index list for the mesh. - List newIndexList = new List(); - - foreach (ObjectNode node in objects) - { - List materialGroups = new List(); - for (i = 0; i < node.ApplyLists.Count; i++) - { - int matId = node.ApplyListsIndex[i]; - int startIndex = newIndexList.Count; - foreach (int triangleIndex in node.ApplyLists[i]) - { - newIndexList.Add((int)(triangleIndex * 3)); - newIndexList.Add((int)(triangleIndex * 3 + 1)); - newIndexList.Add((int)(triangleIndex * 3 + 2)); - } - - Group group = new Group(); - group.startIndex = startIndex; - group.indexCount = node.ApplyLists[i].Length * 3; - group.materialIndex = matId; - materialGroups.Add(group); - } - node.DrawGroup = materialGroups; - } - - // Turn objects into tree - Stack nodeStack = new Stack(); - - List nodeTreeRoot = new List(); - - ObjectNode rootDummy = new ObjectNode(); - rootDummy.Name = "Root"; - rootDummy.Parent = null; - rootDummy.Level = -1; - rootDummy.DrawGroup = null; - - int currentLevel = -1; - - nodeStack.Push(rootDummy); - nodeTreeRoot.Add(rootDummy); - - for (i = 0; i < objHierarchy.Count; i++) - { - int level = objHierarchy[i]; - - if (level <= currentLevel) - { - // pop out all the nodes to intended parent - while (level <= nodeStack.Peek().Level && nodeStack.Count > 1) - { - nodeStack.Pop(); - } - currentLevel = level; - - } - - if (objNames[i].StartsWith("$$$")) - { - ObjectNode dummy = new ObjectNode(); - dummy.Name = objNames[i].Replace("$$$", ""); - dummy.Parent = nodeStack.Peek(); - dummy.Parent.Children.Add(dummy); - dummy.Level = currentLevel = level; - dummy.DrawGroup = null; - nodeStack.Push(dummy); - } - else - { - objectTable[objNames[i]].Level = currentLevel = level; - objectTable[objNames[i]].Parent = nodeStack.Peek(); - objectTable[objNames[i]].Parent.Children.Add(objectTable[objNames[i]]); - nodeStack.Push(objectTable[objNames[i]]); - } - } - - if (objHierarchy.Count == 0) - { - foreach (ObjectNode node in objects) - { - rootDummy.Children.Add(node); - node.Parent = rootDummy; - } - } - - - if (normalMapFound) - { - // If we've got a normal map, we want to generate tangent vectors for the mesh - - // Mapping of vertices to geometry is extremely straightforward now, but this could - // change when a mesh optimization step is introduced. - List tangentIndexList = new List(); - for (uint tangentIndex = 0; tangentIndex < newVertexCount; ++tangentIndex) - { - tangentIndexList.Add(tangentIndex); - } - - Vector3d[] tangents = CalculateVertexTangents(newVertexList, tangentIndexList, (float)creaseAngleRad); - - // Copy the tangents in the vertex data list - PositionNormalTexturedTangent[] vertices = new PositionNormalTexturedTangent[newVertexList.Count]; - int vertexIndex = 0; - foreach (PositionNormalTextured v in newVertexList) - { - PositionNormalTexturedTangent tvertex = new PositionNormalTexturedTangent(v.Position, v.Normal, Vector2d.Create(v.Tu, v.Tv), tangents[vertexIndex]); - vertices[vertexIndex] = tvertex; - ++vertexIndex; - } - mesh = Mesh.CreateTangent(vertices, newIndexList); - } - else - { - mesh = Mesh.Create(newVertexList, newIndexList); - } - - Objects = nodeTreeRoot; - mesh.setObjects(nodeTreeRoot); - mesh.commitToDevice(); - - dirty = false; - readyToRender = true; - } - - private void OffsetObjects(List vertList, List objects, Matrix3d offsetMat, Vector3d offsetPoint) - { - foreach (ObjectNode node in objects) - { - Matrix3d matLoc = node.LocalMat; //offsetMat *; - - OffsetObjects(vertList, node.Children, matLoc, Vector3d.AddVectors(node.PivotPoint, offsetPoint)); - - foreach (Group group in node.DrawGroup) - { - int end = group.startIndex + group.indexCount; - for (int i = group.startIndex; i < end; i++) - { - PositionNormalTextured vert = vertList[i]; - vert.Position = Vector3d.AddVectors(vert.Position, Vector3d.AddVectors(node.PivotPoint, offsetPoint)); - vertList[i] = vert; - } - } - } - } - - - private static int GetMaterialID(string material, List materialNames) - { - int index = 0; - foreach (string mat in materialNames) - { - if (mat == material) - { - return index; - } - index++; - } - - return -1; - } - - - // Set up lighting state to account for: - // - Light reflected from a nearby planet - // - Shadows cast by nearby planets - public void SetupLighting(RenderContext renderContext) - { - Vector3d objPosition = Vector3d.Create(renderContext.World.OffsetX, renderContext.World.OffsetY, renderContext.World.OffsetZ); - Vector3d objToLight = Vector3d.SubtractVectors(objPosition, renderContext.ReflectedLightPosition); - Vector3d sunPosition = Vector3d.SubtractVectors(renderContext.SunPosition, renderContext.ReflectedLightPosition); - double cosPhaseAngle = sunPosition.Length() <= 0.0 ? 1.0 : Vector3d.Dot(objToLight, sunPosition) / (objToLight.Length() * sunPosition.Length()); - float reflectedLightFactor = (float)Math.Max(0.0, cosPhaseAngle); - reflectedLightFactor = (float)Math.Sqrt(reflectedLightFactor); // Tweak falloff of reflected light - float hemiLightFactor = 0.0f; - - // 1. Reduce the amount of sunlight when the object is in the shadow of a planet - // 2. Introduce some lighting due to scattering by the planet's atmosphere if it's - // close to the surface. - double sunlightFactor = 1.0; - if (renderContext.OccludingPlanetRadius > 0.0) - { - double objAltitude = Vector3d.SubtractVectors(objPosition, renderContext.OccludingPlanetPosition).Length() - renderContext.OccludingPlanetRadius; - hemiLightFactor = (float)Math.Max(0.0, Math.Min(1.0, 1.0 - (objAltitude / renderContext.OccludingPlanetRadius) * 300)); - reflectedLightFactor *= (1.0f - hemiLightFactor); - - // Compute the distance from the center of the object to the line between the sun and occluding planet - // We're assuming that the radius of the object is very small relative to Earth; - // for large objects the amount of shadow will vary, and we should use circular - // eclipse shadows. - Vector3d sunToPlanet = Vector3d.SubtractVectors(renderContext.OccludingPlanetPosition, renderContext.SunPosition); - Vector3d objToPlanet = Vector3d.SubtractVectors(renderContext.OccludingPlanetPosition, objPosition); - - Vector3d hemiLightDirection = Vector3d.Create(-objToPlanet.X, -objToPlanet.Y, -objToPlanet.Z); - hemiLightDirection.Normalize(); - renderContext.HemisphereLightUp = hemiLightDirection; - - Vector3d objToSun = Vector3d.SubtractVectors(renderContext.SunPosition, objPosition); - double sunPlanetDistance = sunToPlanet.Length(); - double t = -Vector3d.Dot(objToSun, sunToPlanet) / (sunPlanetDistance * sunPlanetDistance); - if (t > 1.0) - { - // Object is on the side of the planet opposite the sun, so a shadow is possible - - // Compute the position of the object projected onto the shadow axis - Vector3d shadowAxisPoint = Vector3d.AddVectors(renderContext.SunPosition, Vector3d.MultiplyScalar(sunToPlanet, t)); - - // d is the distance to the shadow axis - double d = Vector3d.SubtractVectors(shadowAxisPoint, objPosition).Length(); - - // s is the distance from the sun along the shadow axis - double s = Vector3d.SubtractVectors(shadowAxisPoint, renderContext.SunPosition).Length(); - - // Use the sun's radius to accurately compute the penumbra and umbra cones - const double solarRadius = 0.004645784; // AU - double penumbraRadius = renderContext.OccludingPlanetRadius + (t - 1.0) * (renderContext.OccludingPlanetRadius + solarRadius); - double umbraRadius = renderContext.OccludingPlanetRadius + (t - 1.0) * (renderContext.OccludingPlanetRadius - solarRadius); - - if (d < penumbraRadius) - { - // The object is inside the penumbra, so it is at least partly shadowed - double minimumShadow = 0.0; - if (umbraRadius < 0.0) - { - // No umbra at this point; degree of shadowing is limited because the - // planet doesn't completely cover the sun even when the object is positioned - // exactly on the shadow axis. - double occlusion = Math.Pow(1.0 / (1.0 - umbraRadius), 2.0); - umbraRadius = 0.0; - minimumShadow = 1.0 - occlusion; - } - - // Approximate the amount of shadow with linear interpolation. The accurate - // calculation involves computing the area of the intersection of two circles. - double u = Math.Max(0.0, umbraRadius); - sunlightFactor = Math.Max(minimumShadow, (d - u) / (penumbraRadius - u)); - - int gray = (int)(255.99f * sunlightFactor); - renderContext.SunlightColor = Color.FromArgb(255, gray, gray, gray); - - // Reduce sky-scattered light as well - hemiLightFactor *= (float)sunlightFactor; - } - } - } - - renderContext.ReflectedLightColor = Color.FromArgb(255, (int)(renderContext.ReflectedLightColor.R * reflectedLightFactor), - (int)(renderContext.ReflectedLightColor.G * reflectedLightFactor), - (int)(renderContext.ReflectedLightColor.B * reflectedLightFactor)); - renderContext.HemisphereLightColor = Color.FromArgb(255, (int)(renderContext.HemisphereLightColor.R * hemiLightFactor), - (int)(renderContext.HemisphereLightColor.G * hemiLightFactor), - (int)(renderContext.HemisphereLightColor.B * hemiLightFactor)); - } - - public const int MAX_VERTICES = 8000; - public const int MAX_POLYGONS = 8000; - - - - public bool ISSLayer = false; - bool readyToRender = false; - public void Render(RenderContext renderContext, float opacity) - { - if (!readyToRender) - { - return; - } - - if (dirty && !(ISSLayer)) - { - Reload(); - } - Matrix3d oldWorld = renderContext.World; - - Vector3d offset = mesh.BoundingSphere.Center; - double unitScale = 1.0f; - if (mesh.BoundingSphere.Radius > 0.0f) - { - unitScale = 1.0f / mesh.BoundingSphere.Radius; - } - //renderContext.World = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.RotationY(Math.PI),Matrix3d.Translation(Vector3d.Create(-offset.X, -offset.Y, -offset.Z))), Matrix3d.Scaling(unitScale, unitScale, unitScale)), oldWorld); - renderContext.World = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.Translation(Vector3d.Create(-offset.X, -offset.Y, -offset.Z)), Matrix3d.Scaling(unitScale, unitScale, unitScale)), oldWorld); - - Matrix3d worldView = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View); - Vector3d v = worldView.Transform(Vector3d.Empty); - double scaleFactor = Math.Sqrt(worldView.M11 * worldView.M11 + worldView.M22 * worldView.M22 + worldView.M33 * worldView.M33) / unitScale; - double dist = v.Length(); - double radius = scaleFactor; - - // Calculate pixelsPerUnit which is the number of pixels covered - // by an object 1 AU at the distance of the planet center from - // the camera. This calculation works regardless of the projection - // type. - int viewportHeight = (int)renderContext.Height; - double p11 = renderContext.Projection.M11; - double p34 = renderContext.Projection.M34; - double p44 = renderContext.Projection.M44; - - - double w = Math.Abs(p34) * dist + p44; - float pixelsPerUnit = (float)(p11 / w) * viewportHeight; - float radiusInPixels = (float)(radius * pixelsPerUnit); - if (radiusInPixels < 0.5f) - { - // Too small to be visible; skip rendering - return; - } - - // These colors can be modified by shadows, distance from planet, etc. Restore - // the original values after rendering. - Color savedSunlightColor = renderContext.SunlightColor; - Color savedReflectedColor = renderContext.ReflectedLightColor; - Color savedHemiColor = renderContext.HemisphereLightColor; - - if (Settings.Current.SolarSystemLighting) - { - SetupLighting(renderContext); - if (!UseCurrentAmbient) - { - renderContext.AmbientLightColor = Color.FromArgb(255, 11, 11, 11); - } - } - else - { - // No lighting: set ambient light to white and turn off all other light sources - renderContext.SunlightColor = Colors.Black; - renderContext.ReflectedLightColor = Colors.Black; - renderContext.HemisphereLightColor = Colors.Black; - renderContext.AmbientLightColor = Colors.White; - } - - - if (mesh == null) - { - return; - } - - ModelShader.MinLightingBrightness = .1f; - - //renderContext.DepthStencilMode = DepthStencilMode.ZReadWrite; - //renderContext.BlendMode = BlendMode.Alpha; - - int count = meshMaterials.Count; - - mesh.beginDrawing(renderContext); - if (count > 0) - { - for (int i = 0; i < meshMaterials.Count; i++) - { - if (meshMaterials[i].IsDefault) - { - Material mat = meshMaterials[i]; - mat.Diffuse = Color; - mat.Ambient = Color; - meshMaterials[i] = mat; - } - // Set the material and texture for this subset - renderContext.SetMaterial(meshMaterials[i], meshTextures[i], meshSpecularTextures[i], meshNormalMaps[i], opacity); - if (mesh.vertexBuffer != null) - { - ModelShader.Use(renderContext, mesh.vertexBuffer.VertexBuffer, mesh.indexBuffer.Buffer, meshTextures[i]!= null ? meshTextures[i].Texture2d : null, opacity, false,32); - } - else - { - ModelShader.Use(renderContext, mesh.tangentVertexBuffer.VertexBuffer, mesh.indexBuffer.Buffer, meshTextures[i] != null ? meshTextures[i].Texture2d : null, opacity, false,44); - - } - renderContext.PreDraw(); - //todo renderContext.setSamplerState(0, renderContext.WrapSampler); - mesh.drawSubset(renderContext, i); - } - } - else - { - renderContext.PreDraw(); - for (int i = 0; i < meshTextures.Count; i++) - { - //todo - //var key = new PlanetShaderKey(PlanetSurfaceStyle.Diffuse, false, 0); - //renderContext.SetupPlanetSurfaceEffect(key, 1.0f); - if (meshTextures[i] != null) - { - renderContext.MainTexture = meshTextures[i]; - if (mesh.vertexBuffer != null) - { - ModelShader.Use(renderContext, mesh.vertexBuffer.VertexBuffer, mesh.indexBuffer.Buffer, meshTextures[i] != null ? meshTextures[i].Texture2d : null, opacity, false, 32); - } - else - { - ModelShader.Use(renderContext, mesh.tangentVertexBuffer.VertexBuffer, mesh.indexBuffer.Buffer, meshTextures[i] != null ? meshTextures[i].Texture2d : null, opacity, false, 44); - - } - } - renderContext.PreDraw(); - mesh.drawSubset(renderContext, i); - } - } - - - - - //todo - //renderContext.setSamplerState(0, renderContext.ClampSampler); - - //renderContext.setRasterizerState(TriangleCullMode.CullClockwise); - renderContext.World = oldWorld; - - - - renderContext.SunlightColor = savedSunlightColor; - renderContext.ReflectedLightColor = savedReflectedColor; - renderContext.HemisphereLightColor = savedHemiColor; - renderContext.AmbientLightColor = Colors.Black; - - - - - } - - public bool UseCurrentAmbient = false; - - bool dirty = true; - - static void DisposeTextureList(List textures) - { - if (textures != null) - { - for (int i = 0; i < textures.Count; ++i) - { - if (textures[i] != null) - { - textures[i].Dispose(); - textures[i] = null; - } - } - - textures.Clear(); - } - } - - public void Dispose() - { - if (mesh != null) - { - mesh.Dispose(); - mesh = null; - } - - foreach (string key in TextureCache.Keys) - { - Texture tex = TextureCache[key]; - if (tex != null) - { - tex.Dispose(); - } - } - TextureCache.Clear(); - - DisposeTextureList(meshTextures); - DisposeTextureList(meshSpecularTextures); - DisposeTextureList(meshNormalMaps); - - meshMaterials.Clear(); - dirty = true; - } - } - - public class ObjectNode - { - public string Name; - public int Level = -1; - public List Children = new List(); - public ObjectNode Parent; - public bool Enabled = true; - public Vector3d PivotPoint; - public Matrix3d LocalMat; - public List DrawGroup = new List(); - public List ApplyLists = new List(); - public List ApplyListsIndex = new List(); - public ObjectNode() - { - } - - } - - - public class Object3dLayerUI : LayerUI - { - Object3dLayer layer = null; - bool opened = true; - - public Object3dLayerUI(Object3dLayer layer) - { - this.layer = layer; - } - IUIServicesCallbacks callbacks = null; - - public override void SetUICallbacks(IUIServicesCallbacks callbacks) - { - this.callbacks = callbacks; - } - public override bool HasTreeViewNodes - { - get - { - return true; - } - } - - public override List GetTreeNodes() - { - List nodes = new List(); - if (layer.object3d.Objects.Count > 0 && layer.object3d.Objects[0].Children != null) - { - LoadTree(nodes, layer.object3d.Objects[0].Children); - } - return nodes; - } - - void LoadTree(List nodes, List children) - { - foreach (ObjectNode child in children) - { - LayerUITreeNode node = new LayerUITreeNode(); - node.Name = child.Name; - node.Tag = child; - node.Checked = child.Enabled; - node.NodeSelected += new LayerUITreeNodeSelectedDelegate(node_NodeSelected); - node.NodeChecked += new LayerUITreeNodeCheckedDelegate(node_NodeChecked); - nodes.Add(node); - LoadTree(node.Nodes, child.Children); - } - } - - - void node_NodeChecked(LayerUITreeNode node, bool newState) - { - ObjectNode child = (ObjectNode)node.Tag; - - if (child != null) - { - child.Enabled = newState; - } - } - - - - void node_NodeSelected(LayerUITreeNode node) - { - if (callbacks != null) - { - ObjectNode child = (ObjectNode)node.Tag; - - Dictionary rowData = new Dictionary(); - - rowData["Name"] = child.Name; - rowData["Pivot.X"] = child.PivotPoint.X.ToString(); - rowData["Pivot.Y"] = child.PivotPoint.Y.ToString(); - rowData["Pivot.Z"] = child.PivotPoint.Z.ToString(); - callbacks.ShowRowData(rowData); - - //Object3dLayer.sketch.Clear(); - //Object3dLayer.sketch.AddLine(Vector3d.Create(0, 0, 0), Vector3d.Create(child.PivotPoint.X,-child.PivotPoint.Z,child.PivotPoint.Y)); - } - } - - public override List GetNodeContextMenu(LayerUITreeNode node) - { - return base.GetNodeContextMenu(node); - } - } -} diff --git a/engine/csharp_ref/Layers/Orbit.cs b/engine/csharp_ref/Layers/Orbit.cs deleted file mode 100644 index 93c6d6aa..00000000 --- a/engine/csharp_ref/Layers/Orbit.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; -namespace wwtlib -{ - public class Orbit - { - private EOE elements = null; - - Color orbitColor = Colors.White; - float scale; - public Orbit(EOE elements, int segments, Color color, float thickness, float scale) - { - this.elements = elements; - this.segmentCount = segments; - this.orbitColor = color; - this.scale = scale; - } - public void CleanUp() - { - - } - - // Get the radius of a sphere (centered at a focus of the ellipse) that is - // large enough to contain the orbit. The value returned has units of the orbit scale. - public double BoundingRadius - { - get - { - if (elements != null) - { - return (elements.a * (1.0 + elements.e)) / scale; - } - else - { - return 0.0; - } - } - } - - // Convert from standard coordinate system with z normal to the orbital plane - // to WWT's system where y is the normal. Note that this transformation is not - // a pure rotation: it incorporates a reflection, because the two systems have - // different handedness. - static Matrix3d orbitalToWwt = Matrix3d.Create(1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 0.0, 1.0); - - static bool initBegun = false; - // ** Begin - public void Draw3D(RenderContext renderContext, float opacity, Vector3d centerPoint) - { - Matrix3d orbitalPlaneOrientation = Matrix3d.MultiplyMatrix(Matrix3d.RotationZ(Coordinates.DegreesToRadians(elements.w)), - Matrix3d.MultiplyMatrix( Matrix3d.RotationX(Coordinates.DegreesToRadians(elements.i)), - Matrix3d.RotationZ(Coordinates.DegreesToRadians(elements.omega)))); - - // Extra transformation required because the ellipse shader uses the xy-plane, but WWT uses the - // xz-plane as the reference. - orbitalPlaneOrientation = Matrix3d.MultiplyMatrix(orbitalPlaneOrientation, orbitalToWwt); - - Matrix3d worldMatrix = Matrix3d.MultiplyMatrix( Matrix3d.MultiplyMatrix(orbitalPlaneOrientation , Matrix3d.Translation(centerPoint)), renderContext.World); - - double M = elements.n * (SpaceTimeController.JNow - elements.T); - double F = 1; - if (M < 0) - { - F = -1; - } - M = Math.Abs(M) / 360.0; - M = (M - (int)(M)) * 360.0 * F; - - Color color = Color.FromArgbColor((int)(opacity * 255.0f), orbitColor); - - // Newton-Raphson iteration to solve Kepler's equation. - // This is faster than calling CAAKepler.Calculate(), and 5 steps - // is more than adequate for draw the orbit paths of small satellites - // (which are ultimately rendered using single-precision floating point.) - M = Coordinates.DegreesToRadians(M); - double E = M; - for (int i = 0; i < 5; i++) - { - E += (M - E + elements.e * Math.Sin(E)) / (1 - elements.e * Math.Cos(E)); - } - - EllipseRenderer.DrawEllipse(renderContext, elements.a / scale, elements.e, E, color, worldMatrix); - } - - //VertexBuffer orbitVertexBuffer = null; - int segmentCount = 0; - } - - public class EllipseRenderer - { - private static PositionVertexBuffer ellipseVertexBuffer; - private static PositionVertexBuffer ellipseWithoutStartPointVertexBuffer; - private static EllipseShader ellipseShader; - - - // Draw an ellipse with the specified semi-major axis and eccentricity. The orbit is drawn over a single period, - // fading from full brightness at the given eccentric anomaly. - // - // In order to match exactly the position at which a planet is drawn, the planet's position at the current time - // must be passed as a parameter. positionNow is in the current coordinate system of the render context, not the - // translated and rotated system of the orbital plane. - public static void DrawEllipseWithPosition(RenderContext renderContext, double semiMajorAxis, double eccentricity, double eccentricAnomaly, Color color, Matrix3d worldMatrix, Vector3d positionNow) - { - if (ellipseShader == null) - { - ellipseShader = new EllipseShader(); - } - - if (ellipseVertexBuffer == null) - { - ellipseVertexBuffer = CreateEllipseVertexBuffer(500); - } - - Matrix3d savedWorld = renderContext.World; - renderContext.World = worldMatrix; - - renderContext.gl.bindBuffer(GL.ARRAY_BUFFER, ellipseVertexBuffer.VertexBuffer); - renderContext.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - - EllipseShader.Use(renderContext, (float)semiMajorAxis, (float)eccentricity, (float)eccentricAnomaly, color, 1.0f, savedWorld, positionNow); - - renderContext.gl.drawArrays(GL.LINE_STRIP, 0, ellipseVertexBuffer.Count); - - renderContext.World = savedWorld; - } - - - // This version of DrawEllipse works without a 'head' point - public static void DrawEllipse(RenderContext renderContext, double semiMajorAxis, double eccentricity, double eccentricAnomaly, Color color, Matrix3d worldMatrix) - { - if (ellipseShader == null) - { - ellipseShader = new EllipseShader(); - } - - if (ellipseWithoutStartPointVertexBuffer == null) - { - ellipseWithoutStartPointVertexBuffer = CreateEllipseVertexBufferWithoutStartPoint(360); - } - - Matrix3d savedWorld = renderContext.World; - renderContext.World = worldMatrix; - - renderContext.gl.bindBuffer(GL.ARRAY_BUFFER, ellipseWithoutStartPointVertexBuffer.VertexBuffer); - renderContext.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); - EllipseShader.Use(renderContext, (float)semiMajorAxis, (float)eccentricity, (float)eccentricAnomaly, color, 1.0f, savedWorld, Vector3d.Create(0.0, 0.0, 0.0)); - - renderContext.gl.drawArrays(GL.LINE_STRIP, 0, ellipseWithoutStartPointVertexBuffer.Count-1); - - renderContext.World = savedWorld; - } - - - public static PositionVertexBuffer CreateEllipseVertexBuffer(int vertexCount) - { - PositionVertexBuffer vb = new PositionVertexBuffer(vertexCount); - Vector3d[] verts = vb.Lock(); - int index = 0; - // Pack extra samples into the front of the orbit to avoid obvious segmentation - // when viewed from near the planet or moon. - for (int i = 0; i < vertexCount / 2; ++i) - { - verts[index++] = Vector3d.Create(2.0f * (float)i / (float)vertexCount * 0.05f, 0.0f, 0.0f); - } - for (int i = 0; i < vertexCount / 2; ++i) - { - verts[index++] = Vector3d.Create(2.0f * (float)i / (float)vertexCount * 0.95f + 0.05f, 0.0f, 0.0f); - } - - vb.Unlock(); - - return vb; - } - - public static PositionVertexBuffer CreateEllipseVertexBufferWithoutStartPoint(int vertexCount) - { - PositionVertexBuffer vb = new PositionVertexBuffer(vertexCount); - Vector3d[] verts = vb.Lock(); - - // Setting a non-zero value will prevent the ellipse shader from using the 'head' point - verts[0] = Vector3d.Create(1.0e-6f, 0.0f, 0.0f); - - for (int i = 1; i < vertexCount; ++i) - { - verts[i] = Vector3d.Create(2.0f * (float)i / (float)vertexCount, 0.0f, 0.0f); - } - - vb.Unlock(); - - return vb; - } - } -} diff --git a/engine/csharp_ref/Layers/OrbitLayer.cs b/engine/csharp_ref/Layers/OrbitLayer.cs deleted file mode 100644 index 712e51dc..00000000 --- a/engine/csharp_ref/Layers/OrbitLayer.cs +++ /dev/null @@ -1,316 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Data.Files; - -namespace wwtlib -{ - public class OrbitLayer : Layer - { - List frames = new List(); - - public List Frames - { - get { return frames; } - set { frames = value; } - } - - OrbitLayerUI primaryUI = null; - public override LayerUI GetPrimaryUI() - { - if (primaryUI == null) - { - primaryUI = new OrbitLayerUI(this); - } - - return primaryUI; - } - - public OrbitLayer() - { - } - - public override void CleanUp() - { - foreach (ReferenceFrame frame in frames) - { - if (frame.Orbit != null) - { - frame.Orbit.CleanUp(); - frame.Orbit = null; - } - } - } - - public override void WriteLayerProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteAttributeString("PointOpacity", PointOpacity.ToString()); - xmlWriter.WriteAttributeString("PointColor", pointColor.Save()); - - } - - private double pointOpacity = 1; - - - public double PointOpacity - { - get { return pointOpacity; } - set - { - if (pointOpacity != value) - { - version++; - - pointOpacity = value; - - } - } - } - - Color pointColor = Colors.Yellow; - - - public Color PointColor - { - get { return pointColor; } - set - { - if (pointColor != value) - { - version++; - pointColor = value; - - } - } - } - - public override double[] GetParams() - { - double[] paramList = new double[6]; - paramList[0] = pointOpacity; - paramList[1] = Color.R / 255; - paramList[2] = Color.G / 255; - paramList[3] = Color.B / 255; - paramList[4] = Color.A / 255; - paramList[5] = Opacity; - - - return paramList; - } - - public override string[] GetParamNames() - { - return new string[] { "PointOpacity", "Color.Red", "Color.Green", "Color.Blue", "Color.Alpha", "Opacity" }; - } - - //public override BaseTweenType[] GetParamTypes() - //{ - // return new BaseTweenType[] { BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear, BaseTweenType.Linear }; - //} - - public override void SetParams(double[] paramList) - { - if (paramList.Length == 6) - { - pointOpacity = paramList[0]; - Opacity = (float)paramList[5]; - Color color = Color.FromArgb((int)(paramList[4] * 255), (int)(paramList[1] * 255), (int)(paramList[2] * 255), (int)(paramList[3] * 255)); - Color = color; - - } - } - - - public override void InitializeFromXml(XmlNode node) - { - PointOpacity = double.Parse(node.Attributes.GetNamedItem("PointOpacity").Value); - PointColor = Color.Load(node.Attributes.GetNamedItem("PointColor").Value); - - } - - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - Matrix3d matSaved = renderContext.World; - renderContext.World = renderContext.WorldBaseNonRotating; - - foreach (ReferenceFrame frame in frames) - { - if (frame.ShowOrbitPath) - { - if (frame.Orbit == null) - { - frame.Orbit = new Orbit(frame.Elements, 360, this.Color, 1, (float)renderContext.NominalRadius); - } - frame.Orbit.Draw3D(renderContext, opacity * this.Opacity, new Vector3d()); - } - } - renderContext.World = matSaved; - return true; - } - - string filename = ""; - - public override void AddFilesToCabinet(FileCabinet fc) - { - filename = fc.TempDirectory + string.Format("{0}\\{1}.txt", fc.PackageID, this.ID.ToString()); - - string dir = filename.Substring(0, filename.LastIndexOf("\\")); - - Blob blob = new Blob(new object[] { dataFile }); - - fc.AddFile(filename, blob); - - base.AddFilesToCabinet(fc); - - } - - string dataFile = ""; - - public override void LoadData(TourDocument tourDoc, string filename) - { - Blob blob = tourDoc.GetFileBlob(filename); - FileReader doc = new FileReader(); - doc.OnLoadEnd = delegate (FileProgressEvent ee) - { - dataFile = doc.Result as string; - LoadString(dataFile); - - }; - doc.ReadAsText(blob); - } - - public void LoadString(string dataFile) - { - string[] data = dataFile.Split("\n"); - frames.Clear(); - for (int i = 0; i < data.Length; i += 2) - { - int line1 = i; - int line2 = i + 1; - if (data[i].Length > 0) - { - ReferenceFrame frame = new ReferenceFrame(); - if (data[i].Substring(0, 1) != "1") - { - line1++; - line2++; - frame.Name = data[i].Trim(); - i++; - } - else if (data[i].Substring(0, 1) == "1") - { - frame.Name = data[i].Substring(2, 5); - } - else - { - i -= 2; - continue; - } - - frame.Reference = ReferenceFrames.Custom; - frame.Oblateness = 0; - frame.ShowOrbitPath = true; - frame.ShowAsPoint = true; - frame.ReferenceFrameType = ReferenceFrameTypes.Orbital; - frame.Scale = 1; - frame.SemiMajorAxisUnits = AltUnits.Meters; - frame.MeanRadius = 10; - frame.Oblateness = 0; - frame.FromTLE(data[line1], data[line2], 398600441800000); - frames.Add(frame); - } - else - { - i -= 1; - } - } - } - } - - - - public class OrbitLayerUI : LayerUI - { - OrbitLayer layer = null; - bool opened = true; - - public OrbitLayerUI(OrbitLayer layer) - { - this.layer = layer; - } - IUIServicesCallbacks callbacks = null; - - public override void SetUICallbacks(IUIServicesCallbacks callbacks) - { - this.callbacks = callbacks; - } - public override bool HasTreeViewNodes - { - get - { - return true; - } - } - - public override List GetTreeNodes() - { - List nodes = new List(); - foreach (ReferenceFrame frame in layer.Frames) - { - - LayerUITreeNode node = new LayerUITreeNode(); - node.Name = frame.Name; - - - node.Tag = frame; - node.Checked = frame.ShowOrbitPath; - node.NodeSelected += new LayerUITreeNodeSelectedDelegate(node_NodeSelected); - node.NodeChecked += new LayerUITreeNodeCheckedDelegate(node_NodeChecked); - nodes.Add(node); - } - return nodes; - } - - void node_NodeChecked(LayerUITreeNode node, bool newState) - { - ReferenceFrame frame = (ReferenceFrame)node.Tag; - - if (frame != null) - { - frame.ShowOrbitPath = newState; - } - } - - - - void node_NodeSelected(LayerUITreeNode node) - { - if (callbacks != null) - { - ReferenceFrame frame = (ReferenceFrame)node.Tag; - - Dictionary rowData = new Dictionary(); - - rowData["Name"] = frame.Name; - rowData["SemiMajor Axis"] = frame.SemiMajorAxis.ToString(); - rowData["SMA Units"] = frame.SemiMajorAxisUnits.ToString(); - rowData["Inclination"] = frame.Inclination.ToString(); - rowData["Eccentricity"] = frame.Eccentricity.ToString(); - rowData["Long of Asc. Node"] = frame.LongitudeOfAscendingNode.ToString(); - rowData["Argument Of Periapsis"] = frame.ArgumentOfPeriapsis.ToString(); - rowData["Epoch"] = frame.Epoch.ToString(); - rowData["Mean Daily Motion"] = frame.MeanDailyMotion.ToString(); - rowData["Mean Anomoly at Epoch"] = frame.MeanAnomolyAtEpoch.ToString(); - callbacks.ShowRowData(rowData); - } - } - - public override List GetNodeContextMenu(LayerUITreeNode node) - { - return base.GetNodeContextMenu(node); - } - } -} diff --git a/engine/csharp_ref/Layers/ReferenceFrame.cs b/engine/csharp_ref/Layers/ReferenceFrame.cs deleted file mode 100644 index 4a312375..00000000 --- a/engine/csharp_ref/Layers/ReferenceFrame.cs +++ /dev/null @@ -1,811 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public enum ReferenceFrameTypes { FixedSherical=0, Orbital=1, Trajectory = 2, Synodic = 3 /*,FixedRectangular*/ }; - public class ReferenceFrame - { - public ReferenceFrame() - { - WorldMatrix = new Matrix3d(); - WorldMatrix = Matrix3d.Identity; - } - - internal bool SystemGenerated = false; - // Calclulated - public Vector3d Position; - public double MeanAnomoly; - public Matrix3d WorldMatrix; - public double OrbitalYears; - - public bool ObservingLocation = false; - - // Serialized - public string Name; - public string Parent; - public ReferenceFrames Reference = ReferenceFrames.Custom; - public bool ParentsRoationalBase = false; - public ReferenceFrameTypes ReferenceFrameType = ReferenceFrameTypes.FixedSherical; - public double MeanRadius = 6371000; - public double Oblateness = 0.0033528; - public double Heading; - public double Pitch; - public double Roll; - public double Scale = 1; - public double Tilt; - public Vector3d Translation = new Vector3d(); - - // For Sphetical Offset - public double Lat; - public double Lng; - public double Altitude; - // For Rotating frames - public double RotationalPeriod; // Days - public double ZeroRotationDate; // Julian decimal - - // For representing orbits & distant point location - public Color representativeColor = Colors.White; // Used for orbits and points - public Color RepresentativeColor - { - get - { - return representativeColor; - } - set - { - if (value != representativeColor) - { - representativeColor = value; - //todo add lines back - //trajectoryLines = null; - orbit = null; - } - } - } - public bool ShowAsPoint = false; - public bool ShowOrbitPath = false; - public bool StationKeeping = true; - - public double SemiMajorAxis; // a Au's - public AltUnits SemiMajorAxisUnits = AltUnits.Meters; - public double Eccentricity; // e - public double Inclination; // i - public double ArgumentOfPeriapsis; // w - public double LongitudeOfAscendingNode; // Omega - public double MeanAnomolyAtEpoch; // M - public double MeanDailyMotion; // n .degrees day - public double Epoch; // Standard Equinox - private Orbit orbit = null; - - public Orbit Orbit - { - get - { - return orbit; - } - set { orbit = value; } - } - //todo add this back - //public LineList trajectoryLines = null; - EOE elements = new EOE(); - - public string GetIndentifier() - { - return Name; - } - - // public List Trajectory = new List(); - - public void ImportTrajectory(string filename) - { - //Trajectory.Clear(); - //string[] data = File.ReadAllLines(filename); - //foreach (string line in data) - //{ - // Trajectory.Add(new TrajectorySample(line)); - //} - } - - //public virtual void SaveToXml(System.Xml.XmlTextWriter xmlWriter) - //{ - // xmlWriter.WriteStartElement("ReferenceFrame"); - // xmlWriter.WriteAttributeString("Name", Name); - // xmlWriter.WriteAttributeString("Parent", Parent); - // xmlWriter.WriteAttributeString("ReferenceFrameType", ReferenceFrameType.ToString()); - // xmlWriter.WriteAttributeString("Reference", Reference.ToString()); - // xmlWriter.WriteAttributeString("ParentsRoationalBase",ParentsRoationalBase.ToString() ); - // xmlWriter.WriteAttributeString("MeanRadius", MeanRadius.ToString()); - // xmlWriter.WriteAttributeString("Oblateness", Oblateness.ToString()); - // xmlWriter.WriteAttributeString("Heading", Heading.ToString()); - // xmlWriter.WriteAttributeString("Pitch", Pitch.ToString()); - // xmlWriter.WriteAttributeString("Roll", Roll.ToString()); - // xmlWriter.WriteAttributeString("Scale", Scale.ToString()); - // xmlWriter.WriteAttributeString("Tilt", Tilt.ToString()); - // xmlWriter.WriteAttributeString("Translation", Translation.ToString()); - // if (ReferenceFrameType == ReferenceFrameTypes.FixedSherical) - // { - // xmlWriter.WriteAttributeString("Lat", Lat.ToString()); - // xmlWriter.WriteAttributeString("Lng", Lng.ToString()); - // xmlWriter.WriteAttributeString("Altitude", Altitude.ToString()); - // } - // xmlWriter.WriteAttributeString("RotationalPeriod", RotationalPeriod.ToString()); - // xmlWriter.WriteAttributeString("ZeroRotationDate", ZeroRotationDate.ToString()); - // xmlWriter.WriteAttributeString("RepresentativeColor",SavedColor.Save(RepresentativeColor)); - // xmlWriter.WriteAttributeString("ShowAsPoint", ShowAsPoint.ToString()); - // xmlWriter.WriteAttributeString("StationKeeping", StationKeeping.ToString()); - // if (ReferenceFrameType == ReferenceFrameTypes.Orbital) - // { - // xmlWriter.WriteAttributeString("ShowOrbitPath", ShowOrbitPath.ToString()); - // xmlWriter.WriteAttributeString("SemiMajorAxis", SemiMajorAxis.ToString()); - // xmlWriter.WriteAttributeString("SemiMajorAxisScale", this.SemiMajorAxisUnits.ToString()); - // xmlWriter.WriteAttributeString("Eccentricity", Eccentricity.ToString()); - // xmlWriter.WriteAttributeString("Inclination", Inclination.ToString()); - // xmlWriter.WriteAttributeString("ArgumentOfPeriapsis", ArgumentOfPeriapsis.ToString()); - // xmlWriter.WriteAttributeString("LongitudeOfAscendingNode", LongitudeOfAscendingNode.ToString()); - // xmlWriter.WriteAttributeString("MeanAnomolyAtEpoch", MeanAnomolyAtEpoch.ToString()); - // xmlWriter.WriteAttributeString("MeanDailyMotion", MeanDailyMotion.ToString()); - // xmlWriter.WriteAttributeString("Epoch", Epoch.ToString()); - // } - - // xmlWriter.WriteEndElement(); - //} - - public virtual void SaveToXml(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("ReferenceFrame"); - xmlWriter.WriteAttributeString("Name", Name); - xmlWriter.WriteAttributeString("Parent", Parent); - xmlWriter.WriteAttributeString("ReferenceFrameType", Enums.ToXml("ReferenceFrameTypes", (int)ReferenceFrameType)); - xmlWriter.WriteAttributeString("Reference", Enums.ToXml("ReferenceFrames",(int)Reference)); - xmlWriter.WriteAttributeString("ParentsRoationalBase", ParentsRoationalBase.ToString()); - xmlWriter.WriteAttributeString("MeanRadius", MeanRadius.ToString()); - xmlWriter.WriteAttributeString("Oblateness", Oblateness.ToString()); - xmlWriter.WriteAttributeString("Heading", Heading.ToString()); - xmlWriter.WriteAttributeString("Pitch", Pitch.ToString()); - xmlWriter.WriteAttributeString("Roll", Roll.ToString()); - xmlWriter.WriteAttributeString("Scale", Scale.ToString()); - xmlWriter.WriteAttributeString("Tilt", Tilt.ToString()); - xmlWriter.WriteAttributeString("Translation", Translation.ToString()); - if (ReferenceFrameType == ReferenceFrameTypes.FixedSherical) - { - xmlWriter.WriteAttributeString("Lat", Lat.ToString()); - xmlWriter.WriteAttributeString("Lng", Lng.ToString()); - xmlWriter.WriteAttributeString("Altitude", Altitude.ToString()); - } - xmlWriter.WriteAttributeString("RotationalPeriod", RotationalPeriod.ToString()); - xmlWriter.WriteAttributeString("ZeroRotationDate", ZeroRotationDate.ToString()); - xmlWriter.WriteAttributeString("RepresentativeColor", RepresentativeColor.Save()); - xmlWriter.WriteAttributeString("ShowAsPoint", ShowAsPoint.ToString()); - xmlWriter.WriteAttributeString("ShowOrbitPath", ShowOrbitPath.ToString()); - - xmlWriter.WriteAttributeString("StationKeeping", StationKeeping.ToString()); - - if (ReferenceFrameType == ReferenceFrameTypes.Orbital) - { - xmlWriter.WriteAttributeString("SemiMajorAxis", SemiMajorAxis.ToString()); - xmlWriter.WriteAttributeString("SemiMajorAxisScale", Enums.ToXml("AltUnits", (int)SemiMajorAxisUnits)); - xmlWriter.WriteAttributeString("Eccentricity", Eccentricity.ToString()); - xmlWriter.WriteAttributeString("Inclination", Inclination.ToString()); - xmlWriter.WriteAttributeString("ArgumentOfPeriapsis", ArgumentOfPeriapsis.ToString()); - xmlWriter.WriteAttributeString("LongitudeOfAscendingNode", LongitudeOfAscendingNode.ToString()); - xmlWriter.WriteAttributeString("MeanAnomolyAtEpoch", MeanAnomolyAtEpoch.ToString()); - xmlWriter.WriteAttributeString("MeanDailyMotion", MeanDailyMotion.ToString()); - xmlWriter.WriteAttributeString("Epoch", Epoch.ToString()); - } - - - //todo add this back when we support trajectories - //if (ReferenceFrameType == ReferenceFrameTypes.Trajectory) - //{ - // xmlWriter.WriteStartElement("Trajectory"); - - // foreach (TrajectorySample sample in Trajectory) - // { - // string data = sample.ToString(); - // xmlWriter.WriteElementString("Sample", data); - // } - // xmlWriter.WriteEndElement(); - //} - - xmlWriter.WriteEndElement(); - } - - - public virtual void InitializeFromXml(XmlNode node) - { - Name = node.Attributes.GetNamedItem("Name").Value; - Parent = node.Attributes.GetNamedItem("Parent").Value; - ReferenceFrameType = (ReferenceFrameTypes)Enums.Parse("ReferenceFrameTypes", node.Attributes.GetNamedItem("ReferenceFrameType").Value); - - Reference = (ReferenceFrames)Enums.Parse("ReferenceFrames", node.Attributes.GetNamedItem("Reference").Value); - - ParentsRoationalBase = Boolean.Parse(node.Attributes.GetNamedItem("ParentsRoationalBase").Value); - MeanRadius = Double.Parse(node.Attributes.GetNamedItem("MeanRadius").Value); - Oblateness = Double.Parse(node.Attributes.GetNamedItem("Oblateness").Value); - Heading = Double.Parse(node.Attributes.GetNamedItem("Heading").Value); - Pitch = Double.Parse(node.Attributes.GetNamedItem("Pitch").Value); - Roll = Double.Parse(node.Attributes.GetNamedItem("Roll").Value); - Scale = Double.Parse(node.Attributes.GetNamedItem("Scale").Value); - Tilt = Double.Parse(node.Attributes.GetNamedItem("Tilt").Value); - Translation = Vector3d.Parse(node.Attributes.GetNamedItem("Translation").Value); - if (ReferenceFrameType == ReferenceFrameTypes.FixedSherical) - { - Lat = Double.Parse(node.Attributes.GetNamedItem("Lat").Value); - Lng = Double.Parse(node.Attributes.GetNamedItem("Lng").Value); - Altitude = Double.Parse(node.Attributes.GetNamedItem("Altitude").Value); - } - - RotationalPeriod = Double.Parse(node.Attributes.GetNamedItem("RotationalPeriod").Value); - ZeroRotationDate = Double.Parse(node.Attributes.GetNamedItem("ZeroRotationDate").Value); - RepresentativeColor = Color.Load(node.Attributes.GetNamedItem("RepresentativeColor").Value); - ShowAsPoint = Boolean.Parse(node.Attributes.GetNamedItem("ShowAsPoint").Value); - if (node.Attributes.GetNamedItem("StationKeeping")!= null) - { - StationKeeping = Boolean.Parse(node.Attributes.GetNamedItem("StationKeeping").Value); - } - - if (ReferenceFrameType == ReferenceFrameTypes.Orbital) - { - ShowOrbitPath = Boolean.Parse(node.Attributes.GetNamedItem("ShowOrbitPath").Value); - SemiMajorAxis = Double.Parse(node.Attributes.GetNamedItem("SemiMajorAxis").Value); - - SemiMajorAxisUnits = (AltUnits)Enums.Parse("AltUnits", node.Attributes.GetNamedItem("SemiMajorAxisScale").Value); - - Eccentricity = Double.Parse(node.Attributes.GetNamedItem("Eccentricity").Value); - Inclination = Double.Parse(node.Attributes.GetNamedItem("Inclination").Value); - ArgumentOfPeriapsis = Double.Parse(node.Attributes.GetNamedItem("ArgumentOfPeriapsis").Value); - LongitudeOfAscendingNode = Double.Parse(node.Attributes.GetNamedItem("LongitudeOfAscendingNode").Value); - MeanAnomolyAtEpoch = Double.Parse(node.Attributes.GetNamedItem("MeanAnomolyAtEpoch").Value); - MeanDailyMotion = Double.Parse(node.Attributes.GetNamedItem("MeanDailyMotion").Value); - Epoch = Double.Parse(node.Attributes.GetNamedItem("Epoch").Value); - - } - } - - public void FromTLE(string line1, string line2, double gravity) - { - Epoch = SpaceTimeController.TwoLineDateToJulian(line1.Substr(18, 14)); - Eccentricity = double.Parse("0." + line2.Substr(26, 7)); - Inclination = double.Parse(line2.Substr(8, 8)); - LongitudeOfAscendingNode = double.Parse(line2.Substr(17, 8)); - ArgumentOfPeriapsis = double.Parse(line2.Substr(34, 8)); - double revs = double.Parse(line2.Substr(52, 11)); - MeanAnomolyAtEpoch = double.Parse(line2.Substr(43, 8)); - MeanDailyMotion = revs * 360.0; - double part = (86400.0 / revs) / (Math.PI * 2.0); - SemiMajorAxis = Math.Pow((part * part) * gravity, 1.0 / 3.0); - SemiMajorAxisUnits = AltUnits.Meters; - - } - public static bool IsTLECheckSumGood(string line) - { - if (line.Length != 69) - { - return false; - } - - int checksum = 0; - for (int i = 0; i < 68; i++ ) - { - switch (line.Substr(i,1)) - { - case "1": - checksum += 1; - break; - case "2": - checksum += 2; - break; - case "3": - checksum += 3; - break; - case "4": - checksum += 4; - break; - case "5": - checksum += 5; - break; - case "6": - checksum += 6; - break; - case "7": - checksum += 7; - break; - case "8": - checksum += 8; - break; - case "9": - checksum += 9; - break; - case "-": - checksum += 1; - - break; - } - } - return (checksum % 10).ToString() == line.CharAt(68).ToString(); - - } - - public string ToTLE() - { - //Epoch need to convert to TLE time string. - // Ecentricity remove "0." from the begin and trim to 7 digits - // Inclination decimal degrees 8 digits max - // LOAN decimal degrees 8 digits - // AOP - // mean anomoly at epoch 8 digits - // Mean motion (revs per day) Compute - // Convert Semi-major-axis to meters from storage unit - // Compute revs - - StringBuilder line1 = new StringBuilder(); - - line1.Append("1 99999U 00111AAA "); - line1.Append(SpaceTimeController.JulianToTwoLineDate(Epoch)); - line1.Append(" "); - // line1.Append("-.00000001"); - line1.Append(SemiMajorAxis.ToExponential(4)); - line1.Append(" 00000-0 "); - line1.Append(ToTLEExponential(MeanDailyMotion, 5)); - //line1.Append("-00000-1 0 "); - line1.Append(" 001"); - line1.Append(ComputeTLECheckSum(line1.ToString())); - line1.AppendLine(""); - StringBuilder line2 = new StringBuilder(); - - line2.Append("2 99999 "); - line2.Append(TLENumberString(Inclination,3,4) + " "); - line2.Append(TLENumberString(LongitudeOfAscendingNode, 3, 4) + " "); - line2.Append((TLENumberString(Eccentricity, 1, 7) + " ").Substring(2)); - line2.Append(TLENumberString(ArgumentOfPeriapsis, 3, 4) + " "); - line2.Append(TLENumberString(MeanAnomolyAtEpoch, 3, 4) + " "); - line2.Append(ToTLEExponential(MeanDailyMotion / 207732, 5)); - line2.Append("00001"); - line2.Append(ComputeTLECheckSum(line2.ToString())); - line2.AppendLine(""); - return line1.ToString() + line2.ToString(); - } - - public static string ToTLEExponential(double num, int size) - { - string exp = num.ToExponential(size); - if (exp.Length < size+6) - { - exp = exp.Substring(0, size + 4) + "0" + exp.Substr(size + 4, 1); - } - return exp; - } - - public static string TLENumberString(double num, int left, int right) - { - string formated = num.ToFixed(right); - - int point = formated.IndexOf("."); - if (point == -1) - { - point = formated.Length; - formated += ".0"; - } - int len = formated.Length - point - 1; - - string fill = "00000000"; - - formated = fill.Substr(0, left - point) + formated + fill.Substr(0, right - len); - - return formated; - } - - public static char ComputeTLECheckSum(string line) - { - if (line.Length != 68) - { - return '0'; - } - - int checksum = 0; - for (int i = 0; i < 68; i++) - { - switch (line[i]) - { - case '1': - checksum += 1; - break; - case '2': - checksum += 2; - break; - case '3': - checksum += 3; - break; - case '4': - checksum += 4; - break; - case '5': - checksum += 5; - break; - case '6': - checksum += 6; - break; - case '7': - checksum += 7; - break; - case '8': - checksum += 8; - break; - case '9': - checksum += 9; - break; - case '-': - checksum += 1; - - break; - } - } - return (char)( (char)(checksum % 10)); - } - - public EOE Elements - { - get - { - elements.a = SemiMajorAxis; - elements.e = Eccentricity; - elements.i = Inclination; - //ArgumentOfPeriapsis += LongitudeOfAscendingNode; - elements.w = ArgumentOfPeriapsis; - elements.omega = LongitudeOfAscendingNode; - elements.JDEquinox = Epoch; - if (MeanDailyMotion == 0) - { - elements.n = ELL.MeanMotionFromSemiMajorAxis(elements.a); - } - else - { - elements.n = MeanDailyMotion; - } - elements.T = Epoch - (MeanAnomolyAtEpoch / elements.n); - return elements; - } - set { elements = value; } - } - - public void ComputeFrame(RenderContext renderContext) - { - switch (ReferenceFrameType) - { - case ReferenceFrameTypes.Orbital: - ComputeOrbital(renderContext); - break; - case ReferenceFrameTypes.FixedSherical: - ComputeFixedSherical(renderContext); - break; - case ReferenceFrameTypes.Trajectory: - ComputeFrameTrajectory(renderContext); - break; - // todo port synodic for JWST orbits.. - //case ReferenceFrameTypes.FixedRectangular: - // ComputeFixedRectangular(renderContext); - // break; - default: - break; - } - } - - public bool useRotatingParentFrame() - { - switch (ReferenceFrameType) - { - case ReferenceFrameTypes.Orbital: - case ReferenceFrameTypes.Trajectory: - case ReferenceFrameTypes.Synodic: - return false; - default: - return true; - } - } - - private void ComputeFixedRectangular(RenderContext renderContext) - { - //WorldMatrix = Matrix3d.Identity; - //WorldMatrix.Multiply(Matrix3d.RotationX( - //WorldMatrix.Rotate(Quaternion.RotationYawPitchRoll((float)Heading, (float)Pitch, (float)Roll)); - //WorldMatrix.Translate((Vector3d)Translation); - //WorldMatrix.Scale(new Vector3d(Scale, Scale, Scale)); - //WorldMatrix.Rotate(Quaternion.RotationYawPitchRoll((float)(Coordinates.MstFromUTC2(SpaceTimeController.Now, 0) / 180 * Math.PI), (float)0, (float)0)); - } - private void ComputeFixedSherical(RenderContext renderContext) - { - if (ObservingLocation) - { - Lat = SpaceTimeController.Location.Lat; - Lng = SpaceTimeController.Location.Lng; - Altitude = SpaceTimeController.Altitude; - } - - - WorldMatrix = Matrix3d.Identity; - WorldMatrix.Translate(Translation); - double localScale = (1 / renderContext.NominalRadius) * Scale * MeanRadius; - WorldMatrix.Scale( Vector3d.Create(localScale, localScale, localScale)); - //WorldMatrix.Scale(new Vector3d(1000, 1000, 1000)); - WorldMatrix.Multiply( Matrix3d.RotationYawPitchRoll((float)((Heading) / 180.0 * Math.PI), (float)(Pitch / 180.0 * Math.PI), (float)(Roll / 180.0 * Math.PI))); - WorldMatrix.Multiply(Matrix3d.RotationZ(-90.0 / 180.0 * Math.PI)); - if (RotationalPeriod != 0) - { - double rotationCurrent = (((SpaceTimeController.JNow - this.ZeroRotationDate) / RotationalPeriod) * Math.PI * 2) % (Math.PI * 2); - WorldMatrix.Multiply(Matrix3d.RotationX(-rotationCurrent)); - } - WorldMatrix.Translate( Vector3d.Create(1 + (Altitude / renderContext.NominalRadius), 0, 0)); - WorldMatrix.Multiply(Matrix3d.RotationZ(Lat / 180 * Math.PI)); - WorldMatrix.Multiply(Matrix3d.RotationY(-(Lng+180) / 180 * Math.PI)); - - - - //// Vector3d offset = Coordinates.GeoTo3dDouble(Lat, Lng, 1 + (Altitude / renderContext.NominalRadius)); - // WorldMatrix = Matrix3d.Identity; - // double localScale = (1 / renderContext.NominalRadius) * Scale * MeanRadius; - // WorldMatrix.Scale(new Vector3d(localScale, localScale, localScale)); - // //WorldMatrix.Scale(new Vector3d(1000, 1000, 1000)); - // WorldMatrix.Rotate(Quaternion.RotationYawPitchRoll((float)((Heading-90)/180.0*Math.PI), (float)Pitch, (float)Roll)); - // WorldMatrix.Multiply(Matrix3d.RotationZ(-90.0)); - // if (RotationalPeriod != 0) - // { - // double rotationCurrent = (((SpaceTimeController.JNow - this.ZeroRotationDate) / RotationalPeriod) * 360) % (360); - // WorldMatrix.Multiply(Matrix3d.RotationX(-rotationCurrent)); - // } - // WorldMatrix.Translate(new Vector3d(1 + (Altitude / renderContext.NominalRadius), 0, 0)); - // WorldMatrix.Multiply(Matrix3d.RotationZ(Lat)); - // WorldMatrix.Multiply(Matrix3d.RotationY(-(Lng) )); - } - - private void ComputeFrameTrajectory(RenderContext renderContext) - { - //Vector3d vector = new Vector3d(); - //Vector3d point = GetTragectoryPoint(SpaceTimeController.JNow, out vector); - - //Vector3d direction = vector; - - //direction.Normalize(); - //Vector3d up = point; - //up.Normalize(); - //direction.Normalize(); - - //double dist = point.Length(); - //double scaleFactor = 1.0; - ////scaleFactor = UiTools.KilometersPerAu * 1000; - //scaleFactor *= 1 / renderContext.NominalRadius; - - - //WorldMatrix = Matrix3d.Identity; - //Matrix3d look = Matrix3d.LookAtLH(new Vector3d(0, 0, 0), direction, new Vector3d(0,1,0)); - //look.Invert(); - - //WorldMatrix = Matrix3d.Identity; - - - //double localScale = (1 / renderContext.NominalRadius) * Scale * MeanRadius; - //WorldMatrix.Scale(new Vector3d(localScale, localScale, localScale)); - //WorldMatrix.Rotate(Quaternion.RotationYawPitchRoll((float)Heading, (float)Pitch, (float)Roll)); - //if (RotationalPeriod != 0) - //{ - // double rotationCurrent = (((SpaceTimeController.JNow - this.ZeroRotationDate) / RotationalPeriod) * 360) % (360); - // WorldMatrix.Multiply(Matrix3d.RotationX(-rotationCurrent)); - //} - - //point = Vector3d.Scale(point, scaleFactor); - - //WorldMatrix.Translate(point); - - //if (StationKeeping) - //{ - // WorldMatrix = look * WorldMatrix; - //} - } - - //private Vector3d GetTragectoryPoint(double jNow, out Vector3d vector) - //{ - //int min = 0; - //int max = Trajectory.Count - 1; - - //Vector3d point = new Vector3d(); - - //vector = new Vector3d(); - - //int current = max / 2; - - //bool found = false; - - //while (!found) - //{ - // if (current < 1) - // { - // vector = Trajectory[0].Position - Trajectory[1].Position; - // return Trajectory[0].Position; - // } - - - // if (current == Trajectory.Count - 1) - // { - // vector = Trajectory[current - 1].Position - Trajectory[current].Position; - // return Trajectory[current].Position; - // } - - // if ((Trajectory[current-1].Time <= jNow) && (Trajectory[current].Time > jNow)) - // { - // double denominator = Trajectory[current].Time -Trajectory[current-1].Time; - // double numerator = jNow - Trajectory[current - 1].Time; - // double tween = numerator / denominator; - // vector = Trajectory[current - 1].Position - Trajectory[current].Position; - // point = Vector3d.Lerp(Trajectory[current - 1].Position, Trajectory[current].Position, tween); - // return point; - // } - - // if (Trajectory[current].Time < jNow) - // { - // int next = current + ( max - current + 1) / 2; - // min = current; - // current = next; - // } - // else - // if (Trajectory[current - 1].Time > jNow) - // { - // int next = current - ( current - min + 1) / 2; - // max = current; - // current = next; - // } - //} - - //return point; - //} - - private void ComputeOrbital(RenderContext renderContext) - { - EOE ee = Elements; - Vector3d point = ELL.CalculateRectangularJD(SpaceTimeController.JNow, ee); - MeanAnomoly = ee.meanAnnomolyOut; - Vector3d pointInstantLater = ELL.CalculateRectangular(ee, MeanAnomoly+.001); - - Vector3d direction = Vector3d.SubtractVectors(point, pointInstantLater); - - Vector3d up = point.Copy(); - up.Normalize(); - direction.Normalize(); - - double dist = point.Length(); - double scaleFactor = 1.0; - switch (SemiMajorAxisUnits) - { - case AltUnits.Meters: - scaleFactor = 1.0; - break; - case AltUnits.Feet: - scaleFactor = 1.0 / 3.2808399; - break; - case AltUnits.Inches: - scaleFactor = (1.0 / 3.2808399) / 12; - break; - case AltUnits.Miles: - scaleFactor = 1609.344; - break; - case AltUnits.Kilometers: - scaleFactor = 1000; - break; - case AltUnits.AstronomicalUnits: - scaleFactor = UiTools.KilometersPerAu * 1000; - break; - case AltUnits.LightYears: - scaleFactor = UiTools.AuPerLightYear * UiTools.KilometersPerAu * 1000; - break; - case AltUnits.Parsecs: - scaleFactor = UiTools.AuPerParsec * UiTools.KilometersPerAu * 1000; - break; - case AltUnits.MegaParsecs: - scaleFactor = UiTools.AuPerParsec * UiTools.KilometersPerAu * 1000 * 1000000; - break; - case AltUnits.Custom: - scaleFactor = 1; - break; - default: - break; - } - scaleFactor *= 1/renderContext.NominalRadius; - - - Matrix3d look = Matrix3d.LookAtLH(Vector3d.Create(0,0,0), direction, up); - look.Invert(); - - WorldMatrix = Matrix3d.Identity; - WorldMatrix.Translate(Translation); - - double localScale = (1 / renderContext.NominalRadius) * Scale * MeanRadius; - WorldMatrix.Scale(Vector3d.Create(localScale, localScale, localScale)); - - //Matrix3d mat = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.RotationY(Heading / 180.0 * Math.PI), Matrix3d.RotationX(Pitch / 180.0 * Math.PI)),Matrix3d.RotationZ(Roll / 180.0 * Math.PI)); - - WorldMatrix.Multiply(Matrix3d.RotationYawPitchRoll((float)((Heading) / 180.0 * Math.PI), (float)(Pitch / 180.0 * Math.PI), (float)(Roll / 180.0 * Math.PI))); - - if (RotationalPeriod != 0) - { - double rotationCurrent = (((SpaceTimeController.JNow - this.ZeroRotationDate) / RotationalPeriod) * Math.PI * 2) % (Math.PI * 2); - WorldMatrix.Multiply(Matrix3d.RotationX(-rotationCurrent)); - } - - point = Vector3d.Scale(point, scaleFactor); - - WorldMatrix.Translate(point); - - if (StationKeeping) - { - WorldMatrix = Matrix3d.MultiplyMatrix(look, WorldMatrix); - } - } - } - - //public class TrajectorySample - //{ - // public double Time; - // public double X; - // public double Y; - // public double Z; - // public double H; - // public double P; - // public double R; - // public TrajectorySample(double time, double x, double y, double z) - // { - // X = x; - // Y = y; - // Z = z; - // Time = time; - // } - - // public Vector3d Position - // { - // get - // { - // return Vector3d.Create(X*1000, Z*1000, Y*1000); - // } - // } - - // public TrajectorySample(string line) - // { - // line = line.Replace(" ", " "); - // line = line.Replace(" ", " "); - // line = line.Replace(" ", " "); - - // string[] parts = line.Split(new char[] { ' ', '\t', ',' }); - - // if (parts.Length > 3) - // { - // Time = double.Parse(parts[0]); - // X = double.Parse(parts[1]); - // Y = double.Parse(parts[2]); - // Z = double.Parse(parts[3]); - // } - // if (parts.Length > 6) - // { - // H = double.Parse(parts[4]); - // P = double.Parse(parts[5]); - // R = double.Parse(parts[6]); - // } - // } - - // public override string ToString() - // { - // if (H == 0 && P == 0 && R == 0) - // { - // return string.Format("{0} {1} {2} {3}", Time, X, Y, Z); - // } - // else - // { - // return string.Format("{0} {1} {2} {3} {4} {5} {6]", Time, X, Y, Z, H, P, R); - // } - - // } - //} -} diff --git a/engine/csharp_ref/Layers/SpreadSheetLayer.cs b/engine/csharp_ref/Layers/SpreadSheetLayer.cs deleted file mode 100644 index 641f5451..00000000 --- a/engine/csharp_ref/Layers/SpreadSheetLayer.cs +++ /dev/null @@ -1,3248 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; -using System.Html.Data.Files; - -namespace wwtlib -{ - // public enum PointScaleTypes { Linear=0, Power=1, Log=2, Constant=3, StellarMagnitude=4 }; - - - public class SpreadSheetLayer : Layer - { - public SpreadSheetLayer() - { - } - - public override string GetTypeName() - { - return "TerraViewer.SpreadSheetLayer"; - } - - public List Header - { - get { return table.Header; } - } - - //public SpreadSheetLayer(string filename) - //{ - // //todo file reading - // //string data = File.ReadAllText(filename); - // //LoadFromString(data, false, false, false, true); - // //ComputeDateDomainRange(-1, -1); - //} - - public override bool CanCopyToClipboard() - { - - return true; - } - - public override void CopyToClipboard() - { - //todo copy binary format - - - // Clipboard.SetText(table.ToString()); - - } - - - - - bool dataDirty = false; - //public SpreadSheetLayer(string data, bool something) - //{ - // LoadFromString(data, false, false, false, true); - // ComputeDateDomainRange(-1, -1); - //} - - public bool DynamicUpdate() - { - string data = GetDatafromFeed(DataSourceUrl); - if (data != null) - { - UpdateData(data, false, true, true); - GuessHeaderAssignments(); - return true; - } - return false; - } - - private static string GetDatafromFeed(string url) - { - //string xml = ExecuteQuery(url); - - //if (xml == null) - //{ - // return null; - //} - - //try - //{ - - // XmlDocument xmlDoc = new XmlDocument(); - // XmlNamespaceManager xmlNsMgr = new XmlNamespaceManager(xmlDoc.NameTable); - // xmlNsMgr.AddNamespace("atom", "//www.w3.org/2005/Atom"); - // xmlNsMgr.AddNamespace("m", "//schemas.microsoft.com/ado/2007/08/dataservices/metadata"); - // xmlNsMgr.AddNamespace("d", "//schemas.microsoft.com/ado/2007/08/dataservices"); - - // xmlDoc.LoadXml(xml); - // XmlNodeList elements = xmlDoc.DocumentElement.SelectNodes("./atom:entry", xmlNsMgr); - // StringBuilder sb = new StringBuilder(); - - // if (elements != null && elements.Count > 0) - // { - // // Add ODATA properties as first row - // XmlNodeList properties = elements[0].SelectSingleNode("./atom:content/m:properties", xmlNsMgr).ChildNodes; - // int columnCount = 1; - // foreach (XmlNode property in properties) - // { - // if (columnCount != 1) - // { - // sb.Append("\t"); - // } - - // sb.Append(property.Name.Substring(property.Name.IndexOf(":") + 1, property.Name.Length - property.Name.IndexOf(":") - 1)); - // columnCount++; - // } - - // sb.AppendLine(string.Empty); - - // // Add ODATA property values from second row onwards - // foreach (XmlNode element in elements) - // { - // XmlNodeList propertyValues = element.SelectSingleNode("./atom:content/m:properties", xmlNsMgr).ChildNodes; - // // Reset Column Count - // columnCount = 1; - // foreach (XmlNode propertyValue in propertyValues) - // { - // if (columnCount != 1) - // { - // sb.Append("\t"); - // } - - // sb.Append(propertyValue.InnerText); - // columnCount++; - // } - - // sb.AppendLine(string.Empty); - // } - // } - - // return sb.ToString(); - //} - //catch - //{ - // return xml; - //} - - return ""; - } - - - - private static string ExecuteQuery(string url) - { - //try - //{ - - // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url)); - // request.Method = "GET"; - // request.Accept = "application/atom+xml, text/plain"; - // using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - // { - // using (StreamReader readStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"))) - // { - // return readStream.ReadToEnd(); - // } - // } - //} - //catch - //{ - // return null; - //} - return ""; - } - - public override bool UpdateData(object data, bool purgeOld, bool purgeAll, bool hasHeader) - { - - LoadFromString(data as string, true, purgeOld, purgeAll, hasHeader); - ComputeDateDomainRange(-1, -1); - dataDirty = true; - dirty = true; - return true; - } - - public override void LoadData(TourDocument tourDoc, string filename) - { - table = new Table(); - Blob blob = tourDoc.GetFileBlob(filename); - this.GetStringFromGzipBlob(blob, delegate (string data) - { - table.LoadFromString(data, false, true, true); - - // The NormalizeSizeColumnName column is only present for backward-compatibility - // and should be removed in this version of SpreadSheetLayer, otherwise we might - // keep adding it several times if exporting to XML again. - if (table.Header.IndexOf(NormalizeSizeColumnName) > -1) { - table.RemoveColumn(NormalizeSizeColumnName); - } - - ComputeDateDomainRange(-1, -1); - - if (DynamicData && AutoUpdate) - { - DynamicUpdate(); - } - dataDirty = true; - dirty = true; - }); - } - - - string fileName; - - public override void AddFilesToCabinet(FileCabinet fc) - { - - fileName = fc.TempDirectory + string.Format("{0}\\{1}.txt", fc.PackageID, this.ID.ToString()); - - string dir = fileName.Substring(0, fileName.LastIndexOf("\\")); - - string data = ""; - - // See PrepareBackCompatTable for an explanation of the - // circumstances under which table_backcompat is used. - if (table_backcompat == null) { - data = table.Save(); - } else { - data = table_backcompat.Save(); - } - - Blob blob = new Blob(new object[] { data }); - - fc.AddFile(fileName, blob); - - base.AddFilesToCabinet(fc); - } - - private int lastNormalizeSizeColumnIndex = -1; - private int lastDynamicColorColumnIndex = -1; - - private Table table_backcompat = null; - - private void PrepareBackCompatTable() - { - - // In this this layer class we implement dynamic normalization of the - // points based on one of the existing numerical columns. However, we - // need to produce XML files that are backward-compatible with older - // versions of WWT, so the approach we take is to add a column with - // the computed sizes for versions of WWT that can't do the dynamic - // scaling - while in newer versions we ignore this additional column - // and use the dynamic scaling. - - // Take a shortcut to avoid copying the table if possible - if ((sizeColumn == -1 || !NormalizeSize) && (colorMapColumn == -1 || !DynamicColor)) { - lastNormalizeSizeColumnIndex = -1; - lastDynamicColorColumnIndex = -1; - return; - } - - table_backcompat = table.Clone(); - - if (sizeColumn > -1 && NormalizeSize) { - List normalizedPointSize = new List(); - foreach (string[] row in table_backcompat.Rows) { - normalizedPointSize.Add(NormalizePointSize(Single.Parse(row[sizeColumn])).ToString()); - } - table_backcompat.AddColumn(NormalizeSizeColumnName, normalizedPointSize); - lastNormalizeSizeColumnIndex = table_backcompat.Header.Count - 1; - } else { - lastNormalizeSizeColumnIndex = -1; - } - - if (colorMapColumn > -1 && DynamicColor) { - List pointColors = new List(); - foreach (string[] row in table_backcompat.Rows) { - pointColors.Add(ColorMapper.FindClosestColor(NormalizeColorMapValue(Single.Parse(row[ColorMapColumn]))).ToSimpleHex()); - } - table_backcompat.AddColumn(DynamicColorColumnName, pointColors); - lastDynamicColorColumnIndex = table_backcompat.Header.Count - 1; - } else { - lastDynamicColorColumnIndex = -1; - } - - } - - public void GuessHeaderAssignments() - { - int index = 0; - foreach (string headerName in table.Header) - { - GuessHeaderAssignment(headerName, index++); - } - - if (table.Header.Count > 0) - { - nameColumn = 0; - } - } - - public void GuessHeaderAssignmentsFromVoTable(VoTable votable) - { - VoColumn decColumn = votable.GetDecColumn(); - if (decColumn != null) - { - latColumn = decColumn.Index; - astronomical = true; - - } - VoColumn raColumn = votable.GetRAColumn(); - if (raColumn != null) - { - lngColumn = raColumn.Index; - astronomical = true; - pointScaleType = PointScaleTypes.StellarMagnitude; - } - VoColumn magColumn = votable.GetMagColumn(); - if (magColumn != null) - { - sizeColumn = magColumn.Index; - } - - int index = 0; - foreach (VoColumn column in votable.Column) - { - GuessHeaderAssignment(column.Name, index++); - } - - if (table.Header.Count > 0) - { - nameColumn = 0; - } - } - - private void GuessHeaderAssignment(string name, int index) - { - name = name.ToLowerCase(); - if (name.IndexOf("lat") > -1 && latColumn == -1) - { - latColumn = index; - } - - if ((name.IndexOf("lon") > -1 || name.IndexOf("lng") > -1) && lngColumn == -1) - { - lngColumn = index; - } - - if (name.IndexOf("dec") > -1 && latColumn == -1) - { - latColumn = index; - astronomical = true; - } - - if ((name.IndexOf("ra") > -1 || name.IndexOf("ascen") > -1) && lngColumn == -1) - { - lngColumn = index; - astronomical = true; - pointScaleType = PointScaleTypes.StellarMagnitude; - } - - if ((name.IndexOf("mag") > -1 || name.IndexOf("size") > -1) && sizeColumn == -1) - { - sizeColumn = index; - } - - if ((name.IndexOf("date") > -1 || name.IndexOf("time") > -1 || name.IndexOf("dt") > -1 || name.IndexOf("tm") > -1)) - { - if (name.IndexOf("end") > -1 && endDateColumn == -1) - { - endDateColumn = index; - } - else if (startDateColumn == -1) - { - startDateColumn = index; - } - } - - - if ((name.IndexOf("altitude") > -1 || name.IndexOf("alt") > -1) && altColumn == -1) - { - altColumn = index; - AltType = AltTypes.Altitude; - AltUnit = AltUnits.Meters; - } - - if (name.IndexOf("depth") > -1 && altColumn == -1) - { - altColumn = index; - AltType = AltTypes.Depth; - AltUnit = AltUnits.Kilometers; - } - - if (name.StartsWith("x") && XAxisColumn == -1) - { - XAxisColumn = index; - } - - if (name.StartsWith("y") && YAxisColumn == -1) - { - YAxisColumn = index; - } - - if (name.StartsWith("z") && ZAxisColumn == -1) - { - ZAxisColumn = index; - } - - if (name.IndexOf("color") > -1 && ColorMapColumn == -1) - { - ColorMapColumn = index; - } - - if ((name.IndexOf("geometry") > -1 || name.IndexOf("geography") > -1) && geometryColumn == -1) - { - geometryColumn = index; - } - } - - public void ComputeDateDomainRange(int columnStart, int columnEnd) - { - if (columnStart == -1) - { - columnStart = startDateColumn; - } - - if (columnEnd == -1) - { - columnEnd = endDateColumn; - } - - if (columnEnd == -1) - { - columnEnd = columnStart; - } - - BeginRange = new Date("12/31/2100"); - EndRange = new Date("12/31/1890"); - - foreach (string[] row in table.Rows) - { - try - { - if (columnStart > -1) - { - bool sucsess = true; - Date dateTimeStart = new Date("12/31/2100"); - try - { - dateTimeStart = new Date(row[columnStart]); - if (dateTimeStart < BeginRange) - { - BeginRange = dateTimeStart; - } - } - catch - { - } - try - { - Date dateTimeEnd = new Date("12/31/1890"); - - - - if (columnEnd > -1) - { - dateTimeEnd = new Date(row[columnEnd]); - if (sucsess && dateTimeEnd > EndRange) - { - EndRange = dateTimeEnd; - } - } - } - catch - { - } - } - } - catch - { - } - } - } - - - // public struct ColumnStats - //{ - // int TargetColumn = -1; - // int FilterColumn = -1; - // string FilterValue = null; - // double Min = 0; - // double Max = 0; - // double Average = 0; - // double Median = 0; - // double Sum = 0; - // double Count = 0; - // int[] Histogram = null; - // int Buckets=256; - // double BucketWidth =0; - // bool Computed = false; - - //} - - - - public void CheckState() - { - - } - - - - - - - public double GetMaxValue(int column) - { - - double max = 0; - table.Lock(); - foreach (string[] row in table.Rows) - { - try - { - if (column > -1) - { - bool sucsess = true; - try - { - double val = double.Parse(row[column]); - - if (sucsess && val > max) - { - max = val; - } - } - catch - { - } - } - } - catch - { - } - } - table.Unlock(); - return max; - } - - public List GetDomainValues(int column) - { - List domainValues = new List(); - table.Lock(); - foreach (string[] row in table.Rows) - { - try - { - if (column > -1) - { - if (!domainValues.Contains(row[column])) - { - domainValues.Add(row[column]); - } - } - } - catch - { - } - } - domainValues.Sort(); - table.Unlock(); - return domainValues; - } - - - int barChartBitmask = 0; - - public int BarChartBitmask - { - get { return barChartBitmask; } - set { barChartBitmask = value; } - } - double barScaleFactor = 20; - - private double meanRadius = 6371000; - - private bool IsPointInFrustum(Vector3d position, PlaneD[] frustum) - { - Vector4d centerV4 = new Vector4d(position.X, position.Y, position.Z, 1f); - - for (int i = 0; i < 6; i++) - { - if (frustum[i].Dot(centerV4) < 0) - { - return false; - } - } - return true; - } - - public string GetTableDataInView() - { - - string data = ""; - - bool first = true; - - foreach (string col in Header) - { - if (!first) - { - data += "\t"; - } - else - { - first = false; - } - - data += col; - } - data += "\r\n"; - foreach (string[] row in Table.Rows) - { - double ra = Double.Parse(row[LngColumn]); - double dec = Double.Parse(row[LatColumn]); - Vector3d position = Coordinates.GeoTo3dDouble(dec, ra); - - if(!IsPointInFrustum(position, WWTControl.Singleton.RenderContext.Frustum)) - { - continue; - } - first = true; - foreach (string col in row) - { - if (!first) - { - data += "\t"; - } - else - { - first = false; - } - - data += col; - } - data += "\r\n"; - } - - return data; - } - - protected bool PrepVertexBuffer(RenderContext renderContext, float opacity) - { - table.Lock(); - if (lineList != null) - { - lineList.Clear(); - } - - if (lineList2d != null) - { - lineList2d.Clear(); - } - - if (triangleList != null) - { - triangleList.Clear(); - } - - if (pointList != null) - { - pointList.Clear(); - } - - - if (triangleList2d != null) - { - triangleList2d.Clear(); - } - - if (lineList == null) - { - lineList = new LineList(); - } - - if (pointList == null) - { - pointList = new PointList(renderContext); - } - - lineList.TimeSeries = this.timeSeries; - - if (lineList2d == null) - { - lineList2d = new LineList(); - lineList2d.DepthBuffered = false; - - } - - lineList.TimeSeries = this.timeSeries; - - - - if (triangleList == null) - { - triangleList = new TriangleList(); - } - - if (triangleList2d == null) - { - triangleList2d = new TriangleList(); - triangleList2d.DepthBuffered = false; - } - - - - - positions.Clear(); - UInt32 currentIndex = 0; - // device.RenderState.FillMode = FillMode.WireFrame; - Color colorLocal = Color; - - // colorLocal.A = (byte)(Color.A * Opacity); - - // for space 3d - double ecliptic = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI; - - - - Dictionary selectDomain = new Dictionary(); - - - double mr = LayerManager.AllMaps[ReferenceFrame].Frame.MeanRadius; - if (mr != 0) - { - meanRadius = mr; - } - - Vector3d position = new Vector3d(); - float pointSize = .0002f; - Color pointColor = Colors.White; - float pointStartTime = 0; - float pointEndTime = 0; - foreach (string[] row in table.Rows) - { - try - { - if (geometryColumn > -1 || (this.CoordinatesType == CoordinatesTypes.Spherical && (lngColumn > -1 && latColumn > -1)) || ((this.CoordinatesType == CoordinatesTypes.Rectangular) && (XAxisColumn > -1 && YAxisColumn > -1))) - { - double Xcoord = 0; - double Ycoord = 0; - double Zcoord = 0; - - double alt = 1; - double altitude = 0; - double distParces = 0; - double factor = GetScaleFactor(AltUnit, 1); - if (altColumn == -1 || AltType == AltTypes.SeaLevel || bufferIsFlat) - { - alt = 1; - if (astronomical & !bufferIsFlat) - { - alt = UiTools.AuPerLightYear * 100; - } - } - else - { - if (AltType == AltTypes.Depth) - { - factor = -factor; - } - - alt = 0; - try - { - alt = double.Parse(row[altColumn]); - } - catch - { - } - - if (astronomical) - { - factor = factor / (1000 * UiTools.KilometersPerAu); - distParces = (alt * factor) / UiTools.AuPerParsec; - - altitude = (factor * alt); - alt = (factor * alt); - } - else if (AltType == AltTypes.Distance) - { - altitude = (factor * alt); - alt = (factor * alt / meanRadius); - } - else - { - altitude = (factor * alt); - alt = 1 + (factor * alt / meanRadius); - } - } - - //todo remove hack when alt is fixed - //alt = 1; - - if (CoordinatesType == CoordinatesTypes.Spherical && lngColumn > -1 && latColumn > -1) - { - //Xcoord = Coordinates.Parse(row[lngColumn]); - //Ycoord = Coordinates.Parse(row[latColumn]); - Xcoord = double.Parse(row[lngColumn]); - Ycoord = double.Parse(row[latColumn]); - - if (astronomical) - { - if (RaUnits == RAUnits.Hours) - { - Xcoord *= 015; - } - if (bufferIsFlat) - { - // Xcoord += 180; - } - - } - else - { - Xcoord += 180; - } - - // TODO: - // double offset = EGM96Geoid.Height(Ycoord, Xcoord); - // if (altitude != 0) { - // altitude += offset; - // alt += offset / meanRadius; - // } - - Vector3d pos = Coordinates.GeoTo3dRad(Ycoord, Xcoord, alt); - - if (astronomical && !bufferIsFlat) - { - pos.RotateX(ecliptic); - } - - position = pos; - - positions.Add(position); - - } - else if (this.CoordinatesType == CoordinatesTypes.Rectangular) - { - double xyzScale = GetScaleFactor(CartesianScale, CartesianCustomScale); - - if (astronomical) - { - xyzScale /= (1000 * UiTools.KilometersPerAu); - } - else - { - xyzScale /= meanRadius; - } - - if (ZAxisColumn > -1) - { - Zcoord = double.Parse(row[ZAxisColumn]); - } - - Xcoord = double.Parse(row[XAxisColumn]); - Ycoord = double.Parse(row[YAxisColumn]); - - if (XAxisReverse) - { - Xcoord = -Xcoord; - } - if (YAxisReverse) - { - Ycoord = -Ycoord; - } - if (ZAxisReverse) - { - Zcoord = -Zcoord; - } - - - position = Vector3d.Create((Xcoord * xyzScale), (Zcoord * xyzScale), (Ycoord * xyzScale)); - positions.Add(position); - } - - // SqlGeometry pntGeo = SqlGeometry.Point(Xcoord,Ycoord, 4326); - - - //// SqlGeometry pntGeo = SqlGeometry.Point(new SqlChars(String.Format("Point ({0} {1})", Xcoord,Ycoord).ToCharArray()), 4326); - - - // if (!geo.STContains(pntGeo)) - // { - // continue; - // } - - switch (ColorMap) - { - case ColorMaps.Same_For_All: - pointColor = colorLocal; - break; - case ColorMaps.Per_Column_Literal: - if (ColorMapColumn > -1) - { - if (DynamicColor) - { - pointColor = ColorMapper.FindClosestColor(NormalizeColorMapValue(Single.Parse(row[ColorMapColumn]))); - } - else - { - pointColor = ParseColor(row[ColorMapColumn], colorLocal); - } - } - else - { - pointColor = colorLocal; - } - break; - //case ColorMaps.Group_by_Range: - // break; - //case ColorMaps.Gradients_by_Range: - // break; - //case ColorMaps.Group_by_Values: - // pointColor = ColorDomainValues[row[ColorMapColumn]].MarkerIndex; - // break; - - default: - break; - } - - if (pointColor == null) { - pointColor = Colors.Transparent; - } - - if (sizeColumn > -1) - { - switch (pointScaleType) - { - case PointScaleTypes.Linear: - pointSize = Single.Parse(row[sizeColumn]); - pointSize = NormalizePointSize(pointSize); - break; - case PointScaleTypes.Log: - pointSize = Single.Parse(row[sizeColumn]); - pointSize = (float)Math.Log(pointSize); - break; - case PointScaleTypes.Power: - { - - try - { - pointSize = Single.Parse(row[sizeColumn]); - pointSize = NormalizePointSize(pointSize); - pointSize = Math.Pow(2, pointSize); - } - catch - { - pointSize = 0; - } - } - break; - case PointScaleTypes.StellarMagnitude: - { - double size = 0; - try - { - size = double.Parse(row[sizeColumn]); - - if (!bufferIsFlat) - { - size = size - 5 * ((Util.LogN(distParces, 10) - 1)); - pointSize = (float)(120000000 / Math.Pow(1.6, size)); - } - else - { - pointSize = (float)(40 / Math.Pow(1.6, size)); - } - - } - catch - { - pointSize = 0; - } - - } - break; - - case PointScaleTypes.Constant: - pointSize = 1; - break; - default: - break; - } - } - else - { - pointSize = (float).2f; - } - if (PlotType == PlotTypes.Point) - { - pointSize = (float)1; - } - - if (astronomical & !bufferIsFlat) - { - // lastItem.PointSize *= 1000000000000000000000000000f; - } - - - if (startDateColumn > -1) - { - Date dateTime = new Date(row[startDateColumn]); - pointStartTime = (float)(SpaceTimeController.UtcToJulian(dateTime) - SpaceTimeController.UtcToJulian(baseDate)); - - if (endDateColumn > -1) - { - dateTime = new Date(row[endDateColumn]); - //dateTime = DateTime.Parse(row[endDateColumn]); - pointEndTime = (float)(SpaceTimeController.UtcToJulian(dateTime) - SpaceTimeController.UtcToJulian(baseDate)); - } - else - { - pointEndTime = pointStartTime; - } - } - - pointList.AddPoint(position, pointColor, new Dates(pointStartTime, pointEndTime), pointSize); - - - if (geometryColumn > -1) - { - ParseGeometry(row[geometryColumn], pointColor, pointColor, altitude, new Dates(pointStartTime, pointEndTime)); - } - - //if (barChartBitmask != 0) - //{ - // MakeBarChart(device, row, Ycoord, Xcoord, pointSize, factor, Color.FromArgb(lastItem.Color), selected, new Dates(pointStartTime, pointEndTime)); - //} - - currentIndex++; - } - } - catch - { - } - lines = false; - } - - - table.Unlock(); - dataDirty = false; - dirty = false; - return false; - } - - private void ParseGeometry(string gs, Color lineColor, Color polyColor, double alt, Dates date) - { - - - gs = gs.Trim().ToLowerCase(); - - int index = gs.IndexOf('('); - - if (index < 0) - { - return; - } - - if (!gs.EndsWith(")")) - { - return; - } - string commandPart = gs.Substring(0, index).Trim(); - - string parens = gs.Substr(index); - - string[] parts = commandPart.Split(" "); - - string command = null; - string mods = null; - if (parts.Length > 0) - { - foreach (string item in parts) - { - if (string.IsNullOrEmpty(command)) - { - command = item; - } - else if (string.IsNullOrEmpty(mods)) - { - mods = item; - } - } - } - - switch (command) - { - case "multipolygon": - case "polygon": - { - ParsePolygon(parens, mods, lineColor, polyColor, alt, date); - - } - break; - case "multilinestring": - { - ParseLineString(parens, mods, lineColor, alt, false, date); - } - break; - case "linestring": - { - ParseLineString(parens, mods, lineColor, alt, true, date); - } - break; - case "geometrycollection": - { - parens = parens.Substring(1, parens.Length - 2); - List shapes = UiTools.SplitString(parens, ","); - foreach (string shape in shapes) - { - ParseGeometry(shape, lineColor, polyColor, alt, date); - } - } - break; - default: - break; - } - - } - - - - private void ParsePolygon(string parens, string mods, Color lineColor, Color polyColor, double alt, Dates date) - { - - if (!parens.StartsWith("(") && parens.EndsWith(")")) - { - return; - } - // string the top level of parens - parens = parens.Substring(1, parens.Length - 2); - - List shapes = UiTools.SplitString(parens, ","); - foreach (string shape in shapes) - { - KmlLineList lineList = new KmlLineList(); - lineList.Astronomical = astronomical; - lineList.MeanRadius = meanRadius; - lineList.ParseWkt(shape, mods, alt, date); - if (alt == 0) - { - AddPolygonFlat(false, lineList, 1, polyColor, lineColor, true, true, date); - } - else - { - AddPolygon(false, lineList, 1, polyColor, lineColor, true, true, date); - } - } - } - - private void ParseLineString(string parens, string mods, Color lineColor, double alt, bool single, Dates date) - { - - if (!parens.StartsWith("(") && parens.EndsWith(")")) - { - return; - } - if (!single) - { - // string the top level of parens - parens = parens.Substring(1, parens.Length - 2); - } - List shapes = UiTools.SplitString(parens, ","); - foreach (string shape in shapes) - { - KmlLineList lineList = new KmlLineList(); - lineList.Astronomical = astronomical; - lineList.MeanRadius = meanRadius; - - lineList.ParseWkt(shape, mods, alt, date); - AddPolygon(false, lineList, 1, Colors.White, lineColor, false, false, date); - } - - - } - - private List SplitShapes(string shapes) - { - List shapeList = new List(); - - int nesting = 0; - - int current = 0; - while (current < shapes.Length) - { - if (shapes.Substr(current, 1) == "(") - { - nesting++; - } - } - - return shapeList; - } - - - - private void AddPolygon(bool sky, KmlLineList geo, float lineWidth, Color polyColor, Color lineColor, bool extrude, bool fill, Dates date) - { - - //todo can we save this work for later? - List vertexList = new List(); - List vertexListGround = new List(); - - //todo list - // We need to Wrap Around for complete polygone - // we aldo need to do intereor - //todo space? using RA/DEC - for (int i = 0; i < (geo.PointList.Count); i++) - { - vertexList.Add(Coordinates.GeoTo3dRad(geo.PointList[i].Lat, geo.PointList[i].Lng, 1 + (geo.PointList[i].Alt / meanRadius))); - vertexListGround.Add(Coordinates.GeoTo3dRad(geo.PointList[i].Lat, geo.PointList[i].Lng, 1)); - } - - - for (int i = 0; i < (geo.PointList.Count - 1); i++) - { - if (sky) - { - //tdo reenable this - //this.lineList2d.AddLine - // (Coordinates.RADecTo3d(-(180.0 - geo.PointList[i].Lng) / 15 + 12, geo.PointList[i].Lat, 1), Coordinates.RADecTo3d(-(180.0 - geo.PointList[i + 1].Lng) / 15 + 12, geo.PointList[i + 1].Lat, 1), lineColor, date); - } - else - { - if (extrude) - { - - this.triangleList.AddQuad(vertexList[i], vertexList[i + 1], vertexListGround[i], vertexListGround[i + 1], polyColor, date); - - } - if (lineWidth > 0) - { - if (extrude) - { - this.lineList.AddLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - else - { - this.lineList2d.AddLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - if (extrude) - { - this.lineList.AddLine(vertexListGround[i], vertexListGround[i + 1], lineColor, date); - this.lineList.AddLine(vertexList[i], vertexListGround[i], lineColor, date); - this.lineList.AddLine(vertexList[i + 1], vertexListGround[i + 1], lineColor, date); - } - } - } - } - if (fill) - { - List indexes = Tessellator.TesselateSimplePoly(vertexList); - - for (int i = 0; i < indexes.Count; i += 3) - { - this.triangleList.AddTriangle(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date); - } - } - } - - private void AddPolygonFlat(bool sky, KmlLineList geo, float lineWidth, Color polyColor, Color lineColor, bool extrude, bool fill, Dates date) - { - - //todo can we save this work for later? - List vertexList = new List(); - - for (int i = 0; i < (geo.PointList.Count); i++) - { - vertexList.Add(Coordinates.GeoTo3dRad(geo.PointList[i].Lat, geo.PointList[i].Lng, 1 + (geo.PointList[i].Alt / meanRadius))); - } - - - for (int i = 0; i < (geo.PointList.Count - 1); i++) - { - if (sky) - { - //this.lineList2d.AddLine - // (Coordinates.RADecTo3d(-(180.0 - geo.PointList[i].Lng) / 15 + 12, geo.PointList[i].Lat, 1), Coordinates.RADecTo3d(-(180.0 - geo.PointList[i + 1].Lng) / 15 + 12, geo.PointList[i + 1].Lat, 1), lineColor, date); - } - else - { - if (lineWidth > 0) - { - this.lineList2d.AddLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - } - } - if (fill) - { - List indexes = Tessellator.TesselateSimplePoly(vertexList); - - for (int i = 0; i < indexes.Count; i += 3) - { - this.triangleList2d.AddSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date, 2); - } - } - } - - // todo fix this mess - private Color ParseColor(string colorText, Color defaultColor) - { - return Color.Load(colorText); - - - } - - public static Date ParseDate(string date) - { - Date dt = Date.Now; - try - { - dt = new Date(date); - } - catch - { - try - { - return ExeclToDateTime(double.Parse(date)); - } - catch - { - } - - } - - return dt; - } - - - - public static Date ExeclToDateTime(double excelDate) - { - if (excelDate > 59) - { - excelDate -= 1; - } - if (excelDate > 730000) - { - excelDate = 730000; - } - Date es = new Date(1899, 12, 31); - return new Date(es.GetDate() + (int)(excelDate * 24 * 60 * 60 * 1000)); - } - - public double GetScaleFactor(AltUnits AltUnit, double custom) - { - double factor = 1; - - switch (AltUnit) - { - case AltUnits.Meters: - factor = 1; - break; - case AltUnits.Feet: - factor = 1 * 0.3048; - break; - case AltUnits.Inches: - factor = (1.0 / 12.0) * 0.3048; - break; - case AltUnits.Miles: - factor = 5280 * 0.3048; - break; - case AltUnits.Kilometers: - factor = 1000; - break; - case AltUnits.AstronomicalUnits: - factor = 1000 * UiTools.KilometersPerAu; - break; - case AltUnits.LightYears: - factor = 1000 * UiTools.KilometersPerAu * UiTools.AuPerLightYear; - break; - case AltUnits.Parsecs: - factor = 1000 * UiTools.KilometersPerAu * UiTools.AuPerParsec; - break; - case AltUnits.MegaParsecs: - factor = 1000 * UiTools.KilometersPerAu * UiTools.AuPerParsec * 1000000; - break; - case AltUnits.Custom: - factor = custom; - break; - default: - break; - } - return factor; - } - - // public override Place FindClosest(Coordinates target, float distance, IPlace defaultPlace, bool astronomical) - // { - //Vector3 searchPoint = Coordinates.GeoTo3d(target.Lat, target.Lng); - - ////searchPoint = -searchPoint; - //Vector3 dist; - //if (defaultPlace != null) - //{ - // Vector3 testPoint = Coordinates.RADecTo3d(defaultPlace.RA, -defaultPlace.Dec, -1.0).Vector3; - // dist = searchPoint - testPoint; - // distance = dist.Length(); - //} - - //int closestItem = -1; - //int index = 0; - //foreach (Vector3 point in positions) - //{ - // dist = searchPoint - point; - // if (dist.Length() < distance) - // { - // distance = dist.Length(); - // closestItem = index; - // } - // index++; - //} - - - //if (closestItem == -1) - //{ - // return defaultPlace; - //} - - //Coordinates pnt = Coordinates.CartesianToSpherical2(positions[closestItem]); - - //string name = table.Rows[closestItem][this.nameColumn]; - //if (nameColumn == startDateColumn || nameColumn == endDateColumn) - //{ - // name = ParseDate(name).ToString("u"); - //} - - //if (String.IsNullOrEmpty(name)) - //{ - // name = string.Format("RA={0}, Dec={1}", Coordinates.FormatHMS(pnt.RA), Coordinates.FormatDMS(pnt.Dec)); - //} - //TourPlace place = new TourPlace(name, pnt.Lat, pnt.Lng, Classification.Unidentified, "", ImageSetType.Earth, -1); - - //Dictionary rowData = new Dictionary(); - //for (int i = 0; i < table.Header.GetLength(0); i++) - //{ - // string colValue = table.Rows[closestItem][i]; - // if (i == startDateColumn || i == endDateColumn) - // { - // colValue = ParseDate(colValue).ToString("u"); - // } - - // if (!rowData.ContainsKey(table.Header[i]) && !string.IsNullOrEmpty(table.Header[i])) - // { - // rowData.Add(table.Header[i], colValue); - // } - // else - // { - // rowData.Add("Column" + i.ToString(), colValue); - // } - //} - //place.Tag = rowData; - - //return place; - // } - - - - - Table table = new Table(); - - internal Table Table - { - get { return table; } - set { table = value; } - } - - public void UseHeadersFromVoTable(VoTable voTable) - { - foreach(VoColumn column in voTable.Column) - { - Header.Add(column.Name); - } - GuessHeaderAssignmentsFromVoTable(voTable); - if(voTable.GetRAColumn() != null && voTable.GetRAColumn().Unit.ToLowerCase() == "deg") - { - RaUnits = RAUnits.Degrees; - } - } - - public void LoadFromString(string data, bool isUpdate, bool purgeOld, bool purgeAll, bool hasHeader) - { - if (!isUpdate) - { - table = new Table(); - } - table.Lock(); - table.LoadFromString(data, isUpdate, purgeAll, hasHeader); - if (!isUpdate) - { - - GuessHeaderAssignments(); - - if (astronomical && lngColumn > -1) - { - double max = GetMaxValue(lngColumn); - if (max > 24) - { - RaUnits = RAUnits.Degrees; - } - } - - } - - if (purgeOld) - { - PurgeByTime(); - } - table.Unlock(); - } - - public void PurgeByTime() - { - if (startDateColumn < 0) - { - return; - } - int columnToUse = startDateColumn; - if (endDateColumn > -1) - { - columnToUse = endDateColumn; - } - - Date threasholdTime = SpaceTimeController.Now; - int ts = (int)decay*24*60*60*1000; - threasholdTime = new Date(threasholdTime.GetDate() - ts); - - int count = table.Rows.Count; - for (int i = 0; i < count; i++) - { - try - { - List row = table.Rows[i]; - Date colDate = new Date(row[columnToUse]); - if (colDate < threasholdTime) - { - table.Rows.RemoveAt(i); - count--; - i--; - } - } - catch - { - } - } - } - - public override void CleanUp() - { - CleanUpBase(); - table.Lock(); - base.CleanUp(); - table.Unlock(); - - dirty = true; - } - - //public override void InitFromXml(XmlNode node) - //{ - // base.InitFromXml(node); - //} - - public override void WriteLayerProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteAttributeString("TimeSeries", TimeSeries.ToString()); - xmlWriter.WriteAttributeString("BeginRange", Util.XMLDate(BeginRange)); - xmlWriter.WriteAttributeString("EndRange", Util.XMLDate(EndRange)); - xmlWriter.WriteAttributeString("Decay", Decay.ToString()); - xmlWriter.WriteAttributeString("CoordinatesType", Enums.ToXml("CoordinatesTypes",(int)CoordinatesType)); - xmlWriter.WriteAttributeString("LatColumn", LatColumn.ToString()); - xmlWriter.WriteAttributeString("LngColumn", LngColumn.ToString()); - xmlWriter.WriteAttributeString("GeometryColumn", GeometryColumn.ToString()); - xmlWriter.WriteAttributeString("AltType", Enums.ToXml("AltTypes", (int)AltType)); - xmlWriter.WriteAttributeString("MarkerMix", Enums.ToXml("MarkerMixes", (int)MarkerMix)); - xmlWriter.WriteAttributeString("ColorMap", Enums.ToXml("ColorMaps", (int)ColorMap)); - xmlWriter.WriteAttributeString("MarkerColumn", MarkerColumn.ToString()); - xmlWriter.WriteAttributeString("PlotType", Enums.ToXml("PlotTypes", (int)PlotType)); - xmlWriter.WriteAttributeString("MarkerIndex", MarkerIndex.ToString()); - xmlWriter.WriteAttributeString("MarkerScale", Enums.ToXml("MarkerScales",(int)MarkerScale)); - xmlWriter.WriteAttributeString("AltUnit", Enums.ToXml("AltUnits", (int)AltUnit)); - xmlWriter.WriteAttributeString("AltColumn", AltColumn.ToString()); - xmlWriter.WriteAttributeString("StartDateColumn", StartDateColumn.ToString()); - xmlWriter.WriteAttributeString("EndDateColumn", EndDateColumn.ToString()); - - // In this layer class we implement dynamic scaling and coloring of the points - // based on one of the existing numerical columns. However, we need to produce - // XML files that are backward-compatible with older versions of WWT. If - // dynamic scaling/coloring is used, we therefore point sizeColumn and/or - // colorMapColumn to the hard-coded sizes/colors, and then if we detect - // normalization arguments when reading in the XML, we switch sizeColumn - // and/or colorMapColumn to the original one. - - // Note that we need to call this here since WriteLayerProperties - // gets called before AddFilesToCabinet. - PrepareBackCompatTable(); - - if (lastNormalizeSizeColumnIndex > -1) { - xmlWriter.WriteAttributeString("SizeColumn", lastNormalizeSizeColumnIndex); - xmlWriter.WriteAttributeString("NormalizeSizeColumn", sizeColumn.ToString()); - } else { - xmlWriter.WriteAttributeString("SizeColumn", SizeColumn.ToString()); - } - - xmlWriter.WriteAttributeString("NormalizeSize", NormalizeSize.ToString()); - xmlWriter.WriteAttributeString("NormalizeSizeClip", NormalizeSizeClip.ToString()); - xmlWriter.WriteAttributeString("NormalizeSizeMin", NormalizeSizeMin.ToString()); - xmlWriter.WriteAttributeString("NormalizeSizeMax", NormalizeSizeMax.ToString()); - - if (lastDynamicColorColumnIndex > -1) { - xmlWriter.WriteAttributeString("ColorMapColumn", lastDynamicColorColumnIndex); - xmlWriter.WriteAttributeString("DynamicColorColumn", ColorMapColumn.ToString()); - } else { - xmlWriter.WriteAttributeString("ColorMapColumn", ColorMapColumn.ToString()); - } - - xmlWriter.WriteAttributeString("DynamicColor", DynamicColor.ToString()); - xmlWriter.WriteAttributeString("ColorMapperName", ColorMapperName); - xmlWriter.WriteAttributeString("NormalizeColorMap", NormalizeColorMap.ToString()); - xmlWriter.WriteAttributeString("NormalizeColorMapMin", NormalizeColorMapMin.ToString()); - xmlWriter.WriteAttributeString("NormalizeColorMapMax", NormalizeColorMapMax.ToString()); - - xmlWriter.WriteAttributeString("HyperlinkFormat", HyperlinkFormat.ToString()); - xmlWriter.WriteAttributeString("HyperlinkColumn", HyperlinkColumn.ToString()); - xmlWriter.WriteAttributeString("ScaleFactor", ScaleFactor.ToString()); - xmlWriter.WriteAttributeString("PointScaleType", Enums.ToXml("PointScaleTypes", (int)PointScaleType)); - xmlWriter.WriteAttributeString("ShowFarSide", ShowFarSide.ToString()); - xmlWriter.WriteAttributeString("RaUnits", Enums.ToXml("RAUnits", (int)RaUnits)); - xmlWriter.WriteAttributeString("HoverTextColumn", NameColumn.ToString()); - xmlWriter.WriteAttributeString("XAxisColumn", XAxisColumn.ToString()); - xmlWriter.WriteAttributeString("XAxisReverse", XAxisReverse.ToString()); - xmlWriter.WriteAttributeString("YAxisColumn", YAxisColumn.ToString()); - xmlWriter.WriteAttributeString("YAxisReverse", YAxisReverse.ToString()); - xmlWriter.WriteAttributeString("ZAxisColumn", ZAxisColumn.ToString()); - xmlWriter.WriteAttributeString("ZAxisReverse", ZAxisReverse.ToString()); - xmlWriter.WriteAttributeString("CartesianScale", Enums.ToXml("AltUnits", (int)CartesianScale)); - xmlWriter.WriteAttributeString("CartesianCustomScale", CartesianCustomScale.ToString()); - xmlWriter.WriteAttributeString("DynamicData", DynamicData.ToString()); - xmlWriter.WriteAttributeString("AutoUpdate", AutoUpdate.ToString()); - xmlWriter.WriteAttributeString("DataSourceUrl", DataSourceUrl.ToString()); - - } - - - - protected bool isLongIndex = false; - protected int shapeVertexCount; - - - protected bool lines = false; - protected int latColumn = -1; - protected float fixedSize = 1; - protected float decay = 16; - protected bool timeSeries = false; - - private bool dynamicData = false; - - - public bool DynamicData - { - get { return dynamicData; } - set { dynamicData = value; } - } - - private bool autoUpdate = false; - - - public bool AutoUpdate - { - get { return autoUpdate; } - set { autoUpdate = value; } - } - - string dataSourceUrl = ""; - - public string DataSourceUrl - { - get { return dataSourceUrl; } - set { dataSourceUrl = value; } - } - - - - - - public bool TimeSeries - { - get { return timeSeries; } - set - { - if (timeSeries != value) - { - version++; - timeSeries = value; - } - } - } - - - Date beginRange = new Date("1/1/2100"); - - - public Date BeginRange - { - get { return beginRange; } - set - { - if (beginRange != value) - { - version++; - beginRange = value; - } - } - } - Date endRange = new Date("01/01/1800"); - - public Date EndRange - { - get { return endRange; } - set - { - if (endRange != value) - { - version++; - endRange = value; - } - } - } - - - public override void InitializeFromXml(XmlNode node) - { - TimeSeries = bool.Parse(node.Attributes.GetNamedItem("TimeSeries").Value); - BeginRange = new Date(node.Attributes.GetNamedItem("BeginRange").Value); - EndRange = new Date(node.Attributes.GetNamedItem("EndRange").Value); - Decay = Single.Parse(node.Attributes.GetNamedItem("Decay").Value); - CoordinatesType = (CoordinatesTypes)Enums.Parse("CoordinatesTypes", node.Attributes.GetNamedItem("CoordinatesType").Value); - - - if ((int)CoordinatesType < 0) - { - CoordinatesType = CoordinatesTypes.Spherical; - } - LatColumn = int.Parse(node.Attributes.GetNamedItem("LatColumn").Value); - LngColumn = int.Parse(node.Attributes.GetNamedItem("LngColumn").Value); - if (node.Attributes.GetNamedItem("GeometryColumn") != null) - { - GeometryColumn = int.Parse(node.Attributes.GetNamedItem("GeometryColumn").Value); - } - - AltType = (AltTypes)Enums.Parse("AltTypes", node.Attributes.GetNamedItem("AltType").Value); - - MarkerMix = MarkerMixes.Same_For_All; - ColorMap = (ColorMaps)Enums.Parse("ColorMaps",node.Attributes.GetNamedItem("ColorMap").Value); - - MarkerColumn = int.Parse(node.Attributes.GetNamedItem("MarkerColumn").Value); - ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("ColorMapColumn").Value); - PlotType = (PlotTypes)Enums.Parse("PlotTypes",node.Attributes.GetNamedItem("PlotType").Value); - - MarkerIndex = int.Parse(node.Attributes.GetNamedItem("MarkerIndex").Value); - MarkerScale = (MarkerScales)Enums.Parse("MarkerScales", node.Attributes.GetNamedItem("MarkerScale").Value); - AltUnit = (AltUnits)Enums.Parse("AltUnits", node.Attributes.GetNamedItem("AltUnit").Value); - AltColumn = int.Parse(node.Attributes.GetNamedItem("AltColumn").Value); - StartDateColumn = int.Parse(node.Attributes.GetNamedItem("StartDateColumn").Value); - EndDateColumn = int.Parse(node.Attributes.GetNamedItem("EndDateColumn").Value); - - // In this layer class we implement dynamic scaling and coloring of the points - // based on one of the existing numerical columns. However, we need to produce - // XML files that are backward-compatible with older versions of WWT. Since we - // can deal with size/color scaling here, we ignore SizeColumn and ColorMapColumn - // and use NormalizeSizeColumn and DynamicColorColumn instead, if present. - - if (node.Attributes.GetNamedItem("NormalizeSizeColumn") != null) - { - SizeColumn = int.Parse(node.Attributes.GetNamedItem("NormalizeSizeColumn").Value); - } else { - SizeColumn = int.Parse(node.Attributes.GetNamedItem("SizeColumn").Value); - } - - // Only recent files have normalization parameters - - if (node.Attributes.GetNamedItem("NormalizeSize") != null) - { - NormalizeSize = Boolean.Parse(node.Attributes.GetNamedItem("NormalizeSize").Value); - NormalizeSizeClip = Boolean.Parse(node.Attributes.GetNamedItem("NormalizeSizeClip").Value); - NormalizeSizeMin = float.Parse(node.Attributes.GetNamedItem("NormalizeSizeMin").Value); - NormalizeSizeMax = float.Parse(node.Attributes.GetNamedItem("NormalizeSizeMax").Value); - } - - if (node.Attributes.GetNamedItem("DynamicColorColumn") != null) - { - ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("DynamicColorColumn").Value); - } else { - ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("ColorMapColumn").Value); - } - - // Only recent files have normalization parameters - - if (node.Attributes.GetNamedItem("DynamicColor") != null) - { - DynamicColor = Boolean.Parse(node.Attributes.GetNamedItem("DynamicColor").Value); - ColorMapperName = node.Attributes.GetNamedItem("ColorMapperName").Value; - NormalizeColorMap = Boolean.Parse(node.Attributes.GetNamedItem("NormalizeColorMap").Value); - NormalizeColorMapMin = float.Parse(node.Attributes.GetNamedItem("NormalizeColorMapMin").Value); - NormalizeColorMapMax = float.Parse(node.Attributes.GetNamedItem("NormalizeColorMapMax").Value); - } - - HyperlinkFormat = node.Attributes.GetNamedItem("HyperlinkFormat").Value; - HyperlinkColumn = int.Parse(node.Attributes.GetNamedItem("HyperlinkColumn").Value); - ScaleFactor = Single.Parse(node.Attributes.GetNamedItem("ScaleFactor").Value); - PointScaleType = (PointScaleTypes)Enums.Parse("PointScaleTypes", node.Attributes.GetNamedItem("PointScaleType").Value); - - if (node.Attributes.GetNamedItem("ShowFarSide") != null) - { - ShowFarSide = Boolean.Parse(node.Attributes.GetNamedItem("ShowFarSide").Value); - } - - if (node.Attributes.GetNamedItem("RaUnits") != null) - { - RaUnits = (RAUnits)Enums.Parse("RAUnits", node.Attributes.GetNamedItem("RaUnits").Value); - } - - if (node.Attributes.GetNamedItem("HoverTextColumn") != null) - { - NameColumn = int.Parse(node.Attributes.GetNamedItem("HoverTextColumn").Value); - } - - if (node.Attributes.GetNamedItem("XAxisColumn") != null) - { - XAxisColumn = int.Parse(node.Attributes.GetNamedItem("XAxisColumn").Value); - XAxisReverse = bool.Parse(node.Attributes.GetNamedItem("XAxisReverse").Value); - YAxisColumn = int.Parse(node.Attributes.GetNamedItem("YAxisColumn").Value); - YAxisReverse = bool.Parse(node.Attributes.GetNamedItem("YAxisReverse").Value); - ZAxisColumn = int.Parse(node.Attributes.GetNamedItem("ZAxisColumn").Value); - ZAxisReverse = bool.Parse(node.Attributes.GetNamedItem("ZAxisReverse").Value); - CartesianScale = (AltUnits)Enums.Parse("AltUnits",node.Attributes.GetNamedItem("CartesianScale").Value); - CartesianCustomScale = double.Parse(node.Attributes.GetNamedItem("CartesianCustomScale").Value); - } - - if (node.Attributes.GetNamedItem("DynamicData") != null) - { - DynamicData = bool.Parse(node.Attributes.GetNamedItem("DynamicData").Value); - AutoUpdate = bool.Parse(node.Attributes.GetNamedItem("AutoUpdate").Value); - DataSourceUrl = node.Attributes.GetNamedItem("DataSourceUrl").Value; - } - } - - - public Dictionary MarkerDomainValues = new Dictionary(); - public Dictionary ColorDomainValues = new Dictionary(); - - - - - public float Decay - { - get { return decay; } - set - { - if (decay != value) - { - version++; - decay = value; - } - } - } - - - private CoordinatesTypes coordinatesType = CoordinatesTypes.Spherical; - - - public CoordinatesTypes CoordinatesType - { - get { return coordinatesType; } - set - { - if (coordinatesType != value) - { - version++; - coordinatesType = value; - } - } - } - - - public int LatColumn - { - get { return latColumn; } - set - { - if (latColumn != value) - { - version++; - latColumn = value; - } - } - } - protected int lngColumn = -1; - - - public int LngColumn - { - get { return lngColumn; } - set - { - if (lngColumn != value) - { - version++; - lngColumn = value; - } - } - } - - protected int geometryColumn = -1; - - - public int GeometryColumn - { - get { return geometryColumn; } - set - { - if (geometryColumn != value) - { - version++; - geometryColumn = value; - } - } - } - - private int xAxisColumn = -1; - - - public int XAxisColumn - { - get { return xAxisColumn; } - set - { - if (xAxisColumn != value) - { - version++; - xAxisColumn = value; - } - } - } - private int yAxisColumn = -1; - - - public int YAxisColumn - { - get { return yAxisColumn; } - set - { - if (yAxisColumn != value) - { - version++; - yAxisColumn = value; - } - } - } - private int zAxisColumn = -1; - - - public int ZAxisColumn - { - get { return zAxisColumn; } - set - { - if (zAxisColumn != value) - { - version++; - zAxisColumn = value; - } - } - } - - private bool xAxisReverse = false; - - - public bool XAxisReverse - { - get { return xAxisReverse; } - set - { - if (xAxisReverse != value) - { - version++; - xAxisReverse = value; - } - } - } - private bool yAxisReverse = false; - - - public bool YAxisReverse - { - get { return yAxisReverse; } - set - { - if (yAxisReverse != value) - { - version++; - yAxisReverse = value; - } - } - } - private bool zAxisReverse = false; - - - public bool ZAxisReverse - { - get { return zAxisReverse; } - set - { - if (zAxisReverse != value) - { - version++; - zAxisReverse = value; - } - } - } - - private AltTypes altType = AltTypes.SeaLevel; - - - public AltTypes AltType - { - get { return altType; } - set - { - if (altType != value) - { - version++; - altType = value; - } - } - } - - - private MarkerMixes markerMix = MarkerMixes.Same_For_All; - - - public MarkerMixes MarkerMix - { - get { return markerMix; } - set - { - if (markerMix != value) - { - version++; - markerMix = value; - } - } - } - - RAUnits raUnits = RAUnits.Hours; - - public RAUnits RaUnits - { - get { return raUnits; } - set - { - - if (raUnits != value) - { - version++; - raUnits = value; - } - } - } - - protected ColorMaps colorMap = ColorMaps.Per_Column_Literal; - - - public ColorMaps ColorMap - { - get { return colorMap; } - set - { - if (colorMap != value) - { - version++; - colorMap = value; - } - } - } - - protected string colorMapperName = "Greys"; - - public string ColorMapperName - { - get { return colorMapperName; } - set - { - if (ColorMapContainer.FromNamedColormap(value) == null) - throw new Exception("Invalid colormap name"); - version++; - colorMapperName = value; - } - } - - public ColorMapContainer ColorMapper - { - get { return ColorMapContainer.FromNamedColormap(colorMapperName); } - } - - // The following attributes control whether and how to map values from - // the ColorMapColumn to colors. The overall option DynamicColor - // determines whether colors should be determined on-the-fly from column - // values. In this case, first, if NormalizeColorMap is true, the values - // are normalized to the range [0:1] using: - // - // new_value = (value - NormalizeColorMapMin) / (NormalizeColorMapMax - NormalizeColorMapMin) - // - // Whether or not the values are normalized, they are then mapped to colors using - // the color map with the name given by ColorMapName. - - // Note that we use a hard-coded UUID since we need it to always be the same across - // all WWT sessions so that we can remove it when it isn't needed. - private string DynamicColorColumnName = "2efc32e3-b9d9-47ff-8036-8cc344c585bd"; - - protected bool dynamicColor = false; - - public bool DynamicColor - { - get { return dynamicColor; } - set - { - version++; - dynamicColor = value; - } - } - - protected bool normalizeColorMap = false; - - public bool NormalizeColorMap - { - get { return normalizeColorMap; } - set - { - version++; - normalizeColorMap = value; - } - } - - protected float normalizeColorMapMin = 0; - - public float NormalizeColorMapMin - { - get { return normalizeColorMapMin; } - set - { - version++; - normalizeColorMapMin = value; - } - } - - protected float normalizeColorMapMax = 1; - - public float NormalizeColorMapMax - { - get { return normalizeColorMapMax; } - set - { - version++; - normalizeColorMapMax = value; - } - } - - public float NormalizeColorMapValue(float value) - { - - if (!NormalizeColorMap) - return value; - - float new_value = (value - NormalizeColorMapMin) / (NormalizeColorMapMax - NormalizeColorMapMin); - - if (new_value < 0) - { - new_value = 0; - } - else if (new_value > 1) - { - new_value = 1; - } - - return new_value; - } - - private int markerColumn = -1; - - - public int MarkerColumn - { - get { return markerColumn; } - set - { - if (markerColumn != value) - { - version++; - markerColumn = value; - } - } - } - - protected int colorMapColumn = -1; - - - public int ColorMapColumn - { - get { return colorMapColumn; } - set - { - if (colorMapColumn != value) - { - version++; - colorMapColumn = value; - } - } - } - - private PlotTypes plotType = PlotTypes.Gaussian; - - - public PlotTypes PlotType - { - get { return plotType; } - set - { - if (plotType != value) - { - version++; - plotType = value; - } - - } - } - - private int markerIndex = 0; - - - public int MarkerIndex - { - get { return markerIndex; } - set - { - if (markerIndex != value) - { - version++; - markerIndex = value; - } - } - } - - private bool showFarSide = false; - - - public bool ShowFarSide - { - get { return showFarSide; } - set - { - if (showFarSide != value) - { - version++; - showFarSide = value; - } - } - } - - - private MarkerScales markerScale = MarkerScales.World; - - - public MarkerScales MarkerScale - { - get { return markerScale; } - set - { - if (markerScale != value) - { - version++; - markerScale = value; - } - } - } - - - private AltUnits altUnit = AltUnits.Meters; - - - public AltUnits AltUnit - { - get { return altUnit; } - set - { - if (altUnit != value) - { - version++; - altUnit = value; - } - } - } - private AltUnits cartesianScale = AltUnits.Meters; - - - public AltUnits CartesianScale - { - get { return cartesianScale; } - set - { - if (cartesianScale != value) - { - version++; - cartesianScale = value; - } - } - } - - private double cartesianCustomScale = 1; - - - public double CartesianCustomScale - { - get { return cartesianCustomScale; } - set - { - if (cartesianCustomScale != value) - { - version++; - cartesianCustomScale = value; - } - } - } - - protected int altColumn = -1; - - public int AltColumn - { - get { return altColumn; } - set - { - if (altColumn != value) - { - version++; - altColumn = value; - } - } - } - - protected int startDateColumn = -1; - - - public int StartDateColumn - { - get { return startDateColumn; } - set - { - if (startDateColumn != value) - { - version++; - startDateColumn = value; - } - } - } - protected int endDateColumn = -1; - - - public int EndDateColumn - { - get { return endDateColumn; } - set - { - if (endDateColumn != value) - { - version++; - endDateColumn = value; - } - } - } - - protected int sizeColumn = -1; - - public int SizeColumn - { - get { return sizeColumn; } - set - { - if (sizeColumn != value) - { - version++; - sizeColumn = value; - } - } - } - - // The following attributes control whether the point sizes should be normalized before - // being used. When NormalizeSize is true, the point sizes are scaled using - // - // new_size = (size - NormalizeSizeMin) / (NormalizeSizeMax - NormalizeSizeMin) - // - // The NormalizeSizeClip attribute can be used to determine whether the sizes should - // be clipped to the range [0:1]. At this time, normalization is only applied if - // PointScaleTypes is Linear or Power. - - // Note that we use a hard-coded UUID since we need it to always be the same across - // all WWT sessions so that we can remove it when it isn't needed. - private string NormalizeSizeColumnName = "dfe78b4c-f972-4796-b04f-68c5efd4ecb0"; - - protected bool normalizeSize = false; - - public bool NormalizeSize - { - get { return normalizeSize; } - set - { - if (normalizeSize != value) - { - version++; - normalizeSize = value; - } - } - } - - protected bool normalizeSizeClip = false; - - public bool NormalizeSizeClip - { - get { return normalizeSizeClip; } - set - { - if (normalizeSizeClip != value) - { - version++; - normalizeSizeClip = value; - } - } - } - - protected float normalizeSizeMin = 0; - - public float NormalizeSizeMin - { - get { return normalizeSizeMin; } - set - { - if (normalizeSizeMin != value) - { - version++; - normalizeSizeMin = value; - } - } - } - - protected float normalizeSizeMax = 1; - - public float NormalizeSizeMax - { - get { return normalizeSizeMax; } - set - { - if (normalizeSizeMax != value) - { - version++; - normalizeSizeMax = value; - } - } - } - - public float NormalizePointSize(float value) - { - - if (!NormalizeSize) - return value; - - float new_value = (value - NormalizeSizeMin) / (NormalizeSizeMax - NormalizeSizeMin); - - if (NormalizeSizeClip) - { - if (new_value < 0) - { - new_value = 0; - } - else if (new_value > 1) - { - new_value = 1; - } - } - - return new_value; - - } - - - protected int nameColumn = 0; - - - public int NameColumn - { - get { return nameColumn; } - set - { - if (nameColumn != value) - { - version++; - nameColumn = value; - } - } - } - private string hyperlinkFormat = ""; - - - public string HyperlinkFormat - { - get { return hyperlinkFormat; } - set - { - if (hyperlinkFormat != value) - { - version++; hyperlinkFormat = value; - } - } - } - - private int hyperlinkColumn = -1; - - - public int HyperlinkColumn - { - get { return hyperlinkColumn; } - set - { - if (hyperlinkColumn != value) - { - version++; - hyperlinkColumn = value; - } - } - } - - - protected float scaleFactor = 1.0f; - - - public float ScaleFactor - { - get { return scaleFactor; } - set - { - if (scaleFactor != value) - { - version++; - - scaleFactor = value; - } - } - } - - protected PointScaleTypes pointScaleType = PointScaleTypes.Power; - - - public PointScaleTypes PointScaleType - { - get { return pointScaleType; } - set - { - if (pointScaleType != value) - { - version++; - pointScaleType = value; - } - } - } - - - - protected List positions = new List(); - - protected LineList lineList; - protected LineList lineList2d; - protected TriangleList triangleList; - protected TriangleList triangleList2d; - - protected PointList pointList; - - protected bool bufferIsFlat = false; - - protected Date baseDate = new Date(2010, 0, 1, 12, 00, 00); - - static Texture circleTexture = null; - - static Texture CircleTexture - { - get { - if (circleTexture == null) { - string url = URLHelpers.singleton.engineAssetUrl("circle.png"); - circleTexture = Planets.LoadPlanetTexture(url); - } - - return circleTexture; - } - } - - public bool dirty = true; - - public int lastVersion = 0; - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - RenderContext device = renderContext; - - if (version != lastVersion) - { - CleanUp(); - } - - lastVersion = version; - - - if (bufferIsFlat != flat) - { - CleanUp(); - bufferIsFlat = flat; - } - - if (dirty) - { - PrepVertexBuffer(device, opacity); - } - - double jNow = SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate); - - float adjustedScale = scaleFactor*3; - - if (flat && astronomical && (markerScale == MarkerScales.World)) - { - adjustedScale = (float)(scaleFactor / (renderContext.ViewCamera.Zoom / 360)); - } - - if (triangleList2d != null) - { - triangleList2d.Decay = decay; - triangleList2d.Sky = this.Astronomical; - triangleList2d.TimeSeries = timeSeries; - triangleList2d.JNow = jNow; - triangleList2d.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - if (triangleList != null) - { - - triangleList.Decay = decay; - triangleList.Sky = this.Astronomical; - triangleList.TimeSeries = timeSeries; - triangleList.JNow = jNow; - triangleList.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - - if (pointList != null) - { - pointList.DepthBuffered = false; - pointList.ShowFarSide = ShowFarSide; - pointList.Decay = timeSeries ? decay : 0; - pointList.Sky = this.Astronomical; - pointList.TimeSeries = timeSeries; - pointList.JNow = jNow; - pointList.scale = (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale; - switch (plotType) - { - case PlotTypes.Gaussian: - pointList.Draw(renderContext, opacity * Opacity, false); - break; - case PlotTypes.Circle: - pointList.DrawTextured(renderContext, CircleTexture.Texture2d, opacity * Opacity); - break; - case PlotTypes.Point: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(19), opacity * Opacity); - break; - case PlotTypes.Square: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(35), opacity * Opacity); - break; - case PlotTypes.Custom: - case PlotTypes.PushPin: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(markerIndex), opacity * Opacity); - break; - - default: - break; - } - - } - - if (lineList != null) - { - lineList.Sky = this.Astronomical; - lineList.Decay = decay; - lineList.TimeSeries = timeSeries; - lineList.JNow = jNow; - lineList.DrawLines(renderContext, opacity * Opacity); - } - - if (lineList2d != null) - { - lineList2d.Sky = this.Astronomical; - lineList2d.Decay = decay; - lineList2d.TimeSeries = timeSeries; - lineList2d.ShowFarSide = ShowFarSide; - lineList2d.JNow = jNow; - lineList2d.DrawLines(renderContext, opacity * Opacity); - } - - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - - //TextureOperation oldTexOp = device.TextureState[0].ColorOperation; - - //bool zBufferEnabled = device.RenderState.ZBufferEnable; - - //if (astronomical && !bufferIsFlat) - //{ - // device.RenderState.ZBufferEnable = true; - //} - //else - //{ - // device.RenderState.ZBufferEnable = false; - //} - //device.TextureState[0].ColorOperation = TextureOperation.Disable; - - //FillMode oldMode = device.RenderState.FillMode; - //DateTime baseDate = new DateTime(2010, 1, 1, 12, 00, 00); - //device.RenderState.FillMode = FillMode.Solid; - //device.SetTexture(0, null); - //device.Indices = shapeFileIndex; - //device.VertexShader = shaderA; - //// Vector3 cam = Vector3d.TransformCoordinate(Earth3d.cameraPosition, Matrix3d.Invert(renderContext.World)).Vector3; - //Vector3 cam = Vector3.TransformCoordinate(renderContext.CameraPosition.Vector3, Matrix.Invert(renderContext.Device.Transform.World)); - //constantTableA.SetValue(device, cameraHandleA, new Vector4(cam.X, cam.Y, cam.Z, 1)); - //constantTableA.SetValue(device, jNowHandleA, (float)(SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate))); - //constantTableA.SetValue(device, decayHandleA, timeSeries ? decay : 0f); - - //float adjustedScale = scaleFactor; - - //if (flat && astronomical && (markerScale == MarkerScales.World)) - //{ - // adjustedScale = (float)(scaleFactor / (Earth3d.MainWindow.ZoomFactor / 360)); - //} - //constantTableA.SetValue(device, scaleHandleA, (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale); - //constantTableA.SetValue(device, skyHandleA, astronomical ? -1 : 1); - //constantTableA.SetValue(device, opacityHandleA, opacity * this.Opacity); - //constantTableA.SetValue(device, showFarSideHandleA, ShowFarSide ? 1f : 0f); - - //// Matrix matrixWVP = Earth3d.WorldMatrix * Earth3d.ViewMatrix * Earth3d.ProjMatrix; - ////Matrix matrixWVP = device.Transform.World * device.Transform.View * device.Transform.Projection; - //Matrix3d matrixWVP = renderContext.World * renderContext.View * renderContext.Projection; - - //constantTableA.SetValue(device, worldViewHandleA, matrixWVP.Matrix); - - //device.SetStreamSource(0, shapeFileVertex, 0); - ////device.VertexFormat = VertexFormats.None; - ////device.VertexDeclaration = vertexDeclA; - //device.VertexFormat = PointVertex.Format; - - //device.RenderState.PointSpriteEnable = plotType != PlotTypes.Point; - - //device.RenderState.PointScaleEnable = (markerScale == MarkerScales.World && plotType != PlotTypes.Point) ? true : false; - //device.RenderState.PointSize = 0; - //device.RenderState.PointScaleA = 0; - //device.RenderState.PointScaleB = 0; - - //device.RenderState.PointScaleC = 10000000f; - - //switch (plotType) - //{ - // case PlotTypes.Gaussian: - // device.SetTexture(0, Grids.StarProfile); - // break; - // case PlotTypes.Circle: - // device.SetTexture(0, CircleTexture); - // break; - // case PlotTypes.Point: - // device.SetTexture(0, null); - // break; - // //case PlotTypes.Square: - // // device.SetTexture(0, null); - // // break; - // //case PlotTypes.Custom: - // // break; - // case PlotTypes.PushPin: - // device.SetTexture(0, PushPin.GetPushPinTexture(markerIndex)); - // break; - - // default: - // break; - //} - - - - //device.RenderState.CullMode = Cull.None; - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //if (plotType == PlotTypes.Gaussian) - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.One; - //} - //else - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //} - - - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - //device.TextureState[0].ColorOperation = TextureOperation.Modulate; - //device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; - //device.TextureState[0].AlphaOperation = TextureOperation.Modulate; - //device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; - - //device.TextureState[1].ColorOperation = TextureOperation.Disable; - //device.TextureState[1].ColorArgument1 = TextureArgument.Current; - //device.TextureState[1].ColorArgument2 = TextureArgument.Constant; - //device.TextureState[1].AlphaOperation = TextureOperation.Disable; - //device.TextureState[1].AlphaArgument1 = TextureArgument.Current; - //device.TextureState[1].AlphaArgument2 = TextureArgument.Constant; - - //device.TextureState[1].ConstantColor = Color.FromArgb(255, 255, 255, 255); - //// device.TextureState[1].ConstantColor = Color.FromArgb(0, 0, 0, 0); - - - - //device.DrawPrimitives(PrimitiveType.PointList, 0, shapeVertexCount); - //device.RenderState.PointSpriteEnable = false; - - - ////device.DrawUserPrimitives(PrimitiveType.LineList, segments, points); - - //device.RenderState.FillMode = oldMode; - //device.TextureState[0].ColorOperation = oldTexOp; - //device.VertexShader = null; - - //device.RenderState.ZBufferEnable = zBufferEnabled; - //device.RenderState.AlphaBlendEnable = false; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlue; - return true; - } - - - //protected static EffectHandle worldViewHandleA = null; - //protected static EffectHandle cameraHandleA = null; - //protected static EffectHandle jNowHandleA = null; - //protected static EffectHandle decayHandleA = null; - //protected static EffectHandle scaleHandleA = null; - //protected static EffectHandle skyHandleA = null; - //protected static EffectHandle opacityHandleA = null; - //protected static EffectHandle showFarSideHandleA = null; - //protected static ConstantTable constantTableA = null; - //protected static VertexShader shaderA = null; - //protected static VertexDeclaration vertexDeclA = null; - - //protected static void MakeVertexShaderA(Device device) - //{ - // // Create the vertex shader and declaration - // VertexElement[] elements = new VertexElement[] - // { - // new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), - // new VertexElement(0, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.PointSize, 0), - // new VertexElement(0, 0, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), - // new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), - // VertexElement.VertexDeclarationEnd - // }; - - // vertexDeclA = new VertexDeclaration(device, elements); - - // ShaderFlags shaderFlags = 0; - - // string errors; - - // string shaderText = - - // " float4x4 matWVP; " + - // " float4 camPos : POSITION; " + - // " float1 jNow; " + - // " float1 decay; " + - // " float1 scale; " + - // " float1 opacity; " + - // " float1 sky; " + - // " float1 showFarSide; " + - // " struct VS_IN " + - // " { " + - // " float4 ObjPos : POSITION; " + // Object space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + // Vertex color - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " struct VS_OUT " + - // " { " + - // " float4 ProjPos : POSITION; " + // Projected space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " VS_OUT main( VS_IN In ) " + - // " { " + - // " float dotCam = dot((camPos.xyz - In.ObjPos.xyz), In.ObjPos.xyz); " + - // " float dist = distance(In.ObjPos, camPos.xyz); " + - // " VS_OUT Out; " + - // " float dAlpha = 1; " + - // " if ( decay > 0) " + - // " { " + - // " dAlpha = 1 - ((jNow - In.Time.y) / decay); " + - // " if (dAlpha > 1 ) " + - // " { " + - // " dAlpha = 1; " + - // " } " + - // " " + - // " } " + - // " Out.ProjPos = mul(In.ObjPos, matWVP ); " + // Transform vertex into - // " if (showFarSide == 0 && (dotCam * sky) < 0 || (jNow < In.Time.x && decay > 0)) " + - // " { " + - // " Out.Color.a = 0; " + - // " } " + - // " else " + - // " { " + - // " Out.Color.a = In.Color.a * dAlpha * opacity; " + - // " } " + - // " Out.Color.r = In.Color.r; " + - // " Out.Color.g = In.Color.g; " + - // " Out.Color.b = In.Color.b; " + - // " Out.Time.x = 0; " + - // " Out.Time.y = 0; " + - // " if ( scale > 0) " + - // " { " + - // " Out.PointSize = scale * (In.PointSize )/ dist;" + - // " } " + - // " else " + - // " { " + - // " Out.PointSize = -scale *In.PointSize;" + - // " } " + - // " if (Out.PointSize > 256) " + - // " { " + - // " Out.PointSize = 256; " + - // " } " + - // " return Out; " + // Transfer color - // " } "; - - // using (GraphicsStream code = ShaderLoader.CompileShader(shaderText, "main", null, null, - // "vs_2_0", shaderFlags, out errors, out constantTableA)) - // { - - // // We will store these constants in an effect handle here for performance reasons. - // // You could simply use the string value (i.e., "worldViewProj") in the SetValue call - // // and it would work just as well, but that actually requires an allocation to be made - // // and can actually slow your performance down. It's much more efficient to simply - // // cache these handles for use later - // worldViewHandleA = constantTableA.GetConstant(null, "matWVP"); - // cameraHandleA = constantTableA.GetConstant(null, "camPos"); - // jNowHandleA = constantTableA.GetConstant(null, "jNow"); - // decayHandleA = constantTableA.GetConstant(null, "decay"); - // scaleHandleA = constantTableA.GetConstant(null, "scale"); - // skyHandleA = constantTableA.GetConstant(null, "sky"); - // opacityHandleA = constantTableA.GetConstant(null, "opacity"); - // showFarSideHandleA = constantTableA.GetConstant(null, "showFarSide"); - - // // Create the shader - // shaderA = new VertexShader(device, code); - // } - //} - - - - public void CleanUpBase() - { - - - if (lineList != null) - { - lineList.Clear(); - } - if (lineList2d != null) - { - lineList2d.Clear(); - } - - if (triangleList2d != null) - { - triangleList2d.Clear(); - } - - if (pointList != null) - { - pointList.Clear(); - } - - if (triangleList != null) - { - triangleList.Clear(); - } - } - } - - - public class CatalogSpreadSheetLayer : SpreadSheetLayer - { - // HashSet not compilable with scriptSharp - private Dictionary addedTiles = new Dictionary(); - public void AddTileRows(string tileKey, List> catalogRows) - { - if (!addedTiles.ContainsKey(tileKey)) - { - foreach (List row in catalogRows) - { - Table.Rows.Add(row); - } - dirty = true; - addedTiles[tileKey] = true; - } - } - - public void RemoveTileRows(string tileKey, List> catalogRows) - { - if (addedTiles.ContainsKey(tileKey)) - { - foreach (List row in catalogRows) - { - Table.Rows.Remove(row); - } - dirty = true; - addedTiles.Remove(tileKey); - } - } - - public override void CleanUp() - { - base.CleanUp(); - addedTiles.Clear(); - Table.Rows.Clear(); - } - } - - - //public struct PointVertex - //{ - // public Vector3 Position; - // public float PointSize; - // public int Color; - // public float Tu; - // public float Tv; - // public static readonly VertexFormats Format = VertexFormats.Position | VertexFormats.PointSize | VertexFormats.Texture1 | VertexFormats.Diffuse; - // public PointVertex(Vector3 position, float size, float time, int color) - // { - // Position = position; - // PointSize = size; - // Tu = time; - // Tv = 0; - // Color = color; - // } - //} - //public struct TimeSeriesLineVertex - //{ - // public Vector3 Position; - // public Vector3 Normal; - // public int Color; - // public float Tu; - // public float Tv; - // public static readonly VertexFormats Format = VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture1 | VertexFormats.Diffuse; - // public TimeSeriesLineVertex(Vector3 position, Vector3 normal, float time, int color) - // { - // Position = position; - // Normal = normal; - // Tu = time; - // Tv = 0; - // Color = color; - // } - //} - - public class KmlCoordinate - { - public double Lat; - public double Lng; - public double Alt; - public Dates Date; - } - - public class KmlLineList - { - public bool extrude; - public bool Astronomical = false; - - public double MeanRadius = 6371000; - - public List PointList = new List(); - - public void ParseWkt(string geoText, string option, double alt, Dates date) - { - //todo fix the WKT parser - List parts = UiTools.Split(geoText, "(,)"); - foreach (string part in parts) - { - string[] coordinates = part.Trim().Split(" "); - if (coordinates.Length > 1) - { - KmlCoordinate pnt = new KmlCoordinate(); - pnt.Lng = double.Parse(coordinates[0]); - if (Astronomical) - { - pnt.Lng -= 180; - } - pnt.Lat = double.Parse(coordinates[1]); - if (coordinates.Length > 2 && alt == 0) - { - pnt.Alt = double.Parse(coordinates[2]); - } - else - { - pnt.Alt = alt; - } - pnt.Date = date; - PointList.Add(pnt); - } - } - } - - - public KmlCoordinate GetCenterPoint() - { - KmlCoordinate point = new KmlCoordinate(); - point.Lat = 0; - point.Lng = 0; - point.Alt = 0; - - - foreach (KmlCoordinate pnt in PointList) - { - point.Lat += pnt.Lat; - point.Lng += pnt.Lng; - point.Alt += pnt.Alt; - } - point.Lat /= PointList.Count; - point.Lng /= PointList.Count; - point.Alt /= PointList.Count; - - return point; - } - } - - public class PushPin - { - static Dictionary pinTextureCache = new Dictionary(); - static Texture Pins = null; - - public static void TriggerLoadSprite() - { - if (Pins == null) { - Pins = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("pins.png")); - } - } - - public static WebGLTexture GetPushPinTexture(int pinId) - { - WebGLTexture texture = null; - - if (pinTextureCache.ContainsKey(pinId)) - { - return pinTextureCache[pinId]; - } - - try - { - texture = Tile.PrepDevice.createTexture(); - - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, texture); - - int row = Math.Floor(pinId / 16); - int col = pinId % 16; - - CanvasElement temp = (CanvasElement)Document.CreateElement("canvas"); - temp.Height = 32; - temp.Width = 32; - CanvasContext2D ctx = (CanvasContext2D)temp.GetContext(Rendering.Render2D); - ctx.DrawImage(Pins.ImageElement, (col * 32), (row * 32), 32, 32, 0, 0, 32, 32); - - //Substitute the resized image - ImageElement image = (ImageElement)(Element)temp; - - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, image); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_NEAREST); - Tile.PrepDevice.generateMipmap(GL.TEXTURE_2D); - - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, null); - pinTextureCache[pinId] = texture; - } - catch - { - - } - return texture; - } - - //static Dictionary pinBitmapCache = new Dictionary(); - - //public static Bitmap GetPushPinBitmap(int pinId) - //{ - // if (pinBitmapCache.ContainsKey(pinId)) - // { - // return pinBitmapCache[pinId]; - // } - - // Bitmap bmp = new Bitmap(32, 32, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - // Graphics gOut = Graphics.FromImage(bmp); - - // int row = pinId / 16; - // int col = pinId % 16; - // gOut.DrawImage(Pins, new Rectangle(0, 0, 32, 32), (col * 32), (row * 32), 32, 32, GraphicsUnit.Pixel); - - // gOut.Flush(); - // gOut.Dispose(); - // pinBitmapCache.Add(pinId, bmp); - // return bmp; - //} - - //public static void DrawAt(Graphics g, int pinId, int x, int y) - //{ - // int row = pinId / 16; - // int col = pinId % 16; - // g.DrawImage(Pins, new Rectangle(x, y, 32, 32), (col * 32), (row * 32), 32, 32, GraphicsUnit.Pixel); - - //} - - //public static int PinCount - //{ - // get - // { - // return 348; - // } - //} - } -} diff --git a/engine/csharp_ref/Layers/Table.cs b/engine/csharp_ref/Layers/Table.cs deleted file mode 100644 index cd1a836a..00000000 --- a/engine/csharp_ref/Layers/Table.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class Table - { - public Table() - { - } - - public Guid Guid = new Guid(); - public List Header = new List(); - public List> Rows = new List>(); - public string Delimiter = "\t"; - public bool Locked = false; - - // private Mutex tableMutex = new Mutex(); - - public void Lock() - { - Locked = true; - // tableMutex.WaitOne(); - } - - public void Unlock() - { - Locked = false; - // tableMutex.ReleaseMutex(); - } - - public string Save() - { - string data = ""; - - bool first = true; - - foreach (string col in Header) - { - if (!first) - { - data += "\t"; - } - else - { - first = false; - } - - data += col; - } - data += "\r\n"; - foreach (string[] row in Rows) - { - first = true; - foreach (string col in row) - { - if (!first) - { - data += "\t"; - } - else - { - first = false; - } - - data += col; - } - data += "\r\n"; - } - - return data; - } - - //public void Save(string path) - //{ - - // using (Stream s = new FileStream(path, FileMode.Create)) - // { - // Save(s); - // } - //} - //public void Save(Stream stream) - //{ - // stream = new GZipStream(stream, CompressionMode.Compress); - - // StreamWriter sw = new StreamWriter(stream, Encoding.UTF8); - // bool first = true; - - // foreach (string col in Header) - // { - // if (!first) - // { - // sw.Write("\t"); - // } - // else - // { - // first = false; - // } - - // sw.Write(col); - // } - // sw.Write("\r\n"); - // foreach (string[] row in Rows) - // { - // first = true; - // foreach (string col in row) - // { - // if (!first) - // { - // sw.Write("\t"); - // } - // else - // { - // first = false; - // } - - // sw.Write(col); - // } - // sw.Write("\r\n"); - // } - // sw.Close(); - - - //} - - //public override string ToString() - //{ - // StringBuilder sb = new StringBuilder(); - - // StringWriter sw = new StringWriter(sb); - // bool first = true; - - // foreach (string col in Header) - // { - // if (!first) - // { - // sw.Write("\t"); - // } - // else - // { - // first = false; - // } - - // sw.Write(col); - // } - // sw.Write("\r\n"); - // foreach (string[] row in Rows) - // { - // first = true; - // foreach (string col in row) - // { - // if (!first) - // { - // sw.Write("\t"); - // } - // else - // { - // first = false; - // } - - // sw.Write(col); - // } - // sw.Write("\r\n"); - // } - // return sb.ToString(); - - //} - - //public static bool IsGzip(Stream stream) - //{ - // BinaryReader br = new BinaryReader(stream); - // byte[] line = br.ReadBytes(2); - - // if (line[0] == 31 && line[1] == 139) - // { - // return true; - // } - // else - // { - // return false; - // } - //} - - //public static Table Load(string path, char delimiter) - //{ - // if (path.ToLower().EndsWith("csv")) - // { - // delimiter = ','; - // } - - // using (Stream s = new FileStream(path, FileMode.Open)) - // { - // return Load(s, delimiter); - // } - //} - - //public static Table Load(Stream stream, char delimiter) - //{ - - // bool gZip = IsGzip(stream); - // stream.Seek(0, SeekOrigin.Begin); - // if (gZip) - // { - // stream = new GZipStream(stream, CompressionMode.Decompress); - // } - - // Table table = new Table(); - // table.Delimiter = delimiter; - - // StreamReader sr = new StreamReader(stream); - - // if (sr.Peek() >= 0) - // { - // string headerLine = sr.ReadLine(); - // table.Rows.Clear(); - // table.Header = UiTools.SplitString(headerLine, delimiter); - // } - // else - // { - // table.Header = new string[0]; - // } - - // int count = 0; - // while (sr.Peek() >= 0) - // { - // string line = sr.ReadLine(); - // string[] rowData = UiTools.SplitString(line, delimiter); - // if (rowData.Length < 2) - // { - // break; - // } - // table.Rows.Add(rowData); - // count++; - // } - // return table; - //} - - public void LoadFromString(string data, bool isUpdate, bool purge, bool hasHeader) - { - int count = 0; - string[] lines = data.Split("\r\n"); - if (!isUpdate || hasHeader) - { - if (lines.Length > 0) - { - string headerLine = lines[0]; - count++; - if (headerLine.IndexOf("\t") == -1 && headerLine.IndexOf(",") > -1) - { - Delimiter = ","; - } - - if (!isUpdate) - { - Rows.Clear(); - } - Header = UiTools.SplitString(headerLine, Delimiter); - } - else - { - Header = new List(); - } - } - List> temp = new List>(); - if (!purge) - { - temp = Rows; - } - - - while (count < lines.Length) - { - string line = lines[count]; - List rowData = UiTools.SplitString(line, Delimiter); - if (rowData.Count < 1) - { - break; - } - temp.Add(rowData); - count++; - } - if (purge) - { - Rows = temp; - } - - } - - //public void Append(string data) - //{ - // StringReader sr = new StringReader(data); - // int count = 0; - // while (sr.Peek() >= 0) - // { - // string line = sr.ReadLine(); - // string[] rowData = UiTools.SplitString(line, Delimiter); - // if (rowData.Length < 2) - // { - // break; - // } - // Rows.Add(rowData); - // count++; - // } - //} - - public Table Clone() - { - Table cloned_table = new Table(); - for (int i = 0; i < Header.Count; i++) - { - cloned_table.Header.Add(Header[i]); - } - for (int j = 0; j < Rows.Count; j++) - { - cloned_table.Rows.Add(new List()); - for (int i = 0; i < Rows[j].Count; i++) - { - cloned_table.Rows[j].Add(Rows[j][i]); - } - } - return cloned_table; - } - - public void AddColumn(string name, List data) - { - Header.Add(name); - for (int i = 0; i < data.Count; i++) - { - Rows[i].Add(data[i]); - } - } - - public void RemoveColumn(string name) { - int remove_index = Header.IndexOf(name); - if (remove_index > -1) - { - Header.RemoveAt(remove_index); - for (int i = 0; i < Rows.Count; i++) - { - Rows[i].RemoveAt(remove_index); - } - } - } - } -} diff --git a/engine/csharp_ref/Layers/TimeSeriesLayer.cs b/engine/csharp_ref/Layers/TimeSeriesLayer.cs deleted file mode 100644 index c4f175fb..00000000 --- a/engine/csharp_ref/Layers/TimeSeriesLayer.cs +++ /dev/null @@ -1,1319 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public enum CoordinatesTypes { Spherical = 0, Rectangular = 1, Orbital = 2 }; - public enum AltTypes { Depth = 0, Altitude = 1, Distance = 2, SeaLevel = 3, Terrain = 4 }; - - public enum MarkerMixes { Same_For_All = 0, /*Group_by_Range, Group_by_Values */}; - public enum ColorMaps { Same_For_All = 0, /*Group_by_Range=1, */Group_by_Values = 2, Per_Column_Literal = 3/*, Gradients_by_Range=4*/}; - - public enum PlotTypes { Gaussian = 0, Point = 1, Circle = 2, Square = 3, PushPin = 4, Custom=5 }; - - public enum MarkerScales { Screen = 0, World = 1 }; - public enum RAUnits { Hours = 0, Degrees = 1 }; - - - public class TimeSeriesLayer : Layer - { - protected bool isLongIndex = false; - protected int shapeVertexCount; - - - protected bool lines = false; - protected int latColumn = -1; - protected float fixedSize = 1; - protected float decay = 16; - protected bool timeSeries = false; - - private bool dynamicData = false; - - - public bool DynamicData - { - get { return dynamicData; } - set { dynamicData = value; } - } - - private bool autoUpdate = false; - - - public bool AutoUpdate - { - get { return autoUpdate; } - set { autoUpdate = value; } - } - - string dataSourceUrl = ""; - - public string DataSourceUrl - { - get { return dataSourceUrl; } - set { dataSourceUrl = value; } - } - - - - - - public bool TimeSeries - { - get { return timeSeries; } - set - { - if (timeSeries != value) - { - version++; - timeSeries = value; - } - } - } - - - public virtual List Header - { - get - { - return null; - } - } - - Date beginRange = new Date("1/1/2100"); - - - public Date BeginRange - { - get { return beginRange; } - set - { - if (beginRange != value) - { - version++; - beginRange = value; - } - } - } - Date endRange = new Date("01/01/1800"); - - public Date EndRange - { - get { return endRange; } - set - { - if (endRange != value) - { - version++; - endRange = value; - } - } - } - - - public override void InitializeFromXml(XmlNode node) - { - TimeSeries = bool.Parse(node.Attributes.GetNamedItem("TimeSeries").Value); - BeginRange = new Date(node.Attributes.GetNamedItem("BeginRange").Value); - EndRange = new Date(node.Attributes.GetNamedItem("EndRange").Value); - Decay = Single.Parse(node.Attributes.GetNamedItem("Decay").Value); - - CoordinatesType = (CoordinatesTypes)Enums.Parse("CoordinatesTypes", node.Attributes.GetNamedItem("CoordinatesType").Value); - - - if ((int)CoordinatesType < 0) - { - CoordinatesType = CoordinatesTypes.Spherical; - } - LatColumn = int.Parse(node.Attributes.GetNamedItem("LatColumn").Value); - LngColumn = int.Parse(node.Attributes.GetNamedItem("LngColumn").Value); - if (node.Attributes.GetNamedItem("GeometryColumn") != null) - { - GeometryColumn = int.Parse(node.Attributes.GetNamedItem("GeometryColumn").Value); - } - - switch (node.Attributes.GetNamedItem("AltType").Value) - { - case "Depth": - AltType = AltTypes.Depth; - break; - case "Altitude": - AltType = AltTypes.Altitude; - break; - case "Distance": - AltType = AltTypes.Distance; - break; - case "SeaLevel": - AltType = AltTypes.SeaLevel; - break; - case "Terrain": - AltType = AltTypes.Terrain; - break; - default: - break; - } - - - - MarkerMix = MarkerMixes.Same_For_All; - - switch (node.Attributes.GetNamedItem("ColorMap").Value) - { - case "Same_For_All": - ColorMap = ColorMaps.Same_For_All; - break; - case "Group_by_Values": - ColorMap = ColorMaps.Group_by_Values; - break; - case "Per_Column_Literal": - ColorMap = ColorMaps.Per_Column_Literal; - break; - default: - break; - } - - - MarkerColumn = int.Parse(node.Attributes.GetNamedItem("MarkerColumn").Value); - ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("ColorMapColumn").Value); - - switch (node.Attributes.GetNamedItem("PlotType").Value) - { - case "Gaussian": - PlotType = PlotTypes.Gaussian; - break; - case "Point": - PlotType = PlotTypes.Point; - break; - case "Circle": - PlotType = PlotTypes.Circle; - break; - case "PushPin": - PlotType = PlotTypes.PushPin; - break; - default: - break; - } - - MarkerIndex = int.Parse(node.Attributes.GetNamedItem("MarkerIndex").Value); - - switch (node.Attributes.GetNamedItem("MarkerScale").Value) - { - case "Screen": - MarkerScale = MarkerScales.Screen; - break; - case "World": - MarkerScale = MarkerScales.World; - break; - default: - break; - } - - switch (node.Attributes.GetNamedItem("AltUnit").Value) - { - case "Meters": - AltUnit = AltUnits.Meters; - break; - case "Feet": - AltUnit = AltUnits.Feet; - break; - case "Inches": - AltUnit = AltUnits.Inches; - break; - case "Miles": - AltUnit = AltUnits.Miles; - break; - case "Kilometers": - AltUnit = AltUnits.Kilometers; - break; - case "AstronomicalUnits": - AltUnit = AltUnits.AstronomicalUnits; - break; - case "LightYears": - AltUnit = AltUnits.LightYears; - break; - case "Parsecs": - AltUnit = AltUnits.Parsecs; - break; - case "MegaParsecs": - AltUnit = AltUnits.MegaParsecs; - break; - case "Custom": - AltUnit = AltUnits.Custom; - break; - default: - break; - } - - AltColumn = int.Parse(node.Attributes.GetNamedItem("AltColumn").Value); - StartDateColumn = int.Parse(node.Attributes.GetNamedItem("StartDateColumn").Value); - EndDateColumn = int.Parse(node.Attributes.GetNamedItem("EndDateColumn").Value); - SizeColumn = int.Parse(node.Attributes.GetNamedItem("SizeColumn").Value); - HyperlinkFormat = node.Attributes.GetNamedItem("HyperlinkFormat").Value; - HyperlinkColumn = int.Parse(node.Attributes.GetNamedItem("HyperlinkColumn").Value); - ScaleFactor = Single.Parse(node.Attributes.GetNamedItem("ScaleFactor").Value); - - switch (node.Attributes.GetNamedItem("PointScaleType").Value) - { - case "Linear": - PointScaleType = PointScaleTypes.Linear; - break; - case "Power": - PointScaleType = PointScaleTypes.Power; - break; - case "Log": - PointScaleType = PointScaleTypes.Log; - break; - case "Constant": - PointScaleType = PointScaleTypes.Constant; - break; - case "StellarMagnitude": - PointScaleType = PointScaleTypes.StellarMagnitude; - break; - default: - break; - } - - - if (node.Attributes.GetNamedItem("ShowFarSide") != null) - { - ShowFarSide = Boolean.Parse(node.Attributes.GetNamedItem("ShowFarSide").Value); - } - - if (node.Attributes.GetNamedItem("RaUnits") != null) - { - // RaUnits = (RAUnits)Enum.Parse(typeof(RAUnits), node.Attributes["RaUnits"].Value); - - switch (node.Attributes.GetNamedItem("RaUnits").Value) - { - case "Hours": - RaUnits = RAUnits.Hours; - break; - case "Degrees": - RaUnits = RAUnits.Degrees; - break; - } - } - - if (node.Attributes.GetNamedItem("HoverTextColumn") != null) - { - NameColumn = int.Parse(node.Attributes.GetNamedItem("HoverTextColumn").Value); - } - - - if (node.Attributes.GetNamedItem("XAxisColumn") != null) - { - XAxisColumn = int.Parse(node.Attributes.GetNamedItem("XAxisColumn").Value); - XAxisReverse = bool.Parse(node.Attributes.GetNamedItem("XAxisReverse").Value); - YAxisColumn = int.Parse(node.Attributes.GetNamedItem("YAxisColumn").Value); - YAxisReverse = bool.Parse(node.Attributes.GetNamedItem("YAxisReverse").Value); - ZAxisColumn = int.Parse(node.Attributes.GetNamedItem("ZAxisColumn").Value); - ZAxisReverse = bool.Parse(node.Attributes.GetNamedItem("ZAxisReverse").Value); - - switch (node.Attributes.GetNamedItem("CartesianScale").Value) - { - case "Meters": - CartesianScale = AltUnits.Meters; - break; - case "Feet": - CartesianScale = AltUnits.Feet; - break; - case "Inches": - CartesianScale = AltUnits.Inches; - break; - case "Miles": - CartesianScale = AltUnits.Miles; - break; - case "Kilometers": - CartesianScale = AltUnits.Kilometers; - break; - case "AstronomicalUnits": - CartesianScale = AltUnits.AstronomicalUnits; - break; - case "LightYears": - CartesianScale = AltUnits.LightYears; - break; - case "Parsecs": - CartesianScale = AltUnits.Parsecs; - break; - case "MegaParsecs": - CartesianScale = AltUnits.MegaParsecs; - break; - case "Custom": - CartesianScale = AltUnits.Custom; - break; - default: - break; - } - - - CartesianCustomScale = double.Parse(node.Attributes.GetNamedItem("CartesianCustomScale").Value); - - - } - - if (node.Attributes.GetNamedItem("DynamicData") != null) - { - DynamicData = bool.Parse(node.Attributes.GetNamedItem("DynamicData").Value); - AutoUpdate = bool.Parse(node.Attributes.GetNamedItem("AutoUpdate").Value); - DataSourceUrl = node.Attributes.GetNamedItem("DataSourceUrl").Value; - } - - - } - - - public virtual void ComputeDateDomainRange(int columnStart, int columnEnd) - { - } - public Dictionary MarkerDomainValues = new Dictionary(); - public Dictionary ColorDomainValues = new Dictionary(); - - public virtual List GetDomainValues(int column) - { - return new List(); - } - - - public float Decay - { - get { return decay; } - set - { - if (decay != value) - { - version++; - decay = value; - } - } - } - - - private CoordinatesTypes coordinatesType = CoordinatesTypes.Spherical; - - - public CoordinatesTypes CoordinatesType - { - get { return coordinatesType; } - set - { - if (coordinatesType != value) - { - version++; - coordinatesType = value; - } - } - } - - - public int LatColumn - { - get { return latColumn; } - set - { - if (latColumn != value) - { - version++; - latColumn = value; - } - } - } - protected int lngColumn = -1; - - - public int LngColumn - { - get { return lngColumn; } - set - { - if (lngColumn != value) - { - version++; - lngColumn = value; - } - } - } - - protected int geometryColumn = -1; - - - public int GeometryColumn - { - get { return geometryColumn; } - set - { - if (geometryColumn != value) - { - version++; - geometryColumn = value; - } - } - } - - private int xAxisColumn = -1; - - - public int XAxisColumn - { - get { return xAxisColumn; } - set - { - if (xAxisColumn != value) - { - version++; - xAxisColumn = value; - } - } - } - private int yAxisColumn = -1; - - - public int YAxisColumn - { - get { return yAxisColumn; } - set - { - if (yAxisColumn != value) - { - version++; - yAxisColumn = value; - } - } - } - private int zAxisColumn = -1; - - - public int ZAxisColumn - { - get { return zAxisColumn; } - set - { - if (zAxisColumn != value) - { - version++; - zAxisColumn = value; - } - } - } - - private bool xAxisReverse = false; - - - public bool XAxisReverse - { - get { return xAxisReverse; } - set - { - if (xAxisReverse != value) - { - version++; - xAxisReverse = value; - } - } - } - private bool yAxisReverse = false; - - - public bool YAxisReverse - { - get { return yAxisReverse; } - set - { - if (yAxisReverse != value) - { - version++; - yAxisReverse = value; - } - } - } - private bool zAxisReverse = false; - - - public bool ZAxisReverse - { - get { return zAxisReverse; } - set - { - if (zAxisReverse != value) - { - version++; - zAxisReverse = value; - } - } - } - - private AltTypes altType = AltTypes.SeaLevel; - - - public AltTypes AltType - { - get { return altType; } - set - { - if (altType != value) - { - version++; - altType = value; - } - } - } - - - private MarkerMixes markerMix = MarkerMixes.Same_For_All; - - - public MarkerMixes MarkerMix - { - get { return markerMix; } - set - { - if (markerMix != value) - { - version++; - markerMix = value; - } - } - } - - RAUnits raUnits = RAUnits.Hours; - - public RAUnits RaUnits - { - get { return raUnits; } - set - { - - if (raUnits != value) - { - version++; - raUnits = value; - } - } - } - - private ColorMaps colorMap = ColorMaps.Per_Column_Literal; - - - internal ColorMaps ColorMap - { - get { return colorMap; } - set - { - if (colorMap != value) - { - version++; - colorMap = value; - } - } - } - - - private int markerColumn = -1; - - - public int MarkerColumn - { - get { return markerColumn; } - set - { - if (markerColumn != value) - { - version++; - markerColumn = value; - } - } - } - - private int colorMapColumn = -1; - - - public int ColorMapColumn - { - get { return colorMapColumn; } - set - { - if (colorMapColumn != value) - { - version++; - colorMapColumn = value; - } - } - } - - private PlotTypes plotType = PlotTypes.Gaussian; - - - public PlotTypes PlotType - { - get { return plotType; } - set - { - if (plotType != value) - { - version++; - plotType = value; - } - - } - } - - private int markerIndex = 0; - - - public int MarkerIndex - { - get { return markerIndex; } - set - { - if (markerIndex != value) - { - version++; - markerIndex = value; - } - } - } - - private bool showFarSide = false; - - - public bool ShowFarSide - { - get { return showFarSide; } - set - { - if (showFarSide != value) - { - version++; - showFarSide = value; - } - } - } - - - private MarkerScales markerScale = MarkerScales.World; - - - public MarkerScales MarkerScale - { - get { return markerScale; } - set - { - if (markerScale != value) - { - version++; - markerScale = value; - } - } - } - - - private AltUnits altUnit = AltUnits.Meters; - - - public AltUnits AltUnit - { - get { return altUnit; } - set - { - if (altUnit != value) - { - version++; - altUnit = value; - } - } - } - private AltUnits cartesianScale = AltUnits.Meters; - - - public AltUnits CartesianScale - { - get { return cartesianScale; } - set - { - if (cartesianScale != value) - { - version++; - cartesianScale = value; - } - } - } - - private double cartesianCustomScale = 1; - - - public double CartesianCustomScale - { - get { return cartesianCustomScale; } - set - { - if (cartesianCustomScale != value) - { - version++; - cartesianCustomScale = value; - } - } - } - - protected int altColumn = -1; - - public int AltColumn - { - get { return altColumn; } - set - { - if (altColumn != value) - { - version++; - altColumn = value; - } - } - } - - protected int startDateColumn = -1; - - - public int StartDateColumn - { - get { return startDateColumn; } - set - { - if (startDateColumn != value) - { - version++; - startDateColumn = value; - } - } - } - protected int endDateColumn = -1; - - - public int EndDateColumn - { - get { return endDateColumn; } - set - { - if (endDateColumn != value) - { - version++; - endDateColumn = value; - } - } - } - - protected int sizeColumn = -1; - - - public int SizeColumn - { - get { return sizeColumn; } - set - { - if (sizeColumn != value) - { - version++; - sizeColumn = value; - } - } - } - protected int nameColumn = 0; - - - public int NameColumn - { - get { return nameColumn; } - set - { - if (nameColumn != value) - { - version++; - nameColumn = value; - } - } - } - private string hyperlinkFormat = ""; - - - public string HyperlinkFormat - { - get { return hyperlinkFormat; } - set - { - if (hyperlinkFormat != value) - { - version++; hyperlinkFormat = value; - } - } - } - - private int hyperlinkColumn = -1; - - - public int HyperlinkColumn - { - get { return hyperlinkColumn; } - set - { - if (hyperlinkColumn != value) - { - version++; - hyperlinkColumn = value; - } - } - } - - - protected float scaleFactor = 1.0f; - - - public float ScaleFactor - { - get { return scaleFactor; } - set - { - if (scaleFactor != value) - { - version++; - - scaleFactor = value; - } - } - } - - protected PointScaleTypes pointScaleType = PointScaleTypes.Power; - - - public PointScaleTypes PointScaleType - { - get { return pointScaleType; } - set - { - if (pointScaleType != value) - { - version++; - pointScaleType = value; - } - } - } - - - - protected List positions = new List(); - - protected LineList lineList; - protected LineList lineList2d; - protected TriangleList triangleList; - protected TriangleList triangleList2d; - - protected PointList pointList; - - protected bool bufferIsFlat = false; - - protected Date baseDate = new Date(2010, 0, 1, 12, 00, 00); - - static ImageElement circleTexture = null; - - static ImageElement CircleTexture - { - get - { - //if (circleTexture == null) - //{ - // circleTexture = UiTools.LoadTextureFromBmp(Tile.prepDevice, Properties.Resources.circle, 0); - //} - - return circleTexture; - } - } - public bool dirty = true; - protected virtual bool PrepVertexBuffer(RenderContext renderContext, float opacity) - { - return true; - } - - public int lastVersion = 0; - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - RenderContext device = renderContext; - - if (version != lastVersion) - { - CleanUp(); - } - - if (bufferIsFlat != flat) - { - CleanUp(); - bufferIsFlat = flat; - } - - if (dirty) - { - PrepVertexBuffer(device, opacity); - } - - double jNow = SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate); - - - float adjustedScale = scaleFactor; - - if (flat && astronomical && (markerScale == MarkerScales.World)) - { - adjustedScale = (float)(scaleFactor / (renderContext.ViewCamera.Zoom / 360)); - } - - - if (triangleList2d != null) - { - triangleList2d.Decay = decay; - triangleList2d.Sky = this.Astronomical; - triangleList2d.TimeSeries = timeSeries; - triangleList2d.JNow = jNow; - triangleList2d.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - if (triangleList != null) - { - triangleList.Decay = decay; - triangleList.Sky = this.Astronomical; - triangleList.TimeSeries = timeSeries; - triangleList.JNow = jNow; - triangleList.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - - if (pointList != null) - { - pointList.DepthBuffered = false; - pointList.Decay = decay; - pointList.Sky = this.Astronomical; - pointList.TimeSeries = timeSeries; - pointList.JNow = jNow; - pointList.scale = (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale; - pointList.Draw(renderContext, opacity * Opacity, false); - } - - if (lineList != null) - { - lineList.Sky = this.Astronomical; - lineList.Decay = decay; - lineList.TimeSeries = timeSeries; - lineList.JNow = jNow; - lineList.DrawLines(renderContext, opacity * Opacity); - } - - if (lineList2d != null) - { - lineList2d.Sky = this.Astronomical; - lineList2d.Decay = decay; - lineList2d.TimeSeries = timeSeries; - lineList2d.ShowFarSide = ShowFarSide; - lineList2d.JNow = jNow; - lineList2d.DrawLines(renderContext, opacity * Opacity); - } - - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - - //TextureOperation oldTexOp = device.TextureState[0].ColorOperation; - - //bool zBufferEnabled = device.RenderState.ZBufferEnable; - - //if (astronomical && !bufferIsFlat) - //{ - // device.RenderState.ZBufferEnable = true; - //} - //else - //{ - // device.RenderState.ZBufferEnable = false; - //} - //device.TextureState[0].ColorOperation = TextureOperation.Disable; - - //FillMode oldMode = device.RenderState.FillMode; - //DateTime baseDate = new DateTime(2010, 1, 1, 12, 00, 00); - //device.RenderState.FillMode = FillMode.Solid; - //device.SetTexture(0, null); - //device.Indices = shapeFileIndex; - //device.VertexShader = shaderA; - //// Vector3 cam = Vector3d.TransformCoordinate(Earth3d.cameraPosition, Matrix3d.Invert(renderContext.World)).Vector3; - //Vector3 cam = Vector3.TransformCoordinate(renderContext.CameraPosition.Vector3, Matrix.Invert(renderContext.Device.Transform.World)); - //constantTableA.SetValue(device, cameraHandleA, new Vector4(cam.X, cam.Y, cam.Z, 1)); - //constantTableA.SetValue(device, jNowHandleA, (float)(SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate))); - //constantTableA.SetValue(device, decayHandleA, timeSeries ? decay : 0f); - - //float adjustedScale = scaleFactor; - - //if (flat && astronomical && (markerScale == MarkerScales.World)) - //{ - // adjustedScale = (float)(scaleFactor / (Earth3d.MainWindow.ZoomFactor / 360)); - //} - //constantTableA.SetValue(device, scaleHandleA, (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale); - //constantTableA.SetValue(device, skyHandleA, astronomical ? -1 : 1); - //constantTableA.SetValue(device, opacityHandleA, opacity * this.Opacity); - //constantTableA.SetValue(device, showFarSideHandleA, ShowFarSide ? 1f : 0f); - - //// Matrix matrixWVP = Earth3d.WorldMatrix * Earth3d.ViewMatrix * Earth3d.ProjMatrix; - ////Matrix matrixWVP = device.Transform.World * device.Transform.View * device.Transform.Projection; - //Matrix3d matrixWVP = renderContext.World * renderContext.View * renderContext.Projection; - - //constantTableA.SetValue(device, worldViewHandleA, matrixWVP.Matrix); - - //device.SetStreamSource(0, shapeFileVertex, 0); - ////device.VertexFormat = VertexFormats.None; - ////device.VertexDeclaration = vertexDeclA; - //device.VertexFormat = PointVertex.Format; - - //device.RenderState.PointSpriteEnable = plotType != PlotTypes.Point; - - //device.RenderState.PointScaleEnable = (markerScale == MarkerScales.World && plotType != PlotTypes.Point) ? true : false; - //device.RenderState.PointSize = 0; - //device.RenderState.PointScaleA = 0; - //device.RenderState.PointScaleB = 0; - - //device.RenderState.PointScaleC = 10000000f; - - //switch (plotType) - //{ - // case PlotTypes.Gaussian: - // device.SetTexture(0, Grids.StarProfile); - // break; - // case PlotTypes.Circle: - // device.SetTexture(0, CircleTexture); - // break; - // case PlotTypes.Point: - // device.SetTexture(0, null); - // break; - // //case PlotTypes.Square: - // // device.SetTexture(0, null); - // // break; - // //case PlotTypes.Custom: - // // break; - // case PlotTypes.PushPin: - // device.SetTexture(0, PushPin.GetPushPinTexture(markerIndex)); - // break; - - // default: - // break; - //} - - - - //device.RenderState.CullMode = Cull.None; - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //if (plotType == PlotTypes.Gaussian) - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.One; - //} - //else - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //} - - - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - //device.TextureState[0].ColorOperation = TextureOperation.Modulate; - //device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; - //device.TextureState[0].AlphaOperation = TextureOperation.Modulate; - //device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; - - //device.TextureState[1].ColorOperation = TextureOperation.Disable; - //device.TextureState[1].ColorArgument1 = TextureArgument.Current; - //device.TextureState[1].ColorArgument2 = TextureArgument.Constant; - //device.TextureState[1].AlphaOperation = TextureOperation.Disable; - //device.TextureState[1].AlphaArgument1 = TextureArgument.Current; - //device.TextureState[1].AlphaArgument2 = TextureArgument.Constant; - - //device.TextureState[1].ConstantColor = Color.FromArgb(255, 255, 255, 255); - //// device.TextureState[1].ConstantColor = Color.FromArgb(0, 0, 0, 0); - - - - //device.DrawPrimitives(PrimitiveType.PointList, 0, shapeVertexCount); - //device.RenderState.PointSpriteEnable = false; - - - ////device.DrawUserPrimitives(PrimitiveType.LineList, segments, points); - - //device.RenderState.FillMode = oldMode; - //device.TextureState[0].ColorOperation = oldTexOp; - //device.VertexShader = null; - - //device.RenderState.ZBufferEnable = zBufferEnabled; - //device.RenderState.AlphaBlendEnable = false; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlue; - return true; - } - - - //protected static EffectHandle worldViewHandleA = null; - //protected static EffectHandle cameraHandleA = null; - //protected static EffectHandle jNowHandleA = null; - //protected static EffectHandle decayHandleA = null; - //protected static EffectHandle scaleHandleA = null; - //protected static EffectHandle skyHandleA = null; - //protected static EffectHandle opacityHandleA = null; - //protected static EffectHandle showFarSideHandleA = null; - //protected static ConstantTable constantTableA = null; - //protected static VertexShader shaderA = null; - //protected static VertexDeclaration vertexDeclA = null; - - //protected static void MakeVertexShaderA(Device device) - //{ - // // Create the vertex shader and declaration - // VertexElement[] elements = new VertexElement[] - // { - // new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), - // new VertexElement(0, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.PointSize, 0), - // new VertexElement(0, 0, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), - // new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), - // VertexElement.VertexDeclarationEnd - // }; - - // vertexDeclA = new VertexDeclaration(device, elements); - - // ShaderFlags shaderFlags = 0; - - // string errors; - - // string shaderText = - - // " float4x4 matWVP; " + - // " float4 camPos : POSITION; " + - // " float1 jNow; " + - // " float1 decay; " + - // " float1 scale; " + - // " float1 opacity; " + - // " float1 sky; " + - // " float1 showFarSide; " + - // " struct VS_IN " + - // " { " + - // " float4 ObjPos : POSITION; " + // Object space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + // Vertex color - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " struct VS_OUT " + - // " { " + - // " float4 ProjPos : POSITION; " + // Projected space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " VS_OUT main( VS_IN In ) " + - // " { " + - // " float dotCam = dot((camPos.xyz - In.ObjPos.xyz), In.ObjPos.xyz); " + - // " float dist = distance(In.ObjPos, camPos.xyz); " + - // " VS_OUT Out; " + - // " float dAlpha = 1; " + - // " if ( decay > 0) " + - // " { " + - // " dAlpha = 1 - ((jNow - In.Time.y) / decay); " + - // " if (dAlpha > 1 ) " + - // " { " + - // " dAlpha = 1; " + - // " } " + - // " " + - // " } " + - // " Out.ProjPos = mul(In.ObjPos, matWVP ); " + // Transform vertex into - // " if (showFarSide == 0 && (dotCam * sky) < 0 || (jNow < In.Time.x && decay > 0)) " + - // " { " + - // " Out.Color.a = 0; " + - // " } " + - // " else " + - // " { " + - // " Out.Color.a = In.Color.a * dAlpha * opacity; " + - // " } " + - // " Out.Color.r = In.Color.r; " + - // " Out.Color.g = In.Color.g; " + - // " Out.Color.b = In.Color.b; " + - // " Out.Time.x = 0; " + - // " Out.Time.y = 0; " + - // " if ( scale > 0) " + - // " { " + - // " Out.PointSize = scale * (In.PointSize )/ dist;" + - // " } " + - // " else " + - // " { " + - // " Out.PointSize = -scale *In.PointSize;" + - // " } " + - // " if (Out.PointSize > 256) " + - // " { " + - // " Out.PointSize = 256; " + - // " } " + - // " return Out; " + // Transfer color - // " } "; - - // using (GraphicsStream code = ShaderLoader.CompileShader(shaderText, "main", null, null, - // "vs_2_0", shaderFlags, out errors, out constantTableA)) - // { - - // // We will store these constants in an effect handle here for performance reasons. - // // You could simply use the string value (i.e., "worldViewProj") in the SetValue call - // // and it would work just as well, but that actually requires an allocation to be made - // // and can actually slow your performance down. It's much more efficient to simply - // // cache these handles for use later - // worldViewHandleA = constantTableA.GetConstant(null, "matWVP"); - // cameraHandleA = constantTableA.GetConstant(null, "camPos"); - // jNowHandleA = constantTableA.GetConstant(null, "jNow"); - // decayHandleA = constantTableA.GetConstant(null, "decay"); - // scaleHandleA = constantTableA.GetConstant(null, "scale"); - // skyHandleA = constantTableA.GetConstant(null, "sky"); - // opacityHandleA = constantTableA.GetConstant(null, "opacity"); - // showFarSideHandleA = constantTableA.GetConstant(null, "showFarSide"); - - // // Create the shader - // shaderA = new VertexShader(device, code); - // } - //} - - public override void InitFromXml(XmlNode node) - { - base.InitFromXml(node); - } - - public override void CleanUp() - { - - - if (lineList != null) - { - lineList.Clear(); - } - if (lineList2d != null) - { - lineList2d.Clear(); - } - - if (triangleList2d != null) - { - triangleList2d.Clear(); - } - - if (pointList != null) - { - pointList.Clear(); - } - - if (triangleList != null) - { - triangleList.Clear(); - } - } - - public virtual bool DynamicUpdate() - { - return false; - } - } - -} diff --git a/engine/csharp_ref/Layers/VOTable.cs b/engine/csharp_ref/Layers/VOTable.cs deleted file mode 100644 index dc89753c..00000000 --- a/engine/csharp_ref/Layers/VOTable.cs +++ /dev/null @@ -1,485 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Net; -using System.Html.Data.Files; - -namespace wwtlib -{ - public enum Primitives - { - VoBoolean = 1, - VoBit = 2, - VoUnsignedByte = 3, - VoShort = 4, - VoInt = 5, - VoLong = 6, - VoChar = 7, - VoUnicodeChar = 8, - VoFloat = 9, - VoDouble = 10, - VoFloatComplex = 11, - VoDoubleComplex = 12, - VoUndefined = 13 - }; - - public class VoTable - { - public Dictionary Columns = new Dictionary(); - public List Column = new List(); - public List Rows = new List(); - public string LoadFilename = ""; - public string Url; - public string SampId = ""; - public VoRow SelectedRow = null; - - public VoTable() - { - - } - //public VoTable(XmlDocument xml) - //{ - // LoadFromXML(xml); - //} - - //public VoTable(string filename) - //{ - // LoadFilename = filename; - // XmlDocument doc = new XmlDocument(); - // doc.Load(filename); - // LoadFromXML(doc); - //} - - WebFile webFile; - Action onComplete; - public static VoTable LoadFromUrl(string url, Action complete) - { - VoTable temp = new VoTable(); - - temp.onComplete = complete; - - temp.webFile = new WebFile(URLHelpers.singleton.rewrite(url, URLRewriteMode.OriginRelative)); - temp.webFile.OnStateChange = temp.LoadData; - temp.webFile.Send(); - - return temp; - - } - - private void LoadData() - { - if (webFile.State == StateType.Error) - { - Script.Literal("alert({0})", webFile.Message); - } - else if (webFile.State == StateType.Received) - { - LoadFromXML(webFile.GetXml()); - - if (onComplete != null) - { - onComplete(); - } - } - } - - public static VoTable LoadFromString(string data) - { - XmlDocumentParser xParser = new XmlDocumentParser(); - XmlDocument doc = xParser.ParseFromString(data, "text/xml"); - - VoTable table = new VoTable(); - - table.LoadFromXML(doc); - - return table; - } - - - public bool error = false; - public string errorText = ""; - public void LoadFromXML(XmlDocument xml) - { - XmlNode voTable = Util.SelectSingleNode(xml, "VOTABLE"); - - if (voTable == null) - { - return; - } - int index = 0; - try - { - XmlNode table = Util.SelectSingleNode(Util.SelectSingleNode(voTable, "RESOURCE"),"TABLE"); - if (table != null) - { - foreach (XmlNode node in table.ChildNodes) - { - if (node.Name == "FIELD") - { - VoColumn col = new VoColumn(node, index++); - Columns[col.Name] = col; - Column.Add(col); - } - } - } - } - catch - { - error = true; - errorText = Util.SelectSingleNode(voTable,"DESCRIPTION").InnerText.ToString(); - } - try - { - XmlNode tableData = Util.SelectSingleNode(Util.SelectSingleNode(Util.SelectSingleNode(Util.SelectSingleNode(voTable,"RESOURCE"),"TABLE"),"DATA"),"TABLEDATA"); - if (tableData != null) - { - foreach (XmlNode node in tableData.ChildNodes) - { - if (node.Name == "TR") - { - VoRow row = new VoRow(this); - row.ColumnData = new object[Columns.Count]; - index = 0; - foreach (XmlNode child in node.ChildNodes) - { - if (child.Name == "TD") - { - row.ColumnData[index++] = Util.GetInnerText(child).Trim(); - } - } - Rows.Add(row); - } - } - } - } - catch - { - } - } - - public bool Save(string filename) - { - //todo add save - //if (String.IsNullOrEmpty(filename) || String.IsNullOrEmpty(LoadFilename)) - //{ - // return false; - //} - //try - //{ - // File.Copy(LoadFilename, filename); - //} - //catch - //{ - // return false; - //} - return true; - - } - public VoColumn GetColumnByUcd(string ucd) - { - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Ucd.Replace("_", ".").ToLocaleLowerCase().IndexOf(ucd.ToLocaleLowerCase()) > -1) - { - return col; - } - } - return null; - } - - public VoColumn GetRAColumn() - { - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Ucd.ToLocaleLowerCase().IndexOf("pos.eq.ra") > -1 || col.Ucd.ToLocaleLowerCase().IndexOf("pos_eq_ra") > -1) - { - return col; - } - } - - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Name.ToLocaleLowerCase().IndexOf("ra") > -1) - { - return col; - } - } - - return null; - } - - public VoColumn GetDecColumn() - { - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Ucd.ToLowerCase().IndexOf("pos.eq.dec") > -1 || col.Ucd.ToLowerCase().IndexOf("pos_eq_dec") > -1) - { - return col; - } - } - - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Name.ToLowerCase().IndexOf("dec") > -1) - { - return col; - } - } - return null; - } - - public VoColumn GetMagColumn() - { - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Ucd.ToLowerCase().IndexOf("phot.mag") > -1 || col.Ucd.ToLowerCase().IndexOf("phot_mag") > -1) - { - return col; - } - } - return null; - } - - public VoColumn GetDistanceColumn() - { - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (col.Ucd.ToLowerCase().IndexOf("pos.distance") > -1 || col.Ucd.ToLowerCase().IndexOf("pos_distance") > -1) - { - return col; - } - } - return null; - } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - bool first = true; - // Copy header - foreach (string key in Columns.Keys) - { - VoColumn col = Columns[key]; - if (first) - { - first = false; - } - else - { - sb.Append("\t"); - } - - sb.Append(col.Name); - } - sb.AppendLine(""); - - // copy rows - - foreach (VoRow row in Rows) - { - first = true; - foreach (object col in row.ColumnData) - { - if (first) - { - first = false; - } - else - { - sb.Append("\t"); - } - - sb.Append(col.ToString()); - } - sb.AppendLine(""); - } - return sb.ToString(); - } - } - - public class VoRow - { - public bool Selected = false; - public VoTable Owner; - public object[] ColumnData; - public VoRow(VoTable owner) - { - Owner = owner; - } - public object this[int index] - { - get - { - if (index < 0 || index >= ColumnData.Length) - { - return null; - } - return ColumnData[index]; - } - } - //public object this[string key] - //{ - // get - // { - // if (Owner.Columns[key] != null) - // { - // return ColumnData[Owner.Columns[key].Index]; - // } - // return null; - // } - //} - - public object GetColumnData(string key) - { - if (Owner.Columns[key] != null) - { - return ColumnData[Owner.Columns[key].Index]; - } - return null; - } - } - - public class VoColumn - { - public VoColumn(XmlNode node, int index) - { - Index = index; - if (node.Attributes.GetNamedItem("datatype") != null) - { - Type = GetType(node.Attributes.GetNamedItem("datatype").Value); - } - if (node.Attributes.GetNamedItem("ucd") != null) - { - Ucd = node.Attributes.GetNamedItem("ucd").Value; - } - if (node.Attributes.GetNamedItem("precision") != null) - { - try - { - Precision = Int32.Parse(node.Attributes.GetNamedItem("precision").Value); - } - catch - { - } - } - if (node.Attributes.GetNamedItem("ID") != null) - { - Id = node.Attributes.GetNamedItem("ID").Value; - } - - if (node.Attributes.GetNamedItem("name") != null) - { - Name = node.Attributes.GetNamedItem("name").Value; - } - else - { - Name = Id; - } - - if (node.Attributes.GetNamedItem("unit") != null) - { - Unit = node.Attributes.GetNamedItem("unit").Value; - } - - - if (node.Attributes.GetNamedItem("arraysize") != null) - { - string[] split = node.Attributes.GetNamedItem("arraysize").Value.Split( 'x' ); - Dimentions = split.Length; - Sizes = new int[split.Length]; - int indexer = 0; - foreach (string dim in split) - { - if (!(dim.IndexOf("*") > -1)) - { - Sizes[indexer++] = Int32.Parse(dim); - } - else - { - int len = 9999; - string lenString = dim.Replace("*",""); - if (lenString.Length > 0) - { - len = Int32.Parse(lenString); - } - Sizes[indexer++] = len; - - } - } - } - - } - public string Id = ""; - public Primitives Type; - public int Precision = 0; - public int Dimentions = 0; - public int[] Sizes = null; - public string Ucd = ""; - public string Unit = ""; - public string Name = ""; - public int Index; - - public static Primitives GetType(string type) - { - Primitives Type = Primitives.VoUndefined; - switch (type) - { - case "boolean": - Type = Primitives.VoBoolean; - break; - case "bit": - Type = Primitives.VoBit; - break; - case "unsignedByte": - Type = Primitives.VoUnsignedByte; - break; - case "short": - Type = Primitives.VoShort; - break; - case "int": - Type = Primitives.VoInt; - break; - case "long": - Type = Primitives.VoLong; - break; - case "char": - Type = Primitives.VoChar; - break; - case "unicodeChar": - Type = Primitives.VoUnicodeChar; - break; - case "float": - Type = Primitives.VoFloat; - break; - case "double": - Type = Primitives.VoDouble; - break; - case "floatComplex": - Type = Primitives.VoFloatComplex; - break; - case "doubleComplex": - Type = Primitives.VoDoubleComplex; - break; - default: - Type = Primitives.VoUndefined; - break; - - } - return Type; - } - public override string ToString() - { - return Name; - } - } -} diff --git a/engine/csharp_ref/Layers/VoTableLayer.cs b/engine/csharp_ref/Layers/VoTableLayer.cs deleted file mode 100644 index aef3ce05..00000000 --- a/engine/csharp_ref/Layers/VoTableLayer.cs +++ /dev/null @@ -1,1707 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; -using System.Html.Data.Files; - -namespace wwtlib -{ - - public class VoTableLayer : Layer - { - protected bool isLongIndex = false; - protected int shapeVertexCount; - - - protected bool lines = false; - protected int latColumn = -1; - protected float fixedSize = 1; - protected float decay = 0; - protected bool timeSeries = false; - - private bool dynamicData = false; - - - public bool DynamicData - { - get { return dynamicData; } - set { dynamicData = value; } - } - - private bool autoUpdate = false; - - - public bool AutoUpdate - { - get { return autoUpdate; } - set { autoUpdate = value; } - } - - string dataSourceUrl = ""; - - public string DataSourceUrl - { - get { return dataSourceUrl; } - set { dataSourceUrl = value; } - } - - public bool TimeSeries - { - get { return timeSeries; } - set - { - if (timeSeries != value) - { - version++; - timeSeries = value; - } - } - } - - Date beginRange = new Date("1/1/2100"); - - - public Date BeginRange - { - get { return beginRange; } - set - { - if (beginRange != value) - { - version++; - beginRange = value; - } - } - } - Date endRange = new Date("01/01/1800"); - - public Date EndRange - { - get { return endRange; } - set - { - if (endRange != value) - { - version++; - endRange = value; - } - } - } - - - public override void InitializeFromXml(XmlNode node) - { - TimeSeries = bool.Parse(node.Attributes.GetNamedItem("TimeSeries").Value); - BeginRange = new Date(node.Attributes.GetNamedItem("BeginRange").Value); - EndRange = new Date(node.Attributes.GetNamedItem("EndRange").Value); - Decay = Single.Parse(node.Attributes.GetNamedItem("Decay").Value); - - CoordinatesType = (CoordinatesTypes)Enums.Parse("CoordinatesTypes", node.Attributes.GetNamedItem("CoordinatesType").Value); - - - if ((int)CoordinatesType < 0) - { - CoordinatesType = CoordinatesTypes.Spherical; - } - LatColumn = int.Parse(node.Attributes.GetNamedItem("LatColumn").Value); - LngColumn = int.Parse(node.Attributes.GetNamedItem("LngColumn").Value); - if (node.Attributes.GetNamedItem("GeometryColumn") != null) - { - GeometryColumn = int.Parse(node.Attributes.GetNamedItem("GeometryColumn").Value); - } - - switch (node.Attributes.GetNamedItem("AltType").Value) - { - case "Depth": - AltType = AltTypes.Depth; - break; - case "Altitude": - AltType = AltTypes.Altitude; - break; - case "Distance": - AltType = AltTypes.Distance; - break; - case "SeaLevel": - AltType = AltTypes.SeaLevel; - break; - case "Terrain": - AltType = AltTypes.Terrain; - break; - default: - break; - } - - - - MarkerMix = MarkerMixes.Same_For_All; - - switch (node.Attributes.GetNamedItem("ColorMap").Value) - { - case "Same_For_All": - ColorMap = ColorMaps.Same_For_All; - break; - case "Group_by_Values": - ColorMap = ColorMaps.Group_by_Values; - break; - case "Per_Column_Literal": - ColorMap = ColorMaps.Per_Column_Literal; - break; - default: - break; - } - - - MarkerColumn = int.Parse(node.Attributes.GetNamedItem("MarkerColumn").Value); - ColorMapColumn = int.Parse(node.Attributes.GetNamedItem("ColorMapColumn").Value); - - switch (node.Attributes.GetNamedItem("PlotType").Value) - { - case "Gaussian": - PlotType = PlotTypes.Gaussian; - break; - case "Point": - PlotType = PlotTypes.Point; - break; - case "Circle": - PlotType = PlotTypes.Circle; - break; - case "PushPin": - PlotType = PlotTypes.PushPin; - break; - default: - break; - } - - MarkerIndex = int.Parse(node.Attributes.GetNamedItem("MarkerIndex").Value); - - switch (node.Attributes.GetNamedItem("MarkerScale").Value) - { - case "Screen": - MarkerScale = MarkerScales.Screen; - break; - case "World": - MarkerScale = MarkerScales.World; - break; - default: - break; - } - - switch (node.Attributes.GetNamedItem("AltUnit").Value) - { - case "Meters": - AltUnit = AltUnits.Meters; - break; - case "Feet": - AltUnit = AltUnits.Feet; - break; - case "Inches": - AltUnit = AltUnits.Inches; - break; - case "Miles": - AltUnit = AltUnits.Miles; - break; - case "Kilometers": - AltUnit = AltUnits.Kilometers; - break; - case "AstronomicalUnits": - AltUnit = AltUnits.AstronomicalUnits; - break; - case "LightYears": - AltUnit = AltUnits.LightYears; - break; - case "Parsecs": - AltUnit = AltUnits.Parsecs; - break; - case "MegaParsecs": - AltUnit = AltUnits.MegaParsecs; - break; - case "Custom": - AltUnit = AltUnits.Custom; - break; - default: - break; - } - - AltColumn = int.Parse(node.Attributes.GetNamedItem("AltColumn").Value); - StartDateColumn = int.Parse(node.Attributes.GetNamedItem("StartDateColumn").Value); - EndDateColumn = int.Parse(node.Attributes.GetNamedItem("EndDateColumn").Value); - SizeColumn = int.Parse(node.Attributes.GetNamedItem("SizeColumn").Value); - HyperlinkFormat = node.Attributes.GetNamedItem("HyperlinkFormat").Value; - HyperlinkColumn = int.Parse(node.Attributes.GetNamedItem("HyperlinkColumn").Value); - ScaleFactor = Single.Parse(node.Attributes.GetNamedItem("ScaleFactor").Value); - - switch (node.Attributes.GetNamedItem("PointScaleType").Value) - { - case "Linear": - PointScaleType = PointScaleTypes.Linear; - break; - case "Power": - PointScaleType = PointScaleTypes.Power; - break; - case "Log": - PointScaleType = PointScaleTypes.Log; - break; - case "Constant": - PointScaleType = PointScaleTypes.Constant; - break; - case "StellarMagnitude": - PointScaleType = PointScaleTypes.StellarMagnitude; - break; - default: - break; - } - - - if (node.Attributes.GetNamedItem("ShowFarSide") != null) - { - ShowFarSide = Boolean.Parse(node.Attributes.GetNamedItem("ShowFarSide").Value); - } - - if (node.Attributes.GetNamedItem("RaUnits") != null) - { - // RaUnits = (RAUnits)Enum.Parse(typeof(RAUnits), node.Attributes["RaUnits"].Value); - - switch (node.Attributes.GetNamedItem("RaUnits").Value) - { - case "Hours": - RaUnits = RAUnits.Hours; - break; - case "Degrees": - RaUnits = RAUnits.Degrees; - break; - } - } - - if (node.Attributes.GetNamedItem("HoverTextColumn") != null) - { - NameColumn = int.Parse(node.Attributes.GetNamedItem("HoverTextColumn").Value); - } - - - if (node.Attributes.GetNamedItem("XAxisColumn") != null) - { - XAxisColumn = int.Parse(node.Attributes.GetNamedItem("XAxisColumn").Value); - XAxisReverse = bool.Parse(node.Attributes.GetNamedItem("XAxisReverse").Value); - YAxisColumn = int.Parse(node.Attributes.GetNamedItem("YAxisColumn").Value); - YAxisReverse = bool.Parse(node.Attributes.GetNamedItem("YAxisReverse").Value); - ZAxisColumn = int.Parse(node.Attributes.GetNamedItem("ZAxisColumn").Value); - ZAxisReverse = bool.Parse(node.Attributes.GetNamedItem("ZAxisReverse").Value); - - switch (node.Attributes.GetNamedItem("CartesianScale").Value) - { - case "Meters": - CartesianScale = AltUnits.Meters; - break; - case "Feet": - CartesianScale = AltUnits.Feet; - break; - case "Inches": - CartesianScale = AltUnits.Inches; - break; - case "Miles": - CartesianScale = AltUnits.Miles; - break; - case "Kilometers": - CartesianScale = AltUnits.Kilometers; - break; - case "AstronomicalUnits": - CartesianScale = AltUnits.AstronomicalUnits; - break; - case "LightYears": - CartesianScale = AltUnits.LightYears; - break; - case "Parsecs": - CartesianScale = AltUnits.Parsecs; - break; - case "MegaParsecs": - CartesianScale = AltUnits.MegaParsecs; - break; - case "Custom": - CartesianScale = AltUnits.Custom; - break; - default: - break; - } - - - CartesianCustomScale = double.Parse(node.Attributes.GetNamedItem("CartesianCustomScale").Value); - - - } - - if (node.Attributes.GetNamedItem("DynamicData") != null) - { - DynamicData = bool.Parse(node.Attributes.GetNamedItem("DynamicData").Value); - AutoUpdate = bool.Parse(node.Attributes.GetNamedItem("AutoUpdate").Value); - DataSourceUrl = node.Attributes.GetNamedItem("DataSourceUrl").Value; - } - - - } - - - public Dictionary MarkerDomainValues = new Dictionary(); - public Dictionary ColorDomainValues = new Dictionary(); - - - - public float Decay - { - get { return decay; } - set - { - if (decay != value) - { - version++; - decay = value; - } - } - } - - - private CoordinatesTypes coordinatesType = CoordinatesTypes.Spherical; - - - public CoordinatesTypes CoordinatesType - { - get { return coordinatesType; } - set - { - if (coordinatesType != value) - { - version++; - coordinatesType = value; - } - } - } - - - public int LatColumn - { - get { return latColumn; } - set - { - if (latColumn != value) - { - version++; - latColumn = value; - } - } - } - protected int lngColumn = -1; - - - public int LngColumn - { - get { return lngColumn; } - set - { - if (lngColumn != value) - { - version++; - lngColumn = value; - } - } - } - - protected int geometryColumn = -1; - - - public int GeometryColumn - { - get { return geometryColumn; } - set - { - if (geometryColumn != value) - { - version++; - geometryColumn = value; - } - } - } - - private int xAxisColumn = -1; - - - public int XAxisColumn - { - get { return xAxisColumn; } - set - { - if (xAxisColumn != value) - { - version++; - xAxisColumn = value; - } - } - } - private int yAxisColumn = -1; - - - public int YAxisColumn - { - get { return yAxisColumn; } - set - { - if (yAxisColumn != value) - { - version++; - yAxisColumn = value; - } - } - } - private int zAxisColumn = -1; - - - public int ZAxisColumn - { - get { return zAxisColumn; } - set - { - if (zAxisColumn != value) - { - version++; - zAxisColumn = value; - } - } - } - - private bool xAxisReverse = false; - - - public bool XAxisReverse - { - get { return xAxisReverse; } - set - { - if (xAxisReverse != value) - { - version++; - xAxisReverse = value; - } - } - } - private bool yAxisReverse = false; - - - public bool YAxisReverse - { - get { return yAxisReverse; } - set - { - if (yAxisReverse != value) - { - version++; - yAxisReverse = value; - } - } - } - private bool zAxisReverse = false; - - - public bool ZAxisReverse - { - get { return zAxisReverse; } - set - { - if (zAxisReverse != value) - { - version++; - zAxisReverse = value; - } - } - } - - private AltTypes altType = AltTypes.SeaLevel; - - - public AltTypes AltType - { - get { return altType; } - set - { - if (altType != value) - { - version++; - altType = value; - } - } - } - - - private MarkerMixes markerMix = MarkerMixes.Same_For_All; - - - public MarkerMixes MarkerMix - { - get { return markerMix; } - set - { - if (markerMix != value) - { - version++; - markerMix = value; - } - } - } - - RAUnits raUnits = RAUnits.Hours; - - public RAUnits RaUnits - { - get { return raUnits; } - set - { - - if (raUnits != value) - { - version++; - raUnits = value; - } - } - } - - private ColorMaps colorMap = ColorMaps.Per_Column_Literal; - - - internal ColorMaps ColorMap - { - get { return colorMap; } - set - { - if (colorMap != value) - { - version++; - colorMap = value; - } - } - } - - - private int markerColumn = -1; - - - public int MarkerColumn - { - get { return markerColumn; } - set - { - if (markerColumn != value) - { - version++; - markerColumn = value; - } - } - } - - private int colorMapColumn = -1; - - - public int ColorMapColumn - { - get { return colorMapColumn; } - set - { - if (colorMapColumn != value) - { - version++; - colorMapColumn = value; - } - } - } - - private PlotTypes plotType = PlotTypes.Gaussian; - - - public PlotTypes PlotType - { - get { return plotType; } - set - { - if (plotType != value) - { - version++; - plotType = value; - } - - } - } - - private int markerIndex = 0; - - - public int MarkerIndex - { - get { return markerIndex; } - set - { - if (markerIndex != value) - { - version++; - markerIndex = value; - } - } - } - - private bool showFarSide = false; - - - public bool ShowFarSide - { - get { return showFarSide; } - set - { - if (showFarSide != value) - { - version++; - showFarSide = value; - } - } - } - - - private MarkerScales markerScale = MarkerScales.World; - - - public MarkerScales MarkerScale - { - get { return markerScale; } - set - { - if (markerScale != value) - { - version++; - markerScale = value; - } - } - } - - - private AltUnits altUnit = AltUnits.Meters; - - - public AltUnits AltUnit - { - get { return altUnit; } - set - { - if (altUnit != value) - { - version++; - altUnit = value; - } - } - } - private AltUnits cartesianScale = AltUnits.Meters; - - - public AltUnits CartesianScale - { - get { return cartesianScale; } - set - { - if (cartesianScale != value) - { - version++; - cartesianScale = value; - } - } - } - - private double cartesianCustomScale = 1; - - - public double CartesianCustomScale - { - get { return cartesianCustomScale; } - set - { - if (cartesianCustomScale != value) - { - version++; - cartesianCustomScale = value; - } - } - } - - protected int altColumn = -1; - - public int AltColumn - { - get { return altColumn; } - set - { - if (altColumn != value) - { - version++; - altColumn = value; - } - } - } - - protected int startDateColumn = -1; - - - public int StartDateColumn - { - get { return startDateColumn; } - set - { - if (startDateColumn != value) - { - version++; - startDateColumn = value; - } - } - } - protected int endDateColumn = -1; - - - public int EndDateColumn - { - get { return endDateColumn; } - set - { - if (endDateColumn != value) - { - version++; - endDateColumn = value; - } - } - } - - protected int sizeColumn = -1; - - - public int SizeColumn - { - get { return sizeColumn; } - set - { - if (sizeColumn != value) - { - version++; - sizeColumn = value; - } - } - } - protected int nameColumn = 0; - - - public int NameColumn - { - get { return nameColumn; } - set - { - if (nameColumn != value) - { - version++; - nameColumn = value; - } - } - } - private string hyperlinkFormat = ""; - - - public string HyperlinkFormat - { - get { return hyperlinkFormat; } - set - { - if (hyperlinkFormat != value) - { - version++; hyperlinkFormat = value; - } - } - } - - private int hyperlinkColumn = -1; - - - public int HyperlinkColumn - { - get { return hyperlinkColumn; } - set - { - if (hyperlinkColumn != value) - { - version++; - hyperlinkColumn = value; - } - } - } - - - protected float scaleFactor = 1.0f; - - - public float ScaleFactor - { - get { return scaleFactor; } - set - { - if (scaleFactor != value) - { - version++; - - scaleFactor = value; - } - } - } - - protected PointScaleTypes pointScaleType = PointScaleTypes.Power; - - - public PointScaleTypes PointScaleType - { - get { return pointScaleType; } - set - { - if (pointScaleType != value) - { - version++; - pointScaleType = value; - } - } - } - - - - protected List positions = new List(); - - protected LineList lineList; - protected LineList lineList2d; - protected TriangleList triangleList; - protected TriangleList triangleList2d; - - protected PointList pointList; - - protected bool bufferIsFlat = false; - - protected Date baseDate = new Date(2010, 0, 1, 12, 00, 00); - - static Texture circleTexture = null; - - static Texture CircleTexture - { - get - { - if (circleTexture == null) - { - string url = URLHelpers.singleton.engineAssetUrl("circle.png"); - circleTexture = Planets.LoadPlanetTexture(url); - } - - return circleTexture; - } - } - public bool dirty = true; - - - public override bool Draw(RenderContext renderContext, float opacity, bool flat) - { - - RenderContext device = renderContext; - - //if (shaderA == null) - //{ - // MakeVertexShaderA(device); - //} - - if (bufferIsFlat != flat) - { - CleanUp(); - bufferIsFlat = flat; - } - - if (dirty) - { - PrepVertexBuffer(renderContext, opacity); - dirty = false; - } - - double jNow = SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate); - - - float adjustedScale = scaleFactor; - - if (flat && astronomical && (markerScale == MarkerScales.World)) - { - adjustedScale = (float)(scaleFactor / (renderContext.ViewCamera.Zoom / 360)); - } - - - if (triangleList2d != null) - { - triangleList2d.Decay = decay; - triangleList2d.Sky = this.Astronomical; - triangleList2d.TimeSeries = timeSeries; - triangleList2d.JNow = jNow; - triangleList2d.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - if (triangleList != null) - { - - triangleList.Decay = decay; - triangleList.Sky = this.Astronomical; - triangleList.TimeSeries = timeSeries; - triangleList.JNow = jNow; - triangleList.Draw(renderContext, opacity * Opacity, CullMode.Clockwise); - } - - - if (pointList != null) - { - pointList.DepthBuffered = false; - pointList.ShowFarSide = ShowFarSide; - pointList.Decay = timeSeries ? decay : 0; - pointList.Sky = this.Astronomical; - pointList.TimeSeries = timeSeries; - pointList.JNow = jNow; - pointList.scale = (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale; - switch (plotType) - { - case PlotTypes.Gaussian: - pointList.Draw(renderContext, opacity * Opacity, false); - break; - case PlotTypes.Circle: - pointList.DrawTextured(renderContext, CircleTexture.Texture2d, opacity * Opacity); - break; - case PlotTypes.Point: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(19), opacity * Opacity); - break; - case PlotTypes.Square: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(35), opacity * Opacity); - break; - case PlotTypes.Custom: - case PlotTypes.PushPin: - pointList.DrawTextured(renderContext, PushPin.GetPushPinTexture(markerIndex), opacity * Opacity); - break; - - default: - break; - } - } - - if (lineList != null) - { - lineList.Sky = this.Astronomical; - lineList.Decay = decay; - lineList.TimeSeries = timeSeries; - lineList.JNow = jNow; - lineList.DrawLines(renderContext, opacity * Opacity); - } - - if (lineList2d != null) - { - lineList2d.Sky = this.Astronomical; - lineList2d.Decay = decay; - lineList2d.TimeSeries = timeSeries; - lineList2d.ShowFarSide = ShowFarSide; - lineList2d.JNow = jNow; - lineList2d.DrawLines(renderContext, opacity * Opacity); - } - - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - - //TextureOperation oldTexOp = device.TextureState[0].ColorOperation; - - //bool zBufferEnabled = device.RenderState.ZBufferEnable; - - //if (astronomical && !bufferIsFlat) - //{ - // device.RenderState.ZBufferEnable = true; - //} - //else - //{ - // device.RenderState.ZBufferEnable = false; - //} - //device.TextureState[0].ColorOperation = TextureOperation.Disable; - - //FillMode oldMode = device.RenderState.FillMode; - //DateTime baseDate = new DateTime(2010, 1, 1, 12, 00, 00); - //device.RenderState.FillMode = FillMode.Solid; - //device.SetTexture(0, null); - //device.Indices = shapeFileIndex; - //device.VertexShader = shaderA; - //// Vector3 cam = Vector3d.TransformCoordinate(Earth3d.cameraPosition, Matrix3d.Invert(renderContext.World)).Vector3; - //Vector3 cam = Vector3.TransformCoordinate(renderContext.CameraPosition.Vector3, Matrix.Invert(renderContext.Device.Transform.World)); - //constantTableA.SetValue(device, cameraHandleA, new Vector4(cam.X, cam.Y, cam.Z, 1)); - //constantTableA.SetValue(device, jNowHandleA, (float)(SpaceTimeController.JNow - SpaceTimeController.UtcToJulian(baseDate))); - //constantTableA.SetValue(device, decayHandleA, timeSeries ? decay : 0f); - - //float adjustedScale = scaleFactor; - - //if (flat && astronomical && (markerScale == MarkerScales.World)) - //{ - // adjustedScale = (float)(scaleFactor / (Earth3d.MainWindow.ZoomFactor / 360)); - //} - //constantTableA.SetValue(device, scaleHandleA, (markerScale == MarkerScales.World) ? (float)adjustedScale : -(float)adjustedScale); - //constantTableA.SetValue(device, skyHandleA, astronomical ? -1 : 1); - //constantTableA.SetValue(device, opacityHandleA, opacity * this.Opacity); - //constantTableA.SetValue(device, showFarSideHandleA, ShowFarSide ? 1f : 0f); - - //// Matrix matrixWVP = Earth3d.WorldMatrix * Earth3d.ViewMatrix * Earth3d.ProjMatrix; - ////Matrix matrixWVP = device.Transform.World * device.Transform.View * device.Transform.Projection; - //Matrix3d matrixWVP = renderContext.World * renderContext.View * renderContext.Projection; - - //constantTableA.SetValue(device, worldViewHandleA, matrixWVP.Matrix); - - //device.SetStreamSource(0, shapeFileVertex, 0); - ////device.VertexFormat = VertexFormats.None; - ////device.VertexDeclaration = vertexDeclA; - //device.VertexFormat = PointVertex.Format; - - //device.RenderState.PointSpriteEnable = plotType != PlotTypes.Point; - - //device.RenderState.PointScaleEnable = (markerScale == MarkerScales.World && plotType != PlotTypes.Point) ? true : false; - //device.RenderState.PointSize = 0; - //device.RenderState.PointScaleA = 0; - //device.RenderState.PointScaleB = 0; - - //device.RenderState.PointScaleC = 10000000f; - - //switch (plotType) - //{ - // case PlotTypes.Gaussian: - // device.SetTexture(0, Grids.StarProfile); - // break; - // case PlotTypes.Circle: - // device.SetTexture(0, CircleTexture); - // break; - // case PlotTypes.Point: - // device.SetTexture(0, null); - // break; - // //case PlotTypes.Square: - // // device.SetTexture(0, null); - // // break; - // //case PlotTypes.Custom: - // // break; - // case PlotTypes.PushPin: - // device.SetTexture(0, PushPin.GetPushPinTexture(markerIndex)); - // break; - - // default: - // break; - //} - - - - //device.RenderState.CullMode = Cull.None; - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //if (plotType == PlotTypes.Gaussian) - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.One; - //} - //else - //{ - // device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - //} - - - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - //device.TextureState[0].ColorOperation = TextureOperation.Modulate; - //device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; - //device.TextureState[0].AlphaOperation = TextureOperation.Modulate; - //device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; - - //device.TextureState[1].ColorOperation = TextureOperation.Disable; - //device.TextureState[1].ColorArgument1 = TextureArgument.Current; - //device.TextureState[1].ColorArgument2 = TextureArgument.Constant; - //device.TextureState[1].AlphaOperation = TextureOperation.Disable; - //device.TextureState[1].AlphaArgument1 = TextureArgument.Current; - //device.TextureState[1].AlphaArgument2 = TextureArgument.Constant; - - //device.TextureState[1].ConstantColor = Color.FromArgb(255, 255, 255, 255); - //// device.TextureState[1].ConstantColor = Color.FromArgb(0, 0, 0, 0); - - - - //device.DrawPrimitives(PrimitiveType.PointList, 0, shapeVertexCount); - //device.RenderState.PointSpriteEnable = false; - - - ////device.DrawUserPrimitives(PrimitiveType.LineList, segments, points); - - //device.RenderState.FillMode = oldMode; - //device.TextureState[0].ColorOperation = oldTexOp; - //device.VertexShader = null; - - //device.RenderState.ZBufferEnable = zBufferEnabled; - //device.RenderState.AlphaBlendEnable = false; - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlue; - return true; - } - - - //protected static EffectHandle worldViewHandleA = null; - //protected static EffectHandle cameraHandleA = null; - //protected static EffectHandle jNowHandleA = null; - //protected static EffectHandle decayHandleA = null; - //protected static EffectHandle scaleHandleA = null; - //protected static EffectHandle skyHandleA = null; - //protected static EffectHandle opacityHandleA = null; - //protected static EffectHandle showFarSideHandleA = null; - //protected static ConstantTable constantTableA = null; - //protected static VertexShader shaderA = null; - //protected static VertexDeclaration vertexDeclA = null; - - //protected static void MakeVertexShaderA(Device device) - //{ - // // Create the vertex shader and declaration - // VertexElement[] elements = new VertexElement[] - // { - // new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), - // new VertexElement(0, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.PointSize, 0), - // new VertexElement(0, 0, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), - // new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), - // VertexElement.VertexDeclarationEnd - // }; - - // vertexDeclA = new VertexDeclaration(device, elements); - - // ShaderFlags shaderFlags = 0; - - // string errors; - - // string shaderText = - - // " float4x4 matWVP; " + - // " float4 camPos : POSITION; " + - // " float1 jNow; " + - // " float1 decay; " + - // " float1 scale; " + - // " float1 opacity; " + - // " float1 sky; " + - // " float1 showFarSide; " + - // " struct VS_IN " + - // " { " + - // " float4 ObjPos : POSITION; " + // Object space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + // Vertex color - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " struct VS_OUT " + - // " { " + - // " float4 ProjPos : POSITION; " + // Projected space position - // " float1 PointSize : PSIZE; " + // Object Point size - // " float4 Color : COLOR; " + - // " float2 Time : TEXCOORD0; " + // Object Point size - // " }; " + - // " " + - // " VS_OUT main( VS_IN In ) " + - // " { " + - // " float dotCam = dot((camPos.xyz - In.ObjPos.xyz), In.ObjPos.xyz); " + - // " float dist = distance(In.ObjPos, camPos.xyz); " + - // " VS_OUT Out; " + - // " float dAlpha = 1; " + - // " if ( decay > 0) " + - // " { " + - // " dAlpha = 1 - ((jNow - In.Time.y) / decay); " + - // " if (dAlpha > 1 ) " + - // " { " + - // " dAlpha = 1; " + - // " } " + - // " " + - // " } " + - // " Out.ProjPos = mul(In.ObjPos, matWVP ); " + // Transform vertex into - // " if (showFarSide == 0 && (dotCam * sky) < 0 || (jNow < In.Time.x && decay > 0)) " + - // " { " + - // " Out.Color.a = 0; " + - // " } " + - // " else " + - // " { " + - // " Out.Color.a = In.Color.a * dAlpha * opacity; " + - // " } " + - // " Out.Color.r = In.Color.r; " + - // " Out.Color.g = In.Color.g; " + - // " Out.Color.b = In.Color.b; " + - // " Out.Time.x = 0; " + - // " Out.Time.y = 0; " + - // " if ( scale > 0) " + - // " { " + - // " Out.PointSize = scale * (In.PointSize )/ dist;" + - // " } " + - // " else " + - // " { " + - // " Out.PointSize = -scale *In.PointSize;" + - // " } " + - // " if (Out.PointSize > 256) " + - // " { " + - // " Out.PointSize = 256; " + - // " } " + - // " return Out; " + // Transfer color - // " } "; - - // using (GraphicsStream code = ShaderLoader.CompileShader(shaderText, "main", null, null, - // "vs_2_0", shaderFlags, out errors, out constantTableA)) - // { - - // // We will store these constants in an effect handle here for performance reasons. - // // You could simply use the string value (i.e., "worldViewProj") in the SetValue call - // // and it would work just as well, but that actually requires an allocation to be made - // // and can actually slow your performance down. It's much more efficient to simply - // // cache these handles for use later - // worldViewHandleA = constantTableA.GetConstant(null, "matWVP"); - // cameraHandleA = constantTableA.GetConstant(null, "camPos"); - // jNowHandleA = constantTableA.GetConstant(null, "jNow"); - // decayHandleA = constantTableA.GetConstant(null, "decay"); - // scaleHandleA = constantTableA.GetConstant(null, "scale"); - // skyHandleA = constantTableA.GetConstant(null, "sky"); - // opacityHandleA = constantTableA.GetConstant(null, "opacity"); - // showFarSideHandleA = constantTableA.GetConstant(null, "showFarSide"); - - // // Create the shader - // shaderA = new VertexShader(device, code); - // } - //} - - public override void InitFromXml(XmlNode node) - { - base.InitFromXml(node); - } - - public override void CleanUp() - { - dirty = true; - - if (lineList != null) - { - lineList.Clear(); - } - if (lineList2d != null) - { - lineList2d.Clear(); - } - - if (triangleList2d != null) - { - triangleList2d.Clear(); - } - - if (pointList != null) - { - pointList.Clear(); - } - - if (triangleList != null) - { - triangleList.Clear(); - } - } - - public virtual bool DynamicUpdate() - { - return false; - } - - //start of VoTable Cutomizations - // public VOTableViewer Viewer = null; - public VoTableLayer() - { - this.table = null; - this.filename = ""; - - PlotType = PlotTypes.Circle; - } - public static VoTableLayer Create(VoTable table, PlotTypes plotType) - { - VoTableLayer layer = new VoTableLayer(); - - layer.table = table; - layer.filename = table.LoadFilename; - layer.LngColumn = table.GetRAColumn().Index; - layer.LatColumn = table.GetDecColumn().Index; - layer.sizeColumn = table.GetColumnByUcd("phot.mag").Index; - layer.PlotType = plotType; - - return layer; - } - public override void AddFilesToCabinet(FileCabinet fc) - { - string fName = filename; - string fileName = fc.TempDirectory + string.Format("{0}\\{1}.txt", fc.PackageID, this.ID.ToString()); - string path = fName.Substring(0, fName.LastIndexOf('\\') + 1); - string path2 = fileName.Substring(0, fileName.LastIndexOf('\\') + 1); - - //if (copy) - //{ - // if (!Directory.Exists(path2)) - // { - // Directory.CreateDirectory(path2); - // } - // if (File.Exists(fName) && !File.Exists(fileName)) - // { - // File.Copy(fName, fileName); - // } - //} - - //if (File.Exists(fileName)) - //{ - // fc.AddFile(fileName); - //} - } - string filename = ""; - - - public override void LoadData(TourDocument tourDoc, string filename) - { - System.Html.Data.Files.Blob blob = tourDoc.GetFileBlob(filename); - - FileReader doc = new FileReader(); - doc.OnLoadEnd = delegate (FileProgressEvent ee) - { - string data = doc.Result as string; - - table = VoTable.LoadFromString(data); - LngColumn = table.GetRAColumn().Index; - LatColumn = table.GetDecColumn().Index; - }; - doc.ReadAsText(blob); - } - - public override bool CanCopyToClipboard() - { - return true; - } - - public override void CopyToClipboard() - { - // System.Windows.Clipboard.SetText(table.ToString()); - } - - public override Place FindClosest(Coordinates target, float distance, Place defaultPlace, bool astronomical) - { - Vector3d searchPoint = Coordinates.GeoTo3dDouble(target.Lat, target.Lng); - - //searchPoint = -searchPoint; - Vector3d dist; - if (defaultPlace != null) - { - Vector3d testPoint = Coordinates.RADecTo3dAu(defaultPlace.RA, -defaultPlace.Dec, -1.0); - dist = Vector3d.SubtractVectors(searchPoint, testPoint); - distance = (float)dist.Length(); - } - - int closestItem = -1; - int index = 0; - foreach (Vector3d point in positions) - { - dist = Vector3d.SubtractVectors(searchPoint, point); - if (dist.Length() < distance) - { - distance = (float)dist.Length(); - closestItem = index; - } - index++; - } - - - if (closestItem == -1) - { - return defaultPlace; - } - - Coordinates pnt = Coordinates.CartesianToSpherical2(positions[closestItem]); - - string name = table.Rows[closestItem].ColumnData[this.nameColumn].ToString(); - if (nameColumn == startDateColumn || nameColumn == endDateColumn) - { - //todo fix data output - name = SpreadSheetLayer.ParseDate(name).ToString(); - // name = SpreadSheetLayer.ParseDate(name).ToString("u"); - } - - if (String.IsNullOrEmpty(name)) - { - name = string.Format("RA={0}, Dec={1}", Coordinates.FormatHMS(pnt.RA), Coordinates.FormatDMS(pnt.Dec)); - } - Place place = Place.Create(name, pnt.Lat, pnt.RA, Classification.Unidentified, "", ImageSetType.Sky, -1); - - Dictionary rowData = new Dictionary(); - for (int i = 0; i < table.Columns.Count; i++) - { - string colValue = table.Rows[closestItem][i].ToString(); - if (i == startDateColumn || i == endDateColumn) - { - //todo fix data output - // colValue = SpreadSheetLayer.ParseDate(colValue).ToString("u"); - colValue = SpreadSheetLayer.ParseDate(colValue).ToString(); - } - - if (!rowData.ContainsKey(table.Column[i].Name) && !string.IsNullOrEmpty(table.Column[i].Name)) - { - rowData[table.Column[i].Name] = colValue; - } - else - { - rowData["Column" + i.ToString()] = colValue; - } - } - place.Tag = rowData; - //todo fix event handling - //if (Viewer != null) - //{ - // Viewer.LabelClicked(closestItem); - //} - return place; - } - - protected bool PrepVertexBuffer(RenderContext renderContext, float opacity) - { - VoColumn col = table.GetColumnByUcd("meta.id"); - if (col == null) - { - col = table.Column[0]; - } - - // if (shapeFileVertex == null) - { - bool siapSet = IsSiapResultSet(); - - if (pointList == null) - { - pointList = new PointList(renderContext); - } - - if (lineList2d == null) - { - lineList2d = new LineList(); - } - lineList2d.Clear(); - - VoColumn stcsCol = table.GetColumnByUcd("phys.area;obs.field"); - - if (stcsCol == null && table.Columns.ContainsKey("regionSTCS")) - { - stcsCol = table.Columns["regionSTCS"]; - } - - if (PlotType == PlotTypes.Gaussian) - { - MarkerScale = MarkerScales.World; - } - else - { - MarkerScale = MarkerScales.Screen; - } - - List vertList = new List(); - List indexList = new List(); - TimeSeriesPointVertex lastItem = new TimeSeriesPointVertex(); - positions.Clear(); - UInt32 currentIndex = 0; - Color color = Color.FromArgb((int)(opacity * (float)Color.A), Color.R, Color.G, Color.B); - - pointScaleType = PointScaleTypes.StellarMagnitude; - foreach (VoRow row in table.Rows) - { - try - { - if (lngColumn > -1 && latColumn > -1) - { - double ra = Double.Parse(row[this.LngColumn].ToString()); - double dec = Double.Parse(row[this.LatColumn].ToString()); - Vector3d position = Coordinates.GeoTo3dDouble(dec, ra); - - lastItem.Position = position; - positions.Add(lastItem.Position); - lastItem.Color = color; - if (sizeColumn > -1) - { - - try - { - if (MarkerScale == MarkerScales.Screen) - { - lastItem.PointSize = 20f; - } - else - { - switch (pointScaleType) - { - case PointScaleTypes.Linear: - lastItem.PointSize = float.Parse(row[sizeColumn].ToString()); - break; - case PointScaleTypes.Log: - lastItem.PointSize = (float)Math.Log(float.Parse(row[sizeColumn].ToString())); - break; - case PointScaleTypes.Power: - lastItem.PointSize = (float)Math.Pow(2, float.Parse(row[sizeColumn].ToString())); - break; - case PointScaleTypes.StellarMagnitude: - { - double size = Single.Parse(row[sizeColumn].ToString()); - lastItem.PointSize = (float)(40 / Math.Pow(1.6, size)) * 10; - } - break; - case PointScaleTypes.Constant: - lastItem.PointSize = 1; - break; - default: - break; - } - } - } - catch - { - lastItem.PointSize = .01f; - } - } - else - { - if (MarkerScale == MarkerScales.Screen) - { - lastItem.PointSize = 20; - } - else - { - lastItem.PointSize = (float)Math.Pow(2, 1) * 100; - } - } - - - if (startDateColumn > -1) - { - Date dateTime = Date.Parse(row[startDateColumn].ToString()); - lastItem.Tu = (float)SpaceTimeController.UtcToJulian(dateTime); - lastItem.Tv = 0; - } - - - vertList.Add(lastItem); - pointList.AddPoint(lastItem.Position, lastItem.color, new Dates(lastItem.Tu, lastItem.Tv), lastItem.PointSize ); - currentIndex++; - } - - - if (siapSet && stcsCol!= null) - { - AddSiapStcRow(stcsCol.Name, row, row == table.SelectedRow); - } - } - - catch - { - } - lines = false; - } - - if (siapSet && stcsCol != null) - { - AddSiapStcRow(stcsCol.Name, table.SelectedRow, true); - } - - } - return true; - } - - private void AddSiapStcRow(string stcsColName, VoRow row, bool selected) - { - string stcs = row.GetColumnData(stcsColName).ToString().Replace(" ", " "); - Color col = Color.FromArgb(120, 255, 255, 255); - - if (selected) - { - col = Colors.Yellow; - } - - if (stcs.StartsWith("Polygon J2000")) - { - string[] parts = stcs.Split(' '); - - int len = parts.Length; - int index = 0; - while (index < len) - { - if (parts[index] == "Polygon") - { - index += 2; - Vector3d lastPoint = new Vector3d(); - Vector3d firstPoint = new Vector3d(); - bool start = true; - for (int i = index; i < len; i += 2) - { - if (parts[i] == "Polygon") - { - start = true; - break; - } - else - { - double Xcoord = Coordinates.ParseRA(parts[i], true) * 15 + 180; - double Ycoord = Coordinates.ParseDec(parts[i + 1]); - - - Vector3d pnt = Coordinates.GeoTo3dDouble(Ycoord, Xcoord); - - if (!start) - { - lineList2d.AddLine(lastPoint, pnt, col, new Dates(0,0)); - } - else - { - firstPoint = pnt; - start = false; - } - lastPoint = pnt; - } - index += 2; - } - if (len > 4) - { - lineList2d.AddLine(firstPoint, lastPoint, col, new Dates(0,0)); - } - - - - } - } - } - } - - public bool IsSiapResultSet() - { - return table.GetColumnByUcd("vox:image.title") != null && table.GetColumnByUcd("VOX:Image.AccessReference") != null; - - } - - public string[] Header - { - get - { - string[] header = new string[table.Columns.Count]; - int index = 0; - foreach (VoColumn col in table.Column) - { - header[index++] = col.Name; - } - - return header; - } - - } - - - private VoTable table; - - public VoTable Table - { - get { return table; } - set { table = value; } - } - - } - -} diff --git a/engine/csharp_ref/Layers/WcsImage.cs b/engine/csharp_ref/Layers/WcsImage.cs deleted file mode 100644 index cf7c1a62..00000000 --- a/engine/csharp_ref/Layers/WcsImage.cs +++ /dev/null @@ -1,247 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Net; -using System.Html.Data.Files; - -namespace wwtlib -{ - public abstract class WcsImage - { - // public static WcsImage FromFile(string fileName) - // { - - // string extension = Path.GetExtension(fileName); - - // switch (extension.ToLower()) - // { - // case ".fits": - // case ".fit": - // case ".gz": - //default: - // return new FitsImage(fileName); - - // // return new VampWCSImageReader(fileName); - - // } - // } - - - - protected string copyright=""; - - public string Copyright - { - get { return copyright; } - set { copyright = value; } - } - protected string creditsUrl=""; - - public string CreditsUrl - { - get { return creditsUrl; } - set { creditsUrl = value; } - } - - private bool validWcs = false; - - public bool ValidWcs - { - get { return validWcs; } - set { validWcs = value; } - } - protected List keywords = new List(); - - public List Keywords - { - get - { - if (keywords.Count == 0) - { - keywords.Add("Image File"); - } - return keywords; - } - set { keywords = value; } - } - protected string description=""; - - public string Description - { - get { return description; } - set { description = value; } - } - protected double scaleX; - - public double ScaleX - { - get { return scaleX; } - set { scaleX = value; } - } - protected double scaleY; - - public double ScaleY - { - get { return scaleY; } - set { scaleY = value; } - } - protected double centerX; - - public double CenterX - { - get { return centerX; } - set { centerX = value; } - } - - public double ViewCenterX - { - get { return centerX + (SizeX / 2 - ReferenceX) * ScaleX; } - } - - protected double centerY; - - public double CenterY - { - get { return centerY; } - set { centerY = value; } - } - - public double ViewCenterY - { - get { return centerY + (SizeY / 2 - ReferenceY) * ScaleY; } - } - - protected double rotation; - - public double Rotation - { - get { return rotation; } - set { rotation = value; } - } - protected double referenceX; - - public double ReferenceX - { - get { return referenceX; } - set { referenceX = value; } - } - protected double referenceY; - - public double ReferenceY - { - get { return referenceY; } - set { referenceY = value; } - } - protected double sizeX; - - public double SizeX - { - get { return sizeX; } - set { sizeX = value; } - } - protected double sizeY; - - public double SizeY - { - get { return sizeY; } - set { sizeY = value; } - } - protected double cd1_1; - - public double Cd1_1 - { - get { return cd1_1; } - set { cd1_1 = value; } - } - protected double cd1_2; - - public double Cd1_2 - { - get { return cd1_2; } - set { cd1_2 = value; } - } - protected double cd2_1; - - public double Cd2_1 - { - get { return cd2_1; } - set { cd2_1 = value; } - } - protected double cd2_2; - - public double Cd2_2 - { - get { return cd2_2; } - set { cd2_2 = value; } - } - protected bool hasRotation = false; - protected bool hasSize = false; - protected bool hasScale = false; - protected bool hasLocation = false; - protected bool hasPixel = false; - - public void AdjustScale(double width, double height) - { - //adjusts the actual height vs the reported height. - if (width != sizeX) - { - scaleX *= (sizeX / width); - referenceX /= (sizeX / width); - sizeX = width; - } - - if (height != sizeY) - { - scaleY *= (sizeY / height); - referenceY /= (sizeY / height); - sizeY = height; - } - } - - protected void CalculateScaleFromCD() - { - scaleX = Math.Sqrt(cd1_1 * cd1_1 + cd2_1 * cd2_1) * (cd1_1 * cd2_2 - cd1_2 * cd2_1) < 0 ? -1 : 1; - scaleY = Math.Sqrt(cd1_2 * cd1_2 + cd2_2 * cd2_2); - } - - protected void CalculateRotationFromCD() - { - double sign = (cd1_1 * cd2_2 - cd1_2 * cd2_1) < 0 ? -1 : 1; - double rot2 = Math.Atan2((-sign * cd1_2), cd2_2); - - rotation = rot2 / Math.PI * 180; - } - protected string filename=""; - - public string Filename - { - get { return filename; } - set { filename = value; } - } - - //private Color color = Color.White; - - //public Color Color - //{ - // get { return color; } - // set { color = value; } - //} - - - private bool colorCombine = false; - - public bool ColorCombine - { - get { return colorCombine; } - set { colorCombine = value; } - } - - - public virtual Bitmap GetBitmap() - { - return null; - } - } -} diff --git a/engine/csharp_ref/MainView.cs b/engine/csharp_ref/MainView.cs deleted file mode 100644 index 52672a3e..00000000 --- a/engine/csharp_ref/MainView.cs +++ /dev/null @@ -1,36 +0,0 @@ -// MainView.cs -// - -using System; -using System.Collections.Generic; -using System.Html; -using System.Runtime.CompilerServices; -using System.Html.Media.Graphics; -using System.Net; -using System.Serialization; - -namespace wwtlib -{ - internal static class MainView - { - static MainView() - { - Script.Literal("if (typeof document === \"undefined\") { canvas = null; return; }"); - CanvasElement canvas = (CanvasElement)Document.GetElementById("canvas"); - } - - static void DrawTest() - { - CanvasElement canvas = (CanvasElement) Document.GetElementById("canvas"); - - CanvasContext2D ctx = (CanvasContext2D) canvas.GetContext(Rendering.Render2D); - - ctx.FillStyle = "rgb(80,0,0)"; - ctx.FillRect(120, 120, 165, 160); - - ctx.FillStyle = "rgba(0, 0, 160, 0.5)"; - ctx.FillRect(140, 140, 165, 160); - - } - } -} diff --git a/engine/csharp_ref/MercatorTile.cs b/engine/csharp_ref/MercatorTile.cs deleted file mode 100644 index c3a94b44..00000000 --- a/engine/csharp_ref/MercatorTile.cs +++ /dev/null @@ -1,603 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - - -namespace wwtlib -{ - public class MercatorTile : Tile - { - - - //public override bool IsTileBigEnough(RenderContext renderContext) - //{ - - - // double arcPixels = tileDegrees / 256 * 900; - // return (renderContext.FovScale < arcPixels); - - //} - double tileDegrees; - private double latMin = 0; - private double latMax = 0; - private double lngMin = 0; - private double lngMax = 0; - - protected void ComputeBoundingSphere() - { - tileDegrees = 360 / (Math.Pow(2, this.Level)); - - latMin = AbsoluteMetersToLatAtZoom(tileY * 256, Level); - latMax = AbsoluteMetersToLatAtZoom((tileY + 1) * 256, Level); - lngMin = (((double)this.tileX * tileDegrees) - 180.0); - lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - - double latCenter = (latMin + latMax) / 2.0; - double lngCenter = (lngMin + lngMax) / 2.0; - - this.sphereCenter = (Vector3d)GeoTo3d(latCenter, lngCenter, false); - - - TopLeft = (Vector3d)GeoTo3d(latMin, lngMin, false); - BottomRight = (Vector3d)GeoTo3d(latMax, lngMax, false); - TopRight = (Vector3d)GeoTo3d(latMin, lngMax, false); - BottomLeft = (Vector3d)GeoTo3d(latMax, lngMin, false); - if (tileY == 0) - { - TopLeft = Vector3d.Create(0, 1, 0); - TopRight = Vector3d.Create(0, 1, 0); - } - - if (tileY == Math.Pow(2, Level) - 1) - { - BottomRight = Vector3d.Create(0, -1, 0); - BottomLeft = Vector3d.Create(0, -1, 0); - - } - - Vector3d distVect = TopLeft; - distVect.Subtract(sphereCenter); - this.sphereRadius = distVect.Length(); - distVect = BottomRight; - distVect.Subtract(sphereCenter); - double len = distVect.Length(); - - if (sphereRadius < len) - { - sphereRadius = len; - } - - tileDegrees = Math.Abs(latMax - latMin); - } - - public override bool IsPointInTile(double lat, double lng) - { - if (!this.DemReady || this.DemData == null || lat < Math.Min(latMin, latMax) || lat > Math.Max(latMax, latMin) || lng < Math.Min(lngMin, lngMax) || lng > Math.Max(lngMin, lngMax)) - { - return false; - } - return true; - - } - public override double GetSurfacePointAltitude(double lat, double lng, bool meters) - { - - if (Level < lastDeepestLevel) - { - //interate children - foreach (Tile child in children) - { - if (child != null) - { - if (child.IsPointInTile(lat, lng)) - { - double retVal = child.GetSurfacePointAltitude(lat, lng, meters); - if (retVal != 0) - { - return retVal; - } - else - { - break; - } - } - } - } - } - - double alt = GetAltitudeAtLatLng(lat, lng, meters ? 1 : DemScaleFactor); - - return alt; - - } - - private double GetAltitudeAtLatLng(double lat, double lng, double scaleFactor) - { - - double height = Math.Abs(latMax - latMin); - double width = Math.Abs(lngMax - lngMin); - - double yy = ((lat - Math.Min(latMax, latMin)) / height * 32); - double xx = ((lng - Math.Min(lngMax, lngMin)) / width * 32); - - - int indexY = Math.Min(31, (int)yy); - int indexX = Math.Min(31, (int)xx); - - double ha = xx - indexX; - double va = yy - indexY; - - double ul = DemData[indexY * 33 + indexX]; - double ur = DemData[indexY * 33 + (indexX + 1)]; - double ll = DemData[(indexY + 1) * 33 + indexX]; - double lr = DemData[(indexY + 1) * 33 + (indexX + 1)]; - - double top = ul * (1 - ha) + ha * ur; - double bottom = ll * (1 - ha) + ha * lr; - double val = top * (1 - va) + va * bottom; - - return val / scaleFactor; - - } - - - - int subDivisionLevel = 32; - public override bool CreateGeometry(RenderContext renderContext) - { - base.CreateGeometry(renderContext); - - if (GeometryCreated) - { - return true; - } - GeometryCreated = true; - - if (uvMultiple == 256) - { - if (dataset.DataSetType == ImageSetType.Earth || dataset.DataSetType == ImageSetType.Planet) - { - subDivisionLevel = Math.Max(2, (6 - Level) * 2); - } - } - - for (int i = 0; i < 4; i++) - { - RenderTriangleLists[i] = new List(); - } - - // try - { - double lat, lng; - - int index = 0; - double tileDegrees = 360 / (Math.Pow(2, this.Level)); - - latMin = AbsoluteMetersToLatAtZoom(tileY * 256, Level); - latMax = AbsoluteMetersToLatAtZoom((tileY + 1) * 256, Level); - lngMin = (((double)this.tileX * tileDegrees) - 180.0); - lngMax = ((((double)(this.tileX + 1)) * tileDegrees) - 180.0); - - double latCenter = AbsoluteMetersToLatAtZoom(((tileY * 2) + 1) * 256, Level + 1); - - TopLeft = (Vector3d)GeoTo3d(latMin, lngMin, false); - BottomRight = (Vector3d)GeoTo3d(latMax, lngMax, false); - TopRight = (Vector3d)GeoTo3d(latMin, lngMax, false); - BottomLeft = (Vector3d)GeoTo3d(latMax, lngMin, false); - - PositionTexture[] verts = new PositionTexture[(subDivisionLevel + 1) * (subDivisionLevel + 1)]; - - - tileDegrees = lngMax - lngMin; - double dGrid = (tileDegrees / subDivisionLevel); - int x1, y1; - double textureStep = 1.0f / subDivisionLevel; - - double latDegrees = latMax - latCenter; - - for (y1 = 0; y1 < subDivisionLevel / 2; y1++) - { - - if (y1 != subDivisionLevel / 2) - { - lat = latMax - (2 * textureStep * latDegrees * (double)y1); - } - else - { - lat = latCenter; - } - - for (x1 = 0; x1 <= subDivisionLevel; x1++) - { - if (x1 != subDivisionLevel) - { - lng = lngMin + (textureStep * tileDegrees * (double)x1); - } - else - { - lng = lngMax; - } - index = y1 * (subDivisionLevel + 1) + x1; - verts[index] = new PositionTexture(); - verts[index].Position = (Vector3d)GeoTo3dWithAlt(lat, lng, false, true);// Add Altitude mapping here - verts[index].Tu = (x1 * textureStep)*Tile.uvMultiple; - verts[index].Tv = ((AbsoluteLatToMetersAtZoom(lat, Level) - (tileY * 256)) / 256f)*Tile.uvMultiple; - demIndex++; - } - } - latDegrees = latMin - latCenter; - - for (y1 = subDivisionLevel / 2; y1 <= subDivisionLevel; y1++) - { - - if (y1 != subDivisionLevel) - { - lat = latCenter + (2 * textureStep * latDegrees * (double)(y1 - (subDivisionLevel / 2))); - } - else - { - lat = latMin; - } - - for (x1 = 0; x1 <= subDivisionLevel; x1++) - { - if (x1 != subDivisionLevel) - { - lng = lngMin + (textureStep * tileDegrees * (double)x1); - } - else - { - lng = lngMax; - } - index = y1 * (subDivisionLevel + 1) + x1; - verts[index] = new PositionTexture(); - verts[index].Position = (Vector3d)GeoTo3dWithAlt(lat, lng, false, true);// Add Altitude mapping here - verts[index].Tu = (x1 * textureStep)*Tile.uvMultiple; - verts[index].Tv = ((AbsoluteLatToMetersAtZoom(lat, Level) - (tileY * 256)) / 256f)*Tile.uvMultiple; - demIndex++; - } - } - if (tileY == 0) - { - // Send the tops to the pole to fill in the Bing Hole - y1 = subDivisionLevel; - for (x1 = 0; x1 <= subDivisionLevel; x1++) - { - index = y1 * (subDivisionLevel + 1) + x1; - verts[index].Position = Vector3d.Create(0, 1, 0); - - } - } - - if (tileY == Math.Pow(2, Level) - 1) - { - // Send the tops to the pole to fill in the Bing Hole - y1 = 0; - for (x1 = 0; x1 <= subDivisionLevel; x1++) - { - index = y1 * (subDivisionLevel + 1) + x1; - verts[index].Position = Vector3d.Create(0, -1, 0); - - } - } - - - TriangleCount = (subDivisionLevel) * (subDivisionLevel) * 2; - - int quarterDivisions = subDivisionLevel / 2; - int part = 0; - - if (renderContext.gl == null) - { - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - - index = 0; - for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - //index = ((y1 * quarterDivisions * 6) + 6 * x1); - // First triangle in quad - - PositionTexture p1; - PositionTexture p2; - PositionTexture p3; - - p1 = verts[(y1 * (subDivisionLevel + 1) + x1)]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - RenderTriangle tri = RenderTriangle.Create(p1, p2, p3, texture, Level); - RenderTriangleLists[part].Add(tri); - - // Second triangle in quad - p1 = verts[(y1 * (subDivisionLevel + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (subDivisionLevel + 1) + x1)]; - p3 = verts[((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))]; - tri = RenderTriangle.Create(p1, p2, p3, texture, Level); - RenderTriangleLists[part].Add(tri); - - } - } - - part++; - } - } - } - else - { - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(verts.Length * 5); - float[] buffer = (float[])(object)f32array; - index = 0; - foreach (PositionTexture pt in verts) - { - index = AddVertex(buffer, index, pt); - } - - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - - for (int y2 = 0; y2 < 2; y2++) - { - for (int x2 = 0; x2 < 2; x2++) - { - Uint16Array ui16array = new Uint16Array(TriangleCount * 3); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - - index = 0; - for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) - { - for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) - { - // First triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - - // Second triangle in quad - indexArray[index++] = (UInt16)((y1 * (subDivisionLevel + 1) + (x1 + 1))); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + x1)); - indexArray[index++] = (UInt16)(((y1 + 1) * (subDivisionLevel + 1) + (x1 + 1))); - } - } - - IndexBuffers[part] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, IndexBuffers[part]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - - part++; - } - } - } - - } - // catch - { - } - - return true; - } - - - //public MercatorTile(int Level, int X, int Y, ImageSet dataset) - //{ - // this.Level = Level; - // this.X = X; - // this.Y = Y; - // this.tileSize = dataset.TileSize; - // rect = new Rectangle(0, 0, tileSize, tileSize); - // ComputeBoundingSphere(); - //} - - public MercatorTile() - { - } - - public static MercatorTile Create(int level, int X, int Y, Imageset dataset, Tile parent) - { - MercatorTile temp = new MercatorTile(); - temp.Parent = parent; - temp.Level = level; - temp.tileX = X; - temp.tileY = Y; - temp.dataset = dataset; - temp.ComputeBoundingSphere(); - - return temp; - } - - private float GetDemSample(int x, int y) - { - return DemData[(32 - y) * 33 + x]; - } - - public override bool CreateDemFromParent() - { - MercatorTile parent = Parent as MercatorTile; - - if (parent == null || parent.DemData == null) - { - return false; - } - - - int offsetX = ((tileX % 2) == 1 ? 16 : 0); - int offsetY = ((tileY % 2) == 1 ? 16 : 0); - - - DemData = new float[demSize]; - // Interpolate accross - for (int y = 0; y < 33; y += 2) - { - bool copy = true; - for (int x = 0; x < 33; x++) - { - if (copy) - { - DemData[(32 - y) * 33 + x] = parent.GetDemSample((x / 2) + offsetX, (y / 2) + offsetY); - } - else - { - DemData[(32 - y) * 33 + x] = - ( - ( - parent.GetDemSample((x / 2) + offsetX, (y / 2) + offsetY) + - parent.GetDemSample(((x / 2) + offsetX) + 1, (y / 2) + offsetY) - ) / 2); - } - copy = !copy; - - } - } - // Interpolate down - for (int y = 1; y < 33; y += 2) - { - for (int x = 0; x < 33; x++) - { - - DemData[(32 - y) * 33 + x] = - ( - ( - GetDemSample(x, y - 1) + - GetDemSample(x, y + 1) - ) / 2); - - } - } - - foreach (float sample in DemData) - { - demAverage += sample; - } - - demAverage /= DemData.Length; - DemReady = true; - return true; - } - - - // string[] tileMap = new string[] { "q", "r", "t", "s" }; - - public static Vector2d GetCentrePointOffsetAsTileRatio(double lat, double lon, int zoom) - { - double metersX = AbsoluteLonToMetersAtZoom(lon, zoom); - - double relativeXIntoCell = (metersX / GRID_SIZE) - - Math.Floor(metersX / GRID_SIZE); - - double metersY = AbsoluteLatToMetersAtZoom(lat, zoom); - - double relativeYIntoCell = (metersY / GRID_SIZE) - - Math.Floor(metersY / GRID_SIZE); - - return (Vector2d.Create(relativeXIntoCell, relativeYIntoCell)); - } - - public static double RelativeMetersToLatAtZoom(double Y, - int zoom) - { - double metersPerPixel = MetersPerPixel2(zoom); - double metersY = Y * metersPerPixel; - - return (RadToDeg(Math.PI / 2 - 2 * Math.Atan(Math.Exp(0 - metersY / EARTH_RADIUS)))); - } - - public static double RelativeMetersToLonAtZoom(double X, - int zoom) - { - double metersPerPixel = MetersPerPixel2(zoom); - double metersX = X * metersPerPixel; - - return (RadToDeg(metersX / EARTH_RADIUS)); - } - - public static int AbsoluteLatToMetersAtZoom(double latitude, int zoom) - { - double sinLat = Math.Sin(DegToRad(latitude)); - double metersY = EARTH_RADIUS / 2 * Math.Log((1 + sinLat) / (1 - sinLat)); - double metersPerPixel = MetersPerPixel2(zoom); - - return ((int)(Math.Round(OFFSET_METERS - metersY) / metersPerPixel)); - } - - public static double AbsoluteMetersToLatAtZoom(int Y, int zoom) - { - double metersPerPixel = MetersPerPixel2(zoom); - double metersY = (double)OFFSET_METERS - (double)Y * metersPerPixel; - - return (RadToDeg(Math.PI / 2 - 2 * Math.Atan(Math.Exp(0 - metersY / EARTH_RADIUS)))); - } - - public static int AbsoluteLonToMetersAtZoom(double longitude, int zoom) - { - double metersX = EARTH_RADIUS * DegToRad(longitude); - double metersPerPixel = MetersPerPixel2(zoom); - - return (int)(((metersX + OFFSET_METERS) / metersPerPixel)); - //return ((int)Math.Round((metersX + OFFSET_METERS) / metersPerPixel)); - } - - public static double AbsoluteMetersToLonAtZoom(int X, int zoom) - { - double metersPerPixel = MetersPerPixel2(zoom); - double metersX = X * metersPerPixel - OFFSET_METERS; - - return (RadToDeg(metersX / EARTH_RADIUS)); - } - - - public static int AbsoluteLonToMetersAtZoomTile(double longitude, int zoom, int tileX) - { - double metersX = EARTH_RADIUS * DegToRad(longitude); - double metersPerPixel = MetersPerPixel2(zoom); - return ((int)((metersX + OFFSET_METERS) / metersPerPixel)); - - //return ((int)Math.Round((metersX + OFFSET_METERS) / metersPerPixel)); - } - - public static int AbsoluteLatToMetersAtZoomTile(double latitude, int zoom, int tileX) - { - double sinLat = Math.Sin(DegToRad(latitude)); - double metersY = EARTH_RADIUS / 2 * Math.Log((1 + sinLat) / (1 - sinLat)); - double metersPerPixel = MetersPerPixel2(zoom); - - return ((int)(Math.Round(OFFSET_METERS - metersY) / metersPerPixel)); - } - - public static double AbsoluteMetersToLonAtZoomByTileY(int X, int zoom, int tileY) - { - double metersPerPixel = MetersPerPixel2(zoom); - double metersX = X * metersPerPixel - OFFSET_METERS; - - return (RadToDeg(metersX / EARTH_RADIUS)); - } - - - private static double DegToRad(double deg) - { - return (deg * Math.PI / 180.0); - } - - public static double MetersPerPixel2(int zoom) - { - //return MetersPerPixel(zoom); - return (BASE_METERS_PER_PIXEL / (double)(1 << zoom)); - } - - private static double RadToDeg(double rad) - { - return (rad * 180.0 / Math.PI); - } - private const double EARTH_RADIUS = 6378137; - private const double GRID_SIZE = 256.0d; - private const double BASE_METERS_PER_PIXEL = 156543;//163840; - private const double OFFSET_METERS = 20037508; - - } -} \ No newline at end of file diff --git a/engine/csharp_ref/MinorPlanets.cs b/engine/csharp_ref/MinorPlanets.cs deleted file mode 100644 index ab15bede..00000000 --- a/engine/csharp_ref/MinorPlanets.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; -using System.Html.Data.Files; - -namespace wwtlib -{ - class MinorPlanets - { - public static List MPCList = new List(); - - static WebFile webMpcFile; - - public static void GetMpcFile(string url) - { - webMpcFile = new WebFile(url); - webMpcFile.ResponseType = "blob"; - webMpcFile.OnStateChange = StarFileStateChange; - webMpcFile.Send(); - } - - public static void StarFileStateChange() - { - if (webMpcFile.State == StateType.Error) - { - Script.Literal("alert({0})", webMpcFile.Message); - } - else if (webMpcFile.State == StateType.Received) - { - System.Html.Data.Files.Blob mainBlob = (System.Html.Data.Files.Blob)webMpcFile.GetBlob(); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e) - { - ReadFromBin(new BinaryReader(new Uint8Array(chunck.Result))); - InitMPCVertexBuffer(); - }; - chunck.ReadAsArrayBuffer(mainBlob); - } - } - - private static void ReadFromBin(BinaryReader br) - { - MPCList = new List(); - int len = (int)br.Length; - EOE ee; - try - { - while (br.Position < len) - { - ee = EOE.Create(br); - MPCList.Add(ee); - } - } - catch - { - } - br.Close(); - } - - static bool initBegun = false; - - static BlendState[] mpcBlendStates = new BlendState[7]; - - public static Texture starTexture = null; - // ** Begin - public static void DrawMPC3D(RenderContext renderContext, float opacity, Vector3d centerPoint) - { - double zoom = renderContext.ViewCamera.Zoom; - double distAlpha = ((Math.Log(Math.Max(1, zoom)) / Math.Log(4)) - 15.5) * 90; - - int alpha = Math.Min(255, Math.Max(0, (int)distAlpha)); - - - - if (alpha > 254) - { - return; - } - - - if (mpcVertexBuffer == null) - { - if (starTexture == null) - { - starTexture = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("StarProfileAlpha.png")); - } - for (int i = 0; i < 7; i++) - { - mpcBlendStates[i] = BlendState.Create(false, 1000); - } - - if (!initBegun) - { - StartInit(); - initBegun = true; - } - return; - } - - Matrix3d offset = Matrix3d.Translation(Vector3d.Negate(centerPoint)); - Matrix3d world = Matrix3d.MultiplyMatrix(renderContext.World, offset); - Matrix3d matrixWV = Matrix3d.MultiplyMatrix(world, renderContext.View); - - Vector3d cam = Vector3d.TransformCoordinate(renderContext.CameraPosition, Matrix3d.InvertMatrix(renderContext.World)); - - //todo star profile texture - - if (mpcVertexBuffer != null) - { - for (int i = 0; i < 7; i++) - { - // mpcBlendStates[i].TargetState = ((Properties.Settings.Default.MinorPlanetsFilter & (int)Math.Pow(2, i)) != 0); - mpcBlendStates[i].TargetState = true; - - if (mpcBlendStates[i].State) - { - - KeplerPointSpriteShader.Use(renderContext, matrixWV, mpcVertexBuffer[i].VertexBuffer, starTexture.Texture2d, Colors.White, - opacity * mpcBlendStates[i].Opacity, false, - (float)(SpaceTimeController.JNow - KeplerVertex.baseDate), 0, renderContext.CameraPosition, 200f, .1f); - - renderContext.gl.drawArrays(GL.POINTS, 0, mpcVertexBuffer[i].Count); - } - } - } - } - - private static void StartInit() - { - if (!WWTControl.Singleton.FreestandingMode) { - GetMpcFile(URLHelpers.singleton.coreStaticUrl("wwtweb/catalog.aspx?Q=mpcbin")); - } - } - - public static void InitMPCVertexBuffer() - { - try - { - if (mpcVertexBuffer == null) - { - KeplerVertexBuffer[] mpcVertexBufferTemp = new KeplerVertexBuffer[7]; - - mpcCount = MinorPlanets.MPCList.Count; - //KeplerVertexBuffer11 temp = new KeplerVertexBuffer11(mpcCount, RenderContext11.PrepDevice); - - List[] lists = new List[7]; - for (int i = 0; i < 7; i++) - { - lists[i] = new List(); - } - - foreach (EOE ee in MinorPlanets.MPCList) - { - int listID = 0; - if (ee.a < 2.5) - { - listID = 0; - } - else if (ee.a < 2.83) - { - listID = 1; - } - else if (ee.a < 2.96) - { - listID = 2; - } - else if (ee.a < 3.3) - { - listID = 3; - } - else if (ee.a < 5) - { - listID = 4; - } - else if (ee.a < 10) - { - listID = 5; - } - else - { - listID = 6; - } - - KeplerVertex vert = new KeplerVertex(); - vert.Fill(ee); - - lists[listID].Add(vert); - } - - for (int i = 0; i < 7; i++) - { - mpcVertexBufferTemp[i] = KeplerVertexBuffer.Create(lists[i]); - mpcVertexBufferTemp[i].Unlock(); - } - - mpcVertexBuffer = mpcVertexBufferTemp; - } - } - finally - { - - } - } - - static KeplerVertexBuffer[] mpcVertexBuffer = null; - static int mpcCount = 0; - } - -} diff --git a/engine/csharp_ref/MouseEvent.cs b/engine/csharp_ref/MouseEvent.cs deleted file mode 100644 index d4985f80..00000000 --- a/engine/csharp_ref/MouseEvent.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Runtime.CompilerServices; - -namespace System.Html -{ - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class MouseEvent - { - internal MouseEvent() {} - - [ScriptField] - public int OffsetX { get { return 0; } set { } } - - [ScriptField] - public int OffsetY { get { return 0; } set { } } - - [ScriptField] - public int PageX { get { return 0; } set { } } - - [ScriptField] - public int PageY { get { return 0; } set { } } - - [ScriptField] - public int stylePaddingLeft { get { return 0; } set { } } - - [ScriptField] - public int stylePaddingTop { get { return 0; } set { } } - - [ScriptField] - public int styleBorderLeft { get { return 0; } set { } } - - [ScriptField] - public int styleBorderTop { get { return 0; } set { } } - - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class MouseCanvasElement - { - internal MouseCanvasElement() { } - - [ScriptField] - public MouseCanvasElement offsetParent { get { return (MouseCanvasElement)this; } set { } } - - [ScriptField] - public int offsetLeft { get { return 0; } set { } } - - [ScriptField] - public int offsetTop { get { return 0; } set { } } - - - } -} diff --git a/engine/csharp_ref/Place.cs b/engine/csharp_ref/Place.cs deleted file mode 100644 index e9cf0b0f..00000000 --- a/engine/csharp_ref/Place.cs +++ /dev/null @@ -1,729 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; - -namespace wwtlib -{ - public class Place : IThumbnail, IPlace - { - public Place() - { - // - // TODO: Add constructor logic here - // - } - - private object tag; - - public object Tag - { - get { return tag; } - set { tag = value; } - } - - private string url; - - public string Url - { - get { return url; } - set { url = value; } - } - - private ImageElement thumbnail; - - public ImageElement Thumbnail - { - get { return thumbnail; } - set { thumbnail = value; } - } - - private string name; - - public string Name - { - get { return Names[0]; } - // set { name = value; } - } - public string[] Names - { - get - { - if (string.IsNullOrEmpty(name)) - { - return ("").Split(";"); - } - return name.Split(";"); - } - set - { - name = UiTools.GetNamesStringFromArray(value); - } - } - - private CameraParameters camParams = CameraParameters.Create(0.0, 0.0, -1.0, 0, 0, 100); - - public CameraParameters CamParams - { - get - { - if (Classification == Classification.SolarSystem && camParams.Target != SolarSystemObjects.Custom) - { - // todo wire this up when astrocalc is moved - AstroRaDec raDec = Planets.GetPlanetLocation(Name); - camParams.RA = raDec.RA; - camParams.Dec = raDec.Dec; - this.distnace = raDec.Distance; - } - - return camParams; - } - set { camParams = value; } - } - - public void UpdatePlanetLocation(double jNow) - { - camParams.ViewTarget = Planets.GetPlanet3dLocationJD(Target, jNow); - if (Target != SolarSystemObjects.Undefined && Target != SolarSystemObjects.Custom) - { - //todo add back when planets are added - camParams.ViewTarget = Planets.GetPlanetTargetPoint(Target, Lat, Lng, jNow); - } - } - - Vector3d location3d = Vector3d.Create(0, 0, 0); - - public Vector3d Location3d - { - get - { - if (Classification == Classification.SolarSystem || (location3d.X == 0 && location3d.Y == 0 && location3d.Z == 0)) - { - location3d = Coordinates.RADecTo3d(this.RA, this.Dec); - } - return location3d; - } - } - - public double Lat - { - get { return CamParams.Lat; } - set { camParams.Lat = value; } - } - - public double Lng - { - get { return CamParams.Lng; } - set { camParams.Lng = value; } - } - - public double Opacity - { - get { return CamParams.Opacity; } - set { camParams.Opacity = value; } - } - public string HtmlDescription = ""; - - private string constellation = ""; - - public string Constellation - { - get { return constellation; } - set { constellation = value; } - } - private Classification classification = Classification.Galaxy; - - public Classification Classification - { - get { return classification; } - set { classification = value; } - } - private ImageSetType type = ImageSetType.Sky; - - public ImageSetType Type - { - get { return type; } - set { type = value; } - } - private double magnitude = 0; - - public double Magnitude - { - get { return magnitude; } - set { magnitude = value; } - } - private double distnace = 0; - - public double Distance - { - get { return distnace; } - set { distnace = value; } - } - /// - /// Angular Size in Arc Seconds - /// - public double AngularSize = 60; - - - public double ZoomLevel - { - get { return CamParams.Zoom; } - set { camParams.Zoom = value; } - } - - public string annotation = ""; - public string Annotation - { - get - { - return annotation; - } - set - { - annotation = value; - } - } - - - - ImageElement thumbNail = null; - - private Imageset studyImageset = null; - - public Imageset StudyImageset - { - get { return studyImageset; } - set { studyImageset = value; } - } - - - private Imageset backgroundImageSet = null; - - public Imageset BackgroundImageset - { - get { return backgroundImageSet; } - set - { - if (value != null) - { - Type = value.DataSetType; - } - backgroundImageSet = value; - } - } - - private double searchDistance = 0; - - public double SearchDistance - { - get { return searchDistance; } - set { searchDistance = value; } - } - - double elevation = 50; - - public double Elevation - { - get { return elevation; } - set { elevation = value; } - } - - private string thumbnailField; - - public string ThumbnailUrl - { - get - { - if (string.IsNullOrEmpty(this.thumbnailField)) - { - if (studyImageset != null && !string.IsNullOrEmpty(studyImageset.ThumbnailUrl)) - { - return studyImageset.ThumbnailUrl; - } - - if (backgroundImageSet != null && !string.IsNullOrEmpty(backgroundImageSet.ThumbnailUrl)) - { - return backgroundImageSet.ThumbnailUrl; - } - - string name = this.Name; - - if (name.IndexOf(";") > -1) - { - name = name.Substr(0, name.IndexOf(";")); - } - - if (Classification == Classification.Star || WWTControl.Singleton.FreestandingMode) - { - return URLHelpers.singleton.engineAssetUrl("thumb_star.jpg"); - } - - return URLHelpers.singleton.coreStaticUrl("wwtweb/thumbnail.aspx?name=" + name.ToLowerCase()); - } - - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - - public double RA - { - get - { - return CamParams.RA; - } - set - { - camParams.RA = value; - } - } - - - public double Dec - { - get { return CamParams.Dec; } - set { camParams.Dec = value; } - } - - //public Place(string name, double lat, double lng) - //{ - // this.name = name; - // Lat = lat; - // Lng = lng; - // Type = DataSetType.Geo; - // ZoomLevel = -1; - //} - - public static Place Create(string name, double lat, double lng, Classification classification, string constellation, ImageSetType type, double zoomFactor) - { - Place temp = new Place(); - temp.ZoomLevel = zoomFactor; - temp.constellation = constellation; - temp.name = name; - if (type == ImageSetType.Sky || type == ImageSetType.SolarSystem) - { - temp.camParams.RA = lng; - } - else - { - temp.Lng = lng; - } - temp.Lat = lat; - temp.Classification = classification; - temp.Type = type; - - return temp; - } - - public static Place CreateCameraParams(string name, CameraParameters camParams, Classification classification, string constellation, ImageSetType type, SolarSystemObjects target) - { - Place temp = new Place(); - - temp.constellation = constellation; - temp.name = name; - temp.Classification = classification; - temp.camParams = camParams; - temp.Type = type; - temp.Target = target; - - return temp; - } - - //public TourPlace(string input, bool sky) - //{ - - // string[] sa = input.Split('\t'); - - // if (sky) - // { - // name = sa[0]; - - - // Lat = Convert.ToDouble(sa[3]); - // if (sky) - // { - // camParams.RA = Convert.ToDouble(sa[2]) / 15; - // Type = ImageSetType.Sky; - // } - // else - // { - // Lng = 180 - ((Convert.ToDouble(sa[2]) / 24.0 * 360) - 180); - // Type = ImageSetType.Earth; - // } - // string type = sa[1]; - // type = type.Replace(" ", ""); - // type = type.Replace("StarCluster", "Cluster"); - // type = type.Replace("TripleStar", "MultipleStars"); - // type = type.Replace("HubbleImage", "Unidentified"); - // Classification = (Classification)Enum.Parse(typeof(Classification), type); - // if (sa.Length > 4) - // { - // try - // { - // if (sa[4].ToUpper() != "NULL" && sa[4] != "") - // { - // magnitude = Convert.ToDouble(sa[4]); - // } - // } - // catch - // { - // } - // } - // if (sa.Length > 5) - // { - // constellation = sa[5].ToUpper(); - // } - // if (sa.Length > 6) - // { - // try - // { - // ZoomLevel = Convert.ToDouble(sa[6]); - // } - // catch - // { - // } - // } - // if (sa.Length > 7) - // { - // try - // { - // distnace = Convert.ToDouble(sa[7]); - // } - // catch - // { - // } - // } - // } - // else - // { - // name = sa[0]; - // Lat = (float)Convert.ToDouble(sa[1]); - // Lng = (float)Convert.ToDouble(sa[2]); - // Type = ImageSetType.Earth; - // if (sa.Length > 3) - // { - // elevation = Convert.ToDouble(sa[3]); - // } - // } - //} - public override string ToString() - { - return name; - } - - internal void SaveToXml(XmlTextWriter xmlWriter, string elementName) - { - - xmlWriter.WriteStartElement(elementName); - xmlWriter.WriteAttributeString("Name", name); - xmlWriter.WriteAttributeString("DataSetType", Enums.ToXml("ImageSetType", (int) type)); - if (this.Type == ImageSetType.Sky) - { - xmlWriter.WriteAttributeString("RA", camParams.RA.ToString()); - xmlWriter.WriteAttributeString("Dec", camParams.Dec.ToString()); - } - else - { - xmlWriter.WriteAttributeString("Lat", Lat.ToString()); - xmlWriter.WriteAttributeString("Lng", Lng.ToString()); - } - - xmlWriter.WriteAttributeString("Constellation", constellation); - xmlWriter.WriteAttributeString("Classification", Enums.ToXml("Classification", (int)classification)); - xmlWriter.WriteAttributeString("Magnitude", magnitude.ToString()); - xmlWriter.WriteAttributeString("Distance", distnace.ToString()); - xmlWriter.WriteAttributeString("AngularSize", AngularSize.ToString()); - xmlWriter.WriteAttributeString("ZoomLevel", ZoomLevel.ToString()); - xmlWriter.WriteAttributeString("Rotation", camParams.Rotation.ToString()); - xmlWriter.WriteAttributeString("Angle", camParams.Angle.ToString()); - xmlWriter.WriteAttributeString("Opacity", camParams.Opacity.ToString()); - xmlWriter.WriteAttributeString("Target", Enums.ToXml("SolarSystemObjects", (int)Target)); - xmlWriter.WriteAttributeString("ViewTarget", camParams.ViewTarget.ToString()); - xmlWriter.WriteAttributeString("TargetReferenceFrame", camParams.TargetReferenceFrame); - //todo what do we do with full dome? - // xmlWriter.WriteAttributeString("DomeAlt", camParams.DomeAlt.ToString()); - // xmlWriter.WriteAttributeString("DomeAz", camParams.DomeAz.ToString()); - xmlWriter.WriteStartElement("Description"); - xmlWriter.WriteCData(HtmlDescription); - xmlWriter.WriteEndElement(); - - - if (backgroundImageSet != null) - { - xmlWriter.WriteStartElement("BackgroundImageSet"); - Imageset.SaveToXml(xmlWriter, backgroundImageSet, ""); - - xmlWriter.WriteEndElement(); - } - - if (studyImageset != null) - { - Imageset.SaveToXml(xmlWriter, studyImageset, ""); - } - xmlWriter.WriteEndElement(); - } - - internal static Place FromXml(XmlNode place) - { - Place newPlace = new Place(); - - newPlace.name = place.Attributes.GetNamedItem("Name").Value; - - if (place.Attributes.GetNamedItem("MSRComponentId") != null && place.Attributes.GetNamedItem("Permission") != null && place.Attributes.GetNamedItem("Url") != null) - { - //communities item - newPlace.Url = place.Attributes.GetNamedItem("Url").Value; - newPlace.ThumbnailUrl = place.Attributes.GetNamedItem("Thumbnail").Value; - return newPlace; - } - - if (place.Attributes.GetNamedItem("DataSetType") != null) - { - newPlace.type = (ImageSetType)Enums.Parse("ImageSetType", place.Attributes.GetNamedItem("DataSetType").Value); - } - - if (newPlace.Type == ImageSetType.Sky) - { - newPlace.camParams.RA = double.Parse(place.Attributes.GetNamedItem("RA").Value); - newPlace.camParams.Dec = double.Parse(place.Attributes.GetNamedItem("Dec").Value); - } - else - { - newPlace.Lat = double.Parse(place.Attributes.GetNamedItem("Lat").Value); - newPlace.Lng = double.Parse(place.Attributes.GetNamedItem("Lng").Value); - } - - if (place.Attributes.GetNamedItem("Constellation") != null) - { - newPlace.constellation = place.Attributes.GetNamedItem("Constellation").Value; - } - - if (place.Attributes.GetNamedItem("Classification") != null) - { - newPlace.classification = (Classification)Enums.Parse("Classification", place.Attributes.GetNamedItem("Classification").Value); - - } - - if (place.Attributes.GetNamedItem("Magnitude") != null) - { - newPlace.magnitude = double.Parse(place.Attributes.GetNamedItem("Magnitude").Value); - } - - if (place.Attributes.GetNamedItem("AngularSize") != null) - { - newPlace.AngularSize = double.Parse(place.Attributes.GetNamedItem("AngularSize").Value); - } - - if (place.Attributes.GetNamedItem("ZoomLevel") != null) - { - - newPlace.ZoomLevel = double.Parse(place.Attributes.GetNamedItem("ZoomLevel").Value); - } - - if (place.Attributes.GetNamedItem("Rotation") != null) - { - newPlace.camParams.Rotation = double.Parse(place.Attributes.GetNamedItem("Rotation").Value); - } - - if (place.Attributes.GetNamedItem("Annotation") != null) - { - newPlace.annotation = place.Attributes.GetNamedItem("Annotation").Value; - } - - if (place.Attributes.GetNamedItem("Angle") != null) - { - newPlace.camParams.Angle = double.Parse(place.Attributes.GetNamedItem("Angle").Value); - } - - if (place.Attributes.GetNamedItem("Opacity") != null) - { - newPlace.camParams.Opacity = Single.Parse(place.Attributes.GetNamedItem("Opacity").Value); - } - else - { - newPlace.camParams.Opacity = 100; - } - - newPlace.Target = SolarSystemObjects.Undefined; - - if (place.Attributes.GetNamedItem("Target") != null) - { - newPlace.Target = (SolarSystemObjects)Enums.Parse("SolarSystemObjects", place.Attributes.GetNamedItem("Target").Value); - } - - if (place.Attributes.GetNamedItem("ViewTarget") != null) - { - newPlace.camParams.ViewTarget = Vector3d.Parse(place.Attributes.GetNamedItem("ViewTarget").Value); - } - - if (place.Attributes.GetNamedItem("TargetReferenceFrame") != null) - { - newPlace.camParams.TargetReferenceFrame = place.Attributes.GetNamedItem("TargetReferenceFrame").Value; - } - - XmlNode descriptionNode = Util.SelectSingleNode(place, "Description"); - if (descriptionNode != null) - { - newPlace.HtmlDescription = Util.GetInnerText(descriptionNode); - } - - XmlNode backgroundImageSet = Util.SelectSingleNode(place, "BackgroundImageSet"); - if (backgroundImageSet != null) - { - XmlNode imageSet = Util.SelectSingleNode(backgroundImageSet, "ImageSet"); - - newPlace.backgroundImageSet = Imageset.FromXMLNode(imageSet); - - } - XmlNode study = Util.SelectSingleNode(place, "ForegroundImageSet"); - if (study != null) - { - XmlNode imageSet = Util.SelectSingleNode(study, "ImageSet"); - - newPlace.studyImageset = Imageset.FromXMLNode(imageSet); - - } - study = Util.SelectSingleNode(place, "ImageSet"); - if (study != null) - { - - newPlace.studyImageset = Imageset.FromXMLNode(study); - - } - - - return newPlace; - } - //internal static TourPlace FromAstroObjectsRow(AstroObjectsDataset.spGetAstroObjectsRow row) - //{ - // TourPlace newPlace = new TourPlace(); - - // string seperator = ""; - - // string name = ""; - - // if (!row.IsPopularName1Null() && !String.IsNullOrEmpty(row.PopularName1)) - // { - // name = ProperCaps(row.PopularName1); - // seperator = ";"; - // } - - // if (!row.IsMessierNameNull() && !String.IsNullOrEmpty(row.MessierName)) - // { - // name = name + seperator + row.MessierName; - // seperator = ";"; - // } - - // if (!row.IsNGCNameNull() && !String.IsNullOrEmpty(row.NGCName)) - // { - // name = name + seperator + row.NGCName; - // seperator = ";"; - // } - - // newPlace.name = name; - // newPlace.Type = ImageSetType.Sky; - // newPlace.Lat = row.Dec2000; - // newPlace.Lng = row.Ra2000 / 15; - // newPlace.constellation = Constellations.Abbreviation(row.ConstellationName); - // newPlace.Classification = Classification.Galaxy; //(Classification)Enum.Parse(typeof(Classification), place.Attributes["Classification"].Value); - // newPlace.magnitude = row.IsVisualMagnitudeNull() ? row.VisualMagnitude : 0; - // newPlace.AngularSize = 0; // todo fix this - // newPlace.ZoomLevel = .00009; - // return newPlace; - //} - static string ProperCaps(string name) - { - string[] list = name.Split(" "); - - string ProperName = ""; - - foreach (string part in list) - { - ProperName = ProperName + part.Substr(0,1).ToUpperCase() + (part.Length > 1 ? part.Substr(1).ToLowerCase() : "") + " "; - } - - return ProperName.Trim(); - - } - - #region IThumbnail Members - - Rectangle bounds; - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - #endregion - public bool IsImage - { - get - { - return studyImageset != null || backgroundImageSet != null; - } - } - - public bool IsTour - { - get { return false; } - } - - public bool IsFolder - { - get { return false; } - } - - public List Children - { - get { return new List(); } - } - - #region IThumbnail Members - - - public bool ReadOnly - { - get { return true; } - } - - #endregion - - #region IPlace Members - - public SolarSystemObjects Target - { - get - { - return camParams.Target; - } - set - { - camParams.Target = value; - } - } - - #endregion - - #region IThumbnail Members - - - public bool IsCloudCommunityItem - { - get { return false; } - } - - #endregion - } -} diff --git a/engine/csharp_ref/Planets.cs b/engine/csharp_ref/Planets.cs deleted file mode 100644 index 1bda816d..00000000 --- a/engine/csharp_ref/Planets.cs +++ /dev/null @@ -1,3004 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - -namespace wwtlib -{ - // Keplerian elements defined here use eccentric anomaly instead of mean anomaly and - // have all orbital plane angles converted to a rotation matrix. - public class KeplerianElements - { - public double a; - public double e; - public double ea; - public Matrix3d orientation; - } - - public class BodyAngles - { - public double poleDec; - public double poleRa; - public double primeMeridian; - public double rotationRate; - - public BodyAngles(double poleRa, double poleDec, double primeMeridian, double rotationRate ) - { - this.poleDec = poleDec; - this.poleRa = poleRa; - this.primeMeridian = primeMeridian; - this.rotationRate = rotationRate; - } - - }; - - public class Planets - { - static Texture[] planetTextures; - static double[] planetScales; - static double[] planetDiameters; - static double[] planetTilts; - static Vector3d[][] orbits; - static Dictionary planetDrawOrder; - - public static Texture LoadPlanetTexture(string url) - { - Texture texture = new Texture(); - - texture.Load(url); - - return texture; - } - - public static Vector3d GetPlanet3dLocation(SolarSystemObjects target) - { - try - { - if ((int)target < 21) - { - return (Vector3d)planet3dLocations[(int)target].Copy(); - } - } - catch - { - } - return Vector3d.Create(0, 0, 0); - } - - public static double GetPlanet3dSufaceAltitude(SolarSystemObjects target) - { - try - { - if ((int)target < 21) - { - return GetAdjustedPlanetRadius((int)target); - } - } - catch - { - } - return 0; - } - - public static Vector3d GetPlanetTargetPoint(SolarSystemObjects target, double lat, double lng, double jNow) - { - Vector3d temp; - if (jNow == 0) - { - temp = (Vector3d)Planets.GetPlanet3dLocation(target); - } - else - { - temp = (Vector3d)Planets.GetPlanet3dLocationJD(target, jNow); - } - temp.Add((Vector3d)Coordinates.RADecTo3dAu((lng / 15) + 6, lat, Planets.GetPlanet3dSufaceAltitude(target))); - return (Vector3d)temp; - } - - public static Vector3d GetPlanet3dLocationJD(SolarSystemObjects target, double jNow) - { - try - { - Vector3d result = new Vector3d(); - AstroRaDec centerRaDec = AstroCalc.GetPlanet(jNow, 0, 0, 0, -6378149); - Vector3d center = (Vector3d)Coordinates.RADecTo3dAu(centerRaDec.RA, centerRaDec.Dec, centerRaDec.Distance); - if (target == SolarSystemObjects.Earth) - { - result = Vector3d.Create(-center.X, -center.Y, -center.Z); - } - else - { - AstroRaDec planet = AstroCalc.GetPlanet(jNow, (EO)(int)target, 0, 0, -6378149); - result = (Vector3d)Coordinates.RADecTo3dAu(planet.RA, planet.Dec, planet.Distance); - result.Subtract(center); - } - - result.RotateX(Coordinates.MeanObliquityOfEcliptic(jNow) * RC); - if (Settings.Active.SolarSystemScale != 1) - { - switch (target) - { - case SolarSystemObjects.Moon: - { - Vector3d parent = (Vector3d)GetPlanet3dLocationJD(SolarSystemObjects.Earth, jNow); - // Parent Centric - result.Subtract(parent); - result.Multiply(Settings.Active.SolarSystemScale / 2); - result.Add(parent); - } - break; - case SolarSystemObjects.Io: - case SolarSystemObjects.Europa: - case SolarSystemObjects.Ganymede: - case SolarSystemObjects.Callisto: - { - Vector3d parent = (Vector3d)GetPlanet3dLocationJD(SolarSystemObjects.Jupiter, jNow); - - // Parent Centric - result.Subtract(parent); - result.Multiply(Settings.Active.SolarSystemScale); - result.Add(parent); - } - break; - - default: - break; - } - } - return (Vector3d)result; - } - catch - { - return Vector3d.Create(0, 0, 0); - } - } - public static AstroRaDec GetPlanetLocation(string name) - { - int id = GetPlanetIDFromName(name); - - if (planetLocations != null) - { - - return planetLocations[id]; - } - else - { - return AstroCalc.GetPlanet(SpaceTimeController.JNow, (EO)id, SpaceTimeController.Location.Lat, SpaceTimeController.Location.Lng, SpaceTimeController.Altitude); - } - } - public static AstroRaDec GetPlanetLocationJD(string name, double jNow) - { - int id = GetPlanetIDFromName(name); - - - return AstroCalc.GetPlanet(jNow, (EO)id, SpaceTimeController.Location.Lat, SpaceTimeController.Location.Lng, SpaceTimeController.Altitude); - - } - public static int GetPlanetIDFromName(string planetName) - { - switch (planetName) - { - case "Sun": - return 0; - case "Mercury": - return 1; - case "Venus": - return 2; - case "Mars": - return 3; - case "Jupiter": - return 4; - case "Saturn": - return 5; - case "Uranus": - return 6; - case "Neptune": - return 7; - case "Pluto": - return 8; - case "Moon": - return 9; - case "Io": - return 10; - case "Europa": - return 11; - case "Ganymede": - return 12; - case "Callisto": - return 13; - case "Earth": - return 19; - case "IoShadow": - return 14; - case "EuropaShadow": - return 15; - case "GanymedeShadow": - return 16; - case "CallistoShadow": - return 17; - case "SunEclipsed": - return 18; - case "Custom": - return 20; - case "Undefined": - return 65536; - default: - return -1; - } - } - - - public static string GetImageSetNameNameFrom3dId(int id) - { - switch (id) - { - case 0: - return "Sun"; - case 1: - return "Mercury"; - case 2: - return "Venus"; - case 3: - return "Visible Imagery"; - case 4: - return "Jupiter"; - case 5: - return "Saturn"; - case 6: - return "Uranus"; - case 7: - return "Neptune"; - case 8: - return "Pluto"; - case 9: - return "Moon"; - case 10: - return "Io (Jupiter)"; - case 11: - return "Europa (Jupiter)"; - case 12: - return "Ganymede (Jupiter)"; - case 13: - return "Callisto (Jupiter)"; - case 19: - return "Bing Maps Aerial"; - default: - return ""; - } - } - - public static string GetNameFrom3dId(int id) - { - switch (id) - { - case 0: - return "Sun"; - case 1: - return "Mercury"; - case 2: - return "Venus"; - case 3: - return "Mars"; - case 4: - return "Jupiter"; - case 5: - return "Saturn"; - case 6: - return "Uranus"; - case 7: - return "Neptune"; - case 8: - return "Pluto"; - case 9: - return "Moon"; - case 10: - return "Io"; - case 11: - return "Europa"; - case 12: - return "Ganymede"; - case 13: - return "Callisto"; - case 19: - return "Earth"; - default: - return ""; - } - } - //public static string GetLocalPlanetName(string planetName) - //{ - // switch (planetName) - // { - // case "Sun": - // return Language.GetLocalizedText(291, "Sun"); - // case "Mercury": - // return Language.GetLocalizedText(292, "Mercury"); - // case "Venus": - // return Language.GetLocalizedText(293, "Venus"); - // case "Mars": - // return Language.GetLocalizedText(294, "Mars"); - // case "Jupiter": - // return Language.GetLocalizedText(295, "Jupiter"); - // case "Saturn": - // return Language.GetLocalizedText(296, "Saturn"); - // case "Uranus": - // return Language.GetLocalizedText(297, "Uranus"); - // case "Neptune": - // return Language.GetLocalizedText(298, "Neptune"); - // case "Pluto": - // return Language.GetLocalizedText(299, "Pluto"); - // case "Moon": - // return Language.GetLocalizedText(300, "Moon"); - // case "Io": - // return Language.GetLocalizedText(301, "Io"); - // case "Europa": - // return Language.GetLocalizedText(302, "Europa"); - // case "Ganymede": - // return Language.GetLocalizedText(303, "Ganymede"); - // case "Callisto": - // return Language.GetLocalizedText(304, "Callisto"); - // default: - // return planetName; - // } - //} - - public static bool HighPercision = true; - public static bool ShowActualSize = Settings.Active.ActualPlanetScale; - protected static double RC = (Math.PI / 180.0); - public static double[] planetOrbitalYears; - private static Vector3d[] planet3dLocations; - public static double[] planetRotations; - public static Color[] planetColors; - public static double[] planetRotationPeriod; - static double jNow = 0; - - // Values taken from version 10 of the SPICE planetary constants file, updated - // October 21, 2011: ftp://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00010.tpc - // - // Precession rates for rotation angles are currently not stored. - // - // All angles are in degrees. - - static BodyAngles[] planetAngles = - { - new BodyAngles (286.13, 63.87, 84.176, 14.18440 ), // Sun - new BodyAngles (281.0097, 61.4143, 329.548, 6.1385025 ), // Mercury - new BodyAngles (272.76, 67.16, 160.20, -1.4813688 ), // Venus - new BodyAngles (317.68143, 52.88650, 176.630, 350.89198226 ), // Mars - new BodyAngles (268.056595, 64.495303, 284.95, 870.5360000 ), // Jupiter - new BodyAngles ( 40.589, 83.537, 38.90, 810.7939024 ), // Saturn - new BodyAngles (257.311, -15.175, 203.81, 501.1600928 ), // Uranus - new BodyAngles (299.36, 43.46, 253.18, 536.3128492 ), // Neptune - new BodyAngles (132.993, -6.163, 302.695, 56.3625225 ), // Pluto - new BodyAngles (269.9949, 66.5392, 38.3213, 13.17635815 ), // Moon - new BodyAngles (268.05, 64.50, 200.39, 203.4889538 ), // Io - new BodyAngles (268.08, 64.51, 36.022, 101.3747235 ), // Europa - new BodyAngles (268.20, 64.57, 44.064, 50.3176081 ), // Ganymede - new BodyAngles (268.72, 64.83, 259.51, 21.5710715 ), // Callisto - new BodyAngles ( 0.0, 0.0, 0.0, 0.0 ), // UNUSED - IoShadow - new BodyAngles ( 0.0, 0.0, 0.0, 0.0 ), // UNUSED - EuropaShadow - new BodyAngles ( 0.0, 0.0, 0.0, 0.0 ), // UNUSED - GanymedeShadow - new BodyAngles ( 0.0, 0.0, 0.0, 0.0 ), // UNUSED - CallistoShadow - new BodyAngles ( 0.0, 0.0, 0.0, 0.0 ), // UNUSED - SunEclipsed - new BodyAngles ( 0.0, 90.0, 190.147, 360.9856235 ) // Earth - }; - - public static void UpdatePlanetLocations(bool threeDee) - { - jNow = SpaceTimeController.JNow; - if (threeDee) - { - UpdateOrbits(0); - } - - if (planetDiameters == null) - { - planetDiameters = new double[20]; - planetDiameters[0] = 0.009291568; - planetDiameters[1] = 0.0000325794793734425; - planetDiameters[2] = 0.0000808669220531394; - planetDiameters[3] = 0.0000453785605596396; - planetDiameters[4] = 0.000954501; - planetDiameters[5] = 0.000802173; - planetDiameters[6] = 0.000339564; - planetDiameters[7] = 0.000324825; - planetDiameters[8] = 0.0000152007379777805; - planetDiameters[9] = 0.0000232084653538149; - planetDiameters[10] = 0.0000243519298386342; - planetDiameters[11] = 0.0000208692629580609; - planetDiameters[12] = 0.0000351742670356556; - planetDiameters[13] = 0.0000322263666626559; - planetDiameters[14] = 0.0000243519298386342; - planetDiameters[15] = 0.0000208692629580609; - planetDiameters[16] = 0.0000351742670356556; - planetDiameters[17] = 0.0000322263666626559; - planetDiameters[18] = 0.009291568 * 2; - planetDiameters[19] = 0.00008556264121178090; - } - if (planetColors == null) - { - Color lightYellow = Color.FromArgb(255, 255, 255, 221); - Color orangeRed = Color.FromArgb(255, 255, 68, 00); - - planetColors = new Color[20]; - planetColors[0] = Colors.Yellow; - planetColors[1] = Colors.White; - planetColors[2] = lightYellow; - planetColors[3] = orangeRed; - planetColors[4] = Color.FromArgb(255, 255, 165, 00); - planetColors[5] = Color.FromArgb(255, 184, 134, 11); - planetColors[6] = Color.FromArgb(255, 173, 216, 230); - planetColors[7] = Colors.Blue; - planetColors[8] = Colors.White; - planetColors[9] = Colors.White; - planetColors[10] = Colors.White; - planetColors[11] = Colors.White; - planetColors[12] = Colors.White; - planetColors[13] = Colors.White; - planetColors[14] = Colors.Black; - planetColors[15] = Colors.Black; - planetColors[16] = Colors.Black; - planetColors[17] = Colors.Black; - planetColors[18] = Colors.White; - planetColors[19] = Color.FromArgb(255, 173, 216, 230); - - } - - if (planetTilts == null) - { - planetTilts = new double[20]; - planetTilts[0] = 0.0; - planetTilts[1] = 0.01; - planetTilts[2] = 177.4; - planetTilts[3] = 25.19; - planetTilts[4] = 3.13; - planetTilts[5] = 26.73; - planetTilts[6] = 97.77; - planetTilts[7] = 28.32; - planetTilts[8] = 119.61; - planetTilts[9] = 23.439; - planetTilts[10] = 2.21; - planetTilts[11] = 0; - planetTilts[12] = -0.33; - planetTilts[13] = 0; - planetTilts[14] = 0; - planetTilts[15] = 0; - planetTilts[16] = 0; - planetTilts[17] = 0; - planetTilts[18] = 0; - planetTilts[19] = 23.5; - } - - planetTilts[19] = obliquity / RC; - - if (planetRotationPeriod == null) - { - planetRotationPeriod = new double[20]; - planetRotationPeriod[0] = 25.37995; - planetRotationPeriod[1] = 58.6462; - planetRotationPeriod[2] = -243.0187; - planetRotationPeriod[3] = 1.02595675; - planetRotationPeriod[4] = 0.41007; - planetRotationPeriod[5] = 0.426; - planetRotationPeriod[6] = -0.71833; - planetRotationPeriod[7] = 0.67125; - planetRotationPeriod[8] = -6.38718; - planetRotationPeriod[9] = 27.3; - planetRotationPeriod[10] = 1.769137786; - planetRotationPeriod[11] = 3.551; - planetRotationPeriod[12] = 7.155; - planetRotationPeriod[13] = 16.69; - planetRotationPeriod[14] = 0; - planetRotationPeriod[15] = 0; - planetRotationPeriod[16] = 0; - planetRotationPeriod[17] = 0; - planetRotationPeriod[18] = 0; - planetRotationPeriod[19] = .99726968; - } - - if (planetScales == null) - { - planetScales = new double[20]; - } - - - - if (planet3dLocations == null) - { - planet3dLocations = new Vector3d[20]; - } - - if (Settings.Active.ActualPlanetScale) - { - planetScales[0] = .5f; - planetScales[1] = .25f; - planetScales[2] = .25f; - planetScales[3] = .25f; - planetScales[4] = .25f; - planetScales[5] = .5f; - planetScales[6] = .25f; - planetScales[7] = .25f; - planetScales[8] = .25f; - planetScales[9] = .25f; - planetScales[10] = .25f; - planetScales[11] = .25f; - planetScales[12] = .25f; - planetScales[13] = .25f; - planetScales[14] = .25f; - planetScales[15] = .25f; - planetScales[16] = .25f; - planetScales[17] = .25f; - planetScales[18] = .5f; - planetScales[19] = .25f; - - } - else - { - for (int i = 0; i < 20; i++) - { - if (i < 10) - { - planetScales[i] = .25f; - } - else - { - planetScales[i] = .1f; - } - } - - // Make Sun and Saturn bigger - planetScales[0] = .5f; - planetScales[5] = .5f; - planetScales[18] = .5f; - - } - - - planetDrawOrder = new Dictionary(); - planetLocations = new AstroRaDec[20]; - - Vector3d center = new Vector3d(); - int planetCenter = 0; - if (planetCenter > -1) - { - AstroRaDec centerRaDec = AstroCalc.GetPlanet(jNow, (EO)planetCenter, threeDee ? 0 : SpaceTimeController.Location.Lat, threeDee ? 0 : SpaceTimeController.Location.Lng, threeDee ? -6378149 : SpaceTimeController.Altitude); - center = (Vector3d)Coordinates.RADecTo3dAu(centerRaDec.RA, centerRaDec.Dec, centerRaDec.Distance); - } - planet3dLocations[19] = Vector3d.Create(-center.X, -center.Y, -center.Z); - planet3dLocations[19].RotateX(obliquity); - for (int i = 0; i < 18; i++) - { - planetLocations[i] = AstroCalc.GetPlanet(jNow, (EO)i, threeDee ? 0 : SpaceTimeController.Location.Lat, threeDee ? 0 : SpaceTimeController.Location.Lng, threeDee ? -6378149 : SpaceTimeController.Altitude); - planet3dLocations[i] = (Vector3d)Coordinates.RADecTo3dAu(planetLocations[i].RA, planetLocations[i].Dec, planetLocations[i].Distance); - - //planet3dLocations[i] = new Vector3d(planet3dLocations[i].X - center.X, - // planet3dLocations[i].Y - center.Y, - // planet3dLocations[i].Z - center.Z); - planet3dLocations[i].Subtract(center); - - planet3dLocations[i].RotateX(obliquity); - - if (Settings.Active.ActualPlanetScale) - { - planetScales[i] = (2 * Math.Atan(.5 * (planetDiameters[i] / planetLocations[i].Distance))) / Math.PI * 180; - //if (i == 5 || i == 0) - //{ - // planetScales[i] *= 2; - //} - //if ((i > 9 && i != 18) && Properties.Settings.Default.ShowMoonsAsPointSource) // Jupiters moons should be bigger - //{ - // planetScales[i] *= 2; - //} - } - if (Settings.Active.SolarSystemScale != 1) - { - - SolarSystemObjects id = (SolarSystemObjects)i; - switch (id) - { - case SolarSystemObjects.Moon: - { - Vector3d parent = (planet3dLocations[(int)SolarSystemObjects.Earth]); - // Parent Centric - planet3dLocations[i].Subtract(parent); - planet3dLocations[i].Multiply(Settings.Active.SolarSystemScale / 2); - planet3dLocations[i].Add(parent); - } - break; - case SolarSystemObjects.Io: - case SolarSystemObjects.Europa: - case SolarSystemObjects.Ganymede: - case SolarSystemObjects.Callisto: - { - Vector3d parent = (planet3dLocations[(int)SolarSystemObjects.Jupiter]); - // Parent Centric - planet3dLocations[i].Subtract(parent); - planet3dLocations[i].Multiply(Settings.Active.SolarSystemScale); - planet3dLocations[i].Add(parent); - } - break; - - default: - break; - } - } - - double finalDistance = -planetLocations[i].Distance; - while (planetDrawOrder.ContainsKey(finalDistance)) - { - finalDistance += 0.0000000001; - } - planetDrawOrder[finalDistance] = i; - } - - - - - planetLocations[18] = planetLocations[0]; - planetScales[0] *= 2; - planetScales[18] = planetScales[0]; - planetScales[5] = planetScales[5]*2; - - lastUpdate = SpaceTimeController.Now; - - } - static Matrix3d eclipticTilt; - - static int lastPlanetCenterID = -2; - static int orbitalSampleRate = 256; - static double obliquity = 23.5 * RC; - // static Mutex OrbitsMutex = new Mutex(); - // static bool downloadedPlanets = false; - - public static void PlanetsReady() - { - - } - - public static void UpdateOrbits(int planetCenter) - { - try - { - //if (!downloadedPlanets) - //{ - // Wtml.GetWtmlFile("", PlanetsReady); - //} - - obliquity = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) * RC; - if (planetCenter != lastPlanetCenterID) - { - orbits = null; - } - lastPlanetCenterID = planetCenter; - if (orbits == null) - { - if (planetCenter < 0) - { - eclipticTilt = Matrix3d.Identity; - } - else - { - eclipticTilt = Matrix3d.Identity; - eclipticTilt = Matrix3d.RotationX((float)obliquity); - } - if (planetOrbitalYears == null) - { - planetOrbitalYears = new double[20]; - planetOrbitalYears[0] = 1; - planetOrbitalYears[1] = .241; - planetOrbitalYears[2] = .615; - planetOrbitalYears[3] = 1.881; - planetOrbitalYears[4] = 11.87; - planetOrbitalYears[5] = 29.45; - planetOrbitalYears[6] = 84.07; - planetOrbitalYears[7] = 164.9; - planetOrbitalYears[8] = 248.1; - planetOrbitalYears[9] = 27.3 / 365.25; - planetOrbitalYears[10] = 16.6890184 / 365.25; - planetOrbitalYears[11] = 3.551181 / 365.25; - planetOrbitalYears[12] = 7.15455296 / 365.25; - planetOrbitalYears[13] = 16.6890184 / 365.25; - planetOrbitalYears[19] = 1; - - } - if (!ReadOrbits()) - { - orbits = new Vector3d[20][]; - - for (int i = 1; i < 20; i++) - { - orbits[i] = new Vector3d[orbitalSampleRate]; - - if (i < 9 || i == 19) - { - for (int j = 0; j < orbitalSampleRate; j++) - { - int centerId = planetCenter; - double now = jNow + ((planetOrbitalYears[i] * 365.25 / (orbitalSampleRate)) * (double)(j - (orbitalSampleRate / 2))); - Vector3d center = new Vector3d(); - - if (i == (int)SolarSystemObjects.Moon) - { - centerId = -1; - } - else if (i > 9 && i < 14) - { - centerId = (int)SolarSystemObjects.Jupiter; - } - - if (centerId > -1) - { - AstroRaDec centerRaDec = AstroCalc.GetPlanet(now, (EO)centerId, 0, 0, -6378149); - center = Coordinates.RADecTo3dAu(centerRaDec.RA, centerRaDec.Dec, centerRaDec.Distance); - } - - - if (i != 19) - { - AstroRaDec planetRaDec = AstroCalc.GetPlanet(now, (EO)i, 0, 0, -6378149); - // todo move to double precition for less trucation - orbits[i][ j] = (Vector3d)Coordinates.RADecTo3dAu(planetRaDec.RA, planetRaDec.Dec, planetRaDec.Distance); - orbits[i][j].Subtract( (Vector3d)center); - } - else - { - orbits[i][j] = Vector3d.Create(-center.X, -center.Y, -center.Z); - } - - // todo is the tilt right? - //if (i != (int)SolarSystemObjects.Moon && !((i > 9 && i < 14))) - { - orbits[i][j].RotateX(obliquity); - } - } - orbits[i][ orbitalSampleRate - 1] = orbits[i][0]; - } - } - DumpOrbitsFile(); - } - } - } - finally - { -// OrbitsMutex.ReleaseMutex(); - } - } - - public static bool ReadOrbits() - { - // This function ought to fetch wwtweb/catalog.aspx?Q=orbitsbin and set `orbits`, see Windows client code. - return false; - } - - - public static void DumpOrbitsFile() - { - } - - public static bool DrawPlanets(RenderContext renderContext, float opacity) - { - - if (planetTextures == null) - { - LoadPlanetTextures(); - } - - - // Get Moon Phase - double elong = GeocentricElongation(planetLocations[9].RA, planetLocations[9].Dec, planetLocations[0].RA, planetLocations[0].Dec); - double raDif = planetLocations[9].RA - planetLocations[0].RA; - if (planetLocations[9].RA < planetLocations[0].RA) - { - raDif += 24; - } - double phaseAngle = PhaseAngle(elong, planetLocations[9].Distance, planetLocations[0].Distance); - double limbAngle = PositionAngle(planetLocations[9].RA, planetLocations[9].Dec, planetLocations[0].RA, planetLocations[0].Dec); - - if (raDif < 12) - { - phaseAngle += 180; - } - - // Check for solar eclipse - - double dista = (Math.Abs(planetLocations[9].RA - planetLocations[0].RA) * 15) * Math.Cos(Coordinates.DegreesToRadians(planetLocations[0].Dec)); - double distb = Math.Abs(planetLocations[9].Dec - planetLocations[0].Dec); - double sunMoonDist = Math.Sqrt(dista * dista + distb * distb); - - bool eclipse = false; - double coronaOpacity = 0; - - - //if (sunMoonDist < .014 && planetScales[9] > planetScales[0]) - - double moonEffect = (planetScales[9] / 2 - sunMoonDist); - - int darkLimb = Math.Min(32, (int)(sunMoonDist * 32)); - - if (moonEffect > (planetScales[0] / 4)) - { - - eclipse = true; - //coronaOpacity = Math.Min(1.0, Math.Abs((sunMoonDist-.014)/.007)); - coronaOpacity = Math.Min(1.0, (moonEffect - (planetScales[0] / 2)) / .001); - DrawPlanet(renderContext, 18, coronaOpacity); - - } - - // Earth3d.MainWindow.Text = phaseAngle.ToString() + ", " + raDif.ToString(); - -// for (int i = 0; i < planetDrawOrder.Count; i++) - - foreach( double key in planetDrawOrder.Keys) - { - int planetId = planetDrawOrder[key]; - - //if (planetId == 9) - //{ - // DrawPlanetPhase(canvas, planetId, phaseAngle, limbAngle, darkLimb); - //} - //else - { - DrawPlanet(renderContext, planetId, 1); - } - - } - - - return true; - } - - private static void LoadPlanetTextures() - { - string baseUrl = URLHelpers.singleton.engineAssetUrl(""); - - // Note: these PNG files are fairly large and are loaded at - // startup of the web client, adding nontrivially to the needed - // network traffic. JPGs are a lot smaller, but unfortunately the - // transparency support is important here since we don't want - // black boxes surrounding all of our planets when they're viewed - // in the sky. - - planetTextures = new Texture[20]; - planetTextures[0] = LoadPlanetTexture(baseUrl + @"sun.png"); - planetTextures[1] = LoadPlanetTexture(baseUrl + @"mercury.png"); - planetTextures[2] = LoadPlanetTexture(baseUrl + @"venus.png"); - planetTextures[3] = LoadPlanetTexture(baseUrl + @"mars.png"); - planetTextures[4] = LoadPlanetTexture(baseUrl + @"jupiter.png"); - planetTextures[5] = LoadPlanetTexture(baseUrl + @"saturn.png"); - planetTextures[6] = LoadPlanetTexture(baseUrl + @"uranus.png"); - planetTextures[7] = LoadPlanetTexture(baseUrl + @"neptune.png"); - planetTextures[8] = LoadPlanetTexture(baseUrl + @"pluto.png"); - planetTextures[9] = LoadPlanetTexture(baseUrl + @"moon.png"); - planetTextures[10] = LoadPlanetTexture(baseUrl + @"io.png"); - planetTextures[11] = LoadPlanetTexture(baseUrl + @"europa.png"); - planetTextures[12] = LoadPlanetTexture(baseUrl + @"ganymede.png"); - planetTextures[13] = LoadPlanetTexture(baseUrl + @"callisto.png"); - planetTextures[14] = LoadPlanetTexture(baseUrl + @"moonshadow.png"); //todo fix these to shadows - planetTextures[15] = LoadPlanetTexture(baseUrl + @"moonshadow.png"); - planetTextures[16] = LoadPlanetTexture(baseUrl + @"moonshadow.png"); - planetTextures[17] = LoadPlanetTexture(baseUrl + @"moonshadow.png"); - planetTextures[18] = LoadPlanetTexture(baseUrl + @"sunCorona.png"); - planetTextures[19] = LoadPlanetTexture(baseUrl + @"earth.png"); - } - - - static Dictionary drawOrder = new Dictionary(); - public static bool DrawPlanets3D(RenderContext renderContext, float opacity, Vector3d centerPoint) - { - - InitPlanetResources(renderContext); - - double distss = UiTools.SolarSystemToMeters(renderContext.SolarSystemCameraDistance); - - float moonFade = (float)Math.Min(1, Math.Max(Util.Log10(distss) - 7.3, 0)); - - - float fade = (float)Math.Min(1, Math.Max(Util.Log10(distss) - 8.6, 0)); - - if (Settings.Active.SolarSystemOrbits && fade > 0) - { - for (int ii = 1; ii < 10; ii++) - { - int id = ii; - - if (ii == 9) - { - id = 19; - } - - double angle = Math.Atan2(planet3dLocations[id].Z, planet3dLocations[id].X); - - DrawSingleOrbit(renderContext, planetColors[id], id, centerPoint, angle, planet3dLocations[id], fade); - } - - int mid = (int)SolarSystemObjects.Moon; - DrawSingleOrbit(renderContext, planetColors[mid], mid, centerPoint, 0.0, planet3dLocations[mid], fade); - } - - drawOrder.Clear(); - - Vector3d camera = renderContext.CameraPosition.Copy(); - for (int planetId = 0; planetId < 14; planetId++) - { - // If we're using realistic lighting and this is an eclipsed - // moon, don't draw it at all. This is slightly suboptimal - // since, if you're looking at the moon, you'll suddenly be able - // to see the stars through it. In principle we should do - // something like keep on drawing it, but as an all-black - // sphere. - if (!(Settings.Active.SolarSystemLighting && planetLocations[planetId].Eclipsed)) - { - Vector3d distVector = Vector3d.SubtractVectors(camera,Vector3d.SubtractVectors(planet3dLocations[planetId],centerPoint)); - - if (!drawOrder.ContainsKey(distVector.Length())) - { - drawOrder[distVector.Length()] = planetId; - } - } - } - - Vector3d distVectorEarth = Vector3d.SubtractVectors(camera, Vector3d.SubtractVectors(planet3dLocations[(int)SolarSystemObjects.Earth], centerPoint)); - if (!drawOrder.ContainsKey(distVectorEarth.Length())) - { - drawOrder[distVectorEarth.Length()] = (int)SolarSystemObjects.Earth; - } - - - - - //for (int planetId = 0; planetId < 14; planetId++) - //{ - // if (!planetLocations[planetId].Eclipsed) - // { - // DrawPlanet3d( renderContext, planetId, centerPoint); - // } - //} - // DrawPlanet3d(renderContext, (int)SolarSystemObjects.Earth, centerPoint); - - foreach (double key in drawOrder.Keys) - { - int planetId = drawOrder[key]; - DrawPlanet3d(renderContext, planetId, centerPoint); - } - - return true; - } - - - // Compute the rotation of a planet at the J2000 epoch. - // - // The rotation at some instant in can be computed by multiplying the - // the returned matrix by Y(W * t) - public static Matrix3d GetPlanetOrientationAtEpoch(int planetID) - { - Matrix3d m = Matrix3d.Identity; - - // Rotational elements for the planets are in the form used by the - // IAU Working Group on Cartographic Coordinates and Rotational Elements: - // - // a : Right ascension of north pole - // d : Declination of north pole - // W0 : Prime meridian angle at epoch J2000.0 - // - // The canonical Euler angle sequence is: Z(a - 90) * X(90 - d) * Z(W0) - // - // The following transformations are required to convert it to a rotation for WWT: - // * WWT uses a coordinate system with +Y = ecliptic north, +X = equinox of J2000 - // This system is rotated 90 degrees about the X axis from the standard ecliptic - // system based on the Earth Mean Equinox of J2000 (EMEJ2000) - // * WWT uses row vectors instead of column vectors, so the order of transformations - // is reversed - // * WWT has planet maps with longitude 0 at the edge rather than the middle. This - // requires an extra 180 degrees to be added to W0 - - const double obliquityOfEcliptic = 23.4392794; - - if (planetID == (int)SolarSystemObjects.Earth) - { - // Different calculation for Earth, since the meridian offset - // is already included in the Mean Sidereal Time function. - m.Multiply(Matrix3d.RotationX(obliquityOfEcliptic * RC)); // equatorial to ecliptic transformation - } - else - { - m.Multiply(Matrix3d.RotationX(-90 * RC)); // 90 degree rotation from WWT coord sys - - m.Multiply(Matrix3d.RotationZ((180 + planetAngles[planetID].primeMeridian) * RC)); - m.Multiply(Matrix3d.RotationX((90 - planetAngles[planetID].poleDec) * RC)); - m.Multiply(Matrix3d.RotationZ((planetAngles[planetID].poleRa - 90) * RC)); - m.Multiply(Matrix3d.RotationX(obliquityOfEcliptic * RC)); // equatorial to ecliptic transformation - - m.Multiply(Matrix3d.RotationX(90 * RC)); // 90 degree rotation back to WWT coord sys - } - - return m; - } - - public static void SetupPlanetMatrix(RenderContext renderContext, int planetID, Vector3d centerPoint, bool makeFrustum) - { - Matrix3d matNonRotating = renderContext.World.Clone(); - - SetupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, makeFrustum); - - if (planetID == (int)SolarSystemObjects.Sun) - { - // Don't apply the Sun's orientation to its non-rotating frame; this means that - // the Sun's reference frame will be the ecliptic frame. - double radius = GetAdjustedPlanetRadius(planetID); - matNonRotating.Scale(Vector3d.Create(radius, radius, radius)); - Vector3d translation = Vector3d.SubtractVectors(planet3dLocations[planetID], centerPoint); - matNonRotating.Multiply(Matrix3d.Translation(translation)); - renderContext.WorldBaseNonRotating = matNonRotating; - } - } - - public static Matrix3d EarthMatrix = new Matrix3d(); - public static Matrix3d EarthMatrixInv = new Matrix3d(); - - private static double SetupMatrixForPlanetGeometry(RenderContext renderContext, int planetID, Vector3d centerPoint, bool makeFrustum) - { - double radius = GetAdjustedPlanetRadius(planetID); - - - double rotationCurrent = 0; - if (planetID == (int)SolarSystemObjects.Earth) - { - rotationCurrent = Math.PI + Coordinates.MstFromUTC2(SpaceTimeController.Now, 0) / 180.0 * Math.PI; - } - else - { - rotationCurrent = Math.PI + (((jNow - 2451545.0) / planetRotationPeriod[planetID]) * Math.PI * 2) % (Math.PI * 2); - } - - if (planetID == (int)SolarSystemObjects.Moon) - { - rotationCurrent -= Math.PI / 2; - } - - Matrix3d matLocal = renderContext.World.Clone(); - Matrix3d matNonRotating = renderContext.World.Clone(); - Vector3d translation = Vector3d.SubtractVectors(planet3dLocations[planetID],centerPoint); - - Matrix3d orientationAtEpoch = GetPlanetOrientationAtEpoch(planetID); - - matLocal.Scale(Vector3d.Create(radius, radius, radius)); - matLocal.Multiply(Matrix3d.RotationY(-rotationCurrent)); - matLocal.Multiply(orientationAtEpoch); - - - if (planetID == (int)renderContext.ViewCamera.Target) - { - EarthMatrix = Matrix3d.Identity; - EarthMatrix.Multiply(Matrix3d.RotationY(-rotationCurrent)); - EarthMatrix.Multiply(orientationAtEpoch); - - EarthMatrixInv = EarthMatrix.Clone(); - EarthMatrixInv.Invert(); - } - - matLocal.Multiply(Matrix3d.Translation(translation)); - renderContext.World = matLocal; - renderContext.WorldBase = renderContext.World.Clone(); - renderContext.NominalRadius = GetPlanetRadiusInMeters(planetID); - - - if (makeFrustum) - { - renderContext.MakeFrustum(); - } - matNonRotating.Scale(Vector3d.Create(radius, radius, radius)); - matNonRotating.Multiply(orientationAtEpoch); - matNonRotating.Multiply(Matrix3d.Translation(translation)); - renderContext.WorldBaseNonRotating = matNonRotating; - return rotationCurrent; - } - - public static void InitPlanetResources(RenderContext renderContext) - { -// OrbitsMutex.WaitOne(); -// try -// { -// if (planetTexturesMaps == null) -// { -// LoadPlanetTextureMaps(device); -// } -// if (sphereIndexBuffers == null) -// { -// InitSphere(device); -// } - -// if (ringsVertexBuffer == null) -// { -// InitRings(device); -// } -// } -// finally -// { -// OrbitsMutex.ReleaseMutex(); -// } - } - - private static void DrawSingleOrbit(RenderContext renderContext, Color eclipticColor, int id, Vector3d centerPoint, double startAngle, Vector3d planetNow, float opacity) - { - if (opacity < .01) - { - return; - } - - if (renderContext.gl == null) - { - int count = orbitalSampleRate; - bool planetDropped = false; - - Vector3d viewPoint = renderContext.ViewPoint; - - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - - ctx.StrokeStyle = eclipticColor.ToString(); - ctx.LineWidth = 2; - ctx.Alpha = 1; - Vector3d point = new Vector3d(); - Vector3d pointTest = new Vector3d(); - - Vector3d lastPoint = new Vector3d(); - bool firstPoint = true; - Matrix3d translate = Matrix3d.Translation(Vector3d.Negate(centerPoint)); - Matrix3d mat = Matrix3d.MultiplyMatrix(translate, renderContext.WVP); - Matrix3d matWV = Matrix3d.MultiplyMatrix(translate, renderContext.WV); - - for (int i = 0; i < count; i++) - { - Vector3d pnt = orbits[id][i]; - - - double angle = (Math.Atan2(orbits[id][i].Z, orbits[id][i].X) + Math.PI * 2 - startAngle) % (Math.PI * 2); - int alpha = (int)((angle) / (Math.PI * 2) * 255); - - double alphaD = (double)alpha / 255.0; - - if (alpha < 2 && !planetDropped) - { - pnt = planetNow; - alphaD = 1.0; - - } - - pointTest = matWV.Transform(pnt); - point = mat.Transform(pnt); - - if (pointTest.Z > 0) - { - - - if (firstPoint) - { - - firstPoint = false; - } - else - { - // if (Vector3d.Dot(pnt, viewPoint) > .60) - { - ctx.BeginPath(); - ctx.Alpha = alphaD * opacity; - ctx.MoveTo(lastPoint.X, lastPoint.Y); - ctx.LineTo(point.X, point.Y); - ctx.Stroke(); - } - } - } - - lastPoint = point; - } - - - ctx.Restore(); - } - else - { - if (id != (int)SolarSystemObjects.Moon) - { - int count = orbitalSampleRate; - bool planetDropped = false; - - Vector3d viewPoint = renderContext.ViewPoint; - Vector3d point = new Vector3d(); - Vector3d pointTest = new Vector3d(); - - Vector3d lastPoint = new Vector3d(); - Color lastColor = new Color(); - bool firstPoint = true; - OrbitLineList list = new OrbitLineList(); - - for (int i = 0; i < count; i++) - { - Vector3d pnt = orbits[id][i].Copy(); - - double angle = (Math.Atan2(pnt.Z, pnt.X) + Math.PI * 2 - startAngle) % (Math.PI * 2); - int alpha = (int)((angle) / (Math.PI * 2) * 255); - - double alphaD = (double)alpha / 255.0; - Color color = Color.FromArgb(alpha, eclipticColor.R, eclipticColor.G, eclipticColor.B); - - if (alpha < 2 && !planetDropped && !firstPoint) - { - pnt = Vector3d.SubtractVectors(planetNow, centerPoint); - alphaD = 1.0; - alpha = 255; - - color.A = 255; - lastColor.A = 255; - list.AddLine(lastPoint, pnt.Copy(), lastColor.Clone(), color.Clone()); - lastColor.A = 0; - color.A = 0; - pnt = orbits[id][i].Copy(); - planetDropped = true; - } - - pnt = Vector3d.SubtractVectors(pnt, centerPoint); - - - if (firstPoint) - { - - firstPoint = false; - } - else - { - list.AddLine(lastPoint, pnt, lastColor, color); - } - lastPoint = pnt; - lastColor = color.Clone(); - } - list.DrawLines(renderContext, 1.0f, Colors.White); - list.Clear(); - } - else - { - double mu = 0.0; - switch (id) - { - case (int)SolarSystemObjects.Moon: - mu = muEarth + muMoon; - break; - - case (int)SolarSystemObjects.Io: - case (int)SolarSystemObjects.Europa: - case (int)SolarSystemObjects.Ganymede: - case (int)SolarSystemObjects.Callisto: - mu = muJupiter; - break; - - default: - mu = muSun; - break; - } - - // Estimate velocity through differences - double deltaT = 1.0 / 1440.0 * 0.1; - Vector3d r0 = GetPlanetPositionDirect((SolarSystemObjects)id, jNow); - Vector3d r1 = GetPlanetPositionDirect((SolarSystemObjects)id, jNow - deltaT); - - Vector3d v = Vector3d.Scale(Vector3d.SubtractVectors(r0, r1), 1.0 / deltaT); - - KeplerianElements elements = stateVectorToKeplerian(r0, v, mu); - - DrawSingleOrbitElements(renderContext, eclipticColor, id, centerPoint, startAngle, planetNow, elements); - } - } - } - - // mu is the standard gravitational parameter GM, where G - // is the gravitational constant and M is the mass of the - // central body. - const double muSun = 1.327124400188e11; // km^3/s^2 - const double muEarth = 3.9860044189e5; - const double muMoon = 4.9027779e3; - const double muJupiter = 1.26686534e8; - - - // Get the position of a Solar System object using a 'direct' calculation that - // avoids including an aberration correction. - // - // The returned position is in ecliptic coordinate system with the origin at the center - // of the parent body (i.e. the Sun for planets, a planet for moons). The position of moons - // is _not_ modified by the SolarSystemScale, making it possible to use function to - // a calculate valid Keplerian elements. - public static Vector3d GetPlanetPositionDirect(SolarSystemObjects id, double jd) - { - double L = 0.0; - double B = 0.0; - double R = 0.0; - - switch (id) - { - case SolarSystemObjects.Mercury: - L = CAAMercury.EclipticLongitude(jd); - B = CAAMercury.EclipticLatitude(jd); - R = CAAMercury.RadiusVector(jd); - break; - case SolarSystemObjects.Venus: - L = CAAVenus.EclipticLongitude(jd); - B = CAAVenus.EclipticLatitude(jd); - R = CAAVenus.RadiusVector(jd); - break; - case SolarSystemObjects.Earth: - { - //double x = HiResTimer.TickCount; - L = CAAEarth.EclipticLongitude(jd); - B = CAAEarth.EclipticLatitude(jd); - R = CAAEarth.RadiusVector(jd); - //x = (HiResTimer.TickCount - x) / HiResTimer.Frequency; - //System.Console.WriteLine("Earth orbit time: " + x * 1000.0 + "ms"); - } - break; - case SolarSystemObjects.Mars: - L = CAAMars.EclipticLongitude(jd); - B = CAAMars.EclipticLatitude(jd); - R = CAAMars.RadiusVector(jd); - break; - case SolarSystemObjects.Jupiter: - L = CAAJupiter.EclipticLongitude(jd); - B = CAAJupiter.EclipticLatitude(jd); - R = CAAJupiter.RadiusVector(jd); - break; - case SolarSystemObjects.Saturn: - L = CAASaturn.EclipticLongitude(jd); - B = CAASaturn.EclipticLatitude(jd); - R = CAASaturn.RadiusVector(jd); - break; - case SolarSystemObjects.Uranus: - L = CAAUranus.EclipticLongitude(jd); - B = CAAUranus.EclipticLatitude(jd); - R = CAAUranus.RadiusVector(jd); - break; - case SolarSystemObjects.Neptune: - L = CAANeptune.EclipticLongitude(jd); - B = CAANeptune.EclipticLatitude(jd); - R = CAANeptune.RadiusVector(jd); - break; - case SolarSystemObjects.Pluto: - L = CAAPluto.EclipticLongitude(jd); - B = CAAPluto.EclipticLatitude(jd); - R = CAAPluto.RadiusVector(jd); - break; - case SolarSystemObjects.Moon: - L = CAAMoon.EclipticLongitude(jd); - B = CAAMoon.EclipticLatitude(jd); - R = CAAMoon.RadiusVector(jd) / 149598000; - break; - case SolarSystemObjects.Io: - { - GMDS galileanInfo = GM.Calculate(jd); - C3D position = galileanInfo.Satellite1.EclipticRectangularCoordinates; - return Vector3d.Create(position.X, position.Z, position.Y); - } - case SolarSystemObjects.Europa: - { - GMDS galileanInfo = GM.Calculate(jd); - C3D position = galileanInfo.Satellite2.EclipticRectangularCoordinates; - return Vector3d.Create(position.X, position.Z, position.Y); - } - case SolarSystemObjects.Ganymede: - { - GMDS galileanInfo = GM.Calculate(jd); - C3D position = galileanInfo.Satellite3.EclipticRectangularCoordinates; - return Vector3d.Create(position.X, position.Z, position.Y); - } - case SolarSystemObjects.Callisto: - { - GMDS galileanInfo = GM.Calculate(jd); - C3D position = galileanInfo.Satellite4.EclipticRectangularCoordinates; - return Vector3d.Create(position.X, position.Z, position.Y); - } - } - // Enabling this code transforms planet positions from the mean ecliptic/equinox of - // date to the J2000 ecliptic. It is necessary because the VSOP87D series used - // for planet positions is in the mean-of-date frame. The transformation is currently - // disabled in order to better match planet positions calculated elsewhere in the code. - //CAA2DCoordinate prec = CAAPrecession.PrecessEcliptic(L, B, jd, 2451545.0); - //L = prec.X; - //B = prec.Y; - - L = Coordinates.DegreesToRadians(L); - B = Coordinates.DegreesToRadians(B); - Vector3d eclPos = Vector3d.Create(Math.Cos(L) * Math.Cos(B)* R, Math.Sin(L) * Math.Cos(B)* R, Math.Sin(B)* R) ; - - // Transform from the ecliptic of date to the J2000 ecliptic; this transformation should be deleted - // once the precession is turned one. - double eclipticOfDateRotation = (Coordinates.MeanObliquityOfEcliptic(jd) - Coordinates.MeanObliquityOfEcliptic(2451545.0)) * RC; - eclPos.RotateX(eclipticOfDateRotation); - - return Vector3d.Create(eclPos.X, eclPos.Z, eclPos.Y); - } - - private static KeplerianElements stateVectorToKeplerian(Vector3d position, Vector3d velocity, double mu) - { - // Work in units of km and seconds - Vector3d r = Vector3d.Scale(position, UiTools.KilometersPerAu); - Vector3d v = Vector3d.Scale(Vector3d.Scale(velocity, 1.0 / 86400.0), UiTools.KilometersPerAu); - - double rmag = r.Length(); - double vmag = v.Length(); - - double sma = 1.0 / (2.0 / rmag - vmag * vmag / mu); - - // h is the orbital angular momentum vector - Vector3d h = Vector3d.Cross(r, v); - - // ecc is the eccentricity vector, which points from the - // planet at periapsis to the center point. - Vector3d ecc = Vector3d.SubtractVectors(Vector3d.Scale(Vector3d.Cross(v, h), 1.0 / mu), Vector3d.Scale( r, 1.0 / rmag)); - double e = ecc.Length(); - - h.Normalize(); - ecc.Normalize(); - - // h, s, and ecc are orthogonal vectors that define a coordinate - // system. h is normal to the orbital plane. - Vector3d s = Vector3d.Cross(h, ecc); - - // Calculate the sine and cosine of the true anomaly - r.Normalize(); - double cosNu = Vector3d.Dot(ecc, r); - double sinNu = Vector3d.Dot(s, r); - - // Compute the eccentric anomaly - double E = Math.Atan2(Math.Sqrt(1 - e * e) * sinNu, e + cosNu); - - // Mean anomaly not required - // double M = E - e * Math.Sin(E); - - KeplerianElements elements = new KeplerianElements(); - - // Create a rotation matrix given the three orthogonal vectors: - // ecc - eccentricity vector - // s - in the orbital plane, perpendicular to ecc - // h - angular momentum vector, normal to orbital plane - elements.orientation = Matrix3d.Create(ecc.X, ecc.Y, ecc.Z, 0.0, - s.X, s.Y, s.Z, 0.0, - h.X, h.Y, h.Z, 0.0, - 0.0, 0.0, 0.0, 1.0); - elements.a = sma; - elements.e = e; - elements.ea = E; - - return elements; - } - - private static void DrawSingleOrbitElements(RenderContext renderContext, Color eclipticColor, int id, Vector3d centerPoint, double xstartAngle, Vector3d planetNow, KeplerianElements el) - { - double scaleFactor; - switch (id) - { - case (int)SolarSystemObjects.Moon: - if (Settings.Active.SolarSystemScale > 1) - scaleFactor = Settings.Active.SolarSystemScale / 2; - else - scaleFactor = 1.0; - break; - - case (int)SolarSystemObjects.Io: - case (int)SolarSystemObjects.Europa: - case (int)SolarSystemObjects.Ganymede: - case (int)SolarSystemObjects.Callisto: - scaleFactor = Settings.Active.SolarSystemScale; - break; - - default: - scaleFactor = 1.0; - break; - } - - Vector3d translation = Vector3d.Negate(centerPoint); - if (id == (int)SolarSystemObjects.Moon) - { - translation.Add(planet3dLocations[(int)SolarSystemObjects.Earth]); - } - else if (id == (int)SolarSystemObjects.Io || id == (int)SolarSystemObjects.Europa || id == (int)SolarSystemObjects.Ganymede || id == (int)SolarSystemObjects.Callisto) - { - translation.Add(planet3dLocations[(int)SolarSystemObjects.Jupiter]); - } - - Vector3d currentPosition = Vector3d.SubtractVectors(planetNow, centerPoint); - //if (orbitTraces[id] != null) - //{ - // Matrix3d worldMatrix = Matrix3d.Translation(translation) * renderContext.World; - // orbitTraces[id].render(renderContext, Color.FromArgb(eclipticColor), worldMatrix, jNow, currentPosition, 0.0); - //} - //else - { - Matrix3d worldMatrix = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(el.orientation, Matrix3d.Translation(translation)), renderContext.World); - EllipseRenderer.DrawEllipseWithPosition(renderContext, el.a / UiTools.KilometersPerAu * scaleFactor, el.e, el.ea, eclipticColor, worldMatrix, currentPosition); - } - - } - - static Date lastUpdate = new Date(); - const double EarthDiameter = 0.000137224; -// //private static void DrawPlanet2pnt5d(Device device, int planetID) -// //{ - -// // Vector3 planetPosition = planet3dLocations[planetID]; - -// // if (planetID < 9 ) -// // { -// // device.SetTexture(0, planetTextures[planetID]); -// // } -// // else if (planetID == 9 ) -// // { -// // device.SetTexture(0, planetTextures[19]); - -// // } -// // else -// // { -// // return; -// // } - -// // double diameter = planetDiameters[planetID]; - -// // float radius = (double)(diameter / 2.0 ); -// // if (!Settings.Active.ActualPlanetScale) -// // { -// // if (planetID != 0) -// // { -// // radius *= 1000; -// // } -// // else -// // { -// // radius *= 100; -// // } -// // } - -// // CustomVertex.PositionTextured[] points = new CustomVertex.PositionTextured[4]; - -// // Vector3 pos = planet3dLocations[planetID]; -// // points[0].Position = new Vector3(pos.X + radius, pos.Y, pos.Z + radius); - -// // points[0].Tu = 0; -// // points[0].Tv = 0; - -// // points[1].Position = new Vector3(pos.X - radius, pos.Y, pos.Z + radius); -// // points[1].Tu = 1; -// // points[1].Tv = 0; - -// // points[2].Position = new Vector3(pos.X + radius, pos.Y, pos.Z - radius); -// // points[2].Tu = 0; -// // points[2].Tv = 1; - -// // points[3].Position = new Vector3(pos.X - radius, pos.Y, pos.Z - radius); -// // points[3].Tu = 1; -// // points[3].Tv = 1; - - -// // //Matrix mat = Microsoft.DirectX.Matrix.RotationZ(rotationAngle); - -// // device.DrawUserPrimitives(PrimitiveType.TriangleStrip, points.Length - 2, points); -// // // Render Stuff Here - - -// //} public static bool Lighting = true; -// //private static void DrawPlanet3d(Device device, int planetID, Vector3d centerPoint) -// //{ - -// // if (planetID == (int)SolarSystemObjects.Sun) -// // { -// // device.RenderState.Lighting = false; -// // } -// // else -// // { -// // device.RenderState.Lighting = Lighting; -// // } - - -// // double radius = GetAdjustedPlanetRadius(planetID); -// // double rotationCurrent = 0; -// // if (planetID == (int)SolarSystemObjects.Earth) -// // { -// // rotationCurrent = Coordinates.MstFromUTC2(SpaceTimeController.Now, 0)/180.0 * Math.PI; -// // } -// // else -// // { -// // rotationCurrent = (((jNow - 2451545.0) / planetRotationPeriod[planetID]) * Math.PI * 2) % (Math.PI * 2); -// // } -// // Matrix matOld = device.Transform.World; - -// // matOld = device.Transform.World; -// // Matrix matLocal = device.Transform.World; -// // Vector3d translation = planet3dLocations[planetID]-centerPoint; - -// // matLocal.Scale((double)radius, (double)radius, (double)radius); -// // matLocal.Multiply(Matrix.RotationY((double)-rotationCurrent)); -// // matLocal.Multiply(Matrix.RotationX((double)(planetTilts[planetID]*RC))); -// // matLocal.Multiply(Matrix.Translation(translation.Vector3)); -// // device.Transform.World = matLocal; -// // Earth3d.MainWindow.MakeFrustum(); -// // DrawSphere(device, planetTexturesMaps[planetID], GetNameFrom3dId(planetID)); -// // if (planetID == 5) -// // { -// // device.RenderState.CullMode = Cull.None; -// // Color oldAmbient = device.RenderState.Ambient; -// // device.RenderState.Ambient = Color.FromArgb(40, 40, 40); -// // DrawRings(device); -// // device.RenderState.Ambient = oldAmbient; -// // device.RenderState.CullMode = Cull.Clockwise; - -// // } -// // device.Transform.World = matOld; -// // Earth3d.MainWindow.MakeFrustum(); -// // device.RenderState.Lighting = false; -// //} -// public static bool Lighting = true; - public static bool IsPlanetInFrustum(RenderContext renderContext, float rad) - { - PlaneD[] frustum = renderContext.Frustum; - Vector3d center = Vector3d.Create(0, 0, 0); - Vector4d centerV4 = new Vector4d(0, 0, 0, 1f); - for (int i = 0; i < 6; i++) - { - if (frustum[i].Dot(centerV4) + rad < 0) - { - return false; - } - } - return true; - } -// private static Matrix bias = Matrix.Scaling(new Vector3(.5f, .5f, .5f)) * Matrix.Translation(new Vector3(.5f, .5f, .5f)); - private static void DrawPlanet3d(RenderContext renderContext, int planetID, Vector3d centerPoint) - { - - if (planetID == (int)SolarSystemObjects.Sun) - { - TileShader.MinLightingBrightness = 1.0f; - // device.RenderState.Lighting = false; - } - else - { - TileShader.MinLightingBrightness = 0.025f; - - if (planetID == (int)SolarSystemObjects.Earth) - { - TileShader.AtmosphereColor = Color.FromArgb(255, 65, 157, 217); - } - else - { - TileShader.AtmosphereColor = Color.FromArgb(0, 0, 0, 0); - } - // device.RenderState.Lighting = Settings.Active.SolarSystemLighting; - } - - Matrix3d matOld = renderContext.World; - Matrix3d matOldBase = renderContext.WorldBase; - Matrix3d matOldNonRotating = renderContext.WorldBaseNonRotating; - - double radius = GetAdjustedPlanetRadius(planetID); - - SetupPlanetMatrix(renderContext, planetID, centerPoint, true); - - //double rotationCurrent = 0; - //if (planetID == (int)SolarSystemObjects.Earth) - //{ - // rotationCurrent = Math.PI + Coordinates.MstFromUTC2(SpaceTimeController.Now, 0) / 180.0 * Math.PI; - //} - //else - //{ - // rotationCurrent = (((jNow - 2451545.0) / planetRotationPeriod[planetID]) * Math.PI * 2) % (Math.PI * 2); - //} - - ////Matrix3d matOldWV = renderContext.WV.Clone(); - - - //Matrix3d matLocal = renderContext.World.Clone(); - //Matrix3d matLocalNR = renderContext.World.Clone(); - //Vector3d translation = Vector3d.SubtractVectors(planet3dLocations[planetID], centerPoint); - - //matLocal.Scale(Vector3d.Create(radius, radius, radius)); - //matLocal.Multiply(Matrix3d.RotationY((double)-rotationCurrent)); - //matLocal.Multiply(Matrix3d.RotationX((double)(planetTilts[planetID] * RC))); - //matLocal.Multiply(Matrix3d.Translation(translation)); - - - //matLocalNR.Scale(Vector3d.Create(radius, radius, radius)); - //matLocalNR.Multiply(Matrix3d.RotationX((double)(planetTilts[planetID] * RC))); - //matLocalNR.Multiply(Matrix3d.Translation(translation)); - - //renderContext.World = matLocal; - //renderContext.WorldBase = matLocal.Clone(); - //renderContext.WorldBaseNonRotating = matLocalNR; - //renderContext.MakeFrustum(); - - float planetWidth = 1; - - if (planetID == (int)SolarSystemObjects.Saturn) - { - planetWidth = 3; - } - - if (IsPlanetInFrustum(renderContext,planetWidth)) - { - // Save all matrices modified by SetupMatrix... - Matrix3d matOld2 = renderContext.World; - Matrix3d matOldBase2 = renderContext.WorldBase; - Matrix3d matOldNonRotating2 = renderContext.WorldBaseNonRotating; - - - Vector3d sun = planet3dLocations[0].Copy(); - Vector3d planet = planet3dLocations[planetID].Copy(); - - sun = matOld.Transform(sun); - planet = matOld.Transform(planet); - - renderContext.World = matOld; - renderContext.WorldBase = matOldBase; - renderContext.WorldBaseNonRotating = matOldNonRotating; - - SetupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, true); - - Vector3d sunPosition = Vector3d.SubtractVectors(sun, planet); - sunPosition.Normalize(); - - renderContext.SunPosition = sunPosition; - TileShader.SunPosition = Vector3d.SubtractVectors(planet3dLocations[0], planet); - Vector3d loc = Vector3d.SubtractVectors(planet3dLocations[planetID], centerPoint); - loc.Subtract(renderContext.CameraPosition); - double dist = loc.Length(); - double sizeIndexParam = (2 * Math.Atan(.5 * (radius / dist))) / Math.PI * 180; - - - - int sizeIndex = 0; - if (sizeIndexParam > 10.5) - { - sizeIndex = 0; - } - else if (sizeIndexParam > 3.9) - { - sizeIndex = 1; - } - else if (sizeIndexParam > .72) - { - sizeIndex = 2; - } - else if (sizeIndexParam > 0.05) - { - sizeIndex = 3; - } - else - { - sizeIndex = 4; - } - - - //ShadowStuff - if (planetID == (int)SolarSystemObjects.Earth && sizeIndex < 2) - { - float width = Settings.Active.SolarSystemScale * .00001f; - //todo add shadows centerPoint = SetupShadow(device, centerPoint, width, SolarSystemObjects.Moon); - } - //ShadowStuff end - - if (sizeIndex < 4) - { - bool oldLighting = renderContext.Lighting; - //double planetDistance = Vector3d.SubtractVectors(planet3dLocations[planetID], renderContext.CameraPosition).Length(); - if (planetID == 5) - { - if (renderContext.gl == null) - { - renderContext.Lighting = false; - // DRAW BACK HALF OF RINGS - DrawSaturnsRings(renderContext, false, dist); - renderContext.Lighting = oldLighting; - //if (Settings.Active.SolarSystemLighting) - //{ - // SetupRingShadow(device, centerPoint, SolarSystemObjects.Saturn, rotationCurrent); - //} - // todo saturns rings DrawRings(device); - } - - } - - if (planetID == 0) - { - renderContext.Lighting = false; - } - - DrawSphere(renderContext, planetID); - - if (planetID == 5) - { - if (renderContext.gl == null) - { - renderContext.Lighting = false; - DrawSaturnsRings(renderContext, true, dist); - // DRAW FRONT HALF OF RINGS - //if (Settings.Active.SolarSystemLighting) - //{ - // SetupRingShadow(device, centerPoint, SolarSystemObjects.Saturn, rotationCurrent); - //} - // todo saturns rings DrawRings(device); - } - else - { - renderContext.Lighting = false; - - DrawRings(renderContext); - renderContext.Lighting = oldLighting; - } - } - - renderContext.Lighting = oldLighting; - - } - else - { - if (planetID == 0) - { - DrawPointPlanet(renderContext, new Vector3d(), (double)(10 * planetDiameters[planetID]), planetColors[planetID], true); - } - else if (planetID < (int)SolarSystemObjects.Moon || planetID == (int)SolarSystemObjects.Earth) - { - double size = (800 * planetDiameters[planetID]); - DrawPointPlanet(renderContext, new Vector3d(), (double)Math.Max(.05, Math.Min(.1f, size)), planetColors[planetID], true); - } - else if (sizeIndexParam > .002) - { - double size = (800 * planetDiameters[planetID]); - DrawPointPlanet(renderContext, new Vector3d(), (double)Math.Max(.05, Math.Min(.1f, size)), planetColors[planetID], true); - } - } - } - - LayerManager.Draw(renderContext, 1.0f, false, GetNameFrom3dId(planetID), true, false); - renderContext.World = matOld; - renderContext.WorldBase = matOldBase; - renderContext.WorldBaseNonRotating = matOldNonRotating; - } - - internal static List[] RingsTriangleLists = new List[2]; - internal static ImageElement ringImage = null; - public static void DrawSaturnsRings(RenderContext renderContext, bool front, double distance) - { - if (RingsTriangleLists[0] == null) - { - ringImage = (ImageElement)Document.CreateElement("img"); - CrossDomainImage xdomimg = (CrossDomainImage)(object)ringImage; - - //texture.AddEventListener("load", delegate(ElementEvent e) - //{ - // texReady = true; - // Downloading = false; - // errored = false; - // ReadyToRender = texReady && (DemReady || !demTile); - // RequestPending = false; - // TileCache.RemoveFromQueue(this.Key, true); - // MakeTexture(); - //}, false); - - //texture.AddEventListener("error", delegate(ElementEvent e) - //{ - // Downloading = false; - // ReadyToRender = false; - // errored = true; - // RequestPending = false; - // TileCache.RemoveFromQueue(this.Key, true); - //}, false); - - xdomimg.crossOrigin = "anonymous"; - ringImage.Src = URLHelpers.singleton.engineAssetUrl("saturnringsshadow.png"); - - RingsTriangleLists[0] = new List(); - RingsTriangleLists[1] = new List(); - - double ringSize = 2.25; - - Vector3d TopLeft = Vector3d.Create(-ringSize, 0, -ringSize); - Vector3d TopRight = Vector3d.Create(ringSize, 0, -ringSize); - Vector3d BottomLeft = Vector3d.Create(-ringSize, 0, ringSize); - Vector3d BottomRight = Vector3d.Create(ringSize, 0, ringSize); - Vector3d center = Vector3d.Create(0, 0, 0); - Vector3d leftCenter = Vector3d.Create(-ringSize, 0, 0); - Vector3d topCenter = Vector3d.Create(0, 0, -ringSize); - Vector3d bottomCenter = Vector3d.Create(0, 0, ringSize); - Vector3d rightCenter = Vector3d.Create(ringSize, 0, 0); - - int level = 6; - //RingsTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(TopLeft, 0, 0, 1024, 1024), PositionTexture.CreatePosSize(leftCenter, 0, .5, 1024, 1024), PositionTexture.CreatePosSize(topCenter, .5, 0, 1024, 1024), ringImage, level)); - //RingsTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(leftCenter, 0, 0.5, 1024, 1024), PositionTexture.CreatePosSize(center, .5, .5, 1024, 1024), PositionTexture.CreatePosSize(topCenter, .5, 0, 1024, 1024), ringImage, level)); - //RingsTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(topCenter, .5, 0, 1024, 1024), PositionTexture.CreatePosSize(rightCenter, 1, .5, 1024, 1024), PositionTexture.CreatePosSize(TopRight, 1, 0, 1024, 1024), ringImage, level)); - //RingsTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(topCenter, .5, 0, 1024, 1024), PositionTexture.CreatePosSize(center, .5, .5, 1024, 1024), PositionTexture.CreatePosSize(rightCenter, 1, .5, 1024, 1024), ringImage, level)); - //RingsTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(leftCenter, 0, .5, 1024, 1024), PositionTexture.CreatePosSize(bottomCenter, .5, 1, 1024, 1024), PositionTexture.CreatePosSize(center, .5, .5, 1024, 1024), ringImage, level)); - //RingsTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(leftCenter, 0, .5, 1024, 1024), PositionTexture.CreatePosSize(BottomLeft, 0, 1, 1024, 1024), PositionTexture.CreatePosSize(bottomCenter, .5, 1, 1024, 1024), ringImage, level)); - //RingsTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(center, .5, .5, 1024, 1024), PositionTexture.CreatePosSize(BottomRight, 1, 1, 1024, 1024), PositionTexture.CreatePosSize(rightCenter, 1, .5, 1024, 1024), ringImage, level)); - //RingsTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePosSize(center, .5, .5, 1024, 1024), PositionTexture.CreatePosSize(bottomCenter, .5, 1, 1024, 1024), PositionTexture.CreatePosSize(BottomRight, 1, 1, 1024, 1024), ringImage, level)); - - List vertexList; - vertexList = new List(); - - int Width = 1024; - int Height = 1024; - - vertexList.Add(PositionTexture.CreatePosSize(TopLeft, 0, 0, Width, Height)); - vertexList.Add(PositionTexture.CreatePosSize(TopRight, 1, 0, Width, Height)); - vertexList.Add(PositionTexture.CreatePosSize(BottomLeft, 0, 1, Width, Height)); - vertexList.Add(PositionTexture.CreatePosSize(BottomRight, 1, 1, Width, Height)); - - List childTriangleList = new List(); - - //if (dataset.BottomsUp) - //{ - // childTriangleList.Add(Triangle.Create(0, 1, 2)); - // childTriangleList.Add(Triangle.Create(2, 1, 3)); - //} - //else - { - childTriangleList.Add(Triangle.Create(0, 2, 1)); - childTriangleList.Add(Triangle.Create(2, 3, 1)); - - } - - int count = 5; - while (count-- > 1) - { - List newList = new List(); - foreach (Triangle tri in childTriangleList) - { - tri.SubDivideNoNormalize(newList, vertexList); - } - childTriangleList = newList; - } - - double miter = .6 / (Width / 256); - foreach (Triangle tri in childTriangleList) - { - PositionTexture p1 = vertexList[tri.A]; - PositionTexture p2 = vertexList[tri.B]; - PositionTexture p3 = vertexList[tri.C]; - - - RingsTriangleLists[0].Add(RenderTriangle.CreateWithMiter(p1, p2, p3, ringImage, level, miter)); - } - - } - - if (renderContext.gl == null) - { - Vector3d cam = renderContext.CameraPosition; - Vector3d test = new Vector3d(); - - //Matrix3d wv = renderContext.WV; - - Matrix3d worldLocal = Matrix3d.MultiplyMatrix(Matrix3d.RotationY(Math.Atan2(renderContext.SunPosition.X, renderContext.SunPosition.Z)), renderContext.WorldBaseNonRotating); - - Matrix3d wv = Matrix3d.MultiplyMatrix(worldLocal, renderContext.View); - Matrix3d wvp = Matrix3d.MultiplyMatrix(wv, renderContext.Projection); - double Width = renderContext.Width; - double Height = renderContext.Height; - - wvp.Scale(Vector3d.Create(Width / 2, -Height / 2, 1)); - wvp.Translate(Vector3d.Create(Width / 2, Height / 2, 0)); - double td = 0; - // RenderTriangle.CullInside = !RenderTriangle.CullInside; - for (int i = 0; i < 2; i++) - { - foreach (RenderTriangle tri in RingsTriangleLists[0]) - { - //test = Vector3d.SubtractVectors(wv.Transform(tri.A.Position), cam); - test = wv.Transform(tri.A.Position); - td = test.Length(); - - bool draw = td > distance; - - if (front) - { - draw = !draw; - } - - if (draw) - { - tri.Opacity = 1; - - tri.Draw(renderContext.Device, wvp); - } - } - RenderTriangle.CullInside = !RenderTriangle.CullInside; - } - } - else - { - //todo port rings to web gl - //renderContext.gl.enableVertexAttribArray(renderContext.vertLoc); - //renderContext.gl.enableVertexAttribArray(renderContext.textureLoc); - //renderContext.gl.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - //renderContext.gl.vertexAttribPointer(renderContext.vertLoc, 3, GL.FLOAT, false, 20, 0); - ////renderContext.gl.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - //renderContext.gl.vertexAttribPointer(renderContext.textureLoc, 2, GL.FLOAT, false, 20, 12); - //renderContext.gl.activeTexture(GL.TEXTURE0); - //renderContext.gl.bindTexture(GL.TEXTURE_2D, texture2d); - - ////if (tileX == TileTargetX && tileY == TileTargetY && Level == TileTargetLevel) - ////{ - //// renderContext.gl.bindTexture(GL.TEXTURE_2D, null); - ////} - - //renderContext.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, GetIndexBuffer(part, accomidation)); - //renderContext.gl.drawElements(GL.TRIANGLES, TriangleCount * 3, GL.UNSIGNED_SHORT, 0); - } - } - const int subDivisionsRings = 192; - - static int triangleCountRings = subDivisionsRings +1 * 2; - static PositionTextureVertexBuffer ringsVertexBuffer = null; - static Texture ringsTexture; - - // Various input layouts used in 3D solar system mode - // TODO Replace with an input layout cache - - static void DrawRings(RenderContext renderContext) - { - InitRings(); - - TileShader.Use(renderContext, ringsVertexBuffer.VertexBuffer, null, ringsTexture.Texture2d, 1.0f, false, Vector3d.Zero); - renderContext.gl.drawArrays(GL.TRIANGLE_STRIP, 0, triangleCountRings); - } - - - - static void InitRings() - { - if (ringsVertexBuffer != null) - { - return; - } - ringsTexture = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("saturnringsstrip.png")); - double inner = 1.113; - double outer = 2.25; - - ringsVertexBuffer = new PositionTextureVertexBuffer(((subDivisionsRings + 1) * 2)); - - triangleCountRings = (subDivisionsRings+1) * 2; - PositionTexture[] verts = (PositionTexture[])ringsVertexBuffer.Lock(); // Lock the buffer (which will return our structs) - - double radStep = Math.PI * 2.0 / (double)subDivisionsRings; - int index = 0; - for (int x = 0; x <= subDivisionsRings; x += 2) - { - double rads1 = x * radStep; - double rads2 = (x + 1) * radStep; - verts[index] = new PositionTexture(); - verts[index].Position = Vector3d.Create((Math.Cos(rads1) * inner), 0, (Math.Sin(rads1) * inner)); - verts[index].Tu = 1; - verts[index].Tv = 0; - index++; - verts[index] = new PositionTexture(); - verts[index].Position = Vector3d.Create((Math.Cos(rads1) * outer), 0, (Math.Sin(rads1) * outer)); - verts[index].Tu = 0; - verts[index].Tv = 0; - index++; - verts[index] = new PositionTexture(); - verts[index].Position = Vector3d.Create((Math.Cos(rads2) * inner), 0, (Math.Sin(rads2) * inner)); - verts[index].Tu = 1; - verts[index].Tv = 1; - index++; - verts[index] = new PositionTexture(); - verts[index].Position = Vector3d.Create((Math.Cos(rads2) * outer), 0, (Math.Sin(rads2) * outer)); - verts[index].Tu = 0; - verts[index].Tv = 1; - index++; - - } - ringsVertexBuffer.Unlock(); - } - - - public static void DrawPointPlanet(RenderContext renderContext, Vector3d location, double size, Color color, bool zOrder) - { - //size = Math.Max(2, size); - - Vector3d center = (Vector3d)location; - - double rad = size / 2; - - - if (renderContext.gl != null) - { - PointList ppList = new PointList(renderContext); - ppList.MinSize = 20; - ppList.AddPoint(location.Copy(), color.Clone(), new Dates(0, 1), (float)size/100); - // ppList.ShowFarSide = true; - ppList.DepthBuffered = true; - ppList.Draw(renderContext, 1, false); - // ppList.Clear(); - - } - else - { - Vector3d screenSpacePnt = renderContext.WVP.Transform(center); - if (screenSpacePnt.Z < 0) - { - return; - } - if (!zOrder) - { - if (Vector3d.Dot((Vector3d)renderContext.ViewPoint, (Vector3d)center) < .55) - { - return; - } - } - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - //ctx.Alpha = opacity; - ctx.BeginPath(); - ctx.Arc(screenSpacePnt.X, screenSpacePnt.Y, rad, 0, Math.PI * 2, true); - ctx.LineWidth = 1; - ctx.FillStyle = color.ToString(); - if (true) - { - ctx.Fill(); - } - ctx.Alpha = 1.0; - ctx.StrokeStyle = color.ToString(); - ctx.Stroke(); - - ctx.Restore(); - } - //device.RenderState.Lighting = false; - //StarVertex[] vert = new StarVertex[1]; - //vert[0] = new StarVertex(location.Vector3, size, color.ToArgb()); - //device.RenderState.PointSpriteEnable = true; - //device.RenderState.PointScaleEnable = true; - //device.RenderState.PointScaleA = 100; - //device.RenderState.PointScaleB = 0; - //device.RenderState.PointScaleC = 0; - //device.RenderState.ZBufferEnable = zOrder; - //device.SetTexture(0, Grids.StarProfile); - ////device.SetTexture(0, null); - - //device.VertexFormat = VertexFormats.Position | VertexFormats.PointSize | VertexFormats.Diffuse; - - //// device.RenderState.CullMode = Cull.None; - //device.RenderState.AlphaBlendEnable = true; - //device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; - //device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - - //device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - //device.TextureState[0].ColorOperation = TextureOperation.Modulate; - //device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; - //device.TextureState[0].AlphaOperation = TextureOperation.Modulate; - //device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; - //device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; - - //device.TextureState[1].ColorOperation = TextureOperation.Modulate; - //device.TextureState[1].ColorArgument1 = TextureArgument.Current; - //device.TextureState[1].ColorArgument2 = TextureArgument.Constant; - //device.TextureState[1].AlphaOperation = TextureOperation.Modulate; - //device.TextureState[1].AlphaArgument1 = TextureArgument.Current; - //device.TextureState[1].AlphaArgument2 = TextureArgument.Constant; - - //device.TextureState[1].ConstantColor = Color.FromArgb(255, 255, 255, 255); - - //device.DrawUserPrimitives(PrimitiveType.PointList, 1, vert); - - //device.RenderState.PointSpriteEnable = false; - //device.RenderState.PointScaleEnable = false; - } - -// private static Vector3d SetupShadow(Device device, Vector3d centerPoint, float width, SolarSystemObjects shadowCaster) -// { -// if (PlanetShadow == null) -// { -// PlanetShadow = LoadPlanetTexture(device, Properties.Resources.planetShadow); -// } - -// // device.SetTexture(2, PlanetShadow); -// device.SetTexture(2, PlanetShadow); -// device.SamplerState[2].AddressU = TextureAddress.Clamp; -// device.SamplerState[2].AddressV = TextureAddress.Clamp; -// device.TextureState[2].ColorOperation = TextureOperation.Modulate; -// device.TextureState[2].ColorArgument1 = TextureArgument.TextureColor; -// device.TextureState[2].ColorArgument2 = TextureArgument.Current; -// device.TextureState[2].AlphaOperation = TextureOperation.Disable; -// device.TextureState[2].AlphaArgument1 = TextureArgument.Current; -// device.TextureState[2].AlphaArgument2 = TextureArgument.Current; -// device.TextureState[2].TextureTransform = TextureTransform.Count3 | TextureTransform.Projected; -// device.TextureState[2].TextureCoordinateIndex = (int)TextureCoordinateIndex.CameraSpacePosition; -// Matrix invViewCam = device.Transform.View; -// invViewCam.Invert(); - -// Vector3d sun = planet3dLocations[0]; -// sun.Subtract(centerPoint); - -// Vector3d moon = planet3dLocations[(int)shadowCaster]; -// moon.Subtract(centerPoint); -// Matrix mat = -// invViewCam * -// Matrix.LookAtLH(sun.Vector3, moon.Vector3, new Vector3(0, 1, 0)) * -// Matrix.PerspectiveFovLH(width, 1, .001f, 200f) * -// bias; - -// device.Transform.Texture2 = mat; -// return centerPoint; -// } -// private static Texture ringShadow; -// private static Vector3d SetupRingShadow(Device device, Vector3d centerPoint, SolarSystemObjects shadowCaster, double rotation) -// { -// if (ringShadow == null) -// { -// ringShadow = LoadPlanetTexture(device, Properties.Resources.ringShadow); -// } - -// // device.SetTexture(2, PlanetShadow); -// device.SetTexture(2, ringShadow); -// device.SamplerState[2].AddressU = TextureAddress.Wrap; -// device.SamplerState[2].AddressV = TextureAddress.Wrap; -// device.TextureState[2].ColorOperation = TextureOperation.Modulate; -// device.TextureState[2].ColorArgument1 = TextureArgument.TextureColor; -// device.TextureState[2].ColorArgument2 = TextureArgument.Current; -// device.TextureState[2].AlphaOperation = TextureOperation.Disable; -// device.TextureState[2].AlphaArgument1 = TextureArgument.Current; -// device.TextureState[2].AlphaArgument2 = TextureArgument.Current; -// device.TextureState[2].TextureTransform = TextureTransform.Count3 | TextureTransform.Projected; -// device.TextureState[2].TextureCoordinateIndex = (int)TextureCoordinateIndex.CameraSpacePosition; -// Matrix invViewCam = device.Transform.World * device.Transform.View; -// invViewCam.Invert(); - -// Vector3d sun = planet3dLocations[0]; -// sun.Subtract(centerPoint); - -// Vector3d moon = planet3dLocations[(int)shadowCaster]; -// moon.Subtract(centerPoint); - -// Vector3d sunMoonAngle = moon - sun; -// Vector2d latLng = sunMoonAngle.ToSpherical(); -// Matrix mat = -// invViewCam * -// Matrix.LookAtLH(new Vector3(0, -5, 0), new Vector3(0, 0, 0), new Vector3(1, 0, 0)) * -// Matrix.PerspectiveFovLH(.95f, 1, .00f, 200f) * -// Matrix.RotationZ((double)(-rotation + latLng.X)) * -// bias; - -// device.Transform.Texture2 = mat; -// return centerPoint; -// } - public static double GetAdjustedPlanetRadius(int planetID) - { - if (planetID > planetDiameters.Length - 1) - { - planetID = (int)SolarSystemObjects.Earth; - } - - - double diameter = planetDiameters[planetID]; - - - double radius = (double)(diameter / 2.0); - if (planetID != 0) - { - radius = radius * (1 + (3 * (Settings.Active.SolarSystemScale - 1))); - } - else - { - radius = radius * (1 + (.30 * (Settings.Active.SolarSystemScale - 1))); - } - - return radius; - } - - public static double GetPlanetRadiusInMeters(int planetID) - { - if (planetID > planetDiameters.Length - 1) - { - planetID = (int)SolarSystemObjects.Earth; - } - - - double diameter = planetDiameters[planetID]; - - - return (diameter / 2.0) * UiTools.KilometersPerAu * 1000; - - } - - static AstroRaDec[] planetLocations; - - static Sprite2d planetSprite = new Sprite2d(); - - static PositionColoredTextured[] planetPoints = null; - private static void DrawPlanet(RenderContext renderContext, int planetID, double opacity) - { - - AstroRaDec planetPosition = planetLocations[planetID]; - - if (((planetID < 14) && planetScales[planetID] < ( renderContext.ViewCamera.Zoom / 6.0) / 400) ) - { - if (planetID < 10 || ((planetID < 14) && planetScales[planetID] > (renderContext.ViewCamera.Zoom / 6.0) / 6400)) - { - Vector3d point = (Vector3d)Coordinates.RADecTo3d(planetPosition.RA, planetPosition.Dec); - DrawPointPlanet(renderContext, point, 3, planetColors[planetID], false); - } - return; - } - //else - //{ - // if ((planetID < 10 ) || (planetID < 14 && !planetPosition.Eclipsed) || (planetID > 13 && planetPosition.Shadow) ) - // { - // Vector3d point = (Vector3d)Coordinates.RADecTo3d(planetPosition.RA, planetPosition.Dec); - // DrawPointPlanet(canvas, point, planetScales[planetID] / (Viewer.MasterView.FovScale / 3600), planetColors[planetID], false, perspectiveViewMatrix, perspectiveProjectionMatrix); - // } - //} - - Texture brush = null; - - if (planetID < 10 || planetID == 18) - { - brush = planetTextures[planetID]; - } - else if (planetID < 14) - { - if (planetLocations[planetID].Eclipsed) - { - brush = planetTextures[15]; - - } - else - { - if (Settings.Active.ShowMoonsAsPointSource) - { - brush = planetTextures[14]; - } - else - { - brush = planetTextures[planetID]; - } - } - } - else - { - if (!planetLocations[planetID].Shadow) - { - return; - } - //Shadows of moons - brush = planetTextures[15]; - } - - - - - // Special Case for Saturn and Eclipse - //if (planetID == 18 || planetID == 5) - //{ - // double Width = rad*2; - // double Height = rad*2; - // var points = new PointCollection { new Point(screenSpacePnt.X - Width / 2, screenSpacePnt.Y - Height / 2), new Point(screenSpacePnt.X + Width / 2, screenSpacePnt.Y - Height / 2), new Point(screenSpacePnt.X + Width / 2, screenSpacePnt.Y + Height / 2), new Point(screenSpacePnt.X - Width / 2, screenSpacePnt.Y + Height / 2) }; - // //var bitmapImage = new BitmapImage(this.sourceUri); - // //var imageBrush = new ImageBrush { ImageSource = bitmapImage, RelativeTransform = this.imageTransform }; - - - // Polygon polygon = new Polygon { Points = points }; - - // polygon.Opacity = opacity; - // if (rad < 8) - // { - // SolidColorBrush fillBrush = new SolidColorBrush(planetColors[planetID]); - // polygon.Fill = fillBrush; - // } - // else - // { - // polygon.Fill = brush; - // } - - // //RotateTransform rt = new RotateTransform(); - // //rt.CenterX = screenSpacePnt.X; - // //rt.CenterY = screenSpacePnt.Y; - // //rt.Angle = this.RotationAngle; - // //polygon.RenderTransform = rt; - // canvas.Children.Add(polygon); - //} - //else - { - if (renderContext.gl != null) - { - //todo draw in WebGL - if (planetPoints == null) - { - planetPoints = new PositionColoredTextured[4]; - for (int i = 0; i < 4; i++) - { - planetPoints[i] = new PositionColoredTextured(); - } - } - float radius = (float)(planetScales[planetID] / 2.0); - float raRadius = (float)(radius / Math.Cos(planetPosition.Dec / 180.0 * Math.PI)); - - - planetPoints[0].Position = Coordinates.RADecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.Dec + radius, 1); - planetPoints[0].Tu = 0; - planetPoints[0].Tv = 1; - planetPoints[0].Color = Colors.White; - - planetPoints[1].Position = Coordinates.RADecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.Dec - radius, 1); - planetPoints[1].Tu = 0; - planetPoints[1].Tv = 0; - planetPoints[1].Color = Colors.White; - - - planetPoints[2].Position = Coordinates.RADecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.Dec + radius, 1); - planetPoints[2].Tu = 1; - planetPoints[2].Tv = 1; - planetPoints[2].Color = Colors.White; - - planetPoints[3].Position = Coordinates.RADecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.Dec - radius, 1); - - planetPoints[3].Tu = 1; - planetPoints[3].Tv = 0; - planetPoints[3].Color = Colors.White; - - planetSprite.Draw(renderContext, planetPoints, 4, brush, true, 1); - } - else - { - - Vector3d center = Coordinates.RADecTo3d(planetPosition.RA, planetPosition.Dec); - - double rad = planetScales[planetID] / (renderContext.FovScale / 3600) / 2; - - Vector3d screenSpacePnt = renderContext.WVP.Transform(center); - if (screenSpacePnt.Z < 0) - { - return; - } - - if (Vector3d.Dot((Vector3d)renderContext.ViewPoint, (Vector3d)center) < .55) - { - return; - } - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Alpha = opacity; - ctx.BeginPath(); - ctx.Arc(screenSpacePnt.X, screenSpacePnt.Y, rad, 0, Math.PI * 2, true); - ctx.LineWidth = 0; - - ctx.ClosePath(); - ctx.Clip(); - ctx.DrawImage(brush.ImageElement, screenSpacePnt.X - rad, screenSpacePnt.Y - rad, rad * 2, rad * 2); - - ctx.Alpha = 1.0; - ctx.Restore(); - - - - //Ellipse ellipse = new Ellipse(); - //ellipse.Width = rad * 2; - //ellipse.Height = ellipse.Width; - //ellipse.StrokeThickness = 0; - //ellipse.Stroke = null; - //ellipse.Opacity = opacity; - - //if (rad < 8) - //{ - // SolidColorBrush fillBrush = new SolidColorBrush(planetColors[planetID]); - // ellipse.Fill = fillBrush; - //} - //else - //{ - // ellipse.Fill = brush; - //} - //TranslateTransform tt = new TranslateTransform(); - //tt.X = screenSpacePnt.X - rad; - //tt.Y = screenSpacePnt.Y - rad; - //ellipse.RenderTransform = tt; - //canvas.Children.Add(ellipse); - } - } - } - private static void DrawPlanetPhase(RenderContext renderContext, int planetID, double phase, double angle, int dark) - { - } - - // //AstroRaDec planetPosition = planetLocations[planetID]; - -// //if (planetID < 10) -// //{ -// // device.SetTexture(0, planetTextures[planetID]); -// //} -// //else if (planetID < 14) -// //{ -// // if (planetLocations[planetID].Eclipsed) -// // { -// // device.SetTexture(0, planetTextures[15]); - -// // } -// // else -// // { -// // if (Properties.Settings.Default.ShowMoonsAsPointSource) -// // { -// // device.SetTexture(0, planetTextures[14]); - -// // } -// // else -// // { -// // device.SetTexture(0, planetTextures[planetID]); -// // } -// // } -// //} -// //else -// //{ -// // if (!planetLocations[planetID].Shadow) -// // { -// // return; -// // } -// // //Shadows of moons -// // device.SetTexture(0, planetTextures[15]); -// //} - - -// //float radius = (double)(planetScales[planetID] / 2.0); -// //float raRadius = (double)(radius / Math.Cos(planetPosition.Dec / 180.0 * Math.PI)); -// //int segments = 128; -// //CustomVertex.PositionColoredTextured[] points = new CustomVertex.PositionColoredTextured[4 * (segments + 1)]; - -// //int index = 0; - -// ////double top = planetPosition.Dec + radius; -// ////double bottom = planetPosition.Dec - radius; -// ////double left = (planetPosition.RA + (raRadius / 15)) - 12; -// ////double right = (planetPosition.RA - (raRadius / 15)) - 12; -// //double top = radius; -// //double bottom = -radius; -// //double left = +(radius / 15); -// //double right = -(radius / 15); - -// //double width = left - right; -// //double height = bottom - top; - -// //Color rightColor = Color.FromArgb(dark * 4, dark * 4, dark * 4); -// //Color leftColor = Color.FromArgb(dark, dark, dark); - -// //double phaseFactor = Math.Sin(Coordinates.DegreesToRadians(phase + 90)); -// //if (phase < 180) -// //{ -// // rightColor = leftColor; -// // leftColor = Color.FromArgb(dark * 4, dark * 4, dark * 4); -// // // phaseFactor = -phaseFactor; -// //} - -// //double rotation = -Math.Cos(planetPosition.RA / 12 * Math.PI) * 23.5; - -// //Matrix matrix = Microsoft.DirectX.Matrix.Identity; -// //matrix.Multiply(Microsoft.DirectX.Matrix.RotationX((double)(((rotation)) / 180f * Math.PI))); -// //matrix.Multiply(Microsoft.DirectX.Matrix.RotationZ((double)((planetPosition.Dec) / 180f * Math.PI))); -// //matrix.Multiply(Microsoft.DirectX.Matrix.RotationY((double)(((360 - (planetPosition.RA * 15)) + 180) / 180f * Math.PI))); - -// //double step = 1.0 / segments; -// //for (int i = 0; i <= segments; i++) -// //{ - -// // double y = i * (1.0 / segments); -// // double yf = (y - .5) * 2; -// // double x = Math.Sqrt(1 - ((yf) * (yf))); -// // double xt; -// // x = x * phaseFactor; -// // x = ((width / 2) + (x * width / 2)) - width / 80; -// // if (x > width) -// // { -// // x = width; -// // } -// // if (x < 0) -// // { -// // x = 0; -// // } -// // xt = x / width; -// // double x1 = Math.Sqrt(1 - ((yf) * (yf))); -// // double x1t; -// // x1 = x1 * phaseFactor; -// // x1 = ((width / 2) + (x1 * width / 2)) + width / 80; -// // if (x1 > width) -// // { -// // x1 = width; -// // } -// // if (x1 < 0) -// // { -// // x1 = 0; -// // } -// // x1t = x1 / width; - -// // points[index].Position = Coordinates.RADecTo3d(left, top + y * height, matrix); -// // points[index].Tu = 0; -// // points[index].Tv = (double)y; -// // points[index].Color = leftColor.ToArgb(); -// // points[index + 1].Position = Coordinates.RADecTo3d(left - x, top + y * height, matrix); -// // points[index + 1].Tu = (double)xt; -// // points[index + 1].Tv = (double)y; -// // points[index + 1].Color = leftColor.ToArgb(); -// // points[index + 2].Position = Coordinates.RADecTo3d(left - x1, top + y * height, matrix); -// // points[index + 2].Tu = (double)x1t; -// // points[index + 2].Tv = (double)y; -// // points[index + 2].Color = rightColor.ToArgb(); -// // points[index + 3].Position = Coordinates.RADecTo3d(right, top + y * height, matrix); -// // points[index + 3].Tu = 1; -// // points[index + 3].Tv = (double)y; -// // points[index + 3].Color = rightColor.ToArgb(); - -// // index += 4; -// // //points -// //} - -// //CustomVertex.PositionColoredTextured[] triangles = new CustomVertex.PositionColoredTextured[18 * (segments)]; -// //index = 0; -// //for (int yy = 0; yy < segments; yy++) -// //{ -// // for (int xx = 0; xx < 3; xx++) -// // { -// // triangles[index] = points[yy * 4 + xx]; -// // triangles[index + 1] = points[yy * 4 + (xx + 1)]; -// // triangles[index + 2] = points[((yy + 1) * 4) + (xx)]; -// // triangles[index + 3] = points[yy * 4 + (xx + 1)]; -// // triangles[index + 4] = points[((yy + 1) * 4) + (xx + 1)]; -// // triangles[index + 5] = points[((yy + 1) * 4) + (xx)]; -// // index += 6; -// // } - -// //} -// ////Matrix mat = Microsoft.DirectX.Matrix.RotationZ(rotationAngle); - -// //device.DrawUserPrimitives(PrimitiveType.TriangleList, triangles.Length / 3, triangles); -// //// Render Stuff Here -// } - - static double GeocentricElongation(double ObjectAlpha, double ObjectDelta, double SunAlpha, double SunDelta) - { - //Convert the RA's to radians - ObjectAlpha = Coordinates.DegreesToRadians(ObjectAlpha * 15); - SunAlpha = Coordinates.DegreesToRadians(SunAlpha * 15); - - //Convert the declinations to radians - ObjectDelta = Coordinates.DegreesToRadians(ObjectDelta); - SunDelta = Coordinates.DegreesToRadians(SunDelta); - - //Return the result - return Coordinates.RadiansToDegrees(Math.Acos(Math.Sin(SunDelta) * Math.Sin(ObjectDelta) + Math.Cos(SunDelta) * Math.Cos(ObjectDelta) * Math.Cos(SunAlpha - ObjectAlpha))); - } - - static double PhaseAngle(double GeocentricElongation, double EarthObjectDistance, double EarthSunDistance) - { - //Convert from degrees to radians - GeocentricElongation = Coordinates.DegreesToRadians(GeocentricElongation); - - //Return the result - return Coordinates.MapTo0To360Range(Coordinates.RadiansToDegrees(Math.Atan2(EarthSunDistance * Math.Sin(GeocentricElongation), EarthObjectDistance - EarthSunDistance * Math.Cos(GeocentricElongation)))); - } - static double PositionAngle(double Alpha0, double Delta0, double Alpha, double Delta) - { - //Convert to radians - Alpha0 = Coordinates.HoursToRadians(Alpha0); - Alpha = Coordinates.HoursToRadians(Alpha); - Delta0 = Coordinates.DegreesToRadians(Delta0); - Delta = Coordinates.DegreesToRadians(Delta); - - return Coordinates.MapTo0To360Range(Coordinates.RadiansToDegrees(Math.Atan2(Math.Cos(Delta0) * Math.Sin(Alpha0 - Alpha), Math.Sin(Delta0) * Math.Cos(Delta) - Math.Cos(Delta0) * Math.Sin(Delta) * Math.Cos(Alpha0 - Alpha)))); - } -// static BitmapImage PlanetShadow; - static void DrawSphere(RenderContext renderContext, int planetID) - { - string planetName = GetImageSetNameNameFrom3dId(planetID); - Imageset planet = WWTControl.Singleton.GetImagesetByName(planetName); - - if (planet == null) - { - planet = WWTControl.Singleton.GetImagesetByName("Bing Maps Aerial"); - } - - if (planet != null) - { - renderContext.DrawImageSet(planet, 100); - if (planetID == (int)SolarSystemObjects.Earth) - { - // todo clouds Earth3d.MainWindow.DrawCloudsNoCheck(); - } - return; - - } - } - -// static int[] triangleCountSphere = null; -// static int[] vertexCountSphere = null; -// static int triangleCountRings = subDivisionsRings * 2; -// static int maxSubDivisionsX = 96; -// static int maxSubDivisionsY = 48; -// const int subDivisionsRings = 192; -// const int sphereCount = 4; -// static void InitSphere(Canvas canvas) -// { -// //if (sphereIndexBuffers != null) -// //{ -// // foreach (IndexBuffer indexBuf in sphereIndexBuffers) -// // { -// // indexBuf.Dispose(); -// // } -// //} -// //if (sphereVertexBuffers != null) -// //{ -// // foreach (VertexBuffer vertBuf in sphereVertexBuffers) -// // { -// // vertBuf.Dispose(); -// // } -// //} -// //sphereVertexBuffers = new VertexBuffer[sphereCount]; -// //sphereIndexBuffers = new IndexBuffer[sphereCount]; - -// //triangleCountSphere = new int[sphereCount]; -// //vertexCountSphere = new int[sphereCount]; - -// //int countX = maxSubDivisionsX; -// //int countY = maxSubDivisionsY; - - -// //for (int sphereIndex = 0; sphereIndex < sphereCount; sphereIndex++) -// //{ -// // triangleCountSphere[sphereIndex] = countX * countY * 2; -// // vertexCountSphere[sphereIndex] = (countX + 1) * (countY + 1); -// // sphereVertexBuffers[sphereIndex] = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), ((countX + 1) * (countY + 1)), device, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Tile.PoolToUse); - -// // sphereIndexBuffers[sphereIndex] = new IndexBuffer(typeof(short), countX * countY * 6, device, Usage.WriteOnly, Tile.PoolToUse); - -// // double lat, lng; - -// // int index = 0; -// // double latMin = 90; -// // double latMax = -90; -// // double lngMin = -180; -// // double lngMax = 180; - - -// // // Create a vertex buffer -// // CustomVertex.PositionNormalTextured[] verts = (CustomVertex.PositionNormalTextured[])sphereVertexBuffers[sphereIndex].Lock(0, 0); // Lock the buffer (which will return our structs) -// // int x1, y1; - -// // double latDegrees = latMax - latMin; -// // double lngDegrees = lngMax - lngMin; - -// // double textureStepX = 1.0f / countX; -// // double textureStepY = 1.0f / countY; -// // for (y1 = 0; y1 <= countY; y1++) -// // { - -// // if (y1 != countY) -// // { -// // lat = latMax - (textureStepY * latDegrees * (double)y1); -// // } -// // else -// // { -// // lat = latMin; -// // } - -// // for (x1 = 0; x1 <= countX; x1++) -// // { -// // if (x1 != countX) -// // { -// // lng = lngMin + (textureStepX * lngDegrees * (double)x1); -// // } -// // else -// // { -// // lng = lngMax; -// // } -// // index = y1 * (countX + 1) + x1; -// // verts[index].Position = Coordinates.GeoTo3d(lat, lng);// Add Altitude mapping here -// // verts[index].Normal = verts[index].Position;// with altitude will come normal recomputer from adjacent triangles -// // verts[index].Tu = (double)(x1 * textureStepX); -// // verts[index].Tv = (double)(1f - (y1 * textureStepY)); -// // } -// // } -// // sphereVertexBuffers[sphereIndex].Unlock(); -// // short[] indexArray = (short[])sphereIndexBuffers[sphereIndex].Lock(0, LockFlags.None); - -// // for (y1 = 0; y1 < countY; y1++) -// // { -// // for (x1 = 0; x1 < countX; x1++) -// // { -// // index = (y1 * countX * 6) + 6 * x1; -// // // First triangle in quad -// // indexArray[index] = (short)(y1 * (countX + 1) + x1); -// // indexArray[index + 2] = (short)((y1 + 1) * (countX + 1) + x1); -// // indexArray[index + 1] = (short)(y1 * (countX + 1) + (x1 + 1)); - -// // // Second triangle in quad -// // indexArray[index + 3] = (short)(y1 * (countX + 1) + (x1 + 1)); -// // indexArray[index + 5] = (short)((y1 + 1) * (countX + 1) + x1); -// // indexArray[index + 4] = (short)((y1 + 1) * (countX + 1) + (x1 + 1)); -// // } -// // } -// // sphereIndexBuffers[sphereIndex].Unlock(); -// // countX /= 2; -// // countY /= 2; -// //} -// } - -// static BitmapImage ringsMap; -// static void DrawRings(Canvas canvas) -// { -// if (ringsMap == null) -// { -// ringsMap = LoadPlanetTexture(device, Properties.Resources.SaturnRings); -// } -// device.RenderState.AlphaBlendEnable = true; -// device.RenderState.SourceBlend = Microsoft.DirectX.Direct3D.Blend.SourceAlpha; -// device.RenderState.DestinationBlend = Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha; - - -// device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; - -// device.RenderState.ColorWriteEnable = ColorWriteEnable.RedGreenBlueAlpha; -// device.TextureState[0].ColorOperation = TextureOperation.Modulate; -// device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; -// device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; -// device.TextureState[0].AlphaOperation = TextureOperation.Modulate; -// device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; -// device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; - -// // test -// device.TextureState[0].ColorArgument0 = TextureArgument.Diffuse; - -// // -// device.TextureState[1].ColorOperation = TextureOperation.SelectArg1; -// device.TextureState[1].ColorArgument1 = TextureArgument.Current; -// device.TextureState[1].ColorArgument2 = TextureArgument.Constant; -// device.TextureState[1].AlphaOperation = TextureOperation.Modulate; -// device.TextureState[1].AlphaArgument1 = TextureArgument.Current; -// device.TextureState[1].AlphaArgument2 = TextureArgument.Constant; -// device.TextureState[1].ConstantColorValue = (int)Color.FromArgb((int)(255), (int)(255), (int)(255), (int)(255)).ToArgb(); - -// device.SetTexture(0, ringsMap); -// device.SetStreamSource(0, ringsVertexBuffer, 0); -// device.VertexFormat = CustomVertex.PositionNormalTextured.Format; -// //.TextureState[2].TextureCoordinateIndex = TextureCoordinateIndex.CameraSpacePosition; -// device.Indices = null; -// device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, triangleCountRings); - - } - - - -// static void InitRings() -// { -// //if (ringsVertexBuffer != null) -// //{ -// // ringsVertexBuffer.Dispose(); -// // ringsVertexBuffer = null; -// //} -// //double inner = 1.113; -// //double outer = 2.25; - -// //ringsVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), ((subDivisionsRings + 1) * 4), device, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Tile.PoolToUse); - -// //triangleCountRings = (subDivisionsRings) * 2; -// //CustomVertex.PositionNormalTextured[] verts = (CustomVertex.PositionNormalTextured[])ringsVertexBuffer.Lock(0, 0); // Lock the buffer (which will return our structs) - -// //double radStep = Math.PI * 2.0 / (double)subDivisionsRings; -// //int index = 0; -// //for (int x = 0; x <= subDivisionsRings; x += 2) -// //{ -// // double rads1 = x * radStep; -// // double rads2 = (x + 1) * radStep; - -// // verts[index].Position = new Vector3((double)(Math.Cos(rads1) * inner), 0, (double)(Math.Sin(rads1) * inner)); -// // verts[index].Normal = new Vector3(0, 1, 0); -// // verts[index].Tu = 1; -// // verts[index].Tv = 0; -// // index++; - -// // verts[index].Position = new Vector3((double)(Math.Cos(rads1) * outer), 0, (double)(Math.Sin(rads1) * outer)); -// // verts[index].Normal = new Vector3(0, 1, 0); -// // verts[index].Tu = 0; -// // verts[index].Tv = 0; -// // index++; -// // verts[index].Position = new Vector3((double)(Math.Cos(rads2) * inner), 0, (double)(Math.Sin(rads2) * inner)); -// // verts[index].Normal = new Vector3(0, 1, 0); -// // verts[index].Tu = 1; -// // verts[index].Tv = 1; -// // index++; -// // verts[index].Position = new Vector3((double)(Math.Cos(rads2) * outer), 0, (double)(Math.Sin(rads2) * outer)); -// // verts[index].Normal = new Vector3(0, 1, 0); -// // verts[index].Tu = 0; -// // verts[index].Tv = 1; -// // index++; - -// //} -// //ringsVertexBuffer.Unlock(); -// } -// } -// //public class SolarSystemObject -// //{ -// // public SolarSystemObject(string name, SolarSystemObject parent, double diameter, double orbitalYears, -// // double tilt, double rotation, bool moon, bool has3d, Image disk, Image map) -// // { -// // this.name = name; -// // this.parent = parent; -// // this.diameter = diameter; -// // this.orbitalYears = orbitalYears; -// // this.tilt = tilt; -// // this.rotation = rotation; -// // this.moon = moon; -// // this.has3d = has3d; -// // this.disk = disk; -// // this.map = map; -// // } - -// // Image disk; -// // Image map; -// // Texture diskTexture; -// // Texture mapTexture; -// // Vector3 location3d; -// // int indexID = 0; -// // double tilt = 0; -// // double diameter = 0; -// // double distance; -// // double ra; - -// // public double Ra -// // { -// // get { return ra; } -// // set { ra = value; } -// // } -// // double dec; - -// // public double Dec -// // { -// // get { return dec; } -// // set { dec = value; } -// // } -// // double rotation; -// // double rotationPeriod; -// // string name; - -// // public string Name -// // { -// // get { return name; } -// // set { name = value; } -// // } -// // string localname; -// // IImageSet sufaceImageset; -// // string wikiLink; -// // double orbitalYears; -// // bool moon; -// // bool eclipsed; -// // bool shadowing; -// // bool has3d; - -// // public bool Has3d -// // { -// // get { return has3d; } -// // set { has3d = value; } -// // } -// // double scale; - -// // public double Scale -// // { -// // get { return scale; } -// // set { scale = value; } -// // } - -// // SolarSystemObject parent; - -// // public void UpdatePosition(bool UpdateOrbit) -// // { -// // } -// // public void Draw2d(Device device) -// // { -// // } -// // public void Draw3d(Device device) -// // { -// // } -// // public void DrawOrbit(Device device) -// // { -// // } - -// //} -} diff --git a/engine/csharp_ref/PlotTile.cs b/engine/csharp_ref/PlotTile.cs deleted file mode 100644 index caba036c..00000000 --- a/engine/csharp_ref/PlotTile.cs +++ /dev/null @@ -1,358 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - -namespace wwtlib -{ - public class PlotTile : Tile - { - bool topDown = true; - - protected PositionTexture[] bounds; - protected bool backslash = false; - List vertexList = null; - List[] childTriangleList = null; - - protected float[] demArray; - protected void ComputeBoundingSphere() - { - InitializeGrids(); - - TopLeft = bounds[0 + 3 * 0].Position.Copy(); - BottomRight = bounds[2 + 3 * 2].Position.Copy(); - TopRight = bounds[2 + 3 * 0].Position.Copy(); - BottomLeft = bounds[0 + 3 * 2].Position.Copy(); - CalcSphere(); - } - - - public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine) - { - if (renderContext.gl != null) - { - //todo draw in WebGL - } - else - { - if (part == 0) - { - foreach(Star star in stars) - { - double radDec = 25 / Math.Pow(1.6, star.Magnitude); - - Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false); - } - } - } - } - - WebFile webFile; - public override void RequestImage() - { - if (!Downloading && !ReadyToRender) - { - Downloading = true; - - webFile = new WebFile(URLHelpers.singleton.rewrite(this.URL, URLRewriteMode.AsIfAbsolute)); - webFile.OnStateChange = FileStateChange; - webFile.Send(); - } - } - - public void FileStateChange() - { - if(webFile.State == StateType.Error) - { - Downloading = false; - ReadyToRender = false; - errored = true; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - } - else if(webFile.State == StateType.Received) - { - - texReady = true; - Downloading = false; - errored = false; - ReadyToRender = texReady && (DemReady || !demTile); - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - LoadData(webFile.GetText()); - } - - } - - List stars = new List(); - private void LoadData(string data) - { - string[] rows = data.Replace("\r\n","\n").Split("\n"); - - bool firstRow = true; - PointType type = PointType.Move; - Star star = null; - foreach (string row in rows) - { - if (firstRow) - { - firstRow = false; - continue; - } - - if (row.Trim().Length > 5) - { - - star = new Star(row); - star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1); - - stars.Add(star); - } - } - } - - public override bool IsPointInTile(double lat, double lng) - { - - if (Level == 0) - { - return true; - } - - if (Level == 1) - { - if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1)) - { - return true; - } - if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1)) - { - return true; - } - if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0)) - { - return true; - } - if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0)) - { - return true; - } - return false; - } - - if (!this.DemReady || this.DemData == null) - { - return false; - } - - Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng); - bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint); - bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint); - bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint); - bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint); - - if (top && right && bottom && left) - { - // showSelected = true; - return true; - } - return false; ; - - } - - private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) - { - pntA.Normalize(); - pntB.Normalize(); - Vector3d cross = Vector3d.Cross(pntA, pntB); - - double dot = Vector3d.Dot(cross, pntTest); - - return dot < 0; - } - - - - private void InitializeGrids() - { - vertexList = new List(); - childTriangleList = new List[4]; - childTriangleList[0] = new List(); - childTriangleList[1] = new List(); - childTriangleList[2] = new List(); - childTriangleList[3] = new List(); - - bounds = new PositionTexture[9]; - - if (Level > 0) - { - // Set in constuctor now - //ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null); - if (Parent == null) - { - Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null); - } - - PlotTile parent = (PlotTile)Parent; - - int xIndex = tileX % 2; - int yIndex = tileY % 2; - - if (Level > 1) - { - backslash = parent.backslash; - } - else - { - backslash = xIndex == 1 ^ yIndex == 1; - } - - - bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy(); - bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); - bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy(); - bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - - if (backslash) - { - bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - } - else - { - bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - } - - bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy(); - bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy(); - - bounds[0 + 3 * 0].Tu = 0*uvMultiple; - bounds[0 + 3 * 0].Tv = 0 * uvMultiple; - bounds[1 + 3 * 0].Tu = .5f * uvMultiple; - bounds[1 + 3 * 0].Tv = 0 * uvMultiple; - bounds[2 + 3 * 0].Tu = 1 * uvMultiple; - bounds[2 + 3 * 0].Tv = 0 * uvMultiple; - - bounds[0 + 3 * 1].Tu = 0 * uvMultiple; - bounds[0 + 3 * 1].Tv = .5f * uvMultiple; - bounds[1 + 3 * 1].Tu = .5f * uvMultiple; - bounds[1 + 3 * 1].Tv = .5f * uvMultiple; - bounds[2 + 3 * 1].Tu = 1 * uvMultiple; - bounds[2 + 3 * 1].Tv = .5f * uvMultiple; - - bounds[0 + 3 * 2].Tu = 0 * uvMultiple; - bounds[0 + 3 * 2].Tv = 1 * uvMultiple; - bounds[1 + 3 * 2].Tu = .5f * uvMultiple; - bounds[1 + 3 * 2].Tv = 1 * uvMultiple; - bounds[2 + 3 * 2].Tu = 1 * uvMultiple; - bounds[2 + 3 * 2].Tv = 1 * uvMultiple; - - } - else - { - bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0); - bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0); - bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0); - bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f); - bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f); - bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f); - bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1); - bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1); - bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1); - - - // Setup default matrix of points. - } - } - - private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2) - { - Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f); - Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f); - - a1.Normalize(); - return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y); - } - int subDivisionLevel = 4; - bool subDivided = false; - - public override bool CreateGeometry(RenderContext renderContext) - { - if (GeometryCreated) - { - return true; - } - - GeometryCreated = true; - base.CreateGeometry(renderContext); - - return true; - } - - - - - - public PlotTile() - { - } - - public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent) - { - PlotTile temp = new PlotTile(); - temp.Parent = parent; - temp.Level = level; - temp.tileX = xc; - temp.tileY = yc; - temp.dataset = dataset; - temp.topDown = !dataset.BottomsUp; - - - if (temp.tileX != (int)xc) - { - Script.Literal("alert('bad')"); - } - //temp.ComputeQuadrant(); - - if (dataset.MeanRadius != 0) - { - temp.DemScaleFactor = dataset.MeanRadius; - } - else - { - if (dataset.DataSetType == ImageSetType.Earth) - { - temp.DemScaleFactor = 6371000; - } - else - { - temp.DemScaleFactor = 3396010; - } - } - - - temp.ComputeBoundingSphere(); - return temp; - } - - public override void CleanUp(bool removeFromParent) - { - base.CleanUp(removeFromParent); - - if (vertexList != null) - { - vertexList = null; - } - if (childTriangleList != null) - { - childTriangleList = null; - } - - - subDivided = false; - demArray = null; - } - - } - -} diff --git a/engine/csharp_ref/Pointing.cs b/engine/csharp_ref/Pointing.cs deleted file mode 100644 index bf012122..00000000 --- a/engine/csharp_ref/Pointing.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; - -namespace wwtlib -{ - public class Pointing - { - /** Colatitude in radians (0 is North Pole; Pi is South Pole) */ - public double theta; - - /** Longitude in radians */ - public double phi; - - /** Default constructor */ - public Pointing() { } - - //public static Pointing Create(Pointing ptg) - //{ - // Pointing temp = new Pointing(); - // temp.theta = ptg.theta; - // temp.phi = ptg.phi; - // return temp; - //} - - /** Simple constructor initializing both values. - @param theta in radians [0,Pi] - @param phi in radians [0,2*Pi] */ - public static Pointing Create(double theta, double phi) - { - Pointing temp = new Pointing(); - temp.theta = theta; - temp.phi = phi; - return temp; - } - - //public static Pointing Create(Vector3d vec) - //{ - // Pointing temp = new Pointing(); - // temp.theta = FastMath.atan2(Math.Sqrt(vec.X * vec.X + vec.Y * vec.Y), vec.Z); - // temp.phi = FastMath.atan2(vec.Y, vec.X); - // if (temp.phi < 0d) - // { - // temp.phi += 2 * Math.PI; - // } - // if (temp.phi >= 2 * Math.PI) - // { - // temp.phi -= 2 * Math.PI; - // } - // return temp; - //} - - - //public static Pointing Create(Zphi zphi) - //{ - // Pointing temp = new Pointing(); - // double xy = Math.Sqrt((1d - zphi.z) * (1d + zphi.z)); - // temp.theta = FastMath.atan2(xy, zphi.z); - // temp.phi = zphi.phi; - // return temp; - //} - - /** Normalize theta range */ - public void normalizeTheta() - { - theta = HealpixUtils.fmodulo(theta, 2 * Math.PI); - if (theta > Math.PI) - { - phi += Math.PI; - theta = 2 * Math.PI - theta; - } - } - - /** Normalize theta and phi ranges */ - public void normalize() - { - normalizeTheta(); - phi = HealpixUtils.fmodulo(phi, 2 * Math.PI); - } - - public String toString() - { - StringBuilder s = new StringBuilder(); - s.Append("ptg("); s.Append(theta); - s.Append(","); s.Append(phi); - s.Append(")"); - return s.ToString(); - } - - - } -} \ No newline at end of file diff --git a/engine/csharp_ref/RenderContext.cs b/engine/csharp_ref/RenderContext.cs deleted file mode 100644 index 3caedc6e..00000000 --- a/engine/csharp_ref/RenderContext.cs +++ /dev/null @@ -1,1604 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; - - -namespace wwtlib -{ - - public class Material - { - public Color Diffuse; - public Color Ambient; - public Color Specular; - public float SpecularSharpness; - public float Opacity; - public bool IsDefault; - } - - public class InViewReturnMessage - { - public string table; - public bool aborted; - } - - public class RenderContext - { - public static bool UseGl = false; - public static bool UseGlVersion2 = false; - public CanvasContext2D Device; - public GL gl; - - public double Height; - public double Width; - public bool Lighting = false; - public RenderContext() - { - - - for (int i = 0; i < 6; i++) - { - frustum[i] = new PlaneD(0, 0, 0, 0); - } - } - public static RenderContext Create(CanvasContext2D device) - { - RenderContext temp = new RenderContext(); - temp.Device = device; - - temp.ViewCamera.Zoom = 700; - temp.ViewCamera.Target = SolarSystemObjects.Undefined; - return temp; - } - - public void Save() - { - if (gl != null) - { - } - else - { - Device.Save(); - } - } - - public void Restore() - { - if (gl != null) - { - } - else - { - Device.Restore(); - } - - } - - public void Clear() - { - if (gl != null) - { - gl.viewport(0, 0, (int)Width, (int)Height); - gl.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT); - //gl.clearColor(1, 0, 0, 1); - - } - else - { - Device.Save(); - Device.FillStyle = "black"; - Device.FillRect(0, 0, Width, Height); - - Device.Restore(); - } - } - - - Vector3d viewPoint = new Vector3d(); - public Vector3d ViewPoint - { - get - { - return viewPoint; - } - } - public double RA - { - get - { - //return ((-((this.currentTheta - 180) / 15) % 24) + 48) % 24; - return ((((180 - (this.ViewCamera.Lng - 180)) / 15) % 24) + 48) % 24; - } - } - - public bool Space = false; - - public double RAtoViewLng(double ra) - { - return 180 - ((ra) / 24.0 * 360) - 180; ; - } - public double Dec - { - get - { - return ViewCamera.Lat; - } - } - const double FOVMULT = 343.774f; - double fovAngle; - public double FovAngle - { - get - { - - return fovAngle; - } - } - double fovScale = 0; - - public double FovScale - { - get { return fovScale; } - set { fovScale = value; } - } - - - private Matrix3d view; - - public Matrix3d View - { - get { return view; } - set - { - view = value; - //Device.Transform.View = view.Matrix; - frustumDirty = true; - } - } - private Matrix3d viewBase; - - public Matrix3d ViewBase - { - get { return viewBase; } - set - { - viewBase = value; - } - } - - private Matrix3d projection; - - public Matrix3d Projection - { - get { return projection; } - set - { - projection = value; - //Device.Transform.Projection = projection.Matrix; - frustumDirty = true; - } - } - private Matrix3d world; - - public Matrix3d World - { - get { return world; } - set - { - world = value; - //Device.Transform.World = world.Matrix; - frustumDirty = true; - } - } - - - private Matrix3d worldBase; - - internal Texture GetScreenTexture() - { - //todo add code to capture screen - Texture tex = null; - - return tex; - - } - - public Matrix3d WorldBase - { - get { return worldBase; } - set - { - worldBase = value; - } - } - private Matrix3d worldBaseNonRotating; - - public Matrix3d WorldBaseNonRotating - { - get { return worldBaseNonRotating; } - set - { - worldBaseNonRotating = value; - } - } - - private double nominalRadius = 6378137.0; - - public double NominalRadius - { - get { return nominalRadius; } - set { nominalRadius = value; } - } - - - Texture mainTexture = null; - public Texture MainTexture - { - get { return mainTexture; } - set - { - if (value != null) - { - mainTexture = value; - gl.bindTexture(GL.TEXTURE_2D, mainTexture.Texture2d); - - - //textureStateDirty = true; - } - } - } - - public IViewMover ViewMover = null; - - public bool OnTarget(Place place) - { - return ( - ( - Math.Abs(ViewCamera.Lat - TargetCamera.Lat) < .000000000001 - && Math.Abs(ViewCamera.Lng - TargetCamera.Lng) < .000000000001 - && Math.Abs(ViewCamera.Zoom - TargetCamera.Zoom) < .000000000001 - ) - && ViewMover == null - ); - - } - - - - public void SetTexture(ImageElement texture) - { - - } - - public CameraParameters ViewCamera = new CameraParameters(); - public CameraParameters TargetCamera = new CameraParameters(); - - public double alt = 0; - public double az = 0; - public double targetAlt = 0; - public double targetAz = 0; - - Imageset backgroundImageset = null; - - public Imageset BackgroundImageset - { - get { return backgroundImageset; } - set - { - bool viewModeChanged = backgroundImageset != null && value != null && (backgroundImageset.DataSetType != value.DataSetType); - backgroundImageset = value; - if (viewModeChanged) //Prevent potential artifacts when going from 3D to Sky/Pan - { - WWTControl.Singleton.FreezeView(); - WWTControl.Singleton.ClampZooms(this); - } - } - } - - Imageset foregroundImageset = null; - - public Imageset ForegroundImageset - { - get { return foregroundImageset; } - set { foregroundImageset = value; } - } - - - private List activeCatalogHipsImagesets = new List(); - - public List CatalogHipsImagesets - { - get { return activeCatalogHipsImagesets; } - } - - - public void GetCatalogHipsDataInView(Imageset imageset, bool limit, Action onComplete) - { - CatalogSpreadSheetLayer layer = new CatalogSpreadSheetLayer(); - Action onHeaderInfoLoad = delegate () - { - layer.UseHeadersFromVoTable(imageset.HipsProperties.CatalogColumnInfo); - TryGetAllDataInView(imageset, limit, layer, onComplete, 0); - }; - - if (imageset.HipsProperties == null) - { - imageset.HipsProperties = new HipsProperties(imageset); - imageset.HipsProperties.SetDownloadCompleteListener(onHeaderInfoLoad); - } - else if (imageset.HipsProperties != null && imageset.HipsProperties.DownloadComplete) - { - onHeaderInfoLoad.Invoke(); - } - else - { - imageset.HipsProperties.SetDownloadCompleteListener(onHeaderInfoLoad); - } - } - - private void TryGetAllDataInView(Imageset imageset, bool limit, CatalogSpreadSheetLayer catalogSpreadSheetLayer, Action onComplete, int i) - { - int maxX = GetTilesXForLevel(imageset, imageset.BaseLevel); - int maxY = GetTilesYForLevel(imageset, imageset.BaseLevel); - bool anyTileStillDownloading = false; - for (int x = 0; x < maxX; x++) - { - for (int y = 0; y < maxY; y++) - { - Tile tile = TileCache.GetTile(imageset.BaseLevel, x, y, imageset, null); - if (tile != null) - { - bool tileAndChildrenReady = ((HealpixTile)tile).GetDataInView(this, limit, catalogSpreadSheetLayer); - anyTileStillDownloading = anyTileStillDownloading || !tileAndChildrenReady; - } - else - { - anyTileStillDownloading = true; - } - } - } - if (anyTileStillDownloading) - { - int count = catalogSpreadSheetLayer.Table.Rows.Count; - if ((count > 10000 || i > 100 * 60 * 5) && limit) // ~5 minutes - { - Script.Literal("console.log('Too Many results - Aborting')"); - Script.Literal("console.log(count)"); - InViewReturnMessage returnMessage = new InViewReturnMessage(); - returnMessage.aborted = true; - returnMessage.table = catalogSpreadSheetLayer.GetTableDataInView(); - onComplete.Invoke(returnMessage); - catalogSpreadSheetLayer.CleanUp(); - } - else - { - Script.SetTimeout(delegate () { TryGetAllDataInView(imageset, limit, catalogSpreadSheetLayer, onComplete, i); }, 10); - if (i % 200 == 0) - { - Script.Literal("console.log('Waiting for more tiles to load')"); - Script.Literal("console.log(count)"); - } - i++; - } - } - else - { - int count = catalogSpreadSheetLayer.Table.Rows.Count; - Script.Literal("console.log('Done!')"); - Script.Literal("console.log(count)"); - InViewReturnMessage returnMessage = new InViewReturnMessage(); - returnMessage.aborted = false; - returnMessage.table = catalogSpreadSheetLayer.GetTableDataInView(); - onComplete.Invoke(returnMessage); - catalogSpreadSheetLayer.CleanUp(); - } - - } - - public void AddCatalogHips(Imageset imageset, Action onLoad) - { - if (!activeCatalogHipsImagesets.Contains(imageset)) - { - activeCatalogHipsImagesets.Add(imageset); - } - if (imageset.HipsProperties == null) - { - imageset.HipsProperties = new HipsProperties(imageset); - imageset.HipsProperties.SetDownloadCompleteListener(onLoad); - } - else if (imageset.HipsProperties != null && imageset.HipsProperties.DownloadComplete) - { - LayerManager.AddSpreadsheetLayer(imageset.HipsProperties.CatalogSpreadSheetLayer, "Sky"); - if (onLoad != null) - { - onLoad.Invoke(); - } - } - } - - public void RemoveCatalogHips(Imageset imageset) - { - activeCatalogHipsImagesets.Remove(imageset); - if (imageset.HipsProperties != null) - { - LayerManager.DeleteLayerByID(imageset.HipsProperties.CatalogSpreadSheetLayer.ID, true, true); - } - } - - public Imageset GetCatalogHipsByName(string name) - { - foreach (Imageset imageset in activeCatalogHipsImagesets) - { - if (imageset.Name == name) - { - return imageset; - } - } - return null; - } - - public double GetAltitudeForLatLongForPlanet(int planetID, double viewLat, double viewLong) - { - - Imageset layer = WWTControl.Singleton.GetImagesetByName(Planets.GetNameFrom3dId(planetID)); - - if (layer == null) - { - return 0; - } - - int maxX = GetTilesXForLevel(layer, layer.BaseLevel); - int maxY = GetTilesYForLevel(layer, layer.BaseLevel); - - for (int x = 0; x < maxX; x++) - { - for (int y = 0; y < maxY; y++) - { - Tile tile = TileCache.GetTile(layer.BaseLevel, x, y, layer, null); - if (tile != null) - { - if (tile.IsPointInTile(viewLat, viewLong)) - { - return tile.GetSurfacePointAltitude(viewLat, viewLong, true); - } - } - } - } - return 0; - } - - public double GetEarthAltitude(double ViewLat, double ViewLong, bool meters) - { - if (WWTControl.Singleton.SolarSystemMode) - { - - Vector3d pnt = Coordinates.GeoTo3dDouble(ViewLat, ViewLong + 90); - - Matrix3d EarthMat = Planets.EarthMatrixInv; - - pnt = Vector3d.TransformCoordinate(pnt, EarthMat); - pnt.Normalize(); - - Vector2d point = Coordinates.CartesianToLatLng(pnt); - - return GetAltitudeForLatLongForPlanet((int)ViewCamera.Target, point.Y, point.X); - - } - else if (BackgroundImageset.DataSetType == ImageSetType.Earth) - { - return meters ? GetMetersAltitudeForLatLong(ViewLat, ViewLong) : GetScaledAltitudeForLatLong(ViewLat, ViewLong); - } - //else if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.Planet) - //{ - // return GetAltitudeForLatLong(ViewLat, ViewLong); - //} - else - { - return 0; - } - } - - public static int GetTilesYForLevel(Imageset layer, int level) - { - int maxY = 1; - - switch (layer.Projection) - { - case ProjectionType.Mercator: - maxY = (int)Math.Pow(2, level); - break; - case ProjectionType.Equirectangular: - // maxY = (int)Math.Pow(2, level-layer.BaseLevel) * (int)(180 / layer.BaseTileDegrees); - - maxY = (int)(Math.Pow(2, level) * (180 / layer.BaseTileDegrees)); - break; - case ProjectionType.Tangent: - maxY = (int)Math.Pow(2, level); - - break; - case ProjectionType.Spherical: - maxY = 1; - break; - case ProjectionType.Healpix: - maxY = 4 * (int)Math.Pow(2, level); - break; - default: - maxY = (int)Math.Pow(2, level); - break; - } - if (maxY == Double.PositiveInfinity) - { - maxY = 1; - } - return maxY; - } - - public static int GetTilesXForLevel(Imageset layer, int level) - { - int maxX = 1; - switch (layer.Projection) - { - case ProjectionType.Plotted: - case ProjectionType.Toast: - maxX = (int)Math.Pow(2, level); - break; - case ProjectionType.Mercator: - maxX = (int)Math.Pow(2, level) * (int)(layer.BaseTileDegrees / 360.0); - break; - case ProjectionType.Equirectangular: - //maxX = (int)Math.Pow(2, level) * (int)(layer.BaseTileDegrees / 90.0); - maxX = (int)Math.Pow(2, level) * (int)(360 / layer.BaseTileDegrees); - - break; - - case ProjectionType.Tangent: - if (layer.WidthFactor == 1) - { - maxX = (int)Math.Pow(2, level) * 2; - } - else - { - maxX = (int)Math.Pow(2, level); - } - break; - - case ProjectionType.SkyImage: - maxX = 1; - break; - case ProjectionType.Spherical: - maxX = 1; - break; - case ProjectionType.Healpix: - maxX = (int)Math.Pow(2, level) * 3; - break; - default: - maxX = (int)Math.Pow(2, level) * 2; - break; - } - - - return maxX; - } - public void DrawImageSet(Imageset imageset, double opacity) - { - - int maxX = GetTilesXForLevel(imageset, imageset.BaseLevel); - int maxY = GetTilesYForLevel(imageset, imageset.BaseLevel); - - for (int x = 0; x < maxX; x++) - { - for (int y = 0; y < maxY; y++) - { - Tile tile = TileCache.GetTile(imageset.BaseLevel, x, y, imageset, null); - if (tile != null) - { - tile.Draw3D(this, opacity); - } - } - } - } - - private Tile GetTileAtLatLong(double viewLat, double viewLong) - { - Imageset layer = BackgroundImageset; - - if (layer == null) - { - return null; - } - - int maxX = GetTilesXForLevel(layer, layer.BaseLevel); - int maxY = GetTilesYForLevel(layer, layer.BaseLevel); - - for (int x = 0; x < maxX; x++) - { - for (int y = 0; y < maxY; y++) - { - Tile tile = TileCache.GetTile(layer.BaseLevel, x, y, layer, null); - if (tile != null) - { - if (tile.IsPointInTile(viewLat, viewLong)) - { - return tile; - } - } - } - } - return null; - } - - public double GetScaledAltitudeForLatLong(double viewLat, double viewLong) - { - Tile tile = GetTileAtLatLong(viewLat, viewLong); - if (tile != null) - { - return tile.GetSurfacePointAltitude(viewLat, viewLong, false); - } - - return 0; - } - - public double GetMetersAltitudeForLatLong(double viewLat, double viewLong) - { - Tile tile = GetTileAtLatLong(viewLat, viewLong); - if (tile != null) - { - return tile.GetSurfacePointAltitude(viewLat, viewLong, true); - } - - return 0; - } - - - double targetHeight = 1; - public double targetAltitude = 0; - - public static double back = 0; - internal void SetupMatricesLand3d() - { - Lighting = false; - Space = false; - RenderTriangle.CullInside = false; - - // For our world matrix, we will just rotate the Earth and Clouds about the y-axis. - Matrix3d WorldMatrix = Matrix3d.RotationY(((ViewCamera.Lng - 90f) / 180f * Math.PI)); - WorldMatrix.Multiply(Matrix3d.RotationX(((-ViewCamera.Lat) / 180f * Math.PI))); - World = WorldMatrix; - WorldBase = WorldMatrix.Clone(); - - viewPoint = Coordinates.GeoTo3d(ViewCamera.Lat, ViewCamera.Lng); - - double distance = 0; - if (backgroundImageset.IsMandelbrot) - { - - distance = (4.0 * (ViewCamera.Zoom / 180)) + 0.00000000000000000000000000000000000000001; - } - else - { - - distance = (4.0 * (ViewCamera.Zoom / 180)) + 0.000001; - } - fovAngle = ((this.ViewCamera.Zoom) / FOVMULT) / Math.PI * 180; - fovScale = (fovAngle / Height) * 3600; - - if (gl != null) - { - targetAltitude = GetScaledAltitudeForLatLong(ViewCamera.Lat, ViewCamera.Lng); - double heightNow = 1 + targetAltitude; - targetAltitude *= NominalRadius; - //if ((double.IsNaN(heightNow))) - //{ - // heightNow = 0; - //} - - if (targetHeight < heightNow) - { - targetHeight = (((targetHeight * 2) + heightNow) / 3); - } - else - { - targetHeight = (((targetHeight * 9) + heightNow) / 10); - } - //if (double.IsNaN(targetHeight)) - //{ - // targetHeight = 0; - //} - - } - else - { - targetAltitude = 0; - targetHeight = 1; - } - - double rotLocal = ViewCamera.Rotation; - - CameraPosition = Vector3d.Create( - (Math.Sin(rotLocal) * Math.Sin(ViewCamera.Angle) * distance), - (Math.Cos(rotLocal) * Math.Sin(ViewCamera.Angle) * distance), - (-targetHeight - (Math.Cos(ViewCamera.Angle) * distance))); - Vector3d cameraTarget = Vector3d.Create(0.0f, 0.0f, -targetHeight); - - - double camHeight = CameraPosition.Length(); - - - Vector3d lookUp = Vector3d.Create(Math.Sin(rotLocal) * Math.Cos(ViewCamera.Angle), Math.Cos(rotLocal) * Math.Cos(ViewCamera.Angle), Math.Sin(ViewCamera.Angle)); - - View = Matrix3d.LookAtLH( - (CameraPosition), - (cameraTarget), - lookUp); - // * Matrix3d.RotationX(((-config.DomeTilt) / 180 * Math.PI)); - - ViewBase = View; - - double back = Math.Sqrt((distance + 1f) * (distance + 1f) - 1); - back = Math.Max(.5, back); - // back = (float)camDist * 40f; - double m_nearPlane = distance * .05f; - - m_nearPlane = distance * .05f; - Projection = Matrix3d.PerspectiveFovLH((Math.PI / 4.0), (double)Width / (double)Height, m_nearPlane, back); - - SetMatrixes(); - - MakeFrustum(); - } - bool galactic = true; - - Matrix3d galacticMatrix = Matrix3d.Create( - -.4838350155, -.0548755604, -.8734370902, 0, - .7469822445, .4941094279, -.4448296300, 0, - .4559837762, -.8676661490, -.1980763734, 0, - 0, 0, 0, 1); - bool firstTimeInit = false; - - public void SetupMatricesSpace3d(double canvasWidth, double canvasHeight) - { - Lighting = false; - if (!firstTimeInit) - { - galacticMatrix = Matrix3d.Identity; - // -28.9361739586894, 17.7603329867975 - galacticMatrix.Multiply(Matrix3d.RotationY(-(270 - (17.7603329867975 * 15)) / 180.0 * Math.PI)); - galacticMatrix.Multiply(Matrix3d.RotationX(-((-28.9361739586894)) / 180.0 * Math.PI)); - galacticMatrix.Multiply(Matrix3d.RotationZ(((31.422052860102041270114993238783) - 90) / 180.0 * Math.PI)); - //galacticMatrix.Transpose(); - //galacticMatrix.Invert(); - firstTimeInit = true; - } - - - Space = true; - RenderTriangle.CullInside = true; - - Matrix3d WorldMatrix = Matrix3d.Identity; - if (Settings.Active.GalacticMode) - { - WorldMatrix.Multiply(galacticMatrix); - WorldMatrix.Multiply(Matrix3d.RotationY(((az)) / 180.0 * Math.PI)); - WorldMatrix.Multiply(Matrix3d.RotationX(-((alt)) / 180.0 * Math.PI)); - double[] gPoint = Coordinates.GalactictoJ2000(az, alt); - - viewPoint = Coordinates.RADecTo3dAu(gPoint[0] / 15, gPoint[1], 1.0); - TargetCamera.Lng = this.RAtoViewLng(gPoint[0] / 15); - TargetCamera.Lat = gPoint[1]; - ViewCamera.Lat = TargetCamera.Lat; - ViewCamera.Lng = TargetCamera.Lng; - } - else - { - WorldMatrix.Multiply(Matrix3d.RotationY(-((ViewCamera.Lng - 90)) / 180.0 * Math.PI)); - WorldMatrix.Multiply(Matrix3d.RotationX(-((ViewCamera.Lat)) / 180.0 * Math.PI)); - viewPoint = Coordinates.RADecTo3dAu(RA, Dec, 1.0); - } - - - - - - double camLocal = ((ViewCamera.Rotation /*+ 90*/)); - fovAngle = ((this.ViewCamera.Zoom) / FOVMULT) / Math.PI * 180; - fovScale = (fovAngle / canvasHeight) * 3600; - - //Settings.Global.LocalHorizonMode = true; - - // altaz - if (Settings.Active.LocalHorizonMode && backgroundImageset.DataSetType == ImageSetType.Sky) - { - Coordinates zenithAltAz = new Coordinates(0, 0); - - zenithAltAz.Az = 0; - - zenithAltAz.Alt = 0; - - Coordinates zenith = Coordinates.HorizonToEquitorial(zenithAltAz, SpaceTimeController.Location, SpaceTimeController.Now); - //Coordinates zenith2 = Coordinates.HorizonToEquitorial(zenithAltAz, Coordinates.FromLatLng(1, 1), SpaceTimeController.Now); - //Coordinates zenith3 = Coordinates.HorizonToEquitorial(zenithAltAz, Coordinates.FromLatLng(-1, 1), SpaceTimeController.Now); - - double raPart = -((zenith.RA - 6) / 24.0 * (Math.PI * 2)); - double decPart = -(((zenith.Dec)) / 360.0 * (Math.PI * 2)); - string raText = Coordinates.FormatDMS(zenith.RA); - WorldMatrix = Matrix3d.RotationY(-raPart - Math.PI); - WorldMatrix.Multiply(Matrix3d.RotationX(decPart)); - - if (SpaceTimeController.Location.Lat < 0) - { - WorldMatrix.Multiply(Matrix3d.RotationY(((az) / 180.0 * Math.PI))); - - WorldMatrix.Multiply(Matrix3d.RotationX(((alt) / 180.0 * Math.PI))); - camLocal += Math.PI; - } - else - { - WorldMatrix.Multiply(Matrix3d.RotationY(((-az) / 180.0 * Math.PI))); - - WorldMatrix.Multiply(Matrix3d.RotationX(((-alt) / 180.0 * Math.PI))); - } - - Coordinates currentRaDec = Coordinates.HorizonToEquitorial(Coordinates.FromLatLng(alt, az), SpaceTimeController.Location, SpaceTimeController.Now); - - ViewCamera.Lat = TargetCamera.Lat = currentRaDec.Dec; - ViewCamera.Lng = TargetCamera.Lng = RAtoViewLng(currentRaDec.RA); - - } - World = WorldMatrix; - WorldBase = WorldMatrix.Clone(); - // altaz - - - - double localZoomFactor = ViewCamera.Zoom; - - double FovAngle = ((localZoomFactor) / FOVMULT) / Math.PI * 180; - CameraPosition = Vector3d.Create(0.0, 0.0, 0.0); - // This is for distance Calculation. For space everything is the same distance, so camera target is key. - - View = Matrix3d.LookAtLH(CameraPosition, Vector3d.Create(0.0, 0.0, -1.0), Vector3d.Create(Math.Sin(camLocal), Math.Cos(camLocal), 0.0)); - ViewBase = View.Clone(); - - double m_nearPlane = .1; - nearPlane = .1f; - Projection = Matrix3d.PerspectiveFovLH((localZoomFactor) / FOVMULT, (double)canvasWidth / (double)canvasHeight, .1, -2.0); - - - SetMatrixes(); - - MakeFrustum(); - - } - - public SolarSystemObjects SolarSystemTrack - { - get - { - return ViewCamera.Target; - } - set - { - ViewCamera.Target = value; - } - } - - - public double SolarSystemCameraDistance - { - get - { - return (4.0 * (ViewCamera.Zoom / 9)) + 0.000001; - } - - } - - public bool SandboxMode - { - get - { - if (backgroundImageset == null) - { - return false; - } - - return backgroundImageset.DataSetType == ImageSetType.Sandbox; - } - } - - public string TrackingFrame - { - get { return ViewCamera.TargetReferenceFrame; } - set { ViewCamera.TargetReferenceFrame = value; } - } - - bool useSolarSystemTilt = true; - - public CameraParameters CustomTrackingParams = new CameraParameters(); - - Vector3d cameraOffset = new Vector3d(); - - double fovLocal = (Math.PI / 4.0); - - public double FovLocal - { - get { return fovLocal; } - set { fovLocal = value; } - } - public double PerspectiveFov = Math.PI / 4; - - - public void SetupMatricesOverlays() - { - - World = Matrix3d.Identity; - - Matrix3d lookAtAdjust = Matrix3d.Identity; - - Vector3d lookFrom = Vector3d.Create(0, 0, 0); - Vector3d lookAt = Vector3d.Create(0, 0, 1); - Vector3d lookUp = Vector3d.Create(0, 1, 0); - - Matrix3d view; - view = Matrix3d.LookAtLH(lookFrom, lookAt, lookUp); - view.Multiply(Matrix3d.Scaling(1, -1, 1)); - - - View = view; - - double back = 10000; - nearPlane = .1f; - - Projection = Matrix3d.PerspectiveFovLH(fovLocal, Width / Height, nearPlane, back); - - - - } - - - - public void SetupMatricesSolarSystem(bool forStars) - { - Lighting = Settings.Active.SolarSystemLighting; - - Space = false; - if (SolarSystemTrack != SolarSystemObjects.Custom && SolarSystemTrack != SolarSystemObjects.Undefined) - { - ViewCamera.ViewTarget = Planets.GetPlanetTargetPoint(SolarSystemTrack, ViewCamera.Lat, ViewCamera.Lng, 0); - } - RenderTriangle.CullInside = false; - - - double cameraDistance = SolarSystemCameraDistance; - - Matrix3d trackingMatrix = Matrix3d.Identity; - cameraDistance -= 0.000001; - - bool activeTrackingFrame = false; - if (SolarSystemTrack == SolarSystemObjects.Custom && !string.IsNullOrEmpty(TrackingFrame)) - { - activeTrackingFrame = true; - FrameTarget target = LayerManager.GetFrameTarget(this, TrackingFrame); - ViewCamera.ViewTarget = target.Target; - trackingMatrix = target.Matrix; - } - else if (!string.IsNullOrEmpty(TrackingFrame)) - { - TrackingFrame = ""; - } - - - Vector3d center = ViewCamera.ViewTarget; - //Vector3d lightPosition = -center; - - double localZoom = ViewCamera.Zoom * 20; - Vector3d lookAt = new Vector3d(); - - Matrix3d viewAdjust = Matrix3d.Identity; - viewAdjust.Multiply(Matrix3d.RotationX(((-ViewCamera.Lat) / 180f * Math.PI))); - viewAdjust.Multiply(Matrix3d.RotationY(((-ViewCamera.Lng) / 180f * Math.PI))); - - Matrix3d lookAtAdjust = Matrix3d.Identity; - - - bool dome = false; - - Vector3d lookUp; - - - if (useSolarSystemTilt && !SandboxMode) - { - double angle = ViewCamera.Angle; - if (cameraDistance > 0.0008) - { - angle = 0; - } - else if (cameraDistance > 0.00001) - { - double val = Math.Min(1.903089987, Util.Log10(cameraDistance) + 5) / 1.903089987; - - angle = angle * Math.Max(0, 1 - val); - } - - - - CameraPosition = Vector3d.Create( - (Math.Sin(-ViewCamera.Rotation) * Math.Sin(angle) * cameraDistance), - (Math.Cos(-ViewCamera.Rotation) * Math.Sin(angle) * cameraDistance), - ((Math.Cos(angle) * cameraDistance))); - lookUp = Vector3d.Create(Math.Sin(-ViewCamera.Rotation), Math.Cos(-ViewCamera.Rotation), 0.00001f); - } - else - { - CameraPosition = Vector3d.Create(0, 0, ((cameraDistance))); - - lookUp = Vector3d.Create(Math.Sin(-ViewCamera.Rotation), Math.Cos(-ViewCamera.Rotation), 0.0001f); - } - - - CameraPosition = viewAdjust.Transform(CameraPosition); - - cameraOffset = CameraPosition.Copy(); - - Matrix3d tmp = trackingMatrix.Clone(); - tmp.Invert(); - cameraOffset = Vector3d.TransformCoordinate(cameraOffset, tmp); - - - - lookUp = viewAdjust.Transform(lookUp); - - - World = Matrix3d.Identity; - WorldBase = Matrix3d.Identity; - WorldBaseNonRotating = Matrix3d.Identity; - - View = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(trackingMatrix, Matrix3d.LookAtLH(CameraPosition, lookAt, lookUp)), lookAtAdjust); - - - ViewBase = View.Clone(); - - - Vector3d temp = Vector3d.SubtractVectors(lookAt, CameraPosition); - temp.Normalize(); - temp = Vector3d.TransformCoordinate(temp, trackingMatrix); - temp.Normalize(); - viewPoint = temp; - - - - //if (activeTrackingFrame) - //{ - // Vector3d atfCamPos = RenderContext11.CameraPosition; - // Vector3d atfLookAt = lookAt; - // Vector3d atfLookUp = lookUp; - // Matrix3d mat = trackingMatrix; - // mat.Invert(); - - // atfCamPos.TransformCoordinate(mat); - // atfLookAt.TransformCoordinate(mat); - // atfLookUp.TransformCoordinate(mat); - // atfLookAt.Normalize(); - // atfLookUp.Normalize(); - - // CustomTrackingParams.Angle = 0; - // CustomTrackingParams.Rotation = 0; - // CustomTrackingParams.DomeAlt = viewCamera.DomeAlt; - // CustomTrackingParams.DomeAz = viewCamera.DomeAz; - // CustomTrackingParams.TargetReferenceFrame = ""; - // CustomTrackingParams.ViewTarget = viewCamera.ViewTarget; - // CustomTrackingParams.Zoom = viewCamera.Zoom; - // CustomTrackingParams.Target = SolarSystemObjects.Custom; - - - // Vector3d atfLook = atfCamPos - atfLookAt; - // atfLook.Normalize(); - - - - // Coordinates latlng = Coordinates.CartesianToSpherical2(atfLook); - // CustomTrackingParams.Lat = latlng.Lat; - // CustomTrackingParams.Lng = latlng.Lng - 90; - - // Vector3d up = Coordinates.GeoTo3dDouble(latlng.Lat + 90, latlng.Lng - 90); - // Vector3d left = Vector3d.Cross(atfLook, up); - - // double dotU = Math.Acos(Vector3d.Dot(atfLookUp, up)); - // double dotL = Math.Acos(Vector3d.Dot(atfLookUp, left)); - - // CustomTrackingParams.Rotation = dotU;// -Math.PI / 2; - //} - - - double radius = Planets.GetAdjustedPlanetRadius((int)SolarSystemTrack); - - - if (cameraDistance < radius * 2.0 && !forStars) - { - nearPlane = cameraDistance * 0.03; - - //m_nearPlane = Math.Max(m_nearPlane, .000000000030); - nearPlane = Math.Max(nearPlane, .00000000001); - back = 1900; - } - else - { - if (forStars) - { - back = 900056; - back = cameraDistance > 900056 ? cameraDistance * 3 : 900056; - nearPlane = .00003f; - - // m_nearPlane = cameraDistance * 0.03; - - // back = 9937812653; - // back = 21421655730; - } - else - { - back = cameraDistance > 1900 ? cameraDistance + 200 : 1900; - - // m_nearPlane = .0001f; - if (Settings.Active.SolarSystemScale < 13) - { - nearPlane = (float)Math.Min(cameraDistance * 0.03, 0.01); - } - else - { - nearPlane = .001f; - } - } - } - - - Projection = Matrix3d.PerspectiveFovLH((fovLocal), (double)Width / (double)Height, nearPlane, back); - PerspectiveFov = fovLocal; - fovAngle = ((this.ViewCamera.Zoom) / FOVMULT) / Math.PI * 180; - fovScale = (fovAngle / Height) * 3600; - - SetMatrixes(); - MakeFrustum(); - } - - private void SetMatrixes() - { - //if (gl != null) - //{ - // Matrix3d mvMat = Matrix3d.MultiplyMatrix(World, View); - - // gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray()); - // gl.uniformMatrix4fv(projMatLoc, false, Projection.FloatArray()); - // gl.uniform1i(sampLoc, 0); - // if (Space) - // { - // gl.disable(GL.DEPTH_TEST); - // } - // else - // { - // gl.enable(GL.DEPTH_TEST); - // } - //} - } - - - public double nearPlane = 0; - bool frustumDirty = true; - PlaneD[] frustum = new PlaneD[6]; - - public PlaneD[] Frustum - { - get - { - return frustum; - } - } - - private Color ambientLightColor = Colors.Black; - public Color AmbientLightColor - { - get - { - return ambientLightColor; - } - - set - { - ambientLightColor = value; - lightingStateDirty = true; - } - } - - private Color hemiLightColor = Colors.Black; - public Color HemisphereLightColor - { - get - { - return hemiLightColor; - } - - set - { - hemiLightColor = value; - lightingStateDirty = true; - } - } - - private Vector3d hemiLightUp = new Vector3d(); - public Vector3d HemisphereLightUp - { - get - { - return hemiLightUp; - } - - set - { - hemiLightUp = value; - lightingStateDirty = true; - } - } - - - private Color sunlightColor = Colors.White; - public Color SunlightColor - { - get - { - return sunlightColor; - } - - set - { - sunlightColor = value; - lightingStateDirty = true; - } - } - - private Vector3d sunPosition = new Vector3d(); - public Vector3d SunPosition - { - get - { - return sunPosition; - } - - set - { - sunPosition = value; - lightingStateDirty = true; - } - } - - private Color reflectedLightColor = Colors.Black; - public Color ReflectedLightColor - { - get - { - return reflectedLightColor; - } - - set - { - if (reflectedLightColor != value) - { - reflectedLightColor = value; - lightingStateDirty = true; - } - } - } - - private Vector3d reflectedLightPosition = new Vector3d(); - public Vector3d ReflectedLightPosition - { - get - { - return reflectedLightPosition; - } - - set - { - reflectedLightPosition = value; - lightingStateDirty = true; - } - } - - // Radius of a planet casting a shadow; zero when there's no shadow - private double occludingPlanetRadius = 0.0; - public double OccludingPlanetRadius - { - get - { - return occludingPlanetRadius; - } - - set - { - occludingPlanetRadius = value; - } - } - - private Vector3d occludingPlanetPosition = new Vector3d(); - public Vector3d OccludingPlanetPosition - { - get - { - return occludingPlanetPosition; - } - - set - { - occludingPlanetPosition = value; - } - } - - bool lightingStateDirty = true; - - private bool twoSidedLighting = false; - public bool TwoSidedLighting - { - get - { - return twoSidedLighting; - } - - set - { - if (value != twoSidedLighting) - { - twoSidedLighting = value; - lightingStateDirty = true; - } - } - } - - public Vector3d CameraPosition = new Vector3d(); - - public Matrix3d WVP; - public Matrix3d WV; - public void MakeFrustum() - { - WV = Matrix3d.MultiplyMatrix(World, View); - - Matrix3d viewProjection = Matrix3d.MultiplyMatrix(WV, Projection); - - WVP = viewProjection.Clone(); - - Matrix3d inverseWorld = World.Clone(); - inverseWorld.Invert(); - - // Left plane - frustum[0].A = viewProjection.M14 + viewProjection.M11; - frustum[0].B = viewProjection.M24 + viewProjection.M21; - frustum[0].C = viewProjection.M34 + viewProjection.M31; - frustum[0].D = viewProjection.M44 + viewProjection.M41; - - // Right plane - frustum[1].A = viewProjection.M14 - viewProjection.M11; - frustum[1].B = viewProjection.M24 - viewProjection.M21; - frustum[1].C = viewProjection.M34 - viewProjection.M31; - frustum[1].D = viewProjection.M44 - viewProjection.M41; - - // Top plane - frustum[2].A = viewProjection.M14 - viewProjection.M12; - frustum[2].B = viewProjection.M24 - viewProjection.M22; - frustum[2].C = viewProjection.M34 - viewProjection.M32; - frustum[2].D = viewProjection.M44 - viewProjection.M42; - - // Bottom plane - frustum[3].A = viewProjection.M14 + viewProjection.M12; - frustum[3].B = viewProjection.M24 + viewProjection.M22; - frustum[3].C = viewProjection.M34 + viewProjection.M32; - frustum[3].D = viewProjection.M44 + viewProjection.M42; - - // Near plane - frustum[4].A = viewProjection.M13; - frustum[4].B = viewProjection.M23; - frustum[4].C = viewProjection.M33; - frustum[4].D = viewProjection.M43; - - // Far plane - frustum[5].A = viewProjection.M14 - viewProjection.M13; - frustum[5].B = viewProjection.M24 - viewProjection.M23; - frustum[5].C = viewProjection.M34 - viewProjection.M33; - frustum[5].D = viewProjection.M44 - viewProjection.M43; - - // Normalize planes - for (int i = 0; i < 6; i++) - { - frustum[i].Normalize(); - - } - frustumDirty = false; - - WVP.Scale(Vector3d.Create(Width / 2, -Height / 2, 1)); - WVP.Translate(Vector3d.Create(Width / 2, Height / 2, 0)); - SetMatrixes(); - } - - string SkyColor = "Blue"; - - //internal WebGLShader frag; - //internal WebGLShader vert; - - //public int vertLoc; - //public int textureLoc; - //public WebGLUniformLocation projMatLoc; - //public WebGLUniformLocation mvMatLoc; - //public WebGLUniformLocation sampLoc; - internal void InitGL() - { - if (gl == null) - { - return; - } - - int uints_for_indices = gl.getExtension("OES_element_index_uint"); - - Tile.uvMultiple = 1; - Tile.DemEnabled = true; - - TileShader.Init(this); - } - - public void FreezeView() - { - targetAlt = alt; - targetAz = az; - - TargetCamera = ViewCamera.Copy(); - } - - internal void SetVertexBuffer(VertexBufferBase vertexBuffer) - { - } - - internal void SetIndexBuffer(IndexBuffer indexBuffer) - { - } - - // Set up a shader for the specified material properties and the - // current lighting environment. - public void SetMaterial(Material material, Texture diffuseTex, Texture specularTex, Texture normalMap, float opacity) - { - //todo - //PlanetSurfaceStyle surfaceStyle = PlanetSurfaceStyle.Diffuse; - //if (material.Specular != SysColor.FromArgb(255, 0, 0, 0)) - //{ - // surfaceStyle = PlanetSurfaceStyle.Specular; - //} - - //// Force the emissive style when lighting is disabled - //if (!lightingEnabled) - //{ - // surfaceStyle = PlanetSurfaceStyle.Emissive; - //} - - //PlanetShaderKey key = new PlanetShaderKey(surfaceStyle, false, 0); - //if (reflectedLightColor != SysColor.FromArgb(255, 0, 0, 0)) - //{ - // key.lightCount = 2; - //} - - //key.textures = 0; - //if (diffuseTex != null) - //{ - // key.textures |= PlanetShaderKey.SurfaceProperty.Diffuse; - //} - - //if (specularTex != null) - //{ - // key.textures |= PlanetShaderKey.SurfaceProperty.Specular; - //} - - //if (normalMap != null) - //{ - // key.textures |= PlanetShaderKey.SurfaceProperty.Normal; - //} - - //key.TwoSidedLighting = twoSidedLighting; - - //SetupPlanetSurfaceEffect(key, material.Opacity * opacity); - - //shader.DiffuseColor = new Vector4(material.Diffuse.R / 255.0f, material.Diffuse.G / 255.0f, material.Diffuse.B / 255.0f, material.Opacity * opacity); - //if (surfaceStyle == PlanetSurfaceStyle.Specular || surfaceStyle == PlanetSurfaceStyle.SpecularPass) - //{ - // shader.SpecularColor = new Vector4(material.Specular.R / 255.0f, material.Specular.G / 255.0f, material.Specular.B / 255.0f, 0.0f); - // shader.SpecularPower = material.SpecularSharpness; - //} - - MainTexture = diffuseTex; - - //if (diffuseTex != null) - //{ - // shader.MainTexture = diffuseTex.ResourceView; - //} - - //if (specularTex != null) - //{ - // shader.SpecularTexture = specularTex.ResourceView; - //} - - //if (normalMap != null) - //{ - // shader.NormalTexture = normalMap.ResourceView; - //} - } - - public void PreDraw() - { - //updateShaderTransformLightingConstants(); - //if (textureStateDirty) - //{ - // if (mainTexture != null && shader != null) - // { - // shader.MainTexture = mainTexture.ResourceView; - // } - // textureStateDirty = false; - //} - - //if (shader != null) - //{ - // shader.use(devContext); - //} - - //if (currentMode != (int)currentDepthStencilMode) - //{ - // devContext.OutputMerger.DepthStencilState = standardDepthStencilStates[(int)currentDepthStencilMode]; - // currentMode = (int)currentDepthStencilMode; - //} - } - //public PlanetShader SetupPlanetSurfaceEffect(PlanetShaderKey key, float opacity) - //{ - // return SetupPlanetSurfaceEffectShader(key, opacity); - //} - //private PlanetShader SetupPlanetSurfaceEffectShader(PlanetShaderKey key, float opacity) - //{ - // //todo - // //PlanetShader shader = PlanetShader11.GetPlanetShader(Device, key); - - // //// If we've got a shader, make it active on the device and set the - // //// shader constants. - // //if (shader != null) - // //{ - // // shader.use(Device.ImmediateContext); - - // // // Set the combined world/view/projection matrix in the shader - // // Matrix3d worldMatrix = World; - // // Matrix3d viewMatrix = View; - // // Matrix wvp = (worldMatrix * viewMatrix * Projection).Matrix; - // // if (RenderContext11.ExternalProjection) - // // { - // // wvp = wvp * ExternalScalingFactor; - // // } - - - // // shader.WVPMatrix = wvp; - // // shader.DiffuseColor = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); - - // // Matrix3d invWorld = worldMatrix; - // // invWorld.Invert(); - - // // // For view-dependent lighting (e.g. specular), we need the position of the camera - // // // in the planet-fixed coordinate system. - // // Matrix3d worldViewMatrix = worldMatrix * viewMatrix; - // // Matrix3d invWorldView = worldViewMatrix; - // // invWorldView.Invert(); - // // shader.WorldViewMatrix = worldViewMatrix.Matrix; - - // // Vector3d cameraPositionObj = Vector3d.TransformCoordinate(new Vector3d(0.0, 0.0, 0.0), invWorldView); - // // shader.CameraPosition = cameraPositionObj.Vector3; - // //} - - // //Shader = shader; - - // //return shader; - - // return null; - //} - } - //class PlanetShader - //{ - - //} -} diff --git a/engine/csharp_ref/RenderTriangle.cs b/engine/csharp_ref/RenderTriangle.cs deleted file mode 100644 index a1fc6b80..00000000 --- a/engine/csharp_ref/RenderTriangle.cs +++ /dev/null @@ -1,447 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class RenderTriangle - { - public PositionTexture A = new PositionTexture(); - public PositionTexture B = new PositionTexture(); - public PositionTexture C = new PositionTexture(); - - public Vector3d Normal = new Vector3d(); - - public void MakeNormal() - { - Vector3d a = A.Position.Copy(); - Vector3d b = B.Position.Copy(); - Vector3d c = C.Position.Copy(); - - a.Normalize(); - b.Normalize(); - c.Normalize(); - - - double x = a.X + b.X + c.X; - double y = a.Y + b.Y + c.Y; - double z = a.Z + b.Z + c.Z; - - Normal = Vector3d.Create(x / 3, y / 3, z / 3); - Normal.Normalize(); - } - - ImageElement texture; - public double Opacity = 1; - public static double Width = 1024; - public static double Height = 768; - - public double ExpansionInPixels = .6; - private const double ContractionInPixels = -0.5; - - private const bool isOutlined = false; - private const double halfPixel = 0.001953125; - private const double almostOne = 0.998; - - public static int TrianglesRendered = 0; - public static int TrianglesCulled = 0; - public static bool RenderingOn = true; - public int TileLevel = 0; - public static RenderTriangle Create(PositionTexture a, PositionTexture b, PositionTexture c, ImageElement img, int level) - { - RenderTriangle temp = new RenderTriangle(); - - temp.A = a.Copy(); - temp.B = b.Copy(); - temp.C = c.Copy(); - temp.texture = img; - temp.TileLevel = level; - temp.MakeNormal(); - return temp; - - } - - public static RenderTriangle CreateWithMiter(PositionTexture a, PositionTexture b, PositionTexture c, ImageElement img, int level, double expansion) - { - RenderTriangle temp = new RenderTriangle(); - temp.ExpansionInPixels = expansion; - temp.A = a.Copy(); - temp.B = b.Copy(); - temp.C = c.Copy(); - temp.texture = img; - temp.TileLevel = level; - temp.MakeNormal(); - return temp; - - } - - static double factor = 1; - - - - - //bool CheckBackface(Vector3d a, Vector3d b, Vector3d c) - bool CheckBackface() - { - - Vector3d ab = Vector3d.SubtractVectors(ta, tb); - Vector3d ac = Vector3d.SubtractVectors(ta, tc); - Vector3d cp = Vector3d.Cross(ab, ac); - cp.Normalize(); - - - return cp.Z >= 0; - } - - public static bool CullInside = true; - - Vector3d ta = new Vector3d(); - Vector3d tb = new Vector3d(); - Vector3d tc = new Vector3d(); - - - public void Draw(CanvasContext2D ctx, Matrix3d wvp) - { - if (ctx == null) - { - return; - } - - wvp.TransformTo(A.Position, ta); - wvp.TransformTo(B.Position, tb); - wvp.TransformTo(C.Position, tc); - - if (CheckBackface() == CullInside) - { - TrianglesCulled++; - return; - } - - //TrianglesRendered++; - - - - DrawTriangle(ctx, texture, ta.X, ta.Y, tb.X, tb.Y, tc.X, tc.Y, A.Tu, A.Tv, B.Tu, B.Tv, C.Tu, C.Tv); - - //if (rendered) - //{ - // TrianglesRendered++; - //} - //else - //{ - // TrianglesCulled++; - //} - } - - - static double hw; - static double qw; - static double hh; - static double qh; - - Vector2d expandedS0 = new Vector2d(); - Vector2d expandedS1 = new Vector2d(); - Vector2d expandedS2 = new Vector2d(); - - private bool DrawTriangle(CanvasContext2D ctx, ImageElement im, double x0, double y0, double x1, double y1, double x2, double y2, - double sx0, double sy0, double sx1, double sy1, double sx2, double sy2) - { - - if (!Intersects(0, Width, 0, Height, x0, y0, x1, y1, x2, y2)) - { - return false; - } - - //double edgeOffset = isOutlined ? ContractionInPixels : ExpansionInPixels; - //Vector2d expandedS0 = GetMiterPoint(Vector2d.Create(x0, y0), Vector2d.Create(x1, y1), Vector2d.Create(x2, y2), ExpansionInPixels); - //Vector2d expandedS1 = GetMiterPoint(Vector2d.Create(x1, y1), Vector2d.Create(x0, y0), Vector2d.Create(x2, y2), ExpansionInPixels); - //Vector2d expandedS2 = GetMiterPoint(Vector2d.Create(x2, y2), Vector2d.Create(x1, y1), Vector2d.Create(x0, y0), ExpansionInPixels); - - //Vector2d expandedS0 = MiterPoint(x0, y0, x1, y1, x2, y2); - //Vector2d expandedS1 = MiterPoint(x1, y1, x0, y0, x2, y2); - //Vector2d expandedS2 = MiterPoint(x2, y2, x1, y1, x0, y0); - MiterPointOut(expandedS0, x0, y0, x1, y1, x2, y2, ExpansionInPixels); - MiterPointOut(expandedS1, x1, y1, x0, y0, x2, y2, ExpansionInPixels); - MiterPointOut(expandedS2, x2, y2, x1, y1, x0, y0, ExpansionInPixels); - - x0 = expandedS0.X; - y0 = expandedS0.Y; - x1 = expandedS1.X; - y1 = expandedS1.Y; - x2 = expandedS2.X; - y2 = expandedS2.Y; - - - ctx.Save(); - if (RenderingOn) - { - - ctx.BeginPath(); - ctx.MoveTo(x0, y0); - ctx.LineTo(x1, y1); - ctx.LineTo(x2, y2); - ctx.ClosePath(); - ctx.Clip(); - } - double denom = sx0 * (sy2 - sy1) - sx1 * sy2 + sx2 * sy1 + (sx1 - sx2) * sy0; - //if (denom == 0) - //{ - // ctx.Restore(); - // return false; - //} - double m11 = -(sy0 * (x2 - x1) - sy1 * x2 + sy2 * x1 + (sy1 - sy2) * x0) / denom; - double m12 = (sy1 * y2 + sy0 * (y1 - y2) - sy2 * y1 + (sy2 - sy1) * y0) / denom; - double m21 = (sx0 * (x2 - x1) - sx1 * x2 + sx2 * x1 + (sx1 - sx2) * x0) / denom; - double m22 = -(sx1 * y2 + sx0 * (y1 - y2) - sx2 * y1 + (sx2 - sx1) * y0) / denom; - double dx = (sx0 * (sy2 * x1 - sy1 * x2) + sy0 * (sx1 * x2 - sx2 * x1) + (sx2 * sy1 - sx1 * sy2) * x0) / denom; - double dy = (sx0 * (sy2 * y1 - sy1 * y2) + sy0 * (sx1 * y2 - sx2 * y1) + (sx2 * sy1 - sx1 * sy2) * y0) / denom; - - - ctx.Transform(m11, m12, m21, m22, dx, dy); - - if (RenderingOn) - { - ctx.Alpha = Opacity; - - if (lighting < 1.0) - { - ctx.Alpha = 1; - ctx.FillStyle = "Black"; - ctx.FillRect(0, 0, Width, Height); - ctx.Alpha = lighting * Opacity; - } - - ctx.DrawImage(im, 0, 0); - } - - - - ctx.Restore(); - return true; - } - - public float lighting = 1; - - private static Vector2d GetMiterPoint(Vector2d p1, Vector2d p2, Vector2d p3, double edgeOffset) - { - Vector2d edge1 = Vector2d.Subtract(p2, p1); - Vector2d edge2 = Vector2d.Subtract(p3, p1); - edge1.Normalize(); - edge2.Normalize(); - Vector2d dir = Vector2d.Create(edge1.X + edge2.X, edge1.Y + edge2.Y); - dir.Normalize(); - Vector2d delta = Vector2d.Create(edge1.X - edge2.X, edge1.Y - edge2.Y); - double sineHalfAngle = delta.Length / 2; - double net = Math.Min(2, edgeOffset / sineHalfAngle); - - dir.Extend(net); - - return Vector2d.Create(p1.X-dir.X,p1.Y-dir.Y); - } - - private static Vector2d MiterPoint(double p1x, double p1y, double p2x, double p2y, double p3x, double p3y, double ExpansionInPixels) - { - //Vector2d edge1 = Vector2d.SubtractVector(p2, p1); - double e1x = p2x - p1x; - double e1y = p2y - p1y; - - //Vector2d edge2 = Vector2d.SubtractVector(p3, p1); - double e2x = p3x - p1x; - double e2y = p3y - p1y; - - //edge1.Normalize(); - double length = Math.Sqrt(e1x * e1x + e1y * e1y); - if (length != 0) - { - e1x /= length; - e1y /= length; - } - - //edge2.Normalize(); - length = Math.Sqrt(e2x * e2x + e2y * e2y); - if (length != 0) - { - e2x /= length; - e2y /= length; - } - //Vector2d dir = Vector2d.Create(edge1.X + edge2.X, edge1.Y + edge2.Y); - double dx = e1x + e2x; - double dy = e1y + e2y; - - //dir.Normalize(); - length = Math.Sqrt(dx * dx + dy * dy); - if (length != 0) - { - dx /= length; - dy /= length; - } - - //Vector2d delta = Vector2d.Create(edge1.X - edge2.X, edge1.Y - edge2.Y); - double deltax = e1x - e2x; - double deltay = e1y - e2y; - - //double sineHalfAngle = delta.Length / 2; - length = Math.Sqrt(deltax * deltax + deltay * deltay); - double sineHalfAngle = length / 2.0; - - double net = Math.Min(2, ExpansionInPixels / sineHalfAngle); - - //dir.Extend(net); - dx *= net; - dy *= net; - - //return Vector2d.Create(p1.X-dir.X,p1.Y-dir.Y); - return Vector2d.Create(p1x - dx, p1y - dy); - } - - private static void MiterPointOut(Vector2d pntOut, double p1x, double p1y, double p2x, double p2y, double p3x, double p3y, double ExpansionInPixels) - { - //Vector2d edge1 = Vector2d.SubtractVector(p2, p1); - double e1x = p2x - p1x; - double e1y = p2y - p1y; - - //Vector2d edge2 = Vector2d.SubtractVector(p3, p1); - double e2x = p3x - p1x; - double e2y = p3y - p1y; - - //edge1.Normalize(); - double length = Math.Sqrt(e1x * e1x + e1y * e1y); - if (length != 0) - { - e1x /= length; - e1y /= length; - } - - //edge2.Normalize(); - length = Math.Sqrt(e2x * e2x + e2y * e2y); - if (length != 0) - { - e2x /= length; - e2y /= length; - } - //Vector2d dir = Vector2d.Create(edge1.X + edge2.X, edge1.Y + edge2.Y); - double dx = e1x + e2x; - double dy = e1y + e2y; - - //dir.Normalize(); - length = Math.Sqrt(dx * dx + dy * dy); - if (length != 0) - { - dx /= length; - dy /= length; - } - - //Vector2d delta = Vector2d.Create(edge1.X - edge2.X, edge1.Y - edge2.Y); - double deltax = e1x - e2x; - double deltay = e1y - e2y; - - //double sineHalfAngle = delta.Length / 2; - length = Math.Sqrt(deltax * deltax + deltay * deltay); - double sineHalfAngle = length / 2.0; - - double net = Math.Min(2, ExpansionInPixels / sineHalfAngle); - - //dir.Extend(net); - dx *= net; - dy *= net; - - //return Vector2d.Create(p1.X-dir.X,p1.Y-dir.Y); - pntOut.X = p1x - dx; - pntOut.Y = p1y - dy; - } - - public bool Intersects(double l, double r, double t, double b, double x0, double y0, double x1, double y1, double x2, double y2) - { - if (x0 > l && x0 < r && y0 > t && y0 < b) - { - return true; - } - - if (x1 > l && x1 < r && y1 > t && y1 < b) - { - return true; - } - - if (x2 > l && x2 < r && y2 > t && y2 < b) - { - return true; - } - - double h4 = Height * 4; - if (TileLevel < 4 && ((Math.Abs(x0 - x1) > h4) || (Math.Abs(y0 - y1) > h4) || (Math.Abs(x2 - x1) > h4) || (Math.Abs(y2 - y1) > h4) || (Math.Abs(x0 - x2) > h4) || (Math.Abs(y0 - y2) > h4))) - { - return false; - } - - return lineRectangleIntersect(l, r, t, b, x0, y0, x1, y1) - || lineRectangleIntersect(l, r, t, b, x1, y1, x2, y2) - || lineRectangleIntersect(l, r, t, b, x2, y2, x0, y0); - - - - } - - - - - public bool lineRectangleIntersect(double l, double r, double t, double b, double x0, double y0, double x1, double y1) - { - double top_intersection; - double bottom_intersection; - double toptrianglepoint; - double bottomtrianglepoint; - - double m; - double c; - // Calculate m and c for the equation for the line (y = mx+c) - m = (y1 - y0) / (x1 - x0); - c = y0 - (m * x0); - - // if the line is going up from right to left then the top intersect point is on the left - if (m > 0) - { - top_intersection = (m * l + c); - bottom_intersection = (m * r + c); - } - // otherwise it's on the right - else - { - top_intersection = (m * r + c); - bottom_intersection = (m * l + c); - } - - // work out the top and bottom extents for the triangle - if (y0 < y1) - { - toptrianglepoint = y0; - bottomtrianglepoint = y1; - } - else - { - toptrianglepoint = y1; - bottomtrianglepoint = y0; - } - - double topoverlap; - double botoverlap; - - // and calculate the overlap between those two bounds - topoverlap = top_intersection > toptrianglepoint ? top_intersection : toptrianglepoint; - botoverlap = bottom_intersection < bottomtrianglepoint ? bottom_intersection : bottomtrianglepoint; - - // (topoverlapb)) : - // If the bottom overlap is higher than the top of the rectangle or the top overlap is - // lower than the bottom of the rectangle we don't have intersection. So return the negative - // of that. Much faster than checking each of the points is within the bounds of the rectangle. - return (topoverlap < botoverlap) && (!((botoverlap < t) || (topoverlap > b))); - - } - - - } -} diff --git a/engine/csharp_ref/ScriptInterface.cs b/engine/csharp_ref/ScriptInterface.cs deleted file mode 100644 index 11ec40df..00000000 --- a/engine/csharp_ref/ScriptInterface.cs +++ /dev/null @@ -1,805 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; -namespace wwtlib -{ - public delegate void ImagesetLoaded(ImageSetLayer imageset); - public class ScriptInterface - { - bool missedReady = false; - public event EventHandler Ready; - internal void FireReady() - { - - if (Ready != null) - { - Ready.Invoke(this, new EventArgs()); - } - else - { - missedReady = true; - } - } - - public event EventHandler CollectionLoaded; - - internal void FireCollectionLoaded(string url) - { - if (CollectionLoaded != null) - { - CollectionLoaded.Invoke(this, new CollectionLoadedEventArgs(url)); - } - } - - public event EventHandler ColorPickerDisplay; - - public event EventHandler VOTableDisplay; - public event EventHandler RefreshLayerManager; - - public event EventHandler Arrived; - public event EventHandler Clicked; - public event EventHandler AnnotationClicked; - - public event EventHandler ImageryLoaded; - - public event EventHandler TourReady; - public event EventHandler TourError; - public event EventHandler TourPaused; - - public event EventHandler TourResumed; - - public event EventHandler TourEnded; - - public event EventHandler SlideChanged; - - - public event EventHandler TimeScrubberHook; - //UI will set this to a function that takes 2 string properties (prop,val) - //("title", "left", or "right" for the labels, "pos" for the slider pos) - //Pass a 0-1 float to set the slider position (stringify it if you need to for strong typing) - - public void SetTimeScrubberPosition(double posLeft) - { - LayerManager.SetTimeSliderValue(posLeft); - } - - public void SetTimeSlider(string name, string value) - { - TimeScrubberHook.Invoke(name, (EventArgs)(object)value); - } - - public void ShowColorPicker(ColorPicker pickerInstance, EventArgs e) - { - if (ColorPickerDisplay != null) - { - ColorPickerDisplay.Invoke(pickerInstance, e); - } - } - - public void DisplayVoTableLayer(VoTableLayer layer) - { - if (VOTableDisplay != null) - { - VOTableDisplay.Invoke(layer, new EventArgs()); - } - } - - public void RefreshLayerManagerNow() - { - if (RefreshLayerManager != null) - { - RefreshLayerManager.Invoke(null, new EventArgs()); - } - } - internal void FireTourReady() - { - if (TourReady != null) - { - TourReady.Invoke(this, new EventArgs()); - } - } - internal void FireTourError(Exception ex) - { - if (TourError != null) - { - TourError.Invoke(ex, new EventArgs()); - } - } - internal void FireTourPaused() - { - if (TourPaused != null) - { - TourPaused.Invoke(this, new EventArgs()); - } - } - internal void FireTourResume() - { - if (TourResumed != null) - { - TourResumed.Invoke(this, new EventArgs()); - } - } - - internal void FireTourEnded() - { - if (TourEnded != null) - { - TourEnded.Invoke(this, new EventArgs()); - } - } - - internal void FireImageryLoaded() - { - if (ImageryLoaded != null) - { - ImageryLoaded.Invoke(this, new EventArgs()); - } - - } - - internal void FireClick(double ra, double dec) - { - if (Clicked != null) - { - Clicked.Invoke(this, new ArrivedEventArgs(ra, dec, WWTControl.Singleton.RenderContext.ViewCamera.Zoom)); - } - } - - internal void FireArrived(double ra, double dec, double zoom) - { - if (Arrived != null) - { - Arrived.Invoke(this, new ArrivedEventArgs(ra, dec, zoom)); - } - } - - - internal void FireAnnotationclicked(double RA, double Dec, string id) - { - try - { - if (AnnotationClicked != null) - { - AnnotationClicked.Invoke(this, new AnnotationClickEventArgs(RA, Dec, id)); - } - - } - catch - { - } - } - - internal void FireSlideChanged(string caption) - { - try - { - if (SlideChanged != null) - { - SlideChanged.Invoke(this, new SlideChangedEventArgs(caption)); - } - } - catch - { - } - } - - public void EndInit() - { - if (missedReady) - { - FireReady(); - } - } - - public void GotoRaDecZoom(double ra, double dec, double zoom, bool instant, double? roll) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.GotoRADecZoom(ra / 15, dec, zoom * 6, instant, roll); - } - } - - public void SetBackgroundImageByName(string name) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.SetBackgroundImageByName(name); - } - } - - // Call this to add a VOTable to layers - public VoTableLayer AddVoTableLayer(VoTable table) - { - return LayerManager.AddVoTableLayer(table, "Vo Table"); - } - - public Dictionary GetLayers() - { - return LayerManager.LayerList; - } - - public void SetForegroundImageByName(string name) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.SetForegroundImageByName(name); - WWTControl.Singleton.RenderContext.ViewCamera.Opacity = 100; - } - } - - - public void SetForegroundOpacity(double opacity) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.RenderContext.ViewCamera.Opacity = opacity; - } - } - - public void AddCatalogHipsByName(string name) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.AddCatalogHipsByName(name); - } - } - - public void AddCatalogHipsByNameWithCallback(string name, Action onLoad) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.AddCatalogHipsByNameWithCallback(name, onLoad); - } - } - - public void RemoveCatalogHipsByName(string name) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.RemoveCatalogHipsByName(name); - } - } - - public void GetCatalogHipsDataInView(string name, bool limit, Action onComplete) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.GetCatalogHipsDataInView(name, limit, onComplete); - } - } - - public void SetCutsForFits(string imagesetName, double min, double max) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.SetCutsForFits(imagesetName, min , max); - } - } - - public void SetColorMapForFits(string imagesetName, string colorMapName) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.SetColorMapForFits(imagesetName, colorMapName); - } - } - - public void SetScaleTypeForFits(string imagesetName, ScaleTypes scaleType) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.SetScaleTypeForFits(imagesetName, scaleType); - } - } - - - public void HideUI(bool hide) - { - //todo enable - ////App.NoUI = hide; - //this.ContextPanel.Visibility = hide ? Visibility.Collapsed : Visibility.Visible; - //this.Explorer.Visibility = hide ? Visibility.Collapsed : Visibility.Visible; - //this.TabMenus.Visibility = hide ? Visibility.Collapsed : Visibility.Visible; - //Viewer.MasterView.SetRenderNeeded(true, false); - } - public void LoadTour(string url) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.PlayTour(url); - } - - } - - public ImageSetLayer LoadFits(string url) - { - return LoadFitsLayer(url, "", true, null); - } - - public ImageSetLayer LoadFitsLayer(string url, string name, bool gotoTarget, ImagesetLoaded loaded) - { - return AddImageSetLayer(url, "fits", name, gotoTarget, loaded); - } - - public ImageSetLayer AddImageSetLayer(string url, string mode, string name, bool gotoTarget, ImagesetLoaded loaded) - { - if (mode != null && mode.ToLowerCase() == "fits") - { - return AddFitsLayer(url, name, gotoTarget, loaded); - } - else if (mode != null && mode.ToLowerCase() == "preloaded") - { - Imageset imageset = WWTControl.Singleton.GetImageSetByUrl(url); - if (imageset != null) - { - return AddImageSet(name, gotoTarget, loaded, imageset); - } - } - else - { - Imageset imageset = WWTControl.Singleton.GetImageSetByUrl(url); - if (imageset != null) - { - return AddImageSet(name, gotoTarget, loaded, imageset); - } - else if (ContainsFitsLikeExtentsion(url)) - { - return AddFitsLayer(url, name, gotoTarget, loaded); - } - } - return null; - } - - private static bool ContainsFitsLikeExtentsion(string url) - { - string lowerCaseUrl = url.ToLowerCase(); - return (lowerCaseUrl.EndsWith("fits") - || lowerCaseUrl.EndsWith("ftz") - || lowerCaseUrl.EndsWith("fit") - || lowerCaseUrl.EndsWith("fts") - ); - } - - private static ImageSetLayer AddImageSet(string name, bool gotoTarget, ImagesetLoaded loaded, Imageset imageset) - { - if (string.IsNullOrWhiteSpace(name)) - { - name = LayerManager.GetNextImageSetName(); - } - - ImageSetLayer imagesetLayer = LayerManager.AddImageSetLayerCallback(imageset, name, loaded); - - if (gotoTarget) - { - double zoom = imageset.GuessZoomSetting(WWTControl.Singleton.RenderContext.ViewCamera.Zoom); - - WWTControl.Singleton.GotoRADecZoom( - imageset.ViewCenterX / 15, - imageset.ViewCenterY, - zoom, - false, - null - ); - } - - return imagesetLayer; - } - - private static ImageSetLayer AddFitsLayer(string url, string name, bool gotoTarget, ImagesetLoaded loaded) - { - if (string.IsNullOrWhiteSpace(name)) - { - name = LayerManager.GetNextFitsName(); - } - - ImageSetLayer imagesetLayer = new ImageSetLayer(); - Imageset imageset = new Imageset(); - - WcsLoaded wcsLoaded = delegate (WcsImage wcsImage) - { - if (((FitsImage)wcsImage).errored) - { - return; - } - - int width = (int)wcsImage.SizeX; - int height = (int)wcsImage.SizeY; - //TODO make sure dataset URL is unique - imageset.SetInitialParameters( - wcsImage.Description, - wcsImage.Filename, - ImageSetType.Sky, - BandPass.Visible, - ProjectionType.SkyImage, - Util.GetHashCode(wcsImage.Filename), - 0, - 0, - wcsImage.ScaleY, - ".fits", - wcsImage.ScaleX > 0, - "", - wcsImage.CenterX, - wcsImage.CenterY, - wcsImage.Rotation, - false, - "", - false, - false, - 1, - wcsImage.ReferenceX, - wcsImage.ReferenceY, - wcsImage.Copyright, - wcsImage.CreditsUrl, - "", - "", - 0, - "" - ); - - imageset.WcsImage = wcsImage; - imagesetLayer.ImageSet = imageset; - LayerManager.AddFitsImageSetLayer(imagesetLayer, name); - - if (gotoTarget) - { - double zoom = imageset.GuessZoomSetting(WWTControl.Singleton.RenderContext.ViewCamera.Zoom); - - WWTControl.Singleton.GotoRADecZoom( - wcsImage.ViewCenterX / 15, - wcsImage.ViewCenterY, - zoom, - false, - null - ); - } - - if (loaded != null) - { - loaded(imagesetLayer); - } - }; - - if (string.IsNullOrWhiteSpace(name)) - { - name = LayerManager.GetNextFitsName(); - } - - if (RenderContext.UseGlVersion2) - { - new FitsImage(imageset, url, null, wcsLoaded); - } - else - { - new FitsImageJs(imageset, url, null, wcsLoaded); - } - return imagesetLayer; - } - - public void SetImageSetLayerOrder(Guid id, int order) - { - Layer layer = LayerManager.LayerList[id]; - if (layer is ImageSetLayer && order >= 0) { - LayerManager.AllMaps[layer.ReferenceFrame].Layers.Remove(layer); - //In case of order > Layers.length, the layer is properly put at the end of the list - LayerManager.AllMaps[layer.ReferenceFrame].Layers.Insert(order, layer); - } - } - - public bool IsUsingWebGl2() - { - return RenderContext.UseGlVersion2; - } - - public bool hideTourFeedback = false; - public bool HideTourFeedback - { - get - { - return hideTourFeedback; - } - set - { - hideTourFeedback = value; - } - } - - public void PlayTour() - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.PlayCurrentTour(); - } - - } - - public void StopTour() - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.StopCurrentTour(); - } - } - - private string imageUrl; - public void LoadImageCollection(string url, bool? loadChildFolders) - { - imageUrl = url; - Wtml.GetWtmlFile(url, delegate { FireCollectionLoaded(url); }, loadChildFolders); - } - - private void ImageFileLoaded() - { - FireCollectionLoaded(imageUrl); - } - - //public void CollectionReady() - //{ - // Folder wtml = Folder.LoadFromFileStream(e.Stream, true); - // foreach (object child in wtml.Children) - // { - // ImageSet imageset = null; - - - // if (child is ImageSet) - // { - // imageset = (ImageSet)child; - // Viewer.ImageSets.Add(imageset); - // } - // if (child is Place) - // { - // Place place = (Place)child; - // if (place.ForegroundImageSet != null) - // { - // Viewer.ImageSets.Add(place.ForegroundImageSet.ImageSet); - // } - // else if (place.BackgroundImageSet != null) - // { - // Viewer.ImageSets.Add(place.BackgroundImageSet.ImageSet); - // } - // } - // } - // FireCollectionLoaded(afc.Url); - //} - - public void Zoom(double factor) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.Zoom(factor); - } - return ; - } - - public double GetRA() - { - if (WWTControl.Singleton != null) - { - return WWTControl.Singleton.RenderContext.RA; - } - return 0; - } - - public double GetDec() - { - if (WWTControl.Singleton != null) - { - return WWTControl.Singleton.RenderContext.Dec; - } - return 0; - } - - public Folder CreateFolder() - { - Folder folder = new Folder(); - return folder; - } - - public Poly CreatePolygon(bool fill) - { - Poly p = new Poly(); - p.Fill = fill; - - return p; - } - - public PolyLine CreatePolyLine(bool fill) - { - return new PolyLine(); - } - - public Circle CreateCircle(bool fill) - { - Circle c = new Circle(); - c.Fill = fill; - return c; - } - - public void AddAnnotation(Annotation annotation) - { - if (annotation != null && annotation is Annotation) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.AddAnnotation(annotation); - } - } - } - - public void RemoveAnnotation(Annotation annotation) - { - if (annotation != null) - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.RemoveAnnotation(annotation); - } - } - } - - public void ClearAnnotations() - { - if (WWTControl.Singleton != null) - { - WWTControl.Singleton.ClearAnnotations(); - } - } - bool smoothAnimation = false; - public bool SmoothAnimation - { - get - { - return smoothAnimation; - } - set - { - smoothAnimation = value; - } - } - - bool showCaptions = true; - - public bool ShowCaptions - { - get { return showCaptions; } - set { showCaptions = value; } - } - - - public void LoadVOTable(string url, bool useCurrentView) - { - //if (VoTableView == null) - //{ - // VoTableView = new VoTableViewer(); - // VoTableView.Width = double.NaN; - // bottomStuff.Children.Add(VoTableView); - //} - - //if (!useCurrentView) - //{ - // VoTableView.Load(url); - //} - //else - //{ - // VoTableView.Load(url + string.Format("&ra={0}&dec={1}&sr={2}", Viewer.MasterView.RA * 15, Viewer.MasterView.Dec, Viewer.MasterView.FovAngle * 1.3)); - //} - } - public double Fov - { - get - { - if (WWTControl.Singleton != null) - { - return WWTControl.Singleton.RenderContext.ViewCamera.Zoom / 6; - } - return 60; - } - } - - public Settings Settings; - - } - - - public class SlideChangedEventArgs : EventArgs - { - private string caption; - - public string Caption - { - get { return caption; } - set { caption = value; } - } - - public SlideChangedEventArgs(string caption) - { - Caption = caption; - } - } - - - public class ArrivedEventArgs : EventArgs - { - private double ra; - - public double RA - { - get { return ra; } - set { ra = value; } - } - private double dec; - - public double Dec - { - get { return dec; } - set { dec = value; } - } - private double zoom; - - public double Zoom - { - get { return zoom; } - set { zoom = value; } - } - public ArrivedEventArgs(double ra, double dec, double zoom) - { - RA = ra * 15; - Dec = dec; - Zoom = zoom / 6; - } - - - } - - public class AnnotationClickEventArgs : EventArgs - { - private double ra; - - public double RA - { - get { return ra; } - set { ra = value; } - } - private double dec; - - public double Dec - { - get { return dec; } - set { dec = value; } - } - private string id; - - public string Id - { - get { return id; } - set { id = value; } - } - - public AnnotationClickEventArgs(double ra, double dec, string id) - { - RA = ra * 15; - Dec = dec; - Id = id; - } - - - } - - - public class CollectionLoadedEventArgs : EventArgs - { - private string url; - - public string Url - { - get { return url; } - set { url = value; } - } - - public CollectionLoadedEventArgs(string url) - { - this.url = url; - } - } -} diff --git a/engine/csharp_ref/Settings.cs b/engine/csharp_ref/Settings.cs deleted file mode 100644 index ec58e8b7..00000000 --- a/engine/csharp_ref/Settings.cs +++ /dev/null @@ -1,592 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -using System.Linq; - - -namespace wwtlib -{ - public class Settings : ISettings - { - static Settings active = null; - static public ISettings TourSettings = null; - static public Settings Current - { - get - { - if (active == null) - { - active = new Settings(); - } - return active; - } - } - - static public Settings GlobalSettings - { - get - { - if (active == null) - { - active = new Settings(); - } - return active; - } - } - - static public ISettings Active - { - get - { - if (active == null) - { - active = new Settings(); - } - if (TourSettings != null) - { - return TourSettings; - } - return active; - } - } - - public Settings() - { - } - public bool AutoRepeatTour = false; - private bool localHorizonMode = false; - private bool galacticMode = false; - private string constellationBoundryColor = "blue"; - private string constellationSelectionColor = "yellow"; - private string constellationFigureColor = "red"; - private bool showConstellationFigures = true; - private bool showConstellationBoundries = true; - private bool showConstellationSelection = true; - private bool showCrosshairs = true; - private string crosshairsColor = "white"; - private bool showEcliptic = false; - private double locationLat = 47.717; - private double locationLng = -122.08580; - private double locationAltitude = 100.0; - private bool showFiledOfView = false; - bool actualPlanetScale = true; - int fovCamera = 0; - int fovEyepiece = 0; - int fovTelescope = 0; - bool showClouds = false; - - - private bool showGrid = false; - private bool showHorizon = true; - private bool showHorizonPanorama = false; - private bool showMoonsAsPointSource = true; - private bool showSolarSystem = true; - private bool solarSystemStars = true; - private bool solarSystemMilkyWay = true; - private bool solarSystemCosmos = true; - private bool solarSystemOrbits = true; - private bool solarSystemOverlays = true; - private bool solarSystemLighting = true; - private bool solarSystemMultiRes = true; - private int solarSystemScale = 1; - private bool smoothPan = true; - - - public string ConstellationFigureColor - { - get { return constellationFigureColor; } - set { constellationFigureColor = value; } - } - - public string ConstellationBoundryColor - { - get { return constellationBoundryColor; } - set { constellationBoundryColor = value; } - } - - public string ConstellationSelectionColor - { - get { return constellationSelectionColor; } - set { constellationSelectionColor = value; } - } - - public bool ShowCrosshairs - { - get { return showCrosshairs; } - set { showCrosshairs = value; } - } - - public bool SmoothPan - { - get { return smoothPan; } - set { smoothPan = value; } - } - - public string CrosshairsColor - { - get { return crosshairsColor; } - set { crosshairsColor = value; } - } - - public bool ActualPlanetScale - { - get { return actualPlanetScale; } - set { actualPlanetScale = value; } - } - - public int FovCamera - { - get { return fovCamera; } - } - - public int FovEyepiece - { - get { return fovEyepiece; } - } - - public int FovTelescope - { - get { return fovTelescope; } - } - - public double LocationAltitude - { - get { return locationAltitude; } - set { locationAltitude = value; } - } - - public double LocationLat - { - get { return locationLat; } - set { locationLat = value; } - } - - public double LocationLng - { - get { return locationLng; } - set { locationLng = value; } - } - - public bool ShowClouds - { - get { return showClouds; } - } - - public bool ShowConstellationBoundries - { - get { return showConstellationBoundries; } - set { showConstellationBoundries = value; } - } - - public bool ShowConstellationFigures - { - get { return showConstellationFigures; } - set { showConstellationFigures = value; } - } - - public bool ShowConstellationSelection - { - get { return showConstellationSelection; } - set { showConstellationSelection = value; } - } - - public bool ShowEcliptic - { - get { return showEcliptic; } - set { showEcliptic = value; } - } - - bool showElevationModel = true; - - public bool ShowElevationModel - { - get { return showElevationModel; } - set { showElevationModel = value; } - } - - public bool ShowFieldOfView - { - get - { - return showFiledOfView; - } - - } - - public bool ShowGrid - { - get { return showGrid; } - set { showGrid = value; } - } - - public bool ShowHorizon - { - get { return showHorizon; } - set { showHorizon = value; } - } - - public bool ShowHorizonPanorama - { - get { return showHorizonPanorama; } - } - - public bool ShowMoonsAsPointSource - { - get { return showMoonsAsPointSource; } - } - - public bool ShowSolarSystem - { - get { return showSolarSystem; } - set { showSolarSystem = value; } - } - - public bool LocalHorizonMode - { - get { return localHorizonMode; } - set { localHorizonMode = value; } - } - - public bool GalacticMode - { - get { return galacticMode; } - set - { - galacticMode = value; - } - } - - public bool SolarSystemStars - { - get { return solarSystemStars; } - set { solarSystemStars = value; } - } - - public bool SolarSystemMilkyWay - { - get { return solarSystemMilkyWay; } - set { solarSystemMilkyWay = value; } - } - - public bool SolarSystemCosmos - { - get { return solarSystemCosmos; } - set { solarSystemCosmos = value; } - } - - public bool SolarSystemOrbits - { - get { return solarSystemOrbits; } - set { solarSystemOrbits = value; } - } - - public bool SolarSystemOverlays - { - get { return solarSystemOverlays; } - set { solarSystemOverlays = value; } - } - - public bool SolarSystemLighting - { - get { return solarSystemLighting; } - set { solarSystemLighting = value; } - } - - public bool SolarSystemMultiRes - { - get { return true; } - set { solarSystemMultiRes = value; } - } - - public int SolarSystemScale - { - get { return solarSystemScale; } - set { solarSystemScale = value; } - } - - bool showEquatorialGridText = false; - - public bool ShowEquatorialGridText - { - get { return showEquatorialGridText; } - set { showEquatorialGridText = value; } - } - - bool showGalacticGrid = false; - public bool ShowGalacticGrid - { - get { return showGalacticGrid; } - set { showGalacticGrid = value; } - } - - bool showGalacticGridText = false; - - public bool ShowGalacticGridText - { - get { return showGalacticGridText; } - set { showGalacticGridText = value; } - } - bool showEclipticGrid = false; - public bool ShowEclipticGrid - { - get { return showEclipticGrid; } - set { showEclipticGrid = value; } - } - - private bool showEclipticGridText = false; - - public bool ShowEclipticGridText - { - get { return showEclipticGridText; } - set { showEclipticGridText = value; } - } - private bool showEclipticOverviewText = false; - - public bool ShowEclipticOverviewText - { - get { return showEclipticOverviewText; } - set { showEclipticOverviewText = value; } - } - private bool showAltAzGrid = false; - - public bool ShowAltAzGrid - { - get { return showAltAzGrid; } - set { showAltAzGrid = value; } - } - - private Color eclipticGridColor = Colors.Green; - public Color EclipticGridColor - { - get { return eclipticGridColor; } - set { eclipticGridColor = value; } - } - - private Color galacticGridColor = Colors.Cyan; - public Color GalacticGridColor - { - get { return galacticGridColor; } - set { galacticGridColor = value; } - } - - private Color altAzGridColor = Colors.Magenta; - public Color AltAzGridColor - { - get { return altAzGridColor; } - set { altAzGridColor = value; } - } - - private Color precessionChartColor = Colors.Orange; - public Color PrecessionChartColor - { - get { return precessionChartColor; } - set { precessionChartColor = value; } - } - - private Color eclipticColor = Colors.Blue; - public Color EclipticColor - { - get { return eclipticColor; } - set { eclipticColor = value; } - } - - private Color equatorialGridColor = Colors.White; - public Color EquatorialGridColor - { - get { return equatorialGridColor; } - set { equatorialGridColor = value; } - } - - private bool showAltAzGridText = false; - public bool ShowAltAzGridText - { - get { return showAltAzGridText; } - set { showAltAzGridText = value; } - } - private bool showPrecessionChart = false; - - public bool ShowPrecessionChart - { - get { return showPrecessionChart; } - set { showPrecessionChart = value; } - } - private bool showConstellationPictures = false; - - public bool ShowConstellationPictures - { - get { return showConstellationPictures; } - set { showConstellationPictures = value; } - } - private bool showConstellationLabels = false; - - public bool ShowConstellationLabels - { - get { return showConstellationLabels; } - set { showConstellationLabels = value; } - } - - private int constellationLabelsHeight = 80; - public int ConstellationLabelsHeight - { - get { return constellationLabelsHeight; } - set { constellationLabelsHeight = value; } - } - - //public string ConstellationsEnabled = false; - - bool solarSystemCMB = true; - public bool SolarSystemCMB - { - get { return solarSystemCMB; } - set { solarSystemCMB= value;} - } - bool solarSystemMinorPlanets = false; - - public bool SolarSystemMinorPlanets - { - get { return solarSystemMinorPlanets; } - set { solarSystemMinorPlanets = value;} - } - - bool solarSystemPlanets = true; - public bool SolarSystemPlanets - { - get { return solarSystemPlanets; } - set { solarSystemPlanets = value;} - } - - bool showEarthSky = true; - public bool ShowEarthSky - { - get { return showEarthSky; } - set { showEarthSky = value;} - } - - bool solarSystemMinorOrbits = false; - public bool SolarSystemMinorOrbits - { - get { return solarSystemMinorOrbits; } - set { solarSystemMinorOrbits = value;} - } - - string constellationsEnabled = ""; - public string ConstellationsEnabled - { - get { return constellationsEnabled; } - set { constellationsEnabled = value;} - } - - ConstellationFilter constellationFiguresFilter = new ConstellationFilter(); - public ConstellationFilter ConstellationFiguresFilter - { - get { return constellationFiguresFilter; } - set { constellationFiguresFilter = value;} - } - - ConstellationFilter constellationBoundariesFilter= new ConstellationFilter(); - public ConstellationFilter ConstellationBoundariesFilter - { - get { return constellationBoundariesFilter; } - set { constellationBoundariesFilter = value;} - } - - ConstellationFilter constellationNamesFilter = new ConstellationFilter(); - public ConstellationFilter ConstellationNamesFilter - { - get { return constellationNamesFilter; } - set { constellationNamesFilter = value;} - } - - ConstellationFilter constellationArtFilter = new ConstellationFilter(); - public ConstellationFilter ConstellationArtFilter - { - get { return constellationArtFilter; } - set { constellationArtFilter = value;} - } - - bool showSkyOverlays = true; - public bool ShowSkyOverlays - { - get { return showSkyOverlays; } - set { showSkyOverlays = value;} - } - bool showConstellations = true; - public bool ShowConstellations - { - get { return showConstellations; } - set { showConstellations = value;} - } - - bool showSkyNode = true; - public bool ShowSkyNode - { - get { return showSkyNode; } - set { showSkyNode = value;} - } - - bool showSkyGrids = true; - public bool ShowSkyGrids - { - get { return showSkyGrids; } - set { showSkyGrids = value;} - } - - bool showSkyOverlaysIn3d = true; - public bool ShowSkyOverlaysIn3d - { - get { return showSkyOverlaysIn3d; } - set { showSkyOverlaysIn3d = value;} - } - - - bool earthCutawayView = false; - public bool EarthCutawayView - { - get { return earthCutawayView; } - set { earthCutawayView = value;} - } - - bool showISSModel = false; - public bool ShowISSModel - { - get { return showISSModel; } - set { showISSModel = value;} - } - - bool milkyWayModel = false; - public bool MilkyWayModel - { - get { return milkyWayModel; } - set { milkyWayModel = value;} - } - - int minorPlanetsFilter = 255; - public int MinorPlanetsFilter - { - get { return minorPlanetsFilter; } - set { minorPlanetsFilter = value;} - } - - int planetOrbitsFilter = 2147483647; - public int PlanetOrbitsFilter - { - get { return planetOrbitsFilter; } - set { planetOrbitsFilter = value;} - } - bool constellations = true; - public bool Constellations - { - get { return constellations; } - set { constellations = value; } - } - - public SettingParameter GetSetting(StockSkyOverlayTypes type) - { - if (type == StockSkyOverlayTypes.FadeToBlack) - { - return new SettingParameter(true, 0, 0 != 0, null); - } - return new SettingParameter(false, 1, false, null); - } - } -} diff --git a/engine/csharp_ref/SkyImageTile.cs b/engine/csharp_ref/SkyImageTile.cs deleted file mode 100644 index c7e82cc1..00000000 --- a/engine/csharp_ref/SkyImageTile.cs +++ /dev/null @@ -1,69 +0,0 @@ - - - - -namespace wwtlib -{ - public class SkyImageTile : TangentTile - { - public double PixelCenterX = 0.0; - public double PixelCenterY = 0.0; - public double ScaleX = .01; - public double ScaleY = .01; - public double Height = 0; - public double Width = 0; - public SkyImageTile(int level, int x, int y, Imageset dataset, Tile parent) : base(level, x, y, dataset, parent) - { - PixelCenterX = dataset.OffsetX; - PixelCenterY = dataset.OffsetY; - ScaleX = -(ScaleY = dataset.BaseTileDegrees); - if (dataset.BottomsUp) - { - ScaleX = -ScaleX; - } - this.sphereCenter = this.GeoTo3dTan(0, 0); - this.radius = 1.25f; - this.ComputeBoundingSphere(); - } - - protected override LatLngEdges GetLatLngEdges() - { - LatLngEdges edges = new LatLngEdges(); - - WcsImage wcsImage = dataset.WcsImage as WcsImage; - - if (wcsImage != null && RenderContext.UseGl) - { - if (RenderContext.UseGlVersion2) - { - Width = wcsImage.SizeX; - Height = wcsImage.SizeY; - } else - { - Height = bmp.Height; - Width = bmp.Width; - if (bmp.Height != wcsImage.SizeY) - { - PixelCenterY += bmp.Height - wcsImage.SizeY; - } - } - } - else if (texture != null) - { - Height = texture.NaturalHeight; - Width = texture.NaturalWidth; - } else - { - Height = 256; - Width = 256; - } - - edges.latMin = 0 + (ScaleY * (Height - PixelCenterY)); - edges.latMax = 0 - (ScaleY * PixelCenterY); - edges.lngMin = 0 + (ScaleX * PixelCenterX); - edges.lngMax = 0 - (ScaleX * (Width - PixelCenterX)); - return edges; - } - - } -} diff --git a/engine/csharp_ref/SkyText.cs b/engine/csharp_ref/SkyText.cs deleted file mode 100644 index 42617cac..00000000 --- a/engine/csharp_ref/SkyText.cs +++ /dev/null @@ -1,753 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class Text3dBatch - { - public int Height = 128; - //public Text3dBatch() - //{ - //} - - public Text3dBatch(int height) - { - Height = (int)(height * 3f); - } - - //public Text3dBatch(GlyphCache glyphCache) - //{ - // Height = glyphCache.Height; - - //} - - public List Items = new List(); - - public void Add(Text3d newItem) - { - Items.Add(newItem); - } - int glyphVersion = -1; - - public Matrix3d ViewTransform = Matrix3d.Identity; - - public void Draw(RenderContext renderContext, float opacity, Color color) - { - - - if (renderContext.gl == null) - { - Vector3d viewPoint = Vector3d.TransformCoordinate(renderContext.ViewPoint, ViewTransform); - - double drawHeight = (Height / renderContext.FovAngle) * renderContext.Height / 180; - - foreach (Text3d t3d in Items) - { - Vector3d screenSpacePnt = renderContext.WVP.Transform(t3d.center); - if (screenSpacePnt.Z < 0) - { - continue; - } - - if (Vector3d.Dot((Vector3d)viewPoint, (Vector3d)t3d.center) < .55) - { - continue; - } - - Vector3d screenSpaceTop = renderContext.WVP.Transform(t3d.top); - - double rotation = Math.Atan2(screenSpacePnt.X - screenSpaceTop.X, screenSpacePnt.Y - screenSpaceTop.Y); - - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - - ctx.Translate(screenSpacePnt.X, screenSpacePnt.Y); - ctx.Rotate(-rotation); // todo update with up vector - ctx.Alpha = opacity; - ctx.FillStyle = color.ToString(); - ctx.Font = "normal" + " " + (false ? "bold" : "normal") + " " + Math.Round(drawHeight * 1.2).ToString() + "px " + "Arial"; - ctx.TextBaseline = TextBaseline.Top; - - TextMetrics tm = ctx.MeasureText(t3d.Text); - - ctx.FillText(t3d.Text, -tm.Width / 2, -drawHeight / 2); - ctx.Restore(); - } - } - else - { - // gl version - if (glyphCache == null || glyphCache.Version > glyphVersion) - { - PrepareBatch(); - } - if (glyphCache.Ready == false) - { - return; - } - - - TextShader.Use(renderContext, vertexBuffer.VertexBuffer, glyphCache.Texture.Texture2d); - - renderContext.gl.drawArrays(GL.TRIANGLES, 0, vertexBuffer.Count); - - - - } - } - - GlyphCache glyphCache; - - TextObject TextObject = new TextObject(); - PositionTextureVertexBuffer vertexBuffer; - public void PrepareBatch() - { - if (glyphCache == null) - { - glyphCache = GlyphCache.GetCache(Height); - } - - if (glyphCache.Ready == false) - { - return; - } - - // Add All Glyphs - - //foreach (Text3d t3d in Items) - //{ - // foreach (char c in t3d.Text) - // { - // glyphCache.AddGlyph(c); - // } - //} - - //// Calculate Metrics - - TextObject.Text = ""; - TextObject.FontSize = (float)Height * .50f; - - //System.Drawing.Font font = TextObject.Font; - //StringFormat sf = new StringFormat(); - //sf.Alignment = StringAlignment.Near; - - //Bitmap bmp = new Bitmap(20, 20); - //Graphics g = Graphics.FromImage(bmp); - //// Create Index Buffers - - List verts = new List(); - foreach (Text3d t3d in Items) - { - String text = t3d.Text; - float left = 0; - float top = 0; - float fntAdjust = TextObject.FontSize / 128f; - float factor = .6666f; - float width = 0; - float height = 0; - for (int i = 0; i < text.Length; i++) - { - GlyphItem item = glyphCache.GetGlyphItem(text.Substr(i, 1)); - if (item != null) - { - width += (float)(item.Extents.X); - height = Math.Max(item.Extents.Y, height); - } - } - - Vector2d size = Vector2d.Create(width, height); - - t3d.width = size.X * (float)t3d.scale * factor * fntAdjust; - t3d.height = size.Y * (float)t3d.scale * factor * fntAdjust; - - - int charsLeft = text.Length; - - for (int i = 0; i < charsLeft; i++) - { - GlyphItem item = glyphCache.GetGlyphItem(text.Substr(i, 1)); - if (item != null) - { - Rectangle position = Rectangle.Create(left * (float)t3d.scale * factor, 0 * (float)t3d.scale * factor, item.Extents.X * fntAdjust * (float)t3d.scale * factor, item.Extents.Y * fntAdjust * (float)t3d.scale * factor); - left += (float)(item.Extents.X * fntAdjust); - - //System.Diagnostics.Debug.WriteLine((position.Width/position1.Width).ToString() + ", " + (position.Height / position1.Height).ToString()); - - t3d.AddGlyphPoints(verts, item.Size, position, item.UVRect); - } - } - } - - - vertCount = verts.Count; - vertexBuffer = new PositionTextureVertexBuffer(vertCount); - - PositionTexture[] vertBuf = (PositionTexture[])vertexBuffer.Lock(); // Lock the buffer (which will return our structs) - - for (int i = 0; i < vertCount; i++) - { - vertBuf[i] = verts[i]; - } - - vertexBuffer.Unlock(); - - glyphVersion = glyphCache.Version; - } - int vertCount = 0; - - public void CleanUp() - { - if (vertexBuffer != null) - { - vertexBuffer = null; - } - //if (glyphCache != null) - //{ - // glyphCache.CleanUp(); - // glyphCache = null; - //} - - Items.Clear(); - } - - } - - - public class GlyphItem - { - - public GlyphItem(string glyph) - { - Glyph = glyph; - UVRect = new Rectangle(); - Size = new Vector2d(); - ReferenceCount = 1; - } - - public static GlyphItem Create(string glyph, Rectangle uv, Vector2d size, Vector2d extents) - { - GlyphItem temp = new GlyphItem(glyph); - temp.Glyph = glyph; - temp.UVRect = uv; - temp.Size = size; - temp.Extents = extents; - temp.ReferenceCount = 1; - - return temp; - } - - public void AddRef() - { - ReferenceCount++; - } - - public void Release() - { - ReferenceCount--; - } - - public string Glyph; - public Rectangle UVRect; - public Vector2d Size; - public Vector2d Extents; - public int ReferenceCount = 0; - - - internal static GlyphItem FromXML(XmlNode node) - { - string glyph = node.Attributes.GetNamedItem("Glyph").Value; - - GlyphItem item = new GlyphItem(glyph); - item.UVRect = Rectangle.Create( - double.Parse(node.Attributes.GetNamedItem("UVLeft").Value), - double.Parse(node.Attributes.GetNamedItem("UVTop").Value), - double.Parse(node.Attributes.GetNamedItem("UVWidth").Value), - double.Parse(node.Attributes.GetNamedItem("UVHeight").Value) - ); - - item.Size = Vector2d.Create( - double.Parse(node.Attributes.GetNamedItem("SizeWidth").Value), - double.Parse(node.Attributes.GetNamedItem("SizeHeight").Value)); - - item.Extents = Vector2d.Create( - double.Parse(node.Attributes.GetNamedItem("ExtentsWidth").Value), - double.Parse(node.Attributes.GetNamedItem("ExtentsHeight").Value)); - - return item; - } - } - - public class GlyphCache : IDisposable - { - static Dictionary caches = new Dictionary(); - - static public GlyphCache GetCache(int height) - { - if (!caches.ContainsKey(height)) - { - caches[height] = new GlyphCache(height); - } - return caches[height]; - } - - static public void CleanUpAll() - { - //foreach (GlyphCache cache in caches.Values) - //{ - // cache.CleanUp(); - //} - - caches.Clear(); - } - - Texture texture; - - int cellHeight = 128; - - public int Height - { - get - { - return cellHeight; - } - } - int gridSize = 8; - - //public GlyphCache() - //{ - - //} - - private WebFile webFile; - - private GlyphCache(int height) - { - cellHeight = height; - texture = Planets.LoadPlanetTexture(URLHelpers.singleton.engineAssetUrl("glyphs1.png")); - - webFile = new WebFile(URLHelpers.singleton.engineAssetUrl("glyphs1.xml")); - webFile.OnStateChange = GlyphXmlReady; - webFile.Send(); - } - - private void GlyphXmlReady() - { - if (webFile.State == StateType.Error) - { - Script.Literal("alert({0})", webFile.Message); - } - else if (webFile.State == StateType.Received) - { - LoadXmlGlyph(webFile.GetXml()); - - } - } - - public bool Ready = false; - private void LoadXmlGlyph(XmlDocument xml) - { - XmlNode nodes = Util.SelectSingleNode(xml, "GlyphItems"); - - foreach (XmlNode glyphItem in nodes.ChildNodes) - { - if (glyphItem.Name == "GlyphItem") - { - GlyphItem item = GlyphItem.FromXML(glyphItem); - - GlyphItems[item.Glyph] = item; - allGlyphs = allGlyphs + item.Glyph; - } - } - Ready = true; - - } - - public Texture Texture - { - get - { - - - return texture; - } - } - - private void MakeTexture() - { - CalcOrMake(true); - } - - Dictionary GlyphItems = new Dictionary(); - - public GlyphItem GetGlyphItem(string glyph) - { - if (dirty) - { - CalculateGlyphDetails(); - } - return GlyphItems[glyph]; - } - - public TextObject TextObject = new TextObject(); - - private void CalculateGlyphDetails() - { - CalcOrMake(false); - } - - private void CalcOrMake(bool makeTexture) - { - - //gridSize = 1; - - //while ((gridSize * gridSize) < GlyphItems.Count) - //{ - // gridSize *= 2; - //} - - //int cellSize = 2; - - //while (cellSize < cellHeight) - //{ - // cellSize *= 2; - //} - //cellHeight = cellSize; - - //int textureSize = cellHeight * gridSize; - - //TextObject.Text = ""; - //TextObject.FontSize = (float)cellHeight * .50f; - - - //System.Drawing.Font font = TextObject.Font; - //StringFormat sf = new StringFormat(); - //sf.Alignment = StringAlignment.Near; - - //Bitmap bmp; - //if (makeTexture) - //{ - // bmp = new Bitmap(textureSize, textureSize); - //} - //else - //{ - // bmp = new Bitmap(20, 20); - //} - - //Graphics g = Graphics.FromImage(bmp); - - //int count = 0; - - ////g.Clear(Color.Blue); - - //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - - //g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - - - //CharacterRange[] ranges = new CharacterRange[1]; - //ranges[0] = new CharacterRange(0, 1); - - //sf.SetMeasurableCharacterRanges(ranges); - - - - //foreach (GlyphItem item in GlyphItems.Values) - //{ - // int x = (int)(count % gridSize) * cellHeight; - // int y = (int)(count / gridSize) * cellHeight; - // string text = new string(item.Glyph, 1); - // item.Size = g.MeasureString(text, font); - // Region[] reg = g.MeasureCharacterRanges(text, font, new RectangleF(new PointF(0, 0), item.Size), sf); - // RectangleF rectf = reg[0].GetBounds(g); - - // float div = textureSize; - // item.UVRect = new RectangleF(x / div, y / div, item.Size.Width / div, item.Size.Height / div); - // item.UVRect = new RectangleF((x + rectf.X) / div, (y + rectf.Y) / div, rectf.Width / div, rectf.Height / div); - // if (makeTexture) - // { - // g.DrawString(text, font, Brushes.White, x, y, sf); - // } - // count++; - //} - - //g.Dispose(); - //GC.SuppressFinalize(g); - //if (makeTexture) - //{ - // if (texture != null) - // { - // texture.Dispose(); - // GC.SuppressFinalize(texture); - // texture = null; - // } - // texture = Texture11.FromBitmap(RenderContext11.PrepDevice, bmp); - // textureDirty = false; - // //Earth3d.MainWindow.ShowDebugBitmap(bmp); - //} - //else - //{ - // textureDirty = true; - //} - ////bmp.Dispose(); - //GC.SuppressFinalize(bmp); - //dirty = false; - - } - - - - bool dirty = true; - bool textureDirty = true; - int version = 0; - - public int Version - { - get { return version; } - set { version = value; } - } - - static string allGlyphs = ""; - - public void AddGlyph(string glyph) - { - if (!GlyphItems.ContainsKey(glyph)) - { - GlyphItem item = new GlyphItem(glyph); - GlyphItems[glyph] = item; - dirty = true; - textureDirty = true; - version++; - allGlyphs = allGlyphs + glyph.ToString(); - } - else - { - GlyphItems[glyph].AddRef(); - } - } - - - - - - public void CleanUp() - { - dirty = true; - texture = null; - } - - - - #region IDisposable Members - - public void Dispose() - { - CleanUp(); - } - - #endregion - - public bool Dirty - { - get - { - return dirty; - } - set - { - dirty = value; - } - } - } - - public enum Alignment - { - Center = 0, - Left = 1 - } - - public class Text3d - { - //public Text3d() - //{ - - //} - - - public Text3d(Vector3d center, Vector3d up, string text, float fontsize, double scale) - { - Text = text; - this.up = up; - this.center = center; - this.scale = scale; - this.top = Vector3d.AddVectors(center,Vector3d.Scale(up, scale)); - - if (fontsize < 0) - { - sky = false; - } - } - - public double Rotation = 0; - public double Tilt = 0; - public double Bank = 0; - Matrix3d rtbMat; - bool matInit = false; - - public Color Color = Colors.White; - public bool sky = true; - public Vector3d center; - public Vector3d up; - public Vector3d top; - public double scale; - public float Opacity = 1.0f; - public string Text = ""; - - public double width = 1; - public double height = 1; - - public Alignment alignment = Alignment.Center; - - public void AddGlyphPoints(List pointList, Vector2d size, Rectangle position, Rectangle uv) - { - PositionTexture[] points = new PositionTexture[6]; - - for(int i=0; i<6;i++) - { - points[i] = new PositionTexture(); - } - - - - Vector3d left = Vector3d.Cross(center, up); - Vector3d right = Vector3d.Cross(up, center); - - left.Normalize(); - right.Normalize(); - up.Normalize(); - - Vector3d upTan = Vector3d.Cross(center, right); - - upTan.Normalize(); - - if (alignment == Alignment.Center) - { - left.Multiply(width - position.Left * 2); - right.Multiply(width - ((width * 2) - position.Right * 2)); - } - else if (alignment == Alignment.Left) - { - left.Multiply(-position.Left * 2); - right.Multiply(position.Right * 2); - } - - Vector3d top = upTan.Copy(); - Vector3d bottom = Vector3d.SubtractVectors(Vector3d.Empty,upTan); - - top.Multiply(height - position.Top * 2); - bottom.Multiply(height - ((height * 2) - position.Bottom * 2)); - Vector3d ul = center.Copy(); - ul.Add(top); - if (sky) - { - ul.Add(left); - } - else - { - ul.Subtract(left); - } - Vector3d ur = center.Copy(); - ur.Add(top); - if (sky) - { - ur.Add(right); - } - else - { - ur.Subtract(right); - } - Vector3d ll = center.Copy(); - if (sky) - { - ll.Add(left); - } - else - { - ll.Subtract(left); - } - - ll.Add(bottom); - - Vector3d lr = center.Copy(); - if (sky) - { - lr.Add(right); - } - else - { - lr.Subtract(right); - } - lr.Add(bottom); - - points[0].Position = ul.Copy(); - points[0].Tu = uv.Left; - points[0].Tv = uv.Top; - // points[0].Color = Color; - - points[2].Tu = uv.Left; - points[2].Tv = uv.Bottom; - points[2].Position = ll.Copy(); - // points[2].Color = Color; - - points[1].Tu = uv.Right; - points[1].Tv = uv.Top; - points[1].Position = ur.Copy(); - // points[1].Color = Color; - - points[3].Tu = uv.Right; - points[3].Tv = uv.Bottom; - points[3].Position = lr.Copy(); - // points[3].Color = Color; - - points[5].Tu = uv.Right; - points[5].Tv = uv.Top; - points[5].Position = ur.Copy(); - // points[5].Color = Color; - - points[4].Tu = uv.Left; - points[4].Tv = uv.Bottom; - points[4].Position = ll.Copy(); - // points[4].Color = Color; - - if (Rotation != 0 || Tilt != 0 || Bank != 0) - { - if (!matInit) - { - Matrix3d lookAt = Matrix3d.LookAtLH(center, new Vector3d(), up); - Matrix3d lookAtInv = lookAt.Clone(); - lookAtInv.Invert(); - - rtbMat = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix( Matrix3d.MultiplyMatrix(lookAt, Matrix3d.RotationZ(-Rotation / 180 * Math.PI)), Matrix3d.RotationX(-Tilt / 180 * Math.PI)), Matrix3d.RotationY(-Bank / 180 * Math.PI)), lookAtInv); - //todo make this true after debug - matInit = true; - } - for (int i = 0; i < 6; i++) - { - points[i].Position = Vector3d.TransformCoordinate(points[i].Position, rtbMat); - } - } - - foreach (PositionTexture pnt in points) - { - pointList.Add(pnt); - } - } - - } - -} diff --git a/engine/csharp_ref/SpaceTimeController.cs b/engine/csharp_ref/SpaceTimeController.cs deleted file mode 100644 index 192e0bb4..00000000 --- a/engine/csharp_ref/SpaceTimeController.cs +++ /dev/null @@ -1,336 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - public class SpaceTimeController - { - static public void UpdateClock() - { - if (syncToClock) - { - Date justNow = MetaNow; - - if (timeRate != 1.0) - { - int ts = justNow.GetTime() - last.GetTime(); - int ticks = (int)(ts * timeRate); - offset += ticks; - } - last = justNow; - try - { - //now = new Date(justNow.GetTime()); - now = new Date(justNow.GetTime() + offset); - - } - catch - { - now = new Date(1, 12, 25, 23, 59, 59); - offset = now - MetaNow; - } - - if (now.GetFullYear() > 4000) - { - now = new Date(4000, 12, 31, 23, 59, 59); - offset = now - MetaNow; - } - - if (now.GetFullYear() < 1) - { - now = new Date(0, 12, 25, 23, 59, 59); - offset = now - MetaNow; - } - - } - } - - static public Date GetTimeForFutureTime(double delta) - { - try - { - if (syncToClock) - { - Date future = new Date ((int)((int)Now.GetTime() + (delta * 1000) * timeRate)); - return future; - } - else - { - return Now; - } - } - catch - { - return Now; - } - } - static public double GetJNowForFutureTime(double delta) - { - try - { - if (syncToClock) - { - Date future =new Date(Now.GetTime() +(int)(delta * 1000 * timeRate)); - return UtcToJulian(future); - } - else - { - return UtcToJulian(Now); - } - } - catch - { - return UtcToJulian(Now); - } - } - static public Date Now - { - get - { - return now; - } - set - { - now = value; - offset = now - MetaNow; - last = MetaNow; - } - } - public static Date last = MetaNow; - - public static double FramesPerSecond = 30; - - public static bool FrameDumping = false; - public static bool CancelFrameDump = false; - - public static int CurrentFrameNumber = 0; - public static int TotalFrames = 0; - - static Date metaNow = Date.Now; - public static Date MetaNow - { - get - { - return metaNow; - } - set - { - if (!FrameDumping) - { - metaNow = value; - } - } - } - - public static void NextFrame() - { - metaNow.SetMilliseconds(metaNow.GetMilliseconds() + Math.Round(1000.0 / FramesPerSecond)); - CurrentFrameNumber += 1; - } - - public static bool DoneDumping - { - get - { - return !FrameDumping || CancelFrameDump || (CurrentFrameNumber >= TotalFrames); - } - } - - - public static void SyncTime() - { - offset = 0; - now = Date.Now; - syncToClock = true; - } - - static int offset = 0; - - static Date now = Date.Now; - - static public double JNow - { - get - { - return UtcToJulian(Now); - } - } - - static bool syncToClock = true; - - public static bool SyncToClock - { - get { return syncToClock; } - set - { - if (syncToClock != value) - { - syncToClock = value; - if (value) - { - last = Date.Now; - offset = now - Date.Now; - } - else - { - now = new Date(Date.Now.GetTime() + offset); - } - } - } - } - - static private double timeRate = 1; - - static public double TimeRate - { - get { return timeRate; } - set { timeRate = value; } - } - - static private Coordinates location; - static private double altitude; - - public static double Altitude - { - get { return altitude; } - set { altitude = value; } - } - - static public Coordinates Location - { - get - { - //if (location == null) - { - location = Coordinates.FromLatLng(Settings.Active.LocationLat, Settings.Active.LocationLng); - altitude = Settings.Active.LocationAltitude; - } - return location; - } - set - { - if (Settings.GlobalSettings.LocationLat != value.Lat) - { - Settings.GlobalSettings.LocationLat = value.Lat; - } - - if (Settings.GlobalSettings.LocationLng != value.Lng) - { - Settings.GlobalSettings.LocationLng = value.Lng; - } - location = value; - } - } - - public static Date JulianToUtc(double jDate) - { - DT date = new DT(); - date.SetJD(jDate, true); - - //date.Get(ref year, ref month, ref day, ref hour, ref minute, ref second); - - - double ms = (date.Second() - ((int)date.Second())) * 1000; - - return new Date(date.Year(), date.Month()-1, date.Day(), date.Hour(), date.Minute(), (int)date.Second(), (int)ms); - } - - internal static double TwoLineDateToJulian(string p) - { - bool pre1950 = Int32.Parse(p.Substring(0, 1)) < 6; - int year = Int32.Parse((pre1950 ? " 20" : "19") + p.Substring(0, 2)); - double days = double.Parse(p.Substring(2, 3)); - double fraction = double.Parse(p.Substr(5)); - - //TimeSpan ts = TimeSpan.FromDays(days - 1 + fraction); - - //DateTime date = new DateTime(year, 1, 1, 0, 0, 0, 0); - - Date date = new Date(year, 0, 1, 0, 0); - return UtcToJulian(date) + (days-1 + fraction); - } - - public static string JulianToTwoLineDate(double jDate) - { - return DateToTwoLineDate(JulianToUtc(jDate)); - } - - public static string DateToTwoLineDate(Date date) - { - StringBuilder sb = new StringBuilder(); - - sb.Append(date.GetFullYear() % 100); - - Date fullYear = new Date(date.GetFullYear(), 0, 1, 0, 0); - - double dayofyear = Math.Floor((date - fullYear) / (60 * 60 * 24 * 1000))+2; - - double day = dayofyear + date.GetHours() / 24 + date.GetMinutes() / 60 / 24 + date.GetSeconds() / 60 / 60 / 24 + date.GetMilliseconds() / 1000 / 60 / 60 / 24; - - string sDay = TLEDayString(day); - - sb.Append(sDay); - - return sb.ToString(); - } - - public static string TLEDayString(double day) - { - string formated = day.ToString(); - - int point = formated.IndexOf("."); - if (point == -1) - { - point = formated.Length; - formated += ".0"; - } - int len = formated.Length-point-1; - - string fill = "00000000"; - - formated = fill.Substr(0, 3 - point) + formated + fill.Substr(0, 8 - len); - - return formated; - } - - - - public static double UtcToJulian(Date utc) - { - int year = utc.GetUTCFullYear(); - int month = utc.GetUTCMonth()+1; - double day = utc.GetUTCDate(); - double hour = utc.GetUTCHours(); - double minute = utc.GetUTCMinutes(); - double second = utc.GetUTCSeconds() + utc.GetUTCMilliseconds() / 1000.0; - double dblDay = day + (hour / 24.0) + (minute / 1440.0) + (second / 86400.0); - - return AstroCalc.GetJulianDay(year, month, dblDay); - //return DateToJD(year, month, dblDay, true); - //return julianDays; - } - - public static double DateToJD(int Year, int Month, double Day, bool bGregorianCalendar) - { - int Y = Year; - int M = Month; - if (M < 3) - { - Y = Y - 1; - M = M + 12; - } - - int A = 0; - int B = 0; - if (bGregorianCalendar) - { - A = (int)(Y / 100.0); - B = 2 - A + (int)(A / 4.0); - } - - return (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + Day + B - 1524.5; - } - } -} diff --git a/engine/csharp_ref/Star.cs b/engine/csharp_ref/Star.cs deleted file mode 100644 index 57a06838..00000000 --- a/engine/csharp_ref/Star.cs +++ /dev/null @@ -1,278 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - - - -namespace wwtlib -{ - public class Star - { - public double Magnitude; - public double RA; - public double Dec; - public double BMV; - public string Name - { - get - { - return "HIP" + ID.ToString(); - } - } - public Coordinates Coordinates - { - get - { - return Coordinates.FromRaDec(RA, Dec); - } - } - - public int ID; - public double AbsoluteMagnitude; - public double Par; - public double Distance; - public Color Col; - public Vector3d Position; - - public IPlace AsPlace - { - get - { - Place place = Place.Create(Name, Dec, RA, Classification.Star, Constellations.Containment.FindConstellationForPoint(RA, Dec), ImageSetType.SolarSystem, -1); - place.Magnitude = Magnitude; - place.Distance = Distance; - return place; - } - } - - - - public void Stars(string input, bool newish) - { - - string[] sa = input.Split('\t'); - - - ID = Int32.Parse(sa[0]); - RA = Double.Parse(sa[1])/15; - Dec = Double.Parse(sa[2]); - - - if (sa.Length > 3) - { - try - { - Magnitude = Double.Parse(sa[3]); - } - catch - { - } - } - - - if (sa.Length > 4) - { - try - { - Col = Color.Load(sa[4]); - } - catch - { - } - } - } - public Star(string input) - { - - string[] sa = input.Split('\t'); - - - ID = Int32.Parse(sa[0].Replace("HIP", "")); - - Dec = Double.Parse(sa[3]); - - RA = Double.Parse(sa[2]) / 15; - - - if (sa.Length > 4) - { - try - { - if (sa[4].ToUpperCase() != "NULL" && sa[4] != "") - { - Magnitude = Double.Parse(sa[4]); - } - } - catch - { - } - } - if (sa.Length > 5) - { - try - { - BMV = Double.Parse(sa[5]); - MakeColor(BMV); - - } - catch - { - } - } - if (sa.Length > 6) - { - Par = Double.Parse(sa[6]); - MakeDistanceAndMagnitude(); - } - } - - private void MakeDistanceAndMagnitude() - { - Distance = 1 / (Par / 1000); - AbsoluteMagnitude = Magnitude - 5 * ((Util.LogN(Distance, 10) - 1)); - //Convert to AU - Distance *= 206264.806; - } - - private void MakeColor(double bmv) - { - uint c = 0xFFFFFFFF; - if (bmv <= -0.32) { c = 0xFFA2B8FF; } - else if (bmv <= -0.31) { c = 0xFFA3B8FF; } - else if (bmv <= -0.3) { c = 0xFFA4BAFF; } - else if (bmv <= -0.3) { c = 0xFFA5BAFF; } - else if (bmv <= -0.28) { c = 0xFFA7BCFF; } - else if (bmv <= -0.26) { c = 0xFFA9BDFF; } - else if (bmv <= -0.24) { c = 0xFFABBFFF; } - else if (bmv <= -0.2) { c = 0xFFAFC2FF; } - else if (bmv <= -0.16) { c = 0xFFB4C6FF; } - else if (bmv <= -0.14) { c = 0xFFB6C8FF; } - else if (bmv <= -0.12) { c = 0xFFB9CAFF; } - else if (bmv <= -0.09) { c = 0xFFBCCDFF; } - else if (bmv <= -0.06) { c = 0xFFC1D0FF; } - else if (bmv <= 0) { c = 0xFFCAD6FF; } - else if (bmv <= 0.06) { c = 0xFFD2DCFF; } - else if (bmv <= 0.14) { c = 0xFFDDE4FF; } - else if (bmv <= 0.19) { c = 0xFFE3E8FF; } - else if (bmv <= 0.31) { c = 0xFFF2F2FF; } - else if (bmv <= 0.36) { c = 0xFFF9F6FF; } - else if (bmv <= 0.43) { c = 0xFFFFF9FC; } - else if (bmv <= 0.54) { c = 0xFFFFF6F3; } - else if (bmv <= 0.59) { c = 0xFFFFF3EB; } - else if (bmv <= 0.63) { c = 0xFFFFF1E7; } - else if (bmv <= 0.66) { c = 0xFFFFEFE1; } - else if (bmv <= 0.74) { c = 0xFFFFEEDD; } - else if (bmv <= 0.82) { c = 0xFFFFEAD5; } - else if (bmv <= 0.92) { c = 0xFFFFE4C4; } - else if (bmv <= 1.15) { c = 0xFFFFDFB8; } - else if (bmv <= 1.3) { c = 0xFFFFDDB4; } - else if (bmv <= 1.41) { c = 0xFFFFD39D; } - else if (bmv <= 1.48) { c = 0xFFFFCD91; } - else if (bmv <= 1.52) { c = 0xFFFFC987; } - else if (bmv <= 1.55) { c = 0xFFFFC57F; } - else if (bmv <= 1.56) { c = 0xFFFFC177; } - else if (bmv <= 1.61) { c = 0xFFFFBD71; } - else if (bmv <= 1.72) { c = 0xFFFFB866; } - else if (bmv <= 1.84) { c = 0xFFFFB25B; } - else if (bmv <= 2) { c = 0xFFFFAD51; } - Col = Color.FromInt(c); - } - - } - - - public class Galaxy - { - public float RA; - public float Dec; - public float Distance; - public float Type; - public int eTypeBucket; - public float Size = 5; - public long SdssID = 0; - //public Galaxy(string line, bool largeSet) - //{ - // line = line.Replace(" ", " "); - // string[] values = line.Split(new char[] { '\t', ' ', ',' }); - // SdssID = Convert.ToInt64(values[0]); - // RA = Convert.ToSingle(values[1]) / 15; - // Dec = Convert.ToSingle(values[2]); - // Distance = Convert.ToSingle(values[3]); - // if (largeSet) - // { - // Type = Convert.ToSingle(values[4]); - // eTypeBucket = GetEType(Type); - // } - // else - // { - // Size = Convert.ToSingle(values[4]) * 30; - // Type = Convert.ToSingle(values[6]); - // eTypeBucket = Convert.ToInt32(values[7]); - // } - - //} - - //public Galaxy(string line) - //{ - // line = line.Replace(" ", " "); - // string[] values = line.Split(new char[] { '\t', ' ', ',' }); - // SdssID = Convert.ToInt64(values[0]); - // RA = Convert.ToSingle(values[1]) / 15; - // Dec = Convert.ToSingle(values[2]); - // Distance = Convert.ToSingle(values[3]); - // this.Size = 500; - // Type = Convert.ToSingle(values[4]); - - //} - - //public IPlace Place - //{ - // get - // { - // TourPlace place = new TourPlace("SDSS " + SdssID.ToString(), Dec, RA, Classification.Galaxy, Earth3d.MainWindow.ConstellationCheck.FindConstellationForPoint(RA, Dec), ImageSetType.SolarSystem, -1); - // place.Magnitude = 0; - // place.Distance = (this.Distance * UiTools.AuPerParsec * 1000000.0) / .73; - // return place; - // } - //} - - - public Galaxy(BinaryReader br) - { - SdssID = br.ReadInt64(); - RA = br.ReadSingle(); - Dec = br.ReadSingle(); - Distance = br.ReadSingle(); - //Type = br.ReadSingle(); - eTypeBucket = br.ReadByte(); - Size = br.ReadSingle(); - } - - public Vector3d Position; - - static float[] eTypeBuckets = new float[] { -3, -0.1860f, -0.1680f, -0.1580f, -0.1500f, -0.1430f, -0.1370f, -0.1300f, -0.1230f, -0.1150f, -0.1040f, -0.0890f, -0.0680f, -0.0420f, -0.0110f, 0.0240f, 0.0640f, 0.1110f, 0.1690f, 0.2520f, 3 }; - public static int GetEType(float value) - { - int a = 0; - int b = eTypeBuckets.Length - 1; - - while (b - a > 1) - { - int m = (a + b) / 2; - if (value > eTypeBuckets[m]) - { - a = m; - } - else - { - b = m; - } - } - return a; - } - } - -} \ No newline at end of file diff --git a/engine/csharp_ref/TangentTile.cs b/engine/csharp_ref/TangentTile.cs deleted file mode 100644 index 8f48b1b6..00000000 --- a/engine/csharp_ref/TangentTile.cs +++ /dev/null @@ -1,244 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; - - -namespace wwtlib -{ - public class TangentTile : Tile - { - bool topDown = true; - - //Cached bitmap for performance reasons - //Only used in legacy rendering of FITS (WebGL 1.0) inside SkyImageTile - protected Bitmap bmp; - - protected void ComputeBoundingSphere() - { - if (!topDown) - { - ComputeBoundingSphereBottomsUp(); - return; - } - - double tileDegrees = this.dataset.BaseTileDegrees / Math.Pow(2, this.Level); - - double latMin = ((double) this.dataset.BaseTileDegrees / 2 - ((double) this.tileY) * tileDegrees) + dataset.OffsetY; - double latMax = ((double) this.dataset.BaseTileDegrees / 2 - ((double) (this.tileY + 1)) * tileDegrees) + dataset.OffsetY; - double lngMin = (((double) this.tileX) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + dataset.OffsetX; - double lngMax = (((double) (this.tileX + 1)) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + dataset.OffsetX; - - double latCenter = (latMin + latMax) / 2.0; - double lngCenter = (lngMin + lngMax) / 2.0; - - this.sphereCenter = GeoTo3dTan(latCenter, lngCenter); - - TopLeft = GeoTo3dTan(latMin, lngMin); - BottomRight = GeoTo3dTan(latMax, lngMax); - TopRight = GeoTo3dTan(latMin, lngMax); - BottomLeft = GeoTo3dTan(latMax, lngMin); - - Vector3d distVect = GeoTo3dTan(latMin, lngMin); - distVect.Subtract(sphereCenter); - this.sphereRadius = distVect.Length(); - } - - protected void ComputeBoundingSphereBottomsUp() - { - double tileDegrees = this.dataset.BaseTileDegrees / Math.Pow(2, this.Level); - - double latMin = ((double) this.dataset.BaseTileDegrees / 2 + ((double) (this.tileY + 1)) * tileDegrees) + dataset.OffsetY; - double latMax = ((double) this.dataset.BaseTileDegrees / 2 + ((double) this.tileY) * tileDegrees) + dataset.OffsetY; - double lngMin = (((double) this.tileX) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + dataset.OffsetX; - double lngMax = (((double) (this.tileX + 1)) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + dataset.OffsetX; - - TopLeft = GeoTo3dTan(latMin, lngMin); - BottomRight = GeoTo3dTan(latMax, lngMax); - TopRight = GeoTo3dTan(latMin, lngMax); - BottomLeft = GeoTo3dTan(latMax, lngMin); - } - - protected virtual LatLngEdges GetLatLngEdges() - { - double tileDegrees = this.dataset.BaseTileDegrees / Math.Pow(2, this.Level); - - LatLngEdges edges = new LatLngEdges(); - edges.latMin = ((double) this.dataset.BaseTileDegrees / 2 - ((double) this.tileY) * tileDegrees) + this.dataset.OffsetY; - edges.latMax = ((double) this.dataset.BaseTileDegrees / 2 - ((double) (this.tileY + 1)) * tileDegrees) + this.dataset.OffsetY; - edges.lngMin = (((double) this.tileX) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + this.dataset.OffsetX; - edges.lngMax = (((double) (this.tileX + 1)) * tileDegrees - (double) this.dataset.BaseTileDegrees / dataset.WidthFactor) + this.dataset.OffsetX; - - return edges; - } - - protected Vector3d GeoTo3dTan(double lat, double lng) - { - lng = -lng; - double fac1 = this.dataset.BaseTileDegrees / 2; - double factor = Math.Tan(fac1 * RC); - - return (Vector3d)dataset.Matrix.Transform(Vector3d.Create(1, (lat / fac1 * factor), (lng / fac1 * factor))); - - } - - public override void RequestImage() - { - fitsImage = dataset.WcsImage as FitsImage; - if (fitsImage != null) - { - texReady = true; - Downloading = false; - errored = fitsImage.errored; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - if (RenderContext.UseGlVersion2) - { - MakeTexture(); - ReadyToRender = true; - } - else - { - bmp = fitsImage.GetBitmap(); - texture2d = bmp.GetTexture(); - ReadyToRender = true; - } - } - else - { - base.RequestImage(); - } - } - - public override bool CreateGeometry(RenderContext renderContext) - { - if (GeometryCreated) - { - return true; - } - GeometryCreated = true; - - for (int i = 0; i < 4; i++) - { - RenderTriangleLists[i] = new List(); - } - - GlobalCenter = GeoTo3dTan(0, 0); - LatLngEdges edges = GetLatLngEdges(); - - TopLeft = GeoTo3dTan(edges.latMin, edges.lngMin).Subtract(GlobalCenter); - BottomRight = GeoTo3dTan(edges.latMax, edges.lngMax).Subtract(GlobalCenter); - TopRight = GeoTo3dTan(edges.latMin, edges.lngMax).Subtract(GlobalCenter); - BottomLeft = GeoTo3dTan(edges.latMax, edges.lngMin).Subtract(GlobalCenter); - - Vector3d center = Vector3d.MidPoint(TopLeft, BottomRight); - Vector3d leftCenter = Vector3d.MidPoint(TopLeft, BottomLeft); - Vector3d rightCenter = Vector3d.MidPoint(TopRight, BottomRight); - Vector3d topCenter = Vector3d.MidPoint(TopLeft, TopRight); - Vector3d bottomCenter = Vector3d.MidPoint(BottomLeft, BottomRight); - - if (renderContext.gl == null) - { - RenderTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePos(TopLeft, 0, 0), PositionTexture.CreatePos(leftCenter, 0, .5), PositionTexture.CreatePos(topCenter, .5, 0), texture, Level)); - RenderTriangleLists[0].Add(RenderTriangle.Create(PositionTexture.CreatePos(leftCenter, 0, 0.5), PositionTexture.CreatePos(center, .5, .5), PositionTexture.CreatePos(topCenter, .5, 0), texture, Level)); - RenderTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePos(topCenter, .5, 0), PositionTexture.CreatePos(rightCenter, 1, .5), PositionTexture.CreatePos(TopRight, 1, 0), texture, Level)); - RenderTriangleLists[1].Add(RenderTriangle.Create(PositionTexture.CreatePos(topCenter, .5, 0), PositionTexture.CreatePos(center, .5, .5), PositionTexture.CreatePos(rightCenter, 1, .5), texture, Level)); - RenderTriangleLists[2].Add(RenderTriangle.Create(PositionTexture.CreatePos(leftCenter, 0, .5), PositionTexture.CreatePos(bottomCenter, .5, 1), PositionTexture.CreatePos(center, .5, .5), texture, Level)); - RenderTriangleLists[2].Add(RenderTriangle.Create(PositionTexture.CreatePos(leftCenter, 0, .5), PositionTexture.CreatePos(BottomLeft, 0, 1), PositionTexture.CreatePos(bottomCenter, .5, 1), texture, Level)); - RenderTriangleLists[3].Add(RenderTriangle.Create(PositionTexture.CreatePos(center, .5, .5), PositionTexture.CreatePos(BottomRight, 1, 1), PositionTexture.CreatePos(rightCenter, 1, .5), texture, Level)); - RenderTriangleLists[3].Add(RenderTriangle.Create(PositionTexture.CreatePos(center, .5, .5), PositionTexture.CreatePos(bottomCenter, .5, 1), PositionTexture.CreatePos(BottomRight, 1, 1), texture, Level)); - ReadyToRender = true; - } - else - { - - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(9 * 5); - float[] buffer = (float[])(object)f32array; - int index = 0; - - index = AddVertex(buffer, index, PositionTexture.CreatePos(bottomCenter, .5, 1)); //0 - index = AddVertex(buffer, index, PositionTexture.CreatePos(BottomLeft, 0, 1)); //1 - index = AddVertex(buffer, index, PositionTexture.CreatePos(BottomRight, 1, 1)); //2 - index = AddVertex(buffer, index, PositionTexture.CreatePos(center, .5, .5)); //3 - index = AddVertex(buffer, index, PositionTexture.CreatePos(leftCenter, 0, .5)); //4 - index = AddVertex(buffer, index, PositionTexture.CreatePos(rightCenter, 1, .5)); //5 - index = AddVertex(buffer, index, PositionTexture.CreatePos(topCenter, .5, 0)); //6 - index = AddVertex(buffer, index, PositionTexture.CreatePos(TopLeft, 0, 0)); //7 - index = AddVertex(buffer, index, PositionTexture.CreatePos(TopRight, 1, 0)); //8 - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - - // process index buffers - - for (int i = 0; i < 4; i++) - { - index = 0; - TriangleCount = 2; - Uint16Array ui16array = new Uint16Array(TriangleCount * 3); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - switch (i) - { - case 0: - indexArray[index++] = 7; - indexArray[index++] = 4; - indexArray[index++] = 6; - indexArray[index++] = 4; - indexArray[index++] = 3; - indexArray[index++] = 6; - break; - case 1: - indexArray[index++] = 6; - indexArray[index++] = 5; - indexArray[index++] = 8; - indexArray[index++] = 6; - indexArray[index++] = 3; - indexArray[index++] = 5; - break; - case 2: - indexArray[index++] = 4; - indexArray[index++] = 0; - indexArray[index++] = 3; - indexArray[index++] = 4; - indexArray[index++] = 1; - indexArray[index++] = 0; - break; - case 3: - indexArray[index++] = 3; - indexArray[index++] = 2; - indexArray[index++] = 5; - indexArray[index++] = 3; - indexArray[index++] = 0; - indexArray[index++] = 2; - break; - } - IndexBuffers[i] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, IndexBuffers[i]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - - } - } - return true; - } - - public TangentTile(int level, int x, int y, Imageset dataset, Tile parent) - { - this.Parent = parent; - this.Level = level; - this.tileX = x; - this.tileY = y; - this.dataset = dataset; - this.topDown = !dataset.BottomsUp; - this.ComputeBoundingSphere(); - } - } - - public class LatLngEdges - { - public double latMin; - public double latMax; - public double lngMin; - public double lngMax; - } -} diff --git a/engine/csharp_ref/Tile.cs b/engine/csharp_ref/Tile.cs deleted file mode 100644 index d12cc54a..00000000 --- a/engine/csharp_ref/Tile.cs +++ /dev/null @@ -1,1236 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - -namespace wwtlib -{ - public abstract class Tile - { - public static int CurrentRenderGeneration = 0; - internal List[] RenderTriangleLists = new List[4]; - - internal WebGLBuffer[] IndexBuffers = new WebGLBuffer[4]; - internal WebGLBuffer VertexBuffer; - - public virtual WebGLBuffer GetIndexBuffer(int index, int accomidation) - { - return IndexBuffers[index]; - } - - - public static int TileTargetX = -1; - public static int TileTargetY = -1; - public static int TileTargetLevel = -1; - - public int Level; - - public int tileX; - - public int tileY; - public ImageElement texture = null; - public WebGLTexture texture2d = null; - public bool IsCatalogTile = false; - protected FitsImage fitsImage; - - public bool ReadyToRender = false; - public bool InViewFrustum = true; - public static int TilesInView = 0; - public static int TrianglesRendered = 0; - public static int TilesTouched = 0; - public static List frustumList = null; - - public static GL PrepDevice = null; - - protected Vector3d GlobalCenter = Vector3d.Zero; - - protected Vector3d TopLeft; - protected Vector3d BottomRight; - protected Vector3d TopRight; - protected Vector3d BottomLeft; - - public static double uvMultiple = 256; - - public static List GetFrustumList() - { - try - { - return frustumList; - } - catch - { - // return ""; - return null; - } - } - - public virtual bool IsPointInTile(double lat, double lng) - { - return false; - } - - - public virtual double GetSurfacePointAltitude(double lat, double lng, bool meters) - { - return 0; - } - - protected Tile[] children = new Tile[4] { null, null, null, null }; - public Tile Parent = null; - - public Vector3d localCenter = new Vector3d(); - public int RenderedAtOrBelowGeneration = 0; - - public virtual void MakeTexture() - { - if (PrepDevice != null) - { - try - { - texture2d = PrepDevice.createTexture(); - - PrepDevice.bindTexture(GL.TEXTURE_2D, texture2d); - PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE); - PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE); - - if (dataset.Extension.ToLowerCase().IndexOf("fits") > -1 && RenderContext.UseGlVersion2) - { - PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.R32F, (int)fitsImage.SizeX, (int)fitsImage.SizeY, 0, GL.RED, GL.FLOAT, fitsImage.dataUnit); - PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST); - PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST); - } - else - { - ImageElement image = texture; - // Before we bind resize to a power of two if nessesary so we can MIPMAP - if (!Texture.IsPowerOfTwo(texture.Height) | !Texture.IsPowerOfTwo(texture.Width)) - { - CanvasElement temp = (CanvasElement)Document.CreateElement("canvas"); - temp.Height = Texture.FitPowerOfTwo(image.Height); - temp.Width = Texture.FitPowerOfTwo(image.Width); - CanvasContext2D ctx = (CanvasContext2D)temp.GetContext(Rendering.Render2D); - ctx.DrawImage(image, 0, 0, temp.Width, temp.Height); - //Substitute the resized image - image = (ImageElement)(Element)temp; - } - PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, image); - PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_NEAREST); - PrepDevice.generateMipmap(GL.TEXTURE_2D); - } - - PrepDevice.bindTexture(GL.TEXTURE_2D, null); - } - catch - { - errored = true; - - } - } - } - - public int AddVertex(float[] buffer, int index, PositionTexture p) - { - buffer[index++] = (float)p.Position.X; - buffer[index++] = (float)p.Position.Y; - buffer[index++] = (float)p.Position.Z; - buffer[index++] = (float)p.Tu; - buffer[index++] = (float)p.Tv; - - return index; - } - - protected Vector3d GeoTo3dWithAlt(double lat, double lng, bool useLocalCenter, bool rev) - { - lat = Math.Max(Math.Min(90, lat), -90); - lng = Math.Max(Math.Min(180, lng), -180); - if (!DemEnabled || DemData == null) - { - return GeoTo3d(lat, lng, useLocalCenter); - } - if (rev) - { - lng -= 180; - } - double altitude = DemData[demIndex]; - Vector3d retVal = GeoTo3dWithAltitude(lat, lng, altitude, useLocalCenter); - return retVal; - } - - public Vector3d GeoTo3dWithAltitude(double lat, double lng, double altitude, bool useLocalCenter) - { - - double radius = 1 + (altitude / DemScaleFactor); - Vector3d retVal = (Vector3d.Create((Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius), (Math.Sin(lat * RC) * radius), (Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius))); - if (useLocalCenter) - { - retVal.Subtract(localCenter); - } - return retVal; - } - - - private double demScaleFactor = 6371000; - - internal double DemScaleFactor - { - get { return demScaleFactor; } - set - { - demScaleFactor = value;// / Properties.Settings.Default.TerrainScaling; - } - } - - public virtual void RequestImage() - { - if (dataset.Extension.ToLowerCase().IndexOf("fits") > -1) - { - if (!Downloading && !ReadyToRender) - { - Downloading = true; - if (RenderContext.UseGlVersion2) - { - fitsImage = new FitsImageTile(dataset, URL, delegate (WcsImage wcsImage) - { - Downloading = false; - errored = fitsImage.errored; - TileCache.RemoveFromQueue(this.Key, true); - if (!fitsImage.errored) - { - // For a non-HiPS tiled FITS, this is our - // mechanism for notifying the layer creator - // that the initial FITS data have loaded and - // the FitsProperties can be trusted. - if (Level == 0) - { - dataset.FitsProperties.FireMainImageLoaded(fitsImage); - fitsImage.ApplyDisplaySettings(); - } - texReady = true; - ReadyToRender = texReady && (DemReady || !demTile); - RequestPending = false; - MakeTexture(); - } - }); - } - else - { - fitsImage = FitsImageJs.CreateTiledFits(dataset, URL, delegate (WcsImage wcsImage) - { - if (Level == 0) - { - dataset.FitsProperties.FireMainImageLoaded(fitsImage); - } - texReady = true; - Downloading = false; - errored = fitsImage.errored; - ReadyToRender = texReady && (DemReady || !demTile); - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - texture2d = wcsImage.GetBitmap().GetTexture(); - }); - } - } - } - else - { - if (Dataset.WcsImage != null) - { - texReady = true; - Downloading = false; - errored = false; - ReadyToRender = true; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - return; - } - - if (!Downloading && !ReadyToRender) - { - Downloading = true; - texture = (ImageElement)Document.CreateElement("img"); - CrossDomainImage xdomimg = (CrossDomainImage)(object)texture; - - texture.AddEventListener("load", delegate (ElementEvent e) - { - texReady = true; - Downloading = false; - errored = false; - ReadyToRender = texReady && (DemReady || !demTile); - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - MakeTexture(); - }, false); - - texture.AddEventListener("error", delegate (ElementEvent e) - { - if (!texture.HasAttribute("proxyattempt")) - { - texture.SetAttribute("proxyattempt", true); - - // NOTE: `this.URL` is dynamically generated using - // URLHelpers.rewrite(). Say that we request tiles from - // example.com, which requires CORS proxying. Say also - // that this callback is called for a request to a tile - // that should in fact be available. If a different - // request fails before this callback is called, - // activateProxy() will be called on the example.com - // domain, making it so that `this.URL` in the following - // call goes through the proxy, making it so that - // `new_url` is null, making it so that this tile is - // erroneously marked as failed when it should not be. - // The solution: make sure to check proxy activation - // with the *original* request URL, `texture.Src`, not - // the one that may have been updated, `this.URL`. - string new_url = URLHelpers.singleton.activateProxy(texture.Src); - - if (new_url != null) - { // null => don't bother: we know that the proxy won't help - texture.Src = new_url; - return; - } - } - - Downloading = false; - ReadyToRender = false; - errored = true; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - }, false); - - xdomimg.crossOrigin = "anonymous"; - texture.Src = this.URL; - } - } - } - - public Float32Array demFile; - public int demIndex = 0; - public float[] DemData; - public float demAverage; - public bool DemReady = false; - public bool texReady = false; - public bool demTile = false; - public bool demDownloading = false; - public static int callCount = 0; - //public Vector3d localCenter = new Vector3d(); - - public virtual bool CreateDemFromParent() - { - return false; - } - - private bool LoadDemData() - { - if (demFile == null) - { - - return CreateDemFromParent(); - } - DemData = (float[])(object)demFile; - - - if (demFile.length != 1089 && demFile.length != 513) - { - return CreateDemFromParent(); - } - - float total = 0; - foreach (float fv in DemData) - { - total += fv; - } - demAverage /= DemData.Length; - - return true; - } - - - public void RequestDem() - { - if (!ReadyToRender && !demDownloading) - { - demTile = true; - demDownloading = true; - - callCount++; - XMLHttpRequest2 xhr = new XMLHttpRequest2(); - xhr.AddEventListener("load", delegate (ElementEvent e) - { - DemReady = true; - demDownloading = false; - ReadyToRender = texReady && (DemReady || !demTile); - RequestPending = false; - try - { - demFile = new Float32Array(xhr.Response); - } - catch - { - } - - TileCache.RemoveFromQueue(this.Key, true); - }, false); - - xhr.AddEventListener("error", delegate (ElementEvent e) - { - demDownloading = false; - DemReady = false; - ReadyToRender = false; - errored = true; - RequestPending = false; - TileCache.RemoveFromQueue(this.Key, true); - }, false); - - xhr.Open(HttpVerb.Get, DemURL, true); - xhr.ResponseType = "arraybuffer"; - xhr.Send(); - } - } - - public virtual bool Draw3D(RenderContext renderContext, double opacity) - { - // CanvasContext2D device = renderContext.Device; - - - - RenderedGeneration = CurrentRenderGeneration; - TilesTouched++; - AccessCount = TileCache.AccessID++; - - if (errored) - { - return false; - } - - int xMax = 2; - - InViewFrustum = true; - - if (!ReadyToRender) - { - TileCache.AddTileToQueue(this); - //RequestImage(); - return false; - } - - bool transitioning = false; - - int childIndex = 0; - - int yOffset = 0; - if (dataset.Mercator || dataset.BottomsUp) - { - yOffset = 1; - } - int xOffset = 0; - - // try - { - bool anythingToRender = false; - bool childRendered = false; - for (int y1 = 0; y1 < 2; y1++) - { - for (int x1 = 0; x1 < xMax; x1++) - { - // if (level < (demEnabled ? 12 : dataset.Levels)) - if (Level < dataset.Levels) - { - // make children - if (children[childIndex] == null) - { - children[childIndex] = TileCache.GetTile(Level + 1, tileX * 2 + ((x1 + xOffset) % 2), tileY * 2 + ((y1 + yOffset) % 2), dataset, this); - } - - if (children[childIndex].IsTileInFrustum(renderContext.Frustum)) - { - InViewFrustum = true; - if (children[childIndex].IsTileBigEnough(renderContext)) - { - renderChildPart[childIndex].TargetState = !children[childIndex].Draw3D(renderContext, opacity); - if (renderChildPart[childIndex].TargetState) - { - childRendered = true; - } - } - else - { - renderChildPart[childIndex].TargetState = true; - } - } - else - { - renderChildPart[childIndex].TargetState = renderChildPart[childIndex].State = false; - } - - //if (renderChildPart[childIndex].TargetState == true || !blendMode) - //{ - // renderChildPart[childIndex].State = renderChildPart[childIndex].TargetState; - //} - if (renderChildPart[childIndex].TargetState != renderChildPart[childIndex].State) - { - transitioning = true; - } - } - else - { - renderChildPart[childIndex].State = true; - } - - if (renderChildPart[childIndex].State == true) - { - anythingToRender = true; - } - - childIndex++; - } - } - - if (childRendered || anythingToRender) - { - RenderedAtOrBelowGeneration = CurrentRenderGeneration; - if (Parent != null) - { - Parent.RenderedAtOrBelowGeneration = RenderedAtOrBelowGeneration; - } - } - - if (!anythingToRender) - { - return true; - } - - if (!CreateGeometry(renderContext)) - { - return false; - } - - TilesInView++; - - - accomidation = ComputeAccomidation(); - for (int i = 0; i < 4; i++) - { - if (renderChildPart[i].TargetState) - { - RenderPart(renderContext, i, (opacity / 100), false); - } - } - } - // catch - { - } - return true; - } - - public int RenderedGeneration = 0; - public int accomidation = 0; - public static bool useAccomidation = true; - private int ComputeAccomidation() - { - int accVal = 0; - - if (!useAccomidation) - { - return 0; - } - - - - - //Bottom - Tile top = TileCache.GetCachedTile(Level, tileX, tileY + 1, dataset, this); - if (top == null || top.RenderedAtOrBelowGeneration < CurrentRenderGeneration - 2) - { - accVal += 1; - } - - //right - Tile right = TileCache.GetCachedTile(Level, tileX + 1, tileY, dataset, this); - if (right == null || right.RenderedAtOrBelowGeneration < CurrentRenderGeneration - 2) - { - accVal += 2; - } - - //top - Tile bottom = TileCache.GetCachedTile(Level, tileX, tileY - 1, dataset, this); - if (bottom == null || bottom.RenderedAtOrBelowGeneration < CurrentRenderGeneration - 2) - { - accVal += 4; - } - //left - Tile left = TileCache.GetCachedTile(Level, tileX - 1, tileY, dataset, this); - if (left == null || left.RenderedAtOrBelowGeneration < CurrentRenderGeneration - 2) - { - accVal += 8; - } - - return accVal; - } - public virtual void RenderPart(RenderContext renderContext, int part, double opacity, bool combine) - { - - if (PrepDevice == null) - { - bool lighting = renderContext.Lighting && renderContext.SunPosition != null; - - - foreach (RenderTriangle tri in RenderTriangleLists[part]) - { - tri.Opacity = opacity; - if (lighting) - { - // tranform normal by WV - Vector3d norm = tri.Normal.Copy(); - renderContext.World.MultiplyVector(norm); - norm.Normalize(); - - // Dot product from sun angle - double light = Vector3d.Dot(norm, renderContext.SunPosition); - if (light < 0) - { - light = 0; - } - else - { - light = Math.Min(1.0f, (light * 1)); - } - - // set lighting - tri.lighting = (float)light; - } - else - { - tri.lighting = 1.0f; - } - - - - tri.Draw(renderContext.Device, renderContext.WVP); - } - } - else - { - if (RenderContext.UseGlVersion2 && fitsImage != null) - { - ColorMapContainer.BindColorMapTexture(PrepDevice, dataset.FitsProperties.ColorMapName); - FitsShader.Min = (float)dataset.FitsProperties.LowerCut; - FitsShader.Max = (float)dataset.FitsProperties.UpperCut; - FitsShader.ContainsBlanks = dataset.FitsProperties.ContainsBlanks; - FitsShader.BlankValue = (float)dataset.FitsProperties.BlankValue; - FitsShader.BZero = (float)dataset.FitsProperties.BZero; - FitsShader.BScale = (float)dataset.FitsProperties.BScale; - FitsShader.ScaleType = (int)dataset.FitsProperties.ScaleType; - FitsShader.TransparentBlack = dataset.FitsProperties.TransparentBlack; - FitsShader.Use(renderContext, VertexBuffer, GetIndexBuffer(part, accomidation), texture2d, (float)opacity, false, GlobalCenter); - } - else - { - TileShader.Use(renderContext, VertexBuffer, GetIndexBuffer(part, accomidation), texture2d, (float)opacity, false, GlobalCenter); - } - renderContext.gl.drawElements(GL.TRIANGLES, TriangleCount * 3, GL.UNSIGNED_SHORT, 0); - } - } - - public virtual void CleanUp(bool removeFromParent) - { - - ReadyToRender = false; - DemData = null; - demFile = null; - demDownloading = false; - texReady = false; - DemReady = false; - errored = false; - if (this.texture != null) - { - this.texture = null; - - } - - RenderTriangleLists = new List[4]; - GeometryCreated = false; - if (removeFromParent && Parent != null) - { - Parent.RemoveChild(this); - Parent = null; - } - - if (PrepDevice != null) - { - foreach (WebGLBuffer buf in IndexBuffers) - { - PrepDevice.deleteBuffer(buf); - } - IndexBuffers = new WebGLBuffer[4]; - - if (VertexBuffer != null) - { - PrepDevice.deleteBuffer(VertexBuffer); - VertexBuffer = null; - } - - if (texture2d != null) - { - PrepDevice.deleteTexture(texture2d); - - texture2d = null; - } - } - } - - public void RemoveChild(Tile child) - { - for (int i = 0; i < 4; i++) - { - if (children[i] == child) - { - children[i] = null; - return; - } - } - } - - // bool blendMode = false; - - - public int AccessCount = 0; - public bool Downloading = false; - public bool GeometryCreated = false; - public static bool DemEnabled = false; - - public virtual bool CreateGeometry(RenderContext renderContext) - { - if (DemEnabled && DemReady && DemData == null) - { - if (!LoadDemData()) - { - return false; - } - } - - if (DemEnabled && DemData == null) - { - return false; - } - - ReadyToRender = true; - return true; - } - - //private bool LoadDemData() - //{ - // DemData = (float[])(object)demFile; - - // //todo get dem from parent - // return true; - //} - - - protected void CalcSphere() - { - Vector3d[] corners = new Vector3d[4]; - corners[0] = TopLeft; - corners[1] = BottomRight; - corners[2] = TopRight; - corners[3] = BottomLeft; - SphereHull result = ConvexHull.FindEnclosingSphere(corners); - - sphereCenter = result.Center; - sphereRadius = result.Radius; - } - - internal bool isHdTile = false; - protected int demSize = 33 * 33; - - - - // public static Viewport Viewport; - public static int maxLevel = 20; - - - - Vector3d topLeftScreen = new Vector3d(); - Vector3d bottomRightScreen = new Vector3d(); - Vector3d topRightScreen = new Vector3d(); - Vector3d bottomLeftScreen = new Vector3d(); - - virtual public bool IsTileBigEnough(RenderContext renderContext) - { - if (Level > 1) - { - Matrix3d wvp = renderContext.WVP; - - - //// Test for tile scale in view.. - //topLeftScreen = wvp.ProjectToScreen(TopLeft, renderContext.Width, renderContext.Height); - //bottomRightScreen = wvp.ProjectToScreen(BottomRight, renderContext.Width, renderContext.Height); - //topRightScreen = wvp.ProjectToScreen(TopRight, renderContext.Width, renderContext.Height); - //bottomLeftScreen = wvp.ProjectToScreen(BottomLeft, renderContext.Width, renderContext.Height); - - //Vector3d top = topLeftScreen; - //top.Subtract(topRightScreen); - //double topLength = top.Length(); - - //Vector3d bottom = bottomLeftScreen; - //bottom.Subtract(bottomRightScreen); - //double bottomLength = bottom.Length(); - - //Vector3d left = bottomLeftScreen; - //left.Subtract(topLeftScreen); - //double leftLength = left.Length(); - - //Vector3d right = bottomRightScreen; - //right.Subtract(topRightScreen); - //double rightLength = right.Length(); - - // Test for tile scale in view.. - wvp.TransformTo(TopLeft, topLeftScreen); - wvp.TransformTo(BottomRight, bottomRightScreen); - wvp.TransformTo(TopRight, topRightScreen); - wvp.TransformTo(BottomLeft, bottomLeftScreen); - - Vector3d top = topLeftScreen; - top.Subtract(topRightScreen); - double topLength = top.Length(); - - Vector3d bottom = bottomLeftScreen; - bottom.Subtract(bottomRightScreen); - double bottomLength = bottom.Length(); - - Vector3d left = bottomLeftScreen; - left.Subtract(topLeftScreen); - double leftLength = left.Length(); - - Vector3d right = bottomRightScreen; - right.Subtract(topRightScreen); - double rightLength = right.Length(); - - - float lengthMax = Math.Max(Math.Max(rightLength, leftLength), Math.Max(bottomLength, topLength)); - if (lengthMax < 300) // was 220 - { - return false; - } - else - { - deepestLevel = Level > deepestLevel ? Level : deepestLevel; - } - } - - return true; - } - - public static int meshComplexity = 50; - public static int imageQuality = 50; - public static int lastDeepestLevel = 0; - public static int deepestLevel = 0; - //virtual public bool IsTileInFrustum(PlaneD[]frustum) - //{ - // InViewFrustum = false; - // Vector3d center = sphereCenter; - - // if (this.Level < 2 && dataset.Projection == ProjectionType.Mercator) - // { - // return true; - // } - - // Vector4d centerV4 = new Vector4d(center.X , center.Y , center.Z , 1f); - // Vector3d length = Vector3d.Create(sphereRadius, 0, 0); - - // double rad = length.Length(); - // for (int i = 0; i < 6; i++) - // { - // if (frustum[i].Dot(centerV4) + rad < 0) - // { - // return false; - // } - // } - // InViewFrustum = true; - - // return true; - //} - virtual public bool IsTileInFrustum(PlaneD[] frustum) - { - - if (this.Level < 2 && (dataset.Projection == ProjectionType.Mercator || dataset.Projection == ProjectionType.Toast)) - { - // return true; - } - InViewFrustum = false; - - Vector4d centerV4 = new Vector4d(sphereCenter.X, sphereCenter.Y, sphereCenter.Z, 1f); - - for (int i = 0; i < 6; i++) - { - if (frustum[i].Dot(centerV4) < -sphereRadius) - { - return false; - } - } - InViewFrustum = true; - - return true; - } - - - protected double sphereRadius; - - public double SphereRadius - { - get { return sphereRadius; } - } - - protected Vector3d localOrigin; - - protected Vector3d sphereCenter = new Vector3d(); - - public Vector3d SphereCenter - { - get { return sphereCenter; } - } - - protected const double RC = (3.1415927 / 180.0); - protected float radius = 1; - protected Vector3d GeoTo3d(double lat, double lng, bool useLocalCenter) - { - - if (dataset.DataSetType == ImageSetType.Panorama) - { - Vector3d retVal = Vector3d.Create(-(Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius), (Math.Sin(lat * RC) * radius), (Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius)); - - return retVal; - - } - else - { - lng -= 180; - Vector3d retVal = Vector3d.Create((Math.Cos(lng * RC) * Math.Cos(lat * RC) * radius), (Math.Sin(lat * RC) * radius), (Math.Sin(lng * RC) * Math.Cos(lat * RC) * radius)); - - return retVal; - } - - } - - static protected int SubDivisions - { - get { return 32; /*DemEnabled ? 32 : 16; */ } - } - //protected static int subDivisions = 4; - - - protected int TriangleCount = 0; - //{ - // get { return SubDivisions * SubDivisions * 2; } - //} - - public virtual void OnCreateVertexBuffer(object sender, EventArgs e) - { - - } - - public int RequestHits; - public bool RequestPending = false; - public bool errored = false; - protected Imageset dataset; - public Imageset Dataset - { - get - { - return dataset; - } - set - { - dataset = value; - } - } - - private String key = null; - public String Key - { - get - { - if (key == null) - { - key = Imageset.GetTileKey(dataset, Level, tileX, tileY, Parent); - } - return key; - } - - } - - - // URL parameters - //{0} ImageSetID - //{1} level - //{2} x tile id - //{3} y tile id - //{4} quadtree address (VE style) - //{5} quadtree address (Google maps style) - //{6} top left corner RA - //{7} top left corner Dec - //{8} bottom right corner RA - //{9} bottom right corner dec - //{10} bottom left corner RA - //{11} bottom left corner dec - //{12} top right corner RA - //{13} top right corner dec - - //{X} - Tile X value - //{Y} - Tile Y value - //{L} - Tile Level - //{Q} - Quad Key ID - //{S} - Last Digit of Quadkey - // - public String URL - { - get - { - string rewritten_url = URLHelpers.singleton.rewrite(dataset.Url, URLRewriteMode.AsIfAbsolute); - string returnUrl = rewritten_url; - - if (rewritten_url.IndexOf("{1}") > -1) - { - // Old style URL - if (dataset.Projection == ProjectionType.Mercator && !string.IsNullOrEmpty(dataset.QuadTreeTileMap)) - { - returnUrl = String.Format(rewritten_url, this.GetServerID(), GetTileID()); - if (returnUrl.IndexOf("virtualearth.net") > -1) - { - returnUrl += "&n=z"; - } - return returnUrl; - } - else - { - return String.Format(rewritten_url, dataset.ImageSetID, Level, tileX, tileY); - } - } - - returnUrl = returnUrl.Replace("{X}", this.tileX.ToString()); - returnUrl = returnUrl.Replace("{Y}", this.tileY.ToString()); - returnUrl = returnUrl.Replace("{L}", this.Level.ToString()); - int hash = 0; - if (returnUrl.IndexOf("{S:0}") > -1) - { - hash = 0; - returnUrl = returnUrl.Replace("{S:0}", "{S}"); - } - if (returnUrl.IndexOf("{S:1}") > -1) - { - hash = 1; - returnUrl = returnUrl.Replace("{S:1}", "{S}"); - } - if (returnUrl.IndexOf("{S:2}") > -1) - { - hash = 2; - returnUrl = returnUrl.Replace("{S:2}", "{S}"); - } - if (returnUrl.IndexOf("{S:3}") > -1) - { - hash = 3; - returnUrl = returnUrl.Replace("{S:3}", "{S}"); - } - - if (returnUrl.IndexOf("a{S}") > -1) - { - returnUrl = returnUrl.Replace("a{S}", "r{S}"); - } - - if (returnUrl.IndexOf("h{S}") > -1) - { - returnUrl = returnUrl.Replace("h{S}", "r{S}"); - } - - - if (returnUrl.IndexOf("//r{S}.ortho.tiles.virtualearth.net") > -1) - { - returnUrl = returnUrl.Replace("//r{S}.ortho.tiles.virtualearth.net", "//ecn.t{S}.tiles.virtualearth.net"); - } - - - string id = this.GetTileID(); - string server = ""; - - if (id.Length == 0) - { - server = hash.ToString(); - } - else - { - server = id.Substr(id.Length - 1, 1).ToString(); - } - - //if (returnUrl == "//r{S}.ortho.tiles.virtualearth.net/tiles/wtl00{Q}?g=121&band=wwt_rgb" && id.Length > 7 && (id.StartsWith("2") || id.StartsWith("3"))) - //{ - // returnUrl = "//r{S}.ortho.tiles.virtualearth.net/tiles/wtl00{Q}?g=120&band=wwt_jpg"; - //} - - - returnUrl = returnUrl.Replace("{Q}", id); - - returnUrl = returnUrl.Replace("{S}", server); - if (returnUrl.IndexOf("virtualearth.net") > -1) - { - returnUrl += "&n=z"; - } - return returnUrl; - } - } - - public String DemURL - { - get - { - string rewritten_url = URLHelpers.singleton.rewrite(dataset.DemUrl, URLRewriteMode.AsIfAbsolute); - - if (dataset.Projection == ProjectionType.Mercator && !WWTControl.Singleton.FreestandingMode) - { - string baseUrl = URLHelpers.singleton.coreStaticUrl("wwtweb/demtile.aspx?q={0},{1},{2},M"); - if (!String.IsNullOrEmpty(rewritten_url)) - { - baseUrl = rewritten_url; - } - - //return string.Format(baseUrl, level.ToString(), x.ToString(), y.ToString()); - } - - - if (rewritten_url.IndexOf("{1}") > -1) - { - return String.Format(rewritten_url + "&new", Level, tileX, tileY); - } - - string returnUrl = rewritten_url; - - returnUrl = returnUrl.Replace("{X}", tileX.ToString()); - returnUrl = returnUrl.Replace("{Y}", tileY.ToString()); - returnUrl = returnUrl.Replace("{L}", Level.ToString()); - int hash = 0; - if (returnUrl.IndexOf("{S:0}") > -1) - { - hash = 0; - returnUrl = returnUrl.Replace("{S:0}", "{S}"); - } - if (returnUrl.IndexOf("{S:1}") > -1) - { - hash = 1; - returnUrl = returnUrl.Replace("{S:1}", "{S}"); - } - if (returnUrl.IndexOf("{S:2}") > -1) - { - hash = 2; - returnUrl = returnUrl.Replace("{S:2}", "{S}"); - } - if (returnUrl.IndexOf("{S:3}") > -1) - { - hash = 3; - returnUrl = returnUrl.Replace("{S:3}", "{S}"); - } - - - string id = GetTileID(); - string server = ""; - - if (id.Length == 0) - { - server = hash.ToString(); - } - else - { - server = id.Substr(id.Length - 1, 1).ToString(); - } - - - returnUrl = returnUrl.Replace("{Q}", id); - - returnUrl = returnUrl.Replace("{S}", server); - - return returnUrl; - } - } - - public int GetServerID() - { - int server = (this.tileX & 1) + ((this.tileY & 1) << 1); - - return (server); - } - - string tileId = null; - public string GetTileID() - { - if (tileId != null) - { - return tileId; - } - - int netLevel = Level; - int netX = tileX; - int netY = tileY; - - if (dataset.Projection == ProjectionType.Equirectangular) - { - netLevel++; - //netX = x*2; - //netY = y*2; - } - - string tileMap = this.dataset.QuadTreeTileMap; - - if (!string.IsNullOrEmpty(tileMap)) - { - StringBuilder sb = new StringBuilder(); - - for (int i = netLevel; i > 0; --i) - { - int mask = 1 << (i - 1); - int val = 0; - - if ((netX & mask) != 0) - val = 1; - - if ((netY & mask) != 0) - val += 2; - - sb.Append(tileMap.Substr(val, 1)); - - } - tileId = sb.ToString(); - return tileId; - } - else - { - tileId = "0"; - return tileId; - } - } - - private int vertexCount; - - protected int VertexCount - { - get - { - - return vertexCount; - } - set - { - vertexCount = value; - } - } - protected BlendState[] renderChildPart = null; - - public Tile() - { - renderChildPart = new BlendState[4]; - for (int i = 0; i < 4; i++) - { - renderChildPart[i] = BlendState.Create(false, 500); - } - } - } - -} diff --git a/engine/csharp_ref/TileCache.cs b/engine/csharp_ref/TileCache.cs deleted file mode 100644 index 2cfb09e3..00000000 --- a/engine/csharp_ref/TileCache.cs +++ /dev/null @@ -1,392 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace wwtlib -{ - class TileCache - { - private static Dictionary queue = new Dictionary(); - public static int QueueCount - { - get - { - return queue.Count; - } - } - static Dictionary tiles = new Dictionary(); - //internal static void AddTileToQueue(Tile tile) - //{ - - // queue[tile.Key] = tile; - //} - - public static Tile GetTile(int level, int x, int y, Imageset dataset, Tile parent) - { - - Tile retTile = null; - string tileKey = Imageset.GetTileKey(dataset, level, x, y, parent); - // try - { - if (!tiles.ContainsKey(tileKey)) - { - retTile = Imageset.GetNewTile(dataset, level, x, y, parent); - if(retTile != null) - { - tiles[tileKey] = retTile; - } - - } - else - { - retTile = tiles[tileKey]; - } - } - // catch - { - int p = 0; - } - - return retTile; - - } - - public static Tile GetCachedTile(int level, int x, int y, Imageset dataset, Tile parent) - { - if (level < dataset.BaseLevel) - { - return null; - } - - Tile retTile = null; - string tileKey = Imageset.GetTileKey(dataset, level, x, y, parent); - try - { - if (!tiles.ContainsKey(tileKey)) - { - return null; - } - else - { - retTile = tiles[tileKey]; - } - } - catch - { - } - - return retTile; - } - - public static int GetReadyToRenderTileCount() - { - List notReadyCullList = new List(); - List readyCullList = new List(); - - try - { - try - { - foreach (string key in tiles.Keys) - { - Tile tile = tiles[key]; - - if (tile.RenderedGeneration < (Tile.CurrentRenderGeneration - 10) && !(tile.RequestPending || tile.Downloading)) - { - if (tile.ReadyToRender) - { - readyCullList.Add(tile); - } - else - { - notReadyCullList.Add(tile); - } - } - } - } - catch - { - - } - return readyCullList.Count; - } - catch - { - return -1; - } - } - - const int MaxDownloadCount = 8; - - public static int openThreads = 8; - - public static void ProcessQueue(RenderContext renderContext) - { - - while(queue.Count > 0 && openThreads > 0) - { - - - double minDistance = 100000.0f; - bool overlayTile = false; - string maxKey = null; - int level = 1000; - - foreach (String key in queue.Keys) - { - Tile t = queue[key]; - if (!t.RequestPending && t.InViewFrustum) - { - - Vector3d vectTemp = Vector3d.MakeCopy(t.SphereCenter); - - vectTemp.TransformByMatrics(renderContext.World); - - if (renderContext.Space) - { - vectTemp.Subtract(Vector3d.Create(0.0f, 0.0f, -1.0f)); - } - else - { - vectTemp.Subtract(renderContext.CameraPosition); - } - - double distTemp = Math.Max(0, vectTemp.Length() - t.SphereRadius); - - - - //if (t.Level < (level-1) || (distTemp < minDistance && t.Level == level)) - bool thisIsOverlay = (t.Dataset.Projection == ProjectionType.Tangent) || (t.Dataset.Projection == ProjectionType.SkyImage); - if (distTemp < minDistance && (!overlayTile || thisIsOverlay)) - { - minDistance = distTemp; - maxKey = t.Key; - level = t.Level; - overlayTile = thisIsOverlay; - } - } - - } - if (maxKey != null) - { - Tile workTile = (Tile)queue[maxKey]; - workTile.RequestPending = true; - openThreads--; - if (openThreads < 0) - { - openThreads = 0; - } - workTile.RequestImage(); - if (workTile.Dataset.ElevationModel )// && workTile.Dataset.Projection == ProjectionType.Toast) - { - workTile.RequestDem(); - } - } - else - { - return; - } - } - } - - - public static bool AddTileToQueue(Tile tile) - { - - int hitValue; - - hitValue = 256; - - - if (!tile.Downloading && !tile.ReadyToRender) - { - - if (queue.ContainsKey(tile.Key)) - { - (queue[tile.Key]).RequestHits += hitValue; - } - else - { - tile.RequestHits = hitValue; - queue[tile.Key] = tile; - } - } - - return true; - } - - public static void RemoveFromQueue(string key, bool complete) - { - if (complete) - { - Tile workTile = (Tile)queue[key]; - if (workTile != null) - { - workTile.RequestPending = false; - queue.Remove(workTile.Key); - } - openThreads++; - } - queue.Remove(key); - } - - public static void ClearCache() - { - - tiles.Clear(); - - } - - public static void PurgeQueue() - { - - queue.Clear(); - - } - - public static int readyToRenderCount = 0; - public static int maxTileCacheSize = 800; - public static int maxReadyToRenderSize = 200; - public static int AccessID = 0; - - static int maxTotalToPurge = 0; - public static void PurgeLRU() - { - if (tiles.Count < maxReadyToRenderSize) - { - return; - } - - List notReadyCullList = new List(); - List readyCullList = new List(); - - try - { - try - { - foreach (string key in tiles.Keys) - { - Tile tile = tiles[key]; - - if (tile.RenderedGeneration < (Tile.CurrentRenderGeneration - 10) && !(tile.RequestPending || tile.Downloading)) - { - if (tile.ReadyToRender) - { - readyCullList.Add(tile); - } - else - { - notReadyCullList.Add(tile); - } - } - } - } - catch - { - } - readyToRenderCount = readyCullList.Count; - - if (readyCullList.Count > maxReadyToRenderSize) - { - readyCullList.Sort(delegate(Tile t1, Tile t2) - { - return t2.AccessCount < t1.AccessCount ? 1 : (t2.AccessCount == t1.AccessCount ? 0 : -1); - } - ); - int totalToPurge = readyCullList.Count - maxReadyToRenderSize; - - foreach (Tile tile in readyCullList) - { - if (totalToPurge < 1) - { - break; - } - tile.CleanUp(false); - - //tile.CleanUp(true); - //tiles.Remove(tile.Key); - totalToPurge--; - } - } - - if (tiles.Count < maxTileCacheSize) - { - return; - } - - if (notReadyCullList.Count > maxTileCacheSize) - { - notReadyCullList.Sort(delegate(Tile t1, Tile t2) - { - return t2.AccessCount < t1.AccessCount ? 1 : (t2.AccessCount == t1.AccessCount ? 0 : -1); - } - ); - - int totalToPurge = notReadyCullList.Count - maxTileCacheSize; - if (totalToPurge > 20) - { - totalToPurge = 20; - } - foreach (Tile tile in notReadyCullList) - { - if (totalToPurge < 1) - { - break; - } - tile.CleanUp(true); - tiles.Remove(tile.Key); - - totalToPurge--; - } - } - } - catch - { - } - finally - { - - } - - return; - } - - - // Age things in queue. If they are not visible they will go away in time - public static void DecimateQueue() - { - List list = new List(); - - foreach (string key in queue.Keys) - { - Tile t = queue[key]; - if (!t.RequestPending) - { - t.RequestHits = t.RequestHits / 2; - try - { - if (t.RequestHits < 2)// && !t.DirectLoad) - { - list.Add(t); - } - else if (!t.InViewFrustum) - { - list.Add(t); - } - } - catch - { - } - } - - } - foreach (Tile t in list) - { - queue.Remove(t.Key); - } - - - - } - } -} diff --git a/engine/csharp_ref/ToastTile.cs b/engine/csharp_ref/ToastTile.cs deleted file mode 100644 index d9e5ec9f..00000000 --- a/engine/csharp_ref/ToastTile.cs +++ /dev/null @@ -1,928 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -namespace wwtlib -{ - public class ToastTile : Tile - { - bool topDown = true; - - protected PositionTexture[] bounds; - protected bool backslash = false; - List vertexList = null; - List[] childTriangleList = null; - - protected float[] demArray; - protected void ComputeBoundingSphere() - { - InitializeGrids(); - - TopLeft = bounds[0 + 3 * 0].Position.Copy(); - BottomRight = bounds[2 + 3 * 2].Position.Copy(); - TopRight = bounds[2 + 3 * 0].Position.Copy(); - BottomLeft = bounds[0 + 3 * 2].Position.Copy(); - CalcSphere(); - } - - static protected WebGLBuffer[] slashIndexBuffer = new WebGLBuffer[64]; - static protected WebGLBuffer[] backSlashIndexBuffer = new WebGLBuffer[64]; - static protected WebGLBuffer[] rootIndexBuffer = new WebGLBuffer[4]; - - public override WebGLBuffer GetIndexBuffer(int index, int accomidation) - { - if (Level == 0) - { - return rootIndexBuffer[index]; - } - - if (backslash) - { - return backSlashIndexBuffer[index * 16 + accomidation]; - } - else - { - return slashIndexBuffer[index * 16 + accomidation]; - } - } - - private void ProcessIndexBuffer(UInt16[] indexArray, int part) - { - - if (Level == 0) - { - rootIndexBuffer[part] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, rootIndexBuffer[part]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER,(Uint16Array)(object)indexArray, GL.STATIC_DRAW); - return; - } - - for (int a = 0; a < 16; a++) - { - UInt16[] partArray = CloneArray(indexArray); - ProcessAccomindations(partArray, a); - if (backslash) - { - backSlashIndexBuffer[part * 16 + a] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, backSlashIndexBuffer[part * 16 + a]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, (Uint16Array)(object)partArray, GL.STATIC_DRAW); - } - else - { - slashIndexBuffer[part * 16 + a] = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, slashIndexBuffer[part * 16 + a]); - PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, (Uint16Array)(object)partArray, GL.STATIC_DRAW); - } - } - } - - private static UInt16[] CloneArray(UInt16[] indexArray) - { - int count = indexArray.Length; - Uint16Array ui16array = new Uint16Array(count); - - UInt16[] indexArrayNew = (UInt16[])(object)ui16array; - for (int i = 0; i < count; i++) - { - indexArrayNew[i] = indexArray[i]; - } - - return indexArrayNew; - } - - private void ProcessAccomindations(UInt16[] indexArray, int a) - { - Dictionary map = new Dictionary(); - Dictionary gridMap = new Dictionary(); - - foreach (UInt16 index in indexArray) - { - PositionTexture vert = vertexList[index]; - int arrayX = (int)(vert.Tu * 16 + .5); - int arrayY = (int)(vert.Tv * 16 + .5); - int ii = (arrayY << 8) + arrayX; - - if (!gridMap.ContainsKey(ii)) - { - gridMap[ii] = index; - } - - } - - - int sections = 16; - - if ((a & 1) == 1) - { - for (int x = 1; x < sections; x += 2) - { - int y = sections; - int key = (y << 8) + x; - int val = (y << 8) + x + 1; - if (gridMap.ContainsKey(key)) - { - map[gridMap[key]] = (gridMap[val]); - } - } - } - - if ((a & 2) == 2) - { - for (int y = 1; y < sections; y += 2) - { - int x = sections; - int key = (y << 8) + x; - int val = ((y + 1) << 8) + x; - if (gridMap.ContainsKey(key)) - { - map[gridMap[key]] = (gridMap[val]); - } - } - } - - if ((a & 4) == 4) - { - for (int x = 1; x < sections; x += 2) - { - int y = 0; - int key = (y << 8) + x; - int val = (y << 8) + x + 1; - if (gridMap.ContainsKey(key)) - { - map[gridMap[key]] = (gridMap[val]); - } - } - } - - if ((a & 8) == 8) - { - for (int y = 1; y < sections; y += 2) - { - int x = 0; - int key = (y << 8) + x; - int val = ((y + 1) << 8) + x; - if (gridMap.ContainsKey(key)) - { - map[gridMap[key]] = (gridMap[val]); - } - } - } - - if (map.Count == 0) - { - //nothing to process - return; - } - - for (int i = 0; i < indexArray.Length; i++) - { - if (map.ContainsKey(indexArray[i])) - { - indexArray[i] = map[indexArray[i]]; - } - } - } - - - protected void CalculateFullSphere(Vector3d[] list) - { - SphereHull result = ConvexHull.FindEnclosingSphere(list); - - sphereCenter = result.Center; - sphereRadius = result.Radius; - } - - public override bool IsPointInTile(double lat, double lng) - { - - if (Level == 0) - { - return true; - } - - if (Level == 1) - { - if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1)) - { - return true; - } - if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1)) - { - return true; - } - if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0)) - { - return true; - } - if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0)) - { - return true; - } - return false; - } - - if (!this.DemReady || this.DemData == null) - { - return false; - } - - Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng); - bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint); - bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint); - bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint); - bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint); - - if (top && right && bottom && left) - { - // showSelected = true; - return true; - } - return false; ; - - } - - private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) - { - pntA.Normalize(); - pntB.Normalize(); - Vector3d cross = Vector3d.Cross(pntA, pntB); - - double dot = Vector3d.Dot(cross, pntTest); - - return dot < 0; - } - - public override double GetSurfacePointAltitude(double lat, double lng, bool meters) - { - - if (Level < lastDeepestLevel) - { - //interate children - for(int ii=0; ii < 4; ii++) - { - Tile child = children[ii]; - if (child != null) - { - if (child.IsPointInTile(lat, lng)) - { - double retVal = child.GetSurfacePointAltitude(lat, lng, meters); - if (retVal != 0) - { - return retVal; - } - else - { - break; - } - } - } - } - } - - TileTargetLevel = Level; - TileTargetX = tileX; - TileTargetY = tileY; - - - - Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng); - testPoint = Vector3d.SubtractVectors(new Vector3d(), testPoint); - Vector2d uv = DistanceCalc.GetUVFromInnerPoint(TopLeft.Copy(), TopRight.Copy(), BottomLeft.Copy(), BottomRight.Copy(), testPoint.Copy()); - - - //Document.Title = "u:" + uv.X + ", v:" + uv.Y; - //uv.X = 1 - uv.X; - //uv.Y = 1 - uv.Y; - // Get 4 samples and interpolate - double uud = Math.Max(0, Math.Min(16, (uv.X * 16))); - double vvd = Math.Max(0, Math.Min(16, (uv.Y * 16))); - - - - int uu = Math.Max(0, Math.Min(15, (int)(uv.X * 16))); - int vv = Math.Max(0, Math.Min(15, (int)(uv.Y * 16))); - - double ha = uud - uu; - double va = vvd - vv; - - if (demArray != null) - { - // 4 nearest neighbors - double ul = demArray[uu + 17 * vv]; - double ur = demArray[(uu + 1) + 17 * vv]; - double ll = demArray[uu + 17 * (vv + 1)]; - double lr = demArray[(uu + 1) + 17 * (vv + 1)]; - - double top = ul * (1 - ha) + ha * ur; - double bottom = ll * (1 - ha) + ha * lr; - double val = top * (1 - va) + va * bottom; - - return val / DemScaleFactor; - } - - return demAverage / DemScaleFactor; - } - - - private void InitializeGrids() - { - vertexList = new List(); - childTriangleList = new List[4]; - childTriangleList[0] = new List(); - childTriangleList[1] = new List(); - childTriangleList[2] = new List(); - childTriangleList[3] = new List(); - - bounds = new PositionTexture[9]; - - if (Level > 0) - { - // Set in constuctor now - //ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null); - if (Parent == null) - { - Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null); - } - - ToastTile parent = (ToastTile)Parent; - - int xIndex = tileX % 2; - int yIndex = tileY % 2; - - if (Level > 1) - { - backslash = parent.backslash; - } - else - { - backslash = xIndex == 1 ^ yIndex == 1; - } - - - bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy(); - bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); - bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy(); - bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - - if (backslash) - { - bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - } - else - { - bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - } - - bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy(); - bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy(); - - bounds[0 + 3 * 0].Tu = 0*uvMultiple; - bounds[0 + 3 * 0].Tv = 0 * uvMultiple; - bounds[1 + 3 * 0].Tu = .5f * uvMultiple; - bounds[1 + 3 * 0].Tv = 0 * uvMultiple; - bounds[2 + 3 * 0].Tu = 1 * uvMultiple; - bounds[2 + 3 * 0].Tv = 0 * uvMultiple; - - bounds[0 + 3 * 1].Tu = 0 * uvMultiple; - bounds[0 + 3 * 1].Tv = .5f * uvMultiple; - bounds[1 + 3 * 1].Tu = .5f * uvMultiple; - bounds[1 + 3 * 1].Tv = .5f * uvMultiple; - bounds[2 + 3 * 1].Tu = 1 * uvMultiple; - bounds[2 + 3 * 1].Tv = .5f * uvMultiple; - - bounds[0 + 3 * 2].Tu = 0 * uvMultiple; - bounds[0 + 3 * 2].Tv = 1 * uvMultiple; - bounds[1 + 3 * 2].Tu = .5f * uvMultiple; - bounds[1 + 3 * 2].Tv = 1 * uvMultiple; - bounds[2 + 3 * 2].Tu = 1 * uvMultiple; - bounds[2 + 3 * 2].Tv = 1 * uvMultiple; - - vertexList.Add(bounds[0 + 3 * 0]); - vertexList.Add(bounds[1 + 3 * 0]); - vertexList.Add(bounds[2 + 3 * 0]); - vertexList.Add(bounds[0 + 3 * 1]); - vertexList.Add(bounds[1 + 3 * 1]); - vertexList.Add(bounds[2 + 3 * 1]); - vertexList.Add(bounds[0 + 3 * 2]); - vertexList.Add(bounds[1 + 3 * 2]); - vertexList.Add(bounds[2 + 3 * 2]); - - - - - if (backslash) - { - childTriangleList[0].Add(Triangle.Create(4, 1, 0)); - childTriangleList[0].Add(Triangle.Create(3, 4, 0)); - childTriangleList[1].Add(Triangle.Create(5, 2, 1)); - childTriangleList[1].Add(Triangle.Create(4, 5, 1)); - childTriangleList[2].Add(Triangle.Create(7, 4, 3)); - childTriangleList[2].Add(Triangle.Create(6, 7, 3)); - childTriangleList[3].Add(Triangle.Create(8, 5, 4)); - childTriangleList[3].Add(Triangle.Create(7, 8, 4)); - } - else - { - childTriangleList[0].Add(Triangle.Create(3, 1, 0)); - childTriangleList[0].Add(Triangle.Create(4, 1, 3)); - childTriangleList[1].Add(Triangle.Create(4, 2, 1)); - childTriangleList[1].Add(Triangle.Create(5, 2, 4)); - childTriangleList[2].Add(Triangle.Create(6, 4, 3)); - childTriangleList[2].Add(Triangle.Create(7, 4, 6)); - childTriangleList[3].Add(Triangle.Create(7, 5, 4)); - childTriangleList[3].Add(Triangle.Create(8, 5, 7)); - } - } - else - { - bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0); - bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0); - bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0); - bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f); - bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f); - bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f); - bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1); - bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1); - bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1); - - vertexList.Add(bounds[0 + 3 * 0]); - vertexList.Add(bounds[1 + 3 * 0]); - vertexList.Add(bounds[2 + 3 * 0]); - vertexList.Add(bounds[0 + 3 * 1]); - vertexList.Add(bounds[1 + 3 * 1]); - vertexList.Add(bounds[2 + 3 * 1]); - vertexList.Add(bounds[0 + 3 * 2]); - vertexList.Add(bounds[1 + 3 * 2]); - vertexList.Add(bounds[2 + 3 * 2]); - - childTriangleList[0].Add(Triangle.Create(3, 1, 0)); - childTriangleList[0].Add(Triangle.Create(4, 1, 3)); - childTriangleList[1].Add(Triangle.Create(5, 2, 1)); - childTriangleList[1].Add(Triangle.Create(4, 5, 1)); - childTriangleList[2].Add(Triangle.Create(7, 4, 3)); - childTriangleList[2].Add(Triangle.Create(6, 7, 3)); - childTriangleList[3].Add(Triangle.Create(7, 5, 4)); - childTriangleList[3].Add(Triangle.Create(8, 5, 7)); - // Setup default matrix of points. - } - } - - private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2) - { - Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f); - Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f); - - a1.Normalize(); - return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y); - } - int subDivisionLevel = 4; - bool subDivided = false; - - public override bool CreateGeometry(RenderContext renderContext) - { - if (GeometryCreated) - { - return true; - } - - GeometryCreated = true; - base.CreateGeometry(renderContext); - if (!subDivided) - { - - - - if (vertexList == null) - { - InitializeGrids(); - } - - if (uvMultiple == 256) - { - if (dataset.DataSetType == ImageSetType.Earth || dataset.DataSetType == ImageSetType.Planet) - { - subDivisionLevel = Math.Min(5, Math.Max(0, 5 - Level)); - } - else - { - subDivisionLevel = Math.Min(5, Math.Max(0, 5 - Level)); - - } - - } - else - { - if (demTile && Level > 1) - { - demArray = new float[17 * 17]; - demSize = 17 * 17; - if (backslash) - { - if (backslashYIndex == null) - { - tempBackslashYIndex = new byte[demSize]; - tempBackslashXIndex = new byte[demSize]; - } - } - else - { - if (slashYIndex == null) - { - tempSlashYIndex = new byte[demSize]; - tempSlashXIndex = new byte[demSize]; - } - } - } - } - - for (int i = 0; i < 4; i++) - { - int count = subDivisionLevel; - while (count-- > 1) - { - List newList = new List(); - foreach (Triangle tri in childTriangleList[i]) - { - tri.SubDivide(newList, vertexList); - } - childTriangleList[i] = newList; - } - } - - if (renderContext.gl == null) - { - for (int i = 0; i < 4; i++) - { - RenderTriangleLists[i] = new List(); - foreach (Triangle tri in childTriangleList[i]) - { - PositionTexture p1 = vertexList[tri.C]; - PositionTexture p2 = vertexList[tri.B]; - PositionTexture p3 = vertexList[tri.A]; - - - RenderTriangleLists[i].Add(RenderTriangle.Create(p1, p2, p3, texture, Level)); - } - } - } - else - { - //process vertex list - VertexBuffer = PrepDevice.createBuffer(); - PrepDevice.bindBuffer(GL.ARRAY_BUFFER, VertexBuffer); - Float32Array f32array = new Float32Array(vertexList.Count * 5); - float[] buffer = (float[])(object)f32array; - int index = 0; - foreach (PositionTexture pt in vertexList) - { - if (demTile) - { - index = AddVertex(buffer, index, GetMappedVertex(pt)); - demIndex++; - } - else - { - index = AddVertex(buffer, index, pt); - } - } - if (demTile) - { - if (backslash) - { - if (tempBackslashXIndex != null) - { - backslashXIndex = tempBackslashXIndex; - backslashYIndex = tempBackslashYIndex; - tempBackslashXIndex = null; - tempBackslashYIndex = null; - } - } - else - { - if (tempSlashYIndex != null) - { - slashXIndex = tempSlashXIndex; - slashYIndex = tempSlashYIndex; - tempSlashYIndex = null; - tempSlashXIndex = null; - - } - } - } - - - PrepDevice.bufferData(GL.ARRAY_BUFFER, f32array, GL.STATIC_DRAW); - - //process index list - for (int i = 0; i < 4; i++) - { - TriangleCount = childTriangleList[i].Count; - if (GetIndexBuffer(i, 0) == null) - { - - Uint16Array ui16array = new Uint16Array(TriangleCount * 3); - - UInt16[] indexArray = (UInt16[])(object)ui16array; - - index = 0; - foreach (Triangle tri in childTriangleList[i]) - { - indexArray[index++] = (UInt16)tri.C; - indexArray[index++] = (UInt16)tri.B; - indexArray[index++] = (UInt16)tri.A; - } - ProcessIndexBuffer(indexArray, i); - } - //IndexBuffers[i] = PrepDevice.createBuffer(); - //PrepDevice.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, IndexBuffers[i]); - //PrepDevice.bufferData(GL.ELEMENT_ARRAY_BUFFER, ui16array, GL.STATIC_DRAW); - } - } - - subDivided = true; - } - - return true; - } - - private static byte[] slashXIndex; - private static byte[] slashYIndex; - private static byte[] backslashXIndex; - private static byte[] backslashYIndex; - - private byte[] tempSlashXIndex; - private byte[] tempSlashYIndex; - private byte[] tempBackslashXIndex; - private byte[] tempBackslashYIndex; - - - internal PositionTexture GetMappedVertex(PositionTexture vert) - { - PositionTexture vertOut = new PositionTexture(); - Coordinates latLng = Coordinates.CartesianToSpherical2(vert.Position); - // latLng.Lng += 90; - if (latLng.Lng < -180) - { - latLng.Lng += 360; - } - if (latLng.Lng > 180) - { - latLng.Lng -= 360; - } - - - if (Level > 1) - { - byte arrayX = (byte)(int)(vert.Tu * 16 + .5); - byte arrayY = (byte)(int)(vert.Tv * 16 + .5); - demArray[arrayX + arrayY * 17] = DemData[demIndex]; - - if (backslash) - { - if (tempBackslashYIndex != null) - { - tempBackslashXIndex[demIndex] = arrayX; - tempBackslashYIndex[demIndex] = arrayY; - } - } - else - { - if (tempSlashYIndex != null) - { - tempSlashXIndex[demIndex] = arrayX; - tempSlashYIndex[demIndex] = arrayY; - } - } - } - - Vector3d pos = GeoTo3dWithAlt(latLng.Lat, latLng.Lng, false, false); - vertOut.Tu = (float)vert.Tu; - vertOut.Tv = (float)vert.Tv; - - //vertOut.Lat = latLng.Lat; - //vertOut.Lng = latLng.Lng; - //vertOut.Normal = pos; - pos.Subtract(localCenter); - vertOut.Position = pos; - - - return vertOut; - } - - //public override bool IsTileBigEnough(RenderContext renderContext) - //{ - // // return Level < 1; - // double arcPixels = 0; - // if (dataset.DataSetType == ImageSetType.Earth) - // { - // arcPixels = (1600 / Math.Pow(2, Level)); - // } - // else - // { - // arcPixels = (3600 / Math.Pow(2, Level)); - - // } - // return (renderContext.FovScale < arcPixels); - //} - - - - //int quadrant = 0; - - //private void ComputeQuadrant() - //{ - // int xQuad = 0; - // int yQuad = 0; - // int tiles = (int)Math.Pow(2, this.level); - - // if (x > (tiles / 2) - 1) - // { - // xQuad = 1; - // } - - // if (y > (tiles / 2) - 1) - // { - // yQuad = 1; - // } - // quadrant = yQuad * 2 + xQuad; - //} - - public ToastTile() - { - } - - public static ToastTile Create(int level, int xc, int yc, Imageset dataset, Tile parent) - { - ToastTile temp = new ToastTile(); - temp.Parent = parent; - temp.Level = level; - temp.tileX = xc; - temp.tileY = yc; - temp.dataset = dataset; - temp.topDown = !dataset.BottomsUp; - - - if (temp.tileX != (int)xc) - { - Script.Literal("alert('bad')"); - } - //temp.ComputeQuadrant(); - - if (dataset.MeanRadius != 0) - { - temp.DemScaleFactor = dataset.MeanRadius; - } - else - { - if (dataset.DataSetType == ImageSetType.Earth) - { - temp.DemScaleFactor = 6371000; - } - else - { - temp.DemScaleFactor = 3396010; - } - } - - - temp.ComputeBoundingSphere(); - return temp; - } - - public override void CleanUp(bool removeFromParent) - { - base.CleanUp(removeFromParent); - - if (vertexList != null) - { - vertexList = null; - } - if (childTriangleList != null) - { - childTriangleList = null; - } - - - subDivided = false; - demArray = null; - } - - private float GetDemSample(int xc, int yc) - { - return demArray[(16 - yc) * 17 + xc]; - } - - public override bool CreateDemFromParent() - { - - - ToastTile parent = Parent as ToastTile; - if (parent == null) - { - return false; - } - - int offsetX = ((tileX % 2) == 1 ? 8 : 0); - int offsetY = ((tileY % 2) == 0 ? 8 : 0); - - - demArray = new float[17 * 17]; - // Interpolate accross - for (int yy1 = 0; yy1 < 17; yy1 += 2) - { - bool copy = true; - for (int xx1 = 0; xx1 < 17; xx1++) - { - if (copy) - { - demArray[(16 - yy1) * 17 + xx1] = parent.GetDemSample((xx1 / 2) + offsetX, (yy1 / 2) + offsetY); - } - else - { - demArray[(16 - yy1) * 17 + xx1] = - ( - ( - parent.GetDemSample((xx1 / 2) + offsetX, (yy1 / 2) + offsetY) + - parent.GetDemSample(((xx1 / 2) + offsetX) + 1, (yy1 / 2) + offsetY) - ) / 2); - } - copy = !copy; - - } - } - // Interpolate down - for (int yy2 = 1; yy2 < 17; yy2 += 2) - { - for (int xx2 = 0; xx2 < 17; xx2++) - { - - demArray[(16 - yy2) * 17 + xx2] = - ( - ( - GetDemSample(xx2, yy2 - 1) + - GetDemSample(xx2, yy2 + 1) - ) / 2); - - } - } - - // Convert the dem array back to the arranged DEM list thu slash/backslash mapping tables - - - DemData = new float[demSize]; - for (int i = 0; i < demSize; i++) - { - if (backslash) - { - DemData[i] = demArray[backslashXIndex[i] + backslashYIndex[i] * 17]; - } - else - { - DemData[i] = demArray[slashXIndex[i] + slashYIndex[i] * 17]; - } - demAverage += DemData[i]; - - } - - // Get Average value for new DemData table - - demAverage /= DemData.Length; - - DemReady = true; - return true; - } - } - - class DistanceCalc - { - static public double LineToPoint(Vector3d l0, Vector3d l1, Vector3d p) - { - Vector3d v = Vector3d.SubtractVectors(l1, l0); - Vector3d w = Vector3d.SubtractVectors(p, l0); - - double dist = Vector3d.Cross(w, v).Length() / v.Length(); - - return dist; - } - - static public Vector2d GetUVFromInnerPoint(Vector3d ul, Vector3d ur, Vector3d ll, Vector3d lr, Vector3d pnt) - { - ul.Normalize(); - ur.Normalize(); - ll.Normalize(); - lr.Normalize(); - pnt.Normalize(); - - double dUpper = LineToPoint(ul, ur, pnt); - double dLower = LineToPoint(ll, lr, pnt); - double dVert = dUpper + dLower; - - double dRight = LineToPoint(ur, lr, pnt); - double dLeft = LineToPoint(ul, ll, pnt); - double dHoriz = dRight + dLeft; - - return Vector2d.Create(dLeft / dHoriz, dUpper / dVert); - } - } -} diff --git a/engine/csharp_ref/Tour.cs b/engine/csharp_ref/Tour.cs deleted file mode 100644 index b0ec02e7..00000000 --- a/engine/csharp_ref/Tour.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - - -namespace wwtlib -{ - public class Tour : IThumbnail - { - public Tour() - { - } - - internal static Tour FromXml(System.Xml.XmlNode child) - { - Tour temp = new Tour(); - if (child.Attributes.GetNamedItem("ID") != null) - { - temp.Id = child.Attributes.GetNamedItem("ID").Value; - } - if (child.Attributes.GetNamedItem("TourUrl") != null) - { - temp.tourUrl = child.Attributes.GetNamedItem("TourUrl").Value; - } - - if (child.Attributes.GetNamedItem("Title") != null) - { - temp.Title = child.Attributes.GetNamedItem("Title").Value; - } - - if (child.Attributes.GetNamedItem("Description") != null) - { - temp.Description = child.Attributes.GetNamedItem("Description").Value; - } - if (child.Attributes.GetNamedItem("Classification") != null) - { - temp.Classification = (Classification)Enums.Parse("Classification", child.Attributes.GetNamedItem("Classification").Value); - } - if (child.Attributes.GetNamedItem("AuthorEmail") != null) - { - temp.AuthorEmail = child.Attributes.GetNamedItem("AuthorEmail").Value; - } - if (child.Attributes.GetNamedItem("Author") != null) - { - temp.Author = child.Attributes.GetNamedItem("Author").Value; - } - if (child.Attributes.GetNamedItem("AuthorURL") != null) - { - temp.AuthorURL = child.Attributes.GetNamedItem("AuthorURL").Value; - } - - if (child.Attributes.GetNamedItem("AuthorImageUrl") != null) - { - temp.AuthorImageUrl = child.Attributes.GetNamedItem("AuthorImageUrl").Value; - } - - if (child.Attributes.GetNamedItem("AverageRating") != null) - { - temp.AverageRating = double.Parse(child.Attributes.GetNamedItem("AverageRating").Value); - } - if (child.Attributes.GetNamedItem("LengthInSecs") != null) - { - temp.LengthInSecs = double.Parse(child.Attributes.GetNamedItem("LengthInSecs").Value); - } - if (child.Attributes.GetNamedItem("OrganizationUrl") != null) - { - temp.OrganizationUrl = child.Attributes.GetNamedItem("OrganizationUrl").Value; - } - if (child.Attributes.GetNamedItem("OrganizationName") != null) - { - temp.OrganizationName = child.Attributes.GetNamedItem("OrganizationName").Value; - } - if (child.Attributes.GetNamedItem("RelatedTours") != null) - { - temp.RelatedTours = child.Attributes.GetNamedItem("RelatedTours").Value; - } - if (child.Attributes.GetNamedItem("Keywords") != null) - { - temp.Keywords = child.Attributes.GetNamedItem("Keywords").Value; - } - if (child.Attributes.GetNamedItem("ThumbnailUrl") != null) - { - temp.ThumbnailUrl = child.Attributes.GetNamedItem("ThumbnailUrl").Value; - } - - return temp; - - } - - public UserLevel userLevel; - public string Title; - public string Taxonomy; - public string OrganizationName; - public string OrganizationUrl; - public string Id; - public string Description; - public Classification Classification; - public string AuthorEmail; - public string Author; - public string TourDuration; - public string AuthorURL; - public double AverageRating; - public double LengthInSecs; - public string TourAttributionAndCredits; - public string AuthorImageUrl; - public string Keywords; - public string RelatedTours; - - - #region IThumbnail Members - - public string Name - { - get { return Title; } - } - - ImageElement thumbnail; - public System.Html.ImageElement Thumbnail - { - get - { - return thumbnail; - } - set - { - thumbnail = value; - } - } - - string thumbnailUrlField = ""; - - public string ThumbnailUrl - { - get - { - if (!String.IsNullOrEmpty(thumbnailUrlField)) - { - return thumbnailUrlField; - } - else if (WWTControl.Singleton.FreestandingMode) - { - return URLHelpers.singleton.engineAssetUrl("thumb_star.jpg"); - } - { - return String.Format(URLHelpers.singleton.coreStaticUrl("wwtweb/GetTourThumbnail.aspx?GUID={0}"), Id); - } - } - set - { - - thumbnailUrlField = value.ToString(); - } - } - - string tourUrl; - - public string TourUrl - { - get - { - if (string.IsNullOrEmpty(tourUrl) && !WWTControl.Singleton.FreestandingMode) - { - return string.Format(URLHelpers.singleton.coreStaticUrl("wwtweb/GetTour.aspx?GUID={0}"), this.Id); - } - else - { - return tourUrl; - } - } - set { tourUrl = value; } - } - - - Rectangle bounds; - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds=value; - } - } - - public bool IsImage - { - get { return false; } - } - - public bool IsTour - { - get { return true; } - } - - public bool IsFolder - { - get { return false; } - } - - public bool IsCloudCommunityItem - { - get { return false; } - } - - public bool ReadOnly - { - get { return false; } - } - - public List Children - { - get { return new List();} - } - - #endregion - } -} diff --git a/engine/csharp_ref/TourPlace.cs b/engine/csharp_ref/TourPlace.cs deleted file mode 100644 index 047c6dd3..00000000 --- a/engine/csharp_ref/TourPlace.cs +++ /dev/null @@ -1,659 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; - -namespace wwtlib -{ - public class Place : IThumbnail, IPlace - { - public Place() - { - // - // TODO: Add constructor logic here - // - } - - private object tag; - - public object Tag - { - get { return tag; } - set { tag = value; } - } - - private string url; - - public string Url - { - get { return url; } - set { url = value; } - } - - private ImageElement thumbnail; - - public ImageElement Thumbnail - { - get { return thumbnail; } - set { thumbnail = value; } - } - - private string name; - - public string Name - { - get { return Names[0]; } - // set { name = value; } - } - public string[] Names - { - get - { - if (string.IsNullOrEmpty(name)) - { - return ("").Split(";"); - } - return name.Split(";"); - } - set - { - name = UiTools.GetNamesStringFromArray(value); - } - } - - private CameraParameters camParams = CameraParameters.Create(0.0, 0.0, -1.0, 0, 0, 100); - - public CameraParameters CamParams - { - get - { - if (Classification == Classification.SolarSystem && camParams.Target == SolarSystemObjects.Custom) - { - // todo wire this up when astrocalc is moved - //AstroRaDec raDec = Planets.GetPlanetLocation(Name); - //camParams.RA = raDec.RA; - //camParams.Dec = raDec.Dec; - //this.distnace = raDec.Distance; - } - - return camParams; - } - set { camParams = value; } - } - - public void UpdatePlanetLocation(double jNow) - { - //camParams.ViewTarget = Planets.GetPlanet3dLocation(Target, jNow); - if (Target != SolarSystemObjects.Undefined && Target != SolarSystemObjects.Custom) - { - //todo add back when planets are added - // camParams.ViewTarget = Planets.GetPlanetTargetPoint(Target, Lat, Lng, jNow); - } - } - - Vector3d location3d = Vector3d.Create(0, 0, 0); - - public Vector3d Location3d - { - get - { - if (Classification == Classification.SolarSystem || (location3d.X == 0 && location3d.Y == 0 && location3d.Z == 0)) - { - location3d = Coordinates.RADecTo3d(this.RA, this.Dec); - } - return location3d; - } - } - - public double Lat - { - get { return CamParams.Lat; } - set { camParams.Lat = value; } - } - - public double Lng - { - get { return CamParams.Lng; } - set { camParams.Lng = value; } - } - - public double Opacity - { - get { return CamParams.Opacity; } - set { camParams.Opacity = value; } - } - public string HtmlDescription = ""; - - private string constellation = ""; - - public string Constellation - { - get { return constellation; } - set { constellation = value; } - } - private Classification classification = Classification.Galaxy; - - public Classification Classification - { - get { return classification; } - set { classification = value; } - } - private ImageSetType type = ImageSetType.Sky; - - public ImageSetType Type - { - get { return type; } - set { type = value; } - } - private double magnitude = 0; - - public double Magnitude - { - get { return magnitude; } - set { magnitude = value; } - } - private double distnace = 0; - - public double Distance - { - get { return distnace; } - set { distnace = value; } - } - /// - /// Angular Size in Arc Seconds - /// - public double AngularSize = 60; - - - public double ZoomLevel - { - get { return CamParams.Zoom; } - set { camParams.Zoom = value; } - } - - ImageElement thumbNail = null; - - private IImageSet studyImageset = null; - - public IImageSet StudyImageset - { - get { return studyImageset; } - set { studyImageset = value; } - } - - - private IImageSet backgroundImageSet = null; - - public IImageSet BackgroundImageSet - { - get { return backgroundImageSet; } - set - { - if (value != null) - { - Type = value.DataSetType; - } - backgroundImageSet = value; - } - } - - private double searchDistance = 0; - - public double SearchDistance - { - get { return searchDistance; } - set { searchDistance = value; } - } - - double elevation = 50; - - public double Elevation - { - get { return elevation; } - set { elevation = value; } - } - - private string thumbnailField; - - public string ThumbnailUrl - { - get - { - if (string.IsNullOrEmpty(this.thumbnailField)) - { - if (studyImageset != null && !string.IsNullOrEmpty(studyImageset.ThumbnailUrl)) - { - return studyImageset.ThumbnailUrl; - } - - if (backgroundImageSet != null && !string.IsNullOrEmpty(backgroundImageSet.ThumbnailUrl)) - { - return backgroundImageSet.ThumbnailUrl; - } - - string name = this.Name; - - if (name.IndexOf(";") > -1) - { - name = name.Substring(0, name.IndexOf(";")); - } - - if (Classification == Classification.Star || WWTControl.Singleton.FreestandingMode) - { - return URLHelpers.singleton.engineAssetUrl("thumb_star.jpg"); - } - - return URLHelpers.singleton.coreStaticUrl("wwtweb/thumbnail.aspx?name=" + name.ToLowerCase()); - } - - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - - public double RA - { - get - { - return CamParams.RA; - } - set - { - camParams.RA = value; - } - } - - - public double Dec - { - get { return CamParams.Dec; } - set { camParams.Dec = value; } - } - - //public Place(string name, double lat, double lng) - //{ - // this.name = name; - // Lat = lat; - // Lng = lng; - // Type = DataSetType.Geo; - // ZoomLevel = -1; - //} - - public static Place create (string name, double lat, double lng, Classification classification, string constellation, ImageSetType type, double zoomFactor) - { - Place temp = new Place(); - temp.ZoomLevel = zoomFactor; - temp.constellation = constellation; - temp.name = name; - if (type == ImageSetType.Sky || type == ImageSetType.SolarSystem) - { - temp.camParams.RA = lng; - } - else - { - temp.Lng = lng; - } - temp.Lat = lat; - temp.Classification = classification; - temp.Type = type; - - return temp; - } - - public static Place CreateCameraParams(string name, CameraParameters camParams, Classification classification, string constellation, ImageSetType type, SolarSystemObjects target) - { - Place temp = new Place(); - - temp.constellation = constellation; - temp.name = name; - temp.Classification = classification; - temp.camParams = camParams; - temp.Type = type; - temp.Target = target; - - return temp; - } - - //public TourPlace(string input, bool sky) - //{ - - // string[] sa = input.Split('\t'); - - // if (sky) - // { - // name = sa[0]; - - - // Lat = Convert.ToDouble(sa[3]); - // if (sky) - // { - // camParams.RA = Convert.ToDouble(sa[2]) / 15; - // Type = ImageSetType.Sky; - // } - // else - // { - // Lng = 180 - ((Convert.ToDouble(sa[2]) / 24.0 * 360) - 180); - // Type = ImageSetType.Earth; - // } - // string type = sa[1]; - // type = type.Replace(" ", ""); - // type = type.Replace("StarCluster", "Cluster"); - // type = type.Replace("TripleStar", "MultipleStars"); - // type = type.Replace("HubbleImage", "Unidentified"); - // Classification = (Classification)Enum.Parse(typeof(Classification), type); - // if (sa.Length > 4) - // { - // try - // { - // if (sa[4].ToUpper() != "NULL" && sa[4] != "") - // { - // magnitude = Convert.ToDouble(sa[4]); - // } - // } - // catch - // { - // } - // } - // if (sa.Length > 5) - // { - // constellation = sa[5].ToUpper(); - // } - // if (sa.Length > 6) - // { - // try - // { - // ZoomLevel = Convert.ToDouble(sa[6]); - // } - // catch - // { - // } - // } - // if (sa.Length > 7) - // { - // try - // { - // distnace = Convert.ToDouble(sa[7]); - // } - // catch - // { - // } - // } - // } - // else - // { - // name = sa[0]; - // Lat = (float)Convert.ToDouble(sa[1]); - // Lng = (float)Convert.ToDouble(sa[2]); - // Type = ImageSetType.Earth; - // if (sa.Length > 3) - // { - // elevation = Convert.ToDouble(sa[3]); - // } - // } - //} - public override string ToString() - { - return name; - } - - - - //internal void SaveToXml(System.Xml.XmlTextWriter xmlWriter, string elementName) - //{ - - // xmlWriter.WriteStartElement(elementName); - // xmlWriter.WriteAttributeString("Name", name); - // xmlWriter.WriteAttributeString("DataSetType", this.Type.ToString()); - // if (this.Type == ImageSetType.Sky) - // { - // xmlWriter.WriteAttributeString("RA", camParams.RA.ToString()); - // xmlWriter.WriteAttributeString("Dec", camParams.Dec.ToString()); - // } - // else - // { - // xmlWriter.WriteAttributeString("Lat", Lat.ToString()); - // xmlWriter.WriteAttributeString("Lng", Lng.ToString()); - // } - - // xmlWriter.WriteAttributeString("Constellation", constellation); - // xmlWriter.WriteAttributeString("Classification", Classification.ToString()); - // xmlWriter.WriteAttributeString("Magnitude", magnitude.ToString()); - // xmlWriter.WriteAttributeString("Distance", distnace.ToString()); - // xmlWriter.WriteAttributeString("AngularSize", AngularSize.ToString()); - // xmlWriter.WriteAttributeString("ZoomLevel", ZoomLevel.ToString()); - // xmlWriter.WriteAttributeString("Rotation", camParams.Rotation.ToString()); - // xmlWriter.WriteAttributeString("Angle", camParams.Angle.ToString()); - // xmlWriter.WriteAttributeString("Opacity", camParams.Opacity.ToString()); - // xmlWriter.WriteAttributeString("Target", Target.ToString()); - // xmlWriter.WriteAttributeString("ViewTarget", camParams.ViewTarget.ToString()); - // xmlWriter.WriteAttributeString("TargetReferenceFrame", camParams.TargetReferenceFrame); - // xmlWriter.WriteStartElement("Description"); - // xmlWriter.WriteCData(HtmlDescription); - // xmlWriter.WriteEndElement(); - - - // if (backgroundImageSet != null) - // { - // xmlWriter.WriteStartElement("BackgroundImageSet"); - // ImageSetHelper.SaveToXml(xmlWriter, backgroundImageSet, ""); - // xmlWriter.WriteEndElement(); - // } - - // if (studyImageset != null) - // { - // ImageSetHelper.SaveToXml(xmlWriter, studyImageset, ""); - // } - // xmlWriter.WriteEndElement(); - //} - - internal static Place FromXml(XmlNode place) - { - Place newPlace = new Place(); - - newPlace.name = place.Attributes.GetNamedItem("Name").Value; - newPlace.Type = (ImageSetType)Enum.Parse(typeof(ImageSetType), place.Attributes.GetNamedItem("DataSetType").Value); - if (newPlace.Type == ImageSetType.Sky) - { - newPlace.camParams.RA = double.Parse(place.Attributes.GetNamedItem("RA").Value); - newPlace.camParams.Dec = double.Parse(place.Attributes.GetNamedItem("Dec").Value); - } - else - { - newPlace.Lat = double.Parse(place.Attributes.GetNamedItem("Lat").Value); - newPlace.Lng = double.Parse(place.Attributes.GetNamedItem("Lng").Value); - } - - newPlace.constellation = place.Attributes.GetNamedItem("Constellation").Value; - - //todo change to switch/case - newPlace.Classification = (Classification)Enum.Parse(typeof(Classification), place.Attributes.GetNamedItem("Classification").Value); - - newPlace.magnitude = double.Parse(place.Attributes.GetNamedItem("Magnitude").Value); - if (place.Attributes.GetNamedItem("Magnitude") != null) - { - newPlace.magnitude = double.Parse(place.Attributes.GetNamedItem("Magnitude").Value); - } - newPlace.AngularSize = double.Parse(place.Attributes.GetNamedItem("AngularSize").Value); - newPlace.ZoomLevel = double.Parse(place.Attributes.GetNamedItem("ZoomLevel").Value); - newPlace.camParams.Rotation = double.Parse(place.Attributes.GetNamedItem("Rotation").Value); - newPlace.camParams.Angle = double.Parse(place.Attributes.GetNamedItem("Angle").Value); - if (place.Attributes.GetNamedItem("Opacity") != null) - { - newPlace.camParams.Opacity = Single.Parse(place.Attributes.GetNamedItem("Opacity").Value); - } - else - { - newPlace.camParams.Opacity = 100; - } - - if (place.Attributes.GetNamedItem("Target") != null) - { - newPlace.Target = (SolarSystemObjects)Enum.Parse(typeof(SolarSystemObjects), place.Attributes.GetNamedItem("Target").Value); - } - - if (place.Attributes.GetNamedItem("ViewTarget") != null) - { - newPlace.camParams.ViewTarget = Vector3d.Parse(place.Attributes.GetNamedItem("ViewTarget").Value); - } - - //if (place.Attributes.GetNamedItem("TargetReferenceFrame") != null) - //{ - // newPlace.camParams.TargetReferenceFrame = place.Attributes.GetNamedItem("TargetReferenceFrame").Value; - //} - - XmlNode descriptionNode = Util.SelectSingleNode(place,"Description"); - if (descriptionNode != null) - { - newPlace.HtmlDescription = descriptionNode.Value; - } - - XmlNode backgroundImageSet = Util.SelectSingleNode(place, "BackgroundImageSet"); - if (backgroundImageSet != null) - { - XmlNode imageSet = Util.SelectSingleNode(backgroundImageSet,"ImageSet"); - - newPlace.backgroundImageSet = Imageset.FromXMLNode(imageSet); - - } - - XmlNode study = Util.SelectSingleNode(place,"ImageSet"); - if (study != null) - { - newPlace.studyImageset = Imageset.FromXMLNode(study); - - } - return newPlace; - } - //internal static TourPlace FromAstroObjectsRow(AstroObjectsDataset.spGetAstroObjectsRow row) - //{ - // TourPlace newPlace = new TourPlace(); - - // string seperator = ""; - - // string name = ""; - - // if (!row.IsPopularName1Null() && !String.IsNullOrEmpty(row.PopularName1)) - // { - // name = ProperCaps(row.PopularName1); - // seperator = ";"; - // } - - // if (!row.IsMessierNameNull() && !String.IsNullOrEmpty(row.MessierName)) - // { - // name = name + seperator + row.MessierName; - // seperator = ";"; - // } - - // if (!row.IsNGCNameNull() && !String.IsNullOrEmpty(row.NGCName)) - // { - // name = name + seperator + row.NGCName; - // seperator = ";"; - // } - - // newPlace.name = name; - // newPlace.Type = ImageSetType.Sky; - // newPlace.Lat = row.Dec2000; - // newPlace.Lng = row.Ra2000 / 15; - // newPlace.constellation = Constellations.Abbreviation(row.ConstellationName); - // newPlace.Classification = Classification.Galaxy; //(Classification)Enum.Parse(typeof(Classification), place.Attributes["Classification"].Value); - // newPlace.magnitude = row.IsVisualMagnitudeNull() ? row.VisualMagnitude : 0; - // newPlace.AngularSize = 0; // todo fix this - // newPlace.ZoomLevel = .00009; - // return newPlace; - //} - static string ProperCaps(string name) - { - string[] list = name.Split(" "); - - string ProperName = ""; - - foreach (string part in list) - { - ProperName = ProperName + part.Substr(0,1).ToUpperCase() + (part.Length > 1 ? part.Substr(1).ToLowerCase() : "") + " "; - } - - return ProperName.Trim(); - - } - - #region IThumbnail Members - - Rectangle bounds; - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - #endregion - public bool IsImage - { - get - { - return studyImageset != null || backgroundImageSet != null; - } - } - - public bool IsTour - { - get { return false; } - } - - public bool IsFolder - { - get { return false; } - } - - public List Children - { - get { return new List(); } - } - - #region IThumbnail Members - - - public bool ReadOnly - { - get { return true; } - } - - #endregion - - #region IPlace Members - - public SolarSystemObjects Target - { - get - { - return camParams.Target; - } - set - { - camParams.Target = value; - } - } - - #endregion - - #region IThumbnail Members - - - public bool IsCloudCommunityItem - { - get { return false; } - } - - #endregion - } -} diff --git a/engine/csharp_ref/Tours/FileCabinet.cs b/engine/csharp_ref/Tours/FileCabinet.cs deleted file mode 100644 index 8a3f24e2..00000000 --- a/engine/csharp_ref/Tours/FileCabinet.cs +++ /dev/null @@ -1,293 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Data.Files; - -namespace wwtlib -{ - - public class FileEntry - { - public string Filename; - public int Size; - public int Offset; - public Blob Blob; - public FileEntry(string filename, int size) - { - Filename = filename; - Size = size; - } - public override string ToString() - { - return Filename; - } - } - - public class FileCabinet - { - protected List FileList; - Dictionary FileDirectory; - public string Filename; - public string TempDirectory = ""; - private int currentOffset = 0; - private string packageID = ""; - - public string PackageID - { - get { return packageID; } - set { packageID = value; } - } - - //public FileCabinet(string filename, string directory) - //{ - // ClearFileList(); - // Filename = filename; - // TempDirectory = directory; - //} - - public FileCabinet() - { - ClearFileList(); - } - - public void AddFile(string filename, Blob data) - { - if (data == null) - { - return; - } - - if (!FileDirectory.ContainsKey(filename)) - { - FileEntry fe = new FileEntry(filename, (int)data.Size); - fe.Offset = currentOffset; - fe.Blob = data; - FileList.Add(fe); - FileDirectory[filename] = fe; - currentOffset += fe.Size; - } - } - - public void ClearFileList() - { - if (FileList == null) - { - FileList = new List(); - } - if (FileDirectory == null) - { - FileDirectory = new Dictionary(); - } - FileList.Clear(); - FileDirectory.Clear(); - currentOffset = 0; - } - - public Blob PackageFiles() - { - XmlTextWriter xmlWriter = new XmlTextWriter(); - - xmlWriter.Formatting = Formatting.Indented; - xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - xmlWriter.WriteStartElement("FileCabinet"); - xmlWriter.WriteAttributeString("HeaderSize", "0x0BADFOOD"); - - xmlWriter.WriteStartElement("Files"); - foreach (FileEntry entry in FileList) - { - xmlWriter.WriteStartElement("File"); - xmlWriter.WriteAttributeString("Name", entry.Filename); - xmlWriter.WriteAttributeString("Size", entry.Size.ToString()); - xmlWriter.WriteAttributeString("Offset", entry.Offset.ToString()); - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - - xmlWriter.WriteFullEndElement(); - xmlWriter.Close(); - - string data = xmlWriter.Body; - - Blob blob = new Blob(new object[] { data }); - - string sizeText = String.Format("0x{0:x8}", blob.Size); - - data = data.Replace("0x0BADFOOD", sizeText); - - blob = new Blob(new object[] { data }); - - List blobs = new List(); - - blobs.Add(blob); - - // add the blobs to array to append in order - foreach (FileEntry entry in FileList) - { - blobs.Add(entry.Blob); - } - - Blob cabBlob = (Blob)Script.Literal("new Blob({0}, {{type : 'application/x-wtt'}});", blobs); - - return cabBlob; - } - - - public string Url = ""; - private WebFile webFile; - private Action callMe; - private System.Html.Data.Files.Blob mainBlob; - - public static FileCabinet FromUrl(string url, Action callMe) - { - - FileCabinet temp = new FileCabinet(); - temp.Url = url; - temp.callMe = callMe; - - temp.webFile = new WebFile(url); - temp.webFile.ResponseType = "blob"; - temp.webFile.OnStateChange = temp.LoadCabinet; - temp.webFile.Send(); - - return temp; - } - - private void LoadCabinet() - { - if (webFile.State == StateType.Error) - { - Script.Literal("alert({0})", webFile.Message); - } - else if (webFile.State == StateType.Received) - { - mainBlob = (System.Html.Data.Files.Blob)webFile.GetBlob(); - FileReader chunck = new FileReader(); - chunck.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e) - { - int offset = GetSize((string)chunck.Result); - - FileReader header = new FileReader(); - header.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent ee) - { - string data = header.Result as string; - XmlDocumentParser xParser = new XmlDocumentParser(); - Extract(xParser.ParseFromString(data, "text/xml"), offset); - callMe(); - }; - header.ReadAsText(mainBlob.Slice(0, offset)); - }; - chunck.ReadAsText(mainBlob.Slice(0, 255)); - - } - } - - private int GetSize(string data) - { - int start = data.IndexOf("0x"); - if (start == -1) - { - return 0; - } - return int.Parse(data.Substring(start, start + 10), 16); - } - - public void Extract(XmlDocument doc, int offset) - { - try - { - XmlNode cab = Util.SelectSingleNode(doc, "FileCabinet"); - XmlNode files = Util.SelectSingleNode(cab, "Files"); - - FileList.Clear(); - foreach (XmlNode child in files.ChildNodes) - { - if (child.Name == "File") - { - FileEntry fe = new FileEntry(child.Attributes.GetNamedItem("Name").Value, int.Parse(child.Attributes.GetNamedItem("Size").Value)); - fe.Offset = offset; - offset += fe.Size; - FileList.Add(fe); - } - } - } - catch - { - // UiTools.ShowMessageBox("The data cabinet file was not found. WWT will now download all data from network."); - } - } - - public Blob GetFileBlob(string filename) - { - FileEntry fe = GetFileEntry(filename); - if (fe != null) - { - string ext = filename.Substr(filename.LastIndexOf(".")).ToLowerCase(); - string type = null; - - switch (ext) - { - case ".png": - type = "image/png"; - break; - case ".jpg": - case ".jpeg": - type = "image/jpeg"; - break; - case ".mp3": - type = "audio/mpeg3"; - break; - case ".txt": - type = "text/plain"; - break; - case ".fit": - case ".fits": - type = "application/octet-stream"; - break; - } - - - return mainBlob.Slice(fe.Offset, fe.Offset + fe.Size, type); - } - - return null; - } - - public FileEntry GetFileEntry(string filename) - { - foreach (FileEntry entry in FileList) - { - if (entry.Filename == filename) - { - return entry; - } - } - - return null; - } - - public string MasterFile - { - get - { - if (FileList.Count > 0) - { - return FileList[0].Filename; - } - else - { - return null; - } - } - } - public void ClearTempFiles() - { - foreach (FileEntry entry in FileList) - { - //tofo release file URL's from blobs - } - } - - } -} \ No newline at end of file diff --git a/engine/csharp_ref/Tours/ISettings.cs b/engine/csharp_ref/Tours/ISettings.cs deleted file mode 100644 index 9363d9f4..00000000 --- a/engine/csharp_ref/Tours/ISettings.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; - -namespace wwtlib -{ - public interface ISettings - { - bool ActualPlanetScale { get; } - Color AltAzGridColor { get; } - ConstellationFilter ConstellationArtFilter { get; } - ConstellationFilter ConstellationBoundariesFilter { get; } - ConstellationFilter ConstellationFiguresFilter { get; } - ConstellationFilter ConstellationNamesFilter { get; } - int ConstellationLabelsHeight { get; } - string ConstellationsEnabled { get; } - bool EarthCutawayView { get; } - Color EclipticColor { get; } - Color EclipticGridColor { get; } - Color EquatorialGridColor { get; } - int FovCamera { get; } - int FovEyepiece { get; } - int FovTelescope { get; } - Color GalacticGridColor { get; } - bool GalacticMode { get; } - bool LocalHorizonMode { get; } - double LocationAltitude { get; } - double LocationLat { get; } - double LocationLng { get; } - bool MilkyWayModel { get; } - int MinorPlanetsFilter { get; } - int PlanetOrbitsFilter { get; } - Color PrecessionChartColor { get; } - bool ShowAltAzGrid { get; } - bool ShowAltAzGridText { get; } - bool ShowClouds { get; } - bool ShowConstellationBoundries { get; } - bool ShowConstellationFigures { get; } - bool ShowConstellationLabels { get; } - bool ShowConstellationPictures { get; } - bool ShowConstellationSelection { get; } - bool ShowConstellations { get; } - bool ShowEarthSky { get; } - bool ShowEcliptic { get; } - bool ShowEclipticGrid { get; } - bool ShowEclipticGridText { get; } - bool ShowEclipticOverviewText { get; } - bool ShowElevationModel { get; } - bool ShowEquatorialGridText { get; } - bool ShowFieldOfView { get; } - bool ShowGalacticGrid { get; } - bool ShowGalacticGridText { get; } - bool ShowGrid { get; } - bool ShowHorizon { get; } - bool ShowHorizonPanorama { get; } - bool ShowISSModel { get; } - bool ShowMoonsAsPointSource { get; } - bool ShowPrecessionChart { get; } - bool ShowSkyGrids { get; } - bool ShowSkyNode { get; } - bool ShowSkyOverlays { get; } - bool ShowSkyOverlaysIn3d { get; } - bool ShowSolarSystem { get; } - bool SolarSystemCMB { get; } - bool SolarSystemCosmos { get; } - bool SolarSystemLighting { get; } - bool SolarSystemMilkyWay { get; } - bool SolarSystemMinorOrbits { get; } - bool SolarSystemMinorPlanets { get; } - bool SolarSystemMultiRes { get; } - bool SolarSystemOrbits { get; } - bool SolarSystemOverlays { get; } - bool SolarSystemPlanets { get; } - int SolarSystemScale { get; } - bool SolarSystemStars { get; } - - SettingParameter GetSetting(StockSkyOverlayTypes type); - } - - public enum StockSkyOverlayTypes { - Empty = 0, - EquatorialGrid = 1, - EquatorialGridText = 2, - GalacticGrid = 3, - GalacticGridText = 4, - EclipticGrid = 5, - EclipticGridText = 6, - EclipticOverview = 7, - EclipticOverviewText = 8, - PrecessionChart = 9, - AltAzGrid = 10, - AltAzGridText = 11, - ConstellationFigures = 12, - ConstellationBoundaries = 13, - ConstellationFocusedOnly = 14, - ConstellationNames = 15, - ConstellationPictures = 16, - FadeToBlack = 17, - FadeToLogo = 18, - FadeToGradient = 19, - ScreenBroadcast = 20, - FadeRemoteOnly = 21, - SkyGrids = 22, - Constellations = 23, - SolarSystemStars = 24, - SolarSystemMilkyWay = 25, - SolarSystemCosmos = 26, - SolarSystemOrbits = 27, - SolarSystemPlanets = 28, - SolarSystemAsteroids = 29, - SolarSystemLighting = 30, - SolarSystemMinorOrbits = 31, - ShowEarthCloudLayer = 32, - ShowElevationModel = 33, - ShowAtmosphere = 34, - MultiResSolarSystemBodies = 35, - AuroraBorialis = 36, - EarthCutAway = 37, - ShowSolarSystem = 38, - Clouds8k = 39, - FiledOfView = 40, - ShowISSModel = 41, - SolarSystemCMB = 42, - MPCZone1 = 43, - MPCZone2 = 44, - MPCZone3 = 45, - MPCZone4 = 46, - MPCZone5 = 47, - MPCZone6 = 48, - MPCZone7 = 49, - OrbitFilters = 50 - }; - - public sealed class SettingParameter - { - public bool TargetState; - public bool EdgeTrigger; - public double Opacity; - public ConstellationFilter Filter; - - public SettingParameter(bool edgeTrigger, double opacity, bool targetState, ConstellationFilter filter) - { - EdgeTrigger = edgeTrigger; - Opacity = opacity; - TargetState = targetState; - Filter = filter; - } - } -} diff --git a/engine/csharp_ref/Tours/Overlay.cs b/engine/csharp_ref/Tours/Overlay.cs deleted file mode 100644 index b34b1629..00000000 --- a/engine/csharp_ref/Tours/Overlay.cs +++ /dev/null @@ -1,2393 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public enum OverlayAnchor { Sky = 0, Screen = 1 }; - public enum AudioType { Music = 0, Voice = 1 }; - - public abstract class Overlay - { - public static OverlayAnchor DefaultAnchor = OverlayAnchor.Screen; - - public const string ClipboardFormat = "WorldWideTelescope.Overlay"; - public bool isDynamic = false; - protected bool isDesignTimeOnly = false; - string name = ""; - public static int NextId = 11231; - - public string Name - { - get { return name; } - set { name = value; } - } - - public const double RC = 3.1415927 / 180; - //todo no Guid in jscript.. we should only be reading and not creating so we are ok for now - public string Id = (NextId++).ToString();//Guid.NewGuid().ToString(); - - TourStop owner = null; - - public TourStop Owner - { - get { return owner; } - set { owner = value; } - } - - public int ZOrder - { - get - { - int index = 0; - foreach (Overlay item in owner.Overlays) - { - if (item == this) - { - break; - } - index++; - } - return index; - } - } - - private string url = ""; - - public string Url - { - get { return url; } - set { url = value; } - } - - private string linkID = ""; - - public string LinkID - { - get { return linkID; } - set { linkID = value; } - } - - virtual public void Play() - { - } - - virtual public void Pause() - { - } - - virtual public void Stop() - { - } - - virtual public void Seek(double time) - { - } - - Matrix3d domeMatrix = Matrix3d.Identity; - - double domeMatX = 0; - double domeMatY = 0; - double domeAngle = 0; - - public Vector3d MakePosition(double centerX, double centerY, double offsetX, double offsetY, double angle) - { - centerX -= 960; - centerY -= 558; - - Vector3d point = Vector3d.Create(centerX + offsetX, centerY + offsetY, 1347); - - if (domeMatX != 0 || domeMatY != 0 || domeAngle != angle) - { - domeMatX = centerX; - domeMatY = centerY; - domeMatrix = Matrix3d.Translation(Vector3d.Create(-centerX, -centerY, 0)); - domeMatrix.Multiply(Matrix3d.RotationZ((double)(angle / 180 * Math.PI))); - domeMatrix.Multiply(Matrix3d.Translation(Vector3d.Create(centerX, centerY, 0))); - } - point = Vector3d.TransformCoordinate(point, domeMatrix); - - return point; - - } - - virtual public void Draw3D(RenderContext renderContext, bool designTime) - { - if (RenderContext.UseGl) - { - if (texture == null || isDynamic) - { - InitializeTexture(); - } - - if (!isDesignTimeOnly || designTime) - { - InitializeGeometry(); - - UpdateRotation(); - - //todo call proper drawing for this - // Sprite2d.Draw(renderContext, points, points.Length, texture, TriangleStrip ? SharpDX.Direct3D.PrimitiveTopology.TriangleStrip : SharpDX.Direct3D.PrimitiveTopology.TriangleList, transparancy); - } - } - else - { - - } - } - - virtual public void CleanUp() - { - if (texture != null) - { - texture = null; - } - texture2d = null; - } - - virtual public void InitializeTexture() - { - } - - // This hook exists to deal with web browser autoplay restrictions. In - // the strictest case, we can't just start playing media files at will - // -- we need to start playing them in response to a user-initiated - // event. But there is a generally a scheme in which files are - // "unlocked" once they've started to be played, and after that point we - // can control their playback more precisely. So, this function should - // do any multimedia playback initialization needed. It will be called - // when the user initiates tour playback. - // - // Repeated calls should be idempotent. - virtual public void PrepMultimedia() - { - } - - protected PositionColoredTextured[] points = null; - - virtual public void CleanUpGeometry() - { - currentRotation = 0; - points = null; - } - - virtual public void InitializeGeometry() - { - if (points == null) - { - - currentRotation = 0; - points = new PositionColoredTextured[4]; - points[0] = new PositionColoredTextured(); - points[0].Position = MakePosition(X, Y, -Width / 2, -Height / 2, RotationAngle); - points[0].Tu = 0; - points[0].Tv = 0; - points[0].Color = Color; - - points[1] = new PositionColoredTextured(); - points[1].Position = MakePosition(X, Y, Width / 2, -Height / 2, RotationAngle); - points[1].Tu = 1; - points[1].Tv = 0; - points[1].Color = Color; - - points[2] = new PositionColoredTextured(); - points[2].Position = MakePosition(X, Y, -Width / 2, Height / 2, RotationAngle); - points[2].Tu = 0; - points[2].Tv = 1; - points[2].Color = Color; - - points[3] = new PositionColoredTextured(); - points[3].Position = MakePosition(X, Y, Width / 2, Height / 2, RotationAngle); - points[3].Tu = 1; - points[3].Tv = 1; - points[3].Color = Color; - } - } - - virtual public void UpdateRotation() - { - - - } - // Animation Support - bool animate; - - public bool Animate - { - get { return animate; } - set - { - if (animate != value) - { - animate = value; - - if (animate) - { - endX = x; - endY = y; - endRotationAngle = rotationAngle; - endColor = color; - endWidth = width; - endHeight = height; - CleanUpGeometry(); - } - else - { - endX = x = X; - endY = y = Y; - endRotationAngle = rotationAngle = RotationAngle; - endColor = color = Color; - endWidth = width = Width; - endHeight = height = Height; - CleanUpGeometry(); - tweenFactor = 0; - } - } - } - } - double tweenFactor = 0; - - public double TweenFactor - { - get - { - return tweenFactor; - } - set - { - if (!animate) - { - tweenFactor = 0; - } - else - { - if (tweenFactor != value) - { - tweenFactor = value; - CleanUpGeometry(); - } - } - } - } - - double endX; - double endY; - double endOpacity; - Color endColor = new Color(); - double endWidth; - double endHeight; - double endRotationAngle; - - - - // End Animation Support - - - OverlayAnchor anchor = OverlayAnchor.Screen; - - public OverlayAnchor Anchor - { - get { return anchor; } - set { anchor = value; } - } - - public Vector2d Position - { - get - { - return Vector2d.Create(X, Y); - } - set - { - X = value.X; - Y = value.Y; - } - } - private double x; - - - - public double X - { - get { return (x * (1 - tweenFactor)) + (endX * tweenFactor); } - set - { - if (tweenFactor < .5f) - { - if (x != value) - { - x = value; - CleanUpGeometry(); - } - } - else - { - if (endX != value) - { - endX = value; - CleanUpGeometry(); - } - } - } - } - private double y; - - - public double Y - { - get { return (y * (1 - tweenFactor)) + (endY * tweenFactor); } - set - { - if (tweenFactor < .5f) - { - if (y != value) - { - y = value; - CleanUpGeometry(); - } - } - else - { - if (endY != value) - { - endY = value; - CleanUpGeometry(); - } - } - } - } - private double width; - - - public double Width - { - get { return (width * (1 - tweenFactor)) + (endWidth * tweenFactor); } - set - { - if (value < 5 && value != 0) - { - value = 5; - } - - if (tweenFactor < .5f) - { - if (width != value) - { - width = value; - CleanUpGeometry(); - } - } - else - { - if (endWidth != value) - { - endWidth = value; - CleanUpGeometry(); - } - } - } - } - - private double height; - - - public double Height - { - get { return (height * (1 - tweenFactor)) + (endHeight * tweenFactor); } - set - { - if (value < 5 && value != 0) - { - value = 5; - } - - if (tweenFactor < .5f) - { - if (height != value) - { - height = value; - CleanUpGeometry(); - } - } - else - { - if (endHeight != value) - { - endHeight = value; - CleanUpGeometry(); - } - } - } - } - - private Color color = Colors.White; - - - public virtual Color Color - { - get - { - int red = (int)(((double)color.R * (1f - tweenFactor)) + ((double)endColor.R * tweenFactor)); - int green = (int)(((double)color.G * (1f - tweenFactor)) + ((double)endColor.G * tweenFactor)); - int blue = (int)(((double)color.B * (1f - tweenFactor)) + ((double)endColor.B * tweenFactor)); - int alpha = (int)(((double)color.A * (1f - tweenFactor)) + ((double)endColor.A * tweenFactor)); - return Color.FromArgb((byte)Math.Max(0, Math.Min(255, alpha)), (byte)Math.Max(0, Math.Min(255, red)), (byte)Math.Max(0, Math.Min(255, green)), (byte)Math.Max(0, Math.Min(255, blue))); - } - set - { - if (tweenFactor < .5f) - { - if (color != value) - { - color = value; - CleanUpGeometry(); - } - } - else - { - if (endColor != value) - { - endColor = value; - CleanUpGeometry(); - } - } - } - } - - private double opacity = .5f; - - - public double Opacity - { - get - { - return (double)Color.A / 255.0f; - } - set - { - Color col = Color; - this.Color = Color.FromArgb((byte)Math.Min(255, (int)(value * 255f)), col.R, col.G, col.B); - opacity = value; - } - } - - double rotationAngle = 0; - protected double currentRotation = 0; - - - public double RotationAngle - { - get { return (rotationAngle * (1 - tweenFactor)) + (endRotationAngle * tweenFactor); } - set - { - if (tweenFactor < .5f) - { - if (rotationAngle != value) - { - rotationAngle = value; - CleanUpGeometry(); - } - } - else - { - if (endRotationAngle != value) - { - endRotationAngle = value; - CleanUpGeometry(); - } - } - } - } - - protected ImageElement texture = null; - protected Texture texture2d = null; - - virtual public bool HitTest(Vector2d pntTest) - { - Vector2d[] tempPoints = new Vector2d[1]; - tempPoints[0] = Vector2d.Create(pntTest.X, pntTest.Y); - - Matrix2d mat = Matrix2d.RotateAt(-RotationAngle / 180 * Math.PI, Vector2d.Create(X, Y)); - mat.TransformPoints(tempPoints); - - Rectangle rect = Rectangle.Create((X - (Width / 2)), (Y - (Height / 2)), Width, Height); - - return rect.Contains(tempPoints[0]); - - - - - - //todo this needs to be translated to script# - - //Matrix3d mat = new Matrix3d(); - //mat.RotateAt(new Quaternion(new Vector3D(0,0,1), -RotationAngle), new Point3D(X , Y , 0 )); - - //Point3D tempPoint = new Point3D(pntTest.X, pntTest.Y, 0); - - //tempPoint = mat.Transform(tempPoint); - - //Rect rect = new Rect((X-(Width/2)), (Y-(Height/2)), Width, Height); - //if (rect.Contains(new Point(tempPoint.X,tempPoint.Y))) - //{ - // return true; - //} - //return false; - } - - - Rectangle bounds; - - public Rectangle Bounds - { - get - { - return bounds; - } - set - { - bounds = value; - } - } - - private InterpolationType interpolationType = InterpolationType.DefaultV; - - public InterpolationType InterpolationType - { - get { return interpolationType; } - set { interpolationType = value; } - } - - - public virtual void SaveToXml(XmlTextWriter xmlWriter, bool saveKeys) - { - xmlWriter.WriteStartElement("Overlay"); - xmlWriter.WriteAttributeString("Id", Id); - xmlWriter.WriteAttributeString("Type", GetTypeName()); - xmlWriter.WriteAttributeString("Name", Name); - xmlWriter.WriteAttributeString("X", x.ToString()); - xmlWriter.WriteAttributeString("Y", y.ToString()); - xmlWriter.WriteAttributeString("Width", width.ToString()); - xmlWriter.WriteAttributeString("Height", height.ToString()); - xmlWriter.WriteAttributeString("Rotation", rotationAngle.ToString()); - xmlWriter.WriteAttributeString("Color", color.Save()); - xmlWriter.WriteAttributeString("Url", url); - xmlWriter.WriteAttributeString("LinkID", linkID); - xmlWriter.WriteAttributeString("Animate", animate.ToString()); - if (animate) - { - xmlWriter.WriteAttributeString("EndX", endX.ToString()); - xmlWriter.WriteAttributeString("EndY", endY.ToString()); - xmlWriter.WriteAttributeString("EndWidth", endWidth.ToString()); - xmlWriter.WriteAttributeString("EndHeight", endHeight.ToString()); - xmlWriter.WriteAttributeString("EndRotation", endRotationAngle.ToString()); - xmlWriter.WriteAttributeString("EndColor", endColor.Save()); - xmlWriter.WriteAttributeString("InterpolationType", Enums.ToXml("InterpolationType", (int)interpolationType)); - } - xmlWriter.WriteAttributeString("Anchor", Enums.ToXml("OverlayAnchor", (int)anchor)); - - - this.WriteOverlayProperties(xmlWriter); - - // todo add back for timeline tours - //if (AnimationTarget != null && saveKeys) - //{ - // AnimationTarget.SaveToXml(xmlWriter); - //} - - xmlWriter.WriteEndElement(); - } - - public virtual string GetTypeName() - { - return "TerraViewer.Overlay"; - } - - public virtual void AddFilesToCabinet(FileCabinet fc) - { - - } - - public virtual void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - - } - - - internal static Overlay FromXml(TourStop owner, XmlNode overlay) - { - if (overlay.Attributes == null) - { - return null; - } - - if (overlay.Attributes.GetNamedItem("Type") == null) - { - return null; - } - string overlayClassName = overlay.Attributes.GetNamedItem("Type").Value.ToString(); - - string overLayType = overlayClassName.Replace("TerraViewer.", ""); - Overlay newOverlay = null; - - switch (overLayType) - { - case "AudioOverlay": - newOverlay = new AudioOverlay(); - break; - case "BitmapOverlay": - newOverlay = new BitmapOverlay(); - break; - case "FlipBookOverlay": - newOverlay = new FlipbookOverlay(); - break; - case "ShapeOverlay": - newOverlay = new ShapeOverlay(); - break; - case "TextOverlay": - newOverlay = new TextOverlay(); - break; - default: - return null; - } - - newOverlay.owner = owner; - newOverlay.InitOverlayFromXml(overlay); - return newOverlay; - } - - private void InitOverlayFromXml(XmlNode node) - { - Id = node.Attributes.GetNamedItem("Id").Value; - Name = node.Attributes.GetNamedItem("Name").Value; - x = double.Parse(node.Attributes.GetNamedItem("X").Value); - y = double.Parse(node.Attributes.GetNamedItem("Y").Value); - width = double.Parse(node.Attributes.GetNamedItem("Width").Value); - height = double.Parse(node.Attributes.GetNamedItem("Height").Value); - rotationAngle = double.Parse(node.Attributes.GetNamedItem("Rotation").Value); - color = Color.Load(node.Attributes.GetNamedItem("Color").Value); - if (node.Attributes.GetNamedItem("Url") != null) - { - Url = node.Attributes.GetNamedItem("Url").Value; - } - - if (node.Attributes.GetNamedItem("LinkID") != null) - { - LinkID = node.Attributes.GetNamedItem("LinkID").Value; - } - - if (node.Attributes.GetNamedItem("Animate") != null) - { - animate = bool.Parse(node.Attributes.GetNamedItem("Animate").Value); - if (animate) - { - endX = double.Parse(node.Attributes.GetNamedItem("EndX").Value); - endY = double.Parse(node.Attributes.GetNamedItem("EndY").Value); - endColor = Color.Load(node.Attributes.GetNamedItem("EndColor").Value); - endWidth = double.Parse(node.Attributes.GetNamedItem("EndWidth").Value); - endHeight = double.Parse(node.Attributes.GetNamedItem("EndHeight").Value); - endRotationAngle = double.Parse(node.Attributes.GetNamedItem("EndRotation").Value); - if (node.Attributes.GetNamedItem("InterpolationType") != null) - { - InterpolationType = (InterpolationType)Enums.Parse("InterpolationType", node.Attributes.GetNamedItem("InterpolationType").Value); - } - } - } - - InitializeFromXml(node); - } - - public virtual void InitializeFromXml(XmlNode node) - { - - } - - public override string ToString() - { - return this.Name; - } - - } - public class BitmapOverlay : Overlay - { - - public override string GetTypeName() - { - return "TerraViewer.BitmapOverlay"; - } - - string filename; - - public BitmapOverlay() - { - - } - - public static BitmapOverlay Create(TourStop owner, System.Html.Data.Files.File file ) - { - //todo figure out how to load local files into clound and to cabinet - BitmapOverlay temp = new BitmapOverlay(); - - temp.Owner = owner; - // to make directory and guid filename in tour temp dir. - temp.filename = file.Name; - - temp.Name = owner.GetNextDefaultName("Image"); - temp.X = 0; - temp.Y = 0; - owner.Owner.AddCachedFile(file.Name, file); - - return temp; - } - - public BitmapOverlay Copy(TourStop owner) - { - BitmapOverlay newBmpOverlay = new BitmapOverlay(); - newBmpOverlay.Owner = owner; - newBmpOverlay.filename = this.filename; - newBmpOverlay.X = this.X; - newBmpOverlay.Y = this.Y; - newBmpOverlay.Width = this.Width; - newBmpOverlay.Height = this.Height; - newBmpOverlay.Color = this.Color; - newBmpOverlay.Opacity = this.Opacity; - newBmpOverlay.RotationAngle = this.RotationAngle; - newBmpOverlay.Name = this.Name + " - Copy"; - - return newBmpOverlay; - } - - public override void CleanUp() - { - texture = null; - if (texture2d != null) - { - texture2d.CleanUp(); - texture2d = null; - } - - } - - bool textureReady = false; - - public override void InitializeTexture() - { - try - { - if (RenderContext.UseGl) - { - texture2d = Owner.Owner.GetCachedTexture2d(filename); - textureReady = true; - } - else - { - texture = Owner.Owner.GetCachedTexture(filename, delegate { textureReady = true; }); - - } - } - catch - { - - } - } - - private ImageElement imageBrush; - private Sprite2d sprite = new Sprite2d(); - - public override void Draw3D(RenderContext renderContext, bool designTime) - { - if (RenderContext.UseGl) - { - if (texture2d == null) - { - InitializeTexture(); - } - - if (Width == 0 && Height == 0) - { - Width = texture2d.ImageElement.Width; - Height = texture2d.ImageElement.Height; - } - - - InitializeGeometry(); - - UpdateRotation(); - - //todo call proper drawing for this - sprite.Draw(renderContext, points, points.Length, texture2d, true, 1); - } - else - { - - if (texture == null) - { - InitializeTexture(); - } - - if (!textureReady) - { - return; - } - - if (Width == 0 && Height == 0) - { - Width = texture.Width; - Height = texture.Height; - } - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - ctx.Alpha = Opacity; - ctx.DrawImage(texture, -Width / 2, -Height / 2, Width, Height); - ctx.Restore(); - } - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - fc.AddFile(Owner.Owner.WorkingDirectory + filename, Owner.Owner.GetFileBlob(filename)); - } - - public override void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("Bitmap"); - xmlWriter.WriteAttributeString("Filename", filename); - xmlWriter.WriteEndElement(); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode bitmap = Util.SelectSingleNode(node, "Bitmap"); - filename = bitmap.Attributes.GetNamedItem("Filename").Value; - } - } - - public class TextOverlay : Overlay - { - public override string GetTypeName() - { - return "TerraViewer.TextOverlay"; - } - - public TextObject TextObject; - public override Color Color - { - get - { - return base.Color; - //return TextObject.ForgroundColor; - } - set - { - if (TextObject.ForegroundColor != value) - { - TextObject.ForegroundColor = value; - base.Color = value; - CleanUp(); - } - } - } - - public TextOverlay() - { - } - - public static TextOverlay Create(TextObject textObject) - { - TextOverlay to = new TextOverlay(); - to.TextObject = textObject; - to.CalculateTextSize(); - return to; - } - - //public static TextOverlay(Canvas canvas, TextObject textObject) - //{ - // this.canvas = canvas; - // this.TextObject = textObject; - // this.Name = textObject.Text.Split(new char[] { '\r', '\n' })[0]; - // X = 0; - // Y = 0; - - //} - - Sprite2d sprite = new Sprite2d(); - - public override void Draw3D(RenderContext renderContext, bool designTime) - { - if (RenderContext.UseGl) - { - InitializeTexture(); - InitializeGeometry(); - - UpdateRotation(); - - //todo call proper drawing for this - sprite.Draw(renderContext, points, points.Length, texture2d, true, 1); - } - else - { - //TextBlock textBlock = new TextBlock(); - //textBlock.Width = this.Width; - //textBlock.Height = this.Height; - //textBlock.Foreground = new SolidColorBrush(TextObject.ForgroundColor); - //textBlock.Text = TextObject.Text; - //textBlock.FontWeight = TextObject.Bold ? FontWeights.Bold : FontWeights.Normal; - //textBlock.FontSize = TextObject.FontSize * 1.2; - //textBlock.HorizontalAlignment = HorizontalAlignment.Left; - //TranslateTransform tt = new TranslateTransform(); - //tt.X = this.X - (Width / 2); - //tt.Y = this.Y - (Height / 2); - //textBlock.RenderTransform = tt; - //canvas.Children.Add(textBlock); - //textBlock.Opacity = this.Opacity; - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - ctx.Alpha = Opacity; - DrawCanvasText(ctx); - - ctx.Restore(); - } - } - - private void DrawCanvasText(CanvasContext2D ctx) - { - ctx.FillStyle = TextObject.ForegroundColor.ToString(); - ctx.Font = (TextObject.Italic ? "italic" : "normal") + " " + (TextObject.Bold ? "bold" : "normal") + " " + Math.Round(TextObject.FontSize * 1.2).ToString() + "px " + TextObject.FontName; - ctx.TextBaseline = TextBaseline.Top; - - String text = TextObject.Text; - - if (text.IndexOf("{$") > -1) - { - if (text.IndexOf("{$DATE}") > -1) - { - string date = String.Format("{0:yyyy/MM/dd}", SpaceTimeController.Now); - text = text.Replace("{$DATE}", date); - } - - if (text.IndexOf("{$TIME}") > -1) - { - string time = String.Format("{0:HH:mm:ss}", SpaceTimeController.Now); - text = text.Replace("{$TIME}", time); - } - - - text = text.Replace("{$DIST}", UiTools.FormatDistance(WWTControl.Singleton.RenderContext.SolarSystemCameraDistance)); - text = text.Replace("{$LAT}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Lat)); - text = text.Replace("{$LNG}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Lat)); - text = text.Replace("{$RA}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.RA)); - text = text.Replace("{$DEC}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Dec)); - text = text.Replace("{$FOV}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.FovAngle)); - } - - string[] lines = text.Split("\n"); - - double baseline = -(Height / 2); - double lineSpace = TextObject.FontSize * 1.7; - - foreach (string line in lines) - { - List parts = Util.GetWrappedText(ctx, line, Width); - foreach (string part in parts) - { - ctx.FillText(part, -Width / 2, baseline); - baseline += lineSpace; - } - } - } - - private void CalculateTextSize() - { - - if (ctx == null || ce == null) - { - ce = (CanvasElement)Document.CreateElement("canvas"); - ce.Height = (int)100; - ce.Width = (int)100; - ctx = (CanvasContext2D)ce.GetContext(Rendering.Render2D); - } - ctx.FillStyle = TextObject.ForegroundColor.ToString(); - ctx.Font = (TextObject.Italic ? "italic" : "normal") + " " + (TextObject.Bold ? "bold" : "normal") + " " + Math.Round(TextObject.FontSize * 1.2).ToString() + "px " + TextObject.FontName; - ctx.TextBaseline = TextBaseline.Top; - - String text = TextObject.Text; - - if (text.IndexOf("{$") > -1) - { - if (text.IndexOf("{$DATE}") > -1) - { - string date = String.Format("{0:yyyy/MM/dd}", SpaceTimeController.Now); - text = text.Replace("{$DATE}", date); - } - - if (text.IndexOf("{$TIME}") > -1) - { - string time = String.Format("{0:HH:mm:ss}", SpaceTimeController.Now); - text = text.Replace("{$TIME}", time); - } - - - text = text.Replace("{$DIST}", UiTools.FormatDistance(WWTControl.Singleton.RenderContext.SolarSystemCameraDistance)); - text = text.Replace("{$LAT}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Lat)); - text = text.Replace("{$LNG}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Lat)); - text = text.Replace("{$RA}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.RA)); - text = text.Replace("{$DEC}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.ViewCamera.Dec)); - text = text.Replace("{$FOV}", Coordinates.FormatDMS(WWTControl.Singleton.RenderContext.FovAngle)); - } - - string[] lines = text.Split("\n"); - - double baseline = 0; - double lineSpace = TextObject.FontSize * 1.7; - double maxWidth = 0; - foreach (string line in lines) - { - double width = ctx.MeasureText(line).Width; - maxWidth = Math.Max(width, maxWidth); - baseline += lineSpace; - } - //Width + fudge factor - Width = maxWidth*1.01; - Height = baseline; - ce = null; - ctx = null; - } - - CanvasContext2D ctx = null; - CanvasElement ce = null; - - public override void InitializeTexture() - { - if (texture2d == null || (TextObject.Text.IndexOf("{$") > -1)) - { - if (Height == 0 || Width == 0) - { - CalculateTextSize(); - } - if (ctx == null || ce == null) - { - ce = (CanvasElement) Document.CreateElement("canvas") ; - ce.Height = (int)Height; - ce.Width = (int)Width; - ctx = (CanvasContext2D)ce.GetContext(Rendering.Render2D); - } - ctx.Translate(Width/2, Height/2); - ctx.ClearRect(0, 0, Width, Height); - DrawCanvasText(ctx); - - texture2d = new Texture(); - - texture2d.ImageElement = (ImageElement)(Element)ce; - texture2d.MakeTexture(); - ce = null; - ctx = null; - } - - - //System.Drawing.Font font = TextObject.Font; - //StringFormat sf = new StringFormat(); - //sf.Alignment = StringAlignment.Near; - - //Bitmap bmp = new Bitmap(20, 20); - //Graphics g = Graphics.FromImage(bmp); - //SizeF size = g.MeasureString(TextObject.Text, font); - //g.Dispose(); - //bmp.Dispose(); - - //double border =0; - - //switch (TextObject.BorderStyle) - //{ - // case TextBorderStyle.None: - // case TextBorderStyle.Tight: - // border = 0; - // break; - // case TextBorderStyle.Small: - // border = 10; - // break; - // case TextBorderStyle.Medium: - // border = 15; - // break; - // case TextBorderStyle.Large: - // border = 20; - // break; - // default: - // break; - //} - //if (size.Width == 0 || size.Height == 0) - //{ - // size = new SizeF(1, 1); - //} - //bmp = new Bitmap((int)(size.Width + (border * 2)), (int)(size.Height + (border * 2))); - //g = Graphics.FromImage(bmp); - //if (TextObject.BorderStyle != TextBorderStyle.None) - //{ - // g.Clear(TextObject.BackgroundColor); - //} - - //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - ////g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - //g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - - //Brush textBrush = new SolidBrush(TextObject.ForgroundColor); - - //g.DrawString(TextObject.Text, font, textBrush, border, border, sf); - //textBrush.Dispose(); - //g.Dispose(); - //texture = UiTools.LoadTextureFromBmp(device, bmp); - //bmp.Dispose(); - //font.Dispose(); - //if (Width == 0 && Height == 0) - //{ - // Width = size.Width + (border * 2); - // Height = size.Height + (border * 2); - //} - } - - public override void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("Text"); - TextObject.SaveToXml(xmlWriter); - xmlWriter.WriteEndElement(); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode text = Util.SelectSingleNode(node, "Text"); - - TextObject = TextObject.FromXml(Util.SelectSingleNode(text, "TextObject")); - - } - - - override public void InitializeGeometry() - { - if (RenderContext.UseGl) - { - base.InitializeGeometry(); - } - } - } - - public enum ShapeType { Circle = 0, Rectagle = 1, Star = 2, Donut = 3, Arrow = 4, Line = 5, OpenRectagle = 6 }; - - public class ShapeOverlay : Overlay - { - - public override string GetTypeName() - { - return "TerraViewer.ShapeOverlay"; - } - - ShapeType shapeType = ShapeType.Rectagle; - - public ShapeOverlay() - { - } - - - public ShapeType ShapeType - { - get { return shapeType; } - set - { - shapeType = value; - CleanUpGeometry(); - } - } - - //public ShapeOverlay(RenderContext renderContext, TourStop owner, ShapeType shapeType) - //{ - // ShapeType = shapeType; - // this.Owner = owner; - // this.Name = owner.GetNextDefaultName(shapeType.ToString()); - //} - - Sprite2d sprite = new Sprite2d(); - - public override void Draw3D(RenderContext renderContext, bool designTime) - { - if (RenderContext.UseGl) - { - InitializeGeometry(); - sprite.Draw(renderContext, points, points.Length, null, TriangleStrip, Opacity); - } - else - { - - switch (shapeType) - { - case ShapeType.Circle: - DrawCircleGeometry(renderContext); - break; - case ShapeType.Rectagle: - DrawRectGeometry(renderContext); - break; - case ShapeType.OpenRectagle: - DrawOpenRectGeometry(renderContext); - break; - case ShapeType.Star: - DrawStarGeometry(renderContext); - break; - case ShapeType.Donut: - DrawDonutGeometry(renderContext); - break; - case ShapeType.Arrow: - DrawArrowGeometry(renderContext); - break; - case ShapeType.Line: - DrawLineGeometry(renderContext); - break; - default: - break; - } - - } - } - - public override void InitializeGeometry() - { - if (points == null) - { - switch (shapeType) - { - case ShapeType.Circle: - { - CreateCircleGeometry(); - - } - break; - case ShapeType.Rectagle: - base.InitializeGeometry(); - break; - case ShapeType.OpenRectagle: - CreateOpenRectGeometry(); - break; - case ShapeType.Star: - CreateStarGeometry(); - break; - case ShapeType.Donut: - CreateDonutGeometry(); - break; - case ShapeType.Arrow: - CreateArrowGeometry(); - break; - case ShapeType.Line: - CreateLineGeometry(); - break; - default: - break; - } - } - } - - private void CreateLineGeometry() - { - double centerX = X; - double centerY = Y; - double radius = Width / 2; - - //float length = (float)Math.Sqrt(Width * Width + Height * Height); - double length = Width; - int segments = (int)(length / 12f) + 1; - float radiansPerSegment = ((float)Math.PI * 2) / segments; - if (points == null) - { - points = new PositionColoredTextured[segments * 2 + 2]; - } - - for (int j = 0; j <= segments; j++) - { - int i = j * 2; - points[i] = new PositionColoredTextured(); - points[i].Position = MakePosition(X, Y, (((double)j / (double)segments) * (Width) - (Width / 2)), 6f, RotationAngle); - points[i].Tu = ((j) % 2); - points[i].Tv = 0; - points[i].Color = Color; - - points[i + 1] = new PositionColoredTextured(); - points[i + 1].Position = MakePosition(X, Y, (((double)j / (double)segments) * (Width) - (Width / 2)), -6f, RotationAngle); - points[i + 1].Tu = (j % 2); - points[i + 1].Tv = 1; - points[i + 1].Color = Color; - - } - } - - private void CreateOpenRectGeometry() - { - double centerX = X; - double centerY = Y; - double radius = Width / 2; - - double length = Width; - int segments = (int)(length / 12f) + 1; - int segmentsHigh = (int)(Height / 12f) + 1; - - int totalPoints = (((segments + 1) * 2) + ((segmentsHigh + 1) * 2)) * 2; - if (points == null) - { - points = new PositionColoredTextured[totalPoints]; - } - for (int j = 0; j <= segments; j++) - { - int i = j * 2; - points[i] = new PositionColoredTextured(); - points[i].Position = MakePosition(centerX, centerY, - ((double)j / (double)segments) * (Width) - (Width / 2), - ((Height / 2)), RotationAngle); - points[i].Tu = ((j) % 2); - points[i].Tv = 0; - points[i].Color = Color; - - points[i + 1] = new PositionColoredTextured(); - points[i + 1].Position = MakePosition(centerX, centerY, - ((double)j / (double)segments) * (Width) - (Width / 2), - ((Height / 2) - 12f), RotationAngle); - points[i + 1].Tu = (j % 2); - points[i + 1].Tv = 1; - points[i + 1].Color = Color; - - int k = (((segments + 1) * 4) + ((segmentsHigh + 1) * 2) - 2) - i; - - points[k] = new PositionColoredTextured(); - points[k].Position = MakePosition(centerX, centerY, - ((double)j / (double)segments) * (Width) - (Width / 2), - (-(Height / 2)) + 12f, RotationAngle); - - points[k].Tu = ((j) % 2); - points[k].Tv = 0; - points[k].Color = Color; - - points[k + 1] = new PositionColoredTextured(); - points[k + 1].Position = MakePosition(centerX, centerY, - ((double)j / (double)segments) * (Width) - (Width / 2), - (-(Height / 2)), RotationAngle); - points[k + 1].Tu = (j % 2); - points[k + 1].Tv = 1; - points[k + 1].Color = Color; - - } - - int offset = ((segments + 1) * 2); - - for (int j = 0; j <= segmentsHigh; j++) - { - int top = ((segmentsHigh + 1) * 2) + offset - 2; - int i = j * 2; - points[top - i] = new PositionColoredTextured(); - points[top - i].Position = MakePosition(centerX, centerY, (float)(Width / 2), (float)(((double)j / (double)segmentsHigh) * (Height) - (Height / 2)), RotationAngle); - - points[top - i].Tu = ((j) % 2); - points[top - i].Tv = 0; - points[top - i].Color = Color; - - points[top - i + 1] = new PositionColoredTextured(); - points[top - i + 1].Position = MakePosition(centerX, centerY, - ((Width / 2) - 12f), - (((double)j / (double)segmentsHigh) * Height - ((Height / 2))), RotationAngle); - - points[top - i + 1].Tu = (j % 2); - points[top - i + 1].Tv = 1; - points[top - i + 1].Color = Color; - - int k = i + ((segments + 1) * 4) + ((segmentsHigh + 1) * 2); - points[k] = new PositionColoredTextured(); - points[k].Position = MakePosition(centerX, centerY, - (-(Width / 2) + 12), - (((double)j / (double)segmentsHigh) * (Height) - (Height / 2)), RotationAngle); - points[k].Tu = ((j) % 2); - points[k].Tv = 0; - points[k].Color = Color; - - points[k + 1] = new PositionColoredTextured(); - points[k + 1].Position = MakePosition(centerX, centerY, - (-(Width / 2)), - (((double)j / (double)segmentsHigh) * Height - ((Height / 2))), RotationAngle); - points[k + 1].Tu = (j % 2); - points[k + 1].Tv = 1; - points[k + 1].Color = Color; - - } - } - - PositionColoredTextured[] pnts; - - private void CreateStarGeometry() - { - double centerX = X; - double centerY = Y; - double radius = Width / 2; - - double radiansPerSegment = (Math.PI * 2) / 5; - if (points == null) - { - points = new PositionColoredTextured[12]; - } - - if (pnts == null) - { - pnts = new PositionColoredTextured[10]; - } - - for (int i = 0; i < 5; i++) - { - double rads = i * radiansPerSegment - (Math.PI / 2); - pnts[i] = new PositionColoredTextured(); - pnts[i].Position = MakePosition(centerX, centerY, (Math.Cos(rads) * (Width / 2)), (Math.Sin(rads) * (Height / 2)), RotationAngle); - pnts[i].Tu = 0; - pnts[i].Tv = 0; - pnts[i].Color = Color; - } - - for (int i = 5; i < 10; i++) - { - double rads = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); - pnts[i] = new PositionColoredTextured(); - pnts[i].Position = MakePosition(centerX, centerY, (Math.Cos(rads) * (Width / 5.3)), (Math.Sin(rads) * (Height / 5.3)), RotationAngle); - - pnts[i].Tu = 0; - pnts[i].Tv = 0; - pnts[i].Color = Color; - } - - points[0] = pnts[0]; - points[1] = pnts[5]; - points[2] = pnts[9]; - points[3] = pnts[1]; - points[4] = pnts[7]; - points[5] = pnts[4]; - points[6] = pnts[6]; - points[7] = pnts[2]; - points[8] = pnts[7]; - points[9] = pnts[7]; - points[10] = pnts[3]; - points[11] = pnts[8]; - TriangleStrip = false; - } - - private void CreateArrowGeometry() - { - if (points == null) - { - points = new PositionColoredTextured[9]; - } - - points[0] = new PositionColoredTextured(); - points[0].Position = MakePosition(X, Y, -Width / 2, -Height / 4, RotationAngle); - points[0].Tu = 0; - points[0].Tv = 0; - points[0].Color = Color; - - points[1] = new PositionColoredTextured(); - points[1].Position = MakePosition(X, Y, Width / 4, -Height / 4, RotationAngle); - points[1].Tu = 1; - points[1].Tv = 0; - points[1].Color = Color; - - - points[2] = new PositionColoredTextured(); - points[2].Position = MakePosition(X, Y, -Width / 2, Height / 4, RotationAngle); - points[2].Tu = 0; - points[2].Tv = 1; - points[2].Color = Color; - - points[3] = new PositionColoredTextured(); - points[3].Position = MakePosition(X, Y, Width / 4, -Height / 4, RotationAngle); - points[3].Tu = 1; - points[3].Tv = 0; - points[3].Color = Color; - - - points[4] = new PositionColoredTextured(); - points[4].Position = MakePosition(X, Y, -Width / 2, Height / 4, RotationAngle); - points[4].Tu = 0; - points[4].Tv = 1; - points[4].Color = Color; - - - points[5] = new PositionColoredTextured(); - points[5].Position = MakePosition(X, Y, Width / 4, Height / 4, RotationAngle); - points[5].Tu = 1; - points[5].Tv = 1; - points[5].Color = Color; - - // Point - - points[6] = new PositionColoredTextured(); - points[6].Position = MakePosition(X, Y, Width / 4, -Height / 2, RotationAngle); - points[6].Tu = 1; - points[6].Tv = 1; - points[6].Color = Color; - - points[7] = new PositionColoredTextured(); - points[7].Position = MakePosition(X, Y, Width / 2, 0, RotationAngle); - points[7].Tu = 1; - points[7].Tv = .5f; - points[7].Color = Color; - - points[8] = new PositionColoredTextured(); - points[8].Position = MakePosition(X, Y, Width / 4, Height / 2, RotationAngle); - points[8].Tu = 1; - points[8].Tv = 1; - points[8].Color = Color; - - TriangleStrip = false; - } - - private void CreateDonutGeometry() - { - double centerX = X; - double centerY = Y; - double radius = Width / 2; - - double circumference = Math.PI * 2.0f * radius; - int segments = (int)(circumference / 12) + 1; - double radiansPerSegment = (Math.PI * 2) / segments; - if (points == null) - { - points = new PositionColoredTextured[segments * 2 + 2]; - } - - for (int j = 0; j <= segments; j++) - { - int i = j * 2; - points[i] = new PositionColoredTextured(); - points[i].Position = MakePosition(centerX, centerY, (Math.Cos(j * radiansPerSegment) * (Width / 2)), (Math.Sin(j * radiansPerSegment) * (Height / 2)), RotationAngle); - points[i].Tu = ((j) % 2); - points[i].Tv = 0; - points[i].Color = Color; - - points[i + 1] = new PositionColoredTextured(); - points[i + 1].Position = MakePosition(centerX, centerY, (Math.Cos(j * radiansPerSegment) * ((Width / 2) - 10)), (Math.Sin(j * radiansPerSegment) * ((Height / 2) - 10)), RotationAngle); - points[i + 1].Tu = (j % 2); - points[i + 1].Tv = 1; - points[i + 1].Color = Color; - - } - } - - bool TriangleStrip = true; - - private void CreateCircleGeometry() - { - double centerX = X; - double centerY = Y; - double radius = Width / 2; - - double circumference = Math.PI * 2.0f * radius; - int segments = (int)(circumference / 12) + 1; - double radiansPerSegment = (Math.PI * 2) / segments; - if (points == null) - { - points = new PositionColoredTextured[segments * 2 + 2]; - } - for (int j = 0; j <= segments; j++) - { - int i = j * 2; - points[i] = new PositionColoredTextured(); - points[i].Position = MakePosition(centerX, centerY, (Math.Cos(j * radiansPerSegment) * (Width / 2)), (Math.Sin(j * radiansPerSegment) * (Height / 2)), RotationAngle); - points[i].Tu = ((j) % 2); - points[i].Tv = 0; - points[i].Color = Color; - - - points[i + 1] = new PositionColoredTextured(); - points[i + 1].Position = MakePosition(centerX, centerY, 0, 0, RotationAngle); - points[i + 1].Tu = (j % 2); - points[i + 1].Tv = 1; - points[i + 1].Color = Color; - - } - } - - public override void InitializeTexture() - { - switch (ShapeType) - { - case ShapeType.Line: - case ShapeType.Donut: - case ShapeType.OpenRectagle: - { - //Bitmap bmp = new Bitmap(13, 10); - //Graphics g = Graphics.FromImage(bmp); - //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - //Brush brush = new SolidBrush(Color); - //g.FillEllipse(brush, 1, 0, 10, 9); - //g.Dispose(); - //texture = Texture11.FromBitmap(bmp); - //bmp.Dispose(); - } - break; - case ShapeType.Circle: - - case ShapeType.Rectagle: - case ShapeType.Star: - - case ShapeType.Arrow: - default: - { - texture = null; - } - break; - } - } - - private void DrawLineGeometry(RenderContext renderContext) - { - - //todo this needs to be Dashed rounded lines.. - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - double radius = Width / 2; - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle*RC); - - ctx.MoveTo(-radius, 0); - ctx.LineTo(radius, 0); - ctx.LineWidth = 9; - ctx.StrokeStyle = Color.ToString(); - ctx.Alpha = Opacity; - ctx.Stroke(); - ctx.Restore(); - - - } - private void DrawOpenRectGeometry(RenderContext renderContext) - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle*RC); - - ctx.BeginPath(); - ctx.MoveTo(-Width / 2, -Height / 2); - ctx.LineTo(Width / 2, -Height / 2); - ctx.LineTo(Width / 2, Height / 2); - ctx.LineTo(-Width / 2, Height / 2); - ctx.ClosePath(); - ctx.LineWidth = 9; - ctx.StrokeStyle = Color.ToString(); - - ctx.Alpha = Opacity; - ctx.Stroke(); - ctx.Restore(); - } - - private void DrawRectGeometry(RenderContext renderContext) - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - - ctx.BeginPath(); - ctx.MoveTo(-Width / 2, -Height / 2); - ctx.LineTo(Width / 2, -Height / 2); - ctx.LineTo(Width / 2, +Height / 2); - ctx.LineTo(-Width / 2, +Height / 2); - ctx.ClosePath(); - ctx.LineWidth = 0; - ctx.FillStyle = Color.ToString(); - - ctx.Alpha = Opacity; - ctx.Fill(); - ctx.Restore(); - } - private void DrawStarGeometry(RenderContext renderContext) - { - - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - ctx.BeginPath(); - - double centerX = 0; - double centerY = 0; - double radius = Width / 2; - - double radiansPerSegment = ((double)Math.PI * 2) / 5; - - bool first = true; - - for (int i = 0; i < 5; i++) - { - double rads = i * radiansPerSegment - (Math.PI / 2); - if (first) - { - first = false; - ctx.MoveTo(centerX + Math.Cos(rads) * (Width / 2), centerY + Math.Sin(rads) * (Height / 2)); - } - else - { - ctx.LineTo(centerX + Math.Cos(rads) * (Width / 2), centerY + Math.Sin(rads) * (Height / 2)); - } - - double rads2 = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); - ctx.LineTo(centerX + Math.Cos(rads2) * (Width / 5.3), centerY + Math.Sin(rads2) * (Height / 5.3)); - - } - - ctx.ClosePath(); - ctx.LineWidth = 0; - ctx.FillStyle = Color.ToString(); - - - ctx.Alpha = Opacity; - ctx.Fill(); - ctx.Restore(); - } - private void DrawArrowGeometry(RenderContext renderContext) - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - - ctx.BeginPath(); - ctx.MoveTo((-(Width / 2)), (-(Height / 4))); - ctx.LineTo(((Width / 4)), (-(Height / 4))); - ctx.LineTo(((Width / 4)), (-(Height / 2))); - ctx.LineTo(((Width / 2)), 0); - ctx.LineTo(((Width / 4)), ((Height / 2))); - ctx.LineTo(((Width / 4)), ((Height / 4))); - ctx.LineTo((-(Width / 2)), ((Height / 4))); - ctx.ClosePath(); - ctx.LineWidth = 0; - ctx.FillStyle = Color.ToString(); - - ctx.Alpha = Opacity; - ctx.Fill(); - ctx.Restore(); - } - - private void DrawDonutGeometry(RenderContext renderContext) - { - //todo move to dashed lines in future - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Translate(X, Y); - ctx.Scale(1, Height / Width); - ctx.Rotate(RotationAngle * RC); - ctx.BeginPath(); - ctx.Arc(0, 0, Width / 2, 0, Math.PI * 2, false); - - ctx.ClosePath(); - ctx.LineWidth = 9; - ctx.StrokeStyle = Color.ToString(); - ctx.Alpha = Opacity; - ctx.Stroke(); - ctx.Restore(); - - - } - - private void DrawCircleGeometry(RenderContext renderContext) - { - CanvasContext2D ctx = renderContext.Device; - ctx.Save(); - ctx.Scale(1, Width / Height); - ctx.Translate(X, Y); - ctx.Rotate(RotationAngle * RC); - ctx.BeginPath(); - ctx.Arc(0, 0, Width, 0, Math.PI * 2, false); - ctx.ClosePath(); - ctx.LineWidth = 0; - ctx.FillStyle = Color.ToString(); - ctx.Alpha = Opacity; - ctx.Fill(); - ctx.Restore(); - } - - - public override void CleanUpGeometry() - { - base.CleanUpGeometry(); - CleanUp(); - } - - public override void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("Shape"); - xmlWriter.WriteAttributeString("ShapeType", Enums.ToXml("ShapeType",(int)shapeType)); - xmlWriter.WriteEndElement(); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode shape = Util.SelectSingleNode(node, "Shape"); - shapeType = (ShapeType)Enums.Parse("ShapeType", shape.Attributes.GetNamedItem("ShapeType").Value); - } - - internal static ShapeOverlay Create(TourStop currentTourStop, ShapeType shapeType) - { - ShapeOverlay overlay = new ShapeOverlay(); - overlay.shapeType = shapeType; - overlay.Owner = currentTourStop; - - - return overlay; - } - } - - public class AudioOverlay : Overlay - { - public override string GetTypeName() - { - return "TerraViewer.AudioOverlay"; - } - - string filename; - AudioElement audio = null; - bool audioReady = false; - bool wantPlaying = false; - int volume = 100; - bool mute = false; - double position = 0; - - public bool Mute - { - get { return mute; } - set - { - mute = value; - Volume = Volume; - } - } - - public int Volume - { - get { return volume; } - set - { - volume = value; - if (audio != null) - { - audio.Volume = this.mute ? 0 : (float)(volume / 100.0); - } - } - } - - public AudioOverlay() - { - isDesignTimeOnly = true; - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - fc.AddFile(Owner.Owner.WorkingDirectory + filename, Owner.Owner.GetFileBlob(this.filename)); - } - - public override void Play() - { - if (audio == null) - { - PrepMultimedia(); - } - - wantPlaying = true; - - if (audio != null && audioReady) - { - audio.Play(); - Volume = Volume; - audio.CurrentTime = position; - } - } - - public override void Pause() - { - if (audio == null) - { - PrepMultimedia(); - } - - wantPlaying = false; - - if (audio != null && audioReady) - { - audio.Pause(); - } - } - - public override void Stop() - { - Pause(); // these operations are identical for audio - } - - public override void Seek(double time) - { - position = time; - if (audio == null) - { - PrepMultimedia(); - } - //todo double check time - - if (audioReady) - { - if (audio.Duration < time) - { - audio.Pause(); - } - else - { - audio.CurrentTime = position; - } - } - } - - //public AudioOverlay(RenderContext renderContext, TourStop owner, string filename) - //{ - // isDesignTimeOnly = true; - // X = 0; - // Y = 0; - // this.filename = Guid.NewGuid().ToString() + filename.Substr(filename.LastIndexOf(".")); - // this.Owner = owner; - // this.Name = owner.GetNextDefaultName("Audio"); - // // File.Copy(filename, Owner.Owner.WorkingDirectory + this.filename); - //} - - public override void PrepMultimedia() - { - if (audio != null) - return; - - audio = (AudioElement)Document.CreateElement("audio"); - audio.AddEventListener("canplaythrough", delegate { - if (!audioReady) { - audioReady = true; - if (wantPlaying) { - Play(); - } - } - }, false); - - // As of December 2020, on Safari, we need to use a - // sub-element for the audio to play. If we set src/type on the - // parent element the playback breaks. This in turn breaks some - // older browsers -- in a world of infinite developer time we'd - // choose the behavior based on the browser version. - // - // The mis-cast here is intentional since ScriptSharp doesn't - // have a element definition. It also doesn't have the - // "type" property. Sigh. - AudioElement source = (AudioElement) Document.CreateElement("source"); - audio.AppendChild(source); - source.Src = Owner.Owner.GetFileStream(this.filename); - Script.Literal("source.type = {0}", "audio/mp3"); // TODO! non-MP3 audio formats! - audio.Load(); - } - - // TODO: understand better when/how this function is called. It ought to - // be called for every frame by the generic Draw3D implementation since - // we never set `texture`, I think. But note that the main music and - // voice tracks aren't "rendered" in this way, so this function doesn't - // get called for them, it looks. - public override void InitializeTexture() - { - PrepMultimedia(); - } - - public override void CleanUp() - { - base.CleanUp(); - wantPlaying = false; - - if (audio != null) - { - audio.Pause(); - audio.Src = null; - audio = null; - } - } - - AudioType trackType = AudioType.Music; - - public AudioType TrackType - { - get { return trackType; } - set { trackType = value; } - } - - public override void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("Audio"); - xmlWriter.WriteAttributeString("Filename", filename); - xmlWriter.WriteAttributeString("Volume", volume.ToString()); - xmlWriter.WriteAttributeString("Mute", mute.ToString()); - xmlWriter.WriteAttributeString("TrackType", Enums.ToXml("AudioType",(int)trackType)); - // xmlWriter.WriteAttributeString("Begin", begin.ToString()); - // xmlWriter.WriteAttributeString("End", end.ToString()); - // xmlWriter.WriteAttributeString("FadeIn", fadeIn.ToString()); - // xmlWriter.WriteAttributeString("FadeOut", fadeOut.ToString()); - // xmlWriter.WriteAttributeString("Loop", loop.ToString()); - xmlWriter.WriteEndElement(); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode audio = Util.SelectSingleNode(node, "Audio"); - filename = audio.Attributes.GetNamedItem("Filename").Value; - - if (audio.Attributes.GetNamedItem("Volume") != null) - { - volume = int.Parse(audio.Attributes.GetNamedItem("Volume").Value); - } - - if (audio.Attributes.GetNamedItem("Mute") != null) - { - mute = bool.Parse(audio.Attributes.GetNamedItem("Mute").Value); - } - - if (audio.Attributes.GetNamedItem("TrackType") != null) - { - trackType = (AudioType)Enums.Parse("AudioType", audio.Attributes.GetNamedItem("TrackType").Value); - } - } - - public static AudioOverlay Create(TourStop currentTourStop, System.Html.Data.Files.File file) - { - AudioOverlay ao = new AudioOverlay(); - ao.Owner = currentTourStop; - ao.filename = file.Name; - ao.Owner.Owner.AddCachedFile(file.Name, file); - return ao; - } - } - - public enum LoopTypes { Loop = 0, UpDown = 1, Down = 2, UpDownOnce = 3, Once = 4, Begin = 5, End = 6 }; - - public class FlipbookOverlay : Overlay - { - - public override string GetTypeName() - { - return "TerraViewer.FlipbookOverlay"; - } - - string filename; - - LoopTypes loopType = LoopTypes.UpDown; - - public LoopTypes LoopType - { - get { return loopType; } - set { loopType = value; } - } - - int startFrame = 0; - - public int StartFrame - { - get { return startFrame; } - set { startFrame = value; } - } - List framesList = new List(); - string frameSequence; - - public string FrameSequence - { - get { return frameSequence; } - set - { - if (frameSequence != value) - { - frameSequence = value; - framesList = new List(); - if (!string.IsNullOrEmpty(frameSequence)) - { - try - { - string[] parts = frameSequence.Split(","); - foreach (string part in parts) - { - int x = int.Parse(part.Trim()); - framesList.Add(x); - } - } - catch - { - } - } - } - } - } - - int frames = 1; - - public int Frames - { - get { return frames; } - set - { - frames = value; - } - } - - int framesX = 8; - - public int FramesX - { - get { return framesX; } - set { framesX = value; } - } - int framesY = 8; - - public int FramesY - { - get { return framesY; } - set { framesY = value; } - } - - - - public FlipbookOverlay() - { - - } - - //public FlipbookOverlay(RenderContext renderContext, TourStop owner, string filename) - //{ - // this.Owner = owner; - - - // string extension = filename.Substr(filename.LastIndexOf(".")); - - // this.filename = Guid.NewGuid().ToString() + extension; - - // this.Name = filename.Substr(filename.LastIndexOf('\\')); - // //File.Copy(filename, Owner.Owner.WorkingDirectory + this.filename); - - // //Bitmap bmp = new Bitmap(Owner.Owner.WorkingDirectory + this.filename); - // Width = 256; - // Height = 256; - // //bmp.Dispose(); - // //bmp = null; - // X = 0; - // Y = 0; - //} - - - //public FlipbookOverlay(RenderContext renderContext, TourStop owner, Image image) - //{ - // this.Owner = owner; - // this.canvas = canvas; - // // to make directory and guid filename in tour temp dir. - // this.filename = Guid.NewGuid().ToString() + ".png"; - - // this.Name = owner.GetNextDefaultName("Image"); - // X = 0; - // Y = 0; - // //image.Save(Owner.Owner.WorkingDirectory + filename, ImageFormat.Png); - // Width = 256; - // Height = 256; - //} - - public FlipbookOverlay Copy(TourStop owner) - { - //todo fix this - FlipbookOverlay newFlipbookOverlay = new FlipbookOverlay(); - newFlipbookOverlay.Owner = owner; - newFlipbookOverlay.filename = this.filename; - newFlipbookOverlay.X = this.X; - newFlipbookOverlay.Y = this.Y; - newFlipbookOverlay.Width = this.Width; - newFlipbookOverlay.Height = this.Height; - newFlipbookOverlay.Color = this.Color; - newFlipbookOverlay.Opacity = this.Opacity; - newFlipbookOverlay.RotationAngle = this.RotationAngle; - newFlipbookOverlay.Name = this.Name + " - Copy"; - newFlipbookOverlay.StartFrame = this.StartFrame; - newFlipbookOverlay.Frames = this.Frames; - newFlipbookOverlay.LoopType = this.LoopType; - newFlipbookOverlay.FrameSequence = this.FrameSequence; - newFlipbookOverlay.FramesX = this.FramesX; - newFlipbookOverlay.FramesY = this.FramesY; - - return newFlipbookOverlay; - } - - public override void CleanUp() - { - texture = null; - } - bool textureReady = false; - public override void InitializeTexture() - { - try - { - bool colorKey = filename.ToLowerCase().EndsWith(".jpg"); - texture = Owner.Owner.GetCachedTexture( filename, delegate { textureReady = true; }); - - //texture = UiTools.LoadTextureFromBmp(device, Owner.Owner.WorkingDirectory + filename); - - // texture = TextureLoader.FromFile(device, Owner.Owner.WorkingDirectory + filename); - - //if (Width == 0 && Height == 0) - //{ - // Width = sd.Width; - // Height = sd.Height; - - //} - } - catch - { - //texture = UiTools.LoadTextureFromBmp(device, (Bitmap)global::TerraViewer.Properties.Resources.BadImage); - //SurfaceDescription sd = texture.GetLevelDescription(0); - - //{ - // Width = sd.Width; - // Height = sd.Height; - - //} - } - } - - public override void AddFilesToCabinet(FileCabinet fc) - { - fc.AddFile(Owner.Owner.WorkingDirectory + filename, Owner.Owner.GetFileBlob(filename)); - } - - public override void WriteOverlayProperties(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("Flipbook"); - xmlWriter.WriteAttributeString("Filename", filename); - xmlWriter.WriteAttributeString("Frames", frames.ToString()); - xmlWriter.WriteAttributeString("Loop", Enums.ToXml("LoopTypes", (int)loopType)); - xmlWriter.WriteAttributeString("FramesX", framesX.ToString()); - xmlWriter.WriteAttributeString("FramesY", framesY.ToString()); - xmlWriter.WriteAttributeString("StartFrame", startFrame.ToString()); - if (!string.IsNullOrEmpty(frameSequence)) - { - xmlWriter.WriteAttributeString("FrameSequence", frameSequence.ToString()); - } - xmlWriter.WriteEndElement(); - } - - public override void InitializeFromXml(XmlNode node) - { - XmlNode flipbook = Util.SelectSingleNode(node, "Flipbook"); - filename = flipbook.Attributes.GetNamedItem("Filename").Value; - frames = int.Parse(flipbook.Attributes.GetNamedItem("Frames").Value); - - loopType = (LoopTypes)Enums.Parse("LoopTypes", flipbook.Attributes.GetNamedItem("Loop").Value); - - if (flipbook.Attributes.GetNamedItem("FramesX") != null) - { - FramesX = int.Parse(flipbook.Attributes.GetNamedItem("FramesX").Value); - } - if (flipbook.Attributes.GetNamedItem("FramesY") != null) - { - FramesY = int.Parse(flipbook.Attributes.GetNamedItem("FramesY").Value); - } - if (flipbook.Attributes.GetNamedItem("StartFrame") != null) - { - StartFrame = int.Parse(flipbook.Attributes.GetNamedItem("StartFrame").Value); - } - if (flipbook.Attributes.GetNamedItem("FrameSequence") != null) - { - FrameSequence = flipbook.Attributes.GetNamedItem("FrameSequence").Value; - } - } - - int currentFrame = 0; - //int widthCount = 8; - //int heightCount = 8; - int cellHeight = 256; - int cellWidth = 256; - Date timeStart = Date.Now; - bool playing = true; - public override void Play() - { - playing = true; - timeStart = Date.Now; - } - public override void Pause() - { - playing = false; - } - public override void Stop() - { - playing = false; - currentFrame = 0; - } - - override public void InitializeGeometry() - { - int frameCount = frames; - if (!String.IsNullOrEmpty(frameSequence)) - { - frameCount = framesList.Count; - } - - if (playing) - { - // todo allow play backwards loop to point. - int ts = Date.Now - timeStart; - switch (loopType) - { - case LoopTypes.Loop: - currentFrame = (int)((ts / 1000.0 * 24.0) % frameCount) + startFrame; - break; - case LoopTypes.UpDown: - currentFrame = Math.Abs((int)((ts / 1000.0 * 24.0 + frameCount) % (frameCount * 2 - 1)) - (frameCount - 1)) + startFrame; - if (currentFrame < 0 || currentFrame > frameCount - 1) - { - int p = 0; - } - break; - case LoopTypes.Down: - currentFrame = Math.Max(0, frameCount - (int)((ts / 1000.0 * 24.0) % frameCount)) + startFrame; - break; - case LoopTypes.UpDownOnce: - int temp = (int)Math.Min(ts / 1000.0 * 24.0, frameCount * 2 + 1) + frameCount; - currentFrame = Math.Abs((int)((temp) % (frameCount * 2 - 1)) - (frameCount - 1)) + startFrame; - break; - case LoopTypes.Once: - currentFrame = Math.Min(frameCount - 1, (int)((ts / 1000.0 * 24.0))); - break; - case LoopTypes.Begin: - currentFrame = startFrame; - break; - case LoopTypes.End: - currentFrame = (frameCount - 1) + startFrame; - break; - default: - currentFrame = startFrame; - break; - } - - } - if (!String.IsNullOrEmpty(frameSequence)) - { - if (currentFrame < framesList.Count && currentFrame > -1) - { - currentFrame = framesList[currentFrame]; - } - else - { - currentFrame = 0; - } - } - - currentRotation = 0; - } - } -} - - diff --git a/engine/csharp_ref/Tours/Selection.cs b/engine/csharp_ref/Tours/Selection.cs deleted file mode 100644 index 6bcc4226..00000000 --- a/engine/csharp_ref/Tours/Selection.cs +++ /dev/null @@ -1,274 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class Selection - { - Texture SingleSelectHandles = null; - Texture MultiSelectHandles = null; - Texture FocusHandles = null; - public Selection() - { - } - - public List SelectionSet = new List(); - - //public Overlay[] SelectionSet - //{ - // get { return selectionSet.ToArray(); } - //} - - public void ClearSelection() - { - SelectionSet.Clear(); - } - - public void AddSelection(Overlay overlay) - { - if (overlay != null) - { - if(!SelectionSet.Contains(overlay)) - { - SelectionSet.Add(overlay); - } - - } - } - - public void AddSelectionRange(Overlay[] overlays) - { - foreach (Overlay ov in overlays) - { - SelectionSet.Add(ov); - } - } - - public bool IsOverlaySelected(Overlay overlay) - { - return SelectionSet.Contains(overlay); - } - - public void SetSelection(Overlay overlay) - { - SelectionSet.Clear(); - if (overlay != null) - { - SelectionSet.Add(overlay); - } - } - - public bool MultiSelect - { - get - { - return SelectionSet.Count > 1; - } - } - - public void SetSelectionRange(Overlay[] overlays) - { - SelectionSet.Clear(); - foreach (Overlay ov in overlays) - { - SelectionSet.Add(ov); - } - } - - Overlay focus = null; - - public Overlay Focus - { - get { return focus; } - set { focus = value; } - } - - - double ratio = 1.0f; - public void Draw3D(RenderContext renderContext, double transparancy) - { - ratio = 1116f / renderContext.Height; - - if (SingleSelectHandles == null) - { - SingleSelectHandles = Texture.FromUrl("images/Selhand.bmp"); - } - - if (MultiSelectHandles == null) - { - MultiSelectHandles = Texture.FromUrl("images/multiSelhand.bmp"); - } - - if (FocusHandles == null) - { - FocusHandles = Texture.FromUrl("images/FocusHandles.png"); - } - - if (SelectionSet.Count > 1) - { - foreach (Overlay overlay in SelectionSet) - { - if (overlay == focus) - { - - DrawSelectionHandles(renderContext, overlay, FocusHandles); - } - else - { - - DrawSelectionHandles(renderContext, overlay, MultiSelectHandles); - } - } - } - else - { - foreach (Overlay overlay in SelectionSet) - { - DrawSelectionHandles(renderContext, overlay, SingleSelectHandles); - } - } - } - - private static PositionColoredTextured[] points = new PositionColoredTextured[9 * 3 * 2]; - - private Sprite2d sprite = new Sprite2d(); - - private void DrawSelectionHandles(RenderContext renderContext, Overlay overlay, Texture handleTexture) - { - Rectangle[] handles = MakeHandles(overlay); - double angle = overlay.RotationAngle; - - int i = 0; - int j = 0; - foreach (Rectangle handle in handles) - { - points[i + 0] = new PositionColoredTextured(); - points[i + 0].Position = overlay.MakePosition(centerX, centerY, handle.Left - centerX, handle.Top - centerY, angle); - points[i + 0].Tu = j * (1f / 9f); - points[i + 0].Tv = 0; - points[i + 0].Color = Colors.White; - - points[i + 1] = new PositionColoredTextured(); - points[i + 1].Position = overlay.MakePosition(centerX, centerY, handle.Right - centerX, handle.Top - centerY, angle); - points[i + 1].Tu = (j + 1) * (1f / 9f); - points[i + 1].Tv = 0; - points[i + 1].Color = Colors.White; - - points[i + 2] = new PositionColoredTextured(); - points[i + 2].Position = overlay.MakePosition(centerX, centerY, handle.Left - centerX, handle.Bottom - centerY, angle); - points[i + 2].Tu = j * (1f / 9f); - points[i + 2].Tv = 1; - points[i + 2].Color = Colors.White; - - points[i + 3] = new PositionColoredTextured(); - points[i + 3].Position = overlay.MakePosition(centerX, centerY, handle.Right - centerX, handle.Top - centerY, angle); - points[i + 3].Tu = (j + 1) * (1f / 9f); - points[i + 3].Tv = 0; - points[i + 3].Color = Colors.White; - - points[i + 4] = new PositionColoredTextured(); - points[i + 4].Position = overlay.MakePosition(centerX, centerY, handle.Right - centerX, handle.Bottom - centerY, angle); - points[i + 4].Tu = (j + 1) * (1f / 9f); - points[i + 4].Tv = 1; - points[i + 4].Color = Colors.White; - - points[i + 5] = new PositionColoredTextured(); - points[i + 5].Position = overlay.MakePosition(centerX, centerY, handle.Left - centerX, handle.Bottom - centerY, angle); - points[i + 5].Tu = j * (1f / 9f); - points[i + 5].Tv = 1; - points[i + 5].Color = Colors.White; - - i += 6; - j++; - } - - if (MultiSelect) - { - sprite.Draw(renderContext, points, points.Length - 6, handleTexture, false, 1); - } - else - { - sprite.Draw(renderContext, points, points.Length, handleTexture, false, 1); - } - } - - public Vector2d PointToSelectionSpace(Vector2d pntIn) - { - Vector2d[] tempPoints = new Vector2d[1]; - tempPoints[0] = Vector2d.Create(pntIn.X, pntIn.Y); - - Matrix2d mat = Matrix2d.RotateAt(-SelectionSet[0].RotationAngle / 180 * Math.PI, Vector2d.Create((SelectionSet[0].X), (SelectionSet[0].Y))); - mat.TransformPoints(tempPoints); - return tempPoints[0]; - } - - public Vector2d PointToScreenSpace(Vector2d pntIn) - { - Vector2d[] tempPoints = new Vector2d[1]; - tempPoints[0] = Vector2d.Create(pntIn.X, pntIn.Y); - - Matrix2d mat = Matrix2d.RotateAt(SelectionSet[0].RotationAngle / 180 * Math.PI, Vector2d.Create((SelectionSet[0].X), (SelectionSet[0].Y))); - mat.TransformPoints(tempPoints); - return tempPoints[0]; - } - - public SelectionAnchor HitTest(Vector2d position) - { - if (SelectionSet.Count == 1) - { - foreach (Overlay overlay in SelectionSet) - { - Rectangle[] handles = MakeHandles(overlay); - int index = 0; - - Vector2d testPoint = PointToSelectionSpace(position); - foreach (Rectangle rectf in handles) - { - if (rectf.Contains(testPoint)) - { - return (SelectionAnchor)index; - } - index++; - } - } - } - - return SelectionAnchor.None; - - } - - double centerX = 0; - double centerY = 0; - public Rectangle[] MakeHandles(Overlay overlay) - { - double x = ((int)(overlay.X-(overlay.Width/2)))+.5f; - double y = ((int)overlay.Y-(overlay.Height/2))+.5f; - - centerX = overlay.X; - centerY = overlay.Y; - - double width = overlay.Width; - double height = overlay.Height; - double handleSize = 12*ratio; - Rectangle[] handles = new Rectangle[9]; - - handles[0] = Rectangle.Create(x - handleSize, y - handleSize, handleSize, handleSize); - handles[1] = Rectangle.Create((x + (width / 2)) - (handleSize/2), y - handleSize, handleSize, handleSize); - handles[2] = Rectangle.Create(x + width, y - handleSize, handleSize, handleSize); - handles[3] = Rectangle.Create(x + width, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); - handles[4] = Rectangle.Create(x + width, (y + height), handleSize, handleSize); - handles[5] = Rectangle.Create((x + (width / 2)) - (handleSize / 2), (y + height), handleSize, handleSize); - handles[6] = Rectangle.Create(x - handleSize, (y + height), handleSize, handleSize); - handles[7] = Rectangle.Create(x - handleSize, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); - handles[8] = Rectangle.Create((x + (width / 2)) - (handleSize / 2), y - 30f*ratio, handleSize, handleSize); - return handles; - } - - } - public enum SelectionAnchor { TopLeft=0, Top=1, TopRight=2, Right=3, BottomRight=4, Bottom=5, BottomLeft=6, Left=7, Rotate=8, Move=9, Center=10, None=11 }; - -} diff --git a/engine/csharp_ref/Tours/TextObject.cs b/engine/csharp_ref/Tours/TextObject.cs deleted file mode 100644 index 53a0bd1e..00000000 --- a/engine/csharp_ref/Tours/TextObject.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; - -namespace wwtlib -{ - - public enum TextBorderStyle { None=0, Tight=1, Small=2, Medium=3, Large=4 }; - public class TextObject - { - public TextObject() - { - } - - - public static TextObject Create(string text, bool bold, bool italic, bool underline, float fontSize, string fontName, Color forgroundColor, Color backgroundColor , TextBorderStyle borderStyle) - { - TextObject temp = new TextObject(); - - temp.Text = text; - temp.Bold = bold; - temp.Italic = italic; - temp.Underline = underline; - temp.FontSize = fontSize; - temp.FontName = fontName; - temp.ForegroundColor = forgroundColor; - temp.BackgroundColor = backgroundColor; - temp.BorderStyle = borderStyle; - return temp; - } - - public string Text; - public bool Bold; - public bool Italic; - public bool Underline; - public float FontSize; - public string FontName; - public Color ForegroundColor; - public Color BackgroundColor; - public TextBorderStyle BorderStyle; - - public override string ToString() - { - return Text; - } - - internal void SaveToXml(XmlTextWriter xmlWriter) - { - xmlWriter.WriteStartElement("TextObject"); - xmlWriter.WriteAttributeString("Bold", Bold.ToString()); - xmlWriter.WriteAttributeString("Italic", Italic.ToString()); - xmlWriter.WriteAttributeString("Underline", Underline.ToString()); - xmlWriter.WriteAttributeString("FontSize", FontSize.ToString()); - xmlWriter.WriteAttributeString("FontName", FontName); - xmlWriter.WriteAttributeString("ForgroundColor", ForegroundColor.Save()); - xmlWriter.WriteAttributeString("BackgroundColor", BackgroundColor.Save()); - xmlWriter.WriteAttributeString("BorderStyle", Enums.ToXml("TextBorderStyle", (int)BorderStyle)); - - xmlWriter.WriteString(this.Text); - xmlWriter.WriteEndElement(); - } - - internal static TextObject FromXml(XmlNode node) - { - TextObject newTextObject = new TextObject(); - newTextObject.Text = Util.GetInnerText(node); - newTextObject.BorderStyle = TextBorderStyle.None; - newTextObject.Bold = bool.Parse(node.Attributes.GetNamedItem("Bold").Value); - newTextObject.Italic = bool.Parse(node.Attributes.GetNamedItem("Italic").Value); - newTextObject.Underline = bool.Parse(node.Attributes.GetNamedItem("Underline").Value); - newTextObject.FontSize = float.Parse(node.Attributes.GetNamedItem("FontSize").Value); - newTextObject.FontName = node.Attributes.GetNamedItem("FontName").Value; - newTextObject.ForegroundColor = Color.Load(node.Attributes.GetNamedItem("ForgroundColor").Value); - newTextObject.BackgroundColor = Color.Load(node.Attributes.GetNamedItem("BackgroundColor").Value); - if (node.Attributes.GetNamedItem("BorderStyle") != null) - { - newTextObject.BorderStyle = (TextBorderStyle)Enums.Parse("TextBorderStyle",node.Attributes.GetNamedItem("BorderStyle").Value); - } - return newTextObject; - } - } -} diff --git a/engine/csharp_ref/Tours/TourDocument.cs b/engine/csharp_ref/Tours/TourDocument.cs deleted file mode 100644 index 20b95158..00000000 --- a/engine/csharp_ref/Tours/TourDocument.cs +++ /dev/null @@ -1,1094 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Net; -using System.Html.Data.Files; - -namespace wwtlib -{ - - public enum UserLevel { Beginner=0, Intermediate=1, Advanced=2, Educator=3, Professional=4 }; - public class TourDocument - { - int tourDirty = 0; - public bool TourDirty - { - get { return tourDirty > 0; } - set - { - if (value) - { - tourDirty++; - } - else - { - tourDirty = 0; - } - - } - } - - public TourDocument() - { - id = Guid.NewGuid().ToString(); - } - - string workingDirectory = ""; - public string WorkingDirectory - { - get - { - if (String.IsNullOrEmpty(workingDirectory)) - { - workingDirectory = TourDocument.BaseWorkingDirectory + id.ToString() + @"\"; - } - - return workingDirectory; - } - set - { - workingDirectory = value; - } - } - public static string BaseWorkingDirectory - { - get - { - //return Settings.Active.CahceDirectory + @"Temp\"; - return @""; - } - - } - - FileCabinet cabinet; - public string Url = ""; - private Action callMe; - - public static TourDocument FromUrl(string url, Action callMe) - { - TourDocument temp = new TourDocument(); - temp.Url = url; - temp.callMe = callMe; - - temp.cabinet = FileCabinet.FromUrl(url, temp.LoadXmlDocument); - return temp; - } - - public static TourDocument FromUrlRaw(string url, Action callMe) - { - TourDocument temp = new TourDocument(); - temp.Url = url; - temp.callMe = callMe; - - temp.cabinet = FileCabinet.FromUrl(url, callMe); - return temp; - } - - private void LoadXmlDocument() - { - try - { - string master = cabinet.MasterFile; - - FileReader doc = new FileReader(); - doc.OnLoadEnd = delegate (FileProgressEvent ee) - { - string data = doc.Result as string; - XmlDocumentParser xParser = new XmlDocumentParser(); - FromXml(xParser.ParseFromString(data, "text/xml")); - callMe(); - }; - doc.ReadAsText(cabinet.GetFileBlob(master)); - } - catch (Exception ex) - { - WWTControl.scriptInterface.FireTourError(ex); - } - } - - public void FromXml(XmlDocument doc) - { - - XmlNode root = Util.SelectSingleNode(doc, "Tour"); - - - id = root.Attributes.GetNamedItem("ID").Value.ToString(); - Title = root.Attributes.GetNamedItem("Title").Value.ToString(); - Author = root.Attributes.GetNamedItem("Author").Value.ToString(); - - if (root.Attributes.GetNamedItem("Descirption") != null) - { - Description = root.Attributes.GetNamedItem("Descirption").Value; - } - - if (root.Attributes.GetNamedItem("AuthorEmail") != null) - { - authorEmail = root.Attributes.GetNamedItem("AuthorEmail").Value; - } - - if (root.Attributes.GetNamedItem("Keywords") != null) - { - Keywords = root.Attributes.GetNamedItem("Keywords").Value; - } - - if (root.Attributes.GetNamedItem("OrganizationName") != null) - { - OrgName = root.Attributes.GetNamedItem("OrganizationName").Value; - } - - - - organizationUrl = root.Attributes.GetNamedItem("OrganizationUrl").Value; - - level = (UserLevel)Enums.Parse("UserLevel",root.Attributes.GetNamedItem("UserLevel").Value); - - type = (Classification)Enums.Parse("Classification", root.Attributes.GetNamedItem("Classification").Value); - - taxonomy = root.Attributes.GetNamedItem("Taxonomy").Value.ToString(); - XmlNode TourStops = Util.SelectSingleNode(root, "TourStops"); - foreach (XmlNode tourStop in TourStops.ChildNodes) - { - if (tourStop.Name == "TourStop") - { - AddTourStop(TourStop.FromXml(this, tourStop)); - } - } - - XmlNode Frames = Util.SelectSingleNode(root, "ReferenceFrames"); - - if (Frames != null) - { - foreach (XmlNode frame in Frames.ChildNodes) - { - if (frame.Name == "ReferenceFrame") - { - ReferenceFrame newFrame = new ReferenceFrame(); - newFrame.InitializeFromXml(frame); - if (!LayerManager.AllMaps.ContainsKey(newFrame.Name)) - { - LayerMap map = new LayerMap(newFrame.Name, ReferenceFrames.Custom); - map.Frame = newFrame; - map.LoadedFromTour = true; - LayerManager.AllMaps[newFrame.Name] = map; - } - } - } - LayerManager.ConnectAllChildren(); - LayerManager.LoadTree(); - } - - XmlNode Layers = Util.SelectSingleNode(root, "Layers"); - - if (Layers != null) - { - foreach (XmlNode layer in Layers.ChildNodes) - { - if (layer.Name == "Layer") - { - - Layer newLayer = Layer.FromXml(layer,true);//.Layer.FromXml(layer, true); - if (newLayer != null) - { - if (newLayer is ImageSetLayer) - { - ImageSetLayer imageSetLayer = (ImageSetLayer)newLayer; - Imageset imageset = imageSetLayer.ImageSet; - if (imageset.Projection == ProjectionType.Healpix && imageset.Extension == ".tsv") - { - WWTControl.Singleton.AddCatalogHips(imageset); - continue; - } - } - string fileName = string.Format("{0}.txt", newLayer.ID.ToString()); - if (LayerManager.LayerList.ContainsKey(newLayer.ID)) // && newLayer.ID != ISSLayer.ISSGuid) - { - //if (!CollisionChecked) - //{ - // if (UiTools.ShowMessageBox(Language.GetLocalizedText(958, "There are layers with the same name. Overwrite existing layers?"), Language.GetLocalizedText(3, "Microsoft WorldWide Telescope"), System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) - // { - // OverWrite = true; - // } - // else - // { - // OverWrite = false; - - // } - // CollisionChecked = true; - //} - - //if (OverWrite) - //{ - LayerManager.DeleteLayerByID(newLayer.ID, true, false); - //} - } - try - { - newLayer.LoadedFromTour = true; - newLayer.LoadData(this, fileName); - LayerManager.Add(newLayer, false); - } - catch - { - } - } - } - } - LayerManager.LoadTree(); - } - - //todo author - //if (File.Exists(WorkingDirectory + "Author.png")) - //{ - // authorImage = UiTools.LoadBitmap(WorkingDirectory + "Author.png"); - //} - - tourDirty = 0; - - } - - public string SaveToDataUrl() - { - return (string)Script.Literal("URL.createObjectURL({0});", SaveToBlob()); - } - - public Blob SaveToBlob() - { - bool excludeAudio = false; - - CleanUp(); - - string tourXml = GetTourXML(); - - FileCabinet fc = new FileCabinet(); - fc.PackageID = this.Id; - - - fc.AddFile("Tour.wwtxml", new Blob(new object[] { tourXml })); - - if (authorImage != null) - { - //todo add author image pipeline - // fc.AddFile(WorkingDirectory + "Author.Png"); - } - - foreach (TourStop stop in TourStops) - { - stop.AddFilesToCabinet(fc, excludeAudio); - } - - List masterList = CreateLayerMasterList(); - - foreach (Guid id in masterList) - { - if (LayerManager.LayerList.ContainsKey(id)) - { - LayerManager.LayerList[id].AddFilesToCabinet(fc); - } - } - - TourDirty = false; - return fc.PackageFiles(); - } - - public string GetTourXML() - { - XmlTextWriter xmlWriter = new XmlTextWriter(); - - xmlWriter.Formatting = Formatting.Indented; - xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - xmlWriter.WriteStartElement("Tour"); - - xmlWriter.WriteAttributeString("ID", this.id); - xmlWriter.WriteAttributeString("Title", this.title); - xmlWriter.WriteAttributeString("Descirption", this.Description); - xmlWriter.WriteAttributeString("Description", this.Description); - xmlWriter.WriteAttributeString("RunTime", ((double)this.RunTime / 1000.0).ToString()); - xmlWriter.WriteAttributeString("Author", this.author); - xmlWriter.WriteAttributeString("AuthorEmail", this.authorEmail); - xmlWriter.WriteAttributeString("OrganizationUrl", this.organizationUrl); - xmlWriter.WriteAttributeString("OrganizationName", this.OrgName); - xmlWriter.WriteAttributeString("Keywords", this.Keywords); - xmlWriter.WriteAttributeString("UserLevel", Enums.ToXml("UserLevel",(int)level)); - xmlWriter.WriteAttributeString("Classification", Enums.ToXml("Classification", (int)type)); - xmlWriter.WriteAttributeString("Taxonomy", taxonomy.ToString()); - // xmlWriter.WriteAttributeString("DomeMode", DomeMode.ToString()); - bool timeLineTour = IsTimelineTour(); - xmlWriter.WriteAttributeString("TimeLineTour", timeLineTour.ToString()); - - - xmlWriter.WriteStartElement("TourStops"); - foreach (TourStop stop in TourStops) - { - stop.SaveToXml(xmlWriter, true); - } - xmlWriter.WriteEndElement(); - - - List masterList = CreateLayerMasterList(); - - // This will now save and sync emtpy frames... - List referencedFrames = GetReferenceFrameList(); - - xmlWriter.WriteStartElement("ReferenceFrames"); - foreach (ReferenceFrame item in referencedFrames) - { - item.SaveToXml(xmlWriter); - } - xmlWriter.WriteEndElement(); - - - xmlWriter.WriteStartElement("Layers"); - foreach (Guid id in masterList) - { - if (LayerManager.LayerList.ContainsKey(id)) - { - Layer layer = LayerManager.LayerList[id]; - string name = layer.Name; - Imageset imageset = WWTControl.Singleton.RenderContext.GetCatalogHipsByName(name); - if (imageset != null) - { - ImageSetLayer imageSetLayer = ImageSetLayer.Create(imageset); - imageSetLayer.ID = id; - imageSetLayer.Name = name; - imageSetLayer.ReferenceFrame = "Sky"; - imageSetLayer.SaveToXml(xmlWriter); - } - else - { - LayerManager.LayerList[id].SaveToXml(xmlWriter); - } - } - } - xmlWriter.WriteEndElement(); - - - xmlWriter.WriteFullEndElement(); - xmlWriter.Close(); - - return xmlWriter.Body; - } - - private List GetReferenceFrameList() - { - List list = new List(); - - foreach (string key in LayerManager.AllMaps.Keys) - { - LayerMap lm = LayerManager.AllMaps[key]; - if ((lm.Frame.Reference == ReferenceFrames.Custom || lm.Frame.Reference == ReferenceFrames.Identity) && !list.Contains(lm.Frame) && lm.Frame.SystemGenerated == false) - { - list.Add(lm.Frame); - } - } - - return list; - } - - private List CreateLayerMasterList() - { - List masterList = new List(); - foreach (TourStop stop in TourStops) - { - foreach (Guid id in stop.Layers.Keys) - { - if (!masterList.Contains(id)) - { - if (LayerManager.LayerList.ContainsKey(id)) - { - masterList.Add(id); - } - } - } - } - return masterList; - } - - private bool IsTimelineTour() - { - return false; - } - - string tagId=""; - - public string TagId - { - get { return tagId; } - set { tagId = value; } - } - - - - - public string AuthorThumbnailFilename - { - get - { - return "Author.Png"; - } - } - - private int representativeThumbnailTourstop = 0; - - public string TourThumbnailFilename - { - get - { - if (representativeThumbnailTourstop < tourStops.Count) - { - return tourStops[representativeThumbnailTourstop].TourStopThumbnailFilename; - } - else - { - return null; - } - } - } - - - - string id=""; - - public string Id - { - get { return id; } - set { id = value; } - } - - string title=""; - - public string Title - { - get { return title; } - set - { - title = value; - TourDirty = true; - } - } - - int runTime = 0; - int lastDirtyCheck = 0; - - public int RunTime - { - get - { - //todo this is in ms right now... - if (runTime == 0 || lastDirtyCheck != tourDirty) - { - runTime = CalculateRunTime(); - lastDirtyCheck = tourDirty; - } - return runTime; - } - } - - string description=""; - - public string Description - { - get { return description; } - set - { - description = value; - TourDirty = true; - } - } - string attributesAndCredits=""; - - public string AttributesAndCredits - { - get { return attributesAndCredits; } - set - { - attributesAndCredits = value; - TourDirty = true; - } - } - - string authorEmailOther=""; - - public string AuthorEmailOther - { - get { return authorEmailOther; } - set - { - authorEmailOther = value; - TourDirty = true; - } - } - - string authorEmail=""; - - public string AuthorEmail - { - get { return authorEmail; } - set - { - authorEmail = value; - TourDirty = true; - } - } - - string authorUrl=""; - - public string AuthorUrl - { - get { return authorUrl; } - set - { - authorUrl = value; - TourDirty = true; - } - } - - string authorPhone=""; - - public string AuthorPhone - { - get { return authorPhone; } - set - { - authorPhone = value; - TourDirty = true; - } - } - - string authorContactText = ""; - - public string AuthorContactText - { - get { return authorContactText; } - set - { - authorContactText = value; - TourDirty = true; - } - } - - string orgName = "None"; - - public string OrgName - { - get { return orgName; } - set - { - orgName = value; - TourDirty = true; - } - } - - string orgUrl = ""; - - public string OrgUrl - { - get { return orgUrl; } - set - { - orgUrl = value; - TourDirty = true; - } - } - - string author = ""; - - public string Author - { - get { return author; } - set - { - author = value; - TourDirty = true; - } - } - string authorImageUrl = ""; - - public string AuthorImageUrl - { - get { return authorImageUrl; } - set - { - authorImageUrl = value; - TourDirty = true; - } - } - - ImageElement authorImage = null; - - public ImageElement AuthorImage - { - get { return authorImage; } - set - { - authorImage = value; - TourDirty = true; - } - } - - string organizationUrl = ""; - - public string OrganizationUrl - { - get { return organizationUrl; } - set - { - organizationUrl = value; - TourDirty = true; - } - } - - - String filename = ""; - - public String FileName - { - get { return filename; } - set { filename = value; } - } - - UserLevel level = UserLevel.Beginner; - - public UserLevel Level - { - get { return level; } - set - { - level = value; - TourDirty = true; - } - } - - Classification type = Classification.Unidentified; - - public Classification Type - { - get { return type; } - set - { - type = value; - TourDirty = true; - } - } - - string taxonomy = ""; - - public string Taxonomy - { - get { return taxonomy; } - set - { - taxonomy = value; - TourDirty = true; - } - } - string keywords = ""; - - public string Keywords - { - get { return keywords; } - set - { - keywords = value; - TourDirty = true; - } - } - string objects = ""; - - public string Objects - { - get { return objects; } - set - { - objects = value; - TourDirty = true; - } - } - bool editMode = false; - - public bool EditMode - { - get { return editMode; } - set - { - editMode = value; - } - } - - public List ExplicitTourLinks = new List(); - public List ImplicitTourLinks = new List(); - - List tourStops = new List(); - - public List TourStops - { - get { return tourStops; } - set { tourStops = value; } - } - //todo need change notifications. - int currentTourstopIndex = -1; - - public int CurrentTourstopIndex - { - get { return currentTourstopIndex; } - set { currentTourstopIndex = value; } - } - - public void AddTourStop(TourStop ts) - { - ts.Owner = this; - - TourStops.Add(ts); - currentTourstopIndex = tourStops.Count - 1; - - TourDirty = true; - } - - public void InsertTourStop(TourStop ts) - { - ts.Owner = this; - if (currentTourstopIndex > -1) - { - TourStops.Insert(currentTourstopIndex, ts); - } - else - { - TourStops.Add(ts); - currentTourstopIndex = tourStops.Count - 1; - } - TourDirty = true; - } - - public void InsertAfterTourStop(TourStop ts) - { - ts.Owner = this; - if (currentTourstopIndex > -1 || currentTourstopIndex < TourStops.Count) - { - TourStops.Insert(currentTourstopIndex+1, ts); - } - else - { - TourStops.Add(ts); - currentTourstopIndex = tourStops.Count - 1; - } - TourDirty = true; - } - - public void RemoveTourStop(TourStop ts) - { - tourStops.Remove(ts); - if (currentTourstopIndex > tourStops.Count - 1) - { - currentTourstopIndex--; - } - TourDirty = true; - } - - private int CalculateRunTime() - { - double totalTime = 0.0; - for (int i = 0; i < tourStops.Count; i++) - { - totalTime += (double)(tourStops[i].Duration); - if (i > 0) - { - switch (tourStops[i].Transition) - { - case TransitionType.Slew: - if (tourStops[i].Target.BackgroundImageset == null || (tourStops[i - 1].Target.BackgroundImageset.DataSetType == tourStops[i].Target.BackgroundImageset.DataSetType - && ((tourStops[i - 1].Target.BackgroundImageset.DataSetType != ImageSetType.SolarSystem) || (tourStops[i - 1].Target.Target == tourStops[i].Target.Target)))) - { - CameraParameters start = tourStops[i - 1].EndTarget == null ? tourStops[i - 1].Target.CamParams : tourStops[i - 1].EndTarget.CamParams; - ViewMoverSlew slew = ViewMoverSlew.Create(start, tourStops[i].Target.CamParams); - totalTime += slew.MoveTime*1000; - } - break; - case TransitionType.CrossCut: - break; - case TransitionType.CrossFade: - break; - case TransitionType.FadeOut: - break; - default: - break; - } - } - } - return (int)totalTime; - } - - public double ElapsedTimeTillTourstop(int index) - { - if (index == 0 && index >= tourStops.Count) - { - return 0; - } - double totalTime = 0.0; - for (int i = 0; i < index; i++) - { - totalTime += (double)(tourStops[i].Duration); - if (i > 0) - { - switch (tourStops[i].Transition) - { - case TransitionType.Slew: - CameraParameters start = tourStops[i - 1].EndTarget == null ? tourStops[i - 1].Target.CamParams : tourStops[i - 1].EndTarget.CamParams; - if (tourStops[i - 1].Target.BackgroundImageset.DataSetType == tourStops[i].Target.BackgroundImageset.DataSetType - && ((tourStops[i - 1].Target.BackgroundImageset.DataSetType != ImageSetType.SolarSystem) || (tourStops[i - 1].Target.Target == tourStops[i].Target.Target))) - { - ViewMoverSlew slew = ViewMoverSlew.Create(start, tourStops[i].Target.CamParams); - totalTime += slew.MoveTime*1000; - } - break; - case TransitionType.CrossCut: - break; - case TransitionType.CrossFade: - break; - case TransitionType.FadeOut: - break; - default: - break; - } - } - } - return totalTime/1000; - } - - public MasterTime ElapsedTimeSinceLastMaster(int index) - { - TourStop masterOut = null; - if (index == 0 && index >= tourStops.Count) - { - return null; - } - double totalTime = 0.0; - for (int i = 0; i < index; i++) - { - if (tourStops[i].MasterSlide) - { - totalTime = 0; - masterOut = tourStops[i]; - } - - totalTime += (double)(tourStops[i].Duration); - if (i > 0) - { - switch (tourStops[i].Transition) - { - case TransitionType.Slew: - CameraParameters start = tourStops[i - 1].EndTarget == null ? tourStops[i - 1].Target.CamParams : tourStops[i - 1].EndTarget.CamParams; - if (tourStops[i - 1].Target.BackgroundImageset.DataSetType == tourStops[i].Target.BackgroundImageset.DataSetType - && ((tourStops[i - 1].Target.BackgroundImageset.DataSetType != ImageSetType.SolarSystem) || (tourStops[i - 1].Target.Target == tourStops[i].Target.Target))) - { - ViewMoverSlew slew = ViewMoverSlew.Create(start, tourStops[i].Target.CamParams); - totalTime += slew.MoveTime*1000; - } - break; - case TransitionType.CrossCut: - break; - case TransitionType.CrossFade: - break; - case TransitionType.FadeOut: - break; - default: - break; - } - } - } - - - return new MasterTime(masterOut, totalTime / 1000); - } - - public TourStop GetMasterSlideForIndex(int index) - { - int master = -1; - for (int i = 0; i < index; i++) - { - if (tourStops[i].MasterSlide) - { - master = i; - } - } - if (master == -1) - { - return null; - } - - return tourStops[master]; - } - - public int GetTourStopIndexByID(string id) - { - if (id == "" || id == "Next") - { - return currentTourstopIndex++; - } - - int index = 0; - foreach (TourStop stop in tourStops) - { - if (stop.Id == id) - { - return index; - } - index++; - } - return -1; - } - - public void CleanUp() - { - //foreach (TourStop stop in TourStops) - //{ - // stop.CleanUp(); - //} - //if (textureList != null) - //{ - - // textureList.Clear(); - //} - - } - private Dictionary textureList = new Dictionary(); - public ImageElement GetCachedTexture(string filename, Action callMe) - { - - if (textureList == null) - { - textureList = new Dictionary(); - } - - if (textureList.ContainsKey(filename)) - { - callMe(); - return textureList[filename]; - } - string url = GetFileStream(filename); - - if (!string.IsNullOrWhiteSpace(url)) - { - ImageElement texture = (ImageElement)Document.CreateElement("img"); - - texture.Src = GetFileStream(filename); - texture.AddEventListener("load", delegate { callMe(); }, false); - - textureList[filename] = texture; - - return texture; - } - else - { - return null; - } - } - - private Dictionary textureList2d = new Dictionary(); - public Texture GetCachedTexture2d(string filename) - { - - if (textureList2d == null) - { - textureList2d = new Dictionary(); - } - - if (textureList2d.ContainsKey(filename)) - { - return textureList2d[filename]; - } - - Texture texture = new Texture(); - - texture.Load(GetFileStream(filename)); - textureList2d[filename] = texture; - - return texture; - - } - - // This handles new files added while editing a tour - private Dictionary fileCache = new Dictionary(); - - public void AddCachedFile( string filename, Blob file) - { - fileCache[filename] = file; - - //Clean up old Cached Textures if they are based on this file. - if (textureList2d.ContainsKey(filename)) - { - textureList2d.Remove(filename); - } - - if (textureList.ContainsKey(filename)) - { - textureList.Remove(filename); - } - } - - public string GetFileStream(string filename) - { - Blob blob = GetFileBlob(filename); - if (blob == null) - { - return null; - } - - return (string)Script.Literal("URL.createObjectURL({0});", blob); - } - - public Blob GetFileBlob(string filename) - { - if (fileCache.ContainsKey(filename)) - { - return fileCache[filename]; - } - else if (cabinet != null) - { - return cabinet.GetFileBlob(WorkingDirectory + filename); - } - else - { - return null; - } - } - - public TourStop CurrentTourStop - { - get - { - if (currentTourstopIndex > -1) - { - return TourStops[currentTourstopIndex]; - } - else - { - return null; - } - } - set - { - int i = 0; - foreach (TourStop stop in TourStops) - { - if (stop == value) - { - if (currentTourstopIndex > -1) - { - // TourStops[currentTourstopIndex].CleanUp(); - } - currentTourstopIndex = i; - break; - } - i++; - } - } - } - public bool DontCleanUpTempFiles = false; - public void ClearTempFiles() - { - - } - } - -} diff --git a/engine/csharp_ref/Tours/TourEdit.cs b/engine/csharp_ref/Tours/TourEdit.cs deleted file mode 100644 index 0712a014..00000000 --- a/engine/csharp_ref/Tours/TourEdit.cs +++ /dev/null @@ -1,1469 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class TourEditTab - { - public TourEditTab() - { - //InitializeComponent(); - //SetUiStrings(); - } - - public SoundEditor MusicTrack = new SoundEditor(); - public SoundEditor VoiceTrack = new SoundEditor(); - - - public void SetUiStrings() - { - //this.toolTip.SetToolTip(this.tourStopList, Language.GetLocalizedText(416, "Slides")); - //this.AddText.Text = Language.GetLocalizedText(417, "Text"); - //this.EditTourProperties.Text = Language.GetLocalizedText(418, "Tour Properties"); - //this.AddShape.Text = Language.GetLocalizedText(419, "Shapes"); - //this.AddPicture.Text = Language.GetLocalizedText(420, "Picture"); - //this.AddVideo.Text = Language.GetLocalizedText(421, "Video"); - //this.SaveTour.Text = Language.GetLocalizedText(422, " Save"); - //this.ShowSafeArea.Text = Language.GetLocalizedText(423, "Show Safe Area"); - //this.runTimeLabel.Text = Language.GetLocalizedText(424, "Run Time"); - //this.Dome.Text = Language.GetLocalizedText(1109, "Dome"); - } - - TourDocument tour = null; - public TourStopList tourStopList = new TourStopList(); - - public TourEditor TourEditorUI = new TourEditor(); - - public TourDocument Tour - { - get - { - return tour; - } - set - { - tour = value; - TourEditorUI.Tour = tour; - tourStopList.Tour = tour; - //todo add current tourstop notification changes. - //tour.CurrentTourstopChanged = tour_CurrentTourstopChanged; - Overlay.DefaultAnchor = OverlayAnchor.Screen; - if (tour.TourStops.Count > 0) - { - WWTControl.Singleton.GotoTarget(tour.TourStops[0].Target, false, true, false); - tour.CurrentTourstopIndex = 0; - tourStopList.SelectedItem = tour.CurrentTourstopIndex; - MusicTrack.Target = tour.CurrentTourStop; - VoiceTrack.Target = tour.CurrentTourStop; - LayerManager.SetVisibleLayerList(tour.CurrentTourStop.Layers); - } - SetEditMode(tour.EditMode); - - - } - } - - public void tour_CurrentTourstopChanged() - { - OverlayList.UpdateOverlayList(tour.CurrentTourStop, TourEditorUI.Selection); - if (TourEditorUI != null) - { - TourEditorUI.ClearSelection(); - } - tourStopList.Refresh(); - } - - public void SetFocusedChild() - { - // tourStopList.Focus(); - } - - public void SelectCurrent() - { - tourStopList.SelectedItem = tour.CurrentTourstopIndex; - tourStopList.Refresh(); - } - - public void TourEdit_Load(object sender, EventArgs e) - { - //if (tour != null && !tour.EditMode) - //{ - // PlayNow(true); - //} - //TourPlayer.TourEnded = TourPlayer_TourEnded); - //ShowSafeArea.Checked = Properties.Settings.Default.ShowSafeArea; - - //if (tour.EditMode) - //{ - // tourStopList.AllowMultipleSelection = true; - //} - } - - public void PlayNow(bool fromStart) - { - playing = true; - if (Tour.EditMode || fromStart) - { - Tour.CurrentTourstopIndex = -1; - } - SetPlayPauseMode(); - } - - void TourPlayer_TourEnded(object sender, EventArgs e) - { - //if (tour != null && !tour.EditMode && !Properties.Settings.Default.AutoRepeatTourAll && !Settings.DomeView) - //{ - - // // Earth3d.MainWindow.ShowTourCompleteDialog = true; - //} - } - - void endTour_CloseTour(object sender, EventArgs e) - { - // Earth3d.MainWindow.CloseTour(false); - } - - void endTour_LaunchTour(object sender, EventArgs e) - { - PlayNow(true); - } - - - public void SetEditMode(bool visible) - { - //tour.EditMode = visible; - - //EditTourProperties.Visible = visible; - //SaveTour.Visible = visible; - //AddText.Visible = visible; - //AddShape.Visible = visible; - //AddPicture.Visible = visible; - //MusicTrack.Visible = visible; - //VoiceTrack.Visible = visible; - //ShowSafeArea.Visible = visible; - //Dome.Visible = visible; - - //if (visible) - //{ - // tourStopList.Width = (EditTourProperties.Left - 3) - tourStopList.Location.X; - // tourStopList.AllowMultipleSelection = true; - //} - //else - //{ - // tourStopList.Width = (MusicTrack.Right) - tourStopList.Location.X; - // tourStopList.AllowMultipleSelection = false; - //} - //tourStopList.ShowAddButton = visible; - - } - - public void tourStopList_ItemClicked(object sender, TourStop e) - { - if (tour.CurrentTourStop != e) - { - tour.CurrentTourStop = e; - - if (e != null) - { - MusicTrack.Target = tour.CurrentTourStop; - VoiceTrack.Target = tour.CurrentTourStop; - } - else - { - MusicTrack.Target = null; - VoiceTrack.Target = null; - - } - TourEditorUI.ClearSelection(); - } - if (playing) - { - playFromHere_Click(sender, new EventArgs()); - } - - } - - - public void tourStopList_ItemDoubleClicked(object sender, TourStop e) - { - ShowSlideStartPosition(e); - - } - - public void ShowSlideStartPosition(TourStop ts) - { - tour.CurrentTourStop = ts; - //tourText.Text = tour.CurrentTourStop.Description; - if (ts != null) - { - MusicTrack.Target = tour.CurrentTourStop; - VoiceTrack.Target = tour.CurrentTourStop; - } - else - { - MusicTrack.Target = null; - VoiceTrack.Target = null; - - } - TourEditorUI.ClearSelection(); - if (tour.CurrentTourStop != null) - { - tour.CurrentTourStop.SyncSettings(); - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - WWTControl.Singleton.GotoTarget(ts.Target, false, true, false); - tour.CurrentTourStop.TweenPosition = 0f; - tour.CurrentTourStop.UpdateLayerOpacity(); - LayerManager.SetVisibleLayerList(tour.CurrentTourStop.Layers); - - } - } - - - ContextMenuStrip contextMenu = new ContextMenuStrip(); - - public void tourStopList_MouseClick(object sender, ElementEvent e) - { - if (!tour.EditMode) - { - // return; - } - //IDataObject dataObject = Clipboard.GetDataObject(); - - // tour.CurrentTourstopIndex = tourStopList.SelectedItem; - - - //if (tourStopList.HitType == TourStopList.HitPosition.Transition) - //{ - // return; - //} - - // if (e.Button == 2) - { - if (tourStopList.MultipleSelection) - { - if (contextMenu != null) - { - contextMenu.Dispose(); - } - // MultiSelection Menu - contextMenu = new ContextMenuStrip(); - ToolStripMenuItem selectAllMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1345, "Select All")); - ToolStripMenuItem cutMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(427, "Cut")); - ToolStripMenuItem copyMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(428, "Copy")); - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(429, "Paste")); - ToolStripMenuItem deleteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(167, "Delete")); - cutMenu.Click = cutMenu_Click; - copyMenu.Click = copyMenu_Click; - pasteMenu.Click = pasteMenu_Click; - deleteMenu.Click = deleteMenu_Click; - selectAllMenu.Click = selectAllMenu_Click; - ToolStripSeparator sep1 = new ToolStripSeparator(); - - contextMenu.Items.Add(selectAllMenu); - contextMenu.Items.Add(sep1); - contextMenu.Items.Add(cutMenu); - contextMenu.Items.Add(copyMenu); - - pasteMenu.Enabled = TourEditorUI.clipboardType == TourStop.ClipboardFormat; - contextMenu.Items.Add(pasteMenu); - contextMenu.Items.Add(deleteMenu); - contextMenu.Show(Cursor.Position); - } - else if (tour.CurrentTourStop == null) - { - // Context menu for no selection - if (contextMenu != null) - { - contextMenu.Dispose(); - } - - contextMenu = new ContextMenuStrip(); - ToolStripMenuItem selectAllMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1345, "Select All")); - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(425, "Paste")); - ToolStripSeparator sep1 = new ToolStripSeparator(); - ToolStripSeparator sep2 = new ToolStripSeparator(); - ToolStripMenuItem insertSlide = ToolStripMenuItem.Create(Language.GetLocalizedText(426, "Add New Slide")); - - pasteMenu.Click = pasteMenu_Click; - selectAllMenu.Click = selectAllMenu_Click; - - insertSlide.Click = AddNewSlide_Click; - - - // todo check for clibboard format first - pasteMenu.Enabled = TourEditorUI.clipboardType == TourStop.ClipboardFormat; - contextMenu.Items.Add(selectAllMenu); - contextMenu.Items.Add(sep1); - contextMenu.Items.Add(pasteMenu); - contextMenu.Items.Add(sep2); - contextMenu.Items.Add(insertSlide); - contextMenu.Show(Cursor.Position); - } - else - { - if (contextMenu != null) - { - contextMenu.Dispose(); - } - - contextMenu = new ContextMenuStrip(); - ToolStripMenuItem selectAllMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1345, "Select All")); - - ToolStripMenuItem cutMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(427, "Cut")); - ToolStripMenuItem copyMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(428, "Copy")); - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(429, "Paste")); - ToolStripMenuItem deleteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(167, "Delete")); - ToolStripSeparator sep1 = new ToolStripSeparator(); - ToolStripSeparator sep3 = new ToolStripSeparator(); - ToolStripSeparator sep4 = new ToolStripSeparator(); - ToolStripSeparator sep5 = new ToolStripSeparator(); - ToolStripSeparator sep6 = new ToolStripSeparator(); - ToolStripSeparator sep7 = new ToolStripSeparator(); - ToolStripMenuItem insertSlide = ToolStripMenuItem.Create(Language.GetLocalizedText(431, "Insert New Slide")); - ToolStripMenuItem insertDuplicate = ToolStripMenuItem.Create(Language.GetLocalizedText(627, "Duplicate Slide at End Position")); - ToolStripMenuItem insertSlideshow = ToolStripMenuItem.Create(Language.GetLocalizedText(628, "Merge Tour after slide...")); - ToolStripMenuItem playFromHere = ToolStripMenuItem.Create(Language.GetLocalizedText(432, "Preview Tour From Here")); - ToolStripSeparator sep2 = new ToolStripSeparator(); - ToolStripMenuItem captureThumbnail = ToolStripMenuItem.Create(Language.GetLocalizedText(433, "Capture New Thumbnail")); - ToolStripMenuItem setSkyPosition = ToolStripMenuItem.Create(Language.GetLocalizedText(434, "Set Start Camera Position")); - ToolStripMenuItem setEndSkyPosition = ToolStripMenuItem.Create(Language.GetLocalizedText(435, "Set End Camera Position")); - ToolStripMenuItem showSkyPosition = ToolStripMenuItem.Create(Language.GetLocalizedText(436, "Show Start Camera Position")); - ToolStripMenuItem showEndSkyPosition = ToolStripMenuItem.Create(Language.GetLocalizedText(437, "Show End Camera Position")); - ToolStripMenuItem masterSlide = ToolStripMenuItem.Create(Language.GetLocalizedText(438, "Master Slide")); - ToolStripMenuItem makeTimeline = ToolStripMenuItem.Create(Language.GetLocalizedText(1346, "Create Timeline")); - ToolStripMenuItem showTimeline = ToolStripMenuItem.Create(Language.GetLocalizedText(1347, "Show Timeline")); - string linkString = tour.CurrentTourStop.NextSlide; - switch (linkString) - { - case "": - case null: - case "Next": - - //linkString = " (Next Slide)"; - linkString = " (" + Language.GetLocalizedText(610, "Next Slide") + ")"; - break; - case "Return": - //linkString = " (Return to Caller)"; - linkString = " (" + Language.GetLocalizedText(602, "Return to Caller") + ")"; - break; - default: - int index = Tour.GetTourStopIndexByID(linkString); - if (index > -1) - { - if (String.IsNullOrEmpty(tour.TourStops[index].Description)) - { - linkString = String.Format(" (Slide {0})", index); - } - else - { - linkString = " (" + tour.TourStops[index].Description + ")"; - } - } - break; - } - - - ToolStripMenuItem setNextSlide = ToolStripMenuItem.Create(Language.GetLocalizedText(590, "Set Next Slide") + linkString); - ToolStripMenuItem trackSpaceTime = ToolStripMenuItem.Create(Language.GetLocalizedText(439, "Track Date/Time/Location")); - ToolStripMenuItem fadeInOverlays = ToolStripMenuItem.Create(Language.GetLocalizedText(629, "Fade In Slide Elements")); - ToolStripMenuItem properties = ToolStripMenuItem.Create(Language.GetLocalizedText(20, "Properties")); - ToolStripMenuItem interpolation = ToolStripMenuItem.Create(Language.GetLocalizedText(1029, "Animation Tween Type")); - - ToolStripMenuItem Linear = ToolStripMenuItem.Create(Language.GetLocalizedText(1030, "Linear")); - ToolStripMenuItem Ease = ToolStripMenuItem.Create(Language.GetLocalizedText(1031, "Ease In/Out")); - ToolStripMenuItem EaseIn = ToolStripMenuItem.Create(Language.GetLocalizedText(1032, "Ease In")); - ToolStripMenuItem EaseOut = ToolStripMenuItem.Create(Language.GetLocalizedText(1033, "Ease Out")); - ToolStripMenuItem Exponential = ToolStripMenuItem.Create(Language.GetLocalizedText(1034, "Exponential")); - - Linear.Tag = InterpolationType.Linear; - Ease.Tag = InterpolationType.EaseInOut; - EaseIn.Tag = InterpolationType.EaseIn; - EaseOut.Tag = InterpolationType.EaseOut; - Exponential.Tag = InterpolationType.Exponential; - - Linear.Click = Interpolation_Click; - Ease.Click = Interpolation_Click; - EaseIn.Click = Interpolation_Click; - EaseOut.Click = Interpolation_Click; - Exponential.Click = Interpolation_Click; - - - switch (tour.CurrentTourStop.InterpolationType) - { - case InterpolationType.Linear: - Linear.Checked = true; - break; - case InterpolationType.EaseIn: - EaseIn.Checked = true; - break; - case InterpolationType.EaseOut: - EaseOut.Checked = true; - break; - case InterpolationType.EaseInOut: - Ease.Checked = true; - break; - case InterpolationType.Exponential: - Exponential.Checked = true; - break; - default: - break; - } - - - interpolation.DropDownItems.Add(Linear); - interpolation.DropDownItems.Add(Ease); - interpolation.DropDownItems.Add(EaseIn); - interpolation.DropDownItems.Add(EaseOut); - interpolation.DropDownItems.Add(Exponential); - - selectAllMenu.Click = selectAllMenu_Click; - insertDuplicate.Click = insertDuplicate_Click; - cutMenu.Click = cutMenu_Click; - copyMenu.Click = copyMenu_Click; - pasteMenu.Click = pasteMenu_Click; - deleteMenu.Click = deleteMenu_Click; - insertSlide.Click = InsertNewSlide_Click; - properties.Click = properties_Click; - captureThumbnail.Click = captureThumbnail_Click; - setSkyPosition.Click = setSkyPosition_Click; - setEndSkyPosition.Click = setEndSkyPosition_Click; - showEndSkyPosition.Click = showEndSkyPosition_Click; - showSkyPosition.Click = showSkyPosition_Click; - playFromHere.Click = playFromHere_Click; - masterSlide.Click = masterSlide_Click; - setNextSlide.Click = setNextSlide_Click; - trackSpaceTime.Click = trackSpaceTime_Click; - insertSlideshow.Click = insertSlideshow_Click; - fadeInOverlays.Click = fadeInOverlays_Click; - - //makeTimeline.Click = makeTimeline_Click; - //showTimeline.Click = makeTimeline_Click; - - if (tour.CurrentTourStop.MasterSlide) - { - masterSlide.Checked = true; - } - - if (tour.CurrentTourStop.HasTime) - { - trackSpaceTime.Checked = true; - } - - fadeInOverlays.Checked = tour.CurrentTourStop.FadeInOverlays; - - contextMenu.Items.Add(selectAllMenu); - contextMenu.Items.Add(sep7); - contextMenu.Items.Add(cutMenu); - contextMenu.Items.Add(copyMenu); - pasteMenu.Enabled = TourEditorUI.clipboardType == TourStop.ClipboardFormat; - contextMenu.Items.Add(pasteMenu); - contextMenu.Items.Add(deleteMenu); - contextMenu.Items.Add(sep1); - contextMenu.Items.Add(insertSlide); - contextMenu.Items.Add(insertDuplicate); - contextMenu.Items.Add(insertSlideshow); - contextMenu.Items.Add(sep2); - contextMenu.Items.Add(playFromHere); - contextMenu.Items.Add(sep3); - contextMenu.Items.Add(setSkyPosition); - contextMenu.Items.Add(setEndSkyPosition); - contextMenu.Items.Add(sep4); - contextMenu.Items.Add(showSkyPosition); - contextMenu.Items.Add(showEndSkyPosition); - contextMenu.Items.Add(sep5); - contextMenu.Items.Add(captureThumbnail); - contextMenu.Items.Add(sep6); - - //if (!tour.CurrentTourStop.KeyFramed) - //{ - // contextMenu.Items.Add(makeTimeline); - //} - //else - //{ - // contextMenu.Items.Add(showTimeline); - //} - - contextMenu.Items.Add(masterSlide); - contextMenu.Items.Add(setNextSlide); - contextMenu.Items.Add(fadeInOverlays); - contextMenu.Items.Add(trackSpaceTime); - contextMenu.Items.Add(interpolation); - // contextMenu.Items.Add(properties); - contextMenu.Show(Vector2d.Create(e.ClientX,e.ClientY)); - } - } - } - - //void makeTimeline_Click(object sender, EventArgs e) - //{ - // if (tour.CurrentTourStop != null) - // { - // tour.CurrentTourStop.KeyFramed = true; - // KeyFramer.ShowTimeline(); - // } - //} - - void selectAllMenu_Click(object sender, EventArgs e) - { - tourStopList.SelectAll(); - } - - void Interpolation_Click(object sender, EventArgs e) - { - ToolStripMenuItem item = (ToolStripMenuItem)sender; - tour.CurrentTourStop.InterpolationType = (InterpolationType)item.Tag; - } - - public SetNextSlideDelegate nextSlideCallback = null; - - private void NextSlideChosen() - { - if (selectDialog.OK) - { - tour.CurrentTourStop.NextSlide = selectDialog.ID; - } - } - private SelectLink selectDialog; - - void setNextSlide_Click(object sender, EventArgs e) - { - selectDialog = new SelectLink(null); - nextSlideCallback(selectDialog, NextSlideChosen); - - } - - void insertDuplicate_Click(object sender, EventArgs e) - { - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(530, "Duplicate Slide at End Position"), tour)); - - TourStop ts = tour.CurrentTourStop.Copy(); - - if (ts == null) - { - return; - } - - if (ts.EndTarget != null) - { - ts.EndTarget.BackgroundImageset = ts.Target.BackgroundImageset; - ts.EndTarget.StudyImageset = ts.Target.StudyImageset; - ts.Target = ts.EndTarget; - ts.StartTime = ts.EndTime; - ts.EndTarget = null; - } - - foreach (Overlay overlay in ts.Overlays) - { - overlay.TweenFactor = 1f; - overlay.Animate = !overlay.Animate; - overlay.Animate = !overlay.Animate; - } - ts.TweenPosition = 0f; - ts.FadeInOverlays = false; - tour.InsertAfterTourStop(ts); - tourStopList.Refresh(); - - } - - void fadeInOverlays_Click(object sender, EventArgs e) - { - tour.CurrentTourStop.FadeInOverlays = !tour.CurrentTourStop.FadeInOverlays; - } - - void insertSlideshow_Click(object sender, EventArgs e) - { - //todo localize - //Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(531, "Merge Slide Show"), tour)); - //OpenFileDialog openFile = new OpenFileDialog(); - //openFile.Filter = Language.GetLocalizedText(101, "WorldWide Telescope Tours") + "|*.wtt"; - //if (openFile.ShowDialog() == DialogResult.OK) - //{ - // string filename = openFile.FileName; - // try - // { - // tour.MergeTour(filename); - // } - // catch - // { - // MessageBox.Show(Language.GetLocalizedText(102, "This file does not seem to be a valid tour"), Language.GetLocalizedText(3, "Microsoft WorldWide Telescope")); - // } - //} - //tourStopList.Refresh(); - } - - void trackSpaceTime_Click(object sender, EventArgs e) - { - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(532, "Track Time Edit"), tour)); - tour.CurrentTourStop.HasTime = !tour.CurrentTourStop.HasTime; - } - - void masterSlide_Click(object sender, EventArgs e) - { - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(533, "Master Slide State Edit"), tour)); - tour.CurrentTourStop.MasterSlide = !tour.CurrentTourStop.MasterSlide; - tourStopList.Refresh(); - } - - void playFromHere_Click(object sender, EventArgs e) - { - PlayFromCurrentTourstop(); - } - - public void PlayFromCurrentTourstop() - { - playing = true; - WWTControl.Singleton.GotoTarget(tour.CurrentTourStop.Target, false, true, false); - //tour.CurrentTourStop.SyncSettings(); - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - SetPlayPauseMode(); - } - - public void PlayFromTourstop(TourStop ts) - { - tour.CurrentTourStop = ts; - PlayFromCurrentTourstop(); - } - - - void showSkyPosition_Click(object sender, EventArgs e) - { - if (tour.CurrentTourStop != null) - { - WWTControl.Singleton.GotoTarget(tour.CurrentTourStop.Target, false, true, false); - tour.CurrentTourStop.SyncSettings(); - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - tour.CurrentTourStop.TweenPosition = 0f; - LayerManager.SetVisibleLayerList(tour.CurrentTourStop.Layers); - tourStopList.Refresh(); - - } - } - - void showEndSkyPosition_Click(object sender, EventArgs e) - { - tour.CurrentTourStop.TweenPosition = 1f; - tour.CurrentTourStop.UpdateLayerOpacity(); - if (tour.CurrentTourStop != null && tour.CurrentTourStop.EndTarget != null) - { - //Earth3d.MainWindow.GotoTarget(tour.CurrentTourStop.EndTarget, false, false); - WWTControl.Singleton.GotoTargetFull(false, true, tour.CurrentTourStop.EndTarget.CamParams, tour.CurrentTourStop.Target.StudyImageset, tour.CurrentTourStop.Target.BackgroundImageset); - WWTControl.Singleton.RenderContext.SolarSystemTrack = tour.CurrentTourStop.EndTarget.Target; - SpaceTimeController.Now = tour.CurrentTourStop.EndTime; - tour.CurrentTourStop.SyncSettings(); - LayerManager.SetVisibleLayerList(tour.CurrentTourStop.Layers); - SpaceTimeController.SyncToClock = false; - tourStopList.Refresh(); - TourEditorUI.ClearSelection(); - } - } - - void setEndSkyPosition_Click(object sender, EventArgs e) - { - if (tour.CurrentTourStop != null) - { - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(435, "Set End Camera Position"), tour)); - - Place newPlace = Place.CreateCameraParams( - "End Place", - WWTControl.Singleton.RenderContext.ViewCamera.Copy(), - Classification.Unidentified, - WWTControl.Singleton.Constellation, - WWTControl.Singleton.RenderContext.BackgroundImageset.DataSetType, - WWTControl.Singleton.RenderContext.SolarSystemTrack - ); - tour.CurrentTourStop.EndTarget = newPlace; - tour.CurrentTourStop.EndTarget.Constellation = WWTControl.Singleton.Constellation; - tour.CurrentTourStop.EndTime = SpaceTimeController.Now; - //tour.CurrentTourStop.SetEndKeyFrames(); - tour.CurrentTourStop.TweenPosition = 1f; - - foreach(Guid key in tour.CurrentTourStop.Layers.Keys) - { - LayerInfo info = tour.CurrentTourStop.Layers[key]; - - if (LayerManager.LayerList.ContainsKey(info.ID)) - { - info.EndOpacity = LayerManager.LayerList[info.ID].Opacity; - info.EndParams = LayerManager.LayerList[info.ID].GetParams(); - } - } - tour.CurrentTourStop.UpdateLayerOpacity(); - - tourStopList.Refresh(); - TimeLine.RefreshUi(); - TourEditorUI.ClearSelection(); - } - } - - void setSkyPosition_Click(object sender, EventArgs e) - { - if (tour.CurrentTourStop != null) - { - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(434, "Set Start Camera Position"), tour)); - - tour.CurrentTourStop.Target.Target = WWTControl.Singleton.RenderContext.SolarSystemTrack; - tour.CurrentTourStop.Target.Type = WWTControl.Singleton.RenderContext.BackgroundImageset.DataSetType; - tour.CurrentTourStop.Target.CamParams = WWTControl.Singleton.RenderContext.ViewCamera.Copy(); - tour.CurrentTourStop.Target.Constellation = WWTControl.Singleton.Constellation; - tour.CurrentTourStop.Target.StudyImageset = WWTControl.Singleton.RenderContext.ForegroundImageset; - tour.CurrentTourStop.Target.Type = WWTControl.Singleton.RenderContext.BackgroundImageset.DataSetType; - tour.CurrentTourStop.Target.BackgroundImageset = WWTControl.Singleton.RenderContext.BackgroundImageset.StockImageSet; - tour.CurrentTourStop.CaptureSettings(); - tour.CurrentTourStop.Layers = LayerManager.GetVisibleLayerList(tour.CurrentTourStop.Layers); - //tour.CurrentTourStop.SetStartKeyFrames(); - tour.CurrentTourStop.TweenPosition = 0f; - tourStopList.Refresh(); - TimeLine.RefreshUi(); - TourEditorUI.ClearSelection(); - } - } - - void captureThumbnail_Click(object sender, EventArgs e) - { - if (tour.CurrentTourStop != null) - { - CaptureThumbnail(tour.CurrentTourStop); - } - } - - private void CaptureThumbnail(TourStop tourStop) - { - WWTControl.Singleton.CaptureThumbnail( - delegate (System.Html.Data.Files.Blob blob) - { - string filename = string.Format("{0}.thumb.png", tourStop.Id); - tour.AddCachedFile(filename, blob); - tourStop.Thumbnail = tour.GetCachedTexture(filename, delegate { tourStopList.Refresh(); }); - }); - } - - void properties_Click(object sender, EventArgs e) - { - throw new Exception("The method or operation is not implemented."); - } - - public void tourStopList_AddNewSlide(object sender, TourStop e) - { - AddSlide(false); - tourStopList.EnsureAddVisible(); - } - - void AddNewSlide_Click(object sender, EventArgs e) - { - AddSlide(false); - tourStopList.EnsureAddVisible(); - } - - void InsertNewSlide_Click(object sender, EventArgs e) - { - AddSlide(true); - - } - - public void AddSlide(bool insert) - { - //todo localize - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(426, "Add New Slide"), tour)); - - Cursor.Current = Cursors.WaitCursor; - string placeName = "Current Screen"; - Place newPlace = Place.CreateCameraParams(placeName, WWTControl.Singleton.RenderContext.ViewCamera.Copy(), Classification.Unidentified, WWTControl.Singleton.Constellation, WWTControl.Singleton.RenderContext.BackgroundImageset.DataSetType, WWTControl.Singleton.RenderContext.SolarSystemTrack); - // newPlace.ThumbNail = null; - newPlace.StudyImageset = WWTControl.Singleton.RenderContext.ForegroundImageset; - newPlace.BackgroundImageset = WWTControl.Singleton.RenderContext.BackgroundImageset.StockImageSet; - - TourStop newTourStop = TourStop.Create(newPlace); - - - if (insert) - { - tour.InsertTourStop(newTourStop); - } - else - { - tour.AddTourStop(newTourStop); - } - - if (tour.CurrentTourStop != null) - { - MusicTrack.Target = tour.CurrentTourStop; - VoiceTrack.Target = tour.CurrentTourStop; - } - else - { - MusicTrack.Target = null; - VoiceTrack.Target = null; - - } - tour.CurrentTourStop.Layers = LayerManager.GetVisibleLayerList(tour.CurrentTourStop.Layers); - CaptureThumbnail(newTourStop); - tourStopList.SelectedItem = tourStopList.FindItem(newTourStop); - tourStopList.Refresh(); - TourEditorUI.ClearSelection(); - Cursor.Current = Cursors.DefaultV; - TimeLine.RefreshUi(); - } - - void deleteMenu_Click(object sender, EventArgs e) - { - //todo localize - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(534, "Delete Slide"), tour)); - foreach (int key in tourStopList.SelectedItems.Keys) - { - TourStop item = tourStopList.SelectedItems[key]; - tour.RemoveTourStop(item); - } - - tourStopList.SelectedItems.Clear(); - tourStopList.SelectedItem = -1; - tour.CurrentTourStop = null; - - - MusicTrack.Target = null; - VoiceTrack.Target = null; - - - tourStopList.Refresh(); - TourEditorUI.ClearSelection(); - } - - void pasteMenu_Click(object sender, EventArgs e) - { - if (TourEditorUI.clipboardType == TourStop.ClipboardFormat) - { - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(535, "Paste Slide"), tour)); - // add try catch block - - XmlDocumentParser xParser = new XmlDocumentParser(); - XmlDocument doc = xParser.ParseFromString(TourEditorUI.clipboardData, "text/xml"); - XmlNode node = Util.SelectSingleNode(doc, "TourStops"); - - Stack pasteStack = new Stack(); - - foreach (XmlNode child in node.ChildNodes) - { - if (child.Name == "TourStop") - { - TourStop ts = TourStop.FromXml(tour, child); - ts.Id = Guid.NewGuid().ToString(); - pasteStack.Push(ts); - } - } - - tourStopList.SelectedItems.Clear(); - int curIndex = tourStopList.SelectedItem + pasteStack.Count - 1; - - while (pasteStack.Count > 0) - { - TourStop ts = pasteStack.Pop(); - tour.InsertTourStop(ts); - tourStopList.SelectedItems[curIndex--] = ts; - } - tourStopList.Refresh(); - TourEditorUI.ClearSelection(); - } - } - - void copyMenu_Click(object sender, EventArgs e) - { - XmlTextWriter writer = new XmlTextWriter(); - - writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - writer.WriteStartElement("TourStops"); - foreach (int key in tourStopList.SelectedItems.Keys) - { - TourStop item = tourStopList.SelectedItems[key]; - item.SaveToXml(writer, true); - } - writer.WriteEndElement(); - - TourEditorUI.clipboardType = TourStop.ClipboardFormat; - TourEditorUI.clipboardData = writer.Body; - } - - void cutMenu_Click(object sender, EventArgs e) - { - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(536, "Cut Slide"), tour)); - - copyMenu_Click(sender, e); - foreach (int key in tourStopList.SelectedItems.Keys) - { - TourStop item = tourStopList.SelectedItems[key]; - tour.RemoveTourStop(item); - } - - tourStopList.SelectedItems.Clear(); - tourStopList.Refresh(); - TourEditorUI.ClearSelection(); - } - - //public void tourText_TextChanged(object sender, EventArgs e) - //{ - // if (tour.CurrentTourStop != null) - // { - // tour.CurrentTourStop.Description = tourText.Text; - // tourStopList.Refresh(); - // } - //} - - public void PauseTour() - { - if (playing) - { - playing = false; - } - SetPlayPauseMode(); - } - - - public bool playing = false; - public void Preview_Click(object sender, EventArgs e) - { - playing = !playing; - if (playing && tour.EditMode) - { - Tour.CurrentTourstopIndex = -1; - } - SetPlayPauseMode(); - } - - TourPlayer player = null; - public void SetPlayPauseMode() - { - if (tour.EditMode) - { - if (playing) - { - if (player == null) - { - player = new TourPlayer(); - } - player.Tour = tour; - WWTControl.Singleton.uiController = player; - player.Play(); - //Preview.Image = global::TerraViewer.Properties.Resources.button_pause_normal; - //Preview.Text = Language.GetLocalizedText(440, "Pause"); - tourStopList.ShowAddButton = false; - } - else - { - WWTControl.Singleton.uiController = TourEditorUI; - - //Preview.Image = global::TerraViewer.Properties.Resources.button_play_normal; - //Preview.Text = Language.GetLocalizedText(441, "Play"); - if (player != null) - { - player.Stop(false); - //player.Dispose(); - } - player = null; - WWTControl.Singleton.Mover = null; - tourStopList.ShowAddButton = tour.EditMode; - } - } - else - { - if (playing) - { - if (player == null) - { - player = new TourPlayer(); - } - player.Tour = tour; - WWTControl.Singleton.uiController = player; - player.Play(); - //Preview.Image = global::TerraViewer.Properties.Resources.button_pause_normal; - //Preview.Text = Language.GetLocalizedText(440, "Pause"); - tourStopList.ShowAddButton = false; - } - else - { - - WWTControl.Singleton.uiController = null; - WWTControl.Singleton.RenderContext.FreezeView(); - - //Preview.Image = global::TerraViewer.Properties.Resources.button_play_normal; - //Preview.Text = Language.GetLocalizedText(441, "Play"); - if (player != null) - { - player.Stop(false); - //player.Dispose(); - } - player = null; - WWTControl.Singleton.uiController = null; - WWTControl.Singleton.Mover = null; - tourStopList.ShowAddButton = tour.EditMode; - } - } - tourStopList.Refresh(); - } - - public void PlayerTimer_Tick(object sender, EventArgs e) - { - - if (playing) - { - if (player != null) - { - if (!TourPlayer.Playing) - { - playing = false; - SetPlayPauseMode(); - } - else - { - if (tourStopList.SelectedItem != tour.CurrentTourstopIndex) - { - tourStopList.SelectedItem = tour.CurrentTourstopIndex; - } - } - } - } - //int ts = Tour.RunTime; - //todo runtime - //totalTimeText.Text = String.Format("{0:0}:{1:00}", ts.Minutes, ts.Seconds); - - } - - public void InsertShapeCircle_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Circle); - - } - - public void InsertShapeRectangle_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Rectagle); - - } - - public void InsertShapeLine_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Line); - - } - - public void insertDonut_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Donut); - - } - - - void AddArrow_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Arrow); - - } - - public void InsertVideo_Click(object sender, EventArgs e) - { - - } - - public void InsertAudio_Click(object sender, EventArgs e) - { - //OpenFileDialog fileDialog = new OpenFileDialog(); - //fileDialog.Filter = Language.GetLocalizedText(442, "Sound/Music") + "(*.MP3;*.WMA)|*.MP3;*.WMA"; - - //if (fileDialog.ShowDialog() == DialogResult.OK) - //{ - // string filename = fileDialog.FileName; - // TourEditorUI.AddAudio(filename); - //} - } - - public void InsertHyperlink_Click(object sender, EventArgs e) - { - - } - Color defultColor = Colors.White; - - public void ColorPicker_Click(object sender, EventArgs e) - { - //PopupColorPicker picker = new PopupColorPicker(); - - //picker.Location = Cursor.Position; - - //picker.Color = TourEditorUI.GetCurrentColor(); - - //if (picker.ShowDialog() == DialogResult.OK) - //{ - // TourEditorUI.SetCurrentColor(picker.Color); - //} - } - - //public void toolkit_MouseEnter(object sender, EventArgs e) - //{ - // //if (Earth3d.MainWindow.IsWindowOrChildFocused()) - // //{ - // // this.Focus(); - // //} - //} - - public void TourEditTab_Leave(object sender, EventArgs e) - { - - } - - public void EditTourProperties_Click(object sender, EventArgs e) - { - - //TourProperties tourProps = new TourProperties(); - //tourProps.EditTour = tour; - //if (tourProps.ShowDialog() == DialogResult.OK) - //{ - // Earth3d.MainWindow.Refresh(); - //} - } - - public void SaveTour_Click(object sender, EventArgs e) - { - //tour.SaveToXml(false); - - Save(false); - - } - - public bool Save(bool saveAs) - { - //if (string.IsNullOrEmpty(tour.SaveFileName) || saveAs) - //{ - // SaveFileDialog saveDialog = new SaveFileDialog(); - // saveDialog.Filter = Language.GetLocalizedText(101, "WorldWide Telescope Tours") + "|*.wtt"; - // saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - // saveDialog.AddExtension = true; - // saveDialog.DefaultExt = ".WTT"; - // saveDialog.FileName = tour.SaveFileName; - // if (saveDialog.ShowDialog() == DialogResult.OK) - // { - // tour.SaveToFile(saveDialog.FileName); - // } - // else - // { - // return false; - // } - // return true; - //} - //else - //{ - // tour.SaveToFile(tour.SaveFileName); - //} - return true; - } - - public void AddVideo_Click(object sender, EventArgs e) - { - //OpenFileDialog fileDialog = new OpenFileDialog(); - - //if (fileDialog.ShowDialog() == DialogResult.OK) - //{ - // string filename = fileDialog.FileName; - // TourEditorUI.AddVideo(filename); - //} - } - - public void AddPicture_Click(object sender, EventArgs e) - { - //if (tour == null || Tour.CurrentTourStop == null) - //{ - // return; - //} - - - //bool flipBook = false; - //if (Control.ModifierKeys == (Keys.Control | Keys.Shift)) - //{ - // flipBook = true; - //} - - //OpenFileDialog fileDialog = new OpenFileDialog(); - //fileDialog.Filter = Language.GetLocalizedText(443, "Images") + "(*.JPG;*.PNG;*.TIF;*.TIFF;*.FITS;*.FIT)|*.JPG;*.PNG;*.TIF;*.TIFF;*.FITS;*.FIT"; - //if (fileDialog.ShowDialog() == DialogResult.OK) - //{ - // string filename = fileDialog.FileName; - // if (flipBook) - // { - // TourEditorUI.AddFlipbook(filename); - // } - // else - // { - // TourEditorUI.AddPicture(filename); - // } - //} - } - - public void AddShape_Click(object sender, EventArgs e) - { - //if (tour.CurrentTourStop != null) - //{ - // // Context menu for no selection - // if (contextMenu != null) - // { - // contextMenu.Dispose(); - // } - - // contextMenu = new ContextMenuStrip(); - - // ToolStripMenuItem AddCircle = ToolStripMenuItem.Create(Language.GetLocalizedText(444, "Circle")); - // ToolStripMenuItem AddRectangle = ToolStripMenuItem.Create(Language.GetLocalizedText(445, "Rectangle")); - // ToolStripMenuItem AddOpenRectangle = ToolStripMenuItem.Create(Language.GetLocalizedText(446, "Open Rectangle")); - // ToolStripMenuItem AddRing = ToolStripMenuItem.Create(Language.GetLocalizedText(447, "Ring")); - // ToolStripMenuItem AddLine = ToolStripMenuItem.Create(Language.GetLocalizedText(448, "Line")); - // ToolStripMenuItem AddArrow = ToolStripMenuItem.Create(Language.GetLocalizedText(449, "Arrow")); - // ToolStripMenuItem AddStar = ToolStripMenuItem.Create(Language.GetLocalizedText(450, "Star")); - - // AddCircle.Click = InsertShapeCircle_Click; - // AddRectangle.Click = InsertShapeRectangle_Click; - // AddOpenRectangle.Click = AddOpenRectangle_Click; - // AddRing.Click = insertDonut_Click; - // AddLine.Click = InsertShapeLine_Click; - // AddArrow.Click = AddArrow_Click; - // AddStar.Click = AddStar_Click; - - - // contextMenu.Items.Add(AddCircle); - // contextMenu.Items.Add(AddRectangle); - // contextMenu.Items.Add(AddOpenRectangle); - // contextMenu.Items.Add(AddRing); - // contextMenu.Items.Add(AddLine); - // contextMenu.Items.Add(AddArrow); - // contextMenu.Items.Add(AddStar); - // contextMenu.Show(AddShape.PointToScreen(Vector2d.Create(0, AddShape.Height))); - //} - } - - void AddOpenRectangle_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.OpenRectagle); - } - - void AddStar_Click(object sender, EventArgs e) - { - TourEditorUI.AddShape("", ShapeType.Star); - - } - - - public void AddText_Click(object sender, EventArgs e) - { - //todo add text editor - //if (tour != null && Tour.CurrentTourStop != null) - //{ - - // TextEditor textEdit = new TextEditor(); - // if (textEdit.ShowDialog() == DialogResult.OK) - // { - // TourEditorUI.AddText(textEdit.Text, textEdit.TextObject); - // } - //} - - } - - public void Preview_EnabledChanged(object sender, EventArgs e) - { - if (playing) - { - //todo change image based on enable/disable state - } - else - { - } - } - - public void Preview_MouseEnter(object sender, EventArgs e) - { - //if (playing) - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_pause_hover; - //} - //else - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_play_hover; - //} - } - - public void Preview_MouseLeave(object sender, EventArgs e) - { - //if (playing) - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_pause_normal; - //} - //else - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_play_normal; - //} - } - - public void Preview_MouseUp(object sender, ElementEvent e) - { - //if (playing) - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_pause_hover; - //} - //else - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_play_hover; - //} - } - - public void Preview_MouseDown(object sender, ElementEvent e) - { - //if (playing) - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_pause_pressed; - //} - //else - //{ - // Preview.Image = global::TerraViewer.Properties.Resources.button_play_pressed; - //} - } - //Bitmap menuArrow = global::TerraViewer.Properties.Resources.menuArrow; - - //public void AddShape_Paint(object sender, PaintEventArgs e) - //{ - //// e.Graphics.DrawImageUnscaled(menuArrow, new Point((AddShape.Width / 2) - (menuArrow.Width / 2), (AddShape.Height - menuArrow.Height) - 2)); - //} - - public void tourStopList_ItemHover(object sender, TourStop e) - { - //if (e != null) - //{ - // toolTip.SetToolTip(tourStopList, e.Description); - //} - //else - //{ - // toolTip.SetToolTip(tourStopList, Language.GetLocalizedText(451, "Slide List")); - //} - - } - - //public void TourEditTab_FormClosed(object sender, FormClosedEventArgs e) - //{ - // TourPlayer.Playing = false; - // TourPlayer.TourEnded -= new EventHandler(TourPlayer_TourEnded); - //} - - - - //public void ShowSafeArea_CheckedChanged(object sender, EventArgs e) - //{ - // Properties.Settings.Default.ShowSafeArea = ShowSafeArea.Checked; - //} - - public void Refresh() - { - - } - - public void UndoStep() - { - if (Undo.PeekAction()) - { - Undo.StepBack(); - tourStopList.Refresh(); - tourStopList.SelectedItem = tour.CurrentTourstopIndex; - ShowSlideStartPosition(tour.CurrentTourStop); - this.Refresh(); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, TourEditorUI.Selection); - } - } - - public void RedoStep() - { - if (Undo.PeekRedoAction()) - { - Undo.StepForward(); - tourStopList.Refresh(); - tourStopList.SelectedItem = tour.CurrentTourstopIndex; - ShowSlideStartPosition(tour.CurrentTourStop); - this.Refresh(); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, TourEditorUI.Selection); - } - } - - public void tourStopList_ShowEndPosition(object sender, TourStop e) - { - showEndSkyPosition_Click(this, new EventArgs()); - } - - public void tourStopList_ShowStartPosition(object sender, TourStop e) - { - ShowSlideStartPosition(Tour.CurrentTourStop); - TourEditorUI.ClearSelection(); - } - - //public void Dome_CheckedChanged(object sender, EventArgs e) - //{ - // Undo.Push(new UndoTourPropertiesChange(Language.GetLocalizedText(549, "Properties Edit"), Tour)); - // Tour.DomeMode = Dome.Checked; - // Overlay.DefaultAnchor = OverlayAnchor.Screen; - //} - - public void tourStopList_KeyDown(object sender, ElementEvent e) - { - if (e.CtrlKey) - { - switch ((Keys)e.KeyCode) - { - case Keys.C: - copyMenu_Click(null, new EventArgs()); - break; - case Keys.V: - pasteMenu_Click(null, new EventArgs()); - - break; - case Keys.X: - cutMenu_Click(null, new EventArgs()); - break; - - case Keys.Z: - if (Undo.PeekAction()) - { - TourEdit.UndoStep(); - } - else - { - UiTools.Beep(); - } - break; - case Keys.Y: - - if (Undo.PeekRedoAction()) - { - TourEdit.RedoStep(); - } - else - { - UiTools.Beep(); - } - - break; - } - } - - if ((Keys)e.KeyCode == Keys.DeleteKey) - { - deleteMenu_Click(null, new EventArgs()); - } - } - - internal void EnsureSelectedVisible() - { - tourStopList.EnsureSelectedVisible(); - } - - - } -} diff --git a/engine/csharp_ref/Tours/TourEditor.cs b/engine/csharp_ref/Tours/TourEditor.cs deleted file mode 100644 index 418098eb..00000000 --- a/engine/csharp_ref/Tours/TourEditor.cs +++ /dev/null @@ -1,2365 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class TourEditor : IUiController - { - public TourEditor() - { - } - - public Selection Selection = new Selection(); - - - - ContextMenuStrip contextMenu = new ContextMenuStrip(); - - public static bool Capturing = false; - - //public static bool Scrubbing = false; - //public static bool ScrubbingBackwards = false; - //public static Date ScrubStartTime = Date.Now; - - public static IUiController CurrentEditor = null; - - //public void PreRender(RenderContext renderContext) - //{ - // if (tour.CurrentTourStop != null) - // { - // //if (Scrubbing) - // //{ - // // Settings.TourSettings = tour.CurrentTourStop; - // // TimeSpan slideElapsedTime = SpaceTimeController.Now - ScrubStartTime; - - // // if (ScrubbingBackwards) - // // { - // // if (slideElapsedTime > tour.CurrentTourStop.Duration) - // // { - // // Scrubbing = false; - // // tour.CurrentTourStop.TweenPosition = 0.0f; - // // } - // // else - // // { - // // tour.CurrentTourStop.TweenPosition = Math.Min(1, 1 - (double)(slideElapsedTime.TotalMilliseconds / tour.CurrentTourStop.Duration.TotalMilliseconds)); - // // TimeLine.RefreshUi(); - // // } - // // } - // // else - // // { - // // if (slideElapsedTime > tour.CurrentTourStop.Duration) - // // { - // // Scrubbing = false; - // // tour.CurrentTourStop.TweenPosition = 1.0f; - // // } - // // else - // // { - // // tour.CurrentTourStop.TweenPosition = (double)(slideElapsedTime.TotalMilliseconds / tour.CurrentTourStop.Duration.TotalMilliseconds); - // // TimeLine.RefreshUi(); - // // } - // // } - // //} - // //else - // //{ - // if (CurrentEditor != null) - // { - // CurrentEditor.PreRender(renderContext); - // } - // //} - // } - //} - - //public void StartScrubbing(bool reverse) - //{ - // if (tour.CurrentTourStop != null) - // { - // Scrubbing = true; - // ScrubbingBackwards = reverse; - - // if (ScrubbingBackwards) - // { - // if (tour.CurrentTourStop.TweenPosition == 0) - // { - // tour.CurrentTourStop.TweenPosition = 1.0f; - // } - // ScrubStartTime = SpaceTimeController.Now - TimeSpan.FromSeconds(tour.CurrentTourStop.Duration.TotalSeconds * (1 - tour.CurrentTourStop.TweenPosition)); - // } - // else - // { - // if (tour.CurrentTourStop.TweenPosition == 1.0f) - // { - // tour.CurrentTourStop.TweenPosition = 0; - // } - // ScrubStartTime = SpaceTimeController.Now - TimeSpan.FromSeconds(tour.CurrentTourStop.Duration.TotalSeconds * (tour.CurrentTourStop.TweenPosition)); - // } - // } - //} - - - //internal void PauseScrubbing(bool p) - //{ - // if (Scrubbing) - // { - // Scrubbing = false; - // } - // else - // { - // StartScrubbing(ScrubbingBackwards); - // } - //} - - public void Render(RenderContext renderContext) - { - renderContext.SetupMatricesOverlays(); - //window.RenderContext11.DepthStencilMode = DepthStencilMode.Off; - - - if (tour == null || tour.CurrentTourStop == null) - { - //if (Settings.GlobalSettings.ShowSafeArea && tour != null && tour.EditMode && !Capturing) - //{ - // DrawSafeZone(window); - //} - return; - } - - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - if (overlay.Animate && Tour.CurrentTourStop.KeyFramed) - { - overlay.TweenFactor = tour.CurrentTourStop.TweenPosition; - } - else if (!Tour.CurrentTourStop.KeyFramed) - { - overlay.TweenFactor = tour.CurrentTourStop.TweenPosition < .5f ? 0f : 1f; - } - overlay.Draw3D(renderContext, true); - } - - //if (Properties.Settings.Default.ShowSafeArea && tour != null && tour.EditMode && !Capturing) - //{ - // DrawSafeZone(window); - //} - Selection.Draw3D(renderContext, 1.0f); - - //if (!Scrubbing) - { - if (CurrentEditor != null) - { - CurrentEditor.Render(renderContext); - } - - Settings.TourSettings = null; - } - } - - //private void DrawSafeZone(Earth3d window) - //{ - // Rectangle rect = window.RenderWindow.ClientRectangle; - - // int x = rect.Width / 2; - // int y = rect.Height / 2; - - // int ratioWidth = rect.Height * 4 / 3; - // int halfWidth = (rect.Width - ratioWidth) / 2; - - - // DrawTranparentBox(window.RenderContext11, new Rectangle(-x, -y, halfWidth, rect.Height)); - // DrawTranparentBox(window.RenderContext11, new Rectangle((rect.Width - halfWidth) - x, -y, halfWidth, rect.Height)); - //} - - //PositionColoredTextured[] boxPoints = new PositionColoredTextured[4]; - //private void DrawTranparentBox(RenderContext11 renderContext, Rectangle rect) - //{ - - - // Color Color = Color.FromArgb(128, 32, 32, 128); - // boxPoints[0].X = rect.X; - // boxPoints[0].Y = rect.Y; - // boxPoints[0].Z = .9f; - // boxPoints[0].W = 1; - // boxPoints[0].Tu = 0; - // boxPoints[0].Tv = 0; - // boxPoints[0].Color = Color; - - // boxPoints[1].X = (double)(rect.X + (rect.Width)); - // boxPoints[1].Y = (double)(rect.Y); - // boxPoints[1].Tu = 1; - // boxPoints[1].Tv = 0; - // boxPoints[1].Color = Color; - // boxPoints[1].Z = .9f; - // boxPoints[1].W = 1; - - // boxPoints[2].X = (double)(rect.X); - // boxPoints[2].Y = (double)(rect.Y + (rect.Height)); - // boxPoints[2].Tu = 0; - // boxPoints[2].Tv = 1; - // boxPoints[2].Color = Color; - // boxPoints[2].Z = .9f; - // boxPoints[2].W = 1; - - // boxPoints[3].X = (double)(rect.X + (rect.Width)); - // boxPoints[3].Y = (double)(rect.Y + (rect.Height)); - // boxPoints[3].Tu = 1; - // boxPoints[3].Tv = 1; - // boxPoints[3].Color = Color; - // boxPoints[3].Z = .9f; - // boxPoints[3].W = 1; - - // SharpDX.Matrix mat = SharpDX.Matrix.OrthoLH(renderContext.ViewPort.Width, renderContext.ViewPort.Height, 1, -1); - - // Sprite2d.Draw(renderContext, boxPoints, 4, mat, true); - - //} - - TourDocument tour = null; - - public TourDocument Tour - { - get { return tour; } - set { tour = value; } - } - - public void Close() - { - if (tour != null) - { - // todo check for changes - tour = null; - Focus = null; - } - } - - public void ClearSelection() - { - Selection.ClearSelection(); - - - OverlayList.UpdateOverlayListSelection(Selection); - Focus = null; - } - - bool mouseDown = false; - - - - public Overlay Focus - { - get { return Selection.Focus; } - set { Selection.Focus = value; } - } - - Vector2d pointDown; - - - public Vector2d PointToView(Vector2d pnt) - { - double clientHeight = WWTControl.Singleton.RenderContext.Height; - double clientWidth = WWTControl.Singleton.RenderContext.Width; - double viewWidth = (WWTControl.Singleton.RenderContext.Width / WWTControl.Singleton.RenderContext.Height) * 1116f; - double x = (((double)pnt.X) / ((double)clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - double y = ((double)pnt.Y) / clientHeight * 1116; - - return Vector2d.Create(x, y); - } - - SelectionAnchor selectionAction = SelectionAnchor.None; - bool needUndoFrame = false; - public bool MouseDown(object sender, ElementEvent e) - { - brokeThreshold = false; - needUndoFrame = true; - Vector2d location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - - if (tour == null || tour.CurrentTourStop == null) - { - needUndoFrame = false; - return false; - } - - if (CurrentEditor != null) - { - if (CurrentEditor.MouseDown(sender, e)) - { - return true; - } - } - - - // if (e.Button == MouseButtons.Left) - { - if (Focus != null) - { - if (Selection.MultiSelect) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - if (overlay.HitTest(location)) - { - selectionAction = SelectionAnchor.Move; - mouseDown = true; - pointDown = location; - Focus = overlay; - if (e.CtrlKey) - { - dragCopying = true; - } - - return true; - } - } - } - else - { - if (Focus.HitTest(location)) - { - selectionAction = SelectionAnchor.Move; - mouseDown = true; - pointDown = location; - - if (e.CtrlKey) - { - dragCopying = true; - } - - return true; - } - } - - SelectionAnchor hit = Selection.HitTest(location); - if (hit != SelectionAnchor.None) - { - selectionAction = hit; - mouseDown = true; - if (hit == SelectionAnchor.Rotate) - { - pointDown = location; - } - else - { - pointDown = Selection.PointToSelectionSpace(location); - } - return true; - } - } - - for (int i = tour.CurrentTourStop.Overlays.Count - 1; i >= 0; i--) - { - if (tour.CurrentTourStop.Overlays[i].HitTest(location)) - { - selectionAction = SelectionAnchor.Move; - Focus = tour.CurrentTourStop.Overlays[i]; - if (e.CtrlKey || e.ShiftKey) - { - Selection.AddSelection(Focus); - } - else - { - Selection.SetSelection(Focus); - } - - OverlayList.UpdateOverlayListSelection(Selection); - mouseDown = true; - pointDown = location; - return true; - } - } - Focus = null; - ClearSelection(); - - } - needUndoFrame = false; - return false; - - } - Vector2d contextPoint = new Vector2d(); - public bool MouseUp(object sender, ElementEvent e) - { - brokeThreshold = false; - if (CurrentEditor != null) - { - if (CurrentEditor.MouseUp(sender, e)) - { - return true; - } - } - - contextPoint = Vector2d.Create(e.OffsetX, e.OffsetY); - if (mouseDown) - { - mouseDown = false; - if (e.Button == 2) - { - if (Focus != null) - { - ShowSelectionContextMenu(Vector2d.Create(e.OffsetX, e.OffsetY)); - } - } - return true; - } - - if (e.Button == 2) - { - if (Focus == null) - { - ShowNoSelectionContextMenu(Vector2d.Create(e.OffsetX, e.OffsetY)); - } - return true; - } - return false; - } - - bool dragCopying = false; - bool brokeThreshold = false; - public bool MouseMove(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.MouseMove(sender, e)) - { - return true; - } - } - - - Vector2d location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - - if (mouseDown && Focus != null) - { - UndoTourStopChange undoFrame = null; - //todo localize - string actionText = Language.GetLocalizedText(502, "Edit"); - if (needUndoFrame) - { - undoFrame = new UndoTourStopChange(Language.GetLocalizedText(502, "Edit"), tour); - } - - double moveX; - double moveY; - if (selectionAction != SelectionAnchor.Move && selectionAction != SelectionAnchor.Rotate) - { - Vector2d newPoint = Selection.PointToSelectionSpace(location); - moveX = newPoint.X - pointDown.X; - moveY = newPoint.Y - pointDown.Y; - pointDown = newPoint; - } - else - { - moveX = location.X - pointDown.X; - moveY = location.Y - pointDown.Y; - if (selectionAction == SelectionAnchor.Move && !brokeThreshold) - { - if (Math.Abs(moveX) > 3 || Math.Abs(moveY) > 3) - { - brokeThreshold = true; - } - else - { - return true; - } - } - - - pointDown = location; - - } - - if (dragCopying) - { - - if (Selection.MultiSelect) - { - Overlay[] set = Selection.SelectionSet; - - ClearSelection(); - foreach (Overlay overlay in set) - { - Overlay newOverlay = AddOverlay(overlay); - newOverlay.X = overlay.X; - newOverlay.Y = overlay.Y; - Focus = newOverlay; - Selection.AddSelection(Focus); - - } - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - dragCopying = false; - } - else - { - Overlay newOverlay = AddOverlay(Focus); - newOverlay.X = Focus.X; - newOverlay.Y = Focus.Y; - Focus = newOverlay; - Selection.SetSelection(Focus); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - dragCopying = false; - } - } - - double aspect = Focus.Width / Focus.Height; - - Vector2d center = Vector2d.Create(Focus.X, Focus.Y); - if (e.CtrlKey) - { - actionText = Language.GetLocalizedText(537, "Resize"); - switch (selectionAction) - { - case SelectionAnchor.TopLeft: - Focus.Width = Math.Max(2, Focus.Width - moveX * 2); - Focus.Height = Math.Max(2, Focus.Height - (moveX / aspect) * 2); - break; - case SelectionAnchor.Top: - Focus.Height = Math.Max(2, Focus.Height - moveY * 2); - break; - case SelectionAnchor.TopRight: - Focus.Width = Math.Max(2, Focus.Width + moveX * 2); - Focus.Height = Math.Max(2, Focus.Height + (moveX / aspect) * 2); - break; - case SelectionAnchor.Right: - Focus.Width = Math.Max(2, Focus.Width + moveX * 2); - break; - case SelectionAnchor.BottomRight: - Focus.Width = Math.Max(2, Focus.Width + moveX * 2); - Focus.Height = Math.Max(2, Focus.Height + (moveX / aspect) * 2); - break; - case SelectionAnchor.Bottom: - Focus.Height = Math.Max(2, Focus.Height + moveY * 2); - break; - case SelectionAnchor.BottomLeft: - Focus.Width = Math.Max(2, Focus.Width - moveX * 2); - Focus.Height = Math.Max(2, Focus.Height - (moveX / aspect) * 2); - break; - case SelectionAnchor.Left: - Focus.Width = Math.Max(2, Focus.Width - moveX * 2); - break; - case SelectionAnchor.Rotate: - actionText = Language.GetLocalizedText(538, "Rotate"); - Focus.RotationAngle = Focus.RotationAngle + moveX / 10; - break; - case SelectionAnchor.Move: - actionText = Language.GetLocalizedText(539, "Drag Copy"); - center.X += moveX; - center.Y += moveY; - break; - case SelectionAnchor.Center: - break; - case SelectionAnchor.None: - break; - default: - break; - } - } - else - { - if (selectionAction != SelectionAnchor.Rotate && selectionAction != SelectionAnchor.Move) - { - if (moveX > (Focus.Width - 2)) - { - moveX = 0; - } - - if (moveY > (Focus.Height - 2)) - { - moveY = 0; - } - } - - //todo localize - actionText = Language.GetLocalizedText(537, "Resize"); - switch (selectionAction) - { - case SelectionAnchor.TopLeft: - Focus.Width -= moveX; - Focus.Height -= (moveX / aspect); - center.X += (moveX / 2); - center.Y += ((moveX / aspect) / 2); - break; - case SelectionAnchor.Top: - Focus.Height -= moveY; - center.Y += (moveY / 2); - break; - case SelectionAnchor.TopRight: - Focus.Width += moveX; - Focus.Height += (moveX / aspect); - center.X += (moveX / 2); - center.Y -= ((moveX / aspect) / 2); - break; - case SelectionAnchor.Right: - Focus.Width += moveX; - center.X += (moveX / 2); - break; - case SelectionAnchor.BottomRight: - Focus.Width += moveX; - Focus.Height += (moveX / aspect); - center.X += (moveX / 2); - center.Y += ((moveX / aspect) / 2); - break; - case SelectionAnchor.Bottom: - Focus.Height += moveY; - center.Y += (moveY / 2); - break; - case SelectionAnchor.BottomLeft: - Focus.Width -= moveX; - Focus.Height -= (moveX / aspect); - center.X += (moveX / 2); - center.Y -= ((moveX / aspect) / 2); - break; - case SelectionAnchor.Left: - Focus.Width -= moveX; - center.X += (moveX / 2); - break; - case SelectionAnchor.Rotate: - actionText = Language.GetLocalizedText(538, "Rotate"); - Focus.RotationAngle = Focus.RotationAngle + moveX; - break; - case SelectionAnchor.Move: - actionText = Language.GetLocalizedText(540, "Move"); - center.X += moveX; - center.Y += moveY; - break; - case SelectionAnchor.Center: - break; - case SelectionAnchor.None: - break; - default: - break; - } - } - - - if (selectionAction != SelectionAnchor.Move && selectionAction != SelectionAnchor.Rotate) - { - center = Selection.PointToScreenSpace(center); - } - - if (Selection.MultiSelect) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.X += moveX; - overlay.Y += moveY; - } - } - - else - { - Focus.X = center.X; - Focus.Y = center.Y; - } - - if (needUndoFrame) - { - needUndoFrame = false; - undoFrame.ActionText = actionText; - Undo.Push(undoFrame); - } - } - else - { - if (Focus != null) - { - if (Focus.HitTest(location)) - { - Cursor.Current = Cursors.SizeAll; - return false; - } - - SelectionAnchor hit = Selection.HitTest(location); - if (hit == SelectionAnchor.None) - { - return false; - } - - switch (hit) - { - case SelectionAnchor.TopLeft: - Cursor.Current = Cursors.SizeNWSE; - break; - case SelectionAnchor.Top: - Cursor.Current = Cursors.SizeNS; - break; - case SelectionAnchor.TopRight: - Cursor.Current = Cursors.SizeNESW; - break; - case SelectionAnchor.Right: - Cursor.Current = Cursors.SizeWE; - break; - case SelectionAnchor.BottomRight: - Cursor.Current = Cursors.SizeNWSE; - break; - case SelectionAnchor.Bottom: - Cursor.Current = Cursors.SizeNS; - break; - case SelectionAnchor.BottomLeft: - Cursor.Current = Cursors.SizeNESW; - break; - case SelectionAnchor.Left: - Cursor.Current = Cursors.SizeWE; - break; - case SelectionAnchor.Rotate: - Cursor.Current = Cursors.SizeWE; - break; - case SelectionAnchor.Center: - break; - case SelectionAnchor.None: - break; - default: - break; - } - - } - } - return false; - } - - private void ShowNoSelectionContextMenu(Vector2d position) - { - if (contextMenu != null) - { - contextMenu.Dispose(); - } - if (tour.CurrentTourStop == null) - { - return; - } - - contextMenu = new ContextMenuStrip(); - - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(425, "Paste")); - // IDataObject data = Clipboard.GetDataObject(); - - pasteMenu.Enabled = clipboardType == Overlay.ClipboardFormat; - - pasteMenu.Click =pasteMenu_Click; - contextMenu.Items.Add(pasteMenu); - // Hide these menu types. This was for early testing before the UI matching Windows was working - //ToolStripMenuItem AddCircle = ToolStripMenuItem.Create(Language.GetLocalizedText(444, "Circle")); - //ToolStripMenuItem AddRectangle = ToolStripMenuItem.Create(Language.GetLocalizedText(445, "Rectangle")); - //ToolStripMenuItem AddOpenRectangle = ToolStripMenuItem.Create(Language.GetLocalizedText(446, "Open Rectangle")); - //ToolStripMenuItem AddRing = ToolStripMenuItem.Create(Language.GetLocalizedText(447, "Ring")); - //ToolStripMenuItem AddLine = ToolStripMenuItem.Create(Language.GetLocalizedText(448, "Line")); - //ToolStripMenuItem AddArrow = ToolStripMenuItem.Create(Language.GetLocalizedText(449, "Arrow")); - //ToolStripMenuItem AddStar = ToolStripMenuItem.Create(Language.GetLocalizedText(450, "Star")); - - //AddCircle.Click = InsertShapeCircle_Click; - //AddRectangle.Click = InsertShapeRectangle_Click; - //AddOpenRectangle.Click = AddOpenRectangle_Click; - //AddRing.Click = insertDonut_Click; - //AddLine.Click = InsertShapeLine_Click; - //AddArrow.Click = AddArrow_Click; - //AddStar.Click = AddStar_Click; - - - //contextMenu.Items.Add(AddCircle); - //contextMenu.Items.Add(AddRectangle); - //contextMenu.Items.Add(AddOpenRectangle); - //contextMenu.Items.Add(AddRing); - //contextMenu.Items.Add(AddLine); - //contextMenu.Items.Add(AddArrow); - //contextMenu.Items.Add(AddStar); - contextMenu.Show(position); - } - - void AddOpenRectangle_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.OpenRectagle); - } - - void AddStar_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Star); - - } - - private void InsertShapeCircle_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Circle); - - } - - private void InsertShapeRectangle_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Rectagle); - - } - - private void InsertShapeLine_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Line); - - } - - private void insertDonut_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Donut); - - } - - - void AddArrow_Click(object sender, EventArgs e) - { - AddShape("", ShapeType.Arrow); - - } - - public void ShowSelectionContextMenu( Vector2d position) - { - if (Focus == null) - { - return; - } - - bool multiSelect = Selection.MultiSelect; - - if (contextMenu != null) - { - contextMenu.Dispose(); - } - - contextMenu = new ContextMenuStrip(); - - ToolStripMenuItem cutMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(427, "Cut")); - ToolStripMenuItem copyMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(428, "Copy")); - ToolStripMenuItem pasteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(425, "Paste")); - ToolStripMenuItem deleteMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(167, "Delete")); - ToolStripSeparator sep1 = new ToolStripSeparator(); - ToolStripSeparator sep2 = new ToolStripSeparator(); - ToolStripSeparator sep3 = new ToolStripSeparator(); - ToolStripMenuItem bringToFront = ToolStripMenuItem.Create(Language.GetLocalizedText(452, "Bring to Front")); - ToolStripMenuItem sendToBack = ToolStripMenuItem.Create(Language.GetLocalizedText(453, "Send to Back")); - ToolStripMenuItem bringForward = ToolStripMenuItem.Create(Language.GetLocalizedText(454, "Bring Forward")); - ToolStripMenuItem sendBackward = ToolStripMenuItem.Create(Language.GetLocalizedText(455, "Send Backward")); - ToolStripMenuItem properties = ToolStripMenuItem.Create(Language.GetLocalizedText(20, "Properties")); - ToolStripMenuItem editText = ToolStripMenuItem.Create(Language.GetLocalizedText(502, "Edit")); - //ToolStripMenuItem fullDome = new ToolStripMenuItem(Language.GetLocalizedText(574, "Full Dome")); - ToolStripMenuItem url = ToolStripMenuItem.Create(Language.GetLocalizedText(587, "Hyperlink")); - string linkString = Focus.LinkID; - switch (Focus.LinkID) - { - case "": - case null: - //linkString = " (No Link)"; - linkString = " (" + Language.GetLocalizedText(609, "No Link") + ")"; - break; - case "Next": - //linkString = " (Next Slide)"; - linkString = " (" + Language.GetLocalizedText(610, "Next Slide") + ")"; - break; - case "Return": - //linkString = " (Return to Caller)"; - linkString = " (" + Language.GetLocalizedText(602, "Return to Caller") + ")"; - break; - default: - int index = Tour.GetTourStopIndexByID(Focus.LinkID); - if (index > -1) - { - if (String.IsNullOrEmpty(tour.TourStops[index].Description)) - { - linkString = String.Format(" (" + Language.GetLocalizedText(1340, "Slide") + " {0})", index); - } - else - { - linkString = " (" + tour.TourStops[index].Description + ")"; - } - } - break; - } - - ToolStripMenuItem animateMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(588, "Animate")); - // ToolStripMenuItem addKeyframes = new ToolStripMenuItem(Language.GetLocalizedText(1280, "Add Keyframe")); - // ToolStripMenuItem addToTimeline = new ToolStripMenuItem(Language.GetLocalizedText(1290, "Add to Timeline")); - - ToolStripMenuItem linkID = ToolStripMenuItem.Create(Language.GetLocalizedText(589, "Link to Slide") + linkString); - ToolStripMenuItem pickColor = ToolStripMenuItem.Create(Language.GetLocalizedText(458, "Color/Opacity")); - ToolStripMenuItem flipbookProperties = ToolStripMenuItem.Create(Language.GetLocalizedText(630, "Flipbook Properties")); - ToolStripMenuItem interpolateMenu = ToolStripMenuItem.Create(Language.GetLocalizedText(1029, "Animation Tween Type")); - - ToolStripMenuItem Linear = ToolStripMenuItem.Create(Language.GetLocalizedText(1030, "Linear")); - ToolStripMenuItem Ease = ToolStripMenuItem.Create(Language.GetLocalizedText(1031, "Ease In/Out")); - ToolStripMenuItem EaseIn = ToolStripMenuItem.Create(Language.GetLocalizedText(1032, "Ease In")); - ToolStripMenuItem EaseOut = ToolStripMenuItem.Create(Language.GetLocalizedText(1033, "Ease Out")); - ToolStripMenuItem Exponential = ToolStripMenuItem.Create(Language.GetLocalizedText(1034, "Exponential")); - ToolStripMenuItem Default = ToolStripMenuItem.Create(Language.GetLocalizedText(1035, "Slide Default")); - - ToolStripMenuItem Align = ToolStripMenuItem.Create(Language.GetLocalizedText(790, "Align")); - ToolStripMenuItem AlignTop = ToolStripMenuItem.Create(Language.GetLocalizedText(1333, "Top")); - ToolStripMenuItem AlignBottom = ToolStripMenuItem.Create(Language.GetLocalizedText(1334, "Bottom")); - ToolStripMenuItem AlignLeft = ToolStripMenuItem.Create(Language.GetLocalizedText(1335, "Left")); - ToolStripMenuItem AlignRight = ToolStripMenuItem.Create(Language.GetLocalizedText(1336, "Right")); - ToolStripMenuItem AlignHorizon = ToolStripMenuItem.Create(Language.GetLocalizedText(1337, "Horizontal")); - ToolStripMenuItem AlignVertical = ToolStripMenuItem.Create(Language.GetLocalizedText(1338, "Vertical")); - ToolStripMenuItem AlignCenter = ToolStripMenuItem.Create(Language.GetLocalizedText(1339, "Centered")); - - Align.DropDownItems.Add(AlignTop); - Align.DropDownItems.Add(AlignBottom); - Align.DropDownItems.Add(AlignLeft); - Align.DropDownItems.Add(AlignRight); - Align.DropDownItems.Add(AlignHorizon); - Align.DropDownItems.Add(AlignVertical); - Align.DropDownItems.Add(AlignCenter); - - - - Linear.Tag = InterpolationType.Linear; - Ease.Tag = InterpolationType.EaseInOut; - EaseIn.Tag = InterpolationType.EaseIn; - EaseOut.Tag = InterpolationType.EaseOut; - Exponential.Tag = InterpolationType.Exponential; - Default.Tag = InterpolationType.DefaultV; - - Linear.Click = Interpolation_Click; - Ease.Click = Interpolation_Click; - EaseIn.Click = Interpolation_Click; - EaseOut.Click = Interpolation_Click; - Exponential.Click = Interpolation_Click; - Default.Click = Interpolation_Click; - - switch (Focus.InterpolationType) - { - case InterpolationType.Linear: - Linear.Checked = true; - break; - case InterpolationType.EaseIn: - EaseIn.Checked = true; - break; - case InterpolationType.EaseOut: - EaseOut.Checked = true; - break; - case InterpolationType.EaseInOut: - Ease.Checked = true; - break; - case InterpolationType.Exponential: - Exponential.Checked = true; - break; - case InterpolationType.DefaultV: - Default.Checked = true; - break; - default: - break; - } - - - interpolateMenu.DropDownItems.Add(Default); - interpolateMenu.DropDownItems.Add(Linear); - interpolateMenu.DropDownItems.Add(Ease); - interpolateMenu.DropDownItems.Add(EaseIn); - interpolateMenu.DropDownItems.Add(EaseOut); - interpolateMenu.DropDownItems.Add(Exponential); - - - - cutMenu.Click = cutMenu_Click; - copyMenu.Click = copyMenu_Click; - deleteMenu.Click = deleteMenu_Click; - bringToFront.Click = bringToFront_Click; - sendToBack.Click = sendToBack_Click; - sendBackward.Click = sendBackward_Click; - bringForward.Click = bringForward_Click; - properties.Click = properties_Click; - editText.Click = editText_Click; - url.Click = url_Click; - pickColor.Click = pickColor_Click; - pasteMenu.Click = pasteMenu_Click; - animateMenu.Click = animateMenu_Click; - - // addToTimeline.Click =addKeyframes_Click; - // addKeyframes.Click =addKeyframes_Click; - - //fullDome.Click =fullDome_Click; - flipbookProperties.Click = flipbookProperties_Click; - linkID.Click = linkID_Click; - - AlignTop.Click = AlignTop_Click; - AlignBottom.Click = AlignBottom_Click; - AlignLeft.Click = AlignLeft_Click; - AlignRight.Click = AlignRight_Click; - AlignHorizon.Click = AlignHorizon_Click; - AlignVertical.Click = AlignVertical_Click; - AlignCenter.Click = AlignCenter_Click; - - - - contextMenu.Items.Add(cutMenu); - contextMenu.Items.Add(copyMenu); - contextMenu.Items.Add(pasteMenu); - contextMenu.Items.Add(deleteMenu); - contextMenu.Items.Add(sep1); - contextMenu.Items.Add(bringToFront); - contextMenu.Items.Add(sendToBack); - contextMenu.Items.Add(bringForward); - contextMenu.Items.Add(sendBackward); - contextMenu.Items.Add(Align); - contextMenu.Items.Add(sep2); - - //IDataObject data = Clipboard.GetDataObject(); - - //pasteMenu.Enabled = Clipboard.ContainsImage() | Clipboard.ContainsText() | Clipboard.ContainsAudio() | data.GetDataPresent(Overlay.ClipboardFormat); - pasteMenu.Enabled = false; // until we can fix clipboard - contextMenu.Items.Add(pickColor); - contextMenu.Items.Add(url); - contextMenu.Items.Add(linkID); - contextMenu.Items.Add(animateMenu); - - //if (Focus.AnimationTarget == null) - //{ - // contextMenu.Items.Add(addToTimeline); - //} - //else - //{ - // contextMenu.Items.Add(addKeyframes); - //} - - - // contextMenu.Items.Add(fullDome); - contextMenu.Items.Add(sep3); - contextMenu.Items.Add(flipbookProperties); - animateMenu.Checked = Focus.Animate; - // fullDome.Checked = Focus.Anchor == OverlayAnchor.Dome; - contextMenu.Items.Add(interpolateMenu); - interpolateMenu.Enabled = Focus.Animate; - - flipbookProperties.Visible = (Focus is FlipbookOverlay); - sep3.Visible = (Focus is FlipbookOverlay); - - if (multiSelect) - { - url.Visible = false; - linkID.Visible = false; - properties.Visible = false; - flipbookProperties.Visible = false; - bringForward.Visible = false; - sendBackward.Visible = false; - } - else - { - Align.Visible = false; - } - - contextMenu.Items.Add(properties); - if (Focus != null) - { - if (Focus.GetType() == typeof(TextOverlay)) - { - contextMenu.Items.Add(editText); - } - } - - contextMenu.Show(position); - } - - void editText_Click(object sender, EventArgs e) - { - if (Focus != null) - { - if (Focus.GetType() == typeof(TextOverlay)) - { - EditText(); - } - } - } - - //void addKeyframes_Click(object sender, EventArgs e) - //{ - // if (Focus != null) - // { - // Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1280, "Add Keyframe"), tour)); - - // Tour.CurrentTourStop.KeyFramed = true; - - // foreach (Overlay overlay in selection.SelectionSet) - // { - - // if (overlay.AnimationTarget == null) - // { - // double savedTween = overlay.TweenFactor; - // overlay.TweenFactor = 0; - // overlay.AnimationTarget = new AnimationTarget(Tour.CurrentTourStop); - // overlay.AnimationTarget.Target = overlay; - // overlay.AnimationTarget.ParameterNames.AddRange(overlay.GetParamNames()); - // overlay.AnimationTarget.CurrentParameters = overlay.GetParams(); - // overlay.AnimationTarget.SetKeyFrame(0, Key.KeyType.Linear); - // if (overlay.Animate) - // { - // overlay.TweenFactor = 1; - // overlay.AnimationTarget.CurrentParameters = overlay.GetParams(); - // overlay.AnimationTarget.SetKeyFrame(1, Key.KeyType.Linear); - // overlay.TweenFactor = savedTween; - // overlay.Animate = false; - // } - - // Tour.CurrentTourStop.AnimationTargets.Add(overlay.AnimationTarget); - // TimeLine.RefreshUi(); - // } - // else - // { - // overlay.AnimationTarget.SetKeyFrame(Tour.CurrentTourStop.TweenPosition, Key.KeyType.Linear); - // } - // } - // TimeLine.RefreshUi(); - // } - //} - - //void fullDome_Click(object sender, EventArgs e) - //{ - // Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1341, "Anchor Full Dome"), tour)); - // if (Focus != null) - // { - // bool fullDome = Focus.Anchor != OverlayAnchor.Dome; - - // foreach (Overlay overlay in selection.SelectionSet) - // { - // overlay.Anchor = fullDome ? OverlayAnchor.Dome : OverlayAnchor.Screen; - // } - // } - //} - - void AlignVertical_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1036, "Vertical Align"), tour)); - - double xCenter = Focus.X; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.X = xCenter; - } - } - - void AlignHorizon_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1037, "Horizontal Align"), tour)); - - double yCenter = Focus.Y; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Y = yCenter; - } - } - - void AlignCenter_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1038, "Align Centers"), tour)); - - double yCenter = Focus.Y; - double xCenter = Focus.X; - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Y = yCenter; - overlay.X = xCenter; - } - } - - void AlignRight_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1040, "Align Right"), tour)); - - double left = Focus.X + Focus.Width / 2; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.X = left - overlay.Width / 2; - } - } - - void AlignLeft_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1041, "Align Left"), tour)); - - double right = Focus.X - Focus.Width / 2; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.X = right + overlay.Width / 2; - } - - } - - void AlignBottom_Click(object sender, EventArgs e) - { - - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1042, "Align Bottoms"), tour)); - - double top = Focus.Y + Focus.Height / 2; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Y = top - overlay.Height / 2; - } - - } - - void AlignTop_Click(object sender, EventArgs e) - { - if (Focus == null) - { - return; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1039, "Align Tops"), tour)); - - double top = Focus.Y - Focus.Height / 2; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Y = top + overlay.Height / 2; - } - } - - void Interpolation_Click(object sender, EventArgs e) - { - ToolStripMenuItem item = (ToolStripMenuItem)sender; - if (Focus != null) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.InterpolationType = (InterpolationType)item.Tag; - } - } - } - - public SetNextSlideDelegate nextSlideCallback = null; - private void LinkSlideChosen() - { - - if (selectDialog.OK) - { - Focus.LinkID = selectDialog.ID; - } - } - public SelectLink selectDialog; - private void linkID_Click(object sender, EventArgs e) - { - this.selectDialog = new SelectLink(Focus.LinkID); - - nextSlideCallback(selectDialog, LinkSlideChosen); - } - - void flipbookProperties_Click(object sender, EventArgs e) - { - //FlipbookOverlay flipbook = (FlipbookOverlay)Focus; - //FlipbookSetup properties = new FlipbookSetup(); - - //properties.LoopType = flipbook.LoopType; - //properties.FramesY = flipbook.FramesY; - //properties.FramesX = flipbook.FramesX; - //properties.FrameSequence = flipbook.FrameSequence; - //properties.StartFrame = flipbook.StartFrame; - //properties.Frames = flipbook.Frames; - - //if (properties.ShowDialog() == DialogResult.OK) - //{ - // flipbook.LoopType = properties.LoopType; - // flipbook.FramesY = properties.FramesY; - // flipbook.FramesX = properties.FramesX; - // flipbook.FrameSequence = properties.FrameSequence; - // flipbook.StartFrame = properties.StartFrame; - // flipbook.Frames = properties.Frames; - //} - } - - void animateMenu_Click(object sender, EventArgs e) - { - if (Focus != null) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(588, "Animate"), tour)); - - bool animate = !Focus.Animate; - - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Animate = animate; - } - - } - } - - void url_Click(object sender, EventArgs e) - { - if (Focus != null) - { - SimpleInput input = new SimpleInput(Language.GetLocalizedText(541, "Edit Hyperlink"), Language.GetLocalizedText(542, "Url"), Focus.Url, 2048); - - input.Show(Cursor.Position, delegate () - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(541, "Edit Hyperlink"), tour)); - Focus.Url = input.Text; - }); - } - } - - void pickColor_Click(object sender, EventArgs e) - { - ColorPicker picker = new ColorPicker(); - - //picker.Location = Cursor.Position; - - picker.Color = Focus.Color; - - // if (picker.ShowDialog() == DialogResult.OK) - - picker.CallBack = delegate - { - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(543, "Edit Color"), tour)); - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.Color = picker.Color; - } - }; - - picker.Show(e); - } - - void volume_Click(object sender, EventArgs e) - { - PopupVolume vol = new PopupVolume(); - vol.Volume = ((AudioOverlay)Focus).Volume; - vol.ShowDialog(); - ((AudioOverlay)Focus).Volume = vol.Volume; - } - - void deleteMenu_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(167, "Delete"), tour)); - - foreach (Overlay overlay in Selection.SelectionSet) - { - tour.CurrentTourStop.RemoveOverlay(overlay); - } - - Focus = null; - ClearSelection(); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void properties_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(549, "Properties Edit"), tour)); - OverlayProperties props = new OverlayProperties(); - props.Overlay = Focus; - - props.ShowDialog(); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void bringForward_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(454, "Bring Forward"), tour)); - foreach (Overlay overlay in GetSortedSelection(false)) - { - tour.CurrentTourStop.BringForward(overlay); - } - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void sendBackward_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(455, "Send Backward"), tour)); - foreach (Overlay overlay in GetSortedSelection(true)) - { - tour.CurrentTourStop.SendBackward(overlay); - } - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void sendToBack_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(453, "Send to Back"), tour)); - foreach (Overlay overlay in GetSortedSelection(true)) - { - tour.CurrentTourStop.SendToBack(overlay); - } - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void bringToFront_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(452, "Bring to Front"), tour)); - foreach (Overlay overlay in GetSortedSelection(false)) - { - tour.CurrentTourStop.BringToFront(overlay); - } - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - List GetSortedSelection(bool reverse) - { - List sorted = new List(); - - foreach (Overlay ov in Selection.SelectionSet) - { - sorted.Add(ov); - } - - - if (reverse) - { - sorted.Sort(delegate (Overlay p1, Overlay p2) { return -Util.Compare(p1.ZOrder, p2.ZOrder); }); - } - else - { - - sorted.Sort(delegate (Overlay p1, Overlay p2) { return Util.Compare(p1.ZOrder, p2.ZOrder); }); - } - return sorted; - } - - public string clipboardData = ""; - public string clipboardType = ""; - void copyMenu_Click(object sender, EventArgs e) - { - //todo impliment copy - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - - - XmlTextWriter writer = new XmlTextWriter(); - - writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - writer.WriteStartElement("Overlays"); - foreach (Overlay overlay in Selection.SelectionSet) - { - overlay.SaveToXml(writer, true); - } - - writer.WriteEndElement(); - - clipboardData = writer.Body; - clipboardType = Overlay.ClipboardFormat; - } - - void cutMenu_Click(object sender, EventArgs e) - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(427, "Cut"), tour)); - copyMenu_Click(sender, e); - - foreach (Overlay overlay in Selection.SelectionSet) - { - tour.CurrentTourStop.RemoveOverlay(overlay); - } - Focus = null; - ClearSelection(); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - void pasteMenu_Click(object sender, EventArgs e) - { - //todo impliment paste - - Undo.Push(new UndoTourSlidelistChange(Language.GetLocalizedText(544, "Paste Object"), tour)); - - - if (clipboardType == Overlay.ClipboardFormat) - { - - XmlDocumentParser xParser = new XmlDocumentParser(); - XmlDocument doc = xParser.ParseFromString(clipboardData, "text/xml"); - - - ClearSelection(); - - XmlNode parent = Util.SelectSingleNode(doc, "Overlays"); - foreach (XmlNode child in parent.ChildNodes) - { - if (child.Name == "Overlay") - { - Overlay copy = Overlay.FromXml(tour.CurrentTourStop, child); - //if (copy.AnimationTarget != null) - //{ - // copy.Id = Guid.NewGuid().ToString(); - // copy.AnimationTarget.TargetID = copy.Id; - // tour.CurrentTourStop.AnimationTargets.Add(copy.AnimationTarget); - //} - bool found = false; - double maxX = 0; - double maxY = 0; - foreach (Overlay item in tour.CurrentTourStop.Overlays) - { - if (item.Id == copy.Id && item.GetType() == copy.GetType()) - { - found = true; - if (maxY < item.Y || maxX < item.X) - { - maxX = item.X; - maxY = item.Y; - } - } - } - - if (found) - { - copy.X = maxX + 20; - copy.Y = maxY + 20; - } - - tour.CurrentTourStop.AddOverlay(copy); - Focus = copy; - Selection.AddSelection(Focus); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - } - } - //else if (UiTools.IsMetaFileAvailable()) - //{ - // Image img = UiTools.GetMetafileFromClipboard(); - // if (img != null) - // { - // BitmapOverlay bmp = new BitmapOverlay(tour.CurrentTourStop, img); - // tour.CurrentTourStop.AddOverlay(bmp); - // bmp.X = contextPoint.X; - // bmp.Y = contextPoint.Y; - // Focus = bmp; - // selection.SetSelection(Focus); - // OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - // } - //} - //else if (Clipboard.ContainsText() && Clipboard.GetText().Length > 0) - //{ - // TextObject temp = TextEditor.DefaultTextobject; - // temp.Text = Clipboard.GetText(); - - // TextOverlay text = new TextOverlay(temp); - // //text.X = Earth3d.MainWindow.ClientRectangle.Width / 2; - // //text.Y = Earth3d.MainWindow.ClientRectangle.Height / 2; - // text.X = contextPoint.X; - // text.Y = contextPoint.Y; - // tour.CurrentTourStop.AddOverlay(text); - // Focus = text; - // selection.SetSelection(Focus); - // OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - //} - //else if (Clipboard.ContainsImage()) - //{ - // Image img = Clipboard.GetImage(); - // BitmapOverlay bmp = new BitmapOverlay(tour.CurrentTourStop, img); - // tour.CurrentTourStop.AddOverlay(bmp); - // bmp.X = contextPoint.X; - // bmp.Y = contextPoint.Y; - // Focus = bmp; - // selection.SetSelection(Focus); - // OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - //} - - } - - public bool MouseClick(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.MouseClick(sender, e)) - { - return true; - } - } - return false; - } - - public bool Click(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.Click(sender, e)) - { - return true; - } - } - return false; - } - - public bool MouseDoubleClick(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.MouseDoubleClick(sender, e)) - { - return true; - } - } - - if (Focus != null) - { - if (Focus.GetType() == typeof(TextOverlay)) - { - EditText(); - return true; - } - } - return true; - } - - - - public TextEditorDelegate editTextCallback = null; - - private void DoneEditing() - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(545, "Text Edit"), tour)); - ((TextOverlay)Focus).Width = 0; - ((TextOverlay)Focus).Height = 0; - Focus.Color = ((TextOverlay)Focus).TextObject.ForegroundColor; - Focus.CleanUp(); - } - - private void EditText() - { - TextObject textObj = ((TextOverlay)Focus).TextObject; - editTextCallback(textObj, DoneEditing); - - //todo port Text Editor - //TextEditor te = new TextEditor(); - //te.TextObject = ((TextOverlay)Focus).TextObject; - //if (te.ShowDialog() == DialogResult.OK) - //{ - // //todo localize - // Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(545, "Text Edit"), tour)); - // ((TextOverlay)Focus).TextObject = te.TextObject; - // ((TextOverlay)Focus).Width = 0; - // ((TextOverlay)Focus).Height = 0; - // Focus.Color = te.TextObject.ForegroundColor; - // Focus.CleanUp(); - //} - } - - public bool KeyDown(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.KeyDown(sender, e)) - { - return true; - } - } - - int increment = 1; - if (e.CtrlKey) - { - increment = 10; - } - - switch ((Keys)e.KeyCode) - { - case Keys.A: - if (e.CtrlKey) - { - ClearSelection(); - Selection.AddSelectionRange(tour.CurrentTourStop.Overlays); - OverlayList.UpdateOverlayListSelection(Selection); - if (tour.CurrentTourStop.Overlays.Count > 0) - { - Focus = tour.CurrentTourStop.Overlays[0]; - } - } - break; - case Keys.Z: - if (e.CtrlKey) - { - if (Undo.PeekAction()) - { - TourEdit.UndoStep(); - } - else - { - UiTools.Beep(); - } - } - break; - case Keys.Y: - if (e.CtrlKey) - { - if (Undo.PeekRedoAction()) - { - TourEdit.RedoStep(); - } - else - { - UiTools.Beep(); - } - } - break; - case Keys.C: - if (e.CtrlKey) - { - this.copyMenu_Click(this, new EventArgs()); - } - break; - case Keys.V: - if (e.CtrlKey) - { - this.pasteMenu_Click(this, new EventArgs()); - } - break; - case Keys.X: - if (e.CtrlKey) - { - this.cutMenu_Click(this, new EventArgs()); - } - break; - case Keys.DeleteKey: - this.deleteMenu_Click(null, null); - return true; - case Keys.Tab: - if (e.ShiftKey) - { - SelectLast(); - } - else - { - SelectNext(); - } - return true; - case Keys.Left: - if (Focus != null) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - if (e.ShiftKey) - { - if (e.AltKey) - { - if (overlay.Width > increment) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - overlay.Width -= increment; - } - } - else - { - double aspect = overlay.Width / overlay.Height; - if (overlay.Width > increment && overlay.Height > (increment * aspect)) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - overlay.Width -= increment; - overlay.Height -= increment * aspect; - } - } - } - else if (e.AltKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(538, "Rotate"), tour)); - overlay.RotationAngle -= increment; - } - else - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(540, "Move"), tour)); - overlay.X -= increment; - } - } - return true; - } - break; - case Keys.Right: - if (Focus != null) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - if (e.ShiftKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - if (e.AltKey) - { - overlay.Width += increment; - - } - else - { - double aspect = overlay.Width / overlay.Height; - overlay.Width += increment; - overlay.Height += increment * aspect; - } - } - else if (e.AltKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(538, "Rotate"), tour)); - overlay.RotationAngle += increment; - } - else - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(540, "Move"), tour)); - overlay.X += increment; - } - } - return true; - } - break; - case Keys.Up: - if (Focus != null) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - if (e.ShiftKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - if (e.AltKey) - { - overlay.Height += increment; - } - else - { - double aspect = overlay.Width / overlay.Height; - overlay.Width += increment; - overlay.Height += increment * aspect; - } - } - else if (!e.AltKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(540, "Move"), tour)); - overlay.Y -= increment; - } - } - return true; - } - break; - case Keys.Down: - if (Focus != null) - { - foreach (Overlay overlay in Selection.SelectionSet) - { - if (e.ShiftKey) - { - if (e.AltKey) - { - if (overlay.Height > increment) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - overlay.Height -= increment; - } - } - else - { - double aspect = overlay.Width / overlay.Height; - if (overlay.Width > increment && overlay.Height > (increment * aspect)) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(537, "Resize"), tour)); - overlay.Width -= increment; - overlay.Height -= increment * aspect; - } - } - } - else if (!e.AltKey) - { - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(540, "Move"), tour)); - overlay.Y += increment; - } - } - return true; - } - break; - case Keys.PageDown: - // Next Slide - if (e.AltKey) - { - if (tour.CurrentTourstopIndex < (tour.TourStops.Count - 1)) - { - tour.CurrentTourstopIndex++; - TourEdit.SelectCurrent(); - TourEdit.EnsureSelectedVisible(); - } - return true; - } - - break; - case Keys.PageUp: - // Prev Slide - if (e.AltKey) - { - if (tour.CurrentTourstopIndex > 0) - { - tour.CurrentTourstopIndex--; - TourEdit.SelectCurrent(); - TourEdit.EnsureSelectedVisible(); - } - return true; - } - break; - } - return false; - } - - private void SelectNext() - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - - Focus = tour.CurrentTourStop.GetNextOverlay(Focus); - Selection.SetSelection(Focus); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - private void SelectLast() - { - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - - Focus = tour.CurrentTourStop.GetPerviousOverlay(Focus); - Selection.SetSelection(Focus); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - } - - public bool KeyUp(object sender, ElementEvent e) - { - if (CurrentEditor != null) - { - if (CurrentEditor.KeyUp(sender, e)) - { - return true; - } - } - return false; - } - - public bool AddPicture(System.Html.Data.Files.File file) - { - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(546, "Insert Picture"), tour)); - BitmapOverlay bmp = BitmapOverlay.Create(tour.CurrentTourStop, file); - bmp.X = 960; - bmp.Y = 600; - tour.CurrentTourStop.AddOverlay(bmp); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - return true; - } - - public bool AddFlipbook(string filename) - { - //if (tour == null || tour.CurrentTourStop == null) - //{ - // return false; - //} - - ////todo localize - - //FlipbookSetup flipSetup = new FlipbookSetup(); - - - //if (flipSetup.ShowDialog() == DialogResult.OK) - //{ - // Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(1342, "Insert Flipbook"), tour)); - // FlipbookOverlay flipbook = new FlipbookOverlay(tour.CurrentTourStop, filename); - // flipbook.X = 960; - // flipbook.Y = 600; - // flipbook.LoopType = flipSetup.LoopType; - // flipbook.FramesY = flipSetup.FramesY; - // flipbook.FramesX = flipSetup.FramesX; - // flipbook.FrameSequence = flipSetup.FrameSequence; - // flipbook.StartFrame = flipSetup.StartFrame; - // flipbook.Frames = flipSetup.Frames; - - // tour.CurrentTourStop.AddOverlay(flipbook); - // OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - // return true; - //} - return false; - } - - public bool AddAudio(System.Html.Data.Files.File file, bool music) - { - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - AudioOverlay audio = AudioOverlay.Create(tour.CurrentTourStop, file); - audio.X = 900; - audio.Y = 600; - - if (music) - { - tour.CurrentTourStop.MusicTrack = audio; - } - else - { - tour.CurrentTourStop.VoiceTrack = audio; - } - - return true; - } - - public bool AddVideo(string filename) - { - // depracted video type - //if (tour == null || tour.CurrentTourStop == null) - //{ - // return false; - //} - - //VideoClip video = new VideoClip(Earth3d.MainWindow.Device, tour.CurrentTourStop, filename); - //video.X = 960; - //video.Y = 600; - //tour.CurrentTourStop.AddOverlay(video); - return true; - - } - - public bool AddText(string p, TextObject textObject) - { - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - TextOverlay text = TextOverlay.Create(textObject); - text.Color = textObject.ForegroundColor; - text.X = 960; - text.Y = 600; - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(547, "Insert Text"), tour)); - tour.CurrentTourStop.AddOverlay(text); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - return true; - } - - public Overlay AddOverlay(Overlay ol) - { - if (tour == null || tour.CurrentTourStop == null) - { - return null; - } - if (ol.GetType() == typeof(ShapeOverlay)) - { - ShapeOverlay srcShapeOverlay = (ShapeOverlay)ol; - if (srcShapeOverlay != null) - { - ShapeOverlay shape = ShapeOverlay.Create(tour.CurrentTourStop, srcShapeOverlay.ShapeType); - shape.Width = srcShapeOverlay.Width; - shape.Height = srcShapeOverlay.Height; - shape.X = contextPoint.X; - shape.Y = contextPoint.Y; - shape.Color = srcShapeOverlay.Color; - shape.RotationAngle = srcShapeOverlay.RotationAngle; - //if (ol.AnimationTarget != null) - //{ - // shape.AnimationTarget = ol.AnimationTarget.Clone(shape); - //} - tour.CurrentTourStop.AddOverlay(shape); - return shape; - } - } - else if (ol.GetType() == typeof(TextOverlay)) - { - TextOverlay srcTxtOverlay = (TextOverlay)ol; - if (srcTxtOverlay != null) - { - TextOverlay text = TextOverlay.Create(srcTxtOverlay.TextObject); - text.X = contextPoint.X; - text.Y = contextPoint.Y; - text.Color = srcTxtOverlay.Color; - //if (ol.AnimationTarget != null) - //{ - // text.AnimationTarget = ol.AnimationTarget.Clone(text); - //} - tour.CurrentTourStop.AddOverlay(text); - return text; - } - } - else if (ol.GetType() == typeof(BitmapOverlay)) - { - BitmapOverlay srcBmpOverlay = (BitmapOverlay)ol; - if (srcBmpOverlay != null) - { - BitmapOverlay bitmap = srcBmpOverlay.Copy(tour.CurrentTourStop); - bitmap.X = contextPoint.X; - bitmap.Y = contextPoint.Y; - //if (ol.AnimationTarget != null) - //{ - // bitmap.AnimationTarget = ol.AnimationTarget.Clone(bitmap); - //} - tour.CurrentTourStop.AddOverlay(bitmap); - return bitmap; - } - } - else if (ol.GetType() == typeof(FlipbookOverlay)) - { - FlipbookOverlay srcFlipbookOverlay = (FlipbookOverlay)ol; - if (srcFlipbookOverlay != null) - { - FlipbookOverlay bitmap = srcFlipbookOverlay.Copy(tour.CurrentTourStop); - bitmap.X = contextPoint.X; - bitmap.Y = contextPoint.Y; - //if (ol.AnimationTarget != null) - //{ - // bitmap.AnimationTarget = ol.AnimationTarget.Clone(bitmap); - //} - tour.CurrentTourStop.AddOverlay(bitmap); - return bitmap; - } - } - return null; - } - - public bool AddShape(string p, ShapeType shapeType) - { - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - //todo localize - Undo.Push(new UndoTourStopChange(Language.GetLocalizedText(548, "Insert Shape"), tour)); - - ShapeOverlay shape = ShapeOverlay.Create(tour.CurrentTourStop, shapeType); - shape.Width = 200; - shape.Height = 200; - - if (shapeType == ShapeType.Arrow) - { - shape.Height /= 2; - } - if (shapeType == ShapeType.Line) - { - shape.Height = 12; - } - shape.X = 960; - shape.Y = 600; - tour.CurrentTourStop.AddOverlay(shape); - - Focus = shape; - Selection.SetSelection(Focus); - OverlayList.UpdateOverlayList(tour.CurrentTourStop, Selection); - return true; - } - Color defaultColor = Colors.White; - public Color GetCurrentColor() - { - if (tour == null || tour.CurrentTourStop == null) - { - return defaultColor; - } - if (Focus != null) - { - return Focus.Color; - } - else - { - return defaultColor; - } - } - - public void SetCurrentColor(Color color) - { - defaultColor = color; - if (tour == null || tour.CurrentTourStop == null) - { - return; - } - if (Focus != null) - { - Focus.Color = color; - } - } - - #region IDisposable Members - - public void Dispose() - { - if (contextMenu != null) - { - contextMenu.Dispose(); - contextMenu = null; - } - } - - #endregion - - - public bool Hover(Vector2d pnt) - { - if (CurrentEditor != null) - { - if (CurrentEditor.Hover(pnt)) - { - return true; - } - } - return true; - } - - } - public class OverlayList - { - internal static void UpdateOverlayList(TourStop currentTourStop, Selection selection) - { - } - - internal static void UpdateOverlayListSelection(Selection selection) - { - } - } - public class TourEdit - { - internal static void EnsureSelectedVisible() - { - } - - - - internal static void SelectCurrent() - { - } - internal static void UndoStep() - { - if (Undo.PeekAction()) - { - Undo.StepBack(); - //todo wire this up to web ui - //tourStopList.Refresh(); - //tourStopList.SelectedItem = tour.CurrentTourstopIndex; - //ShowSlideStartPosition(tour.CurrentTourStop); - //this.Refresh(); - // OverlayList.UpdateOverlayList(tour.CurrentTourStop, TourEditorUI.Selection); - } - } - - internal static void RedoStep() - { - if (Undo.PeekRedoAction()) - { - Undo.StepForward(); - - //tourStopList.Refresh(); - //tourStopList.SelectedItem = tour.CurrentTourstopIndex; - //ShowSlideStartPosition(tour.CurrentTourStop); - //this.Refresh(); - //OverlayList.UpdateOverlayList(tour.CurrentTourStop, TourEditorUI.Selection); - } - } - } - - public class SoundEditor - { - public TourStop Target = null; - } - - public class TourStopList - { - public TourDocument Tour = null; - public bool ShowAddButton = false; - - public Dictionary SelectedItems = null; - public int SelectedItem = -1; - public void SelectAll() - { - SelectedItems = new Dictionary(); - for (int i = 0; i < Tour.TourStops.Count; i++) - { - SelectedItems[i] = Tour.TourStops[i]; - } - } - public Action refreshCallback = null; - - public void Refresh() - { - if (refreshCallback != null) - { - refreshCallback(); - } - } - - - public bool MultipleSelection = false; - public bool HitType = false; - - public int FindItem(TourStop ts) - { - return -1; - } - public void EnsureSelectedVisible() - { - - } - public void EnsureAddVisible() - { - - } - } - - public class TimeLine - { - public static void RefreshUi() - { - - } - } - public delegate void TextEditorDelegate(TextObject item, Action done); - public delegate void SetNextSlideDelegate(SelectLink nextObj, Action done); - -} diff --git a/engine/csharp_ref/Tours/TourPlayer.cs b/engine/csharp_ref/Tours/TourPlayer.cs deleted file mode 100644 index b76572df..00000000 --- a/engine/csharp_ref/Tours/TourPlayer.cs +++ /dev/null @@ -1,848 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class TourPlayer : IUiController - { - public TourPlayer() - { - } - - BlendState overlayBlend = BlendState.Create(false, 1000); - - public void Render(RenderContext renderContext) - { - if (tour == null || tour.CurrentTourStop == null || !playing) - { - return; - } - - renderContext.Save(); - UpdateSlideStates(); - - if (!onTarget) - { - slideStartTime = Date.Now; - - if (renderContext.OnTarget(Tour.CurrentTourStop.Target)) - { - onTarget = true; - overlayBlend.State = !Tour.CurrentTourStop.FadeInOverlays; - overlayBlend.TargetState = true; - - if (tour.CurrentTourStop.MusicTrack != null) - { - tour.CurrentTourStop.MusicTrack.Seek(0); - tour.CurrentTourStop.MusicTrack.Play(); - } - - if (tour.CurrentTourStop.VoiceTrack != null) - { - tour.CurrentTourStop.VoiceTrack.Seek(0); - tour.CurrentTourStop.VoiceTrack.Play(); - } - - string caption = ""; - - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - if (overlay.Name.ToLowerCase() == "caption") - { - TextOverlay text = overlay as TextOverlay; - if (text != null) - { - caption = text.TextObject.Text; - } - } - overlay.Play(); - } - - LayerManager.SetVisibleLayerList(tour.CurrentTourStop.Layers); - - if (tour.CurrentTourStop.EndTarget != null && tour.CurrentTourStop.EndTarget.ZoomLevel != -1) - { - if (tour.CurrentTourStop.Target.Type == ImageSetType.SolarSystem) - { - // TODO fix this when Planets are implenented - //tour.CurrentTourStop.Target.UpdatePlanetLocation(SpaceTimeController.UtcToJulian(tour.CurrentTourStop.StartTime)); - //tour.CurrentTourStop.EndTarget.UpdatePlanetLocation(SpaceTimeController.UtcToJulian(tour.CurrentTourStop.EndTime)); - } - - renderContext.ViewMover = new ViewMoverKenBurnsStyle(tour.CurrentTourStop.Target.CamParams, tour.CurrentTourStop.EndTarget.CamParams, tour.CurrentTourStop.Duration / 1000.0, tour.CurrentTourStop.StartTime, tour.CurrentTourStop.EndTime, tour.CurrentTourStop.InterpolationType); - } - - Settings.TourSettings = tour.CurrentTourStop; - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - WWTControl.scriptInterface.FireSlideChanged(caption); - } - } - - if (renderContext.gl != null) - { - renderContext.SetupMatricesOverlays(); - - //todo Factor opacity in somehow ?? - //view.overlays.Opacity = overlayBlend.Opacity; - - if (currentMasterSlide != null) - { - foreach (Overlay overlay in currentMasterSlide.Overlays) - { - overlay.TweenFactor = 1f; - overlay.Draw3D(renderContext, false); - } - } - - if (onTarget) - { - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - if (overlay.Name.ToLowerCase() != "caption" || WWTControl.scriptInterface.ShowCaptions) - { - overlay.TweenFactor = (float)CameraParameters.EaseCurve( - tour.CurrentTourStop.TweenPosition, - overlay.InterpolationType == InterpolationType.DefaultV ? tour.CurrentTourStop.InterpolationType : overlay.InterpolationType - ); - overlay.Draw3D(renderContext, false); - } - } - } - - renderContext.Restore(); - - // There used to be code to draw on-screen tour player controls here. - // In the web engine, that kind of work is now taken care of at higher levels. - //DrawPlayerControls(renderContext); - } - else - { - renderContext.Device.Scale(renderContext.Height / 1116, renderContext.Height / 1116); - double aspectOrig = 1920 / 1116; - double aspectNow = renderContext.Width / renderContext.Height; - renderContext.Device.Translate(-((1920 - (aspectNow * 1116)) / 2), 0); - - //todo Factor opacity in somehow ?? - //view.overlays.Opacity = overlayBlend.Opacity; - - if (currentMasterSlide != null) - { - foreach (Overlay overlay in currentMasterSlide.Overlays) - { - overlay.TweenFactor = 1f; - overlay.Draw3D(renderContext, false); - } - } - - if (onTarget) - { - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - if (overlay.Name.ToLowerCase() != "caption" || WWTControl.scriptInterface.ShowCaptions) - { - overlay.TweenFactor = (float)CameraParameters.EaseCurve(tour.CurrentTourStop.TweenPosition, overlay.InterpolationType == InterpolationType.DefaultV ? tour.CurrentTourStop.InterpolationType : overlay.InterpolationType); - overlay.Draw3D(renderContext, false); - } - } - } - else - { - int i = 0; - } - renderContext.Restore(); - } - } - - TourDocument tour = null; - - public TourDocument Tour - { - get { return tour; } - set { tour = value; } - } - - static bool playing = false; - - static public bool Playing - { - get { return playing; } - set { playing = value; } - } - - bool onTarget = false; - Date slideStartTime; - TourStop currentMasterSlide = null; - - public void NextSlide() - { - if (tour.CurrentTourStop != null) - { - if (!tour.CurrentTourStop.MasterSlide) - { - if (tour.CurrentTourStop.MusicTrack != null) - { - tour.CurrentTourStop.MusicTrack.Stop(); - } - - if (tour.CurrentTourStop.VoiceTrack != null) - { - tour.CurrentTourStop.VoiceTrack.Stop(); - } - - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - overlay.Stop(); - } - } - else - { - currentMasterSlide = tour.CurrentTourStop; - } - } - - if (tour.CurrentTourstopIndex < (tour.TourStops.Count - 1) || tour.CurrentTourStop.IsLinked) - { - if (tour.CurrentTourStop.EndTarget != null) - { - WWTControl.Singleton.GotoTargetFull(false, true, tour.CurrentTourStop.EndTarget.CamParams, tour.CurrentTourStop.Target.StudyImageset, tour.CurrentTourStop.Target.BackgroundImageset); - WWTControl.Singleton.Mover = null; - } - - onTarget = false; - - if (tour.CurrentTourStop.IsLinked) - { - try - { - switch (tour.CurrentTourStop.NextSlide) - { - case "Return": - if (callStack.Count > 0) - { - PlayFromTourstop(tour.TourStops[callStack.Pop()]); - } - else - { - tour.CurrentTourstopIndex = tour.TourStops.Count - 1; - } - break; - default: - PlayFromTourstop(tour.TourStops[tour.GetTourStopIndexByID(tour.CurrentTourStop.NextSlide)]); - break; - } - } - catch - { - if (tour.CurrentTourstopIndex < (tour.TourStops.Count - 1)) - { - tour.CurrentTourstopIndex++; - } - } - } - else - { - tour.CurrentTourstopIndex++; - } - - if (currentMasterSlide != null && tour.CurrentTourStop.MasterSlide) - { - StopCurrentMaster(); - } - - bool instant = false; - - switch (tour.CurrentTourStop.Transition) - { - case TransitionType.Slew: - break; - case TransitionType.CrossFade: - instant = true; - break; - case TransitionType.CrossCut: - instant = true; - break; - case TransitionType.FadeOutIn: - instant = true; - break; - case TransitionType.FadeOut: - instant = true; - break; - case TransitionType.FadeIn: - instant = true; - break; - default: - break; - } - - WWTControl.Singleton.GotoTarget(tour.CurrentTourStop.Target, false, instant, false); - - slideStartTime = Date.Now; - // Move to new settings - Settings.TourSettings = tour.CurrentTourStop; - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - } - else - { - StopCurrentMaster(); - playing = false; - - if (Settings.Current.AutoRepeatTour) - { - tour.CurrentTourstopIndex = -1; - Play(); - } - else - { - WWTControl.Singleton.FreezeView(); - if (TourEnded != null) - { - TourEnded.Invoke(this, new EventArgs()); - } - - //ShowEndTourPopup(); - WWTControl.Singleton.HideUI(false); - WWTControl.scriptInterface.FireTourEnded(); - } - } - - } - - private void StopCurrentMaster() - { - if (currentMasterSlide != null) - { - if (currentMasterSlide.MusicTrack != null) - { - currentMasterSlide.MusicTrack.Stop(); - } - - if (currentMasterSlide.VoiceTrack != null) - { - currentMasterSlide.VoiceTrack.Stop(); - } - - foreach (Overlay overlay in currentMasterSlide.Overlays) - { - overlay.Stop(); - } - currentMasterSlide = null; - } - } - - static public event EventHandler TourEnded; - static bool switchedToFullScreen = false; - Stack callStack = new Stack(); - - bool leaveSettingsWhenStopped = false; - - public bool LeaveSettingsWhenStopped { - get { return leaveSettingsWhenStopped; } - set { leaveSettingsWhenStopped = value; } - } - - public void Play() - { - if (tour == null) - { - return; - } - - if (playing) - { - Stop(true); - } - else - { - playing = true; - //switchedToFullScreen = !Viewer.MasterView.FullScreen; - //if (switchedToFullScreen) - //{ - // Viewer.MasterView.ShowFullScreen(true); - //} - } - - WWTControl.Singleton.HideUI(true); - playing = true; - - if (tour.TourStops.Count > 0) - { - onTarget = false; - - if (tour.CurrentTourstopIndex == -1) - { - tour.CurrentTourStop = tour.TourStops[0]; - } - - // Ensure that all multimedia elements are prepared. When - // playing back a tour in a browser, restrictions on autoplay - // mean that we have to ensure that all of our multimedia - // elements are prepared for playback inside code that is - // triggered by a user-initiated event. The PrepMultimedia - // callback should do whatever's needed to make sure that media - // files are all ready to go. - - foreach (TourStop stop in tour.TourStops) - { - if (stop.MusicTrack != null) - stop.MusicTrack.PrepMultimedia(); - - if (stop.VoiceTrack != null) - stop.VoiceTrack.PrepMultimedia(); - - foreach (Overlay overlay in stop.Overlays) - { - overlay.PrepMultimedia(); - } - } - - if (tour.CurrentTourstopIndex > 0) - { - PlayMasterForCurrent(); - } - - WWTControl.Singleton.GotoTarget(tour.CurrentTourStop.Target, false, true, false); - } - - slideStartTime = Date.Now; - playing = true; - } - - private void PlayMasterForCurrent() - { - if (!tour.CurrentTourStop.MasterSlide) - { - MasterTime currentMaster = tour.ElapsedTimeSinceLastMaster(tour.CurrentTourstopIndex); - - if (currentMaster != null) - { - double elapsed = currentMaster.Duration; - currentMasterSlide = currentMaster.Master; - - if (currentMasterSlide.MusicTrack != null) - { - currentMasterSlide.MusicTrack.Seek(elapsed); - currentMasterSlide.MusicTrack.Play(); - } - - if (currentMasterSlide.VoiceTrack != null) - { - currentMasterSlide.VoiceTrack.Seek(elapsed); - currentMasterSlide.VoiceTrack.Play(); - } - - foreach (Overlay overlay in currentMasterSlide.Overlays) - { - overlay.Seek(elapsed); - overlay.Play(); - } - } - } - } - - public static bool NoRestoreUIOnStop; - - public void Stop(bool noSwitchBackFullScreen) - { - if (switchedToFullScreen && !noSwitchBackFullScreen) - { - // Viewer.MasterView.ShowFullScreen(false); - } - - // By default, when you stop (or pause) a tour, the main WWT - // settings become active again. However, this can cause a jarring - // jump if, say, the tour has localHorizonMode active and the main - // settings don't. If you activate this option, we'll leave the tour - // settings lingering, preventing any dramatic changes. - if (!leaveSettingsWhenStopped) { - Settings.TourSettings = null; - } - - playing = false; - - if (tour.CurrentTourStop != null) - { - if (tour.CurrentTourStop.MusicTrack != null) - { - tour.CurrentTourStop.MusicTrack.Stop(); - } - - if (tour.CurrentTourStop.VoiceTrack != null) - { - tour.CurrentTourStop.VoiceTrack.Stop(); - } - - foreach (Overlay overlay in tour.CurrentTourStop.Overlays) - { - overlay.Stop(); - } - } - - if (currentMasterSlide != null) - { - if (currentMasterSlide.MusicTrack != null) - { - currentMasterSlide.MusicTrack.Stop(); - } - - if (currentMasterSlide.VoiceTrack != null) - { - currentMasterSlide.VoiceTrack.Stop(); - } - - foreach (Overlay overlay in currentMasterSlide.Overlays) - { - overlay.Stop(); - } - } - - WWTControl.Singleton.HideUI(NoRestoreUIOnStop); - WWTControl.scriptInterface.FireTourEnded(); - } - - public void UpdateSlideStates() - { - bool slideChanging = false; - - int slideElapsedTime = Date.Now - slideStartTime; - - if (slideElapsedTime > tour.CurrentTourStop.Duration && playing) - { - NextSlide(); - slideChanging = true; - } - - slideElapsedTime = Date.Now - slideStartTime; - - if (tour.CurrentTourStop != null) - { - tour.CurrentTourStop.TweenPosition = Math.Min(1, (float)(slideElapsedTime / tour.CurrentTourStop.Duration)); - tour.CurrentTourStop.FaderOpacity = 0; - //Tile.fastLoad = false; - double elapsedSeconds = tour.CurrentTourStop.TweenPosition * tour.CurrentTourStop.Duration / 1000; - - if (slideChanging) - { - WWTControl.Singleton.CrossFadeFrame = false; - } - - switch (tour.CurrentTourStop.Transition) - { - case TransitionType.Slew: - tour.CurrentTourStop.FaderOpacity = 0; - WWTControl.Singleton.CrossFadeFrame = false; - break; - - case TransitionType.CrossCut: - { - if (slideChanging) - { - //Tile.fastLoad = true; - //Tile.fastLoadAutoReset = false; - } - if (elapsedSeconds < (elapsedSeconds - tour.CurrentTourStop.TransitionHoldTime)) - { - WWTControl.Singleton.CrossFadeFrame = true; - tour.CurrentTourStop.FaderOpacity = 1; - - } - else - { - tour.CurrentTourStop.FaderOpacity = 0; - WWTControl.Singleton.CrossFadeFrame = false; - } - } - break; - - case TransitionType.CrossFade: - { - WWTControl.Singleton.CrossFadeFrame = true; - double opacity = Math.Max(0, 1 - Math.Min(1, (elapsedSeconds - tour.CurrentTourStop.TransitionHoldTime) / tour.CurrentTourStop.TransitionTime)); - tour.CurrentTourStop.FaderOpacity = (float)opacity; - if (slideChanging) - { - //Tile.fastLoad = true; - //Tile.fastLoadAutoReset = false; - } - } - break; - - case TransitionType.FadeOutIn: - case TransitionType.FadeIn: - { - WWTControl.Singleton.CrossFadeFrame = false; - double opacity = Math.Max(0, 1 - Math.Max(0, elapsedSeconds - tour.CurrentTourStop.TransitionHoldTime) / tour.CurrentTourStop.TransitionTime); - tour.CurrentTourStop.FaderOpacity = (float)opacity; - } - break; - - case TransitionType.FadeOut: - WWTControl.Singleton.CrossFadeFrame = false; - break; - - default: - break; - } - - if (!tour.CurrentTourStop.IsLinked && tour.CurrentTourstopIndex < (tour.TourStops.Count - 1)) - { - TransitionType nextTrans = tour.TourStops[tour.CurrentTourstopIndex + 1].Transition; - double nextTransTime = tour.TourStops[tour.CurrentTourstopIndex + 1].TransitionOutTime; - - switch (nextTrans) - { - case TransitionType.FadeOut: - case TransitionType.FadeOutIn: - { - if (tour.CurrentTourStop.FaderOpacity == 0) - { - WWTControl.Singleton.CrossFadeFrame = false; - double opacity = Math.Max(0, 1 - Math.Min(1, ((tour.CurrentTourStop.Duration/1000) - elapsedSeconds) / nextTransTime)); - tour.CurrentTourStop.FaderOpacity = (float)opacity; - } - } - break; - - default: - break; - } - } - } - } - - public float UpdateTweenPosition(float tween) - { - float slideElapsedTime = Date.Now - slideStartTime; - - if (tween > -1) - { - return tour.CurrentTourStop.TweenPosition = Math.Min(1, tween); - } - else - { - return tour.CurrentTourStop.TweenPosition = Math.Min(1, (float)(slideElapsedTime / tour.CurrentTourStop.Duration)); - } - } - - public void Close() - { - if (tour != null) - { - if (Playing) - { - Stop(switchedToFullScreen); - } - // todo check for changes - tour = null; - } - } - - public bool MouseDown(object sender, ElementEvent e) - { - // todo enable links - Vector2d location; - - location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - for (int i = tour.CurrentTourStop.Overlays.Count - 1; i >= 0; i--) - { - if (tour.CurrentTourStop.Overlays[i].HitTest(location)) - { - if (!string.IsNullOrEmpty(tour.CurrentTourStop.Overlays[i].Url)) - { - Overlay linkItem = tour.CurrentTourStop.Overlays[i]; - Util.OpenUrl(linkItem.Url); - return true; - } - - if (!string.IsNullOrEmpty(tour.CurrentTourStop.Overlays[i].LinkID)) - { - callStack.Push(tour.CurrentTourstopIndex); - PlayFromTourstop(tour.TourStops[tour.GetTourStopIndexByID(tour.CurrentTourStop.Overlays[i].LinkID)]); - return true; - } - } - } - - return false; - } - - public bool MouseUp(object sender, ElementEvent e) - { - return false; - } - - public bool MouseMove(object sender, ElementEvent e) - { - // todo enable links - Vector2d location; - - try - { - location = PointToView(Vector2d.Create(e.OffsetX, e.OffsetY)); - } - catch - { - return false; - } - - if (tour == null || tour.CurrentTourStop == null) - { - return false; - } - - for (int i = tour.CurrentTourStop.Overlays.Count - 1; i >= 0; i--) - { - if (tour.CurrentTourStop.Overlays[i].HitTest(location) && (!string.IsNullOrEmpty(tour.CurrentTourStop.Overlays[i].Url) || !string.IsNullOrEmpty(tour.CurrentTourStop.Overlays[i].LinkID))) - { - //todo change cursor to hand - return true; - } - } - - //todo set cursor to default - //Viewer.MasterView.Cursor = null; - return false; - } - - public bool MouseClick(object sender, ElementEvent e) - { - return false; - } - - public bool Click(object sender, ElementEvent e) - { - return false; - } - - public bool MouseDoubleClick(object sender, ElementEvent e) - { - return false; - } - - public bool KeyDown(object sender, ElementEvent e) - { - switch (e.KeyCode) - { - case 27: // escape - Stop(switchedToFullScreen); - WWTControl.Singleton.CloseTour(); - return true; - - case 32: // spacebar - PauseTour(); - return true; - - case 39: // right arrow - PlayNextSlide(); - return true; - - case 37: // left arrow - PlayPreviousSlide(); - return true; - - case 35: // end key - if (tour.TourStops.Count > 0) - { - PlayFromTourstop(tour.TourStops[tour.TourStops.Count - 1]); - } - return true; - - case 36: // home key - if (tour.TourStops.Count > 0) - { - PlayFromTourstop(tour.TourStops[0]); - } - return true; - } - - return false; - } - - private void PlayNextSlide() - { - if ((tour.CurrentTourstopIndex < tour.TourStops.Count - 1) && tour.TourStops.Count > 0) - { - PlayFromTourstop(tour.TourStops[tour.CurrentTourstopIndex + 1]); - } - } - - private void PlayPreviousSlide() - { - if (tour.CurrentTourstopIndex > 0) - { - PlayFromTourstop(tour.TourStops[tour.CurrentTourstopIndex - 1]); - } - } - - public void PlayFromTourstop(TourStop tourStop) - { - Stop(true); - tour.CurrentTourStop = tourStop; - WWTControl.Singleton.GotoTarget(tour.CurrentTourStop.Target, false, true, false); - SpaceTimeController.Now = tour.CurrentTourStop.StartTime; - SpaceTimeController.SyncToClock = false; - Play(); - } - - public void PauseTour() - { - if (playing) - { - Stop(switchedToFullScreen); - WWTControl.Singleton.FreezeView(); - WWTControl.scriptInterface.FireTourPaused(); - } - else - { - Play(); - WWTControl.scriptInterface.FireTourResume(); - } - } - - public bool KeyUp(object sender, ElementEvent e) - { - return false; - } - - public bool Hover(Vector2d pnt) - { - if (playing) - { - return true; - } - return false; - } - - public Vector2d PointToView(Vector2d pnt) - { - double clientHeight = WWTControl.Singleton.Canvas.Height; - double clientWidth = WWTControl.Singleton.Canvas.Width; - double viewWidth = (clientWidth / clientHeight) * 1116f; - double x = (((double)pnt.X) / ((double)clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - double y = ((double)pnt.Y) / clientHeight * 1116; - return Vector2d.Create(x, y); - } - } - - public class MasterTime - { - public TourStop Master; - public double Duration; - - public MasterTime(TourStop master, double duration) - { - Master = master; - Duration = duration; - } - } -} diff --git a/engine/csharp_ref/Tours/TourStop.cs b/engine/csharp_ref/Tours/TourStop.cs deleted file mode 100644 index 49ebd3d9..00000000 --- a/engine/csharp_ref/Tours/TourStop.cs +++ /dev/null @@ -1,2106 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; - -namespace wwtlib -{ - public enum TransitionType { Slew=0, CrossFade=1, CrossCut=2, FadeOutIn=3, FadeIn=4, FadeOut=5 }; - public class TourStop : ISettings - { - public const string ClipboardFormat = "WorldWideTelescope.Slide"; - - ImageSetType tourStopType; - - private bool keyFramed = false; - - public bool KeyFramed - { - get { return keyFramed; } - } - - public ImageSetType TourStopType - { - get - { - if (target.BackgroundImageset != null) - { - return target.BackgroundImageset.DataSetType; - } - else - { - return tourStopType; - } - } - set - { - if (target.BackgroundImageset != null) - { - if (target.BackgroundImageset.DataSetType != value) - { - target.BackgroundImageset = null; - } - } - tourStopType = value; - } - } - - private float tweenPosition = 0; - - public float TweenPosition - { - get { return tweenPosition; } - set - { - if (tweenPosition != value) - { - tweenPosition = Math.Max(0, Math.Min(1, value)); - UpdateTweenPosition(); - } - - } - } - - public double FaderOpacity = 0; - - public void UpdateTweenPosition() - { - if (KeyFramed) - { - //KeyFrameMover.CurrentDateTime = this.StartTime; - //KeyFrameMover.ReferenceFrame = this.Target.CamParams.TargetReferenceFrame; - //KeyFrameMover.MoveTime = (double)(Duration.TotalMilliseconds / 1000.0); - ////update key framed elements - //foreach (AnimationTarget target in AnimationTargets) - //{ - // target.Tween(tweenPosition); - //} - //Earth3d.MainWindow.UpdateMover(KeyFrameMover); - //SpaceTimeController.Now = KeyFrameMover.CurrentDateTime; - } - } - - public TourStop Copy() - { - XmlTextWriter writer = new XmlTextWriter(); - - writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - - this.SaveToXml(writer, true); - - // add try catch block - try - { - XmlDocumentParser xParser = new XmlDocumentParser(); - XmlDocument doc = xParser.ParseFromString(writer.Body, "text/xml"); - System.Xml.XmlNode node = Util.SelectSingleNode(doc, "TourStop"); - TourStop ts = TourStop.FromXml(this.Owner, node); - ts.Id = Guid.NewGuid().ToString(); - return ts; - } - catch - { - } - return null; - } - - public TourStop() - { - id = Guid.NewGuid().ToString(); - - } - - public static TourStop Create(Place target) - { - TourStop ts = new TourStop(); - - ts.target = target; - - return ts; - } - - TourDocument owner = null; - - public TourDocument Owner - { - get { return owner; } - set { owner = value; } - } - TransitionType transition = TransitionType.Slew; - - internal TransitionType Transition - { - get { return transition; } - set - { - if (transition != value) - { - transition = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - private double transitionTime = 2; - - internal double TransitionTime - { - get { return transitionTime; } - set - { - if (transitionTime != value) - { - transitionTime = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - private double transitionHoldTime = 4; - - internal double TransitionHoldTime - { - get { return transitionHoldTime; } - set - { - if (transitionHoldTime != value) - { - transitionHoldTime = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - - private double transitionOutTime = 2; - - internal double TransitionOutTime - { - get { return transitionOutTime; } - set - { - if (transitionOutTime != value) - { - transitionOutTime = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - string nextSlide = "Next"; - - public string NextSlide - { - get { return nextSlide; } - set { nextSlide = value; } - } - - public bool IsLinked - { - get - { - if (nextSlide == null || nextSlide == "Next" || nextSlide == "") - { - return false; - } - return true; - } - } - - bool fadeInOverlays = false; - - public bool FadeInOverlays - { - get { return fadeInOverlays; } - set { fadeInOverlays = value; } - } - - bool masterSlide = false; - - public bool MasterSlide - { - get { return masterSlide; } - set - { - if (masterSlide != value) - { - masterSlide = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - string id = ""; - - public string Id - { - get { return id; } - set - { - id = value; - if (owner != null) { owner.TourDirty = true; } - } - } - - public override string ToString() - { - if (target != null) - { - return Target.Name; - } - else - { - return description; - } - } - - string description = ""; - - public string Description - { - get { return description; } - set - { - if (description != value) - { - description = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - private string name = ""; - - public string Name - { - get - { - if (target != null) - { - return target.Name; - } - return name; - } - set - { - if (name != value) - { - name = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - int duration = 10000; - - public int Duration - { - get { return duration; } - set - { - if (duration != value) - { - duration = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - Place target; - - public Place Target - { - get { return target; } - set - { - if (target != value) - { - target = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - Place endTarget; - - public Place EndTarget - { - get { return endTarget; } - set - { - if (endTarget != value) - { - endTarget = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - InterpolationType interpolationType = InterpolationType.Linear; - - public InterpolationType InterpolationType - { - get { return interpolationType; } - set { interpolationType = value; } - } - - - // Settings - - bool hasLocation = true; - - public bool HasLocation - { - get { return hasTime; } - set - { - if (hasLocation != value) - { - hasLocation = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - bool hasTime = true; - - public bool HasTime - { - get { return hasTime; } - set - { - if (hasTime != value) - { - hasTime = hasLocation = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - Date startTime = SpaceTimeController.Now; - - public Date StartTime - { - get { return startTime; } - set - { - startTime = value; - if (startTime != value) - { - startTime = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - Date endTime = SpaceTimeController.Now; - - public Date EndTime - { - get { return endTime; } - set - { - if (endTime != value) - { - endTime = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - - bool actualPlanetScale = Settings.Current.ActualPlanetScale; - double locationAltitude = Settings.Current.LocationAltitude; - double locationLat = Settings.Current.LocationLat; - double locationLng = Settings.Current.LocationLng; - bool showClouds = Settings.Current.ShowClouds; - bool showConstellationBoundries = Settings.Current.ShowConstellationBoundries; - bool showConstellationFigures = Settings.Current.ShowConstellationFigures; - bool showConstellationSelection = Settings.Current.ShowConstellationSelection; - bool showEcliptic = Settings.Current.ShowEcliptic; - bool showElevationModel = Settings.Current.ShowElevationModel; - bool showFieldOfView = Settings.Current.ShowFieldOfView; - bool showGrid = Settings.Current.ShowGrid; - bool showHorizon = Settings.Current.ShowHorizon; - bool showHorizonPanorama = Settings.Current.ShowHorizonPanorama; - bool showMoonsAsPointSource = Settings.Current.ShowMoonsAsPointSource; - bool showSolarSystem = Settings.Current.ShowSolarSystem; - int fovTelescope = Settings.Current.FovTelescope; - int fovEyepiece = Settings.Current.FovEyepiece; - int fovCamera = Settings.Current.FovCamera; - bool localHorizonMode = Settings.Current.LocalHorizonMode; - bool galacticMode = Settings.Current.GalacticMode; - - bool solarSystemStars = Settings.Current.SolarSystemStars; - bool solarSystemMilkyWay = Settings.Current.SolarSystemMilkyWay; - bool solarSystemCosmos = Settings.Current.SolarSystemCosmos; - bool solarSystemOrbits = Settings.Current.SolarSystemOrbits; - bool solarSystemOverlays = Settings.Current.SolarSystemOverlays; - bool solarSystemLighting = Settings.Current.SolarSystemLighting; - int solarSystemScale = Settings.Current.SolarSystemScale; - bool solarSystemMultiRes = Settings.Current.SolarSystemMultiRes; - - //new - bool showEquatorialGridText = Settings.Current.ShowEquatorialGridText; - bool showGalacticGrid = Settings.Current.ShowGalacticGrid; - bool showGalacticGridText = Settings.Current.ShowGalacticGridText; - bool showEclipticGrid = Settings.Current.ShowEclipticGrid; - bool showEclipticGridText = Settings.Current.ShowEclipticGridText; - private bool showEclipticOverviewText = Settings.Current.ShowEclipticOverviewText; - private bool showAltAzGrid = Settings.Current.ShowAltAzGrid; - private bool showAltAzGridText = Settings.Current.ShowAltAzGridText; - private bool showPrecessionChart = Settings.Current.ShowPrecessionChart; - private bool showConstellationPictures = Settings.Current.ShowConstellationPictures; - private bool showConstellationLabels = Settings.Current.ShowConstellationLabels; - bool solarSystemCMB = Settings.Current.SolarSystemCMB; - bool solarSystemMinorPlanets = Settings.Current.SolarSystemMinorPlanets; - bool solarSystemPlanets = Settings.Current.SolarSystemPlanets; - bool showEarthSky = Settings.Current.ShowEarthSky; - bool solarSystemMinorOrbits = Settings.Current.SolarSystemMinorOrbits; - string constellationsEnabled = ""; - ConstellationFilter constellationFiguresFilter = Settings.Current.ConstellationFiguresFilter.Clone(); - ConstellationFilter constellationBoundariesFilter = Settings.Current.ConstellationBoundariesFilter.Clone(); - ConstellationFilter constellationNamesFilter = Settings.Current.ConstellationNamesFilter.Clone(); - ConstellationFilter constellationArtFilter = Settings.Current.ConstellationArtFilter.Clone(); - bool showSkyOverlays = Settings.Current.ShowSkyOverlays; - bool showConstellations = Settings.Current.ShowConstellations; - bool showSkyNode = Settings.Current.ShowSkyNode; - bool showSkyGrids = Settings.Current.ShowSkyGrids; - bool showSkyOverlaysIn3d = Settings.Current.ShowSkyOverlaysIn3d; - bool earthCutawayView = Settings.Current.EarthCutawayView; - bool showISSModel = Settings.Current.ShowISSModel; - bool milkyWayModel = Settings.Current.MilkyWayModel; - int minorPlanetsFilter = Settings.Current.MinorPlanetsFilter; - int planetOrbitsFilter = Settings.Current.PlanetOrbitsFilter; - - - - public void CaptureSettings() - { - startTime = SpaceTimeController.Now; - actualPlanetScale = Settings.Current.ActualPlanetScale; - locationAltitude = Settings.Current.LocationAltitude; - locationLat = Settings.Current.LocationLat; - locationLng = Settings.Current.LocationLng; - showClouds = Settings.Current.ShowClouds; - showConstellationBoundries = Settings.Current.ShowConstellationBoundries; - showConstellationFigures = Settings.Current.ShowConstellationFigures; - showConstellationSelection = Settings.Current.ShowConstellationSelection; - showEcliptic = Settings.Current.ShowEcliptic; - showElevationModel = Settings.Current.ShowElevationModel; - showFieldOfView = Settings.Current.ShowFieldOfView; - showGrid = Settings.Current.ShowGrid; - showHorizon = Settings.Current.ShowHorizon; - showHorizonPanorama = Settings.Current.ShowHorizonPanorama; - showMoonsAsPointSource = Settings.Current.ShowMoonsAsPointSource; - showSolarSystem = Settings.Current.ShowSolarSystem; - fovTelescope = Settings.Current.FovTelescope; - fovEyepiece = Settings.Current.FovEyepiece; - fovCamera = Settings.Current.FovCamera; - localHorizonMode = Settings.Current.LocalHorizonMode; - galacticMode = Settings.Current.GalacticMode; - solarSystemStars = Settings.Current.SolarSystemStars; - solarSystemMilkyWay = Settings.Current.SolarSystemMilkyWay; - solarSystemCosmos = Settings.Current.SolarSystemCosmos; - solarSystemOrbits = Settings.Current.SolarSystemOrbits; - solarSystemOverlays = Settings.Current.SolarSystemOverlays; - solarSystemLighting = Settings.Current.SolarSystemLighting; - solarSystemScale = Settings.Current.SolarSystemScale; - solarSystemMultiRes = Settings.Current.SolarSystemMultiRes; - //new - - showEquatorialGridText = Settings.Current.ShowEquatorialGridText; - showGalacticGrid = Settings.Current.ShowGalacticGrid; - showGalacticGridText = Settings.Current.ShowGalacticGridText; - showEclipticGrid = Settings.Current.ShowEclipticGrid; - showEclipticGridText = Settings.Current.ShowEclipticGridText; - showEclipticOverviewText = Settings.Current.ShowEclipticOverviewText; - showAltAzGrid = Settings.Current.ShowAltAzGrid; - showAltAzGridText = Settings.Current.ShowAltAzGridText; - showPrecessionChart = Settings.Current.ShowPrecessionChart; - showConstellationPictures = Settings.Current.ShowConstellationPictures; - showConstellationLabels = Settings.Current.ShowConstellationLabels; - solarSystemCMB = Settings.Current.SolarSystemCMB; - solarSystemMinorPlanets = Settings.Current.SolarSystemMinorPlanets; - solarSystemPlanets = Settings.Current.SolarSystemPlanets; - showEarthSky = Settings.Current.ShowEarthSky; - solarSystemMinorOrbits = Settings.Current.SolarSystemMinorOrbits; - constellationFiguresFilter = Settings.Current.ConstellationFiguresFilter.Clone(); - constellationBoundariesFilter = Settings.Current.ConstellationBoundariesFilter.Clone(); - constellationNamesFilter = Settings.Current.ConstellationNamesFilter.Clone(); - constellationArtFilter = Settings.Current.ConstellationArtFilter.Clone(); - showSkyOverlays = Settings.Current.ShowSkyOverlays; - showConstellations = Settings.Current.ShowConstellations; - showSkyNode = Settings.Current.ShowSkyNode; - showSkyGrids = Settings.Current.ShowSkyGrids; - showSkyOverlaysIn3d = Settings.Current.ShowSkyOverlaysIn3d; - earthCutawayView = Settings.Current.EarthCutawayView; - showISSModel = Settings.Current.ShowISSModel; - milkyWayModel = Settings.Current.MilkyWayModel; - minorPlanetsFilter = Settings.Current.MinorPlanetsFilter; - planetOrbitsFilter = Settings.Current.PlanetOrbitsFilter; - } - - public static string GetXmlText(TourStop ts) - { - - XmlTextWriter writer = new XmlTextWriter(); - writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); - - ts.SaveToXml(writer, true); - writer.Close(); - return writer.Body; - } - - - - public void SyncSettings() - { - //Earth3d.ignoreChanges = true; - //LayerManager.ProcessingUpdate = true; - - Settings.GlobalSettings.ActualPlanetScale = actualPlanetScale; - Settings.GlobalSettings.LocationAltitude = locationAltitude; - Settings.GlobalSettings.LocationLat = locationLat; - Settings.GlobalSettings.LocationLng = locationLng; - // Settings.GlobalSettings.ShowClouds.TargetState = showClouds; - Settings.GlobalSettings.EarthCutawayView = earthCutawayView; - Settings.GlobalSettings.ShowConstellationBoundries = showConstellationBoundries; - Settings.GlobalSettings.ShowConstellationFigures = showConstellationFigures; - Settings.GlobalSettings.ShowConstellationSelection = showConstellationSelection; - Settings.GlobalSettings.ShowEcliptic = showEcliptic; - Settings.GlobalSettings.ShowElevationModel = showElevationModel; - // Settings.GlobalSettings.ShowFieldOfView = showFieldOfView; - Settings.GlobalSettings.ShowGrid = showGrid; - Settings.GlobalSettings.ShowHorizon = showHorizon; - // Settings.GlobalSettings.ShowHorizonPanorama = showHorizonPanorama; - // Settings.GlobalSettings.ShowMoonsAsPointSource = showMoonsAsPointSource; - Settings.GlobalSettings.ShowSolarSystem = showSolarSystem; - // Settings.GlobalSettings.FovTelescope = fovTelescope; - // Settings.GlobalSettings.FovEyepiece = fovEyepiece; - // Settings.GlobalSettings.FovCamera = fovCamera; - Settings.GlobalSettings.LocalHorizonMode = localHorizonMode; - Settings.GlobalSettings.GalacticMode = galacticMode; - Settings.GlobalSettings.SolarSystemStars = solarSystemStars; - Settings.GlobalSettings.SolarSystemMilkyWay = solarSystemMilkyWay; - Settings.GlobalSettings.SolarSystemCosmos = solarSystemCosmos; - Settings.GlobalSettings.SolarSystemCMB = solarSystemCMB; - Settings.GlobalSettings.SolarSystemOrbits = solarSystemOrbits; - Settings.GlobalSettings.SolarSystemMinorOrbits = solarSystemMinorOrbits; - Settings.GlobalSettings.SolarSystemMinorPlanets = solarSystemMinorPlanets; - Settings.GlobalSettings.SolarSystemOverlays = solarSystemOverlays; - Settings.GlobalSettings.SolarSystemLighting = solarSystemLighting; - Settings.GlobalSettings.ShowISSModel = showISSModel; - Settings.GlobalSettings.SolarSystemScale = solarSystemScale; - Settings.GlobalSettings.SolarSystemMultiRes = solarSystemMultiRes; - Settings.GlobalSettings.ShowEarthSky = showEarthSky; - Settings.GlobalSettings.MinorPlanetsFilter = minorPlanetsFilter; - Settings.GlobalSettings.PlanetOrbitsFilter = planetOrbitsFilter; - Settings.GlobalSettings.ShowEquatorialGridText = showEquatorialGridText; - Settings.GlobalSettings.ShowGalacticGrid = showGalacticGrid; - Settings.GlobalSettings.ShowGalacticGridText = showGalacticGridText; - Settings.GlobalSettings.ShowEclipticGrid = showEclipticGrid; - Settings.GlobalSettings.ShowEclipticGridText = showEclipticGridText; - Settings.GlobalSettings.ShowEclipticOverviewText = showEclipticOverviewText; - Settings.GlobalSettings.ShowAltAzGrid = showAltAzGrid; - Settings.GlobalSettings.ShowAltAzGridText = showAltAzGridText; - Settings.GlobalSettings.ShowPrecessionChart = showPrecessionChart; - Settings.GlobalSettings.ShowConstellationPictures = showConstellationPictures; - Settings.GlobalSettings.ConstellationsEnabled = constellationsEnabled; - Settings.GlobalSettings.ShowSkyOverlays = showSkyOverlays; - Settings.GlobalSettings.Constellations = showConstellations; - Settings.GlobalSettings.ShowSkyNode = showSkyNode; - Settings.GlobalSettings.ShowSkyGrids = showSkyGrids; - // Settings.GlobalSettings.ShowSkyOverlaysIn3d = skyOverlaysIn3d; - Settings.GlobalSettings.ConstellationFiguresFilter = constellationFiguresFilter.Clone(); - Settings.GlobalSettings.ConstellationBoundariesFilter = constellationBoundariesFilter.Clone(); - Settings.GlobalSettings.ConstellationNamesFilter=constellationNamesFilter.Clone(); - Settings.GlobalSettings.ConstellationArtFilter=constellationArtFilter.Clone(); - // Earth3d.ignoreChanges = false; - // LayerManager.ProcessingUpdate = false; - //Settings.Default.PulseMeForUpdate = !Properties.Settings.Default.PulseMeForUpdate; - } - - #region ISettings Members - - public bool SolarSystemStars - { - get { return solarSystemStars; } - } - public bool SolarSystemMultiRes - { - get { return solarSystemMultiRes; } - } - public bool SolarSystemMilkyWay - { - get { return solarSystemMilkyWay; } - } - - public bool SolarSystemCosmos - { - get { return solarSystemCosmos; } - } - - public bool SolarSystemOrbits - { - get { return solarSystemOrbits; } - } - - public bool SolarSystemOverlays - { - get { return solarSystemOverlays; } - } - - public bool SolarSystemLighting - { - get { return solarSystemLighting; } - } - - public int SolarSystemScale - { - get { return solarSystemScale; } - } - - - - public bool ActualPlanetScale - { - get { return actualPlanetScale; } - } - - public int FovCamera - { - get { return fovCamera; } - } - - public int FovEyepiece - { - get { return fovEyepiece; } - } - - public int FovTelescope - { - get { return fovTelescope; } - } - - public double LocationAltitude - { - get - { - if (hasLocation) - { - return locationAltitude; - } - else - { - return Settings.Current.LocationAltitude; - } - } - } - - public double LocationLat - { - get - { - if (hasLocation) - { - return locationLat; - } - else - { - return Settings.Current.LocationLat; - } - } - } - - public double LocationLng - { - get - { - if (hasLocation) - { - return locationLng; - } - else - { - return Settings.Current.LocationLng; - } - } - } - - public bool ShowClouds - { - get - { - return showClouds; - } - } - - public bool ShowConstellationBoundries - { - get - { - return showConstellationBoundries; - } - } - - public bool ShowConstellationFigures - { - get { return showConstellationFigures; } - } - - public bool ShowConstellationSelection - { - get { return showConstellationSelection; } - } - - public bool ShowEcliptic - { - get { return showEcliptic; } - } - - public bool ShowElevationModel - { - get { return showElevationModel; } - } - - public bool ShowFieldOfView - { - get { return showFieldOfView; } - } - - public bool ShowGrid - { - get { return showGrid; } - } - - public bool ShowHorizon - { - get { return showHorizon; } - } - - public bool ShowHorizonPanorama - { - get { return showHorizonPanorama; } - } - - public bool ShowMoonsAsPointSource - { - get { return showMoonsAsPointSource; } - } - - public bool ShowSolarSystem - { - get { return showSolarSystem; } - } - - public bool LocalHorizonMode - { - get { return localHorizonMode; } - } - public bool GalacticMode - { - get { return galacticMode; } - } - #endregion - // End Settings - string thumbnailString = ""; - ImageElement thumbnail = null; - - public ImageElement Thumbnail - { - get - { - if (target != null && thumbnail == null) - { - //todo create bitmap from cab file and return it - return null; - //return target.ThumbNail; - } - return thumbnail; - } - set - { - thumbnail = value; - if (owner != null) { owner.TourDirty = true; } - } - } - - public Dictionary Layers = new Dictionary(); - - - List overlays = new List(); - - public List Overlays - { - get { return overlays; } - } - - AudioOverlay musicTrack = null; - - public AudioOverlay MusicTrack - { - get { return musicTrack; } - set - { - if (musicTrack != value) - { - musicTrack = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - AudioOverlay voiceTrack = null; - - public AudioOverlay VoiceTrack - { - get { return voiceTrack; } - set - { - if (voiceTrack != value) - { - voiceTrack = value; - if (owner != null) { owner.TourDirty = true; } - } - } - } - - public void AddOverlay(Overlay overlay) - { - if (overlay == null) - { - return; - } - - overlay.Owner = this; - overlays.Add(overlay); - if (owner != null) { owner.TourDirty = true; } - - } - - public void RemoveOverlay(Overlay overlay) - { - //todo clean up temp disk - overlays.Remove(overlay); - if (owner != null) { owner.TourDirty = true; } - } - - public void CleanUp() - { - // todo this needs to be evaluated. Causes major pain in WebClient - foreach (Overlay overlay in Overlays) - { - overlay.CleanUp(); - } - - if (voiceTrack != null) - { - voiceTrack.CleanUp(); - } - - if (musicTrack != null) - { - musicTrack.CleanUp(); - } - } - - public void SendToBack(Overlay target) - { - overlays.Remove(target); - overlays.Insert(0, target); - if (owner != null) { owner.TourDirty = true; } - } - - public void BringToFront(Overlay target) - { - overlays.Remove(target); - overlays.Add(target); - if (owner != null) { owner.TourDirty = true; } - } - - public void BringForward(Overlay target) - { - //int index = overlays.FindIndex(delegate(Overlay overlay) { return target == overlay; }); - int index = overlays.IndexOf(target); - if (index < overlays.Count - 1) - { - overlays.Remove(target); - overlays.Insert(index + 1, target); - } - if (owner != null) { owner.TourDirty = true; } - } - - public void SendBackward(Overlay target) - { - int index = overlays.IndexOf(target); - if (index > 0) - { - overlays.Remove(target); - overlays.Insert(index - 1, target); - } - if (owner != null) { owner.TourDirty = true; } - } - - public Overlay GetNextOverlay(Overlay current) - { - if (current == null) - { - if (overlays.Count > 0) - { - return overlays[0]; - } - else - { - return null; - } - } - - int index = overlays.IndexOf(current); - if (index < overlays.Count - 1) - { - return overlays[index + 1]; - } - else - { - return overlays[0]; - } - } - - public Overlay GetPerviousOverlay(Overlay current) - { - if (current == null) - { - if (overlays.Count > 0) - { - return overlays[0]; - } - else - { - return null; - } - } - int index = overlays.IndexOf(current); - if (index > 0) - { - return overlays[index - 1]; - } - else - { - return overlays[overlays.Count - 1]; - } - } - - public Overlay GetOverlayById(string id) - { - foreach (Overlay ol in overlays) - { - if (ol.Id == id) - { - return ol; - } - } - return null; - } - - public string TourStopThumbnailFilename - { - get - { - return string.Format("{0}.thumb.png", id); - } - } - - internal void SaveToXml(XmlTextWriter xmlWriter, bool saveContent) - { - if (saveContent) - { - if (thumbnail != null) - { - //todo how do we save this? - //thumbnail.Save(TourStopThumbnailFilename, System.Drawing.Imaging.ImageFormat.Png); - } - } - - xmlWriter.WriteStartElement("TourStop"); - xmlWriter.WriteAttributeString("Id", id); - xmlWriter.WriteAttributeString("Name", name); - xmlWriter.WriteAttributeString("Description", description); - xmlWriter.WriteAttributeString("Thumbnail", thumbnailString); - xmlWriter.WriteAttributeString("Duration", Util.XMLDuration(duration)); - xmlWriter.WriteAttributeString("Master", masterSlide.ToString()); - xmlWriter.WriteAttributeString("TransitionType", Enums.ToXml("TransitionType", (int)transition)); - xmlWriter.WriteAttributeString("TransitionTime", transitionTime.ToString()); - xmlWriter.WriteAttributeString("TransitionOutTime", transitionOutTime.ToString()); - xmlWriter.WriteAttributeString("TransitionHoldTime", transitionHoldTime.ToString()); - xmlWriter.WriteAttributeString("NextSlide", nextSlide.ToString()); - xmlWriter.WriteAttributeString("InterpolationType", Enums.ToXml("InterpolationType", (int)interpolationType)); - - xmlWriter.WriteAttributeString("HasLocation", hasLocation.ToString()); - if (hasLocation) - { - xmlWriter.WriteAttributeString("LocationAltitude", locationAltitude.ToString()); - xmlWriter.WriteAttributeString("LocationLat", locationLat.ToString()); - xmlWriter.WriteAttributeString("LocationLng", locationLng.ToString()); - } - xmlWriter.WriteAttributeString("HasTime", hasTime.ToString()); - if (hasTime) - { - xmlWriter.WriteAttributeString("StartTime", Util.XMLDate(startTime)); - xmlWriter.WriteAttributeString("EndTime", Util.XMLDate(endTime)); - } - xmlWriter.WriteAttributeString("ActualPlanetScale", actualPlanetScale.ToString()); - xmlWriter.WriteAttributeString("ShowClouds", showClouds.ToString()); - xmlWriter.WriteAttributeString("EarthCutawayView", earthCutawayView.ToString()); - xmlWriter.WriteAttributeString("ShowConstellationBoundries", showConstellationBoundries.ToString()); - xmlWriter.WriteAttributeString("ShowConstellationFigures", showConstellationFigures.ToString()); - xmlWriter.WriteAttributeString("ShowConstellationSelection", showConstellationSelection.ToString()); - xmlWriter.WriteAttributeString("ShowEcliptic", showEcliptic.ToString()); - xmlWriter.WriteAttributeString("EclipticColor", eclipticColor.Save()); - xmlWriter.WriteAttributeString("ShowElevationModel", showElevationModel.ToString()); - showFieldOfView = false; - xmlWriter.WriteAttributeString("ShowFieldOfView", showFieldOfView.ToString()); - xmlWriter.WriteAttributeString("ShowGrid", showGrid.ToString()); - xmlWriter.WriteAttributeString("ShowHorizon", showHorizon.ToString()); - xmlWriter.WriteAttributeString("ShowHorizonPanorama", showHorizonPanorama.ToString()); - xmlWriter.WriteAttributeString("ShowMoonsAsPointSource", showMoonsAsPointSource.ToString()); - xmlWriter.WriteAttributeString("ShowSolarSystem", showSolarSystem.ToString()); - xmlWriter.WriteAttributeString("FovTelescope", fovTelescope.ToString()); - xmlWriter.WriteAttributeString("FovEyepiece", fovEyepiece.ToString()); - xmlWriter.WriteAttributeString("FovCamera", fovCamera.ToString()); - xmlWriter.WriteAttributeString("LocalHorizonMode", localHorizonMode.ToString()); - //xmlWriter.WriteAttributeString("MilkyWayModel", milkyWayModel.ToString()); - xmlWriter.WriteAttributeString("GalacticMode", galacticMode.ToString()); - xmlWriter.WriteAttributeString("FadeInOverlays", fadeInOverlays.ToString()); - xmlWriter.WriteAttributeString("SolarSystemStars", solarSystemStars.ToString()); - xmlWriter.WriteAttributeString("SolarSystemMilkyWay", solarSystemMilkyWay.ToString()); - xmlWriter.WriteAttributeString("SolarSystemCosmos", solarSystemCosmos.ToString()); - xmlWriter.WriteAttributeString("SolarSystemCMB", solarSystemCMB.ToString()); - xmlWriter.WriteAttributeString("SolarSystemOrbits", solarSystemOrbits.ToString()); - xmlWriter.WriteAttributeString("SolarSystemMinorOrbits", solarSystemMinorOrbits.ToString()); - xmlWriter.WriteAttributeString("SolarSystemOverlays", solarSystemOverlays.ToString()); - xmlWriter.WriteAttributeString("SolarSystemLighting", solarSystemLighting.ToString()); - xmlWriter.WriteAttributeString("ShowISSModel", showISSModel.ToString()); - xmlWriter.WriteAttributeString("SolarSystemScale", solarSystemScale.ToString()); - xmlWriter.WriteAttributeString("MinorPlanetsFilter", minorPlanetsFilter.ToString()); - xmlWriter.WriteAttributeString("PlanetOrbitsFilter", planetOrbitsFilter.ToString()); - - xmlWriter.WriteAttributeString("SolarSystemMultiRes", solarSystemMultiRes.ToString()); - xmlWriter.WriteAttributeString("SolarSystemMinorPlanets", solarSystemMinorPlanets.ToString()); - xmlWriter.WriteAttributeString("SolarSystemPlanets", solarSystemPlanets.ToString()); - xmlWriter.WriteAttributeString("ShowEarthSky", showEarthSky.ToString()); - - xmlWriter.WriteAttributeString("ShowEquatorialGridText", ShowEquatorialGridText.ToString()); - xmlWriter.WriteAttributeString("EquatorialGridColor", EquatorialGridColor.Save()); - xmlWriter.WriteAttributeString("ShowGalacticGrid", ShowGalacticGrid.ToString()); - xmlWriter.WriteAttributeString("ShowGalacticGridText", ShowGalacticGridText.ToString()); - xmlWriter.WriteAttributeString("GalacticGridColor", GalacticGridColor.Save()); - xmlWriter.WriteAttributeString("ShowEclipticGrid", ShowEclipticGrid.ToString()); - xmlWriter.WriteAttributeString("ShowEclipticGridText", ShowEclipticGridText.ToString()); - xmlWriter.WriteAttributeString("EclipticGridColor", EclipticGridColor.Save()); - xmlWriter.WriteAttributeString("ShowEclipticOverviewText", ShowEclipticOverviewText.ToString()); - xmlWriter.WriteAttributeString("ShowAltAzGrid", ShowAltAzGrid.ToString()); - xmlWriter.WriteAttributeString("ShowAltAzGridText", ShowAltAzGridText.ToString()); - xmlWriter.WriteAttributeString("AltAzGridColor", AltAzGridColor.Save()); - xmlWriter.WriteAttributeString("ShowPrecessionChart", ShowPrecessionChart.ToString()); - xmlWriter.WriteAttributeString("PrecessionChartColor", PrecessionChartColor.Save()); - xmlWriter.WriteAttributeString("ConstellationPictures", ShowConstellationPictures.ToString()); - xmlWriter.WriteAttributeString("ConstellationsEnabled", ConstellationsEnabled); - xmlWriter.WriteAttributeString("ShowConstellationLabels", ShowConstellationLabels.ToString()); - xmlWriter.WriteAttributeString("ShowSkyOverlays", ShowSkyOverlays.ToString()); - xmlWriter.WriteAttributeString("ShowConstellations", ShowConstellations.ToString()); - xmlWriter.WriteAttributeString("ShowSkyNode", ShowSkyNode.ToString()); - xmlWriter.WriteAttributeString("ShowSkyGrids", ShowSkyGrids.ToString()); - xmlWriter.WriteAttributeString("SkyOverlaysIn3d", ShowSkyOverlaysIn3d.ToString()); - xmlWriter.WriteAttributeString("ConstellationFiguresFilter", constellationFiguresFilter.ToString()); - xmlWriter.WriteAttributeString("ConstellationBoundariesFilter", constellationBoundariesFilter.ToString()); - xmlWriter.WriteAttributeString("ConstellationNamesFilter", constellationNamesFilter.ToString()); - xmlWriter.WriteAttributeString("ConstellationArtFilter", constellationArtFilter.ToString()); - - - - target.SaveToXml(xmlWriter, "Place"); - if (endTarget != null) - { - endTarget.SaveToXml(xmlWriter, "EndTarget"); - } - - xmlWriter.WriteStartElement("Overlays"); - - foreach (Overlay overlay in overlays) - { - overlay.SaveToXml(xmlWriter, false); - } - xmlWriter.WriteEndElement(); - - if (musicTrack != null) - { - xmlWriter.WriteStartElement("MusicTrack"); - - musicTrack.SaveToXml(xmlWriter, false); - - xmlWriter.WriteEndElement(); - } - - if (voiceTrack != null) - { - xmlWriter.WriteStartElement("VoiceTrack"); - - voiceTrack.SaveToXml(xmlWriter, false); - - xmlWriter.WriteEndElement(); - } - - //xmlWriter.WriteElementString("Credits", Credits); - WriteLayerList(xmlWriter); - - //if (KeyFramed) - //{ - // xmlWriter.WriteStartElement("AnimationTargets"); - // foreach (AnimationTarget aniTarget in AnimationTargets) - // { - // aniTarget.SaveToXml(xmlWriter); - // } - // xmlWriter.WriteEndElement(); - //} - - xmlWriter.WriteEndElement(); - } - - private void WriteLayerList(XmlTextWriter xmlWriter) - { - if (Layers.Count > 0) - { - xmlWriter.WriteStartElement("VisibleLayers"); - foreach (Guid key in Layers.Keys) - { - LayerInfo info = Layers[key]; - - xmlWriter.WriteStartElement("Layer"); - xmlWriter.WriteAttributeString("StartOpacity", info.StartOpacity.ToString()); - xmlWriter.WriteAttributeString("EndOpacity", info.EndOpacity.ToString()); - int len = info.StartParams.Length; - - xmlWriter.WriteAttributeString("ParamCount", len.ToString()); - for (int i = 0; i < len; i++) - { - xmlWriter.WriteAttributeString(string.Format("StartParam{0}", i), info.StartParams[i].ToString()); - xmlWriter.WriteAttributeString(string.Format("EndParam{0}", i), info.EndParams[i].ToString()); - } - xmlWriter.WriteValue(info.ID.ToString()); - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - } - } - - - internal void AddFilesToCabinet(FileCabinet fc, bool excludeAudio) - { - if (thumbnail != null) - { - string filename = string.Format("{0}.thumb.png", id); - System.Html.Data.Files.Blob blob = owner.GetFileBlob(filename); - fc.AddFile(owner.WorkingDirectory + filename, blob); - } - - if (!excludeAudio) - { - if (musicTrack != null) - { - musicTrack.AddFilesToCabinet(fc); - } - - if (voiceTrack != null) - { - voiceTrack.AddFilesToCabinet(fc); - } - } - - foreach (Overlay overlay in overlays) - { - overlay.AddFilesToCabinet(fc); - } - } - - - - internal static TourStop FromXml(TourDocument owner, XmlNode tourStop) - { - try - { - TourStop newTourStop = new TourStop(); - newTourStop.owner = owner; - - newTourStop.Id = tourStop.Attributes.GetNamedItem("Id").Value.ToString(); - newTourStop.Name = tourStop.Attributes.GetNamedItem("Name").Value.ToString(); - newTourStop.Description = tourStop.Attributes.GetNamedItem("Description").Value.ToString(); - newTourStop.thumbnailString = tourStop.Attributes.GetNamedItem("Thumbnail").Value.ToString(); - newTourStop.duration = Util.ParseTimeSpan(tourStop.Attributes.GetNamedItem("Duration").Value.ToString()); - - if (tourStop.Attributes.GetNamedItem("Master") != null) - { - newTourStop.masterSlide = bool.Parse(tourStop.Attributes.GetNamedItem("Master").Value); - } - - if (tourStop.Attributes.GetNamedItem("NextSlide") != null) - { - newTourStop.nextSlide = tourStop.Attributes.GetNamedItem("NextSlide").Value; - } - - if (tourStop.Attributes.GetNamedItem("InterpolationType") != null) - { - newTourStop.InterpolationType = (InterpolationType)Enums.Parse("InterpolationType", tourStop.Attributes.GetNamedItem("InterpolationType").Value); - } - - newTourStop.fadeInOverlays = true; - - if (tourStop.Attributes.GetNamedItem("FadeInOverlays") != null) - { - newTourStop.fadeInOverlays = bool.Parse(tourStop.Attributes.GetNamedItem("FadeInOverlays").Value); - } - - if (tourStop.Attributes.GetNamedItem("Transition") != null) - { - newTourStop.transition = (TransitionType)Enums.Parse("TransitionType", tourStop.Attributes.GetNamedItem("Transition").Value); - } - - if (tourStop.Attributes.GetNamedItem("HasLocation") != null) - { - newTourStop.hasLocation = bool.Parse(tourStop.Attributes.GetNamedItem("HasLocation").Value); - } - - if (newTourStop.hasLocation) - { - if (tourStop.Attributes.GetNamedItem("LocationAltitude") != null) - { - newTourStop.locationAltitude = double.Parse(tourStop.Attributes.GetNamedItem("LocationAltitude").Value); - } - if (tourStop.Attributes.GetNamedItem("LocationLat") != null) - { - newTourStop.locationLat = double.Parse(tourStop.Attributes.GetNamedItem("LocationLat").Value); - } - if (tourStop.Attributes.GetNamedItem("LocationLng") != null) - { - newTourStop.locationLng = double.Parse(tourStop.Attributes.GetNamedItem("LocationLng").Value); - } - } - - if (tourStop.Attributes.GetNamedItem("HasTime") != null) - { - newTourStop.hasTime = bool.Parse(tourStop.Attributes.GetNamedItem("HasTime").Value); - - if (newTourStop.hasTime) - { - if (tourStop.Attributes.GetNamedItem("StartTime") != null) - { - newTourStop.startTime = Date.Parse(tourStop.Attributes.GetNamedItem("StartTime").Value + " UTC"); - } - if (tourStop.Attributes.GetNamedItem("EndTime") != null) - { - newTourStop.endTime = Date.Parse(tourStop.Attributes.GetNamedItem("EndTime").Value + " UTC"); - } - } - } - - if (tourStop.Attributes.GetNamedItem("ActualPlanetScale") != null) - { - newTourStop.actualPlanetScale = bool.Parse(tourStop.Attributes.GetNamedItem("ActualPlanetScale").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowClouds") != null) - { - newTourStop.showClouds = bool.Parse(tourStop.Attributes.GetNamedItem("ShowClouds").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellationBoundries") != null) - { - newTourStop.showConstellationBoundries = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellationBoundries").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellationFigures") != null) - { - newTourStop.showConstellationFigures = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellationFigures").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellationSelection") != null) - { - newTourStop.showConstellationSelection = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellationSelection").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowEcliptic") != null) - { - newTourStop.showEcliptic = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEcliptic").Value); - } - if (tourStop.Attributes.GetNamedItem("EclipticColor") != null) - { - newTourStop.eclipticColor = Color.Load(tourStop.Attributes.GetNamedItem("EclipticColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowElevationModel") != null) - { - newTourStop.showElevationModel = bool.Parse(tourStop.Attributes.GetNamedItem("ShowElevationModel").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowFieldOfView") != null) - { - newTourStop.showFieldOfView = bool.Parse(tourStop.Attributes.GetNamedItem("ShowFieldOfView").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowGrid") != null) - { - newTourStop.showGrid = bool.Parse(tourStop.Attributes.GetNamedItem("ShowGrid").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowHorizon") != null) - { - newTourStop.showHorizon = bool.Parse(tourStop.Attributes.GetNamedItem("ShowHorizon").Value); - } - - - if (tourStop.Attributes.GetNamedItem("ShowHorizonPanorama") != null) - { - newTourStop.showHorizonPanorama = bool.Parse(tourStop.Attributes.GetNamedItem("ShowHorizonPanorama").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowMoonsAsPointSource") != null) - { - newTourStop.showMoonsAsPointSource = bool.Parse(tourStop.Attributes.GetNamedItem("ShowMoonsAsPointSource").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowSolarSystem") != null) - { - newTourStop.showSolarSystem = bool.Parse(tourStop.Attributes.GetNamedItem("ShowSolarSystem").Value); - } - - if (tourStop.Attributes.GetNamedItem("FovTelescope") != null) - { - newTourStop.fovTelescope = int.Parse(tourStop.Attributes.GetNamedItem("FovTelescope").Value); - } - - if (tourStop.Attributes.GetNamedItem("FovEyepiece") != null) - { - newTourStop.fovEyepiece = int.Parse(tourStop.Attributes.GetNamedItem("FovEyepiece").Value); - } - - if (tourStop.Attributes.GetNamedItem("FovCamera") != null) - { - newTourStop.fovCamera = int.Parse(tourStop.Attributes.GetNamedItem("FovCamera").Value); - } - - if (tourStop.Attributes.GetNamedItem("LocalHorizonMode") != null) - { - newTourStop.localHorizonMode = bool.Parse(tourStop.Attributes.GetNamedItem("LocalHorizonMode").Value); - } - - if (tourStop.Attributes.GetNamedItem("GalacticMode") != null) - { - newTourStop.galacticMode = bool.Parse(tourStop.Attributes.GetNamedItem("GalacticMode").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemStars") != null) - { - newTourStop.solarSystemStars = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemStars").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemMilkyWay") != null) - { - newTourStop.solarSystemMilkyWay = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemMilkyWay").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemCosmos") != null) - { - newTourStop.solarSystemCosmos = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemCosmos").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemOrbits") != null) - { - newTourStop.solarSystemOrbits = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemOrbits").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemOverlays") != null) - { - newTourStop.solarSystemOverlays = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemOverlays").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemLighting") != null) - { - newTourStop.solarSystemLighting = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemLighting").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemScale") != null) - { - newTourStop.solarSystemScale = int.Parse(tourStop.Attributes.GetNamedItem("SolarSystemScale").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemMultiRes") != null) - { - newTourStop.solarSystemMultiRes = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemMultiRes").Value); - } - - //new - if (tourStop.Attributes.GetNamedItem("ShowEquatorialGridText") != null) - { - newTourStop.showEquatorialGridText = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEquatorialGridText").Value); - } - if (tourStop.Attributes.GetNamedItem("EquatorialGridColor") != null) - { - newTourStop.equatorialGridColor = Color.Load(tourStop.Attributes.GetNamedItem("EquatorialGridColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowGalacticGrid") != null) - { - newTourStop.showGalacticGrid = bool.Parse(tourStop.Attributes.GetNamedItem("ShowGalacticGrid").Value); - } - if (tourStop.Attributes.GetNamedItem("ShowGalacticGridText") != null) - { - newTourStop.showGalacticGridText = bool.Parse(tourStop.Attributes.GetNamedItem("ShowGalacticGridText").Value); - } - if (tourStop.Attributes.GetNamedItem("GalacticGridColor") != null) - { - newTourStop.galacticGridColor = Color.Load(tourStop.Attributes.GetNamedItem("GalacticGridColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowEclipticGrid") != null) - { - newTourStop.showEclipticGrid = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEclipticGrid").Value); - } - if (tourStop.Attributes.GetNamedItem("ShowEclipticGridText") != null) - { - newTourStop.showEclipticGridText = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEclipticGridText").Value); - } - if (tourStop.Attributes.GetNamedItem("EclipticGridColor") != null) - { - newTourStop.eclipticGridColor = Color.Load(tourStop.Attributes.GetNamedItem("EclipticGridColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowEclipticOverviewText") != null) - { - newTourStop.showEclipticOverviewText = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEclipticOverviewText").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowAltAzGrid") != null) - { - newTourStop.showAltAzGrid = bool.Parse(tourStop.Attributes.GetNamedItem("ShowAltAzGrid").Value); - } - if (tourStop.Attributes.GetNamedItem("ShowAltAzGridText") != null) - { - newTourStop.showAltAzGridText = bool.Parse(tourStop.Attributes.GetNamedItem("ShowAltAzGridText").Value); - } - if (tourStop.Attributes.GetNamedItem("AltAzGridColor") != null) - { - newTourStop.altAzGridColor = Color.Load(tourStop.Attributes.GetNamedItem("AltAzGridColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowPrecessionChart") != null) - { - newTourStop.showPrecessionChart = bool.Parse(tourStop.Attributes.GetNamedItem("ShowPrecessionChart").Value); - } - if (tourStop.Attributes.GetNamedItem("PrecessionChartColor") != null) - { - newTourStop.precessionChartColor = Color.Load(tourStop.Attributes.GetNamedItem("PrecessionChartColor").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellationPictures") != null) - { - newTourStop.showConstellationPictures = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellationPictures").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellationLabels") != null) - { - newTourStop.showConstellationLabels = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellationLabels").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemCMB") != null) - { - newTourStop.solarSystemCMB = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemCMB").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemMinorPlanets") != null) - { - newTourStop.solarSystemMinorPlanets = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemMinorPlanets").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemPlanets") != null) - { - newTourStop.solarSystemPlanets = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemPlanets").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowEarthSky") != null) - { - newTourStop.showEarthSky = bool.Parse(tourStop.Attributes.GetNamedItem("ShowEarthSky").Value); - } - - if (tourStop.Attributes.GetNamedItem("SolarSystemMinorOrbits") != null) - { - newTourStop.solarSystemMinorOrbits = bool.Parse(tourStop.Attributes.GetNamedItem("SolarSystemMinorOrbits").Value); - } - - if (tourStop.Attributes.GetNamedItem("ShowSkyOverlays") != null) - { - newTourStop.showSkyOverlays = bool.Parse(tourStop.Attributes.GetNamedItem("ShowSkyOverlays").Value); - } - else - { - newTourStop.showSkyOverlays = true; - } - - if (tourStop.Attributes.GetNamedItem("ShowConstellations") != null) - { - newTourStop.showConstellations = bool.Parse(tourStop.Attributes.GetNamedItem("ShowConstellations").Value); - } - else - { - newTourStop.showConstellations = true; - } - - if (tourStop.Attributes.GetNamedItem("ShowSkyNode") != null) - { - newTourStop.showSkyNode = bool.Parse(tourStop.Attributes.GetNamedItem("ShowSkyNode").Value); - } - else - { - newTourStop.showSkyNode = true; - } - - if (tourStop.Attributes.GetNamedItem("ShowSkyGrids") != null) - { - newTourStop.showSkyGrids = bool.Parse(tourStop.Attributes.GetNamedItem("ShowSkyGrids").Value); - } - else - { - newTourStop.showSkyGrids = true; - } - - if (tourStop.Attributes.GetNamedItem("ShowSkyOverlaysIn3d") != null) - { - newTourStop.showSkyOverlaysIn3d = bool.Parse(tourStop.Attributes.GetNamedItem("ShowSkyOverlaysIn3d").Value); - } - - if (tourStop.Attributes.GetNamedItem("EarthCutawayView") != null) - { - newTourStop.earthCutawayView = bool.Parse(tourStop.Attributes.GetNamedItem("EarthCutawayView").Value); - } - if (tourStop.Attributes.GetNamedItem("ShowISSModel") != null) - { - newTourStop.showISSModel = bool.Parse(tourStop.Attributes.GetNamedItem("ShowISSModel").Value); - } - - if (tourStop.Attributes.GetNamedItem("MilkyWayModel") != null) - { - newTourStop.milkyWayModel = bool.Parse(tourStop.Attributes.GetNamedItem("MilkyWayModel").Value); - } - - if (tourStop.Attributes.GetNamedItem("ConstellationBoundariesFilter") != null) - { - newTourStop.constellationBoundariesFilter = ConstellationFilter.Parse(tourStop.Attributes.GetNamedItem("ConstellationBoundariesFilter").Value); - } - else - { - newTourStop.constellationBoundariesFilter = ConstellationFilter.AllConstellation; - } - - if (tourStop.Attributes.GetNamedItem("ConstellationBoundariesFilter") != null) - { - newTourStop.constellationFiguresFilter = ConstellationFilter.Parse(tourStop.Attributes.GetNamedItem("ConstellationBoundariesFilter").Value); - } - else - { - newTourStop.constellationFiguresFilter = new ConstellationFilter(); - } - - - if (tourStop.Attributes.GetNamedItem("ConstellationNamesFilter") != null) - { - newTourStop.constellationNamesFilter = ConstellationFilter.Parse(tourStop.Attributes.GetNamedItem("ConstellationNamesFilter").Value); - } - else - { - newTourStop.constellationNamesFilter = new ConstellationFilter(); - } - - if (tourStop.Attributes.GetNamedItem("ConstellationArtFilter") != null) - { - newTourStop.constellationArtFilter = ConstellationFilter.Parse(tourStop.Attributes.GetNamedItem("ConstellationArtFilter").Value); - } - else - { - newTourStop.constellationArtFilter = new ConstellationFilter(); - } - - if (tourStop.Attributes.GetNamedItem("MinorPlanetsFilter") != null) - { - newTourStop.minorPlanetsFilter = int.Parse(tourStop.Attributes.GetNamedItem("MinorPlanetsFilter").Value); - } - if (tourStop.Attributes.GetNamedItem("PlanetOrbitsFilter") != null) - { - newTourStop.planetOrbitsFilter = int.Parse(tourStop.Attributes.GetNamedItem("PlanetOrbitsFilter").Value); - } - - XmlNode place = Util.SelectSingleNode(tourStop, "Place"); - - newTourStop.target = Place.FromXml(place); - - XmlNode endTarget = Util.SelectSingleNode(tourStop, "EndTarget"); - if (endTarget != null) - { - newTourStop.endTarget = Place.FromXml(endTarget); - } - - XmlNode overlays = Util.SelectSingleNode(tourStop, "Overlays"); - - foreach (XmlNode overlay in overlays.ChildNodes) - { - //todo this might have issuse if all the childeren are not good - if (overlay.Name == "Overlay") - { - newTourStop.AddOverlay(Overlay.FromXml(newTourStop, overlay)); - } - } - - - XmlNode musicNode = Util.SelectSingleNode(tourStop, "MusicTrack"); - - if (musicNode != null) - { - newTourStop.musicTrack = (AudioOverlay)Overlay.FromXml(newTourStop, Util.SelectSingleNode(musicNode, "Overlay")); - } - - XmlNode voiceNode = Util.SelectSingleNode(tourStop, "VoiceTrack"); - - if (voiceNode != null) - { - newTourStop.voiceTrack = (AudioOverlay)Overlay.FromXml(newTourStop, Util.SelectSingleNode(voiceNode, "Overlay")); - } - - XmlNode layerNode = Util.SelectSingleNode(tourStop, "VisibleLayers"); - if (layerNode != null) - { - newTourStop.LoadLayerList(layerNode); - } - - //todo fix load thumbnail - //newTourStop.thumbnail = UiTools.LoadBitmap(string.Format("{0}{1}.thumb.png", newTourStop.owner.WorkingDirectory, newTourStop.id)); - newTourStop.thumbnail = owner.GetCachedTexture(string.Format("{0}.thumb.png", newTourStop.id), delegate { int c = 0; }); - return newTourStop; - } - catch (Exception ex) - { - WWTControl.scriptInterface.FireTourError(ex); - return null; - } - } - - public string GetNextDefaultName(string baseName) - { - int suffixId = 1; - foreach (Overlay overlay in overlays) - { - if (overlay.Name.StartsWith(baseName)) - { - int id = 0; - try - { - id = int.Parse(overlay.Name.Substr(baseName.Length)); - } - catch - { - } - - if (id >= suffixId) - { - suffixId = id + 1; - } - } - } - - return string.Format("{0} {1}", baseName, suffixId); - } - - private void LoadLayerList(XmlNode layersNode) - { - foreach (XmlNode layer in layersNode.ChildNodes) - { - if (layer.Name == "Layer") - { - LayerInfo info = new LayerInfo(); - string id = (string)Script.Literal("layer.innerHTML"); - info.ID = Guid.FromString(id); - info.StartOpacity = float.Parse(layer.Attributes.GetNamedItem("StartOpacity").Value); - info.EndOpacity = float.Parse(layer.Attributes.GetNamedItem("EndOpacity").Value); - - int len = 0; - if (layer.Attributes.GetNamedItem("ParamCount") != null) - { - len = int.Parse(layer.Attributes.GetNamedItem("ParamCount").Value); - } - info.StartParams = new double[len]; - info.EndParams = new double[len]; - info.FrameParams = new double[len]; - - for (int i = 0; i < len; i++) - { - info.StartParams[i] = double.Parse(layer.Attributes.GetNamedItem(string.Format("StartParam{0}", i)).Value); - info.EndParams[i] = double.Parse(layer.Attributes.GetNamedItem(string.Format("EndParam{0}", i)).Value); - info.FrameParams[i] = info.StartParams[i]; - } - - Layers[info.ID] = info; - } - } - } - - internal void UpdateLayerOpacity() - { - if (!KeyFramed) - { - //foreach (LayerInfo info in Layers.Values) - //{ - // info.FrameOpacity = info.StartOpacity * (1 - tweenPosition) + info.EndOpacity * tweenPosition; - // int len = info.StartParams.Length; - // info.FrameParams = new double[len]; - // for (int i = 0; i < len; i++) - // { - // info.FrameParams[i] = info.StartParams[i] * (1 - tweenPosition) + info.EndParams[i] * tweenPosition; - // } - - //} - } - else - { - UpdateTweenPosition(); - } - } - - - - - - // Start of new Settings - - - public bool ShowEquatorialGridText - { - get { return showEquatorialGridText; } - set { showEquatorialGridText = value; } - } - - public bool ShowGalacticGrid - { - get { return showGalacticGrid; } - set { showGalacticGrid = value; } - } - - - public bool ShowGalacticGridText - { - get { return showGalacticGridText; } - set { showGalacticGridText = value; } - } - public bool ShowEclipticGrid - { - get { return showEclipticGrid; } - set { showEclipticGrid = value; } - } - - - public bool ShowEclipticGridText - { - get { return showEclipticGridText; } - set { showEclipticGridText = value; } - } - - public bool ShowEclipticOverviewText - { - get { return showEclipticOverviewText; } - set { showEclipticOverviewText = value; } - } - - public bool ShowAltAzGrid - { - get { return showAltAzGrid; } - set { showAltAzGrid = value; } - } - - public bool ShowAltAzGridText - { - get { return showAltAzGridText; } - set { showAltAzGridText = value; } - } - - public bool ShowPrecessionChart - { - get { return showPrecessionChart; } - set { showPrecessionChart = value; } - } - - public bool ShowConstellationPictures - { - get { return showConstellationPictures; } - set { showConstellationPictures = value; } - } - - public bool ShowConstellationLabels - { - get { return showConstellationLabels; } - set { showConstellationLabels = value; } - } - - //public string ConstellationsEnabled = false; - - public bool SolarSystemCMB - { - get { return solarSystemCMB; } - set { solarSystemCMB = value; } - } - - public bool SolarSystemMinorPlanets - { - get { return solarSystemMinorPlanets; } - set { solarSystemMinorPlanets = value; } - } - - public bool SolarSystemPlanets - { - get { return solarSystemPlanets; } - set { solarSystemPlanets = value; } - } - - public bool ShowEarthSky - { - get { return showEarthSky; } - set { showEarthSky = value; } - } - - public bool SolarSystemMinorOrbits - { - get { return solarSystemMinorOrbits; } - set { solarSystemMinorOrbits = value; } - } - - public string ConstellationsEnabled - { - get { return constellationsEnabled; } - set { constellationsEnabled = value; } - } - - public ConstellationFilter ConstellationFiguresFilter - { - get { return constellationFiguresFilter; } - set { constellationFiguresFilter = value; } - } - - public ConstellationFilter ConstellationBoundariesFilter - { - get { return constellationBoundariesFilter; } - set { constellationBoundariesFilter = value; } - } - - public ConstellationFilter ConstellationNamesFilter - { - get { return constellationNamesFilter; } - set { constellationNamesFilter = value; } - } - - public ConstellationFilter ConstellationArtFilter - { - get { return constellationArtFilter; } - set { constellationArtFilter = value; } - } - - public bool ShowSkyOverlays - { - get { return showSkyOverlays; } - set { showSkyOverlays = value; } - } - public bool ShowConstellations - { - get { return showConstellations; } - set { showConstellations = value; } - } - - public bool ShowSkyNode - { - get { return showSkyNode; } - set { showSkyNode = value; } - } - - public bool ShowSkyGrids - { - get { return showSkyGrids; } - set { showSkyGrids = value; } - } - - public bool ShowSkyOverlaysIn3d - { - get { return showSkyOverlaysIn3d; } - set { showSkyOverlaysIn3d = value; } - } - - - public bool EarthCutawayView - { - get { return earthCutawayView; } - set { earthCutawayView = value; } - } - - public bool ShowISSModel - { - get { return showISSModel; } - set { showISSModel = value; } - } - - public bool MilkyWayModel - { - get { return milkyWayModel; } - set { milkyWayModel = value; } - } - - public int MinorPlanetsFilter - { - get { return minorPlanetsFilter; } - set { minorPlanetsFilter = value; } - } - - public int PlanetOrbitsFilter - { - get { return planetOrbitsFilter; } - set { planetOrbitsFilter = value; } - } - - public SettingParameter GetSetting(StockSkyOverlayTypes type) - { - if (type == StockSkyOverlayTypes.FadeToBlack) - { - return new SettingParameter(true, FaderOpacity, FaderOpacity != 0, null); - } - - return new SettingParameter(false,1,false,null); - } - - private Color eclipticGridColor = Colors.Green; - public Color EclipticGridColor - { - get { return eclipticGridColor; } - set { eclipticGridColor = value; } - } - - private Color galacticGridColor = Colors.Cyan; - public Color GalacticGridColor - { - get { return galacticGridColor; } - set { galacticGridColor = value; } - } - - private Color altAzGridColor = Colors.Magenta; - public Color AltAzGridColor - { - get { return altAzGridColor; } - set { altAzGridColor = value; } - } - - private Color precessionChartColor = Colors.Orange; - public Color PrecessionChartColor - { - get { return precessionChartColor; } - set { precessionChartColor = value; } - } - - private Color eclipticColor = Colors.Blue; - public Color EclipticColor - { - get { return eclipticColor; } - set { eclipticColor = value; } - } - - private Color equatorialGridColor = Colors.White; - public Color EquatorialGridColor - { - get { return equatorialGridColor; } - set { equatorialGridColor = value; } - } - - private int constellationLabelsHeight = 80; - public int ConstellationLabelsHeight - { - get { return constellationLabelsHeight; } - set { constellationLabelsHeight = value; } - } - } - - public class LayerInfo - { - public Guid ID = Guid.NewGuid(); - public float StartOpacity = 1; - public float EndOpacity = 1; - public float FrameOpacity = 1; - public double[] StartParams = new double[0]; - public double[] EndParams = new double[0]; - public double[] FrameParams = new double[0]; - } - - public interface IUndoStep - { - void Redo(); - string ToString(); - void Undo(); - } - - public class UndoTourStopChange : IUndoStep - { - string undoXml = ""; - string redoXml = ""; - int currentIndex = 0; - string actionText = ""; - - public string ActionText - { - get { return actionText; } - set { actionText = value; } - } - TourDocument targetTour = null; - public UndoTourStopChange(string text, TourDocument tour) - { - currentIndex = tour.CurrentTourstopIndex; - actionText = text; - targetTour = tour; - undoXml = TourStop.GetXmlText(tour.CurrentTourStop); - targetTour.TourDirty = true; - - } - - public void Undo() - { - TourStop tsRedo = targetTour.TourStops[currentIndex]; - XmlDocumentParser parser = new XmlDocumentParser(); - - XmlDocument doc = parser.ParseFromString(undoXml, "text/xml"); - - - XmlNode node = Util.SelectSingleNode(doc, "TourStop"); - targetTour.TourStops[currentIndex] = TourStop.FromXml(targetTour, node); - targetTour.CurrentTourstopIndex = currentIndex; - - - // Setup redo - if (string.IsNullOrEmpty(redoXml)) - { - redoXml = TourStop.GetXmlText(tsRedo); - } - targetTour.TourDirty = true; - - } - - public void Redo() - { - XmlDocumentParser parser = new XmlDocumentParser(); - XmlDocument doc = parser.ParseFromString(redoXml, "text/xml"); - XmlNode node = Util.SelectSingleNode(doc, "TourStop"); - targetTour.TourStops[currentIndex] = TourStop.FromXml(targetTour, node); - targetTour.CurrentTourstopIndex = currentIndex; - targetTour.TourDirty = true; - } - - override public string ToString() - { - return actionText; - } - } -} diff --git a/engine/csharp_ref/Tours/Undo.cs b/engine/csharp_ref/Tours/Undo.cs deleted file mode 100644 index 9a8e18dc..00000000 --- a/engine/csharp_ref/Tours/Undo.cs +++ /dev/null @@ -1,259 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class Undo - { - static Stack undoStack = new Stack(); - static Stack redoStack = new Stack(); - - public static void Clear() - { - undoStack = new Stack(); - redoStack = new Stack(); - } - - public static void Push(IUndoStep step) - { - undoStack.Push(step); - redoStack = new Stack(); - } - - public static string PeekActionString() - { - if (undoStack.Count > 0) - { - return undoStack.Peek().ToString(); - } - else - { - //todo localize - return Language.GetLocalizedText(551, "Nothing to Undo"); - } - } - - public static string PeekRedoActionString() - { - if (redoStack.Count > 0) - { - return redoStack.Peek().ToString(); - } - else - { - return ""; - } - } - - public static bool PeekAction() - { - return (undoStack.Count > 0); - } - - public static bool PeekRedoAction() - { - return (redoStack.Count > 0); - } - - public static void StepBack() - { - IUndoStep step = undoStack.Pop(); - - step.Undo(); - - redoStack.Push(step); - } - - public static void StepForward() - { - IUndoStep step = redoStack.Pop(); - - step.Redo(); - - undoStack.Push(step); - } - } - - public class UndoStep : IUndoStep - { - public UndoStep() - { - } - public void Undo() - { - } - public void Redo() - { - } - override public string ToString() - { - //todo localize - return Language.GetLocalizedText(551, "Nothing to Undo"); - } - } - - public class UndoTourSlidelistChange : IUndoStep - { - List undoList; - List redoList; - - int currentIndex = 0; - string actionText = ""; - - public string ActionText - { - get { return actionText; } - set { actionText = value; } - } - TourDocument targetTour = null; - public UndoTourSlidelistChange(string text, TourDocument tour) - { - undoList = new List(); - - for (int i = 0; i < tour.TourStops.Count; i++) - { - undoList.Add(tour.TourStops[i]); - } - - currentIndex = tour.CurrentTourstopIndex; - actionText = text; - targetTour = tour; - targetTour.TourDirty = true; - } - - public void Undo() - { - - redoList = targetTour.TourStops; - targetTour.TourStops = undoList; - targetTour.CurrentTourstopIndex = currentIndex; - targetTour.TourDirty = true; - - } - - public void Redo() - { - undoList = targetTour.TourStops; - targetTour.TourStops = redoList; - targetTour.CurrentTourstopIndex = currentIndex; - targetTour.TourDirty = true; - } - - override public string ToString() - { - return actionText; - } - } - - public class UndoTourPropertiesChange : IUndoStep - { - - string actionText = ""; - - public string ActionText - { - get { return actionText; } - set { actionText = value; } - } - TourDocument targetTour = null; - string undoTitle; - string undoAuthor; - string undoAuthorEmail; - string undoDescription; - ImageElement undoAuthorImage; - string undoOrganizationUrl; - string undoOrgName; - string undoKeywords; - string undoTaxonomy; - bool undoDomeMode; - UserLevel undoLevel; - string redoTitle; - string redoAuthor; - string redoAuthorEmail; - string redoDescription; - ImageElement redoAuthorImage; - string redoOrganizationUrl; - string redoOrgName; - string redoKeywords; - string redoTaxonomy; - bool redoDomeMode; - UserLevel redoLevel; - public UndoTourPropertiesChange(string text, TourDocument tour) - { - undoTitle = tour.Title; - undoAuthor = tour.Author; - undoAuthorEmail = tour.AuthorEmail; - undoDescription = tour.Description; - undoAuthorImage = tour.AuthorImage; - undoOrganizationUrl = tour.OrganizationUrl; - undoOrgName = tour.OrgName; - undoKeywords = tour.Keywords; - undoTaxonomy = tour.Taxonomy; - undoLevel = tour.Level; - // undoDomeMode = tour.DomeMode; - - actionText = text; - targetTour = tour; - targetTour.TourDirty = true; - } - - public void Undo() - { - redoTitle = targetTour.Title; - redoAuthor = targetTour.Author; - redoAuthorEmail = targetTour.AuthorEmail; - redoDescription = targetTour.Description; - redoAuthorImage = targetTour.AuthorImage; - redoOrganizationUrl = targetTour.OrganizationUrl; - redoOrgName = targetTour.OrgName; - redoKeywords = targetTour.Keywords; - redoTaxonomy = targetTour.Taxonomy; - redoLevel = targetTour.Level; - // redoDomeMode = targetTour.DomeMode; - - targetTour.Title = undoTitle; - targetTour.Author = undoAuthor; - targetTour.AuthorEmail = undoAuthorEmail; - targetTour.Description = undoDescription; - targetTour.AuthorImage = undoAuthorImage; - targetTour.OrganizationUrl = undoOrganizationUrl; - targetTour.OrgName = undoOrgName; - targetTour.Keywords = undoKeywords; - targetTour.Taxonomy = undoTaxonomy; - targetTour.Level = undoLevel; - // targetTour.DomeMode = undoDomeMode; - targetTour.TourDirty = true; - - - } - - public void Redo() - { - targetTour.Title = redoTitle; - targetTour.Author = redoAuthor; - targetTour.AuthorEmail = redoAuthorEmail; - targetTour.Description = redoDescription; - targetTour.AuthorImage = redoAuthorImage; - targetTour.OrganizationUrl = redoOrganizationUrl; - targetTour.OrgName = redoOrgName; - targetTour.Keywords = redoKeywords; - targetTour.Taxonomy = redoTaxonomy; - targetTour.Level = redoLevel; - targetTour.TourDirty = true; - // targetTour.DomeMode = redoDomeMode; - - - } - - override public string ToString() - { - return actionText; - } - } - - -} diff --git a/engine/csharp_ref/Triangle.cs b/engine/csharp_ref/Triangle.cs deleted file mode 100644 index 2a458e35..00000000 --- a/engine/csharp_ref/Triangle.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - class Triangle - { - // Vertex Indexies - public int A; - public int B; - public int C; - - public static Triangle Create(int a, int b, int c) - { - Triangle temp = new Triangle(); - temp.A = a; - temp.B = b; - temp.C = c; - return temp; - } - - public Triangle() - { - A = -1; - B = -1; - C = -1; - } - - public void SubDivide(List triList, List vertexList) - { - Vector3d a1 = Vector3d.Lerp(vertexList[B].Position, vertexList[C].Position, .5f); - Vector3d b1 = Vector3d.Lerp(vertexList[C].Position, vertexList[A].Position, .5f); - Vector3d c1 = Vector3d.Lerp(vertexList[A].Position, vertexList[B].Position, .5f); - - Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(vertexList[B].Tu, vertexList[B].Tv), Vector2d.Create(vertexList[C].Tu, vertexList[C].Tv), .5f); - Vector2d b1uv = Vector2d.Lerp(Vector2d.Create(vertexList[C].Tu, vertexList[C].Tv), Vector2d.Create(vertexList[A].Tu, vertexList[A].Tv), .5f); - Vector2d c1uv = Vector2d.Lerp(Vector2d.Create(vertexList[A].Tu, vertexList[A].Tv), Vector2d.Create(vertexList[B].Tu, vertexList[B].Tv), .5f); - - a1.Normalize(); - b1.Normalize(); - c1.Normalize(); - - int aIndex = vertexList.Count; - int bIndex = vertexList.Count + 1; - int cIndex = vertexList.Count + 2; - - vertexList.Add(PositionTexture.CreatePosRaw(a1, a1uv.X, a1uv.Y)); - vertexList.Add(PositionTexture.CreatePosRaw(b1, b1uv.X, b1uv.Y)); - vertexList.Add(PositionTexture.CreatePosRaw(c1, c1uv.X, c1uv.Y)); - - triList.Add(Triangle.Create(A, cIndex, bIndex)); - triList.Add(Triangle.Create(B, aIndex, cIndex)); - triList.Add(Triangle.Create(C, bIndex, aIndex)); - triList.Add(Triangle.Create(aIndex, bIndex, cIndex)); - } - - public void SubDivideNoNormalize(List triList, List vertexList) - { - Vector3d a1 = Vector3d.Lerp(vertexList[B].Position, vertexList[C].Position, .5f); - Vector3d b1 = Vector3d.Lerp(vertexList[C].Position, vertexList[A].Position, .5f); - Vector3d c1 = Vector3d.Lerp(vertexList[A].Position, vertexList[B].Position, .5f); - - Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(vertexList[B].Tu, vertexList[B].Tv), Vector2d.Create(vertexList[C].Tu, vertexList[C].Tv), .5f); - Vector2d b1uv = Vector2d.Lerp(Vector2d.Create(vertexList[C].Tu, vertexList[C].Tv), Vector2d.Create(vertexList[A].Tu, vertexList[A].Tv), .5f); - Vector2d c1uv = Vector2d.Lerp(Vector2d.Create(vertexList[A].Tu, vertexList[A].Tv), Vector2d.Create(vertexList[B].Tu, vertexList[B].Tv), .5f); - - //a1.Normalize(); - //b1.Normalize(); - //c1.Normalize(); - - int aIndex = vertexList.Count; - int bIndex = vertexList.Count + 1; - int cIndex = vertexList.Count + 2; - - vertexList.Add(PositionTexture.CreatePosRaw(a1, a1uv.X, a1uv.Y)); - vertexList.Add(PositionTexture.CreatePosRaw(b1, b1uv.X, b1uv.Y)); - vertexList.Add(PositionTexture.CreatePosRaw(c1, c1uv.X, c1uv.Y)); - - triList.Add(Triangle.Create(A, cIndex, bIndex)); - triList.Add(Triangle.Create(B, aIndex, cIndex)); - triList.Add(Triangle.Create(C, bIndex, aIndex)); - triList.Add(Triangle.Create(aIndex, bIndex, cIndex)); - } - } -} - diff --git a/engine/csharp_ref/URLHelpers.cs b/engine/csharp_ref/URLHelpers.cs deleted file mode 100644 index fc463127..00000000 --- a/engine/csharp_ref/URLHelpers.cs +++ /dev/null @@ -1,379 +0,0 @@ - -// The helper class for rewriting URLs. This gets complicated, because we -// might need to proxy for CORS headers and/or HTTPS support, *and* we -// sometimes also want to change the host and/or path to allow the engine or -// the webclient to swap out the data backend or the frontend. - -using System; -using System.Collections.Generic; - -namespace wwtlib -{ - enum DomainHandling - { - WWTFlagship = 0, // this host is worldwidetelescope.org or an equivalent - Localhost = 1, // this host is localhost or an equivalent - NeverProxy = 2, // this host is known to never need proxying - TryNoProxy = 3, // none of the above, and we hope that we can get data from it without needing to use our proxy - Proxy = 4, // none of the above, and we need to proxy it for HTTPS/CORS reasons - } - - public enum URLRewriteMode - { - AsIfAbsolute = 0, // act as if this URL is absolute even if it is missing a domain - OriginRelative = 1, // if this URL is relative, treat it as relative to the browser origin - } - - public class URLHelpers - { - String origin_protocol; // this will be "http:" or "https:" - String origin_domain; // host name, no port number - bool force_https; - String engine_asset_baseurl; // baseurl for webgl engine static assets - String core_static_baseurl; // baseurl for core static assets: NB, includes things like wwt.o/wwtweb/dss.aspx - String core_dynamic_baseurl; // baseurl for core dynamic services - Dictionary domain_handling; - - // Note: I wanted to use a HashSet here, but that made ScriptSharp crash without giving - // an explicit error message of any kind. Oh well. - Dictionary flagship_static_lcpaths; - - public URLHelpers() { - this.origin_protocol = (string) Script.Literal("typeof window === \"undefined\" ? \"https:\" : window.location.protocol"); - this.origin_domain = (string)Script.Literal("typeof window === \"undefined\" ? \"\" :window.location.hostname"); - this.force_https = (this.origin_protocol == "https:"); - - this.domain_handling = new Dictionary(); - this.domain_handling["worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["www.worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["cdn.worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["content.worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["beta.worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["beta-cdn.worldwidetelescope.org"] = DomainHandling.WWTFlagship; - this.domain_handling["wwtstaging.azurewebsites.net"] = DomainHandling.WWTFlagship; - - this.domain_handling["wwtfiles.blob.core.windows.net"] = DomainHandling.NeverProxy; - this.domain_handling["wwttiles.blob.core.windows.net"] = DomainHandling.NeverProxy; - this.domain_handling["web.wwtassets.org"] = DomainHandling.NeverProxy; - this.domain_handling["data1.wwtassets.org"] = DomainHandling.NeverProxy; - - this.domain_handling["localhost"] = DomainHandling.Localhost; - this.domain_handling["127.0.0.1"] = DomainHandling.Localhost; - - switch (this.origin_domain) - { - case "worldwidetelescope.org": - case "www.worldwidetelescope.org": - case "cdn.worldwidetelescope.org": - this.core_static_baseurl = this.origin_protocol + "//cdn.worldwidetelescope.org"; - this.core_dynamic_baseurl = this.origin_protocol + "//worldwidetelescope.org"; - break; - - case "beta.worldwidetelescope.org": - case "beta-cdn.worldwidetelescope.org": - this.core_static_baseurl = this.origin_protocol + "//beta-cdn.worldwidetelescope.org"; - this.core_dynamic_baseurl = this.origin_protocol + "//beta.worldwidetelescope.org"; - break; - - default: - this.core_static_baseurl = this.origin_protocol + "//cdn.worldwidetelescope.org"; - this.core_dynamic_baseurl = this.origin_protocol + "//worldwidetelescope.org"; - break; - } - - this.engine_asset_baseurl = this.origin_protocol + "//web.wwtassets.org/engine/assets"; - - this.flagship_static_lcpaths = new Dictionary(); - this.flagship_static_lcpaths["/wwtweb/2massoct.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/bingdemtile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/bingdemtile2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/catalog.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/catalog2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/dem.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/dembath.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/demmars.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/demtile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/dss.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/dsstoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/dusttoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/earthblend.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/earthmerbath.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/fixedaltitudedemtile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/g360.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/galex4far.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/galex4near.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/galextoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/gettile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/gettour.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/gettourfile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/gettours.aspx"] = true; // maybe not? - this.flagship_static_lcpaths["/wwtweb/glimpse.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/halphatoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/hirise.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/hirisedem2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/hirisedem3.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/jupiter.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/mandel.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/mandel1.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/mars.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/marsdem.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/marshirise.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/marsmoc.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/martiantile.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/martiantile2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/mipsgal.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/moondem.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/moonoct.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/moontoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/moontoastdem.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/postmars.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/postmarsdem.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/postmarsdem2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/rasstoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/sdsstoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/sdsstoast2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/sdsstoast2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/thumbnail.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/tiles.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/tiles2.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/tilesthumb.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/twomasstoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/tychooct.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/veblend.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/vlsstoast.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/wmap.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/wmsmoon.aspx"] = true; - this.flagship_static_lcpaths["/wwtweb/wmstoast.aspx"] = true; - } - - public void overrideAssetBaseurl(String baseurl) { - this.engine_asset_baseurl = baseurl; - } - - public String rewrite(String url, URLRewriteMode rwmode) { - // Sadly, we can't take advantage of JS/browser URL parsing - // because this function might be passed template URLs like - // "http://r{S:2}.ortho.tiles.virtualearth.net/..." that won't - // parse. So we have to split up the URL manually. - - string lc = url.ToLowerCase(); - string lcproto; - string url_no_protocol; - - if (lc.StartsWith("http://")) { - lcproto = "http:"; - url_no_protocol = url.Substring(7); - } else if (lc.StartsWith("https://")) { - lcproto = "https:"; - url_no_protocol = url.Substring(8); - } else if (lc.StartsWith("//")) { - lcproto = ""; - url_no_protocol = url.Substring(2); - } else if (lc.StartsWith("blob:")) { - // The web client uses URL.createObjectURL() to ingest local - // disk files into the web app. That function creates blob - // URLs, and it turns out that we definitely don't want to - // rewrite them! - return url; - } else { - switch (rwmode) { - case URLRewriteMode.AsIfAbsolute: - default: - // Treat `foo/bar` as a domain name of `foo` and a - // path of `/bar`. Really we should demand that the - // caller always pass us an absolute URL, but URLs - // will be coming from random data sources and we're - // not currently rigorous enough to guarantee that - // this function will get validated inputs -- and in - // such cases, throwing exceptions won't help. - lcproto = ""; - url_no_protocol = url; - break; - - case URLRewriteMode.OriginRelative: - // Treat `foo/bar` as a URL relative to the window - // origin. Since it looks relative, any weird - // templating stuff in the URL text *ought* not cause - // problems for the browser URL parsing ... - url = (String) Script.Literal("(new URL({0}, window.location.href)).toString()", url); - return this.rewrite(url, URLRewriteMode.AsIfAbsolute); - } - } - - // If we're freestanding, we can't use the proxy and we don't want - // to forcibly rewrite URLs to potentially point at any core WWT - // domains, so there is nothing more to do (now that we've potentially - // handled origin-relative URLs). - if (WWTControl.Singleton.FreestandingMode) { - return url; - } - - string domain; - string rest; // potentially "/foo/CASE/bar?q=1&b=1#fragment" - int slash_index = url_no_protocol.IndexOf('/'); - - if (slash_index < 0) { - domain = url_no_protocol; - rest = "/"; - } else { - domain = url_no_protocol.Substring(0, slash_index); - rest = url_no_protocol.Substring(slash_index); // starts with "/" - } - - string lcdomain = domain.ToLowerCase(); - string lcpath = rest.ToLowerCase().Split('?')[0]; - - if (!this.domain_handling.ContainsKey(lcdomain)) { - // Domains include nonstandard port specifications, so it's - // possible that we could get here with a discernably - // localhost-y domain. - if (lcdomain.StartsWith("localhost:") || lcdomain.StartsWith("127.0.0.1:")) - this.domain_handling[lcdomain] = DomainHandling.Localhost; - else - this.domain_handling[lcdomain] = DomainHandling.TryNoProxy; - } - - DomainHandling mode = this.domain_handling[lcdomain]; - - switch (mode) - { - case DomainHandling.Localhost: - return url; // can't proxy, so we'll just have to hope it works - - case DomainHandling.NeverProxy: - case DomainHandling.TryNoProxy: - default: - if (this.force_https && lcproto != "https:") { - // Force HTTPS and we'll see what happens. If - // downloading fails, we'll set a flag and use our - // proxy to launder the security. - // - // NOTE: it is important that we use `domain` and not - // `lcdomain`, even though domain names are - // case-insensitive, because we might be processing a - // template URL containing text like `{S}`, and WWT's - // replacements *are* case-sensitive. Yes, I did learn - // this the hard way. - return "https://" + domain + rest; - } - return url; - - case DomainHandling.Proxy: - if (lcproto == "") { - // Make sure that we give the proxy a real absolute - // URL. Guess http, and if the proxy is forced to - // upgrade, so be it. - url = "http://" + url; - } - - // We need to encode the URL as a query-string parameter - // to pass to the proxy. However, the encoding will turn - // "{}" into "%7B%7D", so that *if* this URL is then going - // to be fed into the templating system, - // search-and-replace for e.g. "{0}" will break. So we - // un-encode those particular characters, since it ought - // to be safe to do so anyway. - url = url.EncodeUriComponent().Replace("%7B", "{").Replace("%7D", "}"); - - return this.core_dynamic_baseurl + "/webserviceproxy.aspx?targeturl=" + url; - - case DomainHandling.WWTFlagship: - // Rewrite "flagship"/core URLs to go through whatever our - // core bases are. Assume that URLs are dynamic (=> are - // not loaded through the CDN) unless proven otherwise. - bool is_static = false; - - if (lcpath.StartsWith("/data/")) { - is_static = true; - } else if (this.flagship_static_lcpaths.ContainsKey(lcpath)) { - is_static = true; - } else if (lcpath.StartsWith("/content/")) { - is_static = true; - } else if (lcpath.StartsWith("/engine/assets/")) { - is_static = true; - } - - if (is_static) - return this.core_static_baseurl + rest; - return this.core_dynamic_baseurl + rest; - } - } - - // Call this when you have tried to load a url via XMLHttpRequest or - // something along those lines, and the attempt has failed. We will mark the - // domain as needing proxying, and will return a new proxy-enabled URL to try. - // The exception is for flagship website URLs, which we know that the proxy - // won't help with. For those, null is returned. - public string activateProxy(string url) { - // If we're freestanding, we never proxy. - if (WWTControl.Singleton.FreestandingMode) { - return null; - } - - // Get the domain. XXX copy/pastey from the above. - - string lc = url.ToLowerCase(); - string url_no_protocol; - - if (lc.StartsWith("http://")) { - url_no_protocol = url.Substring(7); - } else if (lc.StartsWith("https://")) { - url_no_protocol = url.Substring(8); - } else if (lc.StartsWith("//")) { - url_no_protocol = url.Substring(2); - } else { - url_no_protocol = url; - } - - string lcdomain; - int slash_index = url_no_protocol.IndexOf('/'); - - if (slash_index < 0) { - lcdomain = url_no_protocol; - } else { - lcdomain = url_no_protocol.Substring(0, slash_index).ToLowerCase(); - } - - // Is this a flagship or never-proxy URL? If so, don't bother proxying. - - if (!this.domain_handling.ContainsKey(lcdomain)) { - if (lcdomain.StartsWith("localhost:") || lcdomain.StartsWith("127.0.0.1:")) - this.domain_handling[lcdomain] = DomainHandling.Localhost; - else - this.domain_handling[lcdomain] = DomainHandling.TryNoProxy; - } - - DomainHandling mode = this.domain_handling[lcdomain]; - - if (mode == DomainHandling.WWTFlagship || mode == DomainHandling.NeverProxy || mode == DomainHandling.Localhost) { - return null; - } - - // OK, we should try proxying. So: - - this.domain_handling[lcdomain] = DomainHandling.Proxy; - return this.rewrite(url, URLRewriteMode.AsIfAbsolute); - } - - public string engineAssetUrl(string subpath) - { - return String.Format("{0}/{1}", this.engine_asset_baseurl, subpath); - } - - public string coreDynamicUrl(string subpath) - { - return String.Format("{0}/{1}", this.core_dynamic_baseurl, subpath); - } - - public string coreStaticUrl(string subpath) - { - return String.Format("{0}/{1}", this.core_static_baseurl, subpath); - } - - public static URLHelpers singleton; - - static URLHelpers() { - singleton = new URLHelpers(); - } - } -} diff --git a/engine/csharp_ref/UiTools.cs b/engine/csharp_ref/UiTools.cs deleted file mode 100644 index e82ead8a..00000000 --- a/engine/csharp_ref/UiTools.cs +++ /dev/null @@ -1,221 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - public class UiTools - { - public static int Gamma(int val, float gamma) - { - return (byte)Math.Min(255, (int)((255.0 * Math.Pow(val / 255.0, 1.0 / gamma)) + 0.5)); - } - - static public string GetNamesStringFromArray(string[] array) - { - string names = ""; - string delim = ""; - foreach (string name in array) - { - names += delim; - names += name; - delim = ";"; - } - return names; - } - - public const double KilometersPerAu = 149598000; - public const double AuPerParsec = 206264.806; - public const double AuPerLightYear = 63239.6717; - public const double SSMUnitConversion = 370; // No idea where this fudge factors comes from - public static double SolarSystemToMeters(double SolarSystemCameraDistance) - { - return SolarSystemCameraDistance * UiTools.KilometersPerAu * SSMUnitConversion; - } - - public static double MetersToSolarSystemDistance(double meters) - { - return meters / SSMUnitConversion * UiTools.KilometersPerAu; - } - - - public static double MetersToZoom(double meters) - { - return ((meters / 1000 / SSMUnitConversion) - 0.000001) / 4 * 9; - } - - // Distance is stored in AU in WWT but is displayed in KM AU, LY, MPC - public static string FormatDistance(double distance) - { - - if (distance < .1) - { - // Kilometers - double km = (distance * KilometersPerAu); - - if (km < 10) - { - double m = (int)(km * 1000); - return String.Format("{0} m", m); - } - else - { - km = (int)km; - return String.Format("{0} km",km); - } - } - else if (distance < (10)) - { - //Units in u - double au = ((int)(distance * 10)) / 10.0; - return String.Format("{0} au",au); - } - else if (distance < (AuPerLightYear / 10.0)) - { - //Units in u - double au = (int)(distance); - return String.Format("{0} au",au); - } - else if (distance < (AuPerLightYear * 10)) - { - // Units in lightyears - double ly = ((int)((distance * 10) / AuPerLightYear)) / 10.0; - return String.Format("{0} ly",ly); - } - else if (distance < (AuPerLightYear * 1000000)) - { - // Units in lightyears - double ly = ((int)((distance) / AuPerLightYear)); - return String.Format("{0} ly",ly); - } - else if (distance < (AuPerParsec * 10000000)) - { - double mpc = ((int)((distance * 10) / (AuPerParsec * 1000000.0))) / 10.0; - return String.Format("{0} Mpc", mpc); - } - else if (distance < (AuPerParsec * 1000000000)) - { - double mpc = ((int)((distance) / (AuPerParsec * 1000000.0))); - return String.Format("{0} Mpc",mpc); - } - else - { - double mpc = ((int)((distance * 10) / (AuPerParsec * 1000000000.0))) / 10.0; - return String.Format("{0} Gpc",mpc); - } - } - public static string FormatDecimalHours(double dayFraction) - { - Date today = Date.Now; - - double ts = today.GetTimezoneOffset() / 60; - ts = 0; - double day = (dayFraction - ts) + 0.0083333334; - while (day > 24) - { - day -= 24; - } - while (day < 0) - { - day += 24; - } - int hours = (int)day; - int minutes = (int)((day * 60.0) - ((double)hours * 60.0)); - int seconds = (int)((day * 3600) - (((double)hours * 3600) + ((double)minutes * 60.0))); - - return string.Format("{0}:{1}", hours, minutes, seconds); - //return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds); - } - - public static List SplitString(string data, string delimiter) - { - - List output = new List(); - - int nestingLevel = 0; - - int current = 0; - int count = 0; - int start = 0; - - while (current < data.Length) - { - if (data.Substr(current, 1) == "(") - { - nestingLevel++; - } - if (data.Substr(current, 1) == ")") - { - nestingLevel--; - } - if (current == (data.Length - 1)) - { - if (data.Substr(current, 1) == delimiter) - { - output.Add(data.Substr(start, count)); - output.Add(""); - return output; - } - else - { - count++; - } - } - - if (current == (data.Length - 1) || (data.Substr(current, 1) == delimiter && delimiter == "\t") || (nestingLevel == 0 && data.Substr(current, 1) == delimiter)) - { - output.Add(data.Substr(start, count)); - start = current + 1; - count = 0; - } - else - { - count++; - } - current++; - } - - return output; - } - - public static List Split(string data, string delimiters) - { - - List output = new List(); - - int nestingLevel = 0; - - int current = 0; - int count = 0; - int start = 0; - - while (current < data.Length) - { - - if (current == (data.Length - 1)) - { - count++; - } - - if (current == (data.Length - 1) || delimiters.IndexOf(data.Substr(current, 1)) > -1 ) - { - output.Add(data.Substr(start, count)); - start = current + 1; - count = 0; - } - else - { - count++; - } - current++; - } - - return output; - } - - internal static void Beep() - { - } - } -} diff --git a/engine/csharp_ref/Util.cs b/engine/csharp_ref/Util.cs deleted file mode 100644 index af49c8eb..00000000 --- a/engine/csharp_ref/Util.cs +++ /dev/null @@ -1,1805 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Html; -using System.Runtime.CompilerServices; -using System.Html.Media.Graphics; -using System.Xml; - -namespace wwtlib -{ - public class Util - { - public static string[] SplitString(string target, char[] split) - { - List parts = new List(); - int start = 0; - int end = 0; - - for(int i =0; i < target.Length; i++) - { - bool found = false; - - for(int j = 0; j < split.Length; j++) - { - if (target[i] == split[j]) - { - parts.Add(target.Substring(start, end - start)); - found = true; - continue; - } - start = i + 1; - end = i + 1; - } - - if (!found) - { - end++; - } - } - - if (end > start) - { - parts.Add(target.Substring(start, end - start)); - } - - return parts; - } - - public static bool StringContains(string target, char[] chars) - { - for (int i = 0; i < chars.Length; i++) - { - if (target.IndexOf(chars[i].ToString()) > -1) - { - return true; - } - } - - return false; - } - - public static int GetHashCode(string target) - { - int hash = 0; - - if (target.Length == 0) - { - return hash; - } - - for (int i = 0; i < target.Length; i++) - { - int c = target.CharCodeAt(i); - hash = ((hash << 5) - hash) + c; - } - return hash; - - } - - public static int Compare(int l, int r) - { - if (l==r) - { - return 0; - } - if (l > r) - { - return 1; - } - - return -1; - - } - - public static double LogN(double num, double b) - { - return Math.Log(num) / Math.Log(b); - } - - // Parse timespan into int with milliseconds - public static int ParseTimeSpan(string timespan) - { - int val = 0; - - string[] parts = timespan.Split(":"); - - if (parts.Length == 3) - { - val += int.Parse(parts[0]) * 3600000; - val += int.Parse(parts[1]) * 60000; - val += (int)(double.Parse(parts[2]) * 1000); - } - return val; - } - - // convert duration to HH:MM:SS.S - public static string XMLDuration(int duration) - { - double s = duration / 1000.0; - - int hours = Math.Floor(s / 3600); - int min = Math.Floor(s / 60) - (hours * 60); - double sec = (s) - ((hours * 3600) + min * 60); - - return string.Format("{0}:{1}:{2}", hours, min, sec); - } - - public static string XMLDate(Date d) - { - int hours = d.GetHours(); - string amPm = "AM"; - if (hours > 12) - { - hours -= 12; - amPm = "PM"; - } - - return (d.GetMonth() + 1).ToString() + '/' + - d.GetDate().ToString() + '/' + - d.GetFullYear().ToString() + ' ' + - hours.ToString() + ":" + - d.GetMinutes().ToString() + ":" + - d.GetSeconds().ToString() + " " + - amPm; - } - - public static XmlNode SelectSingleNode(XmlNode parent, string name) - { - //XmlNode - XmlNode node = null; - - //try - //{ - // node = parent.QuerySelector(name); - //} - //catch - //{ - foreach (XmlNode child in parent.ChildNodes) - { - if (child.Name == name) - { - node = child; - break; - } - } - //} - - return node; - } - - public static string GetInnerText(XmlNode node) - { - - if (string.IsNullOrEmpty(node.InnerText)) - { - ChromeNode cn = (ChromeNode)(object)node; - return cn.TextContent; - } - else - { - return node.InnerText; - } - } - - public static List GetWrappedText(CanvasContext2D ctx, string text, double width) - { - List lines = new List(); - lines.Add(text); - return lines; - - - //string[] words = text.Split(" "); - - //string currentLine = ""; - - //for (int i = 0; i < words.Length; i++) - //{ - // if (!string.IsNullOrEmpty(words[i])) - // { - // if (currentLine == "" || ctx.MeasureText(currentLine + " " + words[i]).Width < width) - // { - // currentLine += " " + words[i]; - // } - // else - // { - // lines.Add(currentLine); - // currentLine = words[i]; - // } - // } - //} - //if (currentLine != "") - //{ - // lines.Add(currentLine); - //} - - - //return lines; - } - - public static string ToHex(double number) - { - int num = Math.Max(0, Math.Min((int)number, 255)); - return "0123456789ABCDEF".Substr((num - num % 16) / 16, 1) + "0123456789ABCDEF".Substr(num % 16, 1); - - } - - public static int FromHex(string data) - { - int val = 0; - - - switch (data.Substr(1, 1).ToUpperCase()) - { - case "A": - val += 10; - break; - case "B": - - val += 11; - break; - case "C": - val += 12; - break; - case "D": - val += 13; - break; - case "E": - val += 14; - break; - case "F": - val += 15; - break; - default: - val += int.Parse(data.Substr(1, 1)); - break; - } - switch (data.Substr(0, 1).ToUpperCase()) - { - case "A": - val += 10 * 16; - break; - case "B": - val += 11 * 16; - break; - case "C": - val += 12 * 16; - break; - case "D": - val += 13 * 16; - break; - case "E": - val += 14 * 16; - break; - case "F": - val += 15 * 16; - break; - default: - val += int.Parse(data.Substr(0, 1)) * 16; - break; - } - - return val; - - } - internal static void OpenUrl(string url) - { - Window.Open(url); - } - - - public static double Log10(double num) - { - return Math.Log(num) / 2.302585092994046; - } - - public static double Sign(double num) - { - if (num < 0) - { - return -1; - } - return 1; - } - } - - public class Rectangle - { - public Rectangle() - { - } - - public double X; - public double Y; - public double Width; - public double Height; - - public double Left - { - get - { - return X; - } - } - public double Right - { - get - { - return X + Width; - } - } - public double Top - { - get - { - return Y; - } - } - public double Bottom - { - get - { - return Y + Height; - } - } - - public bool Contains(Vector2d point) - { - return (Between(point.X, X, X + Width) && Between(point.Y, Y, Y + Height)); - - } - - private bool Between(double n, double n1, double n2) - { - if (n1 > n2) - { - return !(n > n1) && !(n < n2); - } - else - { - return !(n < n1) && !(n > n2); - } - } - - public Rectangle Copy() - { - Rectangle temp = new Rectangle(); - temp.X = X; - temp.Y = Y; - temp.Width = Width; - temp.Height = Height; - return temp; - } - - public static Rectangle Create(double x, double y, double width, double height) - { - Rectangle temp = new Rectangle(); - temp.X = x; - temp.Y = y; - temp.Width = width; - temp.Height = height; - return temp; - } - } - - public class Guid - { - - string guid = Create(); - - public Guid() - { - } - - public static Guid NewGuid() - { - return new Guid(); - } - - public override string ToString() - { - return guid; - } - public static Guid FromString(string id) - { - Guid temp = new Guid(); - temp.guid = id.Trim(); - return temp; - } - - public static string Create() - { - return (string)Script.Literal(" 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });"); - } - - - // The value 1420736a-a637-40a7-813a-ba692e72204e is a UUID (generated using the uuid CLI) - // that serves as a 'namespace' for our GUIDs - // The key property here is that this function always yields the same result for a given input - // See for example https://www.sohamkamani.com/uuid-versions-explained/ - public static Guid CreateFrom(string value) - { - string str = (string)Script.Literal("uuid.v5(value, '1420736a-a637-40a7-813a-ba692e72204e')"); - return Guid.FromString(str); - } - - } - - public class Enums - { - public static int Parse(string enumType, string value) - { - if (value == "Default") - { - value = "DefaultV"; - } - - if (value == "0") - { - return 0; - } - - string val = value.Substr(0, 1).ToLowerCase() + value.Substr(1); - - // To keep the C# compilation tractable, we need to pass the enum - // type as a string value. Unfortunately this means that we have to - // somehow dynamically look up the enum type. The JS framework - // has a hack to set `Enums._wwtlib` to point to the wwtlib namespace - // object, making the lookup hack possible. - return (int)Script.Literal("this._wwtlib[{0}][{1}]", enumType, val); - } - - public static string ToXml(string enumType, int value) - { - Script.Literal(" var x = \"0\"; var p = Object.keys(this._wwtlib[{0}]); for (var i in p)\n {{ if ( this._wwtlib[{0}][p[i]] == {1} ) {{\n x = p[i]; break; \n}}\n }}", enumType, value); - string val = (string)Script.Literal(" x"); - - string enumString = val.Substr(0, 1).ToUpperCase() + val.Substr(1); - if (enumString == "DefaultV") - { - enumString = "Default"; - } - - return enumString; - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("navigator")] - public static class Navigator - { - [ScriptField] - [ScriptName("appVersion")] - public static string AppVersion { get { return ""; } } - - [ScriptField] - [ScriptName("geolocation")] - public static GeoLocation Geolocation { get { return null; } } - - [ScriptField] - [ScriptName("clipboard")] - public static Clipboard Clipboard { get { return null; } } - - [ScriptField] - [ScriptName("userAgent")] - public static string UserAgent { get { return null; } } - - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public delegate void ClipbaordDelegate(string clipText); - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("clipboard")] - public class Clipboard - { - - [ScriptName("readText")] - public Promise ReadText() - { - return null; - } - - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("promise")] - public class Promise - { - - [ScriptName("then")] - public void Then(Delegate handler) - { - } - - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - public delegate void GeoEventHandler(Position pos); - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("geolocation")] - public class GeoLocation - { - - [ScriptName("getCurrentPosition")] - public void GetCurrentPosition(GeoEventHandler handler) - { - } - - [ScriptName("getCurrentPosition")] - public void GetCurrentPosition(GeoEventHandler handler, GeoEventHandler error) - { - } - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("position")] - public class Position - { - [ScriptField] - [ScriptName("coords")] - public GeoCoordinates Coords { get { return null; } } - - } - - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("coordinates")] - public class GeoCoordinates - { - [ScriptField] - [ScriptName("latitude")] - public double Latitude { get { return 0; } } - [ScriptField] - [ScriptName("longitude")] - public double Longitude { get { return 0; } } - [ScriptField] - [ScriptName("altitude")] - public double Altitude { get { return 0; } } - } - - - public static class Mouse - { - public static int OffsetX(CanvasElement canvas, ElementEvent e) - { - int x = 0; - MouseCanvasElement element = (MouseCanvasElement)(object)canvas; - MouseEvent me = (MouseEvent)(object)e; - if (element.offsetParent != null) - { - do - { - x += element.offsetLeft; - } while ((element = element.offsetParent) != null); - } - - // Add padding and border style widths to offset - //x += me.stylePaddingLeft; - - //x += me.styleBorderLeft; - - return me.PageX - x; - } - public static int OffsetY(CanvasElement canvas, ElementEvent e) - { - int y = 0; - MouseCanvasElement element = (MouseCanvasElement)(object)canvas; - MouseEvent me = (MouseEvent)(object)e; - if (element.offsetParent != null) - { - do - { - y += element.offsetTop; - } while ((element = element.offsetParent) != null); - } - - // Add padding and border style widths to offset - //y += me.stylePaddingTop; - - //y += me.styleBorderTop; - - return me.PageY - y; - } - } - - public class Language - { - public static string GetLocalizedText(int id, string text) - { - //todo make this actually use localization file. - return text; - } - } - - public class Cursor - { - public static Vector2d Position - { - get - { - return new Vector2d(); - } - } - - public static string Current - { - set - { - Document.Body.Style.Cursor = value; - } - get - { - return Document.Body.Style.Cursor; - } - } - } - - // - // Summary: - // Provides a collection of System.Windows.Forms.Cursor objects for use by a Windows - // Forms application. - public sealed class Cursors - { - - // - // Summary: - // Gets the arrow cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the arrow cursor. - public static string Arrow - { - get - { - return "default"; - } - } - // - // Summary: - // Gets the crosshair cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the crosshair cursor. - public static string Cross - { - get - { - return "crosshair"; - } - } - - // - // Summary: - // Gets the default cursor, which is usually an arrow cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the default cursor. - public static string DefaultV - { - get - { - return "default"; - } - } - // - // Summary: - // Gets the hand cursor, typically used when hovering over a Web link. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the hand cursor. - public static string Hand - { - get - { - return "grab"; - } - } - // - // Summary: - // Gets the Help cursor, which is a combination of an arrow and a question mark. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the Help cursor. - public static string Help - { - get - { - return "help"; - } - } - // - // Summary: - // Gets the cursor that appears when the mouse is positioned over a horizontal splitter - // bar. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the cursor that appears when - // the mouse is positioned over a horizontal splitter bar. - public static string HSplit - { - get - { - return "row-resize"; - } - } - // - // Summary: - // Gets the I-beam cursor, which is used to show where the text cursor appears when - // the mouse is clicked. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the I-beam cursor. - public static string IBeam - { - get - { - return "text"; - } - } - // - // Summary: - // Gets the cursor that indicates that a particular region is invalid for the current - // operation. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the cursor that indicates that - // a particular region is invalid for the current operation. - public static string No - { - get - { - return "not-allowed"; - } - } - - - // - // Summary: - // Gets the four-headed sizing cursor, which consists of four joined arrows that - // point north, south, east, and west. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the four-headed sizing cursor. - public static string SizeAll - { - get - { - return "help"; - } - } - // - // Summary: - // Gets the two-headed diagonal (northeast/southwest) sizing cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents two-headed diagonal (northeast/southwest) - // sizing cursor. - public static string SizeNESW - { - get - { - return "nwse-resize"; - } - } - // Summary: - // Gets the two-headed vertical (north/south) sizing cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the two-headed vertical (north/south) - // sizing cursor. - public static string SizeNS - { - get - { - return "ns-resize"; - } - } - // - // Summary: - // Gets the two-headed diagonal (northwest/southeast) sizing cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the two-headed diagonal (northwest/southeast) - // sizing cursor. - public static string SizeNWSE - { - get - { - return "nwse-resize"; - } - } - // - // Summary: - // Gets the two-headed horizontal (west/east) sizing cursor. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the two-headed horizontal (west/east) - // sizing cursor. - public static string SizeWE - { - get - { - return "ew-resize"; - } - } - // - // Summary: - // Gets the up arrow cursor, typically used to identify an insertion point. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the up arrow cursor. - public static string UpArrow - { - get - { - return "help"; - } - } - // - // Summary: - // Gets the cursor that appears when the mouse is positioned over a vertical splitter - // bar. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the cursor that appears when - // the mouse is positioned over a vertical splitter bar. - public static string VSplit - { - get - { - return "col-resize"; - } - } - // - // Summary: - // Gets the wait cursor, typically an hourglass shape. - // - // Returns: - // The System.Windows.Forms.Cursor that represents the wait cursor. - public static string WaitCursor - { - get - { - return "wait"; - } - } - } - - // - // Summary: - // Specifies key codes and modifiers. - - public enum Keys - { - // - // Summary: - // The bitmask to extract modifiers from a key value. - Modifiers = -65536, - // - // Summary: - // No key pressed. - None = 0, - // - // Summary: - // The left mouse button. - LButton = 1, - // - // Summary: - // The right mouse button. - RButton = 2, - // - // Summary: - // The CANCEL key. - Cancel = 3, - // - // Summary: - // The middle mouse button (three-button mouse). - MButton = 4, - // - // Summary: - // The first x mouse button (five-button mouse). - XButton1 = 5, - // - // Summary: - // The second x mouse button (five-button mouse). - XButton2 = 6, - // - // Summary: - // The BACKSPACE key. - Back = 8, - // - // Summary: - // The TAB key. - Tab = 9, - // - // Summary: - // The LINEFEED key. - LineFeed = 10, - // - // Summary: - // The CLEAR key. - ClearKey = 12, - // - // Summary: - // The RETURN key. - ReturnKey = 13, - // - // Summary: - // The ENTER key. - Enter = 13, - // - // Summary: - // The SHIFT key. - ShiftKey = 16, - // - // Summary: - // The CTRL key. - ControlKey = 17, - // - // Summary: - // The ALT key. - Menu = 18, - // - // Summary: - // The PAUSE key. - Pause = 19, - // - // Summary: - // The CAPS LOCK key. - Capital = 20, - // - // Summary: - // The CAPS LOCK key. - CapsLock = 20, - // - // Summary: - // The IME Kana mode key. - KanaMode = 21, - // - // Summary: - // The IME Hanguel mode key. (maintained for compatibility; use HangulMode) - HanguelMode = 21, - // - // Summary: - // The IME Hangul mode key. - HangulMode = 21, - // - // Summary: - // The IME Junja mode key. - JunjaMode = 23, - // - // Summary: - // The IME final mode key. - FinalMode = 24, - // - // Summary: - // The IME Hanja mode key. - HanjaMode = 25, - // - // Summary: - // The IME Kanji mode key. - KanjiMode = 25, - // - // Summary: - // The ESC key. - Escape = 27, - // - // Summary: - // The IME convert key. - IMEConvert = 28, - // - // Summary: - // The IME nonconvert key. - IMENonconvert = 29, - // - // Summary: - // The IME accept key, replaces System.Windows.Forms.Keys.IMEAceept. - IMEAccept = 30, - // - // Summary: - // The IME accept key. Obsolete, use System.Windows.Forms.Keys.IMEAccept instead. - IMEAceept = 30, - // - // Summary: - // The IME mode change key. - IMEModeChange = 31, - // - // Summary: - // The SPACEBAR key. - Space = 32, - // - // Summary: - // The PAGE UP key. - Prior = 33, - // - // Summary: - // The PAGE UP key. - PageUp = 33, - // - // Summary: - // The PAGE DOWN key. - Next = 34, - // - // Summary: - // The PAGE DOWN key. - PageDown = 34, - // - // Summary: - // The END key. - End = 35, - // - // Summary: - // The HOME key. - Home = 36, - // - // Summary: - // The LEFT ARROW key. - Left = 37, - // - // Summary: - // The UP ARROW key. - Up = 38, - // - // Summary: - // The RIGHT ARROW key. - Right = 39, - // - // Summary: - // The DOWN ARROW key. - Down = 40, - // - // Summary: - // The SELECT key. - Select = 41, - // - // Summary: - // The PRINT key. - Print = 42, - // - // Summary: - // The EXECUTE key. - Execute = 43, - // - // Summary: - // The PRINT SCREEN key. - Snapshot = 44, - // - // Summary: - // The PRINT SCREEN key. - PrintScreen = 44, - // - // Summary: - // The INS key. - InsertKey = 45, - // - // Summary: - // The DEL key. - DeleteKey = 46, - // - // Summary: - // The HELP key. - Help = 47, - // - // Summary: - // The 0 key. - D0 = 48, - // - // Summary: - // The 1 key. - D1 = 49, - // - // Summary: - // The 2 key. - D2 = 50, - // - // Summary: - // The 3 key. - D3 = 51, - // - // Summary: - // The 4 key. - D4 = 52, - // - // Summary: - // The 5 key. - D5 = 53, - // - // Summary: - // The 6 key. - D6 = 54, - // - // Summary: - // The 7 key. - D7 = 55, - // - // Summary: - // The 8 key. - D8 = 56, - // - // Summary: - // The 9 key. - D9 = 57, - // - // Summary: - // The A key. - A = 65, - // - // Summary: - // The B key. - B = 66, - // - // Summary: - // The C key. - C = 67, - // - // Summary: - // The D key. - D = 68, - // - // Summary: - // The E key. - E = 69, - // - // Summary: - // The F key. - F = 70, - // - // Summary: - // The G key. - G = 71, - // - // Summary: - // The H key. - H = 72, - // - // Summary: - // The I key. - I = 73, - // - // Summary: - // The J key. - J = 74, - // - // Summary: - // The K key. - K = 75, - // - // Summary: - // The L key. - L = 76, - // - // Summary: - // The M key. - M = 77, - // - // Summary: - // The N key. - N = 78, - // - // Summary: - // The O key. - O = 79, - // - // Summary: - // The P key. - P = 80, - // - // Summary: - // The Q key. - Q = 81, - // - // Summary: - // The R key. - R = 82, - // - // Summary: - // The S key. - S = 83, - // - // Summary: - // The T key. - T = 84, - // - // Summary: - // The U key. - U = 85, - // - // Summary: - // The V key. - V = 86, - // - // Summary: - // The W key. - W = 87, - // - // Summary: - // The X key. - X = 88, - // - // Summary: - // The Y key. - Y = 89, - // - // Summary: - // The Z key. - Z = 90, - // - // Summary: - // The left Windows logo key (Microsoft Natural Keyboard). - LWin = 91, - // - // Summary: - // The right Windows logo key (Microsoft Natural Keyboard). - RWin = 92, - // - // Summary: - // The application key (Microsoft Natural Keyboard). - Apps = 93, - // - // Summary: - // The computer sleep key. - Sleep = 95, - // - // Summary: - // The 0 key on the numeric keypad. - NumPad0 = 96, - // - // Summary: - // The 1 key on the numeric keypad. - NumPad1 = 97, - // - // Summary: - // The 2 key on the numeric keypad. - NumPad2 = 98, - // - // Summary: - // The 3 key on the numeric keypad. - NumPad3 = 99, - // - // Summary: - // The 4 key on the numeric keypad. - NumPad4 = 100, - // - // Summary: - // The 5 key on the numeric keypad. - NumPad5 = 101, - // - // Summary: - // The 6 key on the numeric keypad. - NumPad6 = 102, - // - // Summary: - // The 7 key on the numeric keypad. - NumPad7 = 103, - // - // Summary: - // The 8 key on the numeric keypad. - NumPad8 = 104, - // - // Summary: - // The 9 key on the numeric keypad. - NumPad9 = 105, - // - // Summary: - // The multiply key. - Multiply = 106, - // - // Summary: - // The add key. - Add = 107, - // - // Summary: - // The separator key. - Separator = 108, - // - // Summary: - // The subtract key. - Subtract = 109, - // - // Summary: - // The decimal key. - Decimal = 110, - // - // Summary: - // The divide key. - Divide = 111, - // - // Summary: - // The F1 key. - F1 = 112, - // - // Summary: - // The F2 key. - F2 = 113, - // - // Summary: - // The F3 key. - F3 = 114, - // - // Summary: - // The F4 key. - F4 = 115, - // - // Summary: - // The F5 key. - F5 = 116, - // - // Summary: - // The F6 key. - F6 = 117, - // - // Summary: - // The F7 key. - F7 = 118, - // - // Summary: - // The F8 key. - F8 = 119, - // - // Summary: - // The F9 key. - F9 = 120, - // - // Summary: - // The F10 key. - F10 = 121, - // - // Summary: - // The F11 key. - F11 = 122, - // - // Summary: - // The F12 key. - F12 = 123, - // - // Summary: - // The F13 key. - F13 = 124, - // - // Summary: - // The F14 key. - F14 = 125, - // - // Summary: - // The F15 key. - F15 = 126, - // - // Summary: - // The F16 key. - F16 = 127, - // - // Summary: - // The F17 key. - F17 = 128, - // - // Summary: - // The F18 key. - F18 = 129, - // - // Summary: - // The F19 key. - F19 = 130, - // - // Summary: - // The F20 key. - F20 = 131, - // - // Summary: - // The F21 key. - F21 = 132, - // - // Summary: - // The F22 key. - F22 = 133, - // - // Summary: - // The F23 key. - F23 = 134, - // - // Summary: - // The F24 key. - F24 = 135, - // - // Summary: - // The NUM LOCK key. - NumLock = 144, - // - // Summary: - // The SCROLL LOCK key. - Scroll = 145, - // - // Summary: - // The left SHIFT key. - LShiftKey = 160, - // - // Summary: - // The right SHIFT key. - RShiftKey = 161, - // - // Summary: - // The left CTRL key. - LControlKey = 162, - // - // Summary: - // The right CTRL key. - RControlKey = 163, - // - // Summary: - // The left ALT key. - LMenu = 164, - // - // Summary: - // The right ALT key. - RMenu = 165, - // - // Summary: - // The browser back key (Windows 2000 or later). - BrowserBack = 166, - // - // Summary: - // The browser forward key (Windows 2000 or later). - BrowserForward = 167, - // - // Summary: - // The browser refresh key (Windows 2000 or later). - BrowserRefresh = 168, - // - // Summary: - // The browser stop key (Windows 2000 or later). - BrowserStop = 169, - // - // Summary: - // The browser search key (Windows 2000 or later). - BrowserSearch = 170, - // - // Summary: - // The browser favorites key (Windows 2000 or later). - BrowserFavorites = 171, - // - // Summary: - // The browser home key (Windows 2000 or later). - BrowserHome = 172, - // - // Summary: - // The volume mute key (Windows 2000 or later). - VolumeMute = 173, - // - // Summary: - // The volume down key (Windows 2000 or later). - VolumeDown = 174, - // - // Summary: - // The volume up key (Windows 2000 or later). - VolumeUp = 175, - // - // Summary: - // The media next track key (Windows 2000 or later). - MediaNextTrack = 176, - // - // Summary: - // The media previous track key (Windows 2000 or later). - MediaPreviousTrack = 177, - // - // Summary: - // The media Stop key (Windows 2000 or later). - MediaStop = 178, - // - // Summary: - // The media play pause key (Windows 2000 or later). - MediaPlayPause = 179, - // - // Summary: - // The launch mail key (Windows 2000 or later). - LaunchMail = 180, - // - // Summary: - // The select media key (Windows 2000 or later). - SelectMedia = 181, - // - // Summary: - // The start application one key (Windows 2000 or later). - LaunchApplication1 = 182, - // - // Summary: - // The start application two key (Windows 2000 or later). - LaunchApplication2 = 183, - // - // Summary: - // The OEM Semicolon key on a US standard keyboard (Windows 2000 or later). - OemSemicolon = 186, - // - // Summary: - // The OEM 1 key. - Oem1 = 186, - // - // Summary: - // The OEM plus key on any country/region keyboard (Windows 2000 or later). - Oemplus = 187, - // - // Summary: - // The OEM comma key on any country/region keyboard (Windows 2000 or later). - Oemcomma = 188, - // - // Summary: - // The OEM minus key on any country/region keyboard (Windows 2000 or later). - OemMinus = 189, - // - // Summary: - // The OEM period key on any country/region keyboard (Windows 2000 or later). - OemPeriod = 190, - // - // Summary: - // The OEM question mark key on a US standard keyboard (Windows 2000 or later). - OemQuestion = 191, - // - // Summary: - // The OEM 2 key. - Oem2 = 191, - // - // Summary: - // The OEM tilde key on a US standard keyboard (Windows 2000 or later). - Oemtilde = 192, - // - // Summary: - // The OEM 3 key. - Oem3 = 192, - // - // Summary: - // The OEM open bracket key on a US standard keyboard (Windows 2000 or later). - OemOpenBrackets = 219, - // - // Summary: - // The OEM 4 key. - Oem4 = 219, - // - // Summary: - // The OEM pipe key on a US standard keyboard (Windows 2000 or later). - OemPipe = 220, - // - // Summary: - // The OEM 5 key. - Oem5 = 220, - // - // Summary: - // The OEM close bracket key on a US standard keyboard (Windows 2000 or later). - OemCloseBrackets = 221, - // - // Summary: - // The OEM 6 key. - Oem6 = 221, - // - // Summary: - // The OEM singled/double quote key on a US standard keyboard (Windows 2000 or later). - OemQuotes = 222, - // - // Summary: - // The OEM 7 key. - Oem7 = 222, - // - // Summary: - // The OEM 8 key. - Oem8 = 223, - // - // Summary: - // The OEM angle bracket or backslash key on the RT 102 key keyboard (Windows 2000 - // or later). - OemBackslash = 226, - // - // Summary: - // The OEM 102 key. - Oem102 = 226, - // - // Summary: - // The PROCESS KEY key. - ProcessKey = 229, - // - // Summary: - // Used to pass Unicode characters as if they were keystrokes. The Packet key value - // is the low word of a 32-bit virtual-key value used for non-keyboard input methods. - Packet = 231, - // - // Summary: - // The ATTN key. - Attn = 246, - // - // Summary: - // The CRSEL key. - Crsel = 247, - // - // Summary: - // The EXSEL key. - Exsel = 248, - // - // Summary: - // The ERASE EOF key. - EraseEof = 249, - // - // Summary: - // The PLAY key. - Play = 250, - // - // Summary: - // The ZOOM key. - Zoom = 251, - // - // Summary: - // A constant reserved for future use. - NoName = 252, - // - // Summary: - // The PA1 key. - Pa1 = 253, - // - // Summary: - // The CLEAR key. - OemClear = 254, - // - // Summary: - // The bitmask to extract a key code from a key value. - KeyCode = 65535, - // - // Summary: - // The SHIFT modifier key. - Shift = 65536, - // - // Summary: - // The CTRL modifier key. - Control = 131072, - // - // Summary: - // The ALT modifier key. - Alt = 262144 - } - - //public class SimpleInput - //{ - // private string url; - // private string v1; - // private string v2; - // private int v3; - - // public SimpleInput(string v1, string v2, string url, int v3) - // { - // this.v1 = v1; - // this.v2 = v2; - // this.url = url; - // this.v3 = v3; - // } - - // public string ResultText = new string(); - - // public DialogResult ShowDialog() - // { - - // return DialogResult.OK; - // } - //} - - public enum DialogResult { OK = 1, }; - - public class SelectLink - { - public SelectLink(string id) - { - if (id != null) - { - this.ID = id; - } - else - { - this.Next = true; - } - } - - private bool _return = false; - public bool ReturnCaller - { - set - { - if (value) - { - _slide = "Return"; - } - _return = value; - } - get { return _return; } - } - private bool _next = true; - public bool Next - { - set - { - if (value) - { - _slide = "Next"; - } - _next = value; - } - get { return _next; } - } - private bool _linkSlide = false; - public bool LinkToSlide - { - set - { - if (value) { - _slide = "Next"; - } - _linkSlide = value; - } - get { return _linkSlide; } - } - private string _slide = null; - public string ID - { - set - { - _return = false; - _next = false; - _linkSlide = true; - _slide = value; - } - get { return _slide; } - } - private bool _ok = false; - public bool OK - { - set { _ok = value; } - get { return _ok; } - } - } - - - public class PopupVolume - { - public int Volume = 0; - - public DialogResult ShowDialog() - { - - return DialogResult.OK; - } - } - - public class PopupColorPicker - { - public int Volume = 0; - - public Vector2d Location = new Vector2d(); - - public Color Color = new Color(); - - - public DialogResult ShowDialog() - { - - return DialogResult.OK; - } - } - public class OverlayProperties - { - public int Volume = 0; - - public Vector2d Location = new Vector2d(); - - public Overlay Overlay = null; - - - public DialogResult ShowDialog() - { - - return DialogResult.OK; - } - } -} diff --git a/engine/csharp_ref/Utilities/BinaryReader.cs b/engine/csharp_ref/Utilities/BinaryReader.cs deleted file mode 100644 index 68030eed..00000000 --- a/engine/csharp_ref/Utilities/BinaryReader.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.Html; - - - - -namespace wwtlib -{ - public class BinaryReader - { - public int position = 0; - Uint8Array data = null; - - public int Position - { - get { return position; } - } - - public void Seek(int pos) - { - position = pos; - } - - public void SeekRelative(int pos) - { - position += pos; - } - - public int Length - { - get { return data.length; } - } - - public bool EndOfStream - { - get { return position >= Length; } - } - - public BinaryReader(Uint8Array arraybuf) - { - data = arraybuf; - } - - public byte ReadByte() - { - byte result; - result = this.data[this.position]; - this.position += 1; - - return result; - } - - public sbyte ReadSByte() - { - sbyte result; - result = (sbyte)this.data[this.position]; - this.position += 1; - - return result; - } - - public byte[] ReadBytes(int count) - { - - byte[] buf = new byte[count]; - - for (int i = 0; i < count; i++) - { - buf[i] = this.data[this.position + i]; - } - - this.position += count; - - return buf; - } - - public Float32Array ReadRemainingI16(int i16Remaining) - { - Float32Array data = new Float32Array(i16Remaining); - for (int i = 0; i < i16Remaining; i++) - { - data[i] = (float)this.ReadInt16(true); - } - return data; - } - - public string ReadByteString(int count) - { - string data = ""; - - for (int i = 0; i < count; i++) - { - data += string.FromCharCode(this.data[this.position + i]); - } - - this.position += count; - - return data; - } - - public float ReadSingle() - { - //if (this.data.length < Position + 4) - //{ - // throw 'range error'; - - //} - - Uint8Array tmp = new Uint8Array(4); - - tmp[0] = this.data[this.position]; - tmp[1] = this.data[this.position + 1]; - tmp[2] = this.data[this.position + 2]; - tmp[3] = this.data[this.position + 3]; - - float result = (new Float32Array(tmp.buffer, 0, 1))[0]; - - this.position += 4; - - return result; - } - public UInt32 ReadUInt32() - { - - //if (this.data.length < this.position + 4) - //{ - // throw 'range error'; - //} - UInt32 result = (UInt32)(this.data[this.position] + (this.data[this.position + 1] << 8) + (this.data[this.position + 2] << 16) + (this.data[this.position + 3] << 24)); - this.position += 4; - return result; - - } - public UInt16 ReadUInt16() - { - - UInt16 result = (UInt16)(this.data[this.position] + (this.data[this.position + 1] << 8) ); - this.position += 2; - return result; - - } - - public UInt16 ReadUInt16LittleEndian() - { - UInt16 result = (UInt16)((this.data[this.position] << 8) + (this.data[this.position + 1])); - this.position += 2; - return result; - } - - public Int16 ReadInt16(bool littleEndian) - { - - UInt16 result = littleEndian ? this.ReadUInt16LittleEndian() : this.ReadUInt16(); - - if ((result & 0x8000) != 0) - { - - return (Int16)(-((result - 1) ^ 0xffff)); - - } - - return (Int16)result; - - } - - public Int32 ReadInt32() - { - - UInt32 result = this.ReadUInt32(); - - if ((result & 0x80000000) != 0) - { - - return (Int32)(-((result - 1) ^ 0xffffffff)); - - } - - return (Int32)result; - - } - public static int id = 1; - public Int64 ReadInt64() - { - this.position += 8; - return id++; - } - - public void Close() - { - - } - } -} diff --git a/engine/csharp_ref/Utilities/Bitmap.cs b/engine/csharp_ref/Utilities/Bitmap.cs deleted file mode 100644 index 82931cd9..00000000 --- a/engine/csharp_ref/Utilities/Bitmap.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html.Media.Graphics; -using System.Html; -using System.Net; - -namespace wwtlib -{ - public class Bitmap - { - public int Width; - public int Height; - - public Bitmap() - { - - } - - Uint8Array buffer; - - public static Bitmap Create(int width, int height) - { - height = Texture.FitPowerOfTwo(height); - width = Texture.FitPowerOfTwo(width); - - Bitmap bmp = new Bitmap(); - bmp.Height = height; - bmp.Width = width; - - bmp.buffer = new Uint8Array(width * height * 4); - return bmp; - } - - public void SetPixel(int x, int y, int r, int g, int b, int a) - { - int index = (x + y * Width) * 4; - - buffer[index++] = (Byte)r; - buffer[index++] = (Byte)g; - buffer[index++] = (Byte)b; - buffer[index++] = (Byte)a; - } - - public WebGLTexture GetTexture() - { - WebGLTexture tex = Tile.PrepDevice.createTexture(); - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, tex); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE); - Tile.PrepDevice.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, Width, Height, 0, GL.RGBA, GL.UNSIGNED_BYTE, (WebGLArray)(object)buffer); - Tile.PrepDevice.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_NEAREST); - Tile.PrepDevice.generateMipmap(GL.TEXTURE_2D); - Tile.PrepDevice.bindTexture(GL.TEXTURE_2D, null); - return tex; - } - - //function textureFromPixelArray(gl, dataArray, type, width, height) - //{ - // var dataTypedArray = new Uint8Array(dataArray); // Don't need to do this if the data is already in a typed array - // var texture = gl.createTexture(); - // gl.bindTexture(gl.TEXTURE_2D, texture); - // gl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, gl.UNSIGNED_BYTE, dataTypedArray); - // // Other texture setup here, like filter modes and mipmap generation - // return texture; - //} - - } -} diff --git a/engine/csharp_ref/Utilities/ColorPicker.cs b/engine/csharp_ref/Utilities/ColorPicker.cs deleted file mode 100644 index e3f99337..00000000 --- a/engine/csharp_ref/Utilities/ColorPicker.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public class ColorPicker - { - public ColorPicker() - { - - } - - public void NonMenuClick(ElementEvent e) - { - //DivElement menu = Document.GetElementById("colorpicker"); - //menu.Style.Display = "none"; - //Window.RemoveEventListener("click", NonMenuClick, true); - - //ImageElement image = Document.GetElementById("colorhex"); - //image.RemoveEventListener("click", PickColor, false); - } - - - public void Show(EventArgs e) - { - WWTControl.scriptInterface.ShowColorPicker(this, e); - //DivElement picker = Document.GetElementById("colorpicker"); - //picker.ClassName = "colorpicker"; - //picker.Style.Display = "block"; - //picker.Style.Left = position.X.ToString() + "px"; - //picker.Style.Top = position.Y.ToString() + "px"; - - //Window.AddEventListener("click", NonMenuClick, true); - - //ImageElement image = Document.GetElementById("colorhex"); - - //image.AddEventListener("mousedown", PickColor, false); - } - - public Color GetColorFromClick(ElementEvent e) - { - ImageElement image = Document.GetElementById("colorhex"); - - CanvasElement canvas = (CanvasElement)Document.CreateElement("canvas"); - canvas.Width = image.Width; - canvas.Height = image.Height; - - CanvasContext2D ctx = (CanvasContext2D)canvas.GetContext(Rendering.Render2D); - ctx.DrawImage(image, 0, 0); - - PixelArray pixels = ctx.GetImageData(e.OffsetX, e.OffsetY, 1, 1).Data; - Color = Color.FromArgb((float)pixels[3], (float)pixels[0], (float)pixels[1], (float)pixels[2]); - - return Color; - - } - - public void PickColor(ElementEvent e) - { - - CallBack(Color); - - } - - public ColorPick CallBack = null; - - public Color Color = Colors.White; - } - - - public delegate void ColorPick(Color Picked); - -} diff --git a/engine/csharp_ref/Utilities/ContextMenuStrip.cs b/engine/csharp_ref/Utilities/ContextMenuStrip.cs deleted file mode 100644 index 54fe325c..00000000 --- a/engine/csharp_ref/Utilities/ContextMenuStrip.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - - public class ContextMenuStrip - { - public ContextMenuStrip() - { - - } - - public List Items = new List(); - - internal void Dispose() - { - } - - internal void NonMenuClick(ElementEvent e) - { - DivElement menu = Document.GetElementById("contextmenu"); - menu.Style.Display = "none"; - Window.RemoveEventListener("click", NonMenuClick, false); - - - DivElement popup = Document.GetElementById("popoutmenu"); - while (popup.FirstChild != null) - { - popup.RemoveChild(popup.FirstChild); - } - - popup.Style.Display = "none"; - - } - - internal void MenuItemClicked(ElementEvent e) - { - TagMe me = (TagMe)(Object)e.CurrentTarget; - - - - me.ItemTag.Click(me.ItemTag, new EventArgs()); - } - - internal void Show(Vector2d position) - { - DivElement menu = Document.GetElementById("contextmenu"); - while(menu.FirstChild != null) - { - menu.RemoveChild(menu.FirstChild); - } - - menu.ClassName = "contextmenu"; - menu.Style.Display = "block"; - menu.Style.Left = position.X.ToString() + "px"; - menu.Style.Top = position.Y.ToString() + "px"; - - Window.AddEventListener("click", NonMenuClick, true); - - foreach (ToolStripMenuItem item in Items) - { - if (item.Visible) - { - DivElement md = (DivElement)Document.CreateElement("div"); - if (item.DropDownItems.Count > 0) - { - md.ClassName = "contextmenuitem submenu"; - } - else - { - if (item.Checked) - { - md.ClassName = "contextmenuitem checkedmenu"; - } - else - { - md.ClassName = "contextmenuitem"; - } - } - md.InnerText = item.Name; - - TagMe it = (TagMe)(Object)md; - it.ItemTag = item; - - md.AddEventListener("mouseover", OpenSubMenu, false); - - if (item.Click != null) - { - md.AddEventListener("click", MenuItemClicked, false); - } - - menu.AppendChild(md); - } - } - } - internal void OpenSubMenu(ElementEvent e) - { - TagMe me = (TagMe)(Object)e.CurrentTarget; - ToolStripMenuItem child = me.ItemTag; - - DivElement menu = Document.GetElementById("popoutmenu"); - while (menu.FirstChild != null) - { - menu.RemoveChild(menu.FirstChild); - } - - menu.Style.Display = "none"; - - if (child.DropDownItems.Count == 0) - { - return; - } - - Vector2d position = new Vector2d(); - position.X = e.CurrentTarget.ParentNode.OffsetLeft + e.CurrentTarget.ParentNode.ClientWidth; - position.Y = e.CurrentTarget.ParentNode.OffsetTop + e.CurrentTarget.OffsetTop; - - - menu.ClassName = "contextmenu"; - menu.Style.Display = "block"; - menu.Style.Left = position.X.ToString() + "px"; - menu.Style.Top = position.Y.ToString() + "px"; - - Window.AddEventListener("click", NonMenuClick, true); - - foreach (ToolStripMenuItem item in child.DropDownItems) - { - if (item.Visible) - { - DivElement md = (DivElement)Document.CreateElement("div"); - md.ClassName = item.Checked ? "contextmenuitem checkedmenu" : "contextmenuitem"; - md.InnerText = item.Name; - - TagMe it = (TagMe)(Object)md; - it.ItemTag = item; - - md.AddEventListener("click", MenuItemClicked, false); - menu.AppendChild(md); - } - } - } - } - - public delegate void MenuEvent(object sender, EventArgs e); - - public class ToolStripMenuItem - { - public string Name; - public object Tag = null; - - public List DropDownItems = new List(); - - public MenuEvent Click; - public bool Checked = false; - public bool Enabled = true; - public bool Visible = true; - - public static ToolStripMenuItem Create(string name) - { - ToolStripMenuItem tsmi = new ToolStripMenuItem(); - tsmi.Name = name; - - return tsmi; - } - } - - public class ToolStripSeparator : ToolStripMenuItem - { - public ToolStripSeparator() - { - this.Name = "--------------------------------------"; - } - } - - public class TagMe - { - public ToolStripMenuItem ItemTag; - } -} diff --git a/engine/csharp_ref/Utilities/Dialog.cs b/engine/csharp_ref/Utilities/Dialog.cs deleted file mode 100644 index 3481c5c2..00000000 --- a/engine/csharp_ref/Utilities/Dialog.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; - - -namespace wwtlib -{ - public class Dialog - { - public Dialog() { } - - public event EventHandler ShowDialogHook; - - public void Show(object dialogArgs, EventArgs e) - { - - if (ShowDialogHook != null) - { - ShowDialogHook.Invoke(dialogArgs, e); - } - } - } - - public class FrameWizard : Dialog - { - public FrameWizard() - { - - } - public void OK(ReferenceFrame frame) - { - LayerManager.referenceFrameWizardFinished(frame); - } - } - - public class ReferenceFrameProps : Dialog - { - public ReferenceFrameProps() - { - - } - public void OK(ReferenceFrame frame) - { - LayerManager.LoadTree(); - } - } - - public class GreatCircleDialog : Dialog - { - public GreatCircleDialog() - { - - } - public void OK(ReferenceFrame frame) - { - - } - } - public class DataVizWizard : Dialog - { - public DataVizWizard() - { - - } - public void OK() - { - - } - } -} diff --git a/engine/csharp_ref/Utilities/FileReader.cs b/engine/csharp_ref/Utilities/FileReader.cs deleted file mode 100644 index aabe761a..00000000 --- a/engine/csharp_ref/Utilities/FileReader.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Html; -using System.Html.Data.Files; -using System.Runtime.CompilerServices; - -namespace wwtlib -{ - - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class FileReader - { - - [ScriptField] - public FileError Error - { - get - { - return null; - } - } - - /// - /// Indicates the state of the FileReader. This will be one of the State constants. Read only. - /// - [ScriptField] - public int ReadyState - { - get - { - return (int)System.Html.Data.Files.FileReadyState.Empty; - } - } - - // File or Blob data - [ScriptField] - public object Result - { - get - { - return null; - } - } - - [ScriptName("onabort")] - public Action OnAbort - { - get - { - return null; - } - set - { - } - } - - [ScriptName("onerror")] - public Action OnError - { - get - { - return null; - } - set - { - } - } - - [ScriptName("onload")] - public Action OnLoad - { - get - { - return null; - } - set - { - } - } - - [ScriptName("onloadend")] - [ScriptField] - public Action OnLoadEnd - { - get - { - return null; - } - set - { - } - } - - [ScriptName("onloadstart")] - public Action OnLoadStart - { - get - { - return null; - } - set - { - } - } - - [ScriptName("onprogress")] - public Action OnProgress - { - get - { - return null; - } - set - { - } - } - - public void Abort() - { - } - - /// - /// Adds a listener for the specified event. - /// - /// The name of the event such as 'load'. - /// The listener to be invoked in response to the event. - /// Whether the listener wants to initiate capturing the event. - public void AddEventListener(string eventName, ElementEventListener listener, bool useCapture) - { - } - - /// - /// Adds a listener for the specified event. - /// - /// The name of the event such as 'load'. - /// The handler to be invoked in response to the event. - /// Whether the handler wants to initiate capturing the event. - public void AddEventListener(string eventName, IElementEventHandler handler, bool useCapture) - { - } - - public bool DispatchEvent(MutableEvent eventObject) - { - return false; - } - - public void ReadAsArrayBuffer(Blob blob) - { - } - - public void ReadAsBinaryString(Blob blob) - { - } - - public void ReadAsDataURL(Blob blob) - { - } - - public void ReadAsText(Blob blob) - { - } - - public void ReadAsText(Blob blob, string encoding) - { - } - - /// - /// Removes a listener for the specified event. - /// - /// The name of the event such as 'load'. - /// The listener to be invoked in response to the event. - /// Whether the listener wants to initiate capturing the event. - public void RemoveEventListener(string eventName, ElementEventListener listener, bool useCapture) - { - } - - /// - /// Removes a listener for the specified event. - /// - /// The name of the event such as 'load'. - /// The handler to be invoked in response to the event. - /// Whether the handler wants to initiate capturing the event. - public void RemoveEventListener(string eventName, IElementEventHandler handler, bool useCapture) - { - } - } -} diff --git a/engine/csharp_ref/Utilities/Histogram.cs b/engine/csharp_ref/Utilities/Histogram.cs deleted file mode 100644 index c0af43c2..00000000 --- a/engine/csharp_ref/Utilities/Histogram.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - enum DragType { Low=0, High=1, Range=2, Center=3, None=4 }; - public class Histogram - { - public Histogram() - { - - } - - public FitsImage image = null; - public ImageSetLayer layer = null; - public SkyImageTile tile = null; - SelectElement dropDown = null; - - public void Close(ElementEvent e) - { - - DivElement menu = Document.GetElementById("histogram"); - DivElement closeBtn = Document.GetElementById("histogramClose"); - menu.Style.Display = "none"; - Window.RemoveEventListener("click", Close, true); - - ImageElement image = Document.GetElementById("graph"); - image.RemoveEventListener("mousedown", OnPointerDown, false); - image.RemoveEventListener("mousemove", OnPointerMove, false); - image.RemoveEventListener("mouseup", OnPointerUp, false); - dropDown.RemoveEventListener("change", CurveStyleSelected, false); - dropDown.RemoveEventListener("click", IgnoreMe, true); - - } - - - public void Show(Vector2d position) - { - tile = (SkyImageTile)TileCache.GetTile(0, 0, 0, layer.ImageSet, null); - - DivElement picker = Document.GetElementById("histogram"); - DivElement closeBtn = Document.GetElementById("histogramClose"); - /////////////picker.ClassName = "histogram"; - picker.Style.Display = "block"; - picker.Style.Left = position.X.ToString() + "px"; - picker.Style.Top = position.Y.ToString() + "px"; - - SelectedCurveStyle = (int)layer.ImageSet.FitsProperties.ScaleType; - - - dropDown = Document.GetElementById("ScaleTypePicker"); - - dropDown.AddEventListener("change", CurveStyleSelected, false); - dropDown.AddEventListener("click", IgnoreMe, true); - CanvasElement canvas = Document.GetElementById("graph"); - - canvas.AddEventListener("pointerdown", OnPointerDown, false); - canvas.AddEventListener("pointermove", OnPointerMove, false); - canvas.AddEventListener("pointerup", OnPointerUp, false); - closeBtn.AddEventListener("click", Close, true); - - Draw(); - } - - public static void UpdateImage(ImageSetLayer isl, double z) - { - if (!RenderContext.UseGlVersion2) - { - FitsImageJs image = isl.ImageSet.WcsImage as FitsImageJs; - SkyImageTile Tile = (SkyImageTile)TileCache.GetTile(0, 0, 0, isl.ImageSet, null); - Tile.texture2d = image.GetBitmap().GetTexture(); - } - } - - public static void UpdateScale(ImageSetLayer isl, ScaleTypes scale, double low, double hi) - { - isl.ImageSet.FitsProperties.ScaleType = scale; - isl.ImageSet.FitsProperties.LowerCut = low; - isl.ImageSet.FitsProperties.UpperCut = hi; - if (!RenderContext.UseGlVersion2) - { - FitsImageJs image = isl.ImageSet.WcsImage as FitsImageJs; - SkyImageTile Tile = (SkyImageTile)TileCache.GetTile(0, 0, 0, isl.ImageSet, null); - Tile.texture2d = image.GetBitmap().GetTexture(); - } - } - - public static void UpdateColorMapper(ImageSetLayer isl, string colorMapperName) - { - isl.ImageSet.FitsProperties.ColorMapName = colorMapperName; - if (!RenderContext.UseGlVersion2) - { - FitsImageJs image = isl.ImageSet.WcsImage as FitsImageJs; - SkyImageTile Tile = (SkyImageTile)TileCache.GetTile(0, 0, 0, isl.ImageSet, null); - Tile.texture2d = image.GetBitmap().GetTexture(); - } - } - - public void IgnoreMe(ElementEvent e) - { - ignoreNextClick = true; - } - - public void CurveStyleSelected(ElementEvent e) - { - SelectedCurveStyle = dropDown.SelectedIndex; - SetUpdateTimer(); - layer.ImageSet.FitsProperties.ScaleType = (ScaleTypes)SelectedCurveStyle; - Draw(); - ignoreNextClick = true; - } - - int downPosition = 0; - int lowPosition = 0; - int highPosition = 255; - int center = 127; - bool ignoreNextClick = false; - - DragType dragType = DragType.None; - - public void OnPointerDown(ElementEvent e) - { - CanvasElement canvas = Document.GetElementById("graph"); - int x = Mouse.OffsetX(canvas, e); - int y = Mouse.OffsetY(canvas, e); - Script.Literal("{0}.setPointerCapture({1}.pointerId)", canvas, e); - - if ((Math.Abs(x - center) < 10) && Math.Abs(y - 75) < 10) - { - dragType = DragType.Center; - } - else if (Math.Abs(x - lowPosition) < 10) - { - dragType = DragType.Low; - } - else if (Math.Abs(x - highPosition) < 10) - { - dragType = DragType.High; - } - else - { - dragType = DragType.Range; - downPosition = Math.Min(255, Math.Max(0, x)); - - Draw(); - } - e.CancelBubble = true; - } - - public void OnPointerMove(ElementEvent e) - { - CanvasElement canvas = Document.GetElementById("graph"); - int x = Mouse.OffsetX(canvas, e); - int y = Mouse.OffsetY(canvas, e); - switch (dragType) - { - case DragType.Low: - lowPosition = Math.Min(255, Math.Max(0, x)); - break; - case DragType.High: - highPosition = Math.Min(255, Math.Max(0, x)); - break; - case DragType.Range: - lowPosition = downPosition; - highPosition = Math.Min(255, Math.Max(0, x)); - break; - case DragType.Center: - int hWidth = Math.Abs(highPosition - lowPosition) / 2; - int adCenter = Math.Min(255 - hWidth, Math.Max(hWidth, x)); - int moved = center - adCenter; - lowPosition -= moved; - highPosition -= moved; - break; - case DragType.None: - return; - default: - break; - } - center = (lowPosition + highPosition) / 2; - Draw(); - double factor = (layer.ImageSet.FitsProperties.MaxVal - layer.ImageSet.FitsProperties.MinVal) / 256.0; - double low = layer.ImageSet.FitsProperties.MinVal + (lowPosition * factor); - double hi = layer.ImageSet.FitsProperties.MinVal + (highPosition * factor); - - SetUpdateTimer(); - - layer.ImageSet.FitsProperties.UpperCut = hi; - layer.ImageSet.FitsProperties.LowerCut = low; - layer.ImageSet.FitsProperties.ScaleType = (ScaleTypes)SelectedCurveStyle; - - e.CancelBubble = true; - } - - public void OnPointerUp(ElementEvent e) - { - Script.Literal("{0}.releasePointerCapture({1}.pointerId)", e.SrcElement, e); - if (dragType != DragType.None) - { - dragType = DragType.None; - SetUpdateTimer(); - ignoreNextClick = true; - } - e.CancelBubble = true; - } - - bool updated = false; - - public void SetUpdateTimer() - { - if (!RenderContext.UseGlVersion2) - { - Script.SetTimeout(delegate () { Update(); }, 500); - updated = false; - } - } - - public void Update() - { - if (updated) - { - return; - } - - if (image is FitsImageJs) - { - double factor = (layer.ImageSet.FitsProperties.MaxVal - layer.ImageSet.FitsProperties.MinVal) / 256.0; - double low = layer.ImageSet.FitsProperties.MinVal + (lowPosition * factor); - double hi = layer.ImageSet.FitsProperties.MinVal + (highPosition * factor); - tile.texture2d = ((FitsImageJs)image).GetScaledBitmap(low, hi, (ScaleTypes)SelectedCurveStyle, 0, null).GetTexture(); - } - updated = true; - } - - public int SelectedCurveStyle = 0; - - public void Draw() - { - CanvasElement canvas = Document.GetElementById("graph"); - CanvasContext2D ctx = (CanvasContext2D)canvas.GetContext(Rendering.Render2D); - if (image != null) - { - image.DrawHistogram(ctx); - } - - string red = "rgba(255,0,0,255)"; - string green = "rgba(0,255,0,255)"; - string blue = "rgba(0,0,255,255)"; - - ctx.StrokeStyle = red; - ctx.BeginPath(); - ctx.MoveTo(lowPosition, 0); - ctx.LineTo(lowPosition, 150); - - ctx.Stroke(); - - ctx.StrokeStyle = green; - ctx.BeginPath(); - ctx.MoveTo(highPosition, 0); - ctx.LineTo(highPosition, 150); - ctx.Stroke(); - - ctx.StrokeStyle = blue; - ctx.BeginPath(); - ctx.Arc(center, 75, 10, 0, Math.PI * 2, false); - ctx.ClosePath(); - ctx.Stroke(); - - - List Curve = new List(); - //todo get from combo box - - switch (SelectedCurveStyle) - { - case 0: // Linear - { - Curve.Clear(); - Curve.Add(Vector2d.Create(lowPosition, 150)); - Curve.Add(Vector2d.Create(highPosition, 0)); - break; - } - case 1: // Log - { - Curve.Clear(); - double factor = 150 / Math.Log(255); - double diff = (highPosition - lowPosition); - int jump = diff < 0 ? -1 : 1; - double step = Math.Abs(256.0 / (diff == 0 ? .000001 : diff)); - double val = .000001; - for (int i = lowPosition; i != highPosition; i += jump) - { - Curve.Add(Vector2d.Create((float)i, (float)(150 - (Math.Log(val) * factor)))); - val += step; - } - } - break; - case 2: // Power 2 - { - Curve.Clear(); - double factor = 150 / Math.Pow(255, 2); - double diff = (highPosition - lowPosition); - int jump = diff < 0 ? -1 : 1; - double step = Math.Abs(256.0 / (diff == 0 ? .000001 : diff)); - double val = .000001; - for (int i = lowPosition; i != highPosition; i += jump) - { - Curve.Add(Vector2d.Create((float)i, (float)(150 - (Math.Pow(val, 2) * factor)))); - val += step; - } - } - - break; - case 3: // Square Root - { - Curve.Clear(); - double factor = 150 / Math.Sqrt(255); - double diff = (highPosition - lowPosition); - int jump = diff < 0 ? -1 : 1; - double step = Math.Abs(256.0 / (diff == 0 ? .000001 : diff)); - double val = .000001; - for (int i = lowPosition; i != highPosition; i += jump) - { - Curve.Add(Vector2d.Create((float)i, (float)(150 - (Math.Sqrt(val) * factor)))); - val += step; - } - } - - break; - } - - if (Curve.Count > 1) - { - ctx.BeginPath(); - ctx.StrokeStyle = blue; - ctx.MoveTo(Curve[0].X, Curve[0].Y); - - for(int i = 1; i < Curve.Count; i++) - { - ctx.LineTo(Curve[i].X, Curve[i].Y); - } - ctx.Stroke(); - } - } - } -} diff --git a/engine/csharp_ref/Utilities/SimpleInput.cs b/engine/csharp_ref/Utilities/SimpleInput.cs deleted file mode 100644 index d4d7e5d9..00000000 --- a/engine/csharp_ref/Utilities/SimpleInput.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Xml; -using System.Html.Services; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public class SimpleInput - { - - public SimpleInput(string title, string label, string text, int v3) - { - Title = title; - Label = label; - Text = text; - } - - public DialogResult ShowDialog() - { - - return DialogResult.OK; - } - - public string Title = "Tile"; - public string Label = "Enter Text Below"; - public string Text = ""; - - private Action okCallback; - public void NonMenuClick(ElementEvent e) - { - if (!ignoreNextClick) - { - Close(); - } - ignoreNextClick = false; - } - - InputElement textElement = null; - - public void Show(Vector2d position, Action callback) - { - DivElement simpleInputElement = Document.GetElementById("simpleinput"); - DivElement modalElement = Document.GetElementById("simplemodal"); - modalElement.Style.Display = "block"; - simpleInputElement.Style.Display = "block"; - simpleInputElement.Style.MarginLeft = position.X.ToString() + "px"; - simpleInputElement.Style.MarginTop = position.Y.ToString() + "px"; - - textElement = Document.GetElementById("inputtext"); - textElement.Value = Text; - - DivElement titleDiv = Document.GetElementById("simpletitle"); - DivElement labelDiv = Document.GetElementById("inputlabel"); - titleDiv.InnerText = Title; - labelDiv.InnerText = Label; - - - - textElement.AddEventListener("change", TextChanged, false); - textElement.AddEventListener("click", IgnoreMe, true); - - //Window.AddEventListener("click", NonMenuClick, true); - - AnchorElement okButton = Document.GetElementById("simpleinputok"); - AnchorElement cancelButton = Document.GetElementById("simpleinputcancel"); - - okButton.AddEventListener("click", OkClicked, false); - cancelButton.AddEventListener("click", CancelClicked, false); - okCallback = callback; - } - - public void OkClicked(ElementEvent e) - { - Close(); - if (okCallback != null) - { - okCallback(); - } - } - - public void CancelClicked(ElementEvent e) - { - Close(); - } - - private void Close() - { - DivElement simpleInputElement = Document.GetElementById("simplemodal"); - simpleInputElement.Style.Display = "none"; - //Window.RemoveEventListener("click", NonMenuClick, true); - textElement.RemoveEventListener("change", TextChanged, false); - - AnchorElement okButton = Document.GetElementById("simpleinputok"); - AnchorElement cancelButton = Document.GetElementById("simpleinputcancel"); - - okButton.RemoveEventListener("click", OkClicked, false); - cancelButton.RemoveEventListener("click", CancelClicked, false); - } - - public void IgnoreMe(ElementEvent e) - { - ignoreNextClick = true; - } - - public void TextChanged(ElementEvent e) - { - Text = textElement.Value; - ignoreNextClick = true; - } - - - bool ignoreNextClick = false; - - } -} diff --git a/engine/csharp_ref/Utilities/XmlTextWriter.cs b/engine/csharp_ref/Utilities/XmlTextWriter.cs deleted file mode 100644 index ab591e30..00000000 --- a/engine/csharp_ref/Utilities/XmlTextWriter.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace wwtlib -{ - - public class XmlTextWriter - { - - public string Body = "\r\n"; - public Formatting Formatting = Formatting.Indented; - Stack elementStack = new Stack(); - bool pending = false; - string currentName = ""; - Dictionary attributes = new Dictionary(); - string value = ""; - void PushNewElement( string name) - { - //write pending element and attributes - - WritePending(false); - - //Push new attribute on to stack - elementStack.Push(name); - - //setup pending structures - pending = true; - currentName = name; - - - } - - private bool WritePending(bool fullClose) - { - bool closed = true; - if (pending) - { - for (int i = 1; i < elementStack.Count; i++) - { - Body += " "; - } - - Body += "<" + currentName; - if (attributes.Count > 0) - { - foreach (string key in attributes.Keys) - { - Body += string.Format(" {0}=\"{1}\"", key, attributes[key]); - } - } - - if (!string.IsNullOrEmpty(value)) - { - Body += ">"; - closed = false; - if (!string.IsNullOrEmpty(value)) - { - Body += value; - } - } - else - { - if (fullClose) - { - Body += " />\r\n"; - closed = true; - } - else - { - Body += ">\r\n"; - } - } - - pending = false; - currentName = ""; - value = ""; - attributes = new Dictionary(); - return closed; - } - - return false; - } - - internal void WriteProcessingInstruction(string v1, string v2) - { - - } - - internal void WriteStartElement(string name) - { - PushNewElement(name); - } - - internal void WriteAttributeString(string key, object value) - { - if (value != null) - { - attributes[key] = value.ToString().Replace("&", "&"); - } - else - { - attributes[key] = ""; - } - } - - internal void WriteEndElement() - { - if (!WritePending(true)) - { - for (int i = 1; i < elementStack.Count; i++) - { - Body += " "; - } - Body += string.Format("\r\n", elementStack.Pop()); - } - else - { - elementStack.Pop(); - } - } - - internal void WriteString(string text) - { - value = text.Replace("&", "&"); - } - - internal void WriteFullEndElement() - { - WritePending(false); - for (int i = 1; i < elementStack.Count; i++) - { - Body += " "; - } - Body += string.Format("\r\n", elementStack.Pop()); - } - - internal void Close() - { - } - - internal void WriteElementString(string name, string value) - { - WriteStartElement(name); - WriteValue(value.Replace("&", "&")); - WriteEndElement(); - } - - internal void WriteValue(string val) - { - value = val.Replace("&", "&"); - } - - - internal void WriteCData(string htmlDescription) - { - value = string.Format("", htmlDescription); - } - } - - public enum Formatting { Indented = 1 }; -} diff --git a/engine/csharp_ref/VideoOutputType.cs b/engine/csharp_ref/VideoOutputType.cs deleted file mode 100644 index 3f43e66d..00000000 --- a/engine/csharp_ref/VideoOutputType.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace wwtlib -{ - public class VideoOutputType - { - public double Fps; - public int Width; - public int Height; - public int TotalFrames = 0; - public bool WaitDownload = false; - public string Format = "image/jpeg"; - - public VideoOutputType(int width, int height, double fps, string format, bool waitDownload) - { - Width = width; - Height = height; - Fps = fps; - Format = format; - WaitDownload = waitDownload; - } - } -} diff --git a/engine/csharp_ref/ViewRederer.cs b/engine/csharp_ref/ViewRederer.cs deleted file mode 100644 index 8445e872..00000000 --- a/engine/csharp_ref/ViewRederer.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; - -namespace wwtlib -{ - public class ViewRenderer - { - public static ViewRenderer Singleton; - - public RenderContext RenderContext; - public CanvasElement Canvas; - public ViewRenderer() - { - } - - static ViewRenderer() - { - Singleton = new ViewRenderer(); - Singleton.RenderContext = new RenderContext(); - } - - - public void Render() - { - RenderTriangle.Width = RenderContext.Width = Canvas.Width; - RenderTriangle.Height = RenderContext.Height = Canvas.Height; - Tile.TilesInView = 0; - Tile.TilesTouched = 0; - RenderContext.Device.Save(); - RenderContext.Device.FillStyle = "black"; - RenderContext.Device.FillRect(0, 0, RenderContext.Width, RenderContext.Height); - //RenderContext.Device.ClearRect(0, 0, RenderContext.Width, RenderContext.Height); - RenderContext.Device.Restore(); - RenderContext.SetupMatricesSpace3d(RenderContext.Width, RenderContext.Height); - RenderContext.DrawImageSet(RenderContext.BackgroundImageSet, 1); - - int tilesInView = Tile.TilesInView; - int itlesTouched = Tile.TilesTouched; - } - - public void Move(double x, double y) - { - - RenderContext.ViewCamera.Lng += x * RenderContext.FovScale/6360.0; - RenderContext.ViewCamera.Lat += y * RenderContext.FovScale/6360.0; - if (RenderContext.ViewCamera.Lat > 90) - { - RenderContext.ViewCamera.Lat = 90; - } - - if (RenderContext.ViewCamera.Lat < -90) - { - RenderContext.ViewCamera.Lat = -90; - } - } - - public void Zoom(double factor) - { - - RenderContext.ViewCamera.Zoom *= factor; - - if (RenderContext.ViewCamera.Zoom > 360) - { - RenderContext.ViewCamera.Zoom = 360; - } - - } - - public void Setup() - { - CanvasElement canvas = (CanvasElement)Document.GetElementById("canvas"); - - canvas.AddEventListener("mousemove", OnMouseMove, false); - canvas.AddEventListener("mouseup", OnMouseUp, false); - canvas.AddEventListener("mousedown", OnMouseDown, false); - canvas.AddEventListener("mousewheel", OnMouseWheel, false); - Document.Body.AddEventListener("touchstart", OnTouchStart, false); - Document.Body.AddEventListener("touchmove", OnTouchMove, false); - Document.Body.AddEventListener("touchend", OnTouchEnd, false); - Document.Body.AddEventListener("gesturechange", OnGestureChange, false); - canvas.AddEventListener("mouseout", OnMouseUp, false); - - } - - public void OnGestureChange(ElementEvent e) - { - GestureEvent g = (GestureEvent) e; - mouseDown = false; - double delta = g.Scale; - - if (delta > 1 && Math.Abs(delta - 1) > .05) - { - Zoom(0.95); - } - else - { - Zoom(1.05); - } - } - - - public void OnTouchStart(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - mouseDown = true; - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - } - - public void OnTouchMove(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - if (mouseDown) - { - double curX = ev.TargetTouches[0].PageX - lastX; - - double curY = ev.TargetTouches[0].PageY - lastY; - - Move(curX, curY); - - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - } - } - - public void OnTouchEnd(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - mouseDown = false; - } - - bool mouseDown = false; - double lastX; - double lastY; - public void OnMouseDown(ElementEvent e) - { - mouseDown = true; - lastX = e.OffsetX; - lastY = e.OffsetY; - } - - public void OnMouseMove(ElementEvent e) - { - if (mouseDown) - { - Move(e.OffsetX - lastX, e.OffsetY - lastY); - - lastX = e.OffsetX; - lastY = e.OffsetY; - } - } - - public void OnMouseUp(ElementEvent e) - { - mouseDown = false; - - - } - - public void OnMouseWheel(ElementEvent e) - { - WheelEvent ev = (WheelEvent)(object)e; - //firefox - // double delta = event.detail ? event.detail * (-120) : event.wheelDelta; - double delta = ev.WheelDelta; - - if (delta > 0) - { - Zoom(0.9); - } - else - { - Zoom(1.1); - } - - } - - } - -} diff --git a/engine/csharp_ref/VizLayer.cs b/engine/csharp_ref/VizLayer.cs deleted file mode 100644 index fdd0f679..00000000 --- a/engine/csharp_ref/VizLayer.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Media.Graphics; - -namespace wwtlib -{ - public class VizLayer - { - public VizLayer() - { - } - - public List table = new List(); - public string[] header; - - public List items = new List(); - - ImageElement starProfile; - bool imageReady = false; - public void Load(string data) - { - string[] lines = data.Split("\r\n"); - - starProfile = (ImageElement)Document.CreateElement("img"); - starProfile.AddEventListener("load", delegate(ElementEvent e) { - imageReady = true; - }, false); - starProfile.Src = URLHelpers.singleton.engineAssetUrl("StarProfileAlpha.png"); - - bool gotHeader = false; - foreach (string line in lines) - { - if (gotHeader) - { - table.Add(line.Split("\t")); - } - else - { - header = line.Split("\t"); - gotHeader = true; - } - } - } - - int DateColumn = 0; - int latColumn = 1; - int lngColumn = 2; - int depthColumn = 3; - int magColumn = 4; - - public const double earthRadius = 6371000; - - Vector3d[] transformedList; - Vector3d[] worldList; - - public void Prepare() - { - worldList = new Vector3d[table.Count]; - transformedList = new Vector3d[table.Count]; - - int index = 0; - foreach (string[] row in table) - { - DataItem item = new DataItem(); - item.EventTime = Date.Parse(row[DateColumn]); - double radius = (earthRadius - double.Parse(row[depthColumn])*1000)/ earthRadius; - item.Location = Coordinates.GeoTo3dRad(double.Parse(row[latColumn]), double.Parse(row[lngColumn])+180, radius); - item.Tranformed = new Vector3d(); - item.Size = (float)Math.Pow(2, double.Parse(row[magColumn]))/50; - - worldList[index] = item.Location; - transformedList[index] = item.Tranformed; - items.Add(item); - index++; - } - } - - public void Draw(RenderContext renderContext) - { - if (!imageReady) - { - return; - } - - renderContext.Device.Save(); - - renderContext.WVP.ProjectArrayToScreen(worldList, transformedList); - CanvasContext2D ctx = renderContext.Device; - ctx.Alpha = .4; - - double width = renderContext.Width; - double height = renderContext.Height; - - Vector3d viewPoint = Vector3d.MakeCopy(renderContext.ViewPoint); - - double scaleFactor = renderContext.FovScale/100; - foreach (DataItem item in items) - { - // if (Vector3d.Dot(viewPoint, item.Location) < 0) - if (item.Tranformed.Z < 1) - { - double x = item.Tranformed.X; - double y = item.Tranformed.Y; - double size = 4*item.Size / scaleFactor; - double half = size / 2; - if (x > -half && x < width + half && y > -half && y < height + half) - { - ctx.DrawImage(starProfile, x - size / 2, y - size / 2, size, size); - - //ctx.BeginPath(); - //ctx.FillStyle = "rgb(200,0,0)"; - //ctx.Arc(x, y, size, 0, Math.PI * 2, true); - //ctx.Fill(); - } - } - - } - - renderContext.Device.Restore(); - - } - } - - public class DataItem - { - public DataItem() - { - } - - public Date EventTime; - public Vector3d Location; - public Vector3d Tranformed; - public Color Color; - public double Size; - public String GetColor() - { - return "Red"; - } - - } - - -} diff --git a/engine/csharp_ref/WWTControl.cs b/engine/csharp_ref/WWTControl.cs deleted file mode 100644 index a50478ec..00000000 --- a/engine/csharp_ref/WWTControl.cs +++ /dev/null @@ -1,3135 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Html; -using System.Html.Data.Files; -using System.Html.Media.Graphics; - - -namespace wwtlib -{ - public class WWTControl - { - public static WWTControl Singleton; - - public RenderContext RenderContext; - public CanvasElement Canvas; - - public WWTControl() - { - } - - public FolderBrowser Explorer; - - static WWTControl() - { - Singleton = new WWTControl(); - Singleton.RenderContext = new RenderContext(); - SpaceTimeController.last = Date.Now; - SpaceTimeController.UpdateClock(); - } - - // In "freestanding" mode, no worldwidetelescope.org resources are - // relied upon. The default screen is black sky, and the 3D solar system - // mode is unavailable because it relies on so many built-in assets. If - // you want to see anything, you need to load it in yourself. - - public bool FreestandingMode = false; - - // Note: ImageSets must remain public because there is JS code in the - // wild that accesses `WWTControl.imageSets`. - public static List ImageSets = new List(); - public static Folder ExploreRoot = new Folder(); - public static string ImageSetName = ""; - - public IUiController uiController = null; - - public static Imageset AddImageSetToRepository(Imageset imagesetToAdd) - { - foreach (Imageset imageset in ImageSets) { - if (imageset.ImageSetID == imagesetToAdd.ImageSetID) - { - return imageset; - } - } - - ImageSets.Add(imagesetToAdd); - return imagesetToAdd; - } - - public static List GetImageSets() - { - return ImageSets; - } - - List annotations = new List(); - internal void AddAnnotation(Annotation annotation) - { - annotations.Add(annotation); - Annotation.BatchDirty = true; - } - - internal void RemoveAnnotation(Annotation annotation) - { - annotations.Remove(annotation); - Annotation.BatchDirty = true; - } - - internal void ClearAnnotations() - { - annotations.Clear(); - Annotation.BatchDirty = true; - } - - private bool Annotationclicked(double ra, double dec, double x, double y) - { - if (annotations != null && annotations.Count > 0) - { - int index = 0; - foreach (Annotation note in annotations) - { - if (note.HitTest(RenderContext, ra, dec, x, y)) - { - scriptInterface.FireAnnotationclicked(ra, dec, note.ID); - return true; - } - index++; - } - } - return false; - } - - string hoverText = ""; - Vector2d hoverTextPoint = new Vector2d(); - Date lastMouseMove = new Date(1900, 1, 0, 0, 0, 0, 0); - - private bool AnnotationHover(double ra, double dec, double x, double y) - { - if (annotations != null && annotations.Count > 0) - { - int index = 0; - foreach (Annotation note in annotations) - { - if (note.HitTest(RenderContext, ra, dec, x, y)) - { - hoverText = note.Label; - hoverTextPoint = Vector2d.Create(x, y); - return true; - } - index++; - } - } - return false; - } - - public List Layers = new List(); - Date lastUpdate; - int frameCount = 0; - - double zoomMax = 360; - double zoomMaxSolarSystem = 10000000000000000; - public double ZoomMax - { - get - { - if (RenderContext.BackgroundImageset != null && RenderContext.BackgroundImageset.DataSetType == ImageSetType.SolarSystem) - { - return zoomMaxSolarSystem; - } - else - { - return zoomMax; - } - } - set { zoomMax = value; } - } - - public void SetSolarSystemMaxZoom(double value) - { - zoomMaxSolarSystem = value; - } - - double zoomMin = 0.001373291015625; - double zoomMinSolarSystem = 0.00000001; - - public double ZoomMin - { - get - { - if (RenderContext.BackgroundImageset != null && RenderContext.BackgroundImageset.DataSetType == ImageSetType.SolarSystem) - { - return zoomMinSolarSystem; - } - else - { - return zoomMin; - } - } - set { zoomMin = value; } - } - - public void SetSolarSystemMinZoom(double value) - { - zoomMinSolarSystem = value; - } - - public static bool showDataLayers = false; - - static bool renderNeeded = false; - public static bool RenderNeeded - { - get - { - return renderNeeded; - } - set - { - renderNeeded = true; - } - } - - public static Constellations constellationsFigures = null; - public static Constellations constellationsBoundries = null; - - - public string Constellation = "UMA"; - private void NotifyMoveComplete() - { - //if (!App.NoUI) - //{ - // ContextPanel.ContextPanelMaster.RunSearch(); - //} - - //Page.Master.OnArrived(); - } - - PositionColoredTextured[] fadePoints = null; - public BlendState Fader = BlendState.Create(true, 2000); - - private bool crossFadeFrame = false; - - private Texture crossFadeTexture = null; - public bool CrossFadeFrame - { - set - { - if (value && crossFadeFrame != value) - { - if (crossFadeTexture != null) - { - // crossFadeTexture.Dispose(); - } - crossFadeTexture = RenderContext.GetScreenTexture(); - - } - crossFadeFrame = value; - - if (!value) - { - if (crossFadeTexture != null) - { - // crossFadeTexture.Dispose(); - crossFadeTexture = null; - } - } - } - get - { - return crossFadeFrame; - } - } - - private Sprite2d sprite = new Sprite2d(); - - private void FadeFrame() - { - if (RenderContext.gl != null) - { - SettingParameter sp = Settings.Active.GetSetting(StockSkyOverlayTypes.FadeToBlack); - if ((sp.Opacity > 0)) - { - Color color = Color.FromArgbColor(255 - (int)UiTools.Gamma(255 - (int)(sp.Opacity * 255), 1 / 2.2f), Colors.Black); - - if (!(sp.Opacity > 0)) - { - color = Color.FromArgbColor(255 - (int)UiTools.Gamma(255 - (int)(sp.Opacity * 255), 1 / 2.2f), Colors.Black); - } - - - if (crossFadeFrame) - { - color = Color.FromArgbColor((int)UiTools.Gamma((int)((sp.Opacity) * 255), 1 / 2.2f), Colors.White); - } - else - { - if (crossFadeTexture != null) - { - // crossFadeTexture.Dispose(); - crossFadeTexture = null; - } - } - if (fadePoints == null) - { - fadePoints = new PositionColoredTextured[4]; - for (int i = 0; i < 4; i++) - { - fadePoints[i] = new PositionColoredTextured(); - } - } - - - fadePoints[0].Position.X = -RenderContext.Width / 2; - fadePoints[0].Position.Y = RenderContext.Height / 2; - fadePoints[0].Position.Z = 1347; - fadePoints[0].Tu = 0; - fadePoints[0].Tv = 1; - fadePoints[0].Color = color; - - fadePoints[1].Position.X = -RenderContext.Width / 2; - fadePoints[1].Position.Y = -RenderContext.Height / 2; - fadePoints[1].Position.Z = 1347; - fadePoints[1].Tu = 0; - fadePoints[1].Tv = 0; - fadePoints[1].Color = color; - - fadePoints[2].Position.X = RenderContext.Width / 2; - fadePoints[2].Position.Y = RenderContext.Height / 2; - fadePoints[2].Position.Z = 1347; - fadePoints[2].Tu = 1; - fadePoints[2].Tv = 1; - fadePoints[2].Color = color; - - fadePoints[3].Position.X = RenderContext.Width / 2; - fadePoints[3].Position.Y = -RenderContext.Height / 2; - fadePoints[3].Position.Z = 1347; - fadePoints[3].Tu = 1; - fadePoints[3].Tv = 0; - fadePoints[3].Color = color; - - sprite.Draw(RenderContext, fadePoints, 4, crossFadeTexture, true, 1); - } - } - } - - public ImageSetType RenderType = ImageSetType.Sky; - - private Imageset milkyWayBackground = null; - - public bool CapturingVideo = false; - - private BlobReady videoBlobReady = null; - - public VideoOutputType dumpFrameParams = null; - - private Dictionary videoBlobQueue = new Dictionary(); - - private int videoQueueIndex = 0; - - private List emptyFrames = new List(); - - public void CaptureVideo(BlobReady VideoBlobReady, int Width, int Height, double FramesPerSecond, int TotalFrames, string Format) - { - CapturingVideo = true; - videoBlobReady = VideoBlobReady; - videoBlobQueue.Clear(); - videoQueueIndex = 0; - emptyFrames.Clear(); - dumpFrameParams = new VideoOutputType(Width, Height, FramesPerSecond, Format, true); - SpaceTimeController.FrameDumping = true; - SpaceTimeController.FramesPerSecond = FramesPerSecond; - SpaceTimeController.TotalFrames = TotalFrames; - SpaceTimeController.CurrentFrameNumber = 0; - } - - // To preserve semantic backwards compatibility, this function must requeue itself - // to be called again in a timeout. - public void Render() - { - RenderOneFrame(); - Script.SetTimeout(delegate () { Render(); }, 10); - } - - public void RenderOneFrame() - { - if (RenderContext.BackgroundImageset != null) - { - RenderType = RenderContext.BackgroundImageset.DataSetType; - } - else - { - RenderType = ImageSetType.Sky; - } - - bool sizeChange = false; - - if (Canvas.Width != Canvas.ParentNode.ClientWidth) - { - Canvas.Width = Canvas.ParentNode.ClientWidth; - sizeChange = true; - } - - if (Canvas.Height != Canvas.ParentNode.ClientHeight) - { - Canvas.Height = Canvas.ParentNode.ClientHeight; - sizeChange = true; - } - - if (sizeChange && Explorer != null) - Explorer.Refresh(); - - if (Canvas.Width < 1 || Canvas.Height < 1) { - // This can happen during initialization if perhaps some - // HTML/JavaScript interaction hasn't happened to set the canvas - // size correctly. If we don't exit this function early, we get - // NaNs in our transformation matrices that lead IsTileBigEnough - // to say "no" for everything so that we spin out of control - // downloading maximum-resolution DSS tiles for an enormous - // viewport. That's bad! - return; - } - - if (sizeChange) { - // In GL, the crosshairs are in viewport coordinates - // ([0,1]x[0,1]), so a size change alters their perceived aspect - // ratio. - crossHairs = null; - } - - Tile.lastDeepestLevel = Tile.deepestLevel; - - RenderTriangle.Width = RenderContext.Width = Canvas.Width; - RenderTriangle.Height = RenderContext.Height = Canvas.Height; - Tile.TilesInView = 0; - Tile.TilesTouched = 0; - Tile.deepestLevel = 0; - - SpaceTimeController.MetaNow = Date.Now; - - if (Mover != null) - { - SpaceTimeController.Now = Mover.CurrentDateTime; - - Planets.UpdatePlanetLocations(SolarSystemMode); - - if (Mover != null) - { - CameraParameters newCam = Mover.CurrentPosition; - - RenderContext.TargetCamera = newCam.Copy(); - RenderContext.ViewCamera = newCam.Copy(); - if (RenderContext.Space && Settings.Active.GalacticMode) - { - double[] gPoint = Coordinates.J2000toGalactic(newCam.RA * 15, newCam.Dec); - - RenderContext.targetAlt = RenderContext.alt = gPoint[1]; - RenderContext.targetAz = RenderContext.az = gPoint[0]; - } - else if (RenderContext.Space && Settings.Active.LocalHorizonMode) - { - Coordinates currentAltAz = Coordinates.EquitorialToHorizon(Coordinates.FromRaDec(newCam.RA, newCam.Dec), SpaceTimeController.Location, SpaceTimeController.Now); - - RenderContext.targetAlt = RenderContext.alt = currentAltAz.Alt; - RenderContext.targetAz = RenderContext.az = currentAltAz.Az; - } - - if (Mover.Complete) - { - //Todo Notify interested parties that move is complete - scriptInterface.FireArrived(Mover.CurrentPosition.RA, Mover.CurrentPosition.Dec, WWTControl.Singleton.RenderContext.ViewCamera.Zoom); - Mover = null; - - NotifyMoveComplete(); - } - } - } - else - { - SpaceTimeController.UpdateClock(); - - Planets.UpdatePlanetLocations(SolarSystemMode); - - UpdateViewParameters(); - } - - RenderContext.Clear(); - - if (RenderType == ImageSetType.SolarSystem) - { - { - if ((int)SolarSystemTrack < (int)SolarSystemObjects.Custom) - { - double radius = Planets.GetAdjustedPlanetRadius((int)SolarSystemTrack); - double distance = RenderContext.SolarSystemCameraDistance; - double camAngle = RenderContext.FovLocal; - //double distrad = distance / (radius * Math.Tan(.5 * camAngle)); - } - - if (trackingObject == null) - { - //todo fix this trackingObject = Search.FindCatalogObject("Sun"); - } - - RenderContext.SetupMatricesSolarSystem(true); - - //float skyOpacity = 1.0f - Planets.CalculateSkyBrightnessFactor(RenderContext11.View, viewCamera.ViewTarget); - //if (float.IsNaN(skyOpacity)) - //{ - // skyOpacity = 0f; - //} - - double zoom = RenderContext.ViewCamera.Zoom; - float milkyWayBlend = (float)Math.Min(1.0, Math.Max(0, (Math.Log(zoom) - 8.4)) / 4.2); - float milkyWayBlendIn = (float)Math.Min(1.0, Math.Max(0, (Math.Log(zoom) - 17.9)) / 2.3); - - Matrix3d matOldMW = RenderContext.World; - Matrix3d matLocalMW = RenderContext.World.Clone(); - matLocalMW.Multiply(Matrix3d.Scaling(100000, 100000, 100000)); - matLocalMW.Multiply(Matrix3d.RotationX(23.5 / 180 * Math.PI)); - // matLocalMW.Multiply(Matrix3d.RotationY(Math.PI)); - matLocalMW.Multiply(Matrix3d.Translation(RenderContext.CameraPosition)); //todo change this when tracking is added back - RenderContext.World = matLocalMW; - RenderContext.WorldBase = matLocalMW; - RenderContext.Space = true; - RenderContext.MakeFrustum(); - bool lighting = RenderContext.Lighting; - RenderContext.Lighting = false; - if (Settings.Active.SolarSystemMilkyWay) - { - if (milkyWayBlend < 1) // Solar System mode Milky Way background - { - if (milkyWayBackground == null) - { - milkyWayBackground = GetImagesetByName("Digitized Sky Survey (Color)"); - } - - if (milkyWayBackground != null) - { - RenderTriangle.CullInside = true; - float c = ((1 - milkyWayBlend)) / 2; - - - RenderContext.DrawImageSet(milkyWayBackground, c * 100); - - RenderTriangle.CullInside = false; - } - } - } - - DrawSkyOverlays(); - RenderContext.Lighting = lighting; - - RenderContext.Space = false; - RenderContext.World = matOldMW; - RenderContext.WorldBase = matOldMW; - RenderContext.MakeFrustum(); - //// CMB - - //float cmbBlend = (float)Math.Min(1, Math.Max(0, (Math.Log(zoom) - 33)) / 2.3); - - - //double cmbLog = Math.Log(zoom); - - //if (Properties.Settings.Default.SolarSystemCMB.State) - //{ - // if (cmbBlend > 0) // Solar System mode Milky Way background - // { - // if (cmbBackground == null) - // { - // cmbBackground = GetImagesetByName("Planck CMB"); - // } - - // if (cmbBackground != null) - // { - // float c = ((cmbBlend)) / 16; - // Matrix3d matOldMW = RenderContext11.World; - // Matrix3d matLocalMW = RenderContext11.World; - // //double dist = UiTools.AuPerLightYear*46000000000; - // matLocalMW.Multiply(Matrix3d.Scaling(2.9090248982E+15, 2.9090248982E+15, 2.9090248982E+15)); - // matLocalMW.Multiply(Matrix3d.RotationX(-23.5 / 180 * Math.PI)); - // matLocalMW.Multiply(Matrix3d.RotationY(Math.PI)); - // // matLocalMW.Multiply(Matrix3d.Translation(cameraOffset)); - // RenderContext11.World = matLocalMW; - // RenderContext11.WorldBase = matLocalMW; - // Earth3d.MainWindow.MakeFrustum(); - - // RenderContext11.SetupBasicEffect(BasicEffect.TextureColorOpacity, 1, Color.White); - // //SetupMatricesSpace11(60, renderType); - // RenderContext11.DepthStencilMode = DepthStencilMode.Off; - // DrawTiledSphere(cmbBackground, c * Properties.Settings.Default.SolarSystemCMB.Opacity, Color.FromArgb(255, 255, 255, 255)); - // RenderContext11.World = matOldMW; - // RenderContext11.WorldBase = matOldMW; - // RenderContext11.DepthStencilMode = DepthStencilMode.ZReadWrite; - // } - // } - //} - - { - Vector3d oldCamera = RenderContext.CameraPosition; - Matrix3d matOld = RenderContext.World; - - Matrix3d matLocal = RenderContext.World; - matLocal.Multiply(Matrix3d.Translation(RenderContext.ViewCamera.ViewTarget)); - RenderContext.CameraPosition = Vector3d.SubtractVectors(RenderContext.CameraPosition, RenderContext.ViewCamera.ViewTarget); - RenderContext.World = matLocal; - RenderContext.MakeFrustum(); - - if (Settings.Active.SolarSystemCosmos) - { - // RenderContext11.DepthStencilMode = DepthStencilMode.Off; - // Grids.DrawCosmos3D(RenderContext, Properties.Settings.Default.SolarSystemCosmos.Opacity * skyOpacity); - Grids.DrawCosmos3D(RenderContext, 1.0f); - // RenderContext11.DepthStencilMode = DepthStencilMode.ZReadWrite; - } - - // if (true) - // { - // RenderContext11.DepthStencilMode = DepthStencilMode.Off; - - // Grids.DrawCustomCosmos3D(RenderContext11, skyOpacity); - - // RenderContext11.DepthStencilMode = DepthStencilMode.ZReadWrite; - // } - - - if (Settings.Active.SolarSystemMilkyWay && milkyWayBlendIn > 0) - { - //Grids.DrawGalaxy3D(RenderContext11, Properties.Settings.Default.SolarSystemMilkyWay.Opacity * skyOpacity * milkyWayBlendIn); - - Grids.DrawGalaxyImage(RenderContext, milkyWayBlendIn); - } - - if (Settings.Active.SolarSystemStars) - { - Grids.DrawStars3D(RenderContext, 1); - } - - matLocal = matOld; - Vector3d pnt = RenderContext.ViewCamera.ViewTarget; - Vector3d vt = Vector3d.Create(-pnt.X, -pnt.Y, -pnt.Z); - RenderContext.CameraPosition = oldCamera; - matLocal.Multiply(Matrix3d.Translation(vt)); - RenderContext.World = matLocal; - RenderContext.MakeFrustum(); - - LayerManager.Draw(RenderContext, 1.0f, true, "Sky", true, false); - - RenderContext.World = matOld; - RenderContext.MakeFrustum(); - } - - if (RenderContext.SolarSystemCameraDistance < 15000) - { - RenderContext.SetupMatricesSolarSystem(false); - - if (Settings.Active.SolarSystemMinorPlanets) - { - MinorPlanets.DrawMPC3D(RenderContext, 1, RenderContext.ViewCamera.ViewTarget); - } - - if (Settings.Active.SolarSystemPlanets) - { - Planets.DrawPlanets3D(RenderContext, 1, RenderContext.ViewCamera.ViewTarget); - } - } - - //double p = Math.Log(zoom); - //double d = (180 / SolarSystemCameraDistance) * 100; // (SolarSystemCameraDistance * SolarSystemCameraDistance) * 10000000; - - //float sunAtDistance = (float)Math.Min(1, Math.Max(0, (Math.Log(zoom) - 7.5)) / 3); - - //if (sunAtDistance > 0) - //{ - // Planets.DrawPointPlanet(RenderContext11, new Vector3d(0, 0, 0), (float)d * sunAtDistance, Color.FromArgb(192, 191, 128), false, 1); - //} - - //if ((SolarSystemMode) && label != null && !TourPlayer.Playing) - //{ - // label.Draw(RenderContext11, true); - //} - } - } - else // RenderType is not SolarSystem - { - if (RenderType == ImageSetType.Earth || RenderType == ImageSetType.Planet) - { - RenderContext.SetupMatricesLand3d(); - } - else - { - RenderContext.SetupMatricesSpace3d(RenderContext.Width, RenderContext.Height); - } - - RenderContext.DrawImageSet(RenderContext.BackgroundImageset, 100); - - if (RenderContext.ForegroundImageset != null) - { - if (RenderContext.ForegroundImageset.DataSetType != RenderContext.BackgroundImageset.DataSetType) - { - RenderContext.ForegroundImageset = null; - } - else - { - if (RenderContext.ViewCamera.Opacity != 100 && RenderContext.gl == null) - { - if (foregroundCanvas.Width != RenderContext.Width || foregroundCanvas.Height != RenderContext.Height) - { - foregroundCanvas.Width = (int)RenderContext.Width; - foregroundCanvas.Height = (int)RenderContext.Height; - } - - CanvasContext2D saveDevice = RenderContext.Device; - fgDevice.ClearRect(0, 0, RenderContext.Width, RenderContext.Height); - RenderContext.Device = fgDevice; - RenderContext.DrawImageSet(RenderContext.ForegroundImageset, 100); - RenderContext.Device = saveDevice; - RenderContext.Device.Save(); - RenderContext.Device.Alpha = RenderContext.ViewCamera.Opacity / 100; - RenderContext.Device.DrawImage(foregroundCanvas, 0, 0); - RenderContext.Device.Restore(); - } - else - { - RenderContext.DrawImageSet(RenderContext.ForegroundImageset, RenderContext.ViewCamera.Opacity); - } - } - } - - if (RenderType == ImageSetType.Sky) - { - foreach (Imageset imageset in RenderContext.CatalogHipsImagesets) - { - if (imageset.HipsProperties.CatalogSpreadSheetLayer.Enabled - && imageset.HipsProperties.CatalogSpreadSheetLayer.lastVersion == imageset.HipsProperties.CatalogSpreadSheetLayer.Version) - { - RenderContext.DrawImageSet(imageset, 100); - } - } - } - - if (RenderType == ImageSetType.Sky && Settings.Active.ShowSolarSystem) - { - Planets.DrawPlanets(RenderContext, 1); - - Constellation = Constellations.Containment.FindConstellationForPoint(RenderContext.ViewCamera.RA, RenderContext.ViewCamera.Dec); - - DrawSkyOverlays(); - - //LayerManager.Draw(RenderContext, 1.0f, true, "Sky", true, true); - } - - // if (RenderType == ImageSetType.Earth) - //{ - - // LayerManager.Draw(RenderContext, 1.0f, false, "Earth", false, false); - //} - - if (PlanetLike || Space) - { - if (!Space) - { - //todo fix this for other planets.. - double angle = Coordinates.MstFromUTC2(SpaceTimeController.Now, 0) / 180.0 * Math.PI; - RenderContext.WorldBaseNonRotating = Matrix3d.MultiplyMatrix(Matrix3d.RotationY(angle), RenderContext.WorldBase); - if (targetBackgroundImageset != null) - { - RenderContext.NominalRadius = targetBackgroundImageset.MeanRadius; - } - } - else - { - RenderContext.WorldBaseNonRotating = RenderContext.World; - if (targetBackgroundImageset != null) - { - RenderContext.NominalRadius = targetBackgroundImageset.MeanRadius; - } - } - - string referenceFrame = GetCurrentReferenceFrame(); - LayerManager.Draw(RenderContext, 1.0f, Space, referenceFrame, true, Space); - } - - - } - - Matrix3d worldSave = RenderContext.World; - Matrix3d viewSave = RenderContext.View; - Matrix3d projSave = RenderContext.Projection; - - if (Settings.Current.ShowCrosshairs) - { - DrawCrosshairs(RenderContext); - } - - if (uiController != null) - { - uiController.Render(RenderContext); - } - else - { - int index = 0; - Annotation.PrepBatch(RenderContext); - foreach (Annotation item in annotations) - { - item.Draw(RenderContext); - index++; - } - - Annotation.DrawBatch(RenderContext); - - if ((Date.Now - lastMouseMove) > 400) - { - Vector2d raDecDown = GetCoordinatesForScreenPoint(hoverTextPoint.X, hoverTextPoint.Y); - this.AnnotationHover(raDecDown.X, raDecDown.Y, hoverTextPoint.X, hoverTextPoint.Y); - lastMouseMove = new Date(2100, 1, 1); - } - - if (!string.IsNullOrEmpty(hoverText)) - { - DrawHoverText(RenderContext); - } - } - - bool tilesAllLoaded = TileCache.QueueCount == 0; - - RenderContext.SetupMatricesOverlays(); - FadeFrame(); - //RenderContext.Clear(); - //int tilesInView = Tile.TilesInView; - //int itlesTouched = Tile.TilesTouched; - - frameCount++; - - //TileCache.PurgeLRU(); - TileCache.DecimateQueue(); - TileCache.ProcessQueue(RenderContext); - Tile.CurrentRenderGeneration++; - - if (!TourPlayer.Playing) - { - CrossFadeFrame = false; - } - // Restore Matrixies for Finder Scope and such to map points - - RenderContext.World = worldSave; - RenderContext.View = viewSave; - RenderContext.Projection = projSave; - - Date now = Date.Now; - - int ms = now - lastUpdate; - if (ms > 1000) - { - lastUpdate = now; - frameCount = 0; - RenderTriangle.TrianglesRendered = 0; - RenderTriangle.TrianglesCulled = 0; - } - - if (CapturingVideo) - { - if ((dumpFrameParams != null) && (!dumpFrameParams.WaitDownload || tilesAllLoaded)) - { - CaptureFrameForVideo(videoBlobReady, dumpFrameParams.Width, dumpFrameParams.Height, dumpFrameParams.Format); - SpaceTimeController.NextFrame(); - } - if (SpaceTimeController.DoneDumping) - { - SpaceTimeController.FrameDumping = false; - SpaceTimeController.CancelFrameDump = false; - CapturingVideo = false; - } - } - } - - public string GetCurrentReferenceFrame() - { - if (RenderContext.BackgroundImageset == null) - { - return "Sun"; - } - - if (!string.IsNullOrEmpty(RenderContext.BackgroundImageset.ReferenceFrame)) - { - return RenderContext.BackgroundImageset.ReferenceFrame; - } - if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.Earth) - { - return "Earth"; - } - if (RenderContext.BackgroundImageset.Name == "Visible Imagery" && RenderContext.BackgroundImageset.Url.ToLowerCase().IndexOf("mars") > -1) - { - - RenderContext.BackgroundImageset.ReferenceFrame = "Mars"; - return RenderContext.BackgroundImageset.ReferenceFrame; - } - - if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.Planet) - { - foreach (string name in SolarSystemObjectsNames) - { - if (RenderContext.BackgroundImageset.Name.ToLowerCase().IndexOf(name.ToLowerCase()) > -1) - { - RenderContext.BackgroundImageset.ReferenceFrame = name; - return name; - } - } - } - if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.Sky) - { - return "Sky"; - } - return ""; - } - - public static string[] SolarSystemObjectsNames = - { - "Sun", - "Mercury", - "Venus", - "Mars", - "Jupiter", - "Saturn", - "Uranus", - "Neptune", - "Pluto", - "Moon", - "Io", - "Europa", - "Ganymede", - "Callisto", - "IoShadow", - "EuropaShadow", - "GanymedeShadow", - "CallistoShadow", - "SunEclipsed", - "Earth", - "Custom", - "Undefined" - }; - - public bool PlanetLike - { - get - { - if (RenderContext.BackgroundImageset != null) - { - return RenderContext.BackgroundImageset.DataSetType == ImageSetType.Earth || RenderContext.BackgroundImageset.DataSetType == ImageSetType.Planet; - } - else - { - return true; - } - } - } - - public bool Space - { - get - { - if (RenderContext.BackgroundImageset != null) - { - return RenderContext.BackgroundImageset.DataSetType == ImageSetType.Sky; - } - else - { - return true; - } - } - } - - private void DrawSkyOverlays() - { - if (Settings.Active.ShowConstellationPictures && !FreestandingMode) - { - Constellations.DrawArtwork(RenderContext); - } - - if (Settings.Active.ShowConstellationFigures) - { - if (constellationsFigures == null) - { - constellationsFigures = Constellations.Create( - "Constellations", - URLHelpers.singleton.engineAssetUrl("figures.txt"), - false, // "boundry" - false, // "noInterpollation" - false // "resource" - ); - } - - constellationsFigures.Draw(RenderContext, false, "UMA", false); - } - - if (Settings.Active.ShowEclipticGrid) - { - Grids.DrawEclipticGrid(RenderContext, 1, Settings.Active.EclipticGridColor); - if (Settings.Active.ShowEclipticGridText) - { - Grids.DrawEclipticGridText(RenderContext, 1, Settings.Active.EclipticGridColor); - } - } - - if (Settings.Active.ShowGalacticGrid) - { - Grids.DrawGalacticGrid(RenderContext, 1, Settings.Active.GalacticGridColor); - if (Settings.Active.ShowGalacticGridText) - { - Grids.DrawGalacticGridText(RenderContext, 1, Settings.Active.GalacticGridColor); - } - } - - if (Settings.Active.ShowAltAzGrid) - { - Grids.DrawAltAzGrid(RenderContext, 1, Settings.Active.AltAzGridColor); - if (Settings.Active.ShowAltAzGridText) - { - Grids.DrawAltAzGridText(RenderContext, 1, Settings.Active.AltAzGridColor); - } - } - - if (Settings.Active.ShowPrecessionChart) - { - Grids.DrawPrecessionChart(RenderContext, 1, Settings.Active.PrecessionChartColor); - - } - - if (Settings.Active.ShowEcliptic) - { - Grids.DrawEcliptic(RenderContext, 1, Settings.Active.EclipticColor); - if (Settings.Active.ShowEclipticOverviewText) - { - Grids.DrawEclipticText(RenderContext, 1, Settings.Active.EclipticColor); - } - } - - if (Settings.Active.ShowGrid) - { - Grids.DrawEquitorialGrid(RenderContext, 1, Settings.Active.EquatorialGridColor); - if (Settings.Active.ShowEquatorialGridText) - { - Grids.DrawEquitorialGridText(RenderContext, 1, Settings.Active.EquatorialGridColor); - } - } - - if (Settings.Active.ShowConstellationBoundries) - { - if (constellationsBoundries == null) - { - constellationsBoundries = Constellations.Create( - "Constellations", - URLHelpers.singleton.engineAssetUrl("constellations.txt"), - true, // "boundry" - false, // "noInterpollation" - false // "resource" - ); - } - constellationsBoundries.Draw(RenderContext, Settings.Active.ShowConstellationSelection, Constellation, false); - } - - - - if (Settings.Active.ShowConstellationLabels) - { - Constellations.DrawConstellationNames(RenderContext, 1, Colors.Yellow); - } - } - - private void DrawHoverText(RenderContext RenderContext) - { - if (RenderContext.gl == null) - { - CanvasContext2D ctx = RenderContext.Device; - ctx.Save(); - - ctx.FillStyle = "White"; - ctx.Font = "15px Arial"; - ctx.FillText(hoverText, hoverTextPoint.X, hoverTextPoint.Y); - ctx.Restore(); - } - } - - - public double RAtoViewLng(double ra) - { - return (((180 - ((ra) / 24.0 * 360) - 180) + 540) % 360) - 180; - } - - private const double DragCoefficient = 0.8; - - - private void UpdateViewParameters() - { - if (RenderContext.Space && tracking && trackingObject != null) - { - if (Settings.Active.GalacticMode && RenderContext.Space) - { - double[] gPoint = Coordinates.J2000toGalactic(trackingObject.RA * 15, trackingObject.Dec); - - RenderContext.targetAlt = RenderContext.alt = gPoint[1]; - RenderContext.targetAz = RenderContext.az = gPoint[0]; - } - else if (RenderContext.Space && Settings.Active.LocalHorizonMode) - { - Coordinates currentAltAz = Coordinates.EquitorialToHorizon(Coordinates.FromRaDec(trackingObject.RA, trackingObject.Dec), SpaceTimeController.Location, SpaceTimeController.Now); - - RenderContext.targetAlt = currentAltAz.Alt; - RenderContext.targetAz = currentAltAz.Az; - } - else - { - RenderContext.ViewCamera.Lng = RenderContext.TargetCamera.Lng = this.RAtoViewLng(trackingObject.RA); - RenderContext.ViewCamera.Lat = RenderContext.TargetCamera.Lat = trackingObject.Dec; - } - } - else if (!SolarSystemMode) - { - tracking = false; - trackingObject = null; - } - - double oneMinusDragCoefficient = 1 - DragCoefficient; - double dc = DragCoefficient; - - //if (!Settings.Current.SmoothPan) - //{ - // oneMinusDragCoefficient = 1; - // dc = 0; - //} - if (!tracking) - { - double minDelta = (RenderContext.ViewCamera.Zoom / 4000.0); - if (RenderContext.ViewCamera.Zoom > 360) - { - minDelta = (360.0 / 40000.0); - } - //if (RenderContext.Space && Settings.Active.LocalHorizonMode) - //{ - // //if (!Settings.Current.SmoothPan) - // //{ - // // this.alt = targetAlt; - // // this.az = targetAz; - // //} - - // if (((Math.Abs(this.TargetAlt - this.alt) >= (minDelta)) | - // ((Math.Abs(this.targetAz - this.az) >= (minDelta))))) - // { - // this.alt += (targetAlt - alt) / 10; - - // if (Math.Abs(targetAz - az) > 170) - // { - // if (targetAz > az) - // { - // this.az += (targetAz - (360 + az)) / 10; - // } - // else - // { - // this.az += ((360 + targetAz) - az) / 10; - // } - // } - // else - // { - // this.az += (targetAz - az) / 10; - // } - - // //this.az = ((az + 540) % 360) - 180; - // this.az = ((az + 720) % 360); - - // } - //} - //else - - - //if (!Settings.Current.SmoothPan) - //{ - // this.viewCamera.Lat = this.targetCamera.Lat; - // this.viewCamera.Lng = this.targetCamera.Lng; - //} - if (RenderContext.Space && (Settings.Active.LocalHorizonMode || Settings.Active.GalacticMode)) - { - if (((Math.Abs(RenderContext.targetAlt - RenderContext.alt) >= (minDelta)) | - ((Math.Abs(RenderContext.targetAz - RenderContext.az) >= (minDelta))))) - { - RenderContext.alt += (RenderContext.targetAlt - RenderContext.alt) / 10; - - if (Math.Abs(RenderContext.targetAz - RenderContext.az) > 170) - { - if (RenderContext.targetAz > RenderContext.az) - { - RenderContext.az += (RenderContext.targetAz - (360 + RenderContext.az)) / 10; - } - else - { - RenderContext.az += ((360 + RenderContext.targetAz) - RenderContext.az) / 10; - } - } - else - { - RenderContext.az += (RenderContext.targetAz - RenderContext.az) / 10; - } - RenderContext.az = ((RenderContext.az + 720) % 360); - } - } - else - { - if (((Math.Abs(RenderContext.TargetCamera.Lat - RenderContext.ViewCamera.Lat) >= (minDelta)) | - ((Math.Abs(RenderContext.TargetCamera.Lng - RenderContext.ViewCamera.Lng) >= (minDelta))))) - { - RenderContext.ViewCamera.Lat += (RenderContext.TargetCamera.Lat - RenderContext.ViewCamera.Lat) / 10; - - if (Math.Abs(RenderContext.TargetCamera.Lng - RenderContext.ViewCamera.Lng) > 170) - { - if (RenderContext.TargetCamera.Lng > RenderContext.ViewCamera.Lng) - { - RenderContext.ViewCamera.Lng += (RenderContext.TargetCamera.Lng - (360 + RenderContext.ViewCamera.Lng)) / 10; - } - else - { - RenderContext.ViewCamera.Lng += ((360 + RenderContext.TargetCamera.Lng) - RenderContext.ViewCamera.Lng) / 10; - } - } - else - { - RenderContext.ViewCamera.Lng += (RenderContext.TargetCamera.Lng - RenderContext.ViewCamera.Lng) / 10; - } - - RenderContext.ViewCamera.Lng = ((RenderContext.ViewCamera.Lng + 720) % 360); - } - else - { - if (RenderContext.ViewCamera.Lat != RenderContext.TargetCamera.Lat || RenderContext.ViewCamera.Lng != RenderContext.TargetCamera.Lng) - { - RenderContext.ViewCamera.Lat = RenderContext.TargetCamera.Lat; - RenderContext.ViewCamera.Lng = RenderContext.TargetCamera.Lng; - } - } - } - } - - - - //if (!tracking) - //{ - // this.viewCamera.Lng = dc * this.viewCamera.Lng + oneMinusDragCoefficient * this.targetCamera.Lng; - // this.viewCamera.Lat = dc * this.viewCamera.Lat + oneMinusDragCoefficient * this.targetCamera.Lat; - //} - RenderContext.ViewCamera.Zoom = dc * RenderContext.ViewCamera.Zoom + oneMinusDragCoefficient * RenderContext.TargetCamera.Zoom; - RenderContext.ViewCamera.Rotation = dc * RenderContext.ViewCamera.Rotation + oneMinusDragCoefficient * RenderContext.TargetCamera.Rotation; - RenderContext.ViewCamera.Angle = dc * RenderContext.ViewCamera.Angle + oneMinusDragCoefficient * RenderContext.TargetCamera.Angle; - - - } - - public void Move(double x, double y) - { - // Emulate MoveView() in the Windows client -- rotate the x and y - // offsets if the view is rotated. Our signs are the opposite of - // the Windows client. - - double angle = Math.Atan2(y, x); - double distance = Math.Sqrt(x * x + y * y); - - if (SolarSystemMode || PlanetLike) { - x = Math.Cos(angle + RenderContext.ViewCamera.Rotation) * distance; - y = Math.Sin(angle + RenderContext.ViewCamera.Rotation) * distance; - } else { - x = Math.Cos(angle - RenderContext.ViewCamera.Rotation) * distance; - y = Math.Sin(angle - RenderContext.ViewCamera.Rotation) * distance; - } - - // Apply the rotated offsets. The following merges up GetPixelScale{X,Y}() - // and MoveViewNative() of the Windows client. - - double scaleY = RenderContext.FovScale / 3600.0; - - if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.SolarSystem) - { - scaleY = .06; - } - - double scaleX = scaleY / Math.Max(.2, Math.Cos(RenderContext.ViewCamera.Lat / 180.0 * Math.PI)); - - if (RenderContext.BackgroundImageset.DataSetType == ImageSetType.Earth || - RenderContext.BackgroundImageset.DataSetType == ImageSetType.Planet || - RenderContext.BackgroundImageset.DataSetType == ImageSetType.SolarSystem) - { - scaleX *= 6.3; // XXX don't know where this magic number comes from - scaleY *= 6.3; - } - - if (RenderContext.Space && (Settings.Active.GalacticMode || Settings.Active.LocalHorizonMode)) - { - x = Settings.Active.LocalHorizonMode ? -x : x; - RenderContext.targetAz += x * scaleX; - RenderContext.targetAz = ((RenderContext.targetAz + 720) % 360); - RenderContext.targetAlt += y * scaleY; - - if (RenderContext.targetAlt > 90) - { - RenderContext.targetAlt = 90; - } - - if (RenderContext.targetAlt < -90) - { - RenderContext.targetAlt = -90; - } - } else { - RenderContext.TargetCamera.Lng -= x * scaleX; - RenderContext.TargetCamera.Lng = ((RenderContext.TargetCamera.Lng + 720) % 360); - RenderContext.TargetCamera.Lat += y * scaleY; - - if (RenderContext.TargetCamera.Lat > 90) - { - RenderContext.TargetCamera.Lat = 90; - } - - if (RenderContext.TargetCamera.Lat < -90) - { - RenderContext.TargetCamera.Lat = -90; - } - } - - if (!Settings.GlobalSettings.SmoothPan) - { - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - } - - if (x != 0 && y != 0) - { - tracking = false; - trackingObject = null; - } - } - - public void Zoom(double factor) - { - RenderContext.TargetCamera.Zoom *= factor; - - if (RenderContext.TargetCamera.Zoom > ZoomMax) - { - RenderContext.TargetCamera.Zoom = ZoomMax; - } - - if (!Settings.GlobalSettings.SmoothPan) - { - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - } - } - - public void Roll(double angle) - { - RenderContext.TargetCamera.Rotation += angle; - } - - // Mouse, touch, gesture controls -- lots of different event listeners for different - // devices and browser support. - - double beginZoom = 1; - bool dragging = false; - bool mouseDown = false; - bool hasTwoTouches = false; - double lastX; - double lastY; - int[] pointerIds = new int[2]; - Vector2d[] pinchingZoomRect = new Vector2d[2]; - bool moved = false; - - // Gesture events - - public void OnGestureStart(ElementEvent e) - { - mouseDown = false; - beginZoom = RenderContext.ViewCamera.Zoom; - } - - public void OnGestureChange(ElementEvent e) - { - GestureEvent g = (GestureEvent)e; - mouseDown = false; - RenderContext.TargetCamera.Zoom = RenderContext.ViewCamera.Zoom = Math.Min(360, beginZoom * (1.0 / g.Scale)); - } - - public void OnGestureEnd(ElementEvent e) - { - GestureEvent g = (GestureEvent)e; - mouseDown = false; - } - - // Touch events - - public void OnTouchStart(ElementEvent e) - { - TouchEvent ev = (TouchEvent)(object)e; - ev.PreventDefault(); - ev.StopPropagation(); - - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - - if (ev.TargetTouches.Length == 2) - { - hasTwoTouches = true; - return; - } - - if (uiController != null) - { - WWTElementEvent ee = new WWTElementEvent(lastX, lastY); - - if (uiController.MouseDown(this, (ElementEvent)(object)ee)) - { - mouseDown = false; - dragging = false; - return; - } - } - - mouseDown = true; - } - - public void OnTouchMove(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - - if (hasTwoTouches) - { - TouchInfo t0 = ev.Touches[0]; - TouchInfo t1 = ev.Touches[1]; - Vector2d[] newRect = new Vector2d[2]; - newRect[0] = Vector2d.Create(t0.PageX, t0.PageY); - newRect[1] = Vector2d.Create(t1.PageX, t1.PageY); - - if (pinchingZoomRect[0] != null && pinchingZoomRect[1] != null) - { - Vector2d centerPoint = Vector2d.Create(RenderContext.Width / 2, RenderContext.Height / 2); - - Vector2d delta1 = Vector2d.Subtract(newRect[0], pinchingZoomRect[0]); - Vector2d delta2 = Vector2d.Subtract(newRect[1], pinchingZoomRect[1]); - Vector2d radialDirection1 = Vector2d.Subtract(pinchingZoomRect[0], centerPoint); - Vector2d radialDirection2 = Vector2d.Subtract(pinchingZoomRect[1], centerPoint); - radialDirection1.Normalize(); - radialDirection2.Normalize(); - - double radialDot1 = delta1.X * radialDirection1.X + delta1.Y * radialDirection1.Y; - double radialDot2 = delta2.X * radialDirection2.X + delta2.Y * radialDirection2.Y; - Vector2d radialComponent1 = Vector2d.Create(radialDot1 * radialDirection1.X, radialDot1 * radialDirection1.Y); - Vector2d radialComponent2 = Vector2d.Create(radialDot2 * radialDirection2.X, radialDot2 * radialDirection2.Y); - Vector2d angularComponent1 = Vector2d.Subtract(delta1, radialComponent1); - Vector2d angularComponent2 = Vector2d.Subtract(delta2, radialComponent2); - double radialMagnitude = radialComponent1.Length + radialComponent2.Length; - double angularMagnitude = angularComponent1.Length + angularComponent2.Length; - - if (radialMagnitude >= angularMagnitude) - { - double oldDist = GetDistance(pinchingZoomRect[0], pinchingZoomRect[1]); - double newDist = GetDistance(newRect[0], newRect[1]); - double ratio = oldDist / newDist; - Zoom(ratio); - } - else - { - Vector2d oldCenterDelta1 = Vector2d.Subtract(pinchingZoomRect[0], centerPoint); - Vector2d oldCenterDelta2 = Vector2d.Subtract(pinchingZoomRect[1], centerPoint); - Vector2d newCenterDelta1 = Vector2d.Subtract(newRect[0], centerPoint); - Vector2d newCenterDelta2 = Vector2d.Subtract(newRect[1], centerPoint); - double cross1 = CrossProductZ(oldCenterDelta1, newCenterDelta1); - double cross2 = CrossProductZ(oldCenterDelta2, newCenterDelta2); - double angle1 = Math.Asin(cross1 / (oldCenterDelta1.Length * newCenterDelta1.Length)); - double angle2 = Math.Asin(cross2 / (oldCenterDelta2.Length * newCenterDelta2.Length)); - if (angle1 * angle2 >= 0) - { - double angle = angle1 + angle2; - if (PlanetLike || SolarSystemMode) - { - angle *= -1; - } - Roll(angle); - } - } - } - - pinchingZoomRect = newRect; - ev.StopPropagation(); - ev.PreventDefault(); - return; - } - - ev.PreventDefault(); - ev.StopPropagation(); - - if (mouseDown) - { - dragging = true; - - double curX = ev.TargetTouches[0].PageX - lastX; - double curY = ev.TargetTouches[0].PageY - lastY; - Move(curX, curY); - - lastX = ev.TargetTouches[0].PageX; - lastY = ev.TargetTouches[0].PageY; - } - else - { - //todo fix this to use syntheszed touch events. - if (uiController != null) - { - if (uiController.MouseMove(this, e)) - { - e.PreventDefault(); - e.StopPropagation(); - return; - } - } - } - } - - public void OnTouchEnd(ElementEvent e) - { - TouchEvent ev = (TouchEvent)e; - ev.PreventDefault(); - ev.StopPropagation(); - - pinchingZoomRect[0] = null; - pinchingZoomRect[1] = null; - - if (hasTwoTouches) - { - if (ev.Touches.Length < 2) - { - hasTwoTouches = false; - } - return; - } - - if (uiController != null) - { - WWTElementEvent ee = new WWTElementEvent(lastX, lastY); - - if (uiController.MouseUp(this, (ElementEvent)(object)ee)) - { - mouseDown = false; - dragging = false; - return; - } - } - - mouseDown = false; - dragging = false; - } - - // Pointer events - - public void OnPointerDown(ElementEvent e) - { - PointerEvent pe = (PointerEvent)(object)e; - int index = 0; - - Script.Literal("var evt = arguments[0], cnv = arguments[0].target; if (cnv.setPointerCapture) {cnv.setPointerCapture(evt.pointerId);} else if (cnv.msSetPointerCapture) { cnv.msSetPointerCapture(evt.pointerId); }"); - - // Check for this pointer already being in the list because as of - // July 2020, Chrome/Mac sometimes fails to deliver the pointerUp - // event. - - if (pointerIds[0] == pe.PointerId) { - index = 0; - } else if (pointerIds[1] == pe.PointerId) { - index = 1; - } else if (pointerIds[0] == 0) { - index = 0; - } else if (pointerIds[1] == 0) { - index = 1; - } else { - return; // only attempt to track two pointers at once - } - - pointerIds[index] = pe.PointerId; - pinchingZoomRect[index] = Vector2d.Create(e.OffsetX, e.OffsetY); - } - - public void OnPointerMove(ElementEvent e) - { - PointerEvent pe = (PointerEvent)(object)e; - int index = 0; - - // Our pointerIds infrastructure is meant to track adjustments - // during a pinch motion. However, as seen in Firefox circa v81 on - // Linux and Android, in some cases the browser can just *lie* and - // swap pointerIds for the two fingers during a pinch gesture, - // leading to catastrophic failures. Therefore, ignore the pointerId - // information and infer which location is being updated from - // whichever change is smaller. - - if (pointerIds[0] == pe.PointerId) - { - index = 0; - } - else if (pointerIds[1] == pe.PointerId) - { - index = 1; - } - else - { - return; - } - - if (pinchingZoomRect[0] != null && pinchingZoomRect[1] != null) - { - double oldDist = GetDistance(pinchingZoomRect[0], pinchingZoomRect[1]); - - Vector2d newRect = Vector2d.Create(e.OffsetX, e.OffsetY); - - double newDist0 = GetDistance(newRect, pinchingZoomRect[0]); - double ratio0 = oldDist / newDist0; - double abslog0 = Math.Abs(Math.Log(ratio0)); - if (!(bool)Script.Literal("isFinite({0})", abslog0)) { - abslog0 = 1000; - } - - double newDist1 = GetDistance(newRect, pinchingZoomRect[1]); - double ratio1 = oldDist / newDist1; - double abslog1 = Math.Abs(Math.Log(ratio1)); - if (!(bool)Script.Literal("isFinite({0})", abslog1)) { - abslog1 = 1000; - } - - if (abslog1 < abslog0) { - pinchingZoomRect[0] = newRect; - Zoom(ratio1); - } else { - pinchingZoomRect[1] = newRect; - Zoom(ratio0); - } - } else { - // Before two fingers are available, just trust. - pinchingZoomRect[index] = Vector2d.Create(e.OffsetX, e.OffsetY); - } - - // There doesn't seem to be a particular reason to call these - // but there also doesn't seem to be a reason NOT to - // and doing so hasn't caused any issues to this point - e.StopPropagation(); - e.PreventDefault(); - } - - // NOTE! As of July 2020, Chrome on Macs seems to sometimes fail to - // deliver this event. So our pinch-detection code needs to be robust to - // that. - public void OnPointerUp(ElementEvent e) - { - PointerEvent pe = (PointerEvent)(object)e; - - // The -2 here is intended to indicate "no pointer ID" - // with the hope being that no browser will use this value. - // Note that -1 is reserved by the W3 spec for - // "events generated by something other than a pointing device" - // which is why we don't use -1 - // (https://www.w3.org/TR/pointerevents3/#pointerevent-interface) - if (pointerIds[0] == pe.PointerId) - { - pointerIds[0] = -2; - pinchingZoomRect[0] = null; - } - - if (pointerIds[1] == pe.PointerId) - { - pointerIds[1] = -2; - pinchingZoomRect[1] = null; - } - } - - // Mouse events - - public void OnMouseDown(ElementEvent e) - { - Document.AddEventListener("mousemove", OnMouseMove, false); - Document.AddEventListener("mouseup", OnMouseUp, false); - - if (uiController != null) - { - if (uiController.MouseDown(this, e)) - { - return; - } - } - - mouseDown = true; - lastX = Mouse.OffsetX(Canvas, e); - lastY = Mouse.OffsetY(Canvas, e); - } - - public void OnMouseMove(ElementEvent e) - { - lastMouseMove = Date.Now; - hoverTextPoint = Vector2d.Create(Mouse.OffsetX(Canvas, e), Mouse.OffsetY(Canvas, e)); - hoverText = ""; - - if (mouseDown) - { - e.PreventDefault(); - e.StopPropagation(); - - moved = true; - if (e.CtrlKey) - { - Tilt(Mouse.OffsetX(Canvas, e) - lastX, Mouse.OffsetY(Canvas, e) - lastY); - } - else - { - Move(Mouse.OffsetX(Canvas, e) - lastX, Mouse.OffsetY(Canvas, e) - lastY); - } - - lastX = Mouse.OffsetX(Canvas, e); - lastY = Mouse.OffsetY(Canvas, e); - } - else - { - if (uiController != null) - { - if (uiController.MouseMove(this, e)) - { - e.PreventDefault(); - e.StopPropagation(); - return; - } - } - } - } - - public void OnMouseUp(ElementEvent e) - { - Document.RemoveEventListener("mousemove", OnMouseMove, false); - Document.RemoveEventListener("mouseup", OnMouseUp, false); - - if (uiController != null) - { - if (uiController.MouseUp(this, e)) - { - mouseDown = false; - e.PreventDefault(); - return; - } - } - - if (mouseDown && !moved) - { - Vector2d raDecDown = GetCoordinatesForScreenPoint(Mouse.OffsetX(Canvas, e), Mouse.OffsetY(Canvas, e)); - if (!Annotationclicked(raDecDown.X, raDecDown.Y, Mouse.OffsetX(Canvas, e), Mouse.OffsetY(Canvas, e))) - { - scriptInterface.FireClick(raDecDown.X, raDecDown.Y); - } - } - - mouseDown = false; - moved = false; - } - - public void OnMouseWheel(ElementEvent e) - { - // WheelEvent is a WWT-specific binding (see WheelEvent.cs) that we - // use to abstract across the different wheel-motion events that - // browsers provide: "wheel", "mousewheel", "DOMMouseScroll". - - WheelEvent ev = (WheelEvent)(object)e; - double delta; - - if (ev.deltaY != 0) - delta = -ev.deltaY; - else if (ev.detail != 0) - delta = ev.detail * -1; - else - delta = ev.WheelDelta; - - if (delta > 0) - Zoom(0.9); - else - Zoom(1.1); - - e.StopPropagation(); - e.PreventDefault(); - } - - public void OnDoubleClick(ElementEvent e) - { - showDataLayers = true; - } - - public void OnKeyDown(ElementEvent e) - { - if (uiController != null) - { - uiController.KeyDown(this, e); - } - } - - public double GetDistance(Vector2d a, Vector2d b) - { - double x; - double y; - x = a.X - b.X; - y = a.Y - b.Y; - return Math.Sqrt(x * x + y * y); - } - - public double CrossProductZ(Vector2d a, Vector2d b) - { - return a.X * b.Y - a.Y * b.X; - } - - public void OnContextMenu(ElementEvent e) - { - e.PreventDefault(); - e.StopPropagation(); - } - - private void Tilt(double x, double y) - { - RenderContext.TargetCamera.Rotation += x * .001; - RenderContext.TargetCamera.Angle += y * .001; - - if (RenderContext.TargetCamera.Angle < -1.52) - { - RenderContext.TargetCamera.Angle = -1.52; - } - - if (RenderContext.TargetCamera.Angle > 0) - { - RenderContext.TargetCamera.Angle = 0; - } - } - - public Vector2d GetCoordinatesForScreenPoint(double x, double y) - { - Vector2d pt = Vector2d.Create(x, y); - Vector3d PickRayDir = TransformPickPointToWorldSpace(pt, RenderContext.Width, RenderContext.Height); - return Coordinates.CartesianToSphericalSky(PickRayDir); - } - - public Vector3d TransformPickPointToWorldSpace(Vector2d ptCursor, double backBufferWidth, double backBufferHeight) - { - Vector3d vPickRayDir = new Vector3d(); - - // It is possible for this function to be called before the RenderContext is - // set up, in which case the Projection is null. In that case we'll leave the - // vector at its 0,0,0 default. - - if (RenderContext.Projection != null) { - Vector3d v = new Vector3d(); - v.X = (((2.0f * ptCursor.X) / backBufferWidth) - 1) / (RenderContext.Projection.M11);// / (backBufferWidth / 2)); - v.Y = (((2.0f * ptCursor.Y) / backBufferHeight) - 1) / (RenderContext.Projection.M22);// / (backBufferHeight / 2)); - v.Z = 1.0f; - - Matrix3d m = Matrix3d.MultiplyMatrix(RenderContext.View, RenderContext.World); - - m.Invert(); - - // Transform the screen space pick ray into 3D space - vPickRayDir.X = v.X * m.M11 + v.Y * m.M21 + v.Z * m.M31; - vPickRayDir.Y = v.X * m.M12 + v.Y * m.M22 + v.Z * m.M32; - vPickRayDir.Z = v.X * m.M13 + v.Y * m.M23 + v.Z * m.M33; - vPickRayDir.Normalize(); - } - - return vPickRayDir; - } - - public Vector2d TransformWorldPointToPickSpace(Vector3d worldPoint, double backBufferWidth, double backBufferHeight) - { - Matrix3d m = Matrix3d.MultiplyMatrix(RenderContext.View, RenderContext.World); - m.Invert(); - - Vector2d p = new Vector2d(); - double vz = worldPoint.X * m.M31 + worldPoint.Y * m.M32 + worldPoint.Z * m.M33; - double vx = (worldPoint.X * m.M11 + worldPoint.Y * m.M12 + worldPoint.Z * m.M13) / vz; - double vy = (worldPoint.X * m.M21 + worldPoint.Y * m.M22 + worldPoint.Z * m.M23) / vz; - p.X = Math.Round((1 + RenderContext.Projection.M11 * vx) * (backBufferWidth / 2)); - p.Y = Math.Round((1 + RenderContext.Projection.M22 * vy) * (backBufferHeight / 2)); - return p; - } - - public Vector2d GetScreenPointForCoordinates(double ra, double dec) - { - Vector2d pt = Vector2d.Create(ra, dec); - Vector3d cartesian = Coordinates.SphericalSkyToCartesian(pt); - Vector2d result = TransformWorldPointToPickSpace(cartesian, RenderContext.Width, RenderContext.Height); - return result; - } - - // Initialization - - public static ScriptInterface scriptInterface; - CanvasElement foregroundCanvas = null; - CanvasContext2D fgDevice = null; - - // For backwards compatibility, we preserve the semantics that calling - // this function kicks off the rendering loop. - public static ScriptInterface InitControl(string DivId) - { - return InitControl2(DivId, true); - } - - // This function had a parameter to choose whether to use WebGL or HTML5 - // canvas, but at some point the argument was defused. We preserve it - // for backwards compatibility. - public static ScriptInterface InitControlParam(string DivId, bool webgl_ignored) - { - return InitControl2(DivId, true); - } - - // Prefer using WWTControlBuilder rather than this interface directly. - public static ScriptInterface InitControl2(string DivId, bool startRenderLoop) - { - return InitControl6( - DivId, - startRenderLoop, - 0, - 0, - 360, - "Sky" - ); - } - - // Prefer using WWTControlBuilder rather than this interface directly. - public static ScriptInterface InitControl6( - string DivId, - bool startRenderLoop, - double startLat, - double startLng, - double startZoom, - string startMode - ) - { - if (Singleton.RenderContext.Device == null) - { - scriptInterface = new ScriptInterface(); - scriptInterface.Settings = Settings.Current; - - CanvasElement canvas = CreateCanvasElement(DivId); - - GL gl = (GL)(Object)canvas.GetContext((Rendering)(object)"webgl2"); - if(gl != null) - { - RenderContext.UseGlVersion2 = true; - } - else - { - Script.Literal("console.warn('This browser does not support WebGL 2.0. Some features will work suboptimally. To get the full AAS WWT experience, consider using the latest version of Chrome, Firefox or Edge. In case you would like to use Safari, we recommend that you enable WebGL 2.0')"); - gl = (GL)(Object)canvas.GetContext((Rendering)(object)"webgl"); - } - if (gl == null) { - gl = (GL)(Object)canvas.GetContext((Rendering)(object)"experimental-webgl"); - } - - if (gl == null) { - CanvasContext2D ctx = (CanvasContext2D)canvas.GetContext(Rendering.Render2D); - Singleton.RenderContext.Device = ctx; - } else { - Tile.PrepDevice = gl; - Singleton.RenderContext.gl = gl; - RenderContext.UseGl = true; - } - - Singleton.Canvas = canvas; - Singleton.RenderContext.Width = canvas.Width; - Singleton.RenderContext.Height = canvas.Height; - Singleton.Setup(canvas, startLat, startLng, startZoom); - - Constellations.InitializeConstellations(); - LayerManager.OneTimeInitialization(); - - if (startMode == "earth") { - Singleton.RenderContext.BackgroundImageset = Imageset.Create( - "Blue Marble", // name - URLHelpers.singleton.coreStaticUrl("wwtweb/tiles.aspx?q={1},{2},{3},bm200407"), // url - ImageSetType.Earth, // dataSetType - BandPass.Visible, // bandPass - ProjectionType.Toast, // projectionType - 101, // imageSetID - 0, // baseLevel - 7, // levels - 256, // tileSize (unused) - 180, // baseTileDegrees - ".png", // extension - false, // bottomsUp - "", // quadTreeMap - 0, // centerX - 0, // centerY - 0, // rotation - false, // sparse - URLHelpers.singleton.coreStaticUrl("wwtweb/thumbnail.aspx?name=bm200407"), // thumbnailUrl - true, // defaultSet - false, // elevationModel - 0, // widthFactor - 0, // offsetX - 0, // offsetY - "", // creditsText - "", // creditsUrl - "", // demUrl - "", // altUrl - 6371000, // meanRadius - "Earth" // referenceFrame - ); - } else if (startMode == "black") { - // Black sky init -- probably because we are in freestanding mode - Singleton.RenderContext.BackgroundImageset = Imageset.Create( - "Black Sky Background", // name - "", // url - ImageSetType.Sky, // dataSetType - BandPass.Visible, // bandPass - ProjectionType.Toast, // projectionType - 102, // imageSetID - 0, // baseLevel - 0, // levels - 256, // tileSize (unused) - 180, // baseTileDegrees - ".png", // extension - false, // bottomsUp - "0123", // quadTreeMap - 0, // centerX - 0, // centerY - 0, // rotation - false, // sparse - "", // thumbnailUrl - false, // defaultSet - false, // elevationModel - 2, // widthFactor - 0, // offsetX - 0, // offsetY - "", // creditsText - "", // creditsUrl - "", // demUrl - "", // altUrl - 1, // meanRadius - "Sky" // referenceFrame - ); - } else { - Singleton.RenderContext.BackgroundImageset = Imageset.Create( - "DSS", // name - URLHelpers.singleton.coreStaticUrl("wwtweb/dss.aspx?q={1},{2},{3}"), // url - ImageSetType.Sky, // dataSetType - BandPass.Visible, // bandPass - ProjectionType.Toast, // projectionType - 100, // imageSetId - 0, // baseLevel - 12, // levels - 256, // tileSize (unused) - 180, // baseTileDegrees - ".png", // extension - false, // bottomsUp - "", // quadTreeMap - 0, // centerX - 0, // centerY - 0, // rotation - false, // sparse - URLHelpers.singleton.coreStaticUrl("thumbnails/DSS.png"), // thumbnailUrl - true, // defaultSet - false, // elevationModel - 0, // widthFactor - 0, // offsetX - 0, // offsetY - "", // creditsText - "", // creditsUrl - "", // demUrl - "", // altUrl - 1, // meanRadius - "Sky" // referenceFrame - ); - } - } - - Singleton.RenderContext.ViewCamera.Lng += 0; - Singleton.RenderContext.InitGL(); - - if (startRenderLoop) { - Singleton.Render(); - } - - return scriptInterface; - } - - private static CanvasElement CreateCanvasElement(string DivId) - { - DivElement div = (DivElement) Document.GetElementById(DivId); - - CanvasElement canvas = (CanvasElement) Document.CreateElement("canvas"); - canvas.Height = div.ClientHeight; - canvas.Width = div.ClientWidth; - div.AppendChild(canvas); - return canvas; - } - - // Note that due to limitations of ScriptSharp, this method must be - // public even though it should really be private. - public void Setup( - CanvasElement canvas, - double startLat, - double startLng, - double startZoom - ) { - Window.AddEventListener("contextmenu", OnContextMenu, false); - Document.Body.AddEventListener("keydown", OnKeyDown, false); - canvas.AddEventListener("dblclick", OnDoubleClick, false); - canvas.AddEventListener("mousedown", OnMouseDown, false); - canvas.AddEventListener("wheel", OnMouseWheel, false); - canvas.AddEventListener("mousewheel", OnMouseWheel, false); - canvas.AddEventListener("DOMMouseScroll", OnMouseWheel, false); // old Firefox - canvas.AddEventListener("touchstart", OnTouchStart, false); - canvas.AddEventListener("touchmove", OnTouchMove, false); - canvas.AddEventListener("touchend", OnTouchEnd, false); - canvas.AddEventListener("gesturechange", OnGestureChange, false); - canvas.AddEventListener("gesturestart", OnGestureStart, false); - canvas.AddEventListener("gestureend", OnGestureEnd, false); - canvas.AddEventListener("pointerdown", OnPointerDown, false); - canvas.AddEventListener("pointermove", OnPointerMove, false); - canvas.AddEventListener("pointerup", OnPointerUp, false); - - RenderContext.ViewCamera.Lat = startLat; - RenderContext.ViewCamera.Lng = startLng; - RenderContext.ViewCamera.Zoom = startZoom; - - RenderContext.TargetCamera = RenderContext.ViewCamera.Copy(); - - if (RenderContext.gl == null) - { - foregroundCanvas = (CanvasElement)Document.CreateElement("canvas"); - foregroundCanvas.Width = canvas.Width; - foregroundCanvas.Height = canvas.Height; - fgDevice = (CanvasContext2D)foregroundCanvas.GetContext(Rendering.Render2D); - } - - if (FreestandingMode) { - Script.SetTimeout(delegate () { SetupComplete(); }, 0); - } else { - // To line up with Windows client history, this uses `X=` when - // `W=` would be more appropriate. - Wtml.GetWtmlFile( - URLHelpers.singleton.coreDynamicUrl("wwtweb/catalog.aspx?X=ImageSets6"), - SetupComplete, - true - ); - } - } - - void SetupComplete() - { - scriptInterface.FireReady(); - } - - public static void UseUserLocation() - { - Navigator.Geolocation.GetCurrentPosition(GetLocation, GetLocationError); - } - - private static void GetLocation(Position pos) - { - if (pos.Coords.Latitude != 0) - { - Settings.GlobalSettings.LocationLat = pos.Coords.Latitude; - } - if (pos.Coords.Longitude != 0) - { - Settings.GlobalSettings.LocationLng = pos.Coords.Longitude; - } - if (pos.Coords.Altitude != 0) - { - Settings.GlobalSettings.LocationAltitude = pos.Coords.Altitude; - } - } - private static void GetLocationError (Position pos) - { - if (pos != null && pos.Coords != null) - { - double lat = pos.Coords.Latitude; - double lng = pos.Coords.Longitude; - - } - } - - public void GotoRADecZoom(double ra, double dec, double zoom, bool instant, double? roll) - { - - tracking = false; - trackingObject = null; - - GotoTargetFull( - false, // noZoom - instant, - CameraParametersFromRADecZoom(ra, dec, zoom, roll), - WWTControl.Singleton.RenderContext.ForegroundImageset, - WWTControl.Singleton.RenderContext.BackgroundImageset - ); - } - - CameraParameters CameraParametersFromRADecZoom(double ra, double dec, double zoom, double? roll) - { - while (ra > 24) - { - ra -= 24; - } - while (ra < 0) - { - ra += 24; - } - dec = DoubleUtilities.Clamp(dec, -90, 90); - zoom = DoubleUtilities.Clamp(zoom, ZoomMin, ZoomMax); - double rotation = roll == null ? WWTControl.Singleton.RenderContext.ViewCamera.Rotation : (double)roll; - CameraParameters cameraParams = CameraParameters.Create( - dec, - WWTControl.Singleton.RenderContext.RAtoViewLng(ra), - zoom, - rotation, - WWTControl.Singleton.RenderContext.ViewCamera.Angle, - (float)WWTControl.Singleton.RenderContext.ViewCamera.Opacity - ); - return cameraParams; - } - - public double TimeToRADecZoom(double ra, double dec, double zoom, double? roll) - { - CameraParameters cameraParams = CameraParametersFromRADecZoom(ra, dec, zoom, roll); - return TimeToTargetFull(cameraParams, false); - } - - bool tracking = false; - Place trackingObject = null; - - public bool SandboxMode = false; - - public bool SolarSystemMode - { - get - { - if (RenderContext.BackgroundImageset == null) - { - return false; - } - - return RenderContext.BackgroundImageset.DataSetType == ImageSetType.SolarSystem; - } - } - - SolarSystemObjects SolarSystemTrack = SolarSystemObjects.Undefined; - public void GotoTarget(Place place, bool noZoom, bool instant, bool trackObject) - { - if (place == null) - { - return; - } - if ((trackObject && SolarSystemMode)) - { - if ((place.Classification == Classification.SolarSystem && place.Type != ImageSetType.SolarSystem) || (place.Classification == Classification.Star) || (place.Classification == Classification.Galaxy) && place.Distance > 0) - { - SolarSystemObjects target = SolarSystemObjects.Undefined; - - if (place.Classification == Classification.Star || place.Classification == Classification.Galaxy) - { - target = SolarSystemObjects.Custom; - } - else - { - try - { - if (place.Target != SolarSystemObjects.Undefined) - { - target = place.Target; - } - else - { - target = (SolarSystemObjects)Planets.GetPlanetIDFromName(place.Name); - } - } - catch - { - } - } - if (target != SolarSystemObjects.Undefined) - { - trackingObject = place; - if (target == SolarSystemTrack && !(place.Classification == Classification.Star || place.Classification == Classification.Galaxy)) - { - GotoTarget3(place.CamParams, noZoom, instant); - return; - } - double jumpTime = 4; - - if (target == SolarSystemObjects.Custom) - { - jumpTime = 17; - } - else - { - jumpTime += 13 * (101 - Settings.Active.SolarSystemScale) / 100; - } - - if (instant) - { - jumpTime = 1; - } - - //SolarSystemTrack = target; - CameraParameters camTo = RenderContext.ViewCamera.Copy(); - camTo.TargetReferenceFrame = ""; - camTo.Target = target; - double zoom = 10; - if (target == SolarSystemObjects.Custom) - { - if (place.Classification == Classification.Galaxy) - { - zoom = 1404946007758; - } - else - { - zoom = 63239.6717 * 100; - } - // Star or something outside of SS - Vector3d vect = Coordinates.RADecTo3dAu(place.RA, place.Dec, place.Distance); - double ecliptic = Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI; - - vect.RotateX(ecliptic); - camTo.ViewTarget = Vector3d.Negate(camTo.ViewTarget); - } - else - { - camTo.ViewTarget = Planets.GetPlanet3dLocationJD(target, SpaceTimeController.GetJNowForFutureTime(jumpTime)); - switch (target) - { - case SolarSystemObjects.Sun: - zoom = .6; - break; - case SolarSystemObjects.Mercury: - zoom = .0004; - break; - case SolarSystemObjects.Venus: - zoom = .0004; - break; - case SolarSystemObjects.Mars: - zoom = .0004; - break; - case SolarSystemObjects.Jupiter: - zoom = .007; - break; - case SolarSystemObjects.Saturn: - zoom = .007; - break; - case SolarSystemObjects.Uranus: - zoom = .004; - break; - case SolarSystemObjects.Neptune: - zoom = .004; - break; - case SolarSystemObjects.Pluto: - zoom = .0004; - break; - case SolarSystemObjects.Moon: - zoom = .0004; - break; - case SolarSystemObjects.Io: - zoom = .0004; - break; - case SolarSystemObjects.Europa: - zoom = .0004; - break; - case SolarSystemObjects.Ganymede: - zoom = .0004; - break; - case SolarSystemObjects.Callisto: - zoom = .0004; - break; - case SolarSystemObjects.Earth: - zoom = .0004; - break; - case SolarSystemObjects.Custom: - zoom = 10; - break; - - default: - break; - } - - zoom = zoom * Settings.Active.SolarSystemScale; - - } - - CameraParameters fromParams = RenderContext.ViewCamera.Copy(); - if (SolarSystemTrack == SolarSystemObjects.Custom && !string.IsNullOrEmpty(RenderContext.TrackingFrame)) - { - fromParams = RenderContext.CustomTrackingParams; - RenderContext.TrackingFrame = ""; - } - camTo.Zoom = zoom; - Vector3d toVector = camTo.ViewTarget; - toVector.Subtract(fromParams.ViewTarget); - - //Vector3d toVector = camTo.ViewTarget; - //toVector.Subtract(new Vector3d(cameraPosition)); - - if (place.Classification == Classification.Star) - { - toVector = Vector3d.Negate(toVector); - } - - if (toVector.Length() != 0) - { - - Vector2d raDec = toVector.ToRaDec(); - - if (target == SolarSystemObjects.Custom) - { - camTo.Lat = -raDec.Y; - } - else - { - camTo.Lat = raDec.Y; - } - camTo.Lng = raDec.X * 15 - 90; - } - else - { - camTo.Lat = RenderContext.ViewCamera.Lat; - camTo.Lng = RenderContext.ViewCamera.Lng; - } - - if (target != SolarSystemObjects.Custom) - { - // replace with planet surface - camTo.ViewTarget = Planets.GetPlanetTargetPoint(target, camTo.Lat, camTo.Lng, SpaceTimeController.GetJNowForFutureTime(jumpTime)); - - } - - - - ViewMoverKenBurnsStyle solarMover = new ViewMoverKenBurnsStyle(fromParams, camTo, jumpTime, SpaceTimeController.Now, SpaceTimeController.GetTimeForFutureTime(jumpTime), InterpolationType.EaseInOut); - solarMover.FastDirectionMove = true; - Mover = solarMover; - - return; - } - } - } - - - - - tracking = false; - trackingObject = null; - CameraParameters camParams = place.CamParams.Copy(); - - - // (gonzalo) backgroundimageset could be null... protect onself! - if (RenderContext.BackgroundImageset != null && place.Type != RenderContext.BackgroundImageset.DataSetType) - { - RenderContext.TargetCamera = place.CamParams.Copy(); - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - RenderContext.BackgroundImageset = GetDefaultImageset(place.Type, BandPass.Visible); - instant = true; - } - else if (SolarSystemMode && place.Target != SolarSystemTrack) - { - RenderContext.TargetCamera = place.CamParams.Copy(); - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - SolarSystemTrack = place.Target; - instant = true; - } - - - if (place.Classification == Classification.Constellation) - { - camParams.Zoom = ZoomMax; - GotoTargetFull(false, instant, camParams, null, null); - } - else - { - SolarSystemTrack = place.Target; - GotoTargetFull(noZoom, instant, camParams, place.StudyImageset, place.BackgroundImageset); - //if (place.Classification == Classification.SolarSystem) - if (trackObject) - { - tracking = true; - trackingObject = place; - } - } - } - - public void GotoTarget3(CameraParameters camParams, bool noZoom, bool instant) - { - tracking = false; - trackingObject = null; - GotoTargetFull(noZoom, instant, camParams, RenderContext.ForegroundImageset, RenderContext.BackgroundImageset); - } - - private bool TooCloseForSlewMove(CameraParameters cameraParams) - { - return Math.Abs(RenderContext.ViewCamera.Lat - cameraParams.Lat) < .000000000001 && - Math.Abs(RenderContext.ViewCamera.Lng - cameraParams.Lng) < .000000000001 && - Math.Abs(RenderContext.ViewCamera.Zoom - cameraParams.Zoom) < .000000000001 && - Math.Abs(RenderContext.ViewCamera.Rotation - cameraParams.Rotation) < .000000000001; - } - - public void GotoTargetFull(bool noZoom, bool instant, CameraParameters cameraParams, Imageset studyImageSet, Imageset backgroundImageSet) - { - RenderNeeded = true; - //if (cameraParams == this.viewCamera) - //{ - // instant = true; - //} - tracking = false; - trackingObject = null; - targetStudyImageset = studyImageSet; - targetBackgroundImageset = backgroundImageSet; - - if (noZoom) - { - cameraParams.Zoom = RenderContext.ViewCamera.Zoom; - cameraParams.Angle = RenderContext.ViewCamera.Angle; - cameraParams.Rotation = RenderContext.ViewCamera.Rotation; - } - else - { - if (cameraParams.Zoom == -1 || cameraParams.Zoom == 0) - { - if (RenderContext.Space) - { - cameraParams.Zoom = 1.40625; - } - else - { - cameraParams.Zoom = 0.09F; - } - } - } - - if (instant || TooCloseForSlewMove(cameraParams)) - { - Mover = null; - RenderContext.TargetCamera = cameraParams.Copy(); - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - - if (RenderContext.Space && Settings.Active.GalacticMode) - { - double[] gPoint = Coordinates.J2000toGalactic(RenderContext.ViewCamera.RA * 15, RenderContext.ViewCamera.Dec); - RenderContext.targetAlt = RenderContext.alt = gPoint[1]; - RenderContext.targetAz = RenderContext.az = gPoint[0]; - } - else if (RenderContext.Space && Settings.Active.LocalHorizonMode) - { - Coordinates currentAltAz = Coordinates.EquitorialToHorizon(Coordinates.FromRaDec(RenderContext.ViewCamera.RA, RenderContext.ViewCamera.Dec), SpaceTimeController.Location, SpaceTimeController.Now); - RenderContext.targetAlt = RenderContext.alt = currentAltAz.Alt; - RenderContext.targetAz = RenderContext.az = currentAltAz.Az; - } - - mover_Midpoint(); - } - else - { - Mover = ViewMoverSlew.Create(RenderContext.ViewCamera, cameraParams); - RenderNeeded = true; - Mover.Midpoint = mover_Midpoint; - } - } - - double SlewTimeBetweenTargets(CameraParameters from, CameraParameters to) - { - ViewMoverSlew mover = ViewMoverSlew.Create(from, to); - return mover.MoveTime; - } - - public double TimeToTargetFull(CameraParameters cameraParams, bool noZoom) - { - if (noZoom) - { - cameraParams.Zoom = RenderContext.ViewCamera.Zoom; - cameraParams.Angle = RenderContext.ViewCamera.Angle; - cameraParams.Rotation = RenderContext.ViewCamera.Rotation; - } - if (TooCloseForSlewMove(cameraParams)) - { - return 0; - } - - return SlewTimeBetweenTargets(WWTControl.Singleton.RenderContext.ViewCamera, cameraParams); - } - - internal void FreezeView() - { - RenderContext.ViewCamera = RenderContext.TargetCamera.Copy(); - Mover = null; - } - - - internal IViewMover Mover - { - get { return RenderContext.ViewMover; } - set - { - RenderContext.ViewMover = value; - RenderNeeded = true; - } - } - - bool moving = false; - - public void FadeInImageSet(Imageset newImageSet) - { - if (RenderContext.BackgroundImageset != null && - newImageSet.DataSetType != RenderContext.BackgroundImageset.DataSetType) - { - TileCache.PurgeQueue(); - TileCache.ClearCache(); - } - - RenderContext.BackgroundImageset = newImageSet; - } - - Imageset targetStudyImageset = null; - Imageset targetBackgroundImageset = null; - - void mover_Midpoint() - { - if ((targetStudyImageset != null && - RenderContext.ForegroundImageset == null) || - (RenderContext.ForegroundImageset != null && - !RenderContext.ForegroundImageset.Equals(targetStudyImageset))) - { - RenderContext.ForegroundImageset = targetStudyImageset; - } - - //(gonzalo) protect from backgroundImageset being null ... - if (RenderContext.BackgroundImageset != null && - (targetBackgroundImageset != null && - !RenderContext.BackgroundImageset.Equals(targetBackgroundImageset))) - { - if (targetBackgroundImageset != null && targetBackgroundImageset.Generic) - { - FadeInImageSet(GetRealImagesetFromGeneric(targetBackgroundImageset)); - } - else - { - FadeInImageSet(targetBackgroundImageset); - } - } - } - - public Imageset GetDefaultImageset(ImageSetType imageSetType, BandPass bandPass) - { - foreach (Imageset imageset in ImageSets) - { - if (imageset.DefaultSet && imageset.BandPass == bandPass && imageset.DataSetType == imageSetType) - { - return imageset; - } - - } - foreach (Imageset imageset in ImageSets) - { - if (imageset.BandPass == bandPass && imageset.DataSetType == imageSetType) - { - return imageset; - } - - } - foreach (Imageset imageset in ImageSets) - { - if (imageset.DataSetType == imageSetType) - { - return imageset; - } - - } - return ImageSets[0]; - } - - private Imageset GetRealImagesetFromGeneric(Imageset generic) - { - foreach (Imageset imageset in ImageSets) - { - if (imageset.DefaultSet && imageset.BandPass == generic.BandPass && imageset.DataSetType == generic.DataSetType) - { - return imageset; - } - - } - - foreach (Imageset imageset in ImageSets) - { - if (imageset.BandPass == generic.BandPass && imageset.DataSetType == generic.DataSetType) - { - return imageset; - } - - } - return ImageSets[0]; - } - - public static void SetBackgroundImageName(string name) - { - WWTControl.ImageSetName = name; - } - - public static void SetForegroundImageName(string name) - { - WWTControl.ImageSetName = name; - } - - public static void ShowLayers(bool show) - { - WWTControl.showDataLayers = show; - } - - internal void HideUI(bool p) - { - //todo implement this - } - - public TourDocument tour = null; - public TourEditTab TourEdit = null; - - public TourDocument CreateTour(string name) - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer)uiController; - player.Stop(false); - - } - - tour = new TourDocument(); - tour.Title = name; - - SetupTour(); - tour.EditMode = true; - - return tour; - } - - public void SetupTour() - { - TourEdit = new TourEditTab(); - TourEdit.Tour = tour; - tour.CurrentTourstopIndex = 0; - tour.EditMode = false; - uiController = TourEdit.TourEditorUI; - } - - public void LoadTour(string url) - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer) uiController; - player.Stop(false); - } - - tour = TourDocument.FromUrl(url, delegate { - SetupTour(); - - TourPlayer player = new TourPlayer(); - player.Tour = tour; - WWTControl.Singleton.uiController = player; - - WWTControl.scriptInterface.FireTourReady(); - }); - } - - public void PlayTour(string url) - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer) uiController; - player.Stop(false); - } - - tour = TourDocument.FromUrl(url, delegate { - SetupTour(); - TourEdit.PlayNow(true /* fromStart */); - WWTControl.scriptInterface.FireTourReady(); - }); - } - - public void PlayCurrentTour() - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer)uiController; - player.Play(); - } - } - - public void PauseCurrentTour() - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer)uiController; - player.PauseTour(); - } - } - - public void StopCurrentTour() - { - if (uiController is TourPlayer) - { - TourPlayer player = (TourPlayer)uiController; - player.Stop(false); - } - } - - internal void CloseTour() - { - //todo implement tour close - } - - public Imageset GetImagesetByName(string name) - { - foreach (Imageset imageset in ImageSets) - { - if (imageset.Name.ToLowerCase().IndexOf(name.ToLowerCase()) > -1) - { - return imageset; - } - } - return null; - } - - public Imageset GetImageSetByUrl(string url) - { - foreach (Imageset imageset in ImageSets) - { - if (imageset.Url == url) - { - return imageset; - } - } - return null; - } - - public void SetBackgroundImageByName(string name) - { - Imageset newBackground = GetImagesetByName(name); - - if (newBackground != null) - { - RenderContext.BackgroundImageset = newBackground; - } - } - - public void SetForegroundImageByName(string name) - { - Imageset newForeground = GetImagesetByName(name); - - if (newForeground != null) - { - RenderContext.ForegroundImageset = newForeground; - } - } - - public void AddCatalogHips(Imageset catalogHips) - { - RenderContext.AddCatalogHips(catalogHips, null); - } - - public void AddCatalogHipsByName(string name) - { - AddCatalogHipsByNameWithCallback(name, null); - } - - public void AddCatalogHipsByNameWithCallback(string name, Action onLoad) - { - Imageset catalogHips = GetImagesetByName(name); - if (catalogHips != null) - { - RenderContext.AddCatalogHips(catalogHips, onLoad); - } - } - - public void RemoveCatalogHipsByName(string name) - { - Imageset catalogHips = GetImagesetByName(name); - if (catalogHips != null) - { - RenderContext.RemoveCatalogHips(catalogHips); - } - } - - public Imageset GetCatalogHipsByName(string name) - { - return RenderContext.GetCatalogHipsByName(name); - } - - public void GetCatalogHipsDataInView(string name, bool limit, Action onComplete) - { - Imageset catalogHips = GetImagesetByName(name); - if (catalogHips != null) - { - RenderContext.GetCatalogHipsDataInView(catalogHips, limit, onComplete); - } - } - - public void SetCutsForFits(string imagesetName, double min, double max) - { - Imageset imageset = GetImagesetByName(imagesetName); - if (imageset != null && imageset.FitsProperties != null) - { - imageset.FitsProperties.LowerCut = min; - imageset.FitsProperties.UpperCut = max; - } else - { - Script.Literal("console.log({0} + ' not found')", imagesetName); - } - } - - public void SetColorMapForFits(string imagesetName, string colorMapName) - { - Imageset imageset = GetImagesetByName(imagesetName); - if (imageset != null && imageset.FitsProperties != null) - { - imageset.FitsProperties.ColorMapName = colorMapName; - } - else - { - Script.Literal("console.log({0} + ' not found')", imagesetName); - } - } - - public void SetScaleTypeForFits(string imagesetName, ScaleTypes scaleType) - { - Imageset imageset = GetImagesetByName(imagesetName); - if (imageset != null && imageset.FitsProperties != null) - { - imageset.FitsProperties.ScaleType = scaleType; - } - else - { - Script.Literal("console.log({0} + ' not found')", imagesetName); - } - } - - - private SimpleLineList crossHairs = null; - - private void DrawCrosshairs(RenderContext context) - { - if (context.gl == null) - { - CanvasContext2D ctx = context.Device; - ctx.Save(); - ctx.BeginPath(); - ctx.StrokeStyle = Settings.Current.CrosshairsColor; - ctx.LineWidth = 2; - - double x = context.Width / 2, y = context.Height / 2; - double halfLength = 5; - - ctx.MoveTo(x, y + halfLength); - ctx.LineTo(x, y - halfLength); - ctx.MoveTo(x + halfLength, y); - ctx.LineTo(x - halfLength, y); - - ctx.Stroke(); - ctx.Restore(); - } - else - { - if (crossHairs == null) - { - // These coordinates are in clip space where the shape of - // the viewport is 1x1, so to get the crosshairs to appear - // square on the screen we have to apply the aspect ratio. - double halfHeight = 0.03; - double halfWidth = halfHeight * context.Height / context.Width; - - crossHairs = new SimpleLineList(); - crossHairs.DepthBuffered = false; - crossHairs.Pure2D = true; - crossHairs.AddLine(Vector3d.Create(-halfWidth, .0, 0), Vector3d.Create(halfWidth, 0, 0)); - crossHairs.AddLine(Vector3d.Create(0, -halfHeight, 0), Vector3d.Create(0, halfHeight, 0)); - } - - crossHairs.DrawLines(context, 1.0f, Color.Load(Settings.Current.CrosshairsColor)); - } - } - - public void CaptureThumbnail(BlobReady blobReady) - { - CaptureFrame(blobReady, 96, 45, "image/jpeg", true); - } - - public void CaptureCurrentFrame(BlobReady blobReady, int width, int height, string format) - { - CaptureFrame(blobReady, width, height, format, false); - } - - public void CaptureFrameForVideo(BlobReady blobReady, int width, int height, string format) - { - int frameNumber = SpaceTimeController.CurrentFrameNumber; - BlobReady forVideo = delegate (Blob blob) - { - bool containsIndex; - if (frameNumber == videoQueueIndex) - { - blobReady(blob); - videoQueueIndex += 1; - - // Keep moving forward until we hit the next index that we're still waiting on - while ((containsIndex = videoBlobQueue.ContainsKey(videoQueueIndex)) || emptyFrames.Contains(videoQueueIndex)) - { - if (containsIndex) - { - blobReady(videoBlobQueue[videoQueueIndex]); - videoBlobQueue[videoQueueIndex] = null; - } - else - { - emptyFrames.Remove(videoQueueIndex); - } - videoQueueIndex += 1; - } - } - else - { - if (blob != null) - { - videoBlobQueue[frameNumber] = blob; - } - else - { - emptyFrames.Add(frameNumber); - } - } - if (videoQueueIndex >= SpaceTimeController.TotalFrames) - { - videoBlobReady = null; - videoBlobQueue = null; - videoQueueIndex = 0; - emptyFrames.Clear(); - } - }; - CaptureCurrentFrame(forVideo, width, height, format); - } - - public void CaptureFrame(BlobReady blobReady, int width, int height, string format, bool needRender) - { - if (needRender) - { - RenderOneFrame(); // NB: this used to be Render() but that was almost surely not what we want - } - - ImageElement image = (ImageElement)Document.CreateElement("img"); - image.AddEventListener("load", delegate (ElementEvent e) - { - double imageAspect = ((double)image.Width) / (image.Height); - - double clientAspect = width / height; - - int cw = width; - int ch = height; - - if (imageAspect < clientAspect) - { - ch = (int)((double)cw / imageAspect); - } - else - { - cw = (int)((double)ch * imageAspect); - } - - int cx = (width - cw) / 2; - int cy = (height - ch) / 2; - - CanvasElement temp = (CanvasElement)Document.CreateElement("canvas"); - temp.Height = height; - temp.Width = width; - CanvasContext2D ctx = (CanvasContext2D)temp.GetContext(Rendering.Render2D); - ctx.DrawImage(image, cx, cy, cw, ch); - //Script.Literal("{0}.toBlob({1}, 'image/jpeg')", temp, blobReady); - - Script.Literal("if ( typeof {0}.msToBlob == 'function') {{ var blob = {0}.msToBlob(); {1}(blob); }} else {{ {0}.toBlob({1}, {2}); }}", temp, blobReady, format); - - - // thumb.Src = temp.GetDataUrl(); - }, false); - - image.Src = Singleton.Canvas.GetDataUrl(); - - } - - public void ClampZooms(RenderContext rc) - { - rc.ViewCamera.Zoom = DoubleUtilities.Clamp(rc.ViewCamera.Zoom, ZoomMin, ZoomMax); - rc.TargetCamera.Zoom = DoubleUtilities.Clamp(rc.TargetCamera.Zoom, ZoomMin, ZoomMax); - } - - } - - public class WWTControlBuilder - { - string divId = null; - - public WWTControlBuilder(string divId) { - this.divId = divId; - } - - bool startRenderLoop = false; - - public void StartRenderLoop(bool value) { - startRenderLoop = value; - } - - double startLat = 0.0; - double startLng = 0.0; - double startZoom = 360.0; - - public void InitialView(double lat, double lng, double zoom) { - startLat = lat; - startLng = lng; - startZoom = zoom; - } - - string freestandingAssetBaseurl = ""; - - public void FreestandingMode(string asset_baseurl) { - freestandingAssetBaseurl = asset_baseurl; - } - - string startMode = ""; - - public void InitialMode(string value) { - startMode = value; - } - - public ScriptInterface Create() - { - bool freestandingMode = freestandingAssetBaseurl != ""; - string trueStartMode; - - if (startMode != "") { - trueStartMode = startMode; - } else if (freestandingMode) { - trueStartMode = "black"; - } else { - trueStartMode = "sky"; - } - - WWTControl.Singleton.FreestandingMode = freestandingMode; - - if (freestandingMode) { - URLHelpers.singleton.overrideAssetBaseurl(freestandingAssetBaseurl); - } - - return WWTControl.InitControl6( - divId, startRenderLoop, startLat, startLng, startZoom, trueStartMode - ); - } - } - - public delegate void BlobReady(System.Html.Data.Files.Blob blob); - - //public delegate void BlobFrameReady(System.Html.Data.Files.Blob blob, int FrameNumber); - - public class WWTElementEvent - { - public double OffsetX; - public double OffsetY; - - public WWTElementEvent(double x, double y) - { - OffsetX = x; - OffsetY = y; - } - } -} diff --git a/engine/csharp_ref/WebFile.cs b/engine/csharp_ref/WebFile.cs deleted file mode 100644 index 81b03e61..00000000 --- a/engine/csharp_ref/WebFile.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml; -using System.Net; -using System.Html.Data.Files; - -namespace wwtlib -{ - public enum StateType - { - Pending = 0, - Received = 1, - Error = 2 - } - - public class WebFile - { - private string _url; - private string _message; - private StateType _state; - private string _data; - private object _blobdata; - private XDomainRequest xdr; - private XMLHttpRequest2 xhr; - - public WebFile(string url) - { - _url = url; - } - - public void Send() - { - Script.Literal("if (typeof navigator === \"undefined\") { return; }"); - //send the appropriate request based on browser type - // have to do this because IE8 and 9 don't support CORS - string version = Navigator.AppVersion; - if (version.IndexOf("MSIE 8") > -1 || version.IndexOf("MSIE 9") > -1) - { - IECrossDomain(); - } - else - { - CORS(); - } - - State = StateType.Pending; - } - public String ResponseType = ""; - - public Action OnStateChange; - public string Message { get { return _message; } } - public StateType State - { - get { return _state; } - private set - { - _state = value; - if (OnStateChange != null) - { - OnStateChange(); - } - } - } - - private void LoadData(string textReceived) - { - // received data, set the state vars and send statechange - _data = textReceived; - State = StateType.Received; - } - private void LoadBlob(object blob) - { - // received data, set the state vars and send statechange - _blobdata = blob; - State = StateType.Received; - } - private void Error() - { - _message = String.Format("Error encountered loading {0}", _url); - State = StateType.Error; - } - - private void TimeOut() - { - _message = String.Format("Timeout encountered loading {0}", _url); - State = StateType.Error; - } - - private void IECrossDomain() - { - xdr = new XDomainRequest(); - xdr.OnLoad = delegate() - { - LoadData(xdr.ResponseText); - }; - xdr.OnTimeout = Error; - xdr.OnError = TimeOut; - xdr.Open("get", _url); - xdr.Send(); - } - private bool triedOnce = false; - - private void CORS() - { - xhr = new XMLHttpRequest2(); - try - { - xhr.Open(HttpVerb.Get, _url); - - if (ResponseType != null) - { - xhr.ResponseType = ResponseType; - } - - xhr.OnReadyStateChange = delegate() - { - if (xhr.ReadyState == ReadyState.Loaded) - { - if (xhr.Status == 0) - { - if (!triedOnce) - { - triedOnce = true; - xhr.OnReadyStateChange = null; - - string new_url = URLHelpers.singleton.activateProxy(_url); - - if (new_url != null) // null => don't bother: we know that the proxy won't help - { - _url = new_url; - CORS(); - } else - { - _message = xhr.StatusText; - State = StateType.Error; - } - } - } - else - { - if(xhr.Status >= 400) - { - _message = xhr.StatusText; - State = StateType.Error; - } else - { - if (ResponseType == "") - { - LoadData(xhr.ResponseText); - } - else - { - LoadBlob(xhr.Response); - } - } - - } - - } - }; - - xhr.Send(); - } - catch (Exception err) - { - _message = err.Message; - State = StateType.Error; - throw (err); - } - } - - public string GetText() - { - return _data; - } - - public Blob GetBlob() - { - return (Blob)_blobdata; - } - - public XmlDocument GetXml() - { - XmlDocumentParser xParser = new XmlDocumentParser(); - return xParser.ParseFromString(_data, "text/xml"); - } - } -} diff --git a/engine/csharp_ref/WebGL.cs b/engine/csharp_ref/WebGL.cs deleted file mode 100644 index 702ac0c9..00000000 --- a/engine/csharp_ref/WebGL.cs +++ /dev/null @@ -1,931 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Html.Media.Graphics; - -namespace System.Html -{ - [ScriptIgnoreNamespace] - [ScriptImport] - // [ScriptName("globalCompositeOperation")] - public class GL - { - public const int ACTIVE_ATTRIBUTE_MAX_LENGTH = 35722; - public const int ACTIVE_ATTRIBUTES = 35721; - public const int ACTIVE_TEXTURE = 34016; - public const int ACTIVE_UNIFORM_MAX_LENGTH = 35719; - public const int ACTIVE_UNIFORMS = 35718; - public const int ALIASED_LINE_WIDTH_RANGE = 33902; - public const int ALIASED_POINT_SIZE_RANGE = 33901; - public const int ALPHA = 6406; - public const int ALPHA_BITS = 3413; - public const int ALWAYS = 519; - public const int ARRAY_BUFFER = 34962; - public const int ARRAY_BUFFER_BINDING = 34964; - public const int ATTACHED_SHADERS = 35717; - public const int BACK = 1029; - public const int BLEND = 3042; - public const int BLEND_COLOR = 32773; - public const int BLEND_DST_ALPHA = 32970; - public const int BLEND_DST_RGB = 32968; - public const int BLEND_EQUATION = 32777; - public const int BLEND_EQUATION_ALPHA = 34877; - public const int BLEND_EQUATION_RGB = 32777; - public const int BLEND_SRC_ALPHA = 32971; - public const int BLEND_SRC_RGB = 32969; - public const int BLUE_BITS = 3412; - public const int BOOL = 35670; - public const int BOOL_VEC2 = 35671; - public const int BOOL_VEC3 = 35672; - public const int BOOL_VEC4 = 35673; - public const int BUFFER_SIZE = 34660; - public const int BUFFER_USAGE = 34661; - public const int BYTE = 5120; - public const int CCW = 2305; - public const int CLAMP_TO_EDGE = 33071; - public const int COLOR_ATTACHMENT0 = 36064; - public const int COLOR_BUFFER_BIT = 16384; - public const int COLOR_CLEAR_VALUE = 3106; - public const int COLOR_WRITEMASK = 3107; - public const int COMPILE_STATUS = 35713; - public const int COMPRESSED_TEXTURE_FORMATS = 34467; - public const int CONSTANT_ALPHA = 32771; - public const int CONSTANT_COLOR = 32769; - public const int CULL_FACE = 2884; - public const int CULL_FACE_MODE = 2885; - public const int CURRENT_PROGRAM = 35725; - public const int CURRENT_VERTEX_ATTRIB = 34342; - public const int CW = 2304; - public const int DECR = 7683; - public const int DECR_WRAP = 34056; - public const int DELETE_STATUS = 35712; - public const int DEPTH_ATTACHMENT = 36096; - public const int DEPTH_BITS = 3414; - public const int DEPTH_BUFFER_BIT = 256; - public const int DEPTH_CLEAR_VALUE = 2931; - public const int DEPTH_COMPONENT = 6402; - public const int DEPTH_COMPONENT16 = 33189; - public const int DEPTH_FUNC = 2932; - public const int DEPTH_RANGE = 2928; - public const int DEPTH_STENCIL = 34041; - public const int DEPTH_STENCIL_ATTACHMENT = 33306; - public const int DEPTH_TEST = 2929; - public const int DEPTH_WRITEMASK = 2930; - public const int DITHER = 3024; - public const int DONT_CARE = 4352; - public const int DST_ALPHA = 772; - public const int DST_COLOR = 774; - public const int DYNAMIC_DRAW = 35048; - public const int ELEMENT_ARRAY_BUFFER = 34963; - public const int ELEMENT_ARRAY_BUFFER_BINDING = 34965; - public const int EQUAL = 514; - public const int EXTENSIONS = 7939; - public const int FASTEST = 4353; - public const int FLOAT = 5126; - public const int FLOAT_MAT2 = 35674; - public const int FLOAT_MAT3 = 35675; - public const int FLOAT_MAT4 = 35676; - public const int FLOAT_VEC2 = 35664; - public const int FLOAT_VEC3 = 35665; - public const int FLOAT_VEC4 = 35666; - public const int FRAGMENT_SHADER = 35632; - public const int FRAMEBUFFER = 36160; - public const int FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 36049; - public const int FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 36048; - public const int FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 36051; - public const int FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 36050; - public const int FRAMEBUFFER_BINDING = 36006; - public const int FRAMEBUFFER_COMPLETE = 36053; - public const int FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 36054; - public const int FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 36057; - public const int FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 36055; - public const int FRAMEBUFFER_UNSUPPORTED = 36061; - public const int FRONT = 1028; - public const int FRONT_AND_BACK = 1032; - public const int FRONT_FACE = 2886; - public const int FUNC_ADD = 32774; - public const int FUNC_REVERSE_SUBTRACT = 32779; - public const int FUNC_SUBTRACT = 32778; - public const int GENERATE_MIPMAP_HINT = 33170; - public const int GEQUAL = 518; - public const int GREATER = 516; - public const int GREEN_BITS = 3411; - public const int HIGH_FLOAT = 36338; - public const int HIGH_INT = 36341; - public const int IMPLEMENTATION_COLOR_READ_FORMAT = 35739; - public const int IMPLEMENTATION_COLOR_READ_TYPE = 35738; - public const int INCR = 7682; - public const int INCR_WRAP = 34055; - public const int INFO_LOG_LENGTH = 35716; - public const int INT = 5124; - public const int INT_VEC2 = 35667; - public const int INT_VEC3 = 35668; - public const int INT_VEC4 = 35669; - public const int INVALID_ENUM = 1280; - public const int INVALID_FRAMEBUFFER_OPERATION = 1286; - public const int INVALID_OPERATION = 1282; - public const int INVALID_VALUE = 1281; - public const int INVERT = 5386; - public const int KEEP = 7680; - public const int LEQUAL = 515; - public const int LESS = 513; - public const int LINE_LOOP = 2; - public const int LINE_STRIP = 3; - public const int LINE_WIDTH = 2849; - public const int LINEAR = 9729; - public const int LINEAR_MIPMAP_LINEAR = 9987; - public const int LINEAR_MIPMAP_NEAREST = 9985; - public const int LINES = 1; - public const int LINK_STATUS = 35714; - public const int LOW_FLOAT = 36336; - public const int LOW_INT = 36339; - public const int LUMINANCE = 6409; - public const int LUMINANCE_ALPHA = 6410; - public const int MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661; - public const int MAX_CUBE_MAP_TEXTURE_SIZE = 34076; - public const int MAX_FRAGMENT_UNIFORM_VECTORS = 36349; - public const int MAX_RENDERBUFFER_SIZE = 34024; - public const int MAX_TEXTURE_IMAGE_UNITS = 34930; - public const int MAX_TEXTURE_SIZE = 3379; - public const int MAX_VARYING_VECTORS = 36348; - public const int MAX_VERTEX_ATTRIBS = 34921; - public const int MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660; - public const int MAX_VERTEX_UNIFORM_VECTORS = 36347; - public const int MAX_VIEWPORT_DIMS = 3386; - public const int MEDIUM_FLOAT = 36337; - public const int MEDIUM_INT = 36340; - public const int MIRRORED_REPEAT = 33648; - public const int NEAREST = 9728; - public const int NEAREST_MIPMAP_LINEAR = 9986; - public const int NEAREST_MIPMAP_NEAREST = 9984; - public const int NEVER = 512; - public const int NICEST = 4354; - public const int NO_ERROR = 0; - public const int NONE = 0; - public const int NOTEQUAL = 517; - public const int NUM_COMPRESSED_TEXTURE_FORMATS = 34466; - public const int ONE = 1; - public const int ONE_MINUS_CONSTANT_ALPHA = 32772; - public const int ONE_MINUS_CONSTANT_COLOR = 32770; - public const int ONE_MINUS_DST_ALPHA = 773; - public const int ONE_MINUS_DST_COLOR = 775; - public const int ONE_MINUS_SRC_ALPHA = 771; - public const int ONE_MINUS_SRC_COLOR = 769; - public const int OUT_OF_MEMORY = 1285; - public const int PACK_ALIGNMENT = 3333; - public const int POINTS = 0; - public const int POLYGON_OFFSET_FACTOR = 32824; - public const int POLYGON_OFFSET_FILL = 32823; - public const int POLYGON_OFFSET_UNITS = 10752; - public const int RED_BITS = 3410; - public const int RENDERBUFFER = 36161; - public const int RENDERBUFFER_ALPHA_SIZE = 36179; - public const int RENDERBUFFER_BINDING = 36007; - public const int RENDERBUFFER_BLUE_SIZE = 36178; - public const int RENDERBUFFER_DEPTH_SIZE = 36180; - public const int RENDERBUFFER_GREEN_SIZE = 36177; - public const int RENDERBUFFER_HEIGHT = 36163; - public const int RENDERBUFFER_INTERNAL_FORMAT = 36164; - public const int RENDERBUFFER_RED_SIZE = 36176; - public const int RENDERBUFFER_STENCIL_SIZE = 36181; - public const int RENDERBUFFER_WIDTH = 36162; - public const int RENDERER = 7937; - public const int REPEAT = 10497; - public const int REPLACE = 7681; - public const int RGB = 6407; - public const int RGB8 = 32849; - public const int RGB5_A1 = 32855; - public const int RGB565 = 36194; - public const int RGBA = 6408; - public const int RGBA8 = 32856; - public const int RGBA16I = 36232; - public const int RED_INTEGER = 36244; - public const int RED = 6403; - public const int R32F = 33326; - public const int R16I = 33331; - public const int RGBA4 = 32854; - public const int SAMPLE_ALPHA_TO_COVERAGE = 32926; - public const int SAMPLE_BUFFERS = 32936; - public const int SAMPLE_COVERAGE = 32928; - public const int SAMPLE_COVERAGE_INVERT = 32939; - public const int SAMPLE_COVERAGE_VALUE = 32938; - public const int SAMPLER_2D = 35678; - public const int SAMPLER_CUBE = 35680; - public const int SAMPLES = 32937; - public const int SCISSOR_BOX = 3088; - public const int SCISSOR_TEST = 3089; - public const int SHADER_COMPILER = 36346; - public const int SHADER_SOURCE_LENGTH = 35720; - public const int SHADER_TYPE = 35663; - public const int SHADING_LANGUAGE_VERSION = 35724; - public const int SHORT = 5122; - public const int SRC_ALPHA = 770; - public const int SRC_ALPHA_SATURATE = 776; - public const int SRC_COLOR = 768; - public const int STATIC_DRAW = 35044; - public const int STENCIL_ATTACHMENT = 36128; - public const int STENCIL_BACK_FAIL = 34817; - public const int STENCIL_BACK_FUNC = 34816; - public const int STENCIL_BACK_PASS_DEPTH_FAIL = 34818; - public const int STENCIL_BACK_PASS_DEPTH_PASS = 34819; - public const int STENCIL_BACK_REF = 36003; - public const int STENCIL_BACK_VALUE_MASK = 36004; - public const int STENCIL_BACK_WRITEMASK = 36005; - public const int STENCIL_BITS = 3415; - public const int STENCIL_BUFFER_BIT = 1024; - public const int STENCIL_CLEAR_VALUE = 2961; - public const int STENCIL_FAIL = 2964; - public const int STENCIL_FUNC = 2962; - public const int STENCIL_INDEX = 6401; - public const int STENCIL_INDEX8 = 36168; - public const int STENCIL_PASS_DEPTH_FAIL = 2965; - public const int STENCIL_PASS_DEPTH_PASS = 2966; - public const int STENCIL_REF = 2967; - public const int STENCIL_TEST = 2960; - public const int STENCIL_VALUE_MASK = 2963; - public const int STENCIL_WRITEMASK = 2968; - public const int STREAM_DRAW = 35040; - public const int SUBPIXEL_BITS = 3408; - public const int TEXTURE = 5890; - public const int TEXTURE_2D = 3553; - public const int TEXTURE_BINDING_2D = 32873; - public const int TEXTURE_BINDING_CUBE_MAP = 34068; - public const int TEXTURE_CUBE_MAP = 34067; - public const int TEXTURE_CUBE_MAP_NEGATIVE_X = 34070; - public const int TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072; - public const int TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074; - public const int TEXTURE_CUBE_MAP_POSITIVE_X = 34069; - public const int TEXTURE_CUBE_MAP_POSITIVE_Y = 34071; - public const int TEXTURE_CUBE_MAP_POSITIVE_Z = 34073; - public const int UNPACK_FLIP_Y_WEBGL = 37440; - public const int TEXTURE_MAG_FILTER = 10240; - public const int TEXTURE_MIN_FILTER = 10241; - public const int TEXTURE_WRAP_S = 10242; - public const int TEXTURE_WRAP_T = 10243; - public const int TEXTURE0 = 33984; - public const int TEXTURE1 = 33985; - public const int TEXTURE10 = 33994; - public const int TEXTURE11 = 33995; - public const int TEXTURE12 = 33996; - public const int TEXTURE13 = 33997; - public const int TEXTURE14 = 33998; - public const int TEXTURE15 = 33999; - public const int TEXTURE16 = 34000; - public const int TEXTURE17 = 34001; - public const int TEXTURE18 = 34002; - public const int TEXTURE19 = 34003; - public const int TEXTURE2 = 33986; - public const int TEXTURE20 = 34004; - public const int TEXTURE21 = 34005; - public const int TEXTURE22 = 34006; - public const int TEXTURE23 = 34007; - public const int TEXTURE24 = 34008; - public const int TEXTURE25 = 34009; - public const int TEXTURE26 = 34010; - public const int TEXTURE27 = 34011; - public const int TEXTURE28 = 34012; - public const int TEXTURE29 = 34013; - public const int TEXTURE3 = 33987; - public const int TEXTURE30 = 34014; - public const int TEXTURE31 = 34015; - public const int TEXTURE4 = 33988; - public const int TEXTURE5 = 33989; - public const int TEXTURE6 = 33990; - public const int TEXTURE7 = 33991; - public const int TEXTURE8 = 33992; - public const int TEXTURE9 = 33993; - public const int TRIANGLE_FAN = 6; - public const int TRIANGLE_STRIP = 5; - public const int TRIANGLES = 4; - public const int UNPACK_ALIGNMENT = 3317; - public const int UNSIGNED_BYTE = 5121; - public const int UNSIGNED_INT = 5125; - public const int UNSIGNED_SHORT = 5123; - public const int UNSIGNED_SHORT_4_4_4_4 = 32819; - public const int UNSIGNED_SHORT_5_5_5_1 = 32820; - public const int UNSIGNED_SHORT_5_6_5 = 33635; - public const int VALIDATE_STATUS = 35715; - public const int VENDOR = 7936; - public const int VERSION = 7938; - public const int VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 34975; - public const int VERTEX_ATTRIB_ARRAY_ENABLED = 34338; - public const int VERTEX_ATTRIB_ARRAY_NORMALIZED = 34922; - public const int VERTEX_ATTRIB_ARRAY_POINTER = 34373; - public const int VERTEX_ATTRIB_ARRAY_SIZE = 34339; - public const int VERTEX_ATTRIB_ARRAY_STRIDE = 34340; - public const int VERTEX_ATTRIB_ARRAY_TYPE = 34341; - public const int VERTEX_SHADER = 35633; - public const int VIEWPORT = 2978; - public const int ZERO = 0; - - public GL() - { - } - - [ScriptField] - public CanvasElement canvas - { - get - { - return null; - } - } - [ScriptField] - public WebGLContextAttributes contextAttributes { get { return null; } } - - [ScriptField] - public int error { get { return 0; } } - - public void activeTexture(int texture) { return; } - public void attachShader(WebGLProgram program, WebGLShader shader) { return; } - public void bindAttribLocation(WebGLProgram program, int index, string name) { return; } - public void bindBuffer(int target, WebGLBuffer buffer) { return; } - public void bindFramebuffer(int target, WebGLFramebuffer framebuffer) { return; } - public void bindRenderbuffer(int target, WebGLRenderbuffer renderbuffer) { return; } - public void bindTexture(int target, WebGLTexture texture) { return; } - public void blendColor(float red, float green, float blue, float alpha) { return; } - public void blendEquation(int mode) { return; } - public void blendEquationSeparate(int modeRGB, int modeAlpha) { return; } - public void blendFunc(int sfactor, int dfactor) { return; } - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { return; } - public void bufferData(int target, int size, int usage) { return; } - public void bufferData(int target, Float32Array data, int usage) { return; } - public void bufferData(int target, Uint16Array data, int usage) { return; } - public void bufferData(int target, Uint32Array data, int usage) { return; } - public void bufferData(int target, WebGLArray data, int usage) { return; } - public void bufferSubData(int target, int offset, WebGLArray data) { return; } - public void bufferSubData(int target, int offset, WebGLArrayBuffer data) { return; } - public int checkFramebufferStatus(int target) { return 0; } - public void clear(int mask) { return; } - public void clearColor(float red, float green, float blue, float alpha) { return; } - public void clearDepth(float depth) { return; } - public void clearStencil(int s) { return; } - public void colorMask(bool red, bool green, bool blue, bool alpha) { return; } - public void compileShader(WebGLShader shader) { return; } - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { return; } - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { return; } - public WebGLBuffer createBuffer() { return null; } - public WebGLFramebuffer createFramebuffer() { return null; } - public WebGLProgram createProgram() { return null; } - public WebGLRenderbuffer createRenderbuffer() { return null; } - public WebGLShader createShader(int type) { return null; } - public WebGLTexture createTexture() { return null; } - public void cullFace(int mode) { return; } - public void deleteBuffer(WebGLBuffer buffer) { return; } - public void deleteFramebuffer(WebGLFramebuffer framebuffer) { return; } - public void deleteProgram(WebGLProgram program) { return; } - public void deleteRenderbuffer(WebGLRenderbuffer renderbuffer) { return; } - public void deleteShader(WebGLShader shader) { return; } - public void deleteTexture(WebGLTexture texture) { return; } - public void depthFunc(int func) { return; } - public void depthMask(bool flag) { return; } - public void depthRange(float zNear, float zFar) { return; } - public void detachShader(WebGLProgram program, WebGLShader shader) { return; } - public void disable(int cap) { return; } - public void disableVertexAttribArray(int index) { return; } - public void drawArrays(int mode, int first, int count) { return; } - public void drawElements(int mode, int count, int type, int offset) { return; } - public void enable(int cap) { return; } - public void enableVertexAttribArray(int index) { return; } - public void finish() { return; } - public void flush() { return; } - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, WebGLRenderbuffer renderbuffer) { return; } - public void framebufferTexture2D(int target, int attachment, int textarget, WebGLTexture texture, int level) { return; } - public void frontFace(int mode) { return; } - public void generateMipmap(int target) { return; } - public WebGLActiveInfo getActiveAttrib(WebGLProgram program, int index) { return null; } - public WebGLActiveInfo getActiveUniform(WebGLProgram program, int index) { return null; } - public WebGLObjectArray getAttachedShaders(WebGLProgram program) { return null; } - public int getAttribLocation(WebGLProgram program, string name) { return 0; } - public object getBufferParameter(int target, int pname) { return null; } - public object getFramebufferAttachmentParameter(int target, int attachment, int pname) { return null; } - public object getParameter(int pname) { return null; } - public int getExtension(string name) { return 0; } - public String getProgramInfoLog(WebGLProgram program) { return null; } - public object getProgramParameter(WebGLProgram program, int pname) { return null; } - public object getRenderbufferParameter(int target, int pname) { return null; } - public String getShaderInfoLog(WebGLShader shader) { return null; } - public object getShaderParameter(WebGLShader shader, int pname) { return null; } - public String getShaderSource(WebGLShader shader) { return null; } - public String getString(int name) { return null; } - public object getTexParameter(int target, int pname) { return null; } - public object getUniform(WebGLProgram program, WebGLUniformLocation location) { return null; } - public WebGLUniformLocation getUniformLocation(WebGLProgram program, string name) { return null; } - public object getVertexAttrib(int index, int pname) { return null; } - public int getVertexAttribOffset(int index, int pname) { return 0; } - public void hint(int target, int mode) { return; } - public bool isBuffer(WebGLBuffer buffer) { return false; } - public bool isContextLost() { return false; } - public bool isEnabled(int cap) { return false; ; } - public bool isFramebuffer(WebGLFramebuffer framebuffer) { return false; ; } - public bool isProgram(WebGLProgram program) { return false; ; } - public bool isRenderbuffer(WebGLRenderbuffer renderbuffer) { return false; ; } - public bool isShader(WebGLShader shader) { return false; ; } - public bool isTexture(WebGLTexture texture) { return false; ; } - public void lineWidth(float width) { return; } - public void linkProgram(WebGLProgram program) { return; } - public void pixelStorei(int pname, int param) { return; } - public void polygonOffset(float factor, float units) { return; } - public WebGLArray readPixels(int x, int y, int width, int height, int format, int type) { return null; } - public void renderbufferStorage(int target, int internalformat, int width, int height) { return; } - public bool resetContext() { return false; } - public void sampleCoverage(float value, bool invert) { return; } - public void scissor(int x, int y, int width, int height) { return; } - public void shaderSource(WebGLShader shader, string source) { return; } - public void stencilFunc(int func, int @ref, int mask) { return; } - public void stencilFuncSeparate(int face, int func, int @ref, int mask) { return; } - public void stencilMask(int mask) { return; } - public void stencilMaskSeparate(int face, int mask) { return; } - public void stencilOp(int fail, int zfail, int zpass) { return; } - public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { return; } - public void texImage2D(int target, int level, CanvasElement canvas) { return; } - public void texImage2D(int target, int level, ImageElement image) { return; } - public void texImage2D(int target, int level, VideoElement image) { return; } - public void texImage2D(int target, int level, int format, int fmt, int storage, ImageElement video) { return; } - public void texImage2D(int target, int level, ImageData pixels) { return; } - public void texImage2D(int target, int level, CanvasElement canvas, bool flipY) { return; } - public void texImage2D(int target, int level, ImageElement image, bool flipY) { return; } - public void texImage2D(int target, int level, VideoElement video, bool flipY) { return; } - public void texImage2D(int target, int level, ImageData pixels, bool flipY) { return; } - public void texImage2D(int target, int level, CanvasElement canvas, bool flipY, bool asPremultipliedAlpha) { return; } - public void texImage2D(int target, int level, ImageElement image, bool flipY, bool asPremultipliedAlpha) { return; } - public void texImage2D(int target, int level, VideoElement video, bool flipY, bool asPremultipliedAlpha) { return; } - public void texImage2D(int target, int level, ImageData pixels, bool flipY, bool asPremultipliedAlpha) { return; } - public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, WebGLArray pixels) { return; } - public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Float32Array pixels) { return; } - public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Uint8Array pixels) { return; } - public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Int16Array pixels) { return; } - public void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, byte[] pixels) { return; } - public void texParameterf(int target, int pname, float param) { return; } - public void texParameteri(int target, int pname, int param) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, CanvasElement canvas) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageElement image) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, VideoElement video) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageData pixels) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, CanvasElement canvas, bool flipY) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageElement image, bool flipY) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, VideoElement video, bool flipY) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageData pixels, bool flipY) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, CanvasElement canvas, bool flipY, bool asPremultipliedAlpha) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageElement image, bool flipY, bool asPremultipliedAlpha) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, VideoElement video, bool flipY, bool asPremultipliedAlpha) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, ImageData pixels, bool flipY, bool asPremultipliedAlpha) { return; } - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, WebGLArray pixels) { return; } - public void uniform1f(WebGLUniformLocation location, float x) { return; } - public void uniform1fv(WebGLUniformLocation location, float[] v) { return; } - public void uniform1fv(WebGLUniformLocation location, WebGLFloatArray v) { return; } - public void uniform1i(WebGLUniformLocation location, int x) { return; } - public void uniform1i(WebGLUniformLocation location, bool x) { return; } - public void uniform1iv(WebGLUniformLocation location, int[] v) { return; } - public void uniform1iv(WebGLUniformLocation location, WebGLIntArray v) { return; } - public void uniform2f(WebGLUniformLocation location, float x, float y) { return; } - public void uniform2fv(WebGLUniformLocation location, float[] v) { return; } - public void uniform2fv(WebGLUniformLocation location, WebGLFloatArray v) { return; } - public void uniform2i(WebGLUniformLocation location, int x, int y) { return; } - public void uniform2iv(WebGLUniformLocation location, int[] v) { return; } - public void uniform2iv(WebGLUniformLocation location, WebGLIntArray v) { return; } - public void uniform3f(WebGLUniformLocation location, float x, float y, float z) { return; } - public void uniform3fv(WebGLUniformLocation location, float[] v) { return; } - public void uniform3fv(WebGLUniformLocation location, WebGLFloatArray v) { return; } - public void uniform3i(WebGLUniformLocation location, int x, int y, int z) { return; } - public void uniform3iv(WebGLUniformLocation location, int[] v) { return; } - public void uniform3iv(WebGLUniformLocation location, WebGLIntArray v) { return; } - public void uniform4f(WebGLUniformLocation location, float x, float y, float z, float w) { return; } - public void uniform4fv(WebGLUniformLocation location, float[] v) { return; } - public void uniform4fv(WebGLUniformLocation location, WebGLFloatArray v) { return; } - public void uniform4i(WebGLUniformLocation location, int x, int y, int z, int w) { return; } - public void uniform4iv(WebGLUniformLocation location, int[] v) { return; } - public void uniform4iv(WebGLUniformLocation location, WebGLIntArray v) { return; } - public void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, float[] value) { return; } - public void uniformMatrix2fv(WebGLUniformLocation location, bool transpose, WebGLFloatArray value) { return; } - public void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, float[] value) { return; } - public void uniformMatrix3fv(WebGLUniformLocation location, bool transpose, WebGLFloatArray value) { return; } - public void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, float[] value) { return; } - public void uniformMatrix4fv(WebGLUniformLocation location, bool transpose, WebGLFloatArray value) { return; } - public void useProgram(WebGLProgram program) { return; } - public void validateProgram(WebGLProgram program) { return; } - public void vertexAttrib1f(int indx, float x) { return; } - public void vertexAttrib1fv(int indx, float[] values) { return; } - public void vertexAttrib1fv(int indx, WebGLFloatArray values) { return; } - public void vertexAttrib2f(int indx, float x, float y) { return; } - public void vertexAttrib2fv(int indx, float[] values) { return; } - public void vertexAttrib2fv(int indx, WebGLFloatArray values) { return; } - public void vertexAttrib3f(int indx, float x, float y, float z) { return; } - public void vertexAttrib3fv(int indx, float[] values) { return; } - public void vertexAttrib3fv(int indx, WebGLFloatArray values) { return; } - public void vertexAttrib4f(int indx, float x, float y, float z, float w) { return; } - public void vertexAttrib4fv(int indx, float[] values) { return; } - public void vertexAttrib4fv(int indx, WebGLFloatArray values) { return; } - public void vertexAttribPointer(int indx, int size, int type, bool normalized, int stride, int offset) { return; } - public void viewport(int x, int y, int width, int height) { return; } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLContextAttributes - { - public WebGLContextAttributes() - { } - [ScriptField] - public bool alpha { get { return false; } set { } } - [ScriptField] - public bool antialias { get { return false; } set { } } - [ScriptField] - public bool depth { get { return false; } set { } } - [ScriptField] - public bool premultipliedAlpha { get { return false; } set { } } - [ScriptField] - public bool stencil { get { return false; } set { } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLProgram : WebGLObject - { - public WebGLProgram() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLObject - { - public WebGLObject() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLShader : WebGLObject - { - public WebGLShader() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLBuffer : WebGLObject - { - public WebGLBuffer() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLFramebuffer : WebGLObject - { - public WebGLFramebuffer() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLRenderbuffer : WebGLObject - { - public WebGLRenderbuffer() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLTexture : WebGLObject - { - public WebGLTexture() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLArray - { - public WebGLArray() { } - - [ScriptField] - public WebGLArrayBuffer buffer { get { return null; } set { buffer = value; } } - [ScriptField] - public int byteLength { get { return 0; } } - [ScriptField] - public int byteOffset { get { return 0; } } - [ScriptField] - public int length { get { return 0; } } - - public WebGLArray slice(int start, int end) - { - return null; - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLArrayBuffer - { - public WebGLArrayBuffer() { } - - [ScriptField] - public int byteLength { get { return 0; } set { } } - [ScriptField] - public int size { get { return 0; } set { } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLActiveInfo - { - public WebGLActiveInfo() { } - [ScriptField] - public String name { get { return null; } } - [ScriptField] - public int size { get { return 0; } } - [ScriptField] - public int type { get { return 0; } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLObjectArray - { - public WebGLObjectArray() { } - - [ScriptField] - public int length { get { return 0; } } - - public WebGLObject get(int index) { return null; } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLUniformLocation - { - public WebGLUniformLocation() { } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class VideoElement : MediaElement - { - public VideoElement() { } - [ScriptField] - public String height { get { return null; } set { } } - [ScriptField] - public String poster { get { return null; } set { } } - [ScriptField] - public int videoHeight { get { return 0; } } - [ScriptField] - public int videoWidth { get { return 0; } } - [ScriptField] - public String width { get { return null; } set { } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLFloatArray : WebGLArray - { - public static int BYTES_PER_ELEMENT; - - public WebGLFloatArray() { } - - public float get(int index) { return 0; } - - public void set(float[] array) { } - - public void set(WebGLFloatArray array) { } - - public void set(float[] array, int offset) { } - - public void set(int index, float value) { } - - public void set(WebGLFloatArray array, int offset) { } - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - public class WebGLIntArray : WebGLArray - { - public static int BYTES_PER_ELEMENT; - - public WebGLIntArray() { } - - public int get(int index) { return 0; } - public void set(int[] array) { } - public void set(WebGLIntArray array) { } - public void set(int index, int value) { } - public void set(int[] array, int offset) { } - public void set(WebGLIntArray array, int offset) { } - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - public class MediaElement : Element - { - public static short HAVE_CURRENT_DATA; - public static short HAVE_ENOUGH_DATA; - public static short HAVE_FUTURE_DATA; - public static short HAVE_METADATA; - public static short HAVE_NOTHING; - public static short NETWORK_EMPTY; - public static short NETWORK_IDLE; - public static short NETWORK_LOADING; - public static short NETWORK_NO_SOURCE; - - public MediaElement() { } - [ScriptField] - public bool autoplay { get { return false; } set { } } - [ScriptField] - public TimeRanges buffered { get { return null; } } - [ScriptField] - public bool controls { get { return false; } set { } } - [ScriptField] - public String currentSrc { get { return null; } } - [ScriptField] - public float currentTime { get { return 0; } set { } } - [ScriptField] - public float defaultPlaybackRate { get { return 0; } set { } } - [ScriptField] - public float duration { get { return 0; } } - [ScriptField] - public bool ended { get { return false; } } - [ScriptField] - public MediaError error { get { return null; } } - [ScriptField] - public bool loop { get { return false; } set { } } - [ScriptField] - public bool muted { get { return false; } set { } } - [ScriptField] - public short networkStateget { get { return 0; } } - [ScriptField] - public bool paused { get { return false; } } - [ScriptField] - public float playbackRate { get { return 0; } set { } } - [ScriptField] - public TimeRanges playedget { get { return null; } } - [ScriptField] - public String preload { get { return null; } set { } } - [ScriptField] - public short readyState { get { return 0; } } - [ScriptField] - public TimeRanges seekable { get { return null; } } - [ScriptField] - public bool seeking { get { return false; } } - [ScriptField] - public String src { get { return null; } set { } } - [ScriptField] - public float startTime { get { return 0; } set { } } - [ScriptField] - public float volume { get { return 0; } set { } } - - - public String canPlayType(string type) { return null; } - public void load() { } - public void pause() { } - public void play() { } - } - [ScriptIgnoreNamespace] - [ScriptImport] - public class TimeRanges - { - public TimeRanges() { } - [ScriptField] - public int length { get { return 0; } } - - public float end(int index) { return 0; } - public float start(int index) { return 0; } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class MediaError - { - [ScriptField] - public static short MEDIA_ERR_ABORTED { get { return 0; } } - [ScriptField] - public static short MEDIA_ERR_DECODE { get { return 0; } } - [ScriptField] - public static short MEDIA_ERR_NETWORK { get { return 0; } } - [ScriptField] - public static short MEDIA_ERR_SRC_NOT_SUPPORTED { get { return 0; } } - - public MediaError() { } - - [ScriptField] - public short code { get { return 0; } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class CrossDomainImage - { - [ScriptField] - public string crossOrigin { get { return "anonymous"; } set { } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Float32Array - { - public Float32Array(object data) { } - public Float32Array(object data, int a, int b) { } - [ScriptField] - public int length { get { return 0; } } - - [ScriptField] - public float this[int key] - { - get { return 0; } - set { } - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Float64Array - { - public Float64Array(object data) { } - public Float64Array(object data, int a, int b) { } - [ScriptField] - public int length { get { return 0; } } - - [ScriptField] - public double this[int key] - { - get { return 0; } - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Uint8Array - { - public Uint8Array(object data) { } - public Uint8Array(int size) { } - [ScriptField] - public int length { get { return 0; } } - - [ScriptField] - public byte this[int key] - { - get { return 0; } - set { } - } - - [ScriptField] - public object buffer { get { return null; } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Uint16Array - { - public Uint16Array(object data) { } - [ScriptField] - public int length { get { return 0; } } - - [ScriptField] - public UInt16 this[int key] - { - get { return 0; } - set { } - } - } - - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Int16Array - { - public Int16Array(object data) { } - [ScriptField] - public int length { get { return 0; } } - - [ScriptField] - public Int16 this[int key] - { - get { return 0; } - set { } - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class Uint32Array - { - public Uint32Array(object data) { } - [ScriptField] - public int length { get { return 0; } } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public class DataView - { - public DataView(object data) { } - [ScriptField] - public int byteLength { get { return 0; } } - [ScriptField] - public int buffer { get { return 0; } } - - public int getUint8 (int position) { return 0; } - public int getFloat64 (int position, bool littleEndian) { return 0; } - public int getFloat32 (int position, bool littleEndian) { return 0; } - public int getInt16(int position, bool littleEndian) { return 0; } - public int getInt32(int position, bool littleEndian) { return 0; } - //public int getInt64(int position, bool littleEndian) { return 0; } - - } -} - - - diff --git a/engine/csharp_ref/WheelEvent.cs b/engine/csharp_ref/WheelEvent.cs deleted file mode 100644 index 4ae35c95..00000000 --- a/engine/csharp_ref/WheelEvent.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Runtime.CompilerServices; - -namespace System.Html -{ - [ScriptIgnoreNamespace] - [ScriptImport] - - public sealed class WheelEvent - { - internal WheelEvent() - { - } - [ScriptField] - public double WheelDelta - { - get - { - return 0; - } - } - [ScriptField] - public double detail - { - get - { - return 0; - } - } - [ScriptField] - public double deltaY - { - get - { - return 0; - } - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class ChromeNode - { - internal ChromeNode() - { - - } - [ScriptField] - public string TextContent - { - get - { - return ""; - } - } - } - - [ScriptIgnoreNamespace] - [ScriptImport] - public sealed class PointerEvent - { - internal PointerEvent() - { - - } - - [ScriptField] - public int PointerId - { - get - { - return 0; - } - } - - } -} \ No newline at end of file diff --git a/engine/csharp_ref/Wtml.cs b/engine/csharp_ref/Wtml.cs deleted file mode 100644 index 5295cd92..00000000 --- a/engine/csharp_ref/Wtml.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace wwtlib -{ - public class FolderDownloadAction - { - public readonly bool loadChildFolders; - - private readonly Action onComplete; - private int numLoadingFolders = 0; - - public FolderDownloadAction(Action action, bool loadChildFolders) - { - this.onComplete = action; - this.loadChildFolders = loadChildFolders; - } - - private void FolderLoaded() - { - numLoadingFolders--; - if (numLoadingFolders == 0) - { - onComplete(); - } - } - - public void StartingNewFolderLoad(Folder folder) - { - numLoadingFolders++; - folder.ChildLoadCallback(delegate { - Wtml.LoadImagesets(folder, this); - FolderLoaded(); - }); - } - - } - - public class Wtml - { - - static public Folder GetWtmlFile(string url, Action complete, bool? loadChildFolders) - { - if (loadChildFolders == null) - { - loadChildFolders = false; - } - Folder folder = new Folder(); - folder.Url = url; - FolderDownloadAction folderDownloadAction = new FolderDownloadAction(complete, (bool)loadChildFolders); - folderDownloadAction.StartingNewFolderLoad(folder); - return folder; - } - - static public void LoadImagesets(Folder folder, FolderDownloadAction folderDownloadAction) - { - List children = folder.Children; - - foreach (object child in children) - { - if (child is Imageset) - { - Imageset imageSet = (Imageset)child; - WWTControl.AddImageSetToRepository(imageSet); - } - if (child is Place) - { - Place place = (Place)child; - if (place.StudyImageset != null) - { - WWTControl.AddImageSetToRepository(place.StudyImageset); - } - - if (place.BackgroundImageset != null) - { - WWTControl.AddImageSetToRepository(place.BackgroundImageset); - } - } - if (child is Folder && folderDownloadAction.loadChildFolders) - { - folderDownloadAction.StartingNewFolderLoad(((Folder)child)); - } - } - - - if (!string.IsNullOrEmpty(WWTControl.ImageSetName)) - { - string name = WWTControl.ImageSetName.ToLowerCase(); - foreach (Imageset imageset in WWTControl.GetImageSets()) - { - if (imageset.Name.ToLowerCase() == name) - { - WWTControl.Singleton.RenderContext.BackgroundImageset = imageset; - } - } - } - - - } - - } - -} diff --git a/engine/csharp_ref/XDomainRequest.cs b/engine/csharp_ref/XDomainRequest.cs deleted file mode 100644 index 85c17bb4..00000000 --- a/engine/csharp_ref/XDomainRequest.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Xml; - -namespace wwtlib -{ - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("XDomainRequest")] - public sealed class XDomainRequest - { - public XDomainRequest() { } - - [ScriptField] - public Action OnError { set { } } - - [ScriptField] - public Action OnTimeout { set { } } - - [ScriptField] - public Action OnProgress { set { } } - - [ScriptField] - [ScriptName("onload")] - public Action OnLoad { set{ } } - - [ScriptField] - public int Timeout { get { return 0; } set { } } - - [ScriptField] - [ScriptName("responseText")] - public string ResponseText { get { return ""; } set { } } - - public void Open(string method, string url) { } - public void Send() { } - - } -} diff --git a/engine/csharp_ref/XMLHttpRequest2.cs b/engine/csharp_ref/XMLHttpRequest2.cs deleted file mode 100644 index ad3b5d02..00000000 --- a/engine/csharp_ref/XMLHttpRequest2.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Xml; -using System.Net; -using System.Html; - - -namespace wwtlib -{ - [ScriptIgnoreNamespace] - [ScriptImport] - [ScriptName("XMLHttpRequest")] - public sealed class XMLHttpRequest2 : Element - - { - public XMLHttpRequest2(){} - - [ScriptName("onreadystatechange")] - [ScriptField] - public Action OnReadyStateChange { get { return null; } set { } } - [ScriptField] - public ReadyState ReadyState { get { return ReadyState.Loaded; } } - [ScriptField] - public string ResponseText { get { return null; } } - [ScriptName("responseXML")] - [ScriptField] - public XmlDocument ResponseXml { get { return null; } } - [ScriptField] - public int Status { get { return 0; } } - [ScriptField] - public string StatusText { get { return null; } } - [ScriptField] - public object Response { get { return null; } } - [ScriptField] - public string ResponseType { get { return null; } set { } } - public void Abort() { } - public string GetAllResponseHeaders() { return null; } - public string GetResponseHeader(string name) { return null;} - public void Open(HttpVerb verb, string url) { } - public void Open(string method, string url) { } - public void Open(HttpVerb verb, string url, bool async) { } - public void Open(string method, string url, bool async) { } - public void Open(HttpVerb verb, string url, bool async, string userName, string password) { } - public void Open(string method, string url, bool async, string userName, string password) { } - public void Send() { } - public void Send(string body) { } - public void SetRequestHeader(string name, string value) { } - } -} \ No newline at end of file diff --git a/engine/esm/annotation.js b/engine/esm/annotation.js new file mode 100644 index 00000000..293156ff --- /dev/null +++ b/engine/esm/annotation.js @@ -0,0 +1,521 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Web GL support for annotations. +// +// Annotations all share a set of supporting primitives. Each time any +// annotation changes the primitives, they must be regenerated if they have been +// drawn already. It is best to do updates in large batches. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Vector3d } from "./double3d.js"; +import { Dates, LineList, TriangleList, TriangleFanList, PointList } from "./graphics/primitives3d.js"; +import { Tessellator } from "./graphics/tessellator.js"; +import { Color, Colors } from "./color.js"; +import { Coordinates } from "./coordinates.js"; + + +// wwtlib.Annotation + +export function Annotation() { + this.addedToPrimitives = false; + this.annotationDirty = true; + this._opacity = 1; + this._showHoverLabel = false; +} + +Annotation.pointList = null; +Annotation.lineList = null; +Annotation.triangleFanPointList = null; +Annotation.triangleList = null; +Annotation.batchDirty = true; + +Annotation.prepBatch = function (renderContext) { + if (Annotation.pointList == null || Annotation.batchDirty) { + Annotation.pointList = new PointList(renderContext); + Annotation.lineList = new LineList(); + Annotation.triangleFanPointList = new TriangleFanList(); + Annotation.triangleList = new TriangleList(); + Annotation.lineList.set_depthBuffered(false); + Annotation.triangleList.depthBuffered = false; + } +}; + +Annotation.drawBatch = function (renderContext) { + Annotation.batchDirty = false; + if (renderContext.gl == null) { + return; + } + if (Annotation.pointList != null) { + Annotation.pointList.draw(renderContext, 1, false); + } + if (Annotation.lineList != null) { + Annotation.lineList.drawLines(renderContext, 1); + } + if (Annotation.triangleFanPointList != null) { + Annotation.triangleFanPointList.draw(renderContext, 1); + } + if (Annotation.triangleList != null) { + Annotation.triangleList.draw(renderContext, 1, 0); + } +}; + +Annotation.separation = function (Alpha1, Delta1, Alpha2, Delta2) { + Delta1 = Delta1 / 180 * Math.PI; + Delta2 = Delta2 / 180 * Math.PI; + Alpha1 = Alpha1 / 12 * Math.PI; + Alpha2 = Alpha2 / 12 * Math.PI; + var x = Math.cos(Delta1) * Math.sin(Delta2) - Math.sin(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); + var y = Math.cos(Delta2) * Math.sin(Alpha2 - Alpha1); + var z = Math.sin(Delta1) * Math.sin(Delta2) + Math.cos(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); + var vvalue = Math.atan2(Math.sqrt(x * x + y * y), z); + vvalue = vvalue / Math.PI * 180; + if (vvalue < 0) { + vvalue += 180; + } + return vvalue; +}; + +Annotation.colorToUint = function (col) { + return (col.a) << 24 | (col.r << 16) | (col.g) << 8 | col.b; +}; + +Annotation.colorToUintAlpha = function (col, opacity) { + return opacity << 24 | col.r << 16 | col.g << 8 | col.b; +}; + +var Annotation$ = { + draw: function (renderContext) { }, + + get_opacity: function () { + return this._opacity; + }, + + set_opacity: function (value) { + Annotation.batchDirty = true; + this._opacity = value; + return value; + }, + + get_id: function () { + return this._id; + }, + + set_id: function (value) { + this._id = value; + return value; + }, + + get_tag: function () { + return this._tag; + }, + + set_tag: function (value) { + this._tag = value; + return value; + }, + + get_label: function () { + return this._label; + }, + + set_label: function (value) { + this._label = value; + return value; + }, + + get_showHoverLabel: function () { + return this._showHoverLabel; + }, + + set_showHoverLabel: function (value) { + this._showHoverLabel = value; + return value; + }, + + hitTest: function (renderContext, RA, dec, x, y) { + return false; + }, + + get_center: function () { + return this.center; + }, + + set_center: function (value) { + this.center = value; + return value; + } +}; + +registerType("Annotation", [Annotation, Annotation$, null]); + + +// wwtlib.Circle + +export function Circle() { + this._fill$1 = false; + this._skyRelative$1 = false; + this._strokeWidth$1 = 1; + this._radius$1 = 10; + this._lineColor$1 = Colors.get_white(); + this._fillColor$1 = Colors.get_white(); + this._ra$1 = 0; + this._dec$1 = 0; + Annotation.call(this); +} + +var Circle$ = { + get_fill: function () { + return this._fill$1; + }, + + set_fill: function (value) { + Annotation.batchDirty = true; + this._fill$1 = value; + return value; + }, + + get_skyRelative: function () { + return this._skyRelative$1; + }, + + set_skyRelative: function (value) { + Annotation.batchDirty = true; + this._skyRelative$1 = value; + return value; + }, + + get_lineWidth: function () { + return this._strokeWidth$1; + }, + + set_lineWidth: function (value) { + Annotation.batchDirty = true; + this._strokeWidth$1 = value; + return value; + }, + + get_radius: function () { + return this._radius$1; + }, + + set_radius: function (value) { + Annotation.batchDirty = true; + this._radius$1 = value; + return value; + }, + + get_lineColor: function () { + return this._lineColor$1.toString(); + }, + + set_lineColor: function (value) { + Annotation.batchDirty = true; + this._lineColor$1 = Color.load(value); + return value; + }, + + get_fillColor: function () { + return this._fillColor$1.toString(); + }, + + set_fillColor: function (value) { + Annotation.batchDirty = true; + this._fillColor$1 = Color.fromName(value); + return value; + }, + + setCenter: function (ra, dec) { + Annotation.batchDirty = true; + this._ra$1 = ra / 15; + this._dec$1 = dec; + this.center = Coordinates.raDecTo3d(this._ra$1, this._dec$1); + }, + + draw: function (renderContext) { + var onScreen = true; + var rad = this._radius$1; + if (this._skyRelative$1) { + rad /= renderContext.get_fovScale() / 3600; + } + var screenSpacePnt = renderContext.WVP.transform(this.center); + if (screenSpacePnt.z < 0) { + onScreen = false; + } + if (Vector3d.dot(renderContext.get_viewPoint(), this.center) < 0.55) { + onScreen = false; + } + if (renderContext.gl != null) { + if (Annotation.batchDirty || this.annotationDirty) { + var up = Vector3d.create(0, 1, 0); + var xNormal = Vector3d.cross(this.center, up); + var yNormal = Vector3d.cross(this.center, xNormal); + var r = this._radius$1 / 44; + var segments = 72; + var radiansPerSegment = Math.PI * 2 / segments; + var vertexList = []; + for (var j = 0; j <= segments; j++) { + var x = Math.cos(j * radiansPerSegment) * r; + var y = Math.sin(j * radiansPerSegment) * r; + vertexList.push(Vector3d.create(this.center.x + x * xNormal.x + y * yNormal.x, this.center.y + x * xNormal.y + y * yNormal.y, this.center.z + x * xNormal.z + y * yNormal.z)); + } + if (this._strokeWidth$1 > 0 && vertexList.length > 1) { + var lineColorWithOpacity = this._lineColor$1._clone(); + lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); + for (var i = 0; i < (vertexList.length - 1); i++) { + Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); + } + } + if (this._fill$1) { + var fillColorWithOpacity = this._fillColor$1._clone(); + fillColorWithOpacity.a = Math.round(fillColorWithOpacity.a * this.get_opacity()); + var pos = Vector3d.create(this.center.x, this.center.y, this.center.z); + vertexList.splice(0, 0, pos); + Annotation.triangleFanPointList.addShape(vertexList, fillColorWithOpacity, new Dates(0, 1)); + } + this.annotationDirty = false; + } + } else { + if (onScreen) { + var ctx = renderContext.device; + ctx.save(); + ctx.globalAlpha = this.get_opacity(); + ctx.beginPath(); + ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); + ctx.lineWidth = this._strokeWidth$1; + ctx.fillStyle = this._fillColor$1.toString(); + if (this._fill$1) { + ctx.fill(); + } + ctx.globalAlpha = 1; + ctx.strokeStyle = this._lineColor$1.toString(); + ctx.stroke(); + ctx.restore(); + } + } + }, + + hitTest: function (renderContext, RA, dec, x, y) { + if (ss.emptyString(this.get_id())) { + return false; + } + var rad = this._radius$1; + if (!this._skyRelative$1) { + rad *= renderContext.get_fovScale() / 3600; + } + return Annotation.separation(RA, dec, this._ra$1, this._dec$1) < rad; + } +}; + +registerType("Circle", [Circle, Circle$, Annotation]); + + +// wwtlib.Poly + +export function Poly() { + this._points$1 = []; + this._fill$1 = false; + this._strokeWidth$1 = 1; + this._lineColor$1 = Colors.get_white(); + this._fillColor$1 = Colors.get_white(); + Annotation.call(this); +} + +var Poly$ = { + addPoint: function (x, y) { + Annotation.batchDirty = true; + this._points$1.push(Coordinates.raDecTo3d(x / 15, y)); + }, + + get_fill: function () { + return this._fill$1; + }, + + set_fill: function (value) { + Annotation.batchDirty = true; + this._fill$1 = value; + return value; + }, + + get_lineWidth: function () { + return this._strokeWidth$1; + }, + + set_lineWidth: function (value) { + Annotation.batchDirty = true; + this._strokeWidth$1 = value; + return value; + }, + + get_lineColor: function () { + return this._lineColor$1.toString(); + }, + + set_lineColor: function (value) { + Annotation.batchDirty = true; + this._lineColor$1 = Color.fromName(value); + return value; + }, + + get_fillColor: function () { + return this._fillColor$1.toString(); + }, + + set_fillColor: function (value) { + Annotation.batchDirty = true; + this._fillColor$1 = Color.fromName(value); + return value; + }, + + draw: function (renderContext) { + if (renderContext.gl != null) { + if (Annotation.batchDirty || this.annotationDirty) { + //todo can we save this work for later? + var vertexList = this._points$1; + + if (this._strokeWidth$1 > 0 && this._points$1.length > 1) { + var lineColorWithOpacity = this._lineColor$1._clone(); + lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); + for (var i = 0; i < (this._points$1.length - 1); i++) { + Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); + } + Annotation.lineList.addLine(vertexList[this._points$1.length - 1], vertexList[0], lineColorWithOpacity, new Dates(0, 1)); + } + if (this._fill$1) { + var fillColorWithOpacity = this._fillColor$1._clone(); + fillColorWithOpacity.a = Math.round(fillColorWithOpacity.a * this.get_opacity()); + var indexes = Tessellator.tesselateSimplePoly(vertexList); + for (var i = 0; i < indexes.length; i += 3) { + Annotation.triangleList.addSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], fillColorWithOpacity, new Dates(0, 1), 2); + } + } + this.annotationDirty = false; + } + } else { + var ctx = renderContext.device; + ctx.save(); + ctx.globalAlpha = this.get_opacity(); + ctx.beginPath(); + var first = true; + var $enum1 = ss.enumerate(this._points$1); + while ($enum1.moveNext()) { + var pnt = $enum1.current; + var screenSpacePnt = renderContext.WVP.transform(pnt); + if (screenSpacePnt.z < 0) { + ctx.restore(); + return; + } + if (Vector3d.dot(renderContext.get_viewPoint(), pnt) < 0.75) { + ctx.restore(); + return; + } + if (first) { + first = false; + ctx.moveTo(screenSpacePnt.x, screenSpacePnt.y); + } + else { + ctx.lineTo(screenSpacePnt.x, screenSpacePnt.y); + } + } + ctx.closePath(); + ctx.lineWidth = this._strokeWidth$1; + if (this._fill$1) { + ctx.fillStyle = this._fillColor$1.toString(); + ctx.fill(); + } + ctx.strokeStyle = this._lineColor$1.toString(); + ctx.globalAlpha = 1; + ctx.stroke(); + ctx.restore(); + } + } +}; + +registerType("Poly", [Poly, Poly$, Annotation]); + + +// wwtlib.PolyLine + +export function PolyLine() { + this._points$1 = []; + this._strokeWidth$1 = 1; + this._lineColor$1 = Colors.get_white(); + Annotation.call(this); +} + +var PolyLine$ = { + addPoint: function (x, y) { + Annotation.batchDirty = true; + this._points$1.push(Coordinates.raDecTo3d(x / 15, y)); + }, + + get_lineWidth: function () { + return this._strokeWidth$1; + }, + + set_lineWidth: function (value) { + Annotation.batchDirty = true; + this._strokeWidth$1 = value; + return value; + }, + + get_lineColor: function () { + return this._lineColor$1.toString(); + }, + + set_lineColor: function (value) { + Annotation.batchDirty = true; + this._lineColor$1 = Color.fromName(value); + return value; + }, + + draw: function (renderContext) { + if (renderContext.gl != null) { + if (Annotation.batchDirty || this.annotationDirty) { + //todo can we save this work for later? + var vertexList = this._points$1; + if (this._strokeWidth$1 > 0) { + var lineColorWithOpacity = this._lineColor$1._clone(); + lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); + for (var i = 0; i < (this._points$1.length - 1); i++) { + Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); + } + } + this.annotationDirty = false; + } + } else { + var ctx = renderContext.device; + ctx.save(); + ctx.globalAlpha = this.get_opacity(); + var first = true; + var $enum1 = ss.enumerate(this._points$1); + while ($enum1.moveNext()) { + var pnt = $enum1.current; + var screenSpacePnt = renderContext.WVP.transform(pnt); + if (screenSpacePnt.z < 0) { + ctx.restore(); + return; + } + if (Vector3d.dot(renderContext.get_viewPoint(), pnt) < 0.75) { + ctx.restore(); + return; + } + if (first) { + first = false; + ctx.beginPath(); + ctx.moveTo(screenSpacePnt.x, screenSpacePnt.y); + } + else { + ctx.lineTo(screenSpacePnt.x, screenSpacePnt.y); + } + } + ctx.lineWidth = this._strokeWidth$1; + ctx.strokeStyle = this._lineColor$1.toString(); + ctx.stroke(); + ctx.restore(); + } + } +}; + +registerType("PolyLine", [PolyLine, PolyLine$, Annotation]); diff --git a/engine/esm/astrocalc.js b/engine/esm/astrocalc.js new file mode 100644 index 00000000..1354993b --- /dev/null +++ b/engine/esm/astrocalc.js @@ -0,0 +1,216 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Some miscellaneous types relating to astronomy calculations. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Util } from "./util.js"; +import { CT } from "./astrocalc/coordinate_transformation.js"; +import { DT } from "./astrocalc/date.js"; +import { CAANutation } from "./astrocalc/nutation.js"; +import { CAAParallax } from "./astrocalc/parallax.js"; +import { CAAPhysicalJupiter, CAAPhysicalJupiterDetails } from "./astrocalc/physical_jupiter.js"; +import { CAARiseTransitSet } from "./astrocalc/rise_transit_set.js"; +import { ELL, EPD } from "./astrocalc/elliptical.js"; +import { GM, GMDS } from "./astrocalc/galilean_moons.js"; +import { CAAMoon } from "./astrocalc/moon.js"; + + +// Global state + +var galDetails = new GMDS(); +var jupDetails = new EPD(); +var jupPhisical = new CAAPhysicalJupiterDetails(); +var jDateLast = 0; + + +// wwtlib.AstroRaDec + +export function AstroRaDec(ra, dec, dist, shadow, eclipsed) { + this.RA = 0; + this.dec = 0; + this.distance = 0; + this.shadow = false; + this.eclipsed = false; + this.RA = ra; + this.dec = dec; + this.distance = dist; + this.shadow = shadow; + this.eclipsed = eclipsed; +} + +var AstroRaDec$ = {}; + +registerType("AstroRaDec", [AstroRaDec, AstroRaDec$, null]); + + +// wwtlib.RiseSetDetails + +export function RiseSetDetails(bValid, Rise, Transit, Set, neverRises) { + this.bValid = false; + this.rise = 0; + this.transit = 0; + this.set = 0; + this.bNeverRises = false; + this.bValid = bValid; + this.rise = Rise; + this.transit = Transit; + this.set = Set; + this.bNeverRises = neverRises; +} + +var RiseSetDetails$ = {}; + +registerType("RiseSetDetails", [RiseSetDetails, RiseSetDetails$, null]); + + +// wwtlib.AstroCalc + +export function AstroCalc() { } + +AstroCalc.getPlanet = function (jDate, planetIn, locLat, locLong, locHeight) { + var planet = planetIn; + locLong = -locLong; + + if (planet < 9) { + var Details = ELL.calculate(jDate, planetIn); + var corrected = CAAParallax.equatorial2Topocentric(Details.apparentGeocentricRA, Details.apparentGeocentricDeclination, Details.apparentGeocentricDistance, locLong, locLat, locHeight, jDate); + return new AstroRaDec(corrected.x, corrected.y, Details.apparentGeocentricDistance, false, false); + } + else if (planet === 9) { + var lat = CAAMoon.eclipticLatitude(jDate); + var lng = CAAMoon.eclipticLongitude(jDate); + var dis = CAAMoon.radiusVector(jDate) / 149598000; + var epsilon = CAANutation.trueObliquityOfEcliptic(jDate); + var d = CT.ec2Eq(lng, lat, epsilon); + var corrected = CAAParallax.equatorial2Topocentric(d.x, d.y, dis, locLong, locLat, locHeight, jDate); + return new AstroRaDec(corrected.x, corrected.y, dis, false, false); + } + else { + if (jDate !== jDateLast) { + jupDetails = ELL.calculate(jDate, 4); + jupPhisical = CAAPhysicalJupiter.calculate(jDate); + var corrected = CAAParallax.equatorial2Topocentric(jupDetails.apparentGeocentricRA, jupDetails.apparentGeocentricDeclination, jupDetails.apparentGeocentricDistance, locLong, locLat, locHeight, jDate); + jupDetails.apparentGeocentricRA = corrected.x; + jupDetails.apparentGeocentricDeclination = corrected.y; + galDetails = GM.calculate(jDate); + jDateLast = jDate; + } + var jupiterDiameter = 0.000954501; + var scale = Math.atan(0.5 * (jupiterDiameter / jupDetails.apparentGeocentricDistance)) / 3.1415927 * 180; + var raScale = (scale / Math.cos(jupDetails.apparentGeocentricDeclination / 180 * 3.1415927)) / 15; + var xMoon = 0; + var yMoon = 0; + var zMoon = 0; + var shadow = false; + var eclipsed = false; + switch (planet) { + case 10: // IO + xMoon = galDetails.satellite1.apparentRectangularCoordinates.x; + yMoon = galDetails.satellite1.apparentRectangularCoordinates.y; + zMoon = galDetails.satellite1.apparentRectangularCoordinates.z; + eclipsed = galDetails.satellite1.bInEclipse; + shadow = galDetails.satellite1.bInShadowTransit; + break; + case 11: // Europa + xMoon = galDetails.satellite2.apparentRectangularCoordinates.x; + yMoon = galDetails.satellite2.apparentRectangularCoordinates.y; + zMoon = galDetails.satellite2.apparentRectangularCoordinates.z; + eclipsed = galDetails.satellite2.bInEclipse; + shadow = galDetails.satellite2.bInShadowTransit; + break; + case 12: // Ganymede + xMoon = galDetails.satellite3.apparentRectangularCoordinates.x; + yMoon = galDetails.satellite3.apparentRectangularCoordinates.y; + zMoon = galDetails.satellite3.apparentRectangularCoordinates.z; + eclipsed = galDetails.satellite3.bInEclipse; + shadow = galDetails.satellite3.bInShadowTransit; + break; + case 13: // Callisto + xMoon = galDetails.satellite4.apparentRectangularCoordinates.x; + yMoon = galDetails.satellite4.apparentRectangularCoordinates.y; + zMoon = galDetails.satellite4.apparentRectangularCoordinates.z; + eclipsed = galDetails.satellite4.bInEclipse; + shadow = galDetails.satellite4.bInShadowTransit; + break; + case 14: // Io shadow + xMoon = galDetails.satellite1.apparentShadowRectangularCoordinates.x; + yMoon = galDetails.satellite1.apparentShadowRectangularCoordinates.y; + zMoon = galDetails.satellite1.apparentShadowRectangularCoordinates.z * 0.9; + shadow = galDetails.satellite1.bInShadowTransit; + break; + case 15: // Europa shadow + xMoon = galDetails.satellite2.apparentShadowRectangularCoordinates.x; + yMoon = galDetails.satellite2.apparentShadowRectangularCoordinates.y; + zMoon = galDetails.satellite2.apparentShadowRectangularCoordinates.z * 0.9; + shadow = galDetails.satellite2.bInShadowTransit; + break; + case 16: // Ganymede shadow + xMoon = galDetails.satellite3.apparentShadowRectangularCoordinates.x; + yMoon = galDetails.satellite3.apparentShadowRectangularCoordinates.y; + zMoon = galDetails.satellite3.apparentShadowRectangularCoordinates.z * 0.9; + shadow = galDetails.satellite3.bInShadowTransit; + break; + case 17: // Callisto shadow + xMoon = galDetails.satellite4.apparentShadowRectangularCoordinates.x; + yMoon = galDetails.satellite4.apparentShadowRectangularCoordinates.y; + zMoon = galDetails.satellite4.apparentShadowRectangularCoordinates.z * 0.9; + shadow = galDetails.satellite4.bInShadowTransit; + break; + } + var xTemp; + var yTemp; + var radians = jupPhisical.p / 180 * 3.1415927; + xTemp = xMoon * Math.cos(radians) - yMoon * Math.sin(radians); + yTemp = xMoon * Math.sin(radians) + yMoon * Math.cos(radians); + xMoon = xTemp; + yMoon = yTemp; + return new AstroRaDec(jupDetails.apparentGeocentricRA - (xMoon * raScale), jupDetails.apparentGeocentricDeclination + yMoon * scale, jupDetails.apparentGeocentricDistance + (zMoon * jupiterDiameter / 2), shadow, eclipsed); + } +}; + +AstroCalc.getJulianDay = function (year, month, day) { + return DT.dateToJD(ss.truncate(year), ss.truncate(month), day, true); +}; + +AstroCalc.eclipticToJ2000 = function (l, b, jNow) { + var radec = CT.ec2Eq(l, b, CAANutation.trueObliquityOfEcliptic(jNow)); + return new AstroRaDec(radec.x, radec.y, 0, false, false); +}; + +AstroCalc.galacticToJ2000 = function (l, b) { + var radec = CT.g2Eq(l, b); + return new AstroRaDec(radec.x, radec.y, 0, false, false); +}; + +AstroCalc.j2000ToGalactic = function (ra, dec) { + var galactic = CT.eq2G(ra, dec); + return new AstroRaDec(galactic.x, galactic.y, 0, false, false); +}; + +AstroCalc.getRiseTrinsitSet = function (jd, lat, lng, ra1, dec1, ra2, dec2, ra3, dec3, type) { + var alt = -0.5667; + + switch (type) { + case 0: // Planet or star + alt = -0.5667; + break; + case 1: // Sun + alt = -0.8333; + break; + case 2: + alt = 0.125; + break; + } + var RiseTransitSetTime = CAARiseTransitSet.rise(jd, ra1, dec1, ra2, dec2, ra3, dec3, lng, lat, alt); + var neverRises = false; + if (!RiseTransitSetTime.bValid) { + neverRises = Util.sign(lat) !== Util.sign(dec2); + } + return new RiseSetDetails(RiseTransitSetTime.bValid, RiseTransitSetTime.rise, RiseTransitSetTime.transit, RiseTransitSetTime.set, neverRises); +}; + +var AstroCalc$ = {}; + +registerType("AstroCalc", [AstroCalc, AstroCalc$, null]); diff --git a/engine/esm/astrocalc/aberration.js b/engine/esm/astrocalc/aberration.js new file mode 100644 index 00000000..2d652e68 --- /dev/null +++ b/engine/esm/astrocalc/aberration.js @@ -0,0 +1,152 @@ +// Originally `AAABERRATION.CPP` +// "Purpose: Implementation for the algorithms for Aberration" +// Last update of original: PJN / 21-04-2005 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { C3D, COR, CT } from "./coordinate_transformation.js"; +import { CAASun } from "./sun.js"; + + +// ACFT + +export function ACFT(L2, L3, L4, L5, L6, L7, L8, Ldash, D, Mdash, F, xsin, xsint, xcos, xcost, ysin, ysint, ycos, ycost, zsin, zsint, zcos, zcost) { + this.l2 = 0; + this.l3 = 0; + this.l4 = 0; + this.l5 = 0; + this.l6 = 0; + this.l7 = 0; + this.l8 = 0; + this.ldash = 0; + this.d = 0; + this.mdash = 0; + this.f = 0; + this.xsin = 0; + this.xsint = 0; + this.xcos = 0; + this.xcost = 0; + this.ysin = 0; + this.ysint = 0; + this.ycos = 0; + this.ycost = 0; + this.zsin = 0; + this.zsint = 0; + this.zcos = 0; + this.zcost = 0; + this.l2 = L2; + this.l3 = L3; + this.l4 = L4; + this.l5 = L5; + this.l6 = L6; + this.l7 = L7; + this.l8 = L8; + this.ldash = Ldash; + this.d = D; + this.mdash = Mdash; + this.f = F; + this.xsin = xsin; + this.xsint = xsint; + this.xcos = xcos; + this.xcost = xcost; + this.ysin = ysin; + this.ysint = ysint; + this.ycos = ycos; + this.ycost = ycost; + this.zsin = zsin; + this.zsint = zsint; + this.zcos = zcos; + this.zcost = zcost; +} + +var ACFT$ = {}; + +registerType("ACFT", [ACFT, ACFT$, null]); + + +// Coefficients + +const g_ACft = [new ACFT(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1719914, -2, -25, 0, 25, -13, 1578089, 156, 10, 32, 684185, -358), new ACFT(0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6434, 141, 28007, -107, 25697, -95, -5904, -130, 11141, -48, -2559, -55), new ACFT(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 715, 0, 0, 0, 6, 0, -657, 0, -15, 0, -282, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 715, 0, 0, 0, 0, 0, -656, 0, 0, 0, -285, 0), new ACFT(0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 486, -5, -236, -4, -216, -4, -446, 5, -94, 0, -193, 0), new ACFT(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 2, 0, -147, 0, -6, 0, -61, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, -59, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 39, 0, 0, 0, 0, 0, -36, 0, 0, 0, -16, 0), new ACFT(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 33, 0, -10, 0, -9, 0, -30, 0, -5, 0, -13, 0), new ACFT(0, 2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 31, 0, 1, 0, 1, 0, -28, 0, 0, 0, -12, 0), new ACFT(0, 3, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, 25, 0, 8, 0, 11, 0, 3, 0), new ACFT(0, 5, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, -25, 0, -8, 0, -11, 0, -3, 0), new ACFT(2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, -19, 0, 0, 0, -8, 0), new ACFT(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -19, 0, 0, 0, 0, 0, 17, 0, 0, 0, 8, 0), new ACFT(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, -16, 0, 0, 0, -7, 0), new ACFT(0, 1, 0, -2, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 1, 0, 7, 0), new ACFT(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, -15, 0, -3, 0, -6, 0), new ACFT(0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 11, 0, -1, 0, -1, 0, -10, 0, -1, 0, -5, 0), new ACFT(2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -11, 0, -10, 0, 0, 0, -4, 0, 0, 0), new ACFT(0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -11, 0, -2, 0, -2, 0, 9, 0, -1, 0, 4, 0), new ACFT(0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -8, 0, -8, 0, 6, 0, -3, 0, 3, 0), new ACFT(0, 3, 0, -2, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, 0, 0, 0, 9, 0, 0, 0, 4, 0), new ACFT(1, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -9, 0, 0, 0, -4, 0), new ACFT(2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -8, 0, 0, 0, -4, 0), new ACFT(0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, -8, 0, 0, 0, -3, 0, 0, 0), new ACFT(2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 8, 0, 0, 0, 3, 0, 0, 0), new ACFT(0, 3, -2, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, -8, 0, 0, 0, -3, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 2, -1, 0, 8, 0, 0, 0, 0, 0, -7, 0, 0, 0, -3, 0), new ACFT(8, -12, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, -6, 0, 4, 0, -3, 0, 2, 0), new ACFT(8, -14, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, 6, 0, -4, 0, 3, 0, -2, 0), new ACFT(0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -6, 0, -5, 0, -4, 0, 5, 0, -2, 0, 2, 0), new ACFT(3, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -2, 0, -7, 0, 1, 0, -4, 0), new ACFT(0, 2, 0, -2, 0, 0, 0, 0, 0, 0, 0, 4, 0, -6, 0, -5, 0, -4, 0, -2, 0, -2, 0), new ACFT(3, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -6, 0, 0, 0, -3, 0, 0, 0), new ACFT(0, 2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, -5, 0, -4, 0, -5, 0, -2, 0, -2, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, -2, 0, 0, 5, 0, 0, 0, 0, 0, -5, 0, 0, 0, -2, 0)]; + + +// ABR - was CAAAberration + +export function ABR() { } + +ABR.earthVelocity = function (JD) { + var T = (JD - 2451545) / 36525; + var L2 = 3.1761467 + 1021.3285546 * T; + var L3 = 1.7534703 + 628.3075849 * T; + var L4 = 6.2034809 + 334.0612431 * T; + var L5 = 0.5995465 + 52.9690965 * T; + var L6 = 0.8740168 + 21.3299095 * T; + var L7 = 5.4812939 + 7.4781599 * T; + var L8 = 5.3118863 + 3.8133036 * T; + var Ldash = 3.8103444 + 8399.6847337 * T; + var D = 5.1984667 + 7771.3771486 * T; + var Mdash = 2.3555559 + 8328.6914289 * T; + var F = 1.6279052 + 8433.4661601 * T; + var velocity = new C3D(); + var nAberrationCoefficients = g_ACft.length; + for (var i = 0; i < nAberrationCoefficients; i++) { + var Argument = g_ACft[i].l2 * L2 + g_ACft[i].l3 * L3 + g_ACft[i].l4 * L4 + g_ACft[i].l5 * L5 + g_ACft[i].l6 * L6 + g_ACft[i].l7 * L7 + g_ACft[i].l8 * L8 + g_ACft[i].ldash * Ldash + g_ACft[i].d * D + g_ACft[i].mdash * Mdash + g_ACft[i].f * F; + velocity.x += (g_ACft[i].xsin + g_ACft[i].xsint * T) * Math.sin(Argument); + velocity.x += (g_ACft[i].xcos + g_ACft[i].xcost * T) * Math.cos(Argument); + velocity.y += (g_ACft[i].ysin + g_ACft[i].ysint * T) * Math.sin(Argument); + velocity.y += (g_ACft[i].ycos + g_ACft[i].ycost * T) * Math.cos(Argument); + velocity.z += (g_ACft[i].zsin + g_ACft[i].zsint * T) * Math.sin(Argument); + velocity.z += (g_ACft[i].zcos + g_ACft[i].zcost * T) * Math.cos(Argument); + } + return velocity; +}; + +ABR.eclipticAberration = function (Lambda, Beta, JD) { + var aberration = new COR(); + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var e = 0.016708634 - 4.2037E-05 * T - 1.267E-07 * Tsquared; + var pi = 102.93735 + 1.71946 * T + 0.00046 * Tsquared; + var k = 20.49552; + var SunLongitude = CAASun.geometricEclipticLongitude(JD); + pi = CT.d2R(pi); + Lambda = CT.d2R(Lambda); + Beta = CT.d2R(Beta); + SunLongitude = CT.d2R(SunLongitude); + aberration.x = (-k * Math.cos(SunLongitude - Lambda) + e * k * Math.cos(pi - Lambda)) / Math.cos(Beta) / 3600; + aberration.y = -k * Math.sin(Beta) * (Math.sin(SunLongitude - Lambda) - e * Math.sin(pi - Lambda)) / 3600; + return aberration; +}; + +ABR.equatorialAberration = function (Alpha, Delta, JD) { + Alpha = CT.d2R(Alpha * 15); + Delta = CT.d2R(Delta); + var cosAlpha = Math.cos(Alpha); + var sinAlpha = Math.sin(Alpha); + var cosDelta = Math.cos(Delta); + var sinDelta = Math.sin(Delta); + var velocity = ABR.earthVelocity(JD); + var aberration = new COR(); + aberration.x = CT.r2H((velocity.y * cosAlpha - velocity.x * sinAlpha) / (17314463350 * cosDelta)); + aberration.y = CT.r2D(-(((velocity.x * cosAlpha + velocity.y * sinAlpha) * sinDelta - velocity.z * cosDelta) / 17314463350)); + return aberration; +}; + +var ABR$ = {}; + +registerType("ABR", [ABR, ABR$, null]); diff --git a/engine/esm/astrocalc/angular_separation.js b/engine/esm/astrocalc/angular_separation.js new file mode 100644 index 00000000..79ab3d11 --- /dev/null +++ b/engine/esm/astrocalc/angular_separation.js @@ -0,0 +1,91 @@ +// Originally `AAANGULARSEPARATION.CPP` +// "Purpose: Implementation for the algorithms which obtain various separation distances between celestial objects" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// ASEP - was CAAAngularSeparation + +export function ASEP() { } + +ASEP.separation = function (Alpha1, Delta1, Alpha2, Delta2) { + Delta1 = CT.d2R(Delta1); + Delta2 = CT.d2R(Delta2); + Alpha1 = CT.h2R(Alpha1); + Alpha2 = CT.h2R(Alpha2); + var x = Math.cos(Delta1) * Math.sin(Delta2) - Math.sin(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); + var y = Math.cos(Delta2) * Math.sin(Alpha2 - Alpha1); + var z = Math.sin(Delta1) * Math.sin(Delta2) + Math.cos(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); + var vvalue = Math.atan2(Math.sqrt(x * x + y * y), z); + vvalue = CT.r2D(vvalue); + if (vvalue < 0) { + vvalue += 180; + } + return vvalue; +}; + +ASEP.positionAngle = function (alpha1, delta1, alpha2, delta2) { + var Alpha1; + var Delta1; + var Alpha2; + var Delta2; + Delta1 = CT.d2R(delta1); + Delta2 = CT.d2R(delta2); + Alpha1 = CT.h2R(alpha1); + Alpha2 = CT.h2R(alpha2); + var DeltaAlpha = Alpha1 - Alpha2; + var demoninator = Math.cos(Delta2) * Math.tan(Delta1) - Math.sin(Delta2) * Math.cos(DeltaAlpha); + var numerator = Math.sin(DeltaAlpha); + var vvalue = Math.atan2(numerator, demoninator); + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +ASEP.distanceFromGreatArc = function (Alpha1, Delta1, Alpha2, Delta2, Alpha3, Delta3) { + Delta1 = CT.d2R(Delta1); + Delta2 = CT.d2R(Delta2); + Delta3 = CT.d2R(Delta3); + Alpha1 = CT.h2R(Alpha1); + Alpha2 = CT.h2R(Alpha2); + Alpha3 = CT.h2R(Alpha3); + var X1 = Math.cos(Delta1) * Math.cos(Alpha1); + var X2 = Math.cos(Delta2) * Math.cos(Alpha2); + var Y1 = Math.cos(Delta1) * Math.sin(Alpha1); + var Y2 = Math.cos(Delta2) * Math.sin(Alpha2); + var Z1 = Math.sin(Delta1); + var Z2 = Math.sin(Delta2); + var A = Y1 * Z2 - Z1 * Y2; + var B = Z1 * X2 - X1 * Z2; + var C = X1 * Y2 - Y1 * X2; + var m = Math.tan(Alpha3); + var n = Math.tan(Delta3) / Math.cos(Alpha3); + var vvalue = Math.asin((A + B * m + C * n) / (Math.sqrt(A * A + B * B + C * C) * Math.sqrt(1 + m * m + n * n))); + vvalue = CT.r2D(vvalue); + if (vvalue < 0) { + vvalue = Math.abs(vvalue); + } + return vvalue; +}; + +var ASEP$ = {}; + +registerType("ASEP", [ASEP, ASEP$, null]); diff --git a/engine/esm/astrocalc/coordinate_transformation.js b/engine/esm/astrocalc/coordinate_transformation.js new file mode 100644 index 00000000..b076ddaa --- /dev/null +++ b/engine/esm/astrocalc/coordinate_transformation.js @@ -0,0 +1,211 @@ +// Originally `AACOORDINATETRANSFORMATION.CPP` +// "Purpose: Implementation for the algorithms which convert between the various celestial coordinate systems" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; + + +// COR - was CAA2DCoordinate + +export function COR() { + this.x = 0; + this.y = 0; + this.x = 0; + this.y = 0; +} + +COR.create = function (x, y) { + var item = new COR(); + item.x = x; + item.y = y; + return item; +}; + +var COR$ = {}; + +registerType("COR", [COR, COR$, null]); + + +// C3D - was CAA3DCoordinate + +export function C3D() { + this.x = 0; + this.y = 0; + this.z = 0; + this.x = 0; + this.y = 0; + this.z = 0; +} + +C3D.create = function (x, y, z) { + var item = new C3D(); + item.x = x; + item.y = y; + item.z = z; + return item; +}; + +var C3D$ = {}; + +registerType("C3D", [C3D, C3D$, null]); + + +// CT - was CAACoordinateTransformation + +export function CT() { +} + +CT.eq2Ec = function (Alpha, Delta, Epsilon) { + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + Epsilon = CT.d2R(Epsilon); + var Ecliptic = new COR(); + Ecliptic.x = CT.r2D(Math.atan2(Math.sin(Alpha) * Math.cos(Epsilon) + Math.tan(Delta) * Math.sin(Epsilon), Math.cos(Alpha))); + if (Ecliptic.x < 0) { + Ecliptic.x += 360; + } + Ecliptic.y = CT.r2D(Math.asin(Math.sin(Delta) * Math.cos(Epsilon) - Math.cos(Delta) * Math.sin(Epsilon) * Math.sin(Alpha))); + return Ecliptic; +}; + +CT.ec2Eq = function (Lambda, Beta, Epsilon) { + Lambda = CT.d2R(Lambda); + Beta = CT.d2R(Beta); + Epsilon = CT.d2R(Epsilon); + var Equatorial = new COR(); + Equatorial.x = CT.r2H(Math.atan2(Math.sin(Lambda) * Math.cos(Epsilon) - Math.tan(Beta) * Math.sin(Epsilon), Math.cos(Lambda))); + if (Equatorial.x < 0) { + Equatorial.x += 24; + } + Equatorial.y = CT.r2D(Math.asin(Math.sin(Beta) * Math.cos(Epsilon) + Math.cos(Beta) * Math.sin(Epsilon) * Math.sin(Lambda))); + return Equatorial; +}; + +CT.eq2H = function (LocalHourAngle, Delta, Latitude) { + LocalHourAngle = CT.h2R(LocalHourAngle); + Delta = CT.d2R(Delta); + Latitude = CT.d2R(Latitude); + var Horizontal = new COR(); + Horizontal.x = CT.r2D(Math.atan2(Math.sin(LocalHourAngle), Math.cos(LocalHourAngle) * Math.sin(Latitude) - Math.tan(Delta) * Math.cos(Latitude))); + if (Horizontal.x < 0) { + Horizontal.x += 360; + } + Horizontal.y = CT.r2D(Math.asin(Math.sin(Latitude) * Math.sin(Delta) + Math.cos(Latitude) * Math.cos(Delta) * Math.cos(LocalHourAngle))); + return Horizontal; +}; + +CT.h2Eq = function (Azimuth, Altitude, Latitude) { + Azimuth = CT.d2R(Azimuth); + Altitude = CT.d2R(Altitude); + Latitude = CT.d2R(Latitude); + var Equatorial = new COR(); + Equatorial.x = CT.r2H(Math.atan2(Math.sin(Azimuth), Math.cos(Azimuth) * Math.sin(Latitude) + Math.tan(Altitude) * Math.cos(Latitude))); + if (Equatorial.x < 0) { + Equatorial.x += 24; + } + Equatorial.y = CT.r2D(Math.asin(Math.sin(Latitude) * Math.sin(Altitude) - Math.cos(Latitude) * Math.cos(Altitude) * Math.cos(Azimuth))); + return Equatorial; +}; + +CT.eq2G = function (Alpha, Delta) { + Alpha = 192.25 - CT.h2D(Alpha); + Alpha = CT.d2R(Alpha); + Delta = CT.d2R(Delta); + var Galactic = new COR(); + Galactic.x = CT.r2D(Math.atan2(Math.sin(Alpha), Math.cos(Alpha) * Math.sin(CT.d2R(27.4)) - Math.tan(Delta) * Math.cos(CT.d2R(27.4)))); + Galactic.x = 303 - Galactic.x; + if (Galactic.x >= 360) { + Galactic.x -= 360; + } + Galactic.y = CT.r2D(Math.asin(Math.sin(Delta) * Math.sin(CT.d2R(27.4)) + Math.cos(Delta) * Math.cos(CT.d2R(27.4)) * Math.cos(Alpha))); + return Galactic; +}; + +CT.g2Eq = function (l, b) { + l -= 123; + l = CT.d2R(l); + b = CT.d2R(b); + var Equatorial = new COR(); + Equatorial.x = CT.r2D(Math.atan2(Math.sin(l), Math.cos(l) * Math.sin(CT.d2R(27.4)) - Math.tan(b) * Math.cos(CT.d2R(27.4)))); + Equatorial.x += 12.25; + if (Equatorial.x < 0) { + Equatorial.x += 360; + } + Equatorial.x = CT.d2H(Equatorial.x); + Equatorial.y = CT.r2D(Math.asin(Math.sin(b) * Math.sin(CT.d2R(27.4)) + Math.cos(b) * Math.cos(CT.d2R(27.4)) * Math.cos(l))); + return Equatorial; +}; + +CT.d2R = function (Degrees) { + return Degrees * 0.0174532925199433; +}; + +CT.r2D = function (Radians) { + return Radians * 57.2957795130823; +}; + +CT.r2H = function (Radians) { + return Radians * 3.81971863420549; +}; + +CT.h2R = function (Hours) { + return Hours * 0.261799387799149; +}; + +CT.h2D = function (Hours) { + return Hours * 15; +}; + +CT.d2H = function (Degrees) { + return Degrees / 15; +}; + +CT.PI = function () { + return 3.14159265358979; +}; + +CT.m360 = function (Degrees) { + return Degrees - Math.floor(Degrees / 360) * 360; +}; + +CT.m24 = function (HourAngle) { + return HourAngle - Math.floor(HourAngle / 24) * 24; +}; + +CT.dmS2D = function (Degrees, Minutes, Seconds) { + return CT.dmS2Dp(Degrees, Minutes, Seconds, true); +}; + +CT.dmS2Dp = function (Degrees, Minutes, Seconds, bPositive) { + if (!bPositive) { + console.assert(Degrees >= 0); + console.assert(Minutes >= 0); + console.assert(Seconds >= 0); + } + if (bPositive) { + return Degrees + Minutes / 60 + Seconds / 3600; + } + else { + return -Degrees - Minutes / 60 - Seconds / 3600; + } +}; + +var CT$ = {}; + +registerType("CT", [CT, CT$, null]); diff --git a/engine/esm/astrocalc/date.js b/engine/esm/astrocalc/date.js new file mode 100644 index 00000000..6acae8df --- /dev/null +++ b/engine/esm/astrocalc/date.js @@ -0,0 +1,301 @@ +// Originally `AADATE.CPP` +// "Purpose: Implementation for the algorithms which convert between the +// Gregorian and Julian calendars and the Julian Day" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; + + +// CalD + +export function CalD() { + this.year = 0; + this.month = 0; + this.day = 0; + this.year = 0; + this.month = 0; + this.day = 0; +} + +CalD.create = function (year, month, day) { + var item = new CalD(); + item.year = year; + item.month = month; + item.day = day; + return item; +}; + +var CalD$ = {}; + +registerType("CalD", [CalD, CalD$, null]); + + +// DAY_OF_WEEK + +export var DAY_OF_WEEK = { + SUNDAY: 0, + MONDAY: 1, + TUESDAY: 2, + WEDNESDAY: 3, + THURSDAY: 4, + FRIDAY: 5, + SATURDAY: 6 +}; + +registerType("DAY_OF_WEEK", DAY_OF_WEEK); + + +// DT + +export function DT() { + this.m_dblJulian = 0; + this.m_bGregorianCalendar = false; + this.m_dblJulian = 0; + this.m_bGregorianCalendar = false; +} + +DT.create = function (Year, Month, Day, bGregorianCalendar) { + var item = new DT(); + item.set(Year, Month, Day, 0, 0, 0, bGregorianCalendar); + return item; +}; + +DT.createHMS = function (Year, Month, Day, Hour, Minute, Second, bGregorianCalendar) { + var item = new DT(); + item.set(Year, Month, Day, Hour, Minute, Second, bGregorianCalendar); + return item; +}; + +DT.createJD = function (JD, bGregorianCalendar) { + var item = new DT(); + item.setJD(JD, bGregorianCalendar); + return item; +}; + +DT.dateToJD = function (Year, Month, Day, bGregorianCalendar) { + var Y = Year; + var M = Month; + if (M < 3) { + Y = Y - 1; + M = M + 12; + } + var A = 0; + var B = 0; + if (bGregorianCalendar) { + A = ss.truncate((Y / 100)); + B = 2 - A + ss.truncate((A / 4)); + } + return ss.truncate((365.25 * (Y + 4716))) + ss.truncate((30.6001 * (M + 1))) + Day + B - 1524.5; +}; + +DT.isLeap = function (Year, bGregorianCalendar) { + if (bGregorianCalendar) { + if (!(Year % 100)) { + return (!(Year % 400)) ? true : false; + } + else { + return (!(Year % 4)) ? true : false; + } + } + else { + return (!(Year % 4)) ? true : false; + } +}; + +DT.afterPapalReform = function (Year, Month, Day) { + return ((Year > 1582) || ((Year === 1582) && (Month > 10)) || ((Year === 1582) && (Month === 10) && (Day >= 15))); +}; + +DT.afterPapalReformJD = function (JD) { + return (JD >= 2299160.5); +}; + +DT.dayOfYearJD = function (JD, Year, bGregorianCalendar) { + return JD - DT.dateToJD(Year, 1, 1, bGregorianCalendar) + 1; +}; + +DT.daysInMonthForMonth = function (Month, bLeap) { + console.assert(Month >= 1 && Month <= 12); + var MonthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]; + if (bLeap) { + MonthLength[1]++; + } + return MonthLength[Month - 1]; +}; + +DT.INT = function (vvalue) { + if (vvalue >= 0) { + return ss.truncate(vvalue); + } + else { + return ss.truncate((vvalue - 1)); + } +}; + +var DT$ = { + julian: function () { + return this.m_dblJulian; + }, + + day: function () { + var D = this.get(); + return ss.truncate(D[2]); + }, + + month: function () { + var D = this.get(); + return ss.truncate(D[1]); + }, + + year: function () { + var D = this.get(); + return ss.truncate(D[0]); + }, + + hour: function () { + var D = this.get(); + return ss.truncate(D[3]); + }, + + minute: function () { + var D = this.get(); + return ss.truncate(D[4]); + }, + + second: function () { + var D = this.get(); + return ss.truncate(D[5]); + }, + + set: function (Year, Month, Day, Hour, Minute, Second, bGregorianCalendar) { + var dblDay = Day + (Hour / 24) + (Minute / 1440) + (Second / 86400); + this.setJD(DT.dateToJD(Year, Month, dblDay, bGregorianCalendar), bGregorianCalendar); + }, + + setJD: function (JD, bGregorianCalendar) { + this.m_dblJulian = JD; + this.setInGregorianCalendar(bGregorianCalendar); + }, + + setInGregorianCalendar: function (bGregorianCalendar) { + var bAfterPapalReform = (this.m_dblJulian >= 2299160.5); + this.m_bGregorianCalendar = bGregorianCalendar && bAfterPapalReform; + }, + + get: function () { + var Year; + var Month; + var Day; + var Hour; + var Minute; + var Second; + var JD = this.m_dblJulian + 0.5; + var tempZ = Math.floor(JD); + var F = JD - tempZ; + var Z = ss.truncate(tempZ); + var A; + if (this.m_bGregorianCalendar) { + var alpha = ss.truncate(((Z - 1867216.25) / 36524.25)); + A = Z + 1 + alpha - ss.truncate((alpha / 4)); + } + else { + A = Z; + } + var B = A + 1524; + var C = ss.truncate(((B - 122.1) / 365.25)); + var D = ss.truncate((365.25 * C)); + var E = ss.truncate(((B - D) / 30.6001)); + var dblDay = B - D - ss.truncate((30.6001 * E)) + F; + Day = ss.truncate(dblDay); + if (E < 14) { + Month = E - 1; + } + else { + Month = E - 13; + } + if (Month > 2) { + Year = C - 4716; + } + else { + Year = C - 4715; + } + tempZ = Math.floor(dblDay); + F = dblDay - tempZ; + Hour = ss.truncate((F * 24)); + Minute = ss.truncate(((F - Hour / 24) * 1440)); + Second = (F - (Hour / 24) - (Minute / 1440)) * 86400; + return [Year, Month, Day, Hour, Minute, Second]; + }, + + dayOfWeek: function () { + return (ss.truncate((this.m_dblJulian + 1.5)) % 7); + }, + + dayOfYear: function () { + var year = ss.truncate(this.get()[0]); + return DT.dayOfYearJD(this.m_dblJulian, year, DT.afterPapalReform(year, 1, 1)); + }, + + daysInMonth: function () { + var D = this.get(); + var Year = ss.truncate(D[0]); + var Month = ss.truncate(D[1]); + return DT.daysInMonthForMonth(Month, DT.isLeap(Year, this.m_bGregorianCalendar)); + }, + + daysInYear: function () { + var D = this.get(); + var Year = ss.truncate(D[0]); + if (DT.isLeap(Year, this.m_bGregorianCalendar)) { + return 366; + } + else { + return 365; + } + }, + + leap: function () { + return DT.isLeap(this.year(), this.m_bGregorianCalendar); + }, + + inGregorianCalendar: function () { + return this.m_bGregorianCalendar; + }, + + fractionalYear: function () { + var D = this.get(); + var Year = ss.truncate(D[0]); + var Month = ss.truncate(D[1]); + var Day = ss.truncate(D[2]); + var Hour = ss.truncate(D[3]); + var Minute = ss.truncate(D[4]); + var Second = D[5]; + var DaysInYear; + if (DT.isLeap(Year, this.m_bGregorianCalendar)) { + DaysInYear = 366; + } + else { + DaysInYear = 365; + } + return Year + ((this.m_dblJulian - DT.dateToJD(Year, 1, 1, DT.afterPapalReform(Year, 1, 1))) / DaysInYear); + } +}; + +registerType("DT", [DT, DT$, null]); diff --git a/engine/esm/astrocalc/dynamical_time.js b/engine/esm/astrocalc/dynamical_time.js new file mode 100644 index 00000000..e472bdb4 --- /dev/null +++ b/engine/esm/astrocalc/dynamical_time.js @@ -0,0 +1,68 @@ +// Originally `AADYNAMICALTIME.CPP` +// "Purpose: Implementation for the algorithms which calculate the difference between Dynamical Time and Universal Time" +// Last update of original: PJN / 28-01-2007 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { DT } from "./date.js"; + + +// Constants + +const deltaTTable = [121, 112, 103, 95, 88, 82, 77, 72, 68, 63, 60, 56, 53, 51, 48, 46, 44, 42, 40, 38, 35, 33, 31, 29, 26, 24, 22, 20, 18, 16, 14, 12, 11, 10, 9, 8, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 14, 13, 13.1, 12.5, 12.2, 12, 12, 12, 12, 12, 12, 11.9, 11.6, 11, 10.2, 9.2, 8.2, 7.1, 6.2, 5.6, 5.4, 5.3, 5.4, 5.6, 5.9, 6.2, 6.5, 6.8, 7.1, 7.3, 7.5, 7.6, 7.7, 7.3, 6.2, 5.2, 2.7, 1.4, -1.2, -2.8, -3.8, -4.8, -5.5, -5.3, -5.6, -5.7, -5.9, -6, -6.3, -6.5, -6.2, -4.7, -2.8, -0.1, 2.6, 5.3, 7.7, 10.4, 13.3, 16, 18.2, 20.2, 21.2, 22.4, 23.5, 23.8, 24.3, 24, 23.9, 23.9, 23.7, 24, 24.3, 25.3, 26.2, 27.3, 28.2, 29.1, 30, 30.7, 31.4, 32.2, 33.1, 34, 35, 36.5, 38.3, 40.18, 42.2, 44.5, 46.5, 48.5, 50.54, 52.2, 53.8, 54.9, 55.8, 56.86, 58.31, 59.99, 61.63, 62.97]; + + +// DYT - was CAADynamicalTime + +export function DYT() { } + +DYT.deltaT = function (JD) { + var date = DT.createJD(JD, DT.afterPapalReformJD(JD)); + var y = date.fractionalYear(); + var T = (y - 2000) / 100; + var Delta; + if (y < 948) { + Delta = 2177 + (497 * T) + (44.1 * T * T); + } + else if (y < 1620) { + Delta = 102 + (102 * T) + (25.3 * T * T); + } + else if (y < 1998) { + var Index = ss.truncate(((y - 1620) / 2)); + console.assert(Index < deltaTTable.length); + y = y / 2 - Index - 810; + Delta = (deltaTTable[Index] + (deltaTTable[Index + 1] - deltaTTable[Index]) * y); + } + else if (y <= 2000) { + var nLookupSize = deltaTTable.length; + Delta = deltaTTable[nLookupSize - 1]; + } + else if (y < 2100) { + Delta = 102 + (102 * T) + (25.3 * T * T) + 0.37 * (y - 2100); + } + else { + Delta = 102 + (102 * T) + (25.3 * T * T); + } + return Delta; +}; + +var DYT$ = {}; + +registerType("DYT", [DYT, DYT$, null]); diff --git a/engine/esm/astrocalc/earth.js b/engine/esm/astrocalc/earth.js new file mode 100644 index 00000000..1d680e32 --- /dev/null +++ b/engine/esm/astrocalc/earth.js @@ -0,0 +1,272 @@ +// Originally `AAEARTH.CPP` +// "Purpose: Implementation for the algorithms which calculate the position of Earth" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// VSC + +export function VSC(a, b, c) { + this.a = 0; + this.b = 0; + this.c = 0; + this.a = a; + this.b = b; + this.c = c; +} + +var VSC$ = {}; + +registerType("VSC", [VSC, VSC$, null]); + + +// Coefficients + +const g_L0EarthCoefficients = [new VSC(175347046, 0, 0), new VSC(3341656, 4.6692568, 6283.07585), new VSC(34894, 4.6261, 12566.1517), new VSC(3497, 2.7441, 5753.3849), new VSC(3418, 2.8289, 3.5231), new VSC(3136, 3.6277, 77713.7715), new VSC(2676, 4.4181, 7860.4194), new VSC(2343, 6.1352, 3930.2097), new VSC(1324, 0.7425, 11506.7698), new VSC(1273, 2.0371, 529.691), new VSC(1199, 1.1096, 1577.3435), new VSC(990, 5.233, 5884.927), new VSC(902, 2.045, 26.298), new VSC(857, 3.508, 398.149), new VSC(780, 1.179, 5223.694), new VSC(753, 2.533, 5507.553), new VSC(505, 4.583, 18849.228), new VSC(492, 4.205, 775.523), new VSC(357, 2.92, 0.067), new VSC(317, 5.849, 11790.629), new VSC(284, 1.899, 796.288), new VSC(271, 0.315, 10977.079), new VSC(243, 0.345, 5486.778), new VSC(206, 4.806, 2544.314), new VSC(205, 1.869, 5573.143), new VSC(202, 2.458, 6069.777), new VSC(156, 0.833, 213.299), new VSC(132, 3.411, 2942.463), new VSC(126, 1.083, 20.775), new VSC(115, 0.645, 0.98), new VSC(103, 0.636, 4694.003), new VSC(102, 0.976, 15720.839), new VSC(102, 4.267, 7.114), new VSC(99, 6.21, 2146.17), new VSC(98, 0.68, 155.42), new VSC(86, 5.98, 161000.69), new VSC(85, 1.3, 6275.96), new VSC(85, 3.67, 71430.7), new VSC(80, 1.81, 17260.15), new VSC(79, 3.04, 12036.46), new VSC(75, 1.76, 5088.63), new VSC(74, 3.5, 3154.69), new VSC(74, 4.68, 801.82), new VSC(70, 0.83, 9437.76), new VSC(62, 3.98, 8827.39), new VSC(61, 1.82, 7084.9), new VSC(57, 2.78, 6286.6), new VSC(56, 4.39, 14143.5), new VSC(56, 3.47, 6279.55), new VSC(52, 0.19, 12139.55), new VSC(52, 1.33, 1748.02), new VSC(51, 0.28, 5856.48), new VSC(49, 0.49, 1194.45), new VSC(41, 5.37, 8429.24), new VSC(41, 2.4, 19651.05), new VSC(39, 6.17, 10447.39), new VSC(37, 6.04, 10213.29), new VSC(37, 2.57, 1059.38), new VSC(36, 1.71, 2352.87), new VSC(36, 1.78, 6812.77), new VSC(33, 0.59, 17789.85), new VSC(30, 0.44, 83996.85), new VSC(30, 2.74, 1349.87), new VSC(25, 3.16, 4690.48)]; +const g_L1EarthCoefficients = [new VSC(628331966747, 0, 0), new VSC(206059, 2.678235, 6283.07585), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.59, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.4, 796.3), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.3), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694), new VSC(11, 0.77, 553.57), new VSC(10, 1.3, 6286.6), new VSC(10, 4.24, 1349.87), new VSC(9, 2.7, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.3, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48)]; +const g_L2EarthCoefficients = [new VSC(52919, 0, 0), new VSC(8720, 1.0721, 6283.0758), new VSC(309, 0.867, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.3), new VSC(16, 3.68, 155.42), new VSC(10, 0.76, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.3), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.31, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98)]; +const g_L3EarthCoefficients = [new VSC(289, 5.844, 6283.076), new VSC(35, 0, 0), new VSC(17, 5.49, 12566.15), new VSC(3, 5.2, 155.42), new VSC(1, 4.72, 3.52), new VSC(1, 5.3, 18849.23), new VSC(1, 5.97, 242.73)]; +const g_L4EarthCoefficients = [new VSC(114, 3.142, 0), new VSC(8, 4.13, 6283.08), new VSC(1, 3.84, 12566.15)]; +const g_L5EarthCoefficients = [new VSC(1, 3.14, 0)]; +const g_B0EarthCoefficients = [new VSC(280, 3.199, 84334.662), new VSC(102, 5.422, 5507.553), new VSC(80, 3.88, 5223.69), new VSC(44, 3.7, 2352.87), new VSC(32, 4, 1577.34)]; +const g_B1EarthCoefficients = [new VSC(9, 3.9, 5507.55), new VSC(6, 1.73, 5223.69)]; +const g_B2EarthCoefficients = [new VSC(22378, 3.38509, 10213.28555), new VSC(282, 0, 0), new VSC(173, 5.256, 20426.571), new VSC(27, 3.87, 30639.86)]; +const g_B3EarthCoefficients = [new VSC(647, 4.992, 10213.286), new VSC(20, 3.14, 0), new VSC(6, 0.77, 20426.57), new VSC(3, 5.44, 30639.86)]; +const g_B4EarthCoefficients = [new VSC(14, 0.32, 10213.29)]; +const g_R0EarthCoefficients = [new VSC(100013989, 0, 0), new VSC(1670700, 3.0984635, 6283.07585), new VSC(13956, 3.05525, 12566.1517), new VSC(3084, 5.1985, 77713.7715), new VSC(1628, 1.1739, 5753.3849), new VSC(1576, 2.8469, 7860.4194), new VSC(925, 5.453, 11506.77), new VSC(542, 4.564, 3930.21), new VSC(472, 3.661, 5884.927), new VSC(346, 0.964, 5507.553), new VSC(329, 5.9, 5223.694), new VSC(307, 0.299, 5573.143), new VSC(243, 4.273, 11790.629), new VSC(212, 5.847, 1577.344), new VSC(186, 5.022, 10977.079), new VSC(175, 3.012, 18849.228), new VSC(110, 5.055, 5486.778), new VSC(98, 0.89, 6069.78), new VSC(86, 5.69, 15720.84), new VSC(86, 1.27, 161000.69), new VSC(65, 0.27, 17260.15), new VSC(63, 0.92, 529.69), new VSC(57, 2.01, 83996.85), new VSC(56, 5.24, 71430.7), new VSC(49, 3.25, 2544.31), new VSC(47, 2.58, 775.52), new VSC(45, 5.54, 9437.76), new VSC(43, 6.01, 6275.96), new VSC(39, 5.36, 4694), new VSC(38, 2.39, 8827.39), new VSC(37, 0.83, 19651.05), new VSC(37, 4.9, 12139.55), new VSC(36, 1.67, 12036.46), new VSC(35, 1.84, 2942.46), new VSC(33, 0.24, 7084.9), new VSC(32, 0.18, 5088.63), new VSC(32, 1.78, 398.15), new VSC(28, 1.21, 6286.6), new VSC(28, 1.9, 6279.55), new VSC(26, 4.59, 10447.39)]; +const g_R1EarthCoefficients = [new VSC(103019, 1.10749, 6283.07585), new VSC(1721, 1.0644, 12566.1517), new VSC(702, 3.142, 0), new VSC(32, 1.02, 18849.23), new VSC(31, 2.84, 5507.55), new VSC(25, 1.32, 5223.69), new VSC(18, 1.42, 1577.34), new VSC(10, 5.91, 10977.08), new VSC(9, 1.42, 6275.96), new VSC(9, 0.27, 5486.78)]; +const g_R2EarthCoefficients = [new VSC(4359, 5.7846, 6283.0758), new VSC(124, 5.579, 12566.152), new VSC(12, 3.14, 0), new VSC(9, 3.63, 77713.77), new VSC(6, 1.87, 5573.14), new VSC(3, 5.47, 18849.23)]; +const g_R3EarthCoefficients = [new VSC(145, 4.273, 6283.076), new VSC(7, 3.92, 12566.15)]; +const g_R4EarthCoefficients = [new VSC(4, 2.56, 6283.08)]; +const g_L1EarthCoefficientsJ2000 = [new VSC(628307584999, 0, 0), new VSC(206059, 2.678235, 6283.07585), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.59, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.4, 796.3), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.3), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694), new VSC(11, 0.77, 553.57), new VSC(10, 1.3, 6286.6), new VSC(10, 4.24, 1349.87), new VSC(9, 2.7, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.3, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48)]; +const g_L2EarthCoefficientsJ2000 = [new VSC(8722, 1.0725, 6283.0758), new VSC(991, 3.1416, 0), new VSC(295, 0.437, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.3), new VSC(16, 3.69, 155.42), new VSC(9, 0.3, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.3), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.3, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98)]; +const g_L3EarthCoefficientsJ2000 = [new VSC(289, 5.842, 6283.076), new VSC(21, 6.05, 12566.15), new VSC(3, 5.2, 155.42), new VSC(3, 3.14, 0), new VSC(1, 4.72, 3.52), new VSC(1, 5.97, 242.73), new VSC(1, 5.54, 18849.23)]; +const g_L4EarthCoefficientsJ2000 = [new VSC(8, 4.14, 6283.08), new VSC(1, 3.28, 12566.15)]; +const g_B1EarthCoefficientsJ2000 = [new VSC(227778, 3.413766, 6283.07585), new VSC(3806, 3.3706, 12566.1517), new VSC(3620, 0, 0), new VSC(72, 3.33, 18849.23), new VSC(8, 3.89, 5507.55), new VSC(8, 1.79, 5223.69), new VSC(6, 5.2, 2352.87)]; +const g_B2EarthCoefficientsJ2000 = [new VSC(9721, 5.1519, 6283.07585), new VSC(233, 3.1416, 0), new VSC(134, 0.644, 12566.152), new VSC(7, 1.07, 18849.23)]; +const g_B3EarthCoefficientsJ2000 = [new VSC(276, 0.595, 6283.076), new VSC(17, 3.14, 0), new VSC(4, 0.12, 12566.15)]; +const g_B4EarthCoefficientsJ2000 = [new VSC(6, 2.27, 6283.08), new VSC(1, 0, 0)]; + + +// CAAEarth + +export function CAAEarth() { } + +CAAEarth.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0EarthCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0EarthCoefficients[i].a * Math.cos(g_L0EarthCoefficients[i].b + g_L0EarthCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1EarthCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1EarthCoefficients[i].a * Math.cos(g_L1EarthCoefficients[i].b + g_L1EarthCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2EarthCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2EarthCoefficients[i].a * Math.cos(g_L2EarthCoefficients[i].b + g_L2EarthCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3EarthCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3EarthCoefficients[i].a * Math.cos(g_L3EarthCoefficients[i].b + g_L3EarthCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4EarthCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4EarthCoefficients[i].a * Math.cos(g_L4EarthCoefficients[i].b + g_L4EarthCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5EarthCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5EarthCoefficients[i].a * Math.cos(g_L5EarthCoefficients[i].b + g_L5EarthCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAEarth.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0EarthCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0EarthCoefficients[i].a * Math.cos(g_B0EarthCoefficients[i].b + g_B0EarthCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1EarthCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1EarthCoefficients[i].a * Math.cos(g_B1EarthCoefficients[i].b + g_B1EarthCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2EarthCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2EarthCoefficients[i].a * Math.cos(g_B2EarthCoefficients[i].b + g_B2EarthCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3EarthCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3EarthCoefficients[i].a * Math.cos(g_B3EarthCoefficients[i].b + g_B3EarthCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4EarthCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4EarthCoefficients[i].a * Math.cos(g_B4EarthCoefficients[i].b + g_B4EarthCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAEarth.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nR0Coefficients = g_R0EarthCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0EarthCoefficients[i].a * Math.cos(g_R0EarthCoefficients[i].b + g_R0EarthCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1EarthCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1EarthCoefficients[i].a * Math.cos(g_R1EarthCoefficients[i].b + g_R1EarthCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2EarthCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2EarthCoefficients[i].a * Math.cos(g_R2EarthCoefficients[i].b + g_R2EarthCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3EarthCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3EarthCoefficients[i].a * Math.cos(g_R3EarthCoefficients[i].b + g_R3EarthCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4EarthCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4EarthCoefficients[i].a * Math.cos(g_R4EarthCoefficients[i].b + g_R4EarthCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; +}; + +CAAEarth.sunMeanAnomaly = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(357.5291092 + 35999.0502909 * T - 0.0001536 * Tsquared + Tcubed / 24490000); +}; + +CAAEarth.eccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return 1 - 0.002516 * T - 7.4E-06 * Tsquared; +}; + +CAAEarth.eclipticLongitudeJ2000 = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nL0Coefficients = g_L0EarthCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0EarthCoefficients[i].a * Math.cos(g_L0EarthCoefficients[i].b + g_L0EarthCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1EarthCoefficientsJ2000.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1EarthCoefficientsJ2000[i].a * Math.cos(g_L1EarthCoefficientsJ2000[i].b + g_L1EarthCoefficientsJ2000[i].c * rho); + } + var nL2Coefficients = g_L2EarthCoefficientsJ2000.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2EarthCoefficientsJ2000[i].a * Math.cos(g_L2EarthCoefficientsJ2000[i].b + g_L2EarthCoefficientsJ2000[i].c * rho); + } + var nL3Coefficients = g_L3EarthCoefficientsJ2000.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3EarthCoefficientsJ2000[i].a * Math.cos(g_L3EarthCoefficientsJ2000[i].b + g_L3EarthCoefficientsJ2000[i].c * rho); + } + var nL4Coefficients = g_L4EarthCoefficientsJ2000.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4EarthCoefficientsJ2000[i].a * Math.cos(g_L4EarthCoefficientsJ2000[i].b + g_L4EarthCoefficientsJ2000[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAEarth.eclipticLatitudeJ2000 = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0EarthCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0EarthCoefficients[i].a * Math.cos(g_B0EarthCoefficients[i].b + g_B0EarthCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1EarthCoefficientsJ2000.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1EarthCoefficientsJ2000[i].a * Math.cos(g_B1EarthCoefficientsJ2000[i].b + g_B1EarthCoefficientsJ2000[i].c * rho); + } + var nB2Coefficients = g_B2EarthCoefficientsJ2000.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2EarthCoefficientsJ2000[i].a * Math.cos(g_B2EarthCoefficientsJ2000[i].b + g_B2EarthCoefficientsJ2000[i].c * rho); + } + var nB3Coefficients = g_B3EarthCoefficientsJ2000.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3EarthCoefficientsJ2000[i].a * Math.cos(g_B3EarthCoefficientsJ2000[i].b + g_B3EarthCoefficientsJ2000[i].c * rho); + } + var nB4Coefficients = g_B4EarthCoefficientsJ2000.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4EarthCoefficientsJ2000[i].a * Math.cos(g_B4EarthCoefficientsJ2000[i].b + g_B4EarthCoefficientsJ2000[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +var CAAEarth$ = {}; + +registerType("CAAEarth", [CAAEarth, CAAEarth$, null]); diff --git a/engine/esm/astrocalc/ecliptical_elements.js b/engine/esm/astrocalc/ecliptical_elements.js new file mode 100644 index 00000000..7a9e1a01 --- /dev/null +++ b/engine/esm/astrocalc/ecliptical_elements.js @@ -0,0 +1,111 @@ +// Originally `AAECLIPTICALELEMENTS.CPP` +// "Purpose: Implementation for the algorithms which map the ecliptical elements from one equinox to another" +// Last update of original: PJN / 29-11-2006 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// CAAEclipticalElementDetails + +export function CAAEclipticalElementDetails() { + this.i = 0; + this.w = 0; + this.omega = 0; + this.i = 0; + this.w = 0; + this.omega = 0; +} + +var CAAEclipticalElementDetails$ = {}; + +registerType("CAAEclipticalElementDetails", [CAAEclipticalElementDetails, CAAEclipticalElementDetails$, null]); + + +// CAAEclipticalElements + +export function CAAEclipticalElements() { } + +CAAEclipticalElements.calculate = function (i0, w0, omega0, JD0, JD) { + var T = (JD0 - 2451545) / 36525; + var Tsquared = T * T; + var t = (JD - JD0) / 36525; + var tsquared = t * t; + var tcubed = tsquared * t; + var i0rad = CT.d2R(i0); + var omega0rad = CT.d2R(omega0); + var eta = (47.0029 - 0.06603 * T + 0.000598 * Tsquared) * t + (-0.03302 + 0.000598 * T) * tsquared + 6E-05 * tcubed; + eta = CT.d2R(CT.dmS2D(0, 0, eta)); + var pi = 174.876384 * 3600 + 3289.4789 * T + 0.60622 * Tsquared - (869.8089 + 0.50491 * T) * t + 0.03536 * tsquared; + pi = CT.d2R(CT.dmS2D(0, 0, pi)); + var p = (5029.0966 + 2.22226 * T - 4.2E-05 * Tsquared) * t + (1.11113 - 4.2E-05 * T) * tsquared - 6E-06 * tcubed; + p = CT.d2R(CT.dmS2D(0, 0, p)); + var sini0rad = Math.sin(i0rad); + var cosi0rad = Math.cos(i0rad); + var sinomega0rad_pi = Math.sin(omega0rad - pi); + var cosomega0rad_pi = Math.cos(omega0rad - pi); + var sineta = Math.sin(eta); + var coseta = Math.cos(eta); + var A = sini0rad * sinomega0rad_pi; + var B = -sineta * cosi0rad + coseta * sini0rad * cosomega0rad_pi; + var irad = Math.asin(Math.sqrt(A * A + B * B)); + var details = new CAAEclipticalElementDetails(); + details.i = CT.r2D(irad); + var cosi = cosi0rad * coseta + sini0rad * sineta * cosomega0rad_pi; + if (cosi < 0) { + details.i = 180 - details.i; + } + var phi = pi + p; + details.omega = CT.m360(CT.r2D(Math.atan2(A, B) + phi)); + A = -sineta * sinomega0rad_pi; + B = sini0rad * coseta - cosi0rad * sineta * cosomega0rad_pi; + var deltaw = CT.r2D(Math.atan2(A, B)); + details.w = CT.m360(w0 + deltaw); + return details; +}; + +CAAEclipticalElements.fK4B1950ToFK5J2000 = function (i0, w0, omega0) { + var L = CT.d2R(5.19856209); + var J = CT.d2R(0.00651966); + var i0rad = CT.d2R(i0); + var omega0rad = CT.d2R(omega0); + var sini0rad = Math.sin(i0rad); + var cosi0rad = Math.cos(i0rad); + var cosJ = Math.cos(J); + var sinJ = Math.sin(J); + var W = L + omega0rad; + var cosW = Math.cos(W); + var sinW = Math.sin(W); + var A = sinJ * sinW; + var B = sini0rad * cosJ + cosi0rad * sinJ * cosW; + var details = new CAAEclipticalElementDetails(); + details.i = CT.r2D(Math.asin(Math.sqrt(A * A + B * B))); + var cosi = cosi0rad * cosJ - sini0rad * sinJ * cosW; + if (cosi < 0) { + details.i = 180 - details.i; + } + details.w = CT.m360(w0 + CT.r2D(Math.atan2(A, B))); + details.omega = CT.m360(CT.r2D(Math.atan2(sini0rad * sinW, cosi0rad * sinJ + sini0rad * cosJ * cosW)) - 4.50001688); + return details; +}; + +var CAAEclipticalElements$ = {}; + +registerType("CAAEclipticalElements", [CAAEclipticalElements, CAAEclipticalElements$, null]); diff --git a/engine/esm/astrocalc/elements_planetary_orbit.js b/engine/esm/astrocalc/elements_planetary_orbit.js new file mode 100644 index 00000000..4c8cd5ea --- /dev/null +++ b/engine/esm/astrocalc/elements_planetary_orbit.js @@ -0,0 +1,562 @@ +// Originally `AAELEMENTSPLANETARYORBIT.CPP` +// "Purpose: Implementation for the algorithms to calculate the elements of the planetary orbits" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// EPO - was CAAElementsPlanetaryOrbit + +export function EPO() { } + +EPO.mercuryMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(252.250906 + 149474.0722491 * T + 0.0003035 * Tsquared + 1.8E-08 * Tcubed); +}; + +EPO.mercurySemimajorAxis = function (UnnamedParameter1) { + return 0.38709831; +}; + +EPO.mercuryEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.20563175 + 2.0407E-05 * T - 2.83E-08 * Tsquared - 1.8E-10 * Tcubed; +}; + +EPO.mercuryInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(7.004986 + 0.0018215 * T - 1.81E-05 * Tsquared + 5.6E-08 * Tcubed); +}; + +EPO.mercuryLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(48.330893 + 1.1861883 * T + 0.00017542 * Tsquared + 2.15E-07 * Tcubed); +}; + +EPO.mercuryLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(77.456119 + 1.5564776 * T + 0.00029544 * Tsquared + 9E-09 * Tcubed); +}; + +EPO.venusMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(181.979801 + 58519.2130302 * T + 0.00031014 * Tsquared + 1.5E-08 * Tcubed); +}; + +EPO.venusSemimajorAxis = function (UnnamedParameter1) { + return 0.72332982; +}; + +EPO.venusEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.00677192 - 4.7765E-05 * T + 9.81E-08 * Tsquared + 4.6E-10 * Tcubed; +}; + +EPO.venusInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(3.394662 + 0.0010037 * T - 8.8E-07 * Tsquared - 7E-09 * Tcubed); +}; + +EPO.venusLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(76.67992 + 0.9011206 * T + 0.00040618 * Tsquared - 9.3E-08 * Tcubed); +}; + +EPO.venusLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(131.563703 + 1.4022288 * T - 0.00107618 * Tsquared - 5.678E-06 * Tcubed); +}; + +EPO.earthMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(100.466457 + 36000.7698278 * T + 0.00030322 * Tsquared + 2E-08 * Tcubed); +}; + +EPO.earthSemimajorAxis = function (UnnamedParameter1) { + return 1.000001018; +}; + +EPO.earthEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.01670863 - 4.2037E-05 * T - 1.267E-07 * Tsquared + 1.4E-10 * Tcubed; +}; + +EPO.earthInclination = function (UnnamedParameter1) { + return 0; +}; + +EPO.earthLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(102.937348 + 1.17195366 * T + 0.00045688 * Tsquared - 1.8E-08 * Tcubed); +}; + +EPO.marsMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(355.433 + 19141.6964471 * T + 0.00031052 * Tsquared + 1.6E-08 * Tcubed); +}; + +EPO.marsSemimajorAxis = function (UnnamedParameter1) { + return 1.523679342; +}; + +EPO.marsEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.09340065 + 9.0484E-05 * T - 8.06E-08 * Tsquared - 2.5E-10 * Tcubed; +}; + +EPO.marsInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(1.849726 - 0.0006011 * T + 1.276E-05 * Tsquared - 7E-09 * Tcubed); +}; + +EPO.marsLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(49.588093 + 0.7720959 * T + 1.557E-05 * Tsquared + 2.267E-06 * Tcubed); +}; + +EPO.marsLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(336.060234 + 1.8410449 * T + 0.00013477 * Tsquared + 5.36E-07 * Tcubed); +}; + +EPO.jupiterMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(34.351519 + 3036.3027748 * T + 0.0002233 * Tsquared + 3.7E-08 * Tcubed); +}; + +EPO.jupiterSemimajorAxis = function (JD) { + var T = (JD - 2451545) / 36525; + return 5.202603209 + 1.913E-07 * T; +}; + +EPO.jupiterEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.04849793 + 0.000163225 * T - 4.714E-07 * Tsquared - 2.01E-09 * Tcubed; +}; + +EPO.jupiterInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(1.303267 - 0.0054965 * T + 4.66E-06 * Tsquared - 2E-09 * Tcubed); +}; + +EPO.jupiterLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(100.464407 + 1.0209774 * T + 0.00040315 * Tsquared + 4.04E-07 * Tcubed); +}; + +EPO.jupiterLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(14.331207 + 1.6126352 * T + 0.00103042 * Tsquared - 4.464E-06 * Tcubed); +}; + +EPO.saturnMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(50.077444 + 1223.5110686 * T + 0.00051908 * Tsquared - 3E-08 * Tcubed); +}; + +EPO.saturnSemimajorAxis = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return 9.554909192 - 2.139E-06 * T + 4E-09 * Tsquared; +}; + +EPO.saturnEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.05554814 - 0.0003446641 * T - 6.436E-07 * Tsquared + 3.4E-09 * Tcubed; +}; + +EPO.saturnInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(2.488879 - 0.0037362 * T - 1.519E-05 * Tsquared + 8.7E-08 * Tcubed); +}; + +EPO.saturnLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(113.665503 + 0.877088 * T - 0.00012176 * Tsquared - 2.249E-06 * Tcubed); +}; + +EPO.saturnLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(93.057237 + 1.19637613 * T + 0.00083753 * Tsquared + 4.928E-06 * Tcubed); +}; + +EPO.uranusMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(314.055005 + 429.8640561 * T + 0.0003039 * Tsquared + 2.6E-08 * Tcubed); +}; + +EPO.uranusSemimajorAxis = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return 19.218446062 - 3.72E-08 * T + 9.8E-10 * Tsquared; +}; + +EPO.uranusEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.04638122 - 2.7293E-05 * T + 7.89E-08 * Tsquared + 2.4E-10 * Tcubed; +}; + +EPO.uranusInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(0.773197 + 0.0007744 * T + 3.749E-05 * Tsquared - 9.2E-08 * Tcubed); +}; + +EPO.uranusLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(74.005957 + 0.5211278 * T + 0.00133947 * Tsquared + 1.8484E-05 * Tcubed); +}; + +EPO.uranusLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(173.005291 + 1.486379 * T + 0.00021406 * Tsquared + 4.34E-07 * Tcubed); +}; + +EPO.neptuneMeanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(304.348665 + 219.8833092 * T + 0.00030882 * Tsquared + 1.8E-08 * Tcubed); +}; + +EPO.neptuneSemimajorAxis = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return 30.110386869 - 1.663E-07 * T + 6.9E-10 * Tsquared; +}; + +EPO.neptuneEccentricity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tcubed = T * T * T; + return 0.00945575 + 6.033E-06 * T - 5E-11 * Tcubed; +}; + +EPO.neptuneInclination = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(1.769953 - 0.0093082 * T - 7.08E-06 * Tsquared + 2.7E-08 * Tcubed); +}; + +EPO.neptuneLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(131.784057 + 1.1022039 * T + 0.00025952 * Tsquared - 6.37E-07 * Tcubed); +}; + +EPO.neptuneLongitudePerihelion = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(48.120276 + 1.4262957 * T + 0.00038434 * Tsquared + 2E-08 * Tcubed); +}; + +EPO.mercuryMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(252.250906 + 149472.6746358 * T - 5.36E-06 * Tsquared + 2E-09 * Tcubed); +}; + +EPO.mercuryInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(7.004986 - 0.0059516 * T + 8E-07 * Tsquared + 4.3E-08 * Tcubed); +}; + +EPO.mercuryLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(48.330893 - 0.1254227 * T - 8.833E-05 * Tsquared - 2E-07 * Tcubed); +}; + +EPO.mercuryLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(77.456119 + 0.1588643 * T - 1.342E-05 * Tsquared - 7E-09 * Tcubed); +}; + +EPO.venusMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(181.979801 + 58517.815676 * T + 1.65E-06 * Tsquared - 2E-09 * Tcubed); +}; + +EPO.venusInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(3.394662 - 0.0008568 * T - 3.244E-05 * Tsquared + 9E-09 * Tcubed); +}; + +EPO.venusLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(76.67992 - 0.2780134 * T - 0.00014257 * Tsquared - 1.64E-07 * Tcubed); +}; + +EPO.venusLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(131.563703 + 0.0048746 * T - 0.00138467 * Tsquared - 5.695E-06 * Tcubed); +}; + +EPO.earthMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(100.466457 + 35999.3728565 * T - 5.68E-06 * Tsquared - 1E-09 * Tcubed); +}; + +EPO.earthInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return 0.0130548 * T - 9.31E-06 * Tsquared - 3.4E-08 * Tcubed; +}; + +EPO.earthLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(174.873176 - 0.241098 * T + 4.262E-05 * Tsquared + 1E-09 * Tcubed); +}; + +EPO.earthLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(102.937348 + 0.3225654 * T + 0.00014799 * Tsquared - 3.9E-08 * Tcubed); +}; + +EPO.marsMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(355.433 + 19140.2993039 * T + 2.62E-06 * Tsquared - 3E-09 * Tcubed); +}; + +EPO.marsInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(1.849726 - 0.0081477 * T - 2.255E-05 * Tsquared - 2.9E-08 * Tcubed); +}; + +EPO.marsLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(49.588093 - 0.295025 * T - 0.00064048 * Tsquared - 1.964E-06 * Tcubed); +}; + +EPO.marsLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(336.060234 + 0.4439016 * T - 0.00017313 * Tsquared + 5.18E-07 * Tcubed); +}; + +EPO.jupiterMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(34.351519 + 3034.9056606 * T - 8.501E-05 * Tsquared + 1.6E-08 * Tcubed); +}; + +EPO.jupiterInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(1.303267 - 0.0019877 * T + 3.32E-05 * Tsquared + 9.7E-08 * Tcubed); +}; + +EPO.jupiterLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(100.464407 + 0.1767232 * T + 0.000907 * Tsquared - 7.272E-06 * Tcubed); +}; + +EPO.jupiterLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(14.331207 + 0.2155209 * T + 0.00072211 * Tsquared - 4.485E-06 * Tcubed); +}; + +EPO.saturnMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(50.077444 + 1222.1138488 * T + 0.00021004 * Tsquared - 4.6E-08 * Tcubed); +}; + +EPO.saturnInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(2.488879 + 0.0025514 * T - 4.906E-05 * Tsquared + 1.7E-08 * Tcubed); +}; + +EPO.saturnLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(113.665503 - 0.2566722 * T - 0.00018399 * Tsquared + 4.8E-07 * Tcubed); +}; + +EPO.saturnLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(93.057237 + 0.5665415 * T + 0.0005285 * Tsquared + 4.912E-06 * Tcubed); +}; + +EPO.uranusMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(314.055005 + 428.4669983 * T - 4.86E-06 * Tsquared + 6E-09 * Tcubed); +}; + +EPO.uranusInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(0.773197 - 0.0016869 * T + 3.49E-06 * Tsquared + 1.6E-08 * Tcubed); +}; + +EPO.uranusLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(74.005957 + 0.0741431 * T + 0.00040539 * Tsquared + 1.19E-07 * Tcubed); +}; + +EPO.uranusLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(173.005291 + 0.0893212 * T - 9.47E-05 * Tsquared + 4.14E-07 * Tcubed); +}; + +EPO.neptuneMeanLongitudeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(304.348665 + 218.4862002 * T + 5.9E-07 * Tsquared - 2E-09 * Tcubed); +}; + +EPO.neptuneInclinationJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return CT.m360(1.769953 + 0.0002256 * T + 2.3E-07 * Tsquared); +}; + +EPO.neptuneLongitudeAscendingNodeJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + return CT.m360(131.784057 - 0.0061651 * T - 2.19E-06 * Tsquared - 7.8E-08 * Tcubed); +}; + +EPO.neptuneLongitudePerihelionJ2000 = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + return CT.m360(48.120276 + 0.0291866 * T + 7.61E-05 * Tsquared); +}; + +var EPO$ = {}; + +registerType("EPO", [EPO, EPO$, null]); diff --git a/engine/esm/astrocalc/elliptical.js b/engine/esm/astrocalc/elliptical.js new file mode 100644 index 00000000..04941270 --- /dev/null +++ b/engine/esm/astrocalc/elliptical.js @@ -0,0 +1,490 @@ +// Originally `AAELLIPTICAL.CPP` +// "Purpose: Implementation for the algorithms for an elliptical orbit" +// Last update of original: PJN / 05-06-2006 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { C3D, CT } from "./coordinate_transformation.js"; +import { CAAEarth } from "./earth.js"; +import { CAAFK5 } from "./fk5.js"; +import { CAANutation } from "./nutation.js"; +import { CAASun } from "./sun.js"; +import { CAAMercury } from "./mercury.js"; +import { CAAVenus } from "./venus.js"; +import { CAAMars } from "./mars.js"; +import { CAAJupiter } from "./jupiter.js"; +import { CAASaturn } from "./saturn.js"; +import { CAAUranus } from "./uranus.js"; +import { CAANeptune } from "./neptune.js"; +import { CAAPluto } from "./pluto.js"; +import { ABR } from "./aberration.js"; +import { CAAKepler } from "./kepler.js"; +import { Vector3d } from "../double3d.js"; + + +// EOE - was CAAEllipticalObjectElements + +export function EOE() { + this.a = 0; + this.e = 0; + this.i = 0; + this.w = 0; + this.omega = 0; + this.jdEquinox = 0; + this.t = 0; + this.n = 0; + this.meanAnnomolyOut = 0; + this.a = 0; + this.e = 0; + this.i = 0; + this.w = 0; + this.omega = 0; + this.jdEquinox = 0; + this.t = 0; +} + +EOE._create = function (br) { + var tmp = new EOE(); + tmp.a = br.readSingle(); + tmp.e = br.readSingle(); + tmp.i = br.readSingle(); + tmp.w = br.readSingle(); + tmp.omega = br.readSingle(); + tmp.jdEquinox = br.readSingle(); + tmp.t = br.readSingle(); + return tmp; +}; + +var EOE$ = {}; + +registerType("EOE", [EOE, EOE$, null]); + + +// EPD - was CAAEllipticalPlanetaryDetails + +export function EPD() { + this.apparentGeocentricLongitude = 0; + this.apparentGeocentricLatitude = 0; + this.apparentGeocentricDistance = 0; + this.apparentLightTime = 0; + this.apparentGeocentricRA = 0; + this.apparentGeocentricDeclination = 0; + this.apparentGeocentricLongitude = 0; + this.apparentGeocentricLatitude = 0; + this.apparentGeocentricDistance = 0; + this.apparentLightTime = 0; + this.apparentGeocentricRA = 0; + this.apparentGeocentricDeclination = 0; +} + +var EPD$ = {}; + +registerType("EPD", [EPD, EPD$, null]); + + +// EOD - was CAAEllipticalObjectDetails + +export function EOD() { + this.heliocentricRectangularEquatorial = new C3D(); + this.heliocentricRectangularEcliptical = new C3D(); + this.heliocentricEclipticLongitude = 0; + this.heliocentricEclipticLatitude = 0; + this.trueGeocentricRA = 0; + this.trueGeocentricDeclination = 0; + this.trueGeocentricDistance = 0; + this.trueGeocentricLightTime = 0; + this.astrometricGeocenticRA = 0; + this.astrometricGeocentricDeclination = 0; + this.astrometricGeocentricDistance = 0; + this.astrometricGeocentricLightTime = 0; + this.elongation = 0; + this.phaseAngle = 0; + this.heliocentricEclipticLongitude = 0; + this.heliocentricEclipticLatitude = 0; + this.trueGeocentricRA = 0; + this.trueGeocentricDeclination = 0; + this.trueGeocentricDistance = 0; + this.trueGeocentricLightTime = 0; + this.astrometricGeocenticRA = 0; + this.astrometricGeocentricDeclination = 0; + this.astrometricGeocentricDistance = 0; + this.astrometricGeocentricLightTime = 0; + this.elongation = 0; + this.phaseAngle = 0; +} + +var EOD$ = {}; + +registerType("EOD", [EOD, EOD$, null]); + + +// EO - was EllipticalObject + +export var EO = { + SUN: 0, + MERCURY: 1, + VENUS: 2, + MARS: 3, + JUPITER: 4, + SATURN: 5, + URANUS: 6, + NEPTUNE: 7, + PLUTO: 8 +}; + +registerType("EO", EO); + + +// ELL - was CAAElliptical + +export function ELL() { } + +ELL.distanceToLightTime = function (Distance) { + return Distance * 0.0057755183; +}; + +ELL.calculate = function (JD, oobject) { + var details = new EPD(); + var JD0 = JD; + var L0 = 0; + var B0 = 0; + var R0 = 0; + var cosB0 = 0; + if (!!oobject) { + L0 = CAAEarth.eclipticLongitude(JD0); + B0 = CAAEarth.eclipticLatitude(JD0); + R0 = CAAEarth.radiusVector(JD0); + L0 = CT.d2R(L0); + B0 = CT.d2R(B0); + cosB0 = Math.cos(B0); + } + var L = 0; + var B = 0; + var R = 0; + var Lrad; + var Brad; + var cosB; + var cosL; + var x; + var y; + var z; + var bRecalc = true; + var bFirstRecalc = true; + var LPrevious = 0; + var BPrevious = 0; + var RPrevious = 0; + while (bRecalc) { + switch (oobject) { + case 0: + L = CAASun.geometricEclipticLongitude(JD0); + B = CAASun.geometricEclipticLatitude(JD0); + R = CAAEarth.radiusVector(JD0); + break; + case 1: + L = CAAMercury.eclipticLongitude(JD0); + B = CAAMercury.eclipticLatitude(JD0); + R = CAAMercury.radiusVector(JD0); + break; + case 2: + L = CAAVenus.eclipticLongitude(JD0); + B = CAAVenus.eclipticLatitude(JD0); + R = CAAVenus.radiusVector(JD0); + break; + case 3: + L = CAAMars.eclipticLongitude(JD0); + B = CAAMars.eclipticLatitude(JD0); + R = CAAMars.radiusVector(JD0); + break; + case 4: + L = CAAJupiter.eclipticLongitude(JD0); + B = CAAJupiter.eclipticLatitude(JD0); + R = CAAJupiter.radiusVector(JD0); + break; + case 5: + L = CAASaturn.eclipticLongitude(JD0); + B = CAASaturn.eclipticLatitude(JD0); + R = CAASaturn.radiusVector(JD0); + break; + case 6: + L = CAAUranus.eclipticLongitude(JD0); + B = CAAUranus.eclipticLatitude(JD0); + R = CAAUranus.radiusVector(JD0); + break; + case 7: + L = CAANeptune.eclipticLongitude(JD0); + B = CAANeptune.eclipticLatitude(JD0); + R = CAANeptune.radiusVector(JD0); + break; + case 8: + L = CAAPluto.eclipticLongitude(JD0); + B = CAAPluto.eclipticLatitude(JD0); + R = CAAPluto.radiusVector(JD0); + break; + default: + console.assert(false); + break; + } + if (!bFirstRecalc) { + bRecalc = ((Math.abs(L - LPrevious) > 1E-05) || (Math.abs(B - BPrevious) > 1E-05) || (Math.abs(R - RPrevious) > 1E-06)); + LPrevious = L; + BPrevious = B; + RPrevious = R; + } + else { + bFirstRecalc = false; + } + if (bRecalc) { + var distance = 0; + if (!!oobject) { + Lrad = CT.d2R(L); + Brad = CT.d2R(B); + cosB = Math.cos(Brad); + cosL = Math.cos(Lrad); + x = R * cosB * cosL - R0 * cosB0 * Math.cos(L0); + y = R * cosB * Math.sin(Lrad) - R0 * cosB0 * Math.sin(L0); + z = R * Math.sin(Brad) - R0 * Math.sin(B0); + distance = Math.sqrt(x * x + y * y + z * z); + } + else { + distance = R; + } + JD0 = JD - ELL.distanceToLightTime(distance); + } + } + Lrad = CT.d2R(L); + Brad = CT.d2R(B); + cosB = Math.cos(Brad); + cosL = Math.cos(Lrad); + x = R * cosB * cosL - R0 * cosB0 * Math.cos(L0); + y = R * cosB * Math.sin(Lrad) - R0 * cosB0 * Math.sin(L0); + z = R * Math.sin(Brad) - R0 * Math.sin(B0); + var x2 = x * x; + var y2 = y * y; + details.apparentGeocentricLatitude = CT.r2D(Math.atan2(z, Math.sqrt(x2 + y2))); + details.apparentGeocentricDistance = Math.sqrt(x2 + y2 + z * z); + details.apparentGeocentricLongitude = CT.m360(CT.r2D(Math.atan2(y, x))); + details.apparentLightTime = ELL.distanceToLightTime(details.apparentGeocentricDistance); + var Aberration = ABR.eclipticAberration(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, JD); + details.apparentGeocentricLongitude += Aberration.x; + details.apparentGeocentricLatitude += Aberration.y; + var DeltaLong = CAAFK5.correctionInLongitude(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, JD); + details.apparentGeocentricLatitude += CAAFK5.correctionInLatitude(details.apparentGeocentricLongitude, JD); + details.apparentGeocentricLongitude += DeltaLong; + var NutationInLongitude = CAANutation.nutationInLongitude(JD); + var Epsilon = CAANutation.trueObliquityOfEcliptic(JD); + details.apparentGeocentricLongitude += CT.dmS2D(0, 0, NutationInLongitude); + var ApparentEqu = CT.ec2Eq(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, Epsilon); + details.apparentGeocentricRA = ApparentEqu.x; + details.apparentGeocentricDeclination = ApparentEqu.y; + return details; +}; + +ELL.semiMajorAxisFromPerihelionDistance = function (q, e) { + return q / (1 - e); +}; + +ELL.meanMotionFromSemiMajorAxis = function (a) { + return 0.9856076686 / (a * Math.sqrt(a)); +}; + +ELL.calculateRectangularJD = function (JD, elements) { + var JD0 = JD; + var omega = CT.d2R(elements.omega); + var w = CT.d2R(elements.w); + var i = CT.d2R(elements.i); + var sinEpsilon = 0; + var cosEpsilon = 1; + var sinOmega = Math.sin(omega); + var cosOmega = Math.cos(omega); + var cosi = Math.cos(i); + var sini = Math.sin(i); + var F = cosOmega; + var G = sinOmega * cosEpsilon; + var H = sinOmega * sinEpsilon; + var P = -sinOmega * cosi; + var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; + var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; + var a = Math.sqrt(F * F + P * P); + var b = Math.sqrt(G * G + Q * Q); + var c = Math.sqrt(H * H + R * R); + var A = Math.atan2(F, P); + var B = Math.atan2(G, Q); + var C = Math.atan2(H, R); + var M = elements.n * (JD0 - elements.t); + elements.meanAnnomolyOut = M; + var E = CAAKepler.calculate(M, elements.e); + E = CT.d2R(E); + var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); + var r = elements.a * (1 - elements.e * Math.cos(E)); + var x = r * a * Math.sin(A + w + v); + var y = r * b * Math.sin(B + w + v); + var z = r * c * Math.sin(C + w + v); + return Vector3d.create(x, z, y); +}; + +ELL.calculateRectangular = function (elements, meanAnomoly) { + var omega = CT.d2R(elements.omega); + var w = CT.d2R(elements.w); + var i = CT.d2R(elements.i); + var sinEpsilon = 0; + var cosEpsilon = 1; + var sinOmega = Math.sin(omega); + var cosOmega = Math.cos(omega); + var cosi = Math.cos(i); + var sini = Math.sin(i); + var F = cosOmega; + var G = sinOmega * cosEpsilon; + var H = sinOmega * sinEpsilon; + var P = -sinOmega * cosi; + var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; + var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; + var a = Math.sqrt(F * F + P * P); + var b = Math.sqrt(G * G + Q * Q); + var c = Math.sqrt(H * H + R * R); + var A = Math.atan2(F, P); + var B = Math.atan2(G, Q); + var C = Math.atan2(H, R); + var n = elements.n; + var M = meanAnomoly; + var E = CAAKepler.calculate(M, elements.e); + E = CT.d2R(E); + var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); + var r = elements.a * (1 - elements.e * Math.cos(E)); + var x = r * a * Math.sin(A + w + v); + var y = r * b * Math.sin(B + w + v); + var z = r * c * Math.sin(C + w + v); + return Vector3d.create(x, z, y); +}; + +ELL.calculateElements = function (JD, elements) { + var Epsilon = CAANutation.meanObliquityOfEcliptic(elements.jdEquinox); + var JD0 = JD; + var details = new EOD(); + Epsilon = CT.d2R(Epsilon); + var omega = CT.d2R(elements.omega); + var w = CT.d2R(elements.w); + var i = CT.d2R(elements.i); + var sinEpsilon = Math.sin(Epsilon); + var cosEpsilon = Math.cos(Epsilon); + var sinOmega = Math.sin(omega); + var cosOmega = Math.cos(omega); + var cosi = Math.cos(i); + var sini = Math.sin(i); + var F = cosOmega; + var G = sinOmega * cosEpsilon; + var H = sinOmega * sinEpsilon; + var P = -sinOmega * cosi; + var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; + var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; + var a = Math.sqrt(F * F + P * P); + var b = Math.sqrt(G * G + Q * Q); + var c = Math.sqrt(H * H + R * R); + var A = Math.atan2(F, P); + var B = Math.atan2(G, Q); + var C = Math.atan2(H, R); + var n = ELL.meanMotionFromSemiMajorAxis(elements.a); + var SunCoord = CAASun.equatorialRectangularCoordinatesAnyEquinox(JD, elements.jdEquinox); + for (var j = 0; j < 2; j++) { + var M = n * (JD0 - elements.t); + var E = CAAKepler.calculate(M, elements.e); + E = CT.d2R(E); + var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); + var r = elements.a * (1 - elements.e * Math.cos(E)); + var x = r * a * Math.sin(A + w + v); + var y = r * b * Math.sin(B + w + v); + var z = r * c * Math.sin(C + w + v); + if (!j) { + details.heliocentricRectangularEquatorial.x = x; + details.heliocentricRectangularEquatorial.y = y; + details.heliocentricRectangularEquatorial.z = z; + var u = omega + v; + var cosu = Math.cos(u); + var sinu = Math.sin(u); + details.heliocentricRectangularEcliptical.x = r * (cosOmega * cosu - sinOmega * sinu * cosi); + details.heliocentricRectangularEcliptical.y = r * (sinOmega * cosu + cosOmega * sinu * cosi); + details.heliocentricRectangularEcliptical.z = r * sini * sinu; + details.heliocentricEclipticLongitude = Math.atan2(y, x); + details.heliocentricEclipticLongitude = CT.m24(CT.r2D(details.heliocentricEclipticLongitude) / 15); + details.heliocentricEclipticLatitude = Math.asin(z / r); + details.heliocentricEclipticLatitude = CT.r2D(details.heliocentricEclipticLatitude); + } + var psi = SunCoord.x + x; + var nu = SunCoord.y + y; + var sigma = SunCoord.z + z; + var Alpha = Math.atan2(nu, psi); + Alpha = CT.r2D(Alpha); + var Delta = Math.atan2(sigma, Math.sqrt(psi * psi + nu * nu)); + Delta = CT.r2D(Delta); + var Distance = Math.sqrt(psi * psi + nu * nu + sigma * sigma); + if (!j) { + details.trueGeocentricRA = CT.m24(Alpha / 15); + details.trueGeocentricDeclination = Delta; + details.trueGeocentricDistance = Distance; + details.trueGeocentricLightTime = ELL.distanceToLightTime(Distance); + } + else { + details.astrometricGeocenticRA = CT.m24(Alpha / 15); + details.astrometricGeocentricDeclination = Delta; + details.astrometricGeocentricDistance = Distance; + details.astrometricGeocentricLightTime = ELL.distanceToLightTime(Distance); + var RES = Math.sqrt(SunCoord.x * SunCoord.x + SunCoord.y * SunCoord.y + SunCoord.z * SunCoord.z); + details.elongation = Math.acos((RES * RES + Distance * Distance - r * r) / (2 * RES * Distance)); + details.elongation = CT.r2D(details.elongation); + details.phaseAngle = Math.acos((r * r + Distance * Distance - RES * RES) / (2 * r * Distance)); + details.phaseAngle = CT.r2D(details.phaseAngle); + } + if (!j) { + JD0 = JD - details.trueGeocentricLightTime; + } + } + return details; +}; + +ELL.instantaneousVelocity = function (r, a) { + return 42.1219 * Math.sqrt((1 / r) - (1 / (2 * a))); +}; + +ELL.velocityAtPerihelion = function (e, a) { + return 29.7847 / Math.sqrt(a) * Math.sqrt((1 + e) / (1 - e)); +}; + +ELL.velocityAtAphelion = function (e, a) { + return 29.7847 / Math.sqrt(a) * Math.sqrt((1 - e) / (1 + e)); +}; + +ELL.lengthOfEllipse = function (e, a) { + var b = a * Math.sqrt(1 - e * e); + return CT.PI() * (3 * (a + b) - Math.sqrt((a + 3 * b) * (3 * a + b))); +}; + +ELL.cometMagnitude = function (g, delta, k, r) { + return g + 5 * Util.log10(delta) + k * Util.log10(r); +}; + +ELL.minorPlanetMagnitude = function (H, delta, G, r, PhaseAngle) { + PhaseAngle = CT.d2R(PhaseAngle); + var phi1 = Math.exp(-3.33 * Math.pow(Math.tan(PhaseAngle / 2), 0.63)); + var phi2 = Math.exp(-1.87 * Math.pow(Math.tan(PhaseAngle / 2), 1.22)); + return H + 5 * Util.log10(r * delta) - 2.5 * Util.log10((1 - G) * phi1 + G * phi2); +}; + +var ELL$ = {}; + +registerType("ELL", [ELL, ELL$, null]); diff --git a/engine/esm/astrocalc/equation_of_time.js b/engine/esm/astrocalc/equation_of_time.js new file mode 100644 index 00000000..037ca094 --- /dev/null +++ b/engine/esm/astrocalc/equation_of_time.js @@ -0,0 +1,54 @@ +// Originally `AAEQUATIONOFTIME.CPP` +// "Purpose: Implementation for the algorithms to calculate the "Equation of Time"" +// Last update of original: PJN / 05-07-2005 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAANutation } from "./nutation.js"; +import { CAASun } from "./sun.js"; + + +// EOT + +export function EOT() { } + +EOT.calculate = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var L0 = CT.m360(280.4664567 + 360007.6982779 * rho + 0.03032028 * rhosquared + rhocubed / 49931 - rho4 / 15300 - rho5 / 2000000); + var SunLong = CAASun.apparentEclipticLongitude(JD); + var SunLat = CAASun.apparentEclipticLatitude(JD); + var epsilon = CAANutation.trueObliquityOfEcliptic(JD); + var Equatorial = CT.ec2Eq(SunLong, SunLat, epsilon); + epsilon = CT.d2R(epsilon); + var E = L0 - 0.0057183 - Equatorial.x * 15 + CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)) * Math.cos(epsilon); + if (E > 180) { + E = -(360 - E); + } + E *= 4; + return E; +}; + +var EOT$ = {}; + +registerType("EOT", [EOT, EOT$, null]); diff --git a/engine/esm/astrocalc/fk5.js b/engine/esm/astrocalc/fk5.js new file mode 100644 index 00000000..33b2cbd0 --- /dev/null +++ b/engine/esm/astrocalc/fk5.js @@ -0,0 +1,98 @@ +// Originally `AAFK5.CPP` +// "Purpose: Implementation for the algorithms to convert to the FK5 standard reference frame" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { C3D, CT } from "./coordinate_transformation.js"; + + +// CAAFK5 + +export function CAAFK5() { } + +CAAFK5.correctionInLongitude = function (Longitude, Latitude, JD) { + var T = (JD - 2451545) / 36525; + var Ldash = Longitude - 1.397 * T - 0.00031 * T * T; + Ldash = CT.d2R(Ldash); + Longitude = CT.d2R(Longitude); + Latitude = CT.d2R(Latitude); + var vvalue = -0.09033 + 0.03916 * (Math.cos(Ldash) + Math.sin(Ldash)) * Math.tan(Latitude); + return CT.dmS2D(0, 0, vvalue); +}; + +CAAFK5.correctionInLatitude = function (Longitude, JD) { + var T = (JD - 2451545) / 36525; + var Ldash = Longitude - 1.397 * T - 0.00031 * T * T; + Ldash = CT.d2R(Ldash); + Longitude = CT.d2R(Longitude); + var vvalue = 0.03916 * (Math.cos(Ldash) - Math.sin(Ldash)); + return CT.dmS2D(0, 0, vvalue); +}; + +CAAFK5.convertVSOPToFK5J2000 = function (vvalue) { + var result = new C3D(); + result.x = vvalue.x + 4.4036E-07 * vvalue.y - 1.90919E-07 * vvalue.z; + result.y = -4.79966E-07 * vvalue.x + 0.917482137087 * vvalue.y - 0.397776982902 * vvalue.z; + result.z = 0.397776982902 * vvalue.y + 0.917482137087 * vvalue.z; + return result; +}; + +CAAFK5.convertVSOPToFK5B1950 = function (vvalue) { + var result = new C3D(); + result.x = 0.999925702634 * vvalue.x + 0.012189716217 * vvalue.y + 1.1134016E-05 * vvalue.z; + result.y = -0.011179418036 * vvalue.x + 0.917413998946 * vvalue.y - 0.397777041885 * vvalue.z; + result.z = -0.004859003787 * vvalue.x + 0.397747363646 * vvalue.y + 0.917482111428 * vvalue.z; + return result; +}; + +CAAFK5.convertVSOPToFK5AnyEquinox = function (vvalue, JDEquinox) { + var t = (JDEquinox - 2451545) / 36525; + var tsquared = t * t; + var tcubed = tsquared * t; + var sigma = 2306.2181 * t + 0.30188 * tsquared + 0.017988 * tcubed; + sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); + var zeta = 2306.2181 * t + 1.09468 * tsquared + 0.018203 * tcubed; + zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); + var phi = 2004.3109 * t - 0.42665 * tsquared - 0.041833 * tcubed; + phi = CT.d2R(CT.dmS2D(0, 0, phi)); + var cossigma = Math.cos(sigma); + var coszeta = Math.cos(zeta); + var cosphi = Math.cos(phi); + var sinsigma = Math.sin(sigma); + var sinzeta = Math.sin(zeta); + var sinphi = Math.sin(phi); + var xx = cossigma * coszeta * cosphi - sinsigma * sinzeta; + var xy = sinsigma * coszeta + cossigma * sinzeta * cosphi; + var xz = cossigma * sinphi; + var yx = -cossigma * sinzeta - sinsigma * coszeta * cosphi; + var yy = cossigma * coszeta - sinsigma * sinzeta * cosphi; + var yz = -sinsigma * sinphi; + var zx = -coszeta * sinphi; + var zy = -sinzeta * sinphi; + var zz = cosphi; + var result = new C3D(); + result.x = xx * vvalue.x + yx * vvalue.y + zx * vvalue.z; + result.y = xy * vvalue.x + yy * vvalue.y + zy * vvalue.z; + result.z = xz * vvalue.x + yz * vvalue.y + zz * vvalue.z; + return result; +}; + +var CAAFK5$ = {}; + +registerType("CAAFK5", [CAAFK5, CAAFK5$, null]); diff --git a/engine/esm/astrocalc/galilean_moons.js b/engine/esm/astrocalc/galilean_moons.js new file mode 100644 index 00000000..97a3c4f8 --- /dev/null +++ b/engine/esm/astrocalc/galilean_moons.js @@ -0,0 +1,388 @@ +// Originally `AAGALILEANMOONS.CPP` +// "Purpose: Implementation for the algorithms which obtain the positions of the 4 great moons of Jupiter" +// Last update of original: PJN / 06-01-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { C3D, CT } from "./coordinate_transformation.js"; +import { CAASun } from "./sun.js"; +import { CAAEarth } from "./earth.js"; +import { CAAJupiter } from "./jupiter.js"; +import { ELL } from "./elliptical.js"; +import { EPO } from "./elements_planetary_orbit.js"; + + +// GMD - was CAAGalileanMoonDetail + +export function GMD() { + this.meanLongitude = 0; + this.trueLongitude = 0; + this.tropicalLongitude = 0; + this.equatorialLatitude = 0; + this.r = 0; + this.eclipticRectangularCoordinates = new C3D(); + this.trueRectangularCoordinates = new C3D(); + this.apparentRectangularCoordinates = new C3D(); + this.bInTransit = false; + this.bInOccultation = false; + this.bInEclipse = false; + this.bInShadowTransit = false; + this.apparentShadowRectangularCoordinates = new C3D(); + this.meanLongitude = 0; + this.trueLongitude = 0; + this.tropicalLongitude = 0; + this.equatorialLatitude = 0; + this.r = 0; + this.bInTransit = false; + this.bInOccultation = false; + this.bInEclipse = false; + this.bInShadowTransit = false; +} + +var GMD$ = {}; + +registerType("GMD", [GMD, GMD$, null]); + + +// GMDS - was CAAGalileanMoonsDetails + +export function GMDS() { + this.satellite1 = new GMD(); + this.satellite2 = new GMD(); + this.satellite3 = new GMD(); + this.satellite4 = new GMD(); +} + +var GMDS$ = {}; + +registerType("GMDS", [GMDS, GMDS$, null]); + + +// GM - was CAAGalileanMoons + +export function GM() { } + +GM.calculate = function (JD) { + var sunlong = CAASun.geometricEclipticLongitude(JD); + var sunlongrad = CT.d2R(sunlong); + var beta = CAASun.geometricEclipticLatitude(JD); + var betarad = CT.d2R(beta); + var R = CAAEarth.radiusVector(JD); + var DELTA = 5; + var PreviousEarthLightTravelTime = 0; + var EarthLightTravelTime = ELL.distanceToLightTime(DELTA); + var JD1 = JD - EarthLightTravelTime; + var bIterate = true; + var x = 0; + var y = 0; + var z = 0; + var l = 0; + var lrad = 0; + var b = 0; + var brad = 0; + var r = 0; + while (bIterate) { + l = CAAJupiter.eclipticLongitude(JD1); + lrad = CT.d2R(l); + b = CAAJupiter.eclipticLatitude(JD1); + brad = CT.d2R(b); + r = CAAJupiter.radiusVector(JD1); + x = r * Math.cos(brad) * Math.cos(lrad) + R * Math.cos(sunlongrad); + y = r * Math.cos(brad) * Math.sin(lrad) + R * Math.sin(sunlongrad); + z = r * Math.sin(brad) + R * Math.sin(betarad); + DELTA = Math.sqrt(x * x + y * y + z * z); + EarthLightTravelTime = ELL.distanceToLightTime(DELTA); + bIterate = (Math.abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-06); + if (bIterate) { + JD1 = JD - EarthLightTravelTime; + PreviousEarthLightTravelTime = EarthLightTravelTime; + } + } + var details1 = GM.calculateHelper(JD, sunlongrad, betarad, R); + GM.fillInPhenomenaDetails(details1.satellite1); + GM.fillInPhenomenaDetails(details1.satellite2); + GM.fillInPhenomenaDetails(details1.satellite3); + GM.fillInPhenomenaDetails(details1.satellite4); + JD1 = JD - EarthLightTravelTime; + l = CAAJupiter.eclipticLongitude(JD1); + lrad = CT.d2R(l); + b = CAAJupiter.eclipticLatitude(JD1); + brad = CT.d2R(b); + r = CAAJupiter.radiusVector(JD1); + x = r * Math.cos(brad) * Math.cos(lrad); + y = r * Math.cos(brad) * Math.sin(lrad); + z = r * Math.sin(brad); + DELTA = Math.sqrt(x * x + y * y + z * z); + var SunLightTravelTime = ELL.distanceToLightTime(DELTA); + var details2 = GM.calculateHelper(JD + SunLightTravelTime - EarthLightTravelTime, sunlongrad, betarad, 0); + GM.fillInPhenomenaDetails(details2.satellite1); + GM.fillInPhenomenaDetails(details2.satellite2); + GM.fillInPhenomenaDetails(details2.satellite3); + GM.fillInPhenomenaDetails(details2.satellite4); + details1.satellite1.bInEclipse = details2.satellite1.bInOccultation; + details1.satellite2.bInEclipse = details2.satellite2.bInOccultation; + details1.satellite3.bInEclipse = details2.satellite3.bInOccultation; + details1.satellite4.bInEclipse = details2.satellite4.bInOccultation; + details1.satellite1.bInShadowTransit = details2.satellite1.bInTransit; + details1.satellite2.bInShadowTransit = details2.satellite2.bInTransit; + details1.satellite3.bInShadowTransit = details2.satellite3.bInTransit; + details1.satellite4.bInShadowTransit = details2.satellite4.bInTransit; + details1.satellite1.apparentShadowRectangularCoordinates = details2.satellite1.apparentRectangularCoordinates; + details1.satellite2.apparentShadowRectangularCoordinates = details2.satellite2.apparentRectangularCoordinates; + details1.satellite3.apparentShadowRectangularCoordinates = details2.satellite3.apparentRectangularCoordinates; + details1.satellite4.apparentShadowRectangularCoordinates = details2.satellite4.apparentRectangularCoordinates; + return details1; +}; + +GM.calculateHelper = function (JD, sunlongrad, betarad, R) { + var details = new GMDS(); + var DELTA = 5; + var PreviousLightTravelTime = 0; + var LightTravelTime = ELL.distanceToLightTime(DELTA); + var x = 0; + var y = 0; + var z = 0; + var l = 0; + var lrad = 0; + var b = 0; + var brad = 0; + var r = 0; + var JD1 = JD - LightTravelTime; + var bIterate = true; + while (bIterate) { + l = CAAJupiter.eclipticLongitude(JD1); + lrad = CT.d2R(l); + b = CAAJupiter.eclipticLatitude(JD1); + brad = CT.d2R(b); + r = CAAJupiter.radiusVector(JD1); + x = r * Math.cos(brad) * Math.cos(lrad) + R * Math.cos(sunlongrad); + y = r * Math.cos(brad) * Math.sin(lrad) + R * Math.sin(sunlongrad); + z = r * Math.sin(brad) + R * Math.sin(betarad); + DELTA = Math.sqrt(x * x + y * y + z * z); + LightTravelTime = ELL.distanceToLightTime(DELTA); + bIterate = (Math.abs(LightTravelTime - PreviousLightTravelTime) > 2E-06); + if (bIterate) { + JD1 = JD - LightTravelTime; + PreviousLightTravelTime = LightTravelTime; + } + } + var lambda0 = Math.atan2(y, x); + var beta0 = Math.atan(z / Math.sqrt(x * x + y * y)); + var t = JD - 2443000.5 - LightTravelTime; + var l1 = 106.07719 + 203.48895579 * t; + var l1rad = CT.d2R(l1); + var l2 = 175.73161 + 101.374724735 * t; + var l2rad = CT.d2R(l2); + var l3 = 120.55883 + 50.317609207 * t; + var l3rad = CT.d2R(l3); + var l4 = 84.44459 + 21.571071177 * t; + var l4rad = CT.d2R(l4); + var pi1 = CT.d2R(CT.m360(97.0881 + 0.16138586 * t)); + var pi2 = CT.d2R(CT.m360(154.8663 + 0.04726307 * t)); + var pi3 = CT.d2R(CT.m360(188.184 + 0.00712734 * t)); + var pi4 = CT.d2R(CT.m360(335.2868 + 0.00184 * t)); + var w1 = 312.3346 - 0.13279386 * t; + var w1rad = CT.d2R(w1); + var w2 = 100.4411 - 0.03263064 * t; + var w2rad = CT.d2R(w2); + var w3 = 119.1942 - 0.00717703 * t; + var w3rad = CT.d2R(w3); + var w4 = 322.6186 - 0.00175934 * t; + var w4rad = CT.d2R(w4); + var GAMMA = 0.33033 * Math.sin(CT.d2R(163.679 + 0.0010512 * t)) + 0.03439 * Math.sin(CT.d2R(34.486 - 0.0161731 * t)); + var philambda = CT.d2R(199.6766 + 0.1737919 * t); + var psi = CT.d2R(316.5182 - 2.08E-06 * t); + var G = CT.d2R(30.23756 + 0.0830925701 * t + GAMMA); + var Gdash = CT.d2R(31.97853 + 0.0334597339 * t); + var PI = CT.d2R(13.469942); + var Sigma1 = 0.47259 * Math.sin(2 * (l1rad - l2rad)) + -0.03478 * Math.sin(pi3 - pi4) + 0.01081 * Math.sin(l2rad - 2 * l3rad + pi3) + 0.00738 * Math.sin(philambda) + 0.00713 * Math.sin(l2rad - 2 * l3rad + pi2) + -0.00674 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00666 * Math.sin(l2rad - 2 * l3rad + pi4) + 0.00445 * Math.sin(l1rad - pi3) + -0.00354 * Math.sin(l1rad - l2rad) + -0.00317 * Math.sin(2 * psi - 2 * PI) + 0.00265 * Math.sin(l1rad - pi4) + -0.00186 * Math.sin(G) + 0.00162 * Math.sin(pi2 - pi3) + 0.00158 * Math.sin(4 * (l1rad - l2rad)) + -0.00155 * Math.sin(l1rad - l3rad) + -0.00138 * Math.sin(psi + w3rad - 2 * PI - 2 * G) + -0.00115 * Math.sin(2 * (l1rad - 2 * l2rad + w2rad)) + 0.00089 * Math.sin(pi2 - pi4) + 0.00085 * Math.sin(l1rad + pi3 - 2 * PI - 2 * G) + 0.00083 * Math.sin(w2rad - w3rad) + 0.00053 * Math.sin(psi - w2rad); + var Sigma2 = 1.06476 * Math.sin(2 * (l2rad - l3rad)) + 0.04256 * Math.sin(l1rad - 2 * l2rad + pi3) + 0.03581 * Math.sin(l2rad - pi3) + 0.02395 * Math.sin(l1rad - 2 * l2rad + pi4) + 0.01984 * Math.sin(l2rad - pi4) + -0.01778 * Math.sin(philambda) + 0.01654 * Math.sin(l2rad - pi2) + 0.01334 * Math.sin(l2rad - 2 * l3rad + pi2) + 0.01294 * Math.sin(pi3 - pi4) + -0.01142 * Math.sin(l2rad - l3rad) + -0.01057 * Math.sin(G) + -0.00775 * Math.sin(2 * (psi - PI)) + 0.00524 * Math.sin(2 * (l1rad - l2rad)) + -0.0046 * Math.sin(l1rad - l3rad) + 0.00316 * Math.sin(psi - 2 * G + w3rad - 2 * PI) + -0.00203 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00146 * Math.sin(psi - w3rad) + -0.00145 * Math.sin(2 * G) + 0.00125 * Math.sin(psi - w4rad) + -0.00115 * Math.sin(l1rad - 2 * l3rad + pi3) + -0.00094 * Math.sin(2 * (l2rad - w2rad)) + 0.00086 * Math.sin(2 * (l1rad - 2 * l2rad + w2rad)) + -0.00086 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + -0.00078 * Math.sin(l2rad - l4rad) + -0.00064 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00064 * Math.sin(pi1 - pi4) + -0.00063 * Math.sin(l1rad - 2 * l3rad + pi4) + 0.00058 * Math.sin(w3rad - w4rad) + 0.00056 * Math.sin(2 * (psi - PI - G)) + 0.00056 * Math.sin(2 * (l2rad - l4rad)) + 0.00055 * Math.sin(2 * (l1rad - l3rad)) + 0.00052 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + -0.00043 * Math.sin(l1rad - pi3) + 0.00041 * Math.sin(5 * (l2rad - l3rad)) + 0.00041 * Math.sin(pi4 - PI) + 0.00032 * Math.sin(w2rad - w3rad) + 0.00032 * Math.sin(2 * (l3rad - G - PI)); + var Sigma3 = 0.1649 * Math.sin(l3rad - pi3) + 0.09081 * Math.sin(l3rad - pi4) + -0.06907 * Math.sin(l2rad - l3rad) + 0.03784 * Math.sin(pi3 - pi4) + 0.01846 * Math.sin(2 * (l3rad - l4rad)) + -0.0134 * Math.sin(G) + -0.01014 * Math.sin(2 * (psi - PI)) + 0.00704 * Math.sin(l2rad - 2 * l3rad + pi3) + -0.0062 * Math.sin(l2rad - 2 * l3rad + pi2) + -0.00541 * Math.sin(l3rad - l4rad) + 0.00381 * Math.sin(l2rad - 2 * l3rad + pi4) + 0.00235 * Math.sin(psi - w3rad) + 0.00198 * Math.sin(psi - w4rad) + 0.00176 * Math.sin(philambda) + 0.0013 * Math.sin(3 * (l3rad - l4rad)) + 0.00125 * Math.sin(l1rad - l3rad) + -0.00119 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + 0.00109 * Math.sin(l1rad - l2rad) + -0.001 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00091 * Math.sin(w3rad - w4rad) + 0.0008 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + -0.00075 * Math.sin(2 * l2rad - 3 * l3rad + pi3) + 0.00072 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00069 * Math.sin(pi4 - PI) + -0.00058 * Math.sin(2 * l3rad - 3 * l4rad + pi4) + -0.00057 * Math.sin(l3rad - 2 * l4rad + pi4) + 0.00056 * Math.sin(l3rad + pi3 - 2 * PI - 2 * G) + -0.00052 * Math.sin(l2rad - 2 * l3rad + pi1) + -0.0005 * Math.sin(pi2 - pi3) + 0.00048 * Math.sin(l3rad - 2 * l4rad + pi3) + -0.00045 * Math.sin(2 * l2rad - 3 * l3rad + pi4) + -0.00041 * Math.sin(pi2 - pi4) + -0.00038 * Math.sin(2 * G) + -0.00037 * Math.sin(pi3 - pi4 + w3rad - w4rad) + -0.00032 * Math.sin(3 * l3rad - 7 * l4rad + 2 * pi3 + 2 * pi4) + 0.0003 * Math.sin(4 * (l3rad - l4rad)) + 0.00029 * Math.sin(l3rad + pi4 - 2 * PI - 2 * G) + -0.00028 * Math.sin(w3rad + psi - 2 * PI - 2 * G) + 0.00026 * Math.sin(l3rad - PI - G) + 0.00024 * Math.sin(l2rad - 3 * l3rad + 2 * l4rad) + 0.00021 * Math.sin(l3rad - PI - G) + -0.00021 * Math.sin(l3rad - pi2) + 0.00017 * Math.sin(2 * (l3rad - pi3)); + var Sigma4 = 0.84287 * Math.sin(l4rad - pi4) + 0.03431 * Math.sin(pi4 - pi3) + -0.03305 * Math.sin(2 * (psi - PI)) + -0.03211 * Math.sin(G) + -0.01862 * Math.sin(l4rad - pi3) + 0.01186 * Math.sin(psi - w4rad) + 0.00623 * Math.sin(l4rad + pi4 - 2 * G - 2 * PI) + 0.00387 * Math.sin(2 * (l4rad - pi4)) + -0.00284 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + -0.00234 * Math.sin(2 * (psi - pi4)) + -0.00223 * Math.sin(l3rad - l4rad) + -0.00208 * Math.sin(l4rad - PI) + 0.00178 * Math.sin(psi + w4rad - 2 * pi4) + 0.00134 * Math.sin(pi4 - PI) + 0.00125 * Math.sin(2 * (l4rad - G - PI)) + -0.00117 * Math.sin(2 * G) + -0.00112 * Math.sin(2 * (l3rad - l4rad)) + 0.00107 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00102 * Math.sin(l4rad - G - PI) + 0.00096 * Math.sin(2 * l4rad - psi - w4rad) + 0.00087 * Math.sin(2 * (psi - w4rad)) + -0.00085 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + 0.00085 * Math.sin(l3rad - 2 * l4rad + pi4) + -0.00081 * Math.sin(2 * (l4rad - psi)) + 0.00071 * Math.sin(l4rad + pi4 - 2 * PI - 3 * G) + 0.00061 * Math.sin(l1rad - l4rad) + -0.00056 * Math.sin(psi - w3rad) + -0.00054 * Math.sin(l3rad - 2 * l4rad + pi3) + 0.00051 * Math.sin(l2rad - l4rad) + 0.00042 * Math.sin(2 * (psi - G - PI)) + 0.00039 * Math.sin(2 * (pi4 - w4rad)) + 0.00036 * Math.sin(psi + PI - pi4 - w4rad) + 0.00035 * Math.sin(2 * Gdash - G + CT.d2R(188.37)) + -0.00035 * Math.sin(l4rad - pi4 + 2 * PI - 2 * psi) + -0.00032 * Math.sin(l4rad + pi4 - 2 * PI - G) + 0.0003 * Math.sin(2 * Gdash - 2 * G + CT.d2R(149.15)) + 0.00029 * Math.sin(3 * l3rad - 7 * l4rad + 2 * pi3 + 2 * pi4) + 0.00028 * Math.sin(l4rad - pi4 + 2 * psi - 2 * PI) + -0.00028 * Math.sin(2 * (l4rad - w4rad)) + -0.00027 * Math.sin(pi3 - pi4 + w3rad - w4rad) + -0.00026 * Math.sin(5 * Gdash - 3 * G + CT.d2R(188.37)) + 0.00025 * Math.sin(w4rad - w3rad) + -0.00025 * Math.sin(l2rad - 3 * l3rad + 2 * l4rad) + -0.00023 * Math.sin(3 * (l3rad - l4rad)) + 0.00021 * Math.sin(2 * l4rad - 2 * PI - 3 * G) + -0.00021 * Math.sin(2 * l3rad - 3 * l4rad + pi4) + 0.00019 * Math.sin(l4rad - pi4 - G) + -0.00019 * Math.sin(2 * l4rad - pi3 - pi4) + -0.00018 * Math.sin(l4rad - pi4 + G) + -0.00016 * Math.sin(l4rad + pi3 - 2 * PI - 2 * G); + details.satellite1.meanLongitude = CT.m360(l1); + details.satellite1.trueLongitude = CT.m360(l1 + Sigma1); + var L1 = CT.d2R(details.satellite1.trueLongitude); + details.satellite2.meanLongitude = CT.m360(l2); + details.satellite2.trueLongitude = CT.m360(l2 + Sigma2); + var L2 = CT.d2R(details.satellite2.trueLongitude); + details.satellite3.meanLongitude = CT.m360(l3); + details.satellite3.trueLongitude = CT.m360(l3 + Sigma3); + var L3 = CT.d2R(details.satellite3.trueLongitude); + details.satellite4.meanLongitude = CT.m360(l4); + details.satellite4.trueLongitude = CT.m360(l4 + Sigma4); + var L4 = CT.d2R(details.satellite4.trueLongitude); + var B1 = Math.atan(0.0006393 * Math.sin(L1 - w1rad) + 0.0001825 * Math.sin(L1 - w2rad) + 3.29E-05 * Math.sin(L1 - w3rad) + -3.11E-05 * Math.sin(L1 - psi) + 9.3E-06 * Math.sin(L1 - w4rad) + 7.5E-06 * Math.sin(3 * L1 - 4 * l2rad - 1.9927 * Sigma1 + w2rad) + 4.6E-06 * Math.sin(L1 + psi - 2 * PI - 2 * G)); + details.satellite1.equatorialLatitude = CT.r2D(B1); + var B2 = Math.atan(0.0081004 * Math.sin(L2 - w2rad) + 0.0004512 * Math.sin(L2 - w3rad) + -0.0003284 * Math.sin(L2 - psi) + 0.000116 * Math.sin(L2 - w4rad) + 2.72E-05 * Math.sin(l1rad - 2 * l3rad + 1.0146 * Sigma2 + w2rad) + -1.44E-05 * Math.sin(L2 - w1rad) + 1.43E-05 * Math.sin(L2 + psi - 2 * PI - 2 * G) + 3.5E-06 * Math.sin(L2 - psi + G) + -2.8E-06 * Math.sin(l1rad - 2 * l3rad + 1.0146 * Sigma2 + w3rad)); + details.satellite2.equatorialLatitude = CT.r2D(B2); + var B3 = Math.atan(0.0032402 * Math.sin(L3 - w3rad) + -0.0016911 * Math.sin(L3 - psi) + 0.0006847 * Math.sin(L3 - w4rad) + -0.0002797 * Math.sin(L3 - w2rad) + 3.21E-05 * Math.sin(L3 + psi - 2 * PI - 2 * G) + 5.1E-06 * Math.sin(L3 - psi + G) + -4.5E-06 * Math.sin(L3 - psi - G) + -4.5E-06 * Math.sin(L3 + psi - 2 * PI) + 3.7E-06 * Math.sin(L3 + psi - 2 * PI - 3 * G) + 3E-06 * Math.sin(2 * l2rad - 3 * L3 + 4.03 * Sigma3 + w2rad) + -2.1E-06 * Math.sin(2 * l2rad - 3 * L3 + 4.03 * Sigma3 + w3rad)); + details.satellite3.equatorialLatitude = CT.r2D(B3); + var B4 = Math.atan(-0.0076579 * Math.sin(L4 - psi) + 0.0044134 * Math.sin(L4 - w4rad) + -0.0005112 * Math.sin(L4 - w3rad) + 7.73E-05 * Math.sin(L4 + psi - 2 * PI - 2 * G) + 1.04E-05 * Math.sin(L4 - psi + G) + -1.02E-05 * Math.sin(L4 - psi - G) + 8.8E-06 * Math.sin(L4 + psi - 2 * PI - 3 * G) + -3.8E-06 * Math.sin(L4 + psi - 2 * PI - G)); + details.satellite4.equatorialLatitude = CT.r2D(B4); + details.satellite1.r = 5.90569 * (1 + (-0.0041339 * Math.cos(2 * (l1rad - l2rad)) + -3.87E-05 * Math.cos(l1rad - pi3) + -2.14E-05 * Math.cos(l1rad - pi4) + 1.7E-05 * Math.cos(l1rad - l2rad) + -1.31E-05 * Math.cos(4 * (l1rad - l2rad)) + 1.06E-05 * Math.cos(l1rad - l3rad) + -6.6E-06 * Math.cos(l1rad + pi3 - 2 * PI - 2 * G))); + details.satellite2.r = 9.39657 * (1 + (0.0093848 * Math.cos(l1rad - l2rad) + -0.0003116 * Math.cos(l2rad - pi3) + -0.0001744 * Math.cos(l2rad - pi4) + -0.0001442 * Math.cos(l2rad - pi2) + 5.53E-05 * Math.cos(l2rad - l3rad) + 5.23E-05 * Math.cos(l1rad - l3rad) + -2.9E-05 * Math.cos(2 * (l1rad - l2rad)) + 1.64E-05 * Math.cos(2 * (l2rad - w2rad)) + 1.07E-05 * Math.cos(l1rad - 2 * l3rad + pi3) + -1.02E-05 * Math.cos(l2rad - pi1) + -9.1E-06 * Math.cos(2 * (l1rad - l3rad)))); + details.satellite3.r = 14.98832 * (1 + (-0.0014388 * Math.cos(l3rad - pi3) + -0.0007919 * Math.cos(l3rad - pi4) + 0.0006342 * Math.cos(l2rad - l3rad) + -0.0001761 * Math.cos(2 * (l3rad - l4rad)) + 2.94E-05 * Math.cos(l3rad - l4rad) + -1.56E-05 * Math.cos(3 * (l3rad - l4rad)) + 1.56E-05 * Math.cos(l1rad - l3rad) + -1.53E-05 * Math.cos(l1rad - l2rad) + 7E-06 * Math.cos(2 * l2rad - 3 * l3rad + pi3) + -5.1E-06 * Math.cos(l3rad + pi3 - 2 * PI - 2 * G))); + details.satellite4.r = 26.36273 * (1 + (-0.0073546 * Math.cos(l4rad - pi4) + 0.0001621 * Math.cos(l4rad - pi3) + 9.74E-05 * Math.cos(l3rad - l4rad) + -5.43E-05 * Math.cos(l4rad + pi4 - 2 * PI - 2 * G) + -2.71E-05 * Math.cos(2 * (l4rad - pi4)) + 1.82E-05 * Math.cos(l4rad - PI) + 1.77E-05 * Math.cos(2 * (l3rad - l4rad)) + -1.67E-05 * Math.cos(2 * l4rad - psi - w4rad) + 1.67E-05 * Math.cos(psi - w4rad) + -1.55E-05 * Math.cos(2 * (l4rad - PI - G)) + 1.42E-05 * Math.cos(2 * (l4rad - psi)) + 1.05E-05 * Math.cos(l1rad - l4rad) + 9.2E-06 * Math.cos(l2rad - l4rad) + -8.9E-06 * Math.cos(l4rad - PI - G) + -6.2E-06 * Math.cos(l4rad + pi4 - 2 * PI - 3 * G) + 4.8E-06 * Math.cos(2 * (l4rad - w4rad)))); + var T0 = (JD - 2433282.423) / 36525; + var P = CT.d2R(1.3966626 * T0 + 0.0003088 * T0 * T0); + L1 += P; + details.satellite1.tropicalLongitude = CT.m360(CT.r2D(L1)); + L2 += P; + details.satellite2.tropicalLongitude = CT.m360(CT.r2D(L2)); + L3 += P; + details.satellite3.tropicalLongitude = CT.m360(CT.r2D(L3)); + L4 += P; + details.satellite4.tropicalLongitude = CT.m360(CT.r2D(L4)); + psi += P; + var T = (JD - 2415020.5) / 36525; + var I = 3.120262 + 0.0006 * T; + var Irad = CT.d2R(I); + var X1 = details.satellite1.r * Math.cos(L1 - psi) * Math.cos(B1); + var X2 = details.satellite2.r * Math.cos(L2 - psi) * Math.cos(B2); + var X3 = details.satellite3.r * Math.cos(L3 - psi) * Math.cos(B3); + var X4 = details.satellite4.r * Math.cos(L4 - psi) * Math.cos(B4); + var X5 = 0; + var Y1 = details.satellite1.r * Math.sin(L1 - psi) * Math.cos(B1); + var Y2 = details.satellite2.r * Math.sin(L2 - psi) * Math.cos(B2); + var Y3 = details.satellite3.r * Math.sin(L3 - psi) * Math.cos(B3); + var Y4 = details.satellite4.r * Math.sin(L4 - psi) * Math.cos(B4); + var Y5 = 0; + var Z1 = details.satellite1.r * Math.sin(B1); + var Z2 = details.satellite2.r * Math.sin(B2); + var Z3 = details.satellite3.r * Math.sin(B3); + var Z4 = details.satellite4.r * Math.sin(B4); + var Z5 = 1; + var omega = CT.d2R(EPO.jupiterLongitudeAscendingNode(JD)); + var i = CT.d2R(EPO.jupiterInclination(JD)); + var A6 = 0; + var B6 = 0; + var C6 = 0; + var north = new C3D(); + var abc = GM.rotations(X5, Y5, Z5, Irad, psi, i, omega, lambda0, beta0, north); + A6 = abc[0]; + B6 = abc[1]; + C6 = abc[2]; + var D = Math.atan2(A6, C6); + abc = GM.rotations(X1, Y1, Z1, Irad, psi, i, omega, lambda0, beta0, details.satellite1.eclipticRectangularCoordinates); + A6 = abc[0]; + B6 = abc[1]; + C6 = abc[2]; + details.satellite1.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); + details.satellite1.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); + details.satellite1.trueRectangularCoordinates.z = B6; + abc = GM.rotations(X2, Y2, Z2, Irad, psi, i, omega, lambda0, beta0, details.satellite2.eclipticRectangularCoordinates); + A6 = abc[0]; + B6 = abc[1]; + C6 = abc[2]; + details.satellite2.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); + details.satellite2.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); + details.satellite2.trueRectangularCoordinates.z = B6; + abc = GM.rotations(X3, Y3, Z3, Irad, psi, i, omega, lambda0, beta0, details.satellite3.eclipticRectangularCoordinates); + A6 = abc[0]; + B6 = abc[1]; + C6 = abc[2]; + details.satellite3.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); + details.satellite3.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); + details.satellite3.trueRectangularCoordinates.z = B6; + abc = GM.rotations(X4, Y4, Z4, Irad, psi, i, omega, lambda0, beta0, details.satellite4.eclipticRectangularCoordinates); + A6 = abc[0]; + B6 = abc[1]; + C6 = abc[2]; + details.satellite4.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); + details.satellite4.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); + details.satellite4.trueRectangularCoordinates.z = B6; + details.satellite1.apparentRectangularCoordinates.x = details.satellite1.trueRectangularCoordinates.x + Math.abs(details.satellite1.trueRectangularCoordinates.z) / 17295 * Math.sqrt(1 - (details.satellite1.trueRectangularCoordinates.x / details.satellite1.r) * (details.satellite1.trueRectangularCoordinates.x / details.satellite1.r)); + details.satellite1.apparentRectangularCoordinates.y = details.satellite1.trueRectangularCoordinates.y; + details.satellite1.apparentRectangularCoordinates.z = details.satellite1.trueRectangularCoordinates.z; + details.satellite2.apparentRectangularCoordinates.x = details.satellite2.trueRectangularCoordinates.x + Math.abs(details.satellite2.trueRectangularCoordinates.z) / 21819 * Math.sqrt(1 - (details.satellite2.trueRectangularCoordinates.x / details.satellite2.r) * (details.satellite2.trueRectangularCoordinates.x / details.satellite2.r)); + details.satellite2.apparentRectangularCoordinates.y = details.satellite2.trueRectangularCoordinates.y; + details.satellite2.apparentRectangularCoordinates.z = details.satellite2.trueRectangularCoordinates.z; + details.satellite3.apparentRectangularCoordinates.x = details.satellite3.trueRectangularCoordinates.x + Math.abs(details.satellite3.trueRectangularCoordinates.z) / 27558 * Math.sqrt(1 - (details.satellite3.trueRectangularCoordinates.x / details.satellite3.r) * (details.satellite3.trueRectangularCoordinates.x / details.satellite3.r)); + details.satellite3.apparentRectangularCoordinates.y = details.satellite3.trueRectangularCoordinates.y; + details.satellite3.apparentRectangularCoordinates.z = details.satellite3.trueRectangularCoordinates.z; + details.satellite4.apparentRectangularCoordinates.x = details.satellite4.trueRectangularCoordinates.x + Math.abs(details.satellite4.trueRectangularCoordinates.z) / 36548 * Math.sqrt(1 - (details.satellite4.trueRectangularCoordinates.x / details.satellite4.r) * (details.satellite4.trueRectangularCoordinates.x / details.satellite4.r)); + details.satellite4.apparentRectangularCoordinates.y = details.satellite4.trueRectangularCoordinates.y; + details.satellite4.apparentRectangularCoordinates.z = details.satellite4.trueRectangularCoordinates.z; + var W = DELTA / (DELTA + details.satellite1.trueRectangularCoordinates.z / 2095); + details.satellite1.apparentRectangularCoordinates.x *= W; + details.satellite1.apparentRectangularCoordinates.y *= W; + W = DELTA / (DELTA + details.satellite2.trueRectangularCoordinates.z / 2095); + details.satellite2.apparentRectangularCoordinates.x *= W; + details.satellite2.apparentRectangularCoordinates.y *= W; + W = DELTA / (DELTA + details.satellite3.trueRectangularCoordinates.z / 2095); + details.satellite3.apparentRectangularCoordinates.x *= W; + details.satellite3.apparentRectangularCoordinates.y *= W; + W = DELTA / (DELTA + details.satellite4.trueRectangularCoordinates.z / 2095); + details.satellite4.apparentRectangularCoordinates.x *= W; + details.satellite4.apparentRectangularCoordinates.y *= W; + return details; +}; + +GM.rotations = function (X, Y, Z, I, psi, i, omega, lambda0, beta0, eclipticCoord) { + var A6; + var B6; + var C6; + var phi = psi - omega; + var A1 = X; + var B1 = Y * Math.cos(I) - Z * Math.sin(I); + var C1 = Y * Math.sin(I) + Z * Math.cos(I); + var A2 = A1 * Math.cos(phi) - B1 * Math.sin(phi); + var B2 = A1 * Math.sin(phi) + B1 * Math.cos(phi); + var C2 = C1; + var A3 = A2; + var B3 = B2 * Math.cos(i) - C2 * Math.sin(i); + var C3 = B2 * Math.sin(i) + C2 * Math.cos(i); + var A4 = A3 * Math.cos(omega) - B3 * Math.sin(omega); + var B4 = A3 * Math.sin(omega) + B3 * Math.cos(omega); + var C4 = C3; + var JupiterRadiiToAU = 1 / 2095; + eclipticCoord.x = A4 * JupiterRadiiToAU; + eclipticCoord.y = B4 * JupiterRadiiToAU; + eclipticCoord.z = C4 * JupiterRadiiToAU; + var A5 = A4 * Math.sin(lambda0) - B4 * Math.cos(lambda0); + var B5 = A4 * Math.cos(lambda0) + B4 * Math.sin(lambda0); + var C5 = C4; + A6 = A5; + B6 = C5 * Math.sin(beta0) + B5 * Math.cos(beta0); + C6 = C5 * Math.cos(beta0) - B5 * Math.sin(beta0); + return [A6, B6, C6]; +}; + +GM.fillInPhenomenaDetails = function (detail) { + var Y1 = 1.071374 * detail.apparentRectangularCoordinates.y; + var r = Y1 * Y1 + detail.apparentRectangularCoordinates.x * detail.apparentRectangularCoordinates.x; + if (r < 1) { + if (detail.apparentRectangularCoordinates.z < 0) { + detail.bInTransit = true; + detail.bInOccultation = false; + } + else { + detail.bInTransit = false; + detail.bInOccultation = true; + } + } + else { + detail.bInTransit = false; + detail.bInOccultation = false; + } +}; + +var GM$ = {}; + +registerType("GM", [GM, GM$, null]); diff --git a/engine/esm/astrocalc/globe.js b/engine/esm/astrocalc/globe.js new file mode 100644 index 00000000..fc5f79d9 --- /dev/null +++ b/engine/esm/astrocalc/globe.js @@ -0,0 +1,81 @@ +// Originally `AAGLOBE.CPP` +// "Purpose: Implementation for the algorithms for the Earth's Globe" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// CAAGlobe + +export function CAAGlobe() { } + +CAAGlobe.rhoSinThetaPrime = function (GeographicalLatitude, Height) { + GeographicalLatitude = CT.d2R(GeographicalLatitude); + var U = Math.atan(0.99664719 * Math.tan(GeographicalLatitude)); + return 0.99664719 * Math.sin(U) + (Height / 6378149 * Math.sin(GeographicalLatitude)); +}; + +CAAGlobe.rhoCosThetaPrime = function (GeographicalLatitude, Height) { + GeographicalLatitude = CT.d2R(GeographicalLatitude); + var U = Math.atan(0.99664719 * Math.tan(GeographicalLatitude)); + return Math.cos(U) + (Height / 6378149 * Math.cos(GeographicalLatitude)); +}; + +CAAGlobe.radiusOfParallelOfLatitude = function (GeographicalLatitude) { + GeographicalLatitude = CT.d2R(GeographicalLatitude); + var sinGeo = Math.sin(GeographicalLatitude); + return (6378.14 * Math.cos(GeographicalLatitude)) / Math.sqrt(1 - 0.0066943847614084 * sinGeo * sinGeo); +}; + +CAAGlobe.radiusOfCurvature = function (GeographicalLatitude) { + GeographicalLatitude = CT.d2R(GeographicalLatitude); + var sinGeo = Math.sin(GeographicalLatitude); + return (6378.14 * (1 - 0.0066943847614084)) / Math.pow((1 - 0.0066943847614084 * sinGeo * sinGeo), 1.5); +}; + +CAAGlobe.distanceBetweenPoints = function (GeographicalLatitude1, GeographicalLongitude1, GeographicalLatitude2, GeographicalLongitude2) { + GeographicalLatitude1 = CT.d2R(GeographicalLatitude1); + GeographicalLatitude2 = CT.d2R(GeographicalLatitude2); + GeographicalLongitude1 = CT.d2R(GeographicalLongitude1); + GeographicalLongitude2 = CT.d2R(GeographicalLongitude2); + var F = (GeographicalLatitude1 + GeographicalLatitude2) / 2; + var G = (GeographicalLatitude1 - GeographicalLatitude2) / 2; + var lambda = (GeographicalLongitude1 - GeographicalLongitude2) / 2; + var sinG = Math.sin(G); + var cosG = Math.cos(G); + var cosF = Math.cos(F); + var sinF = Math.sin(F); + var sinLambda = Math.sin(lambda); + var cosLambda = Math.cos(lambda); + var S = (sinG * sinG * cosLambda * cosLambda) + (cosF * cosF * sinLambda * sinLambda); + var C = (cosG * cosG * cosLambda * cosLambda) + (sinF * sinF * sinLambda * sinLambda); + var w = Math.atan(Math.sqrt(S / C)); + var R = Math.sqrt(S * C) / w; + var D = 2 * w * 6378.14; + var Hprime = (3 * R - 1) / (2 * C); + var Hprime2 = (3 * R + 1) / (2 * S); + var f = 0.00335281317789691; + return D * (1 + (f * Hprime * sinF * sinF * cosG * cosG) - (f * Hprime2 * cosF * cosF * sinG * sinG)); +}; + +var CAAGlobe$ = {}; + +registerType("CAAGlobe", [CAAGlobe, CAAGlobe$, null]); diff --git a/engine/esm/astrocalc/illuminated_fraction.js b/engine/esm/astrocalc/illuminated_fraction.js new file mode 100644 index 00000000..48c4b7b1 --- /dev/null +++ b/engine/esm/astrocalc/illuminated_fraction.js @@ -0,0 +1,129 @@ +// Originally `AAILLUMINATEDFRACTION.CPP` +// "Purpose: Implementation for the algorithms for a planet's Phase Angle, Illuminated Fraction and Magnitude" +// Last update of original: PJN / 21-01-2005 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { CT } from "./coordinate_transformation.js"; + + +// IFR + +export function IFR() { } + +IFR.phaseAngle = function (r, R, Delta) { + return CT.m360(CT.r2D(Math.acos((r * r + Delta * Delta - R * R) / (2 * r * Delta)))); +}; + +IFR.phaseAngle2 = function (R, R0, B, L, L0, Delta) { + B = CT.d2R(B); + L = CT.d2R(L); + L0 = CT.d2R(L0); + return CT.m360(CT.r2D(Math.acos((R - R0 * Math.cos(B) * Math.cos(L - L0)) / Delta))); +}; + +IFR.phaseAngleRectangular = function (x, y, z, B, L, Delta) { + B = CT.d2R(B); + L = CT.d2R(L); + var cosB = Math.cos(B); + return CT.m360(CT.r2D(Math.acos((x * cosB * Math.cos(L) + y * cosB * Math.sin(L) + z * Math.sin(B)) / Delta))); +}; + +IFR.illuminatedFraction = function (PhaseAngle) { + PhaseAngle = CT.d2R(PhaseAngle); + return (1 + Math.cos(PhaseAngle)) / 2; +}; + +IFR.illuminatedFraction2 = function (r, R, Delta) { + return (((r + Delta) * (r + Delta) - R * R) / (4 * r * Delta)); +}; + +IFR.mercuryMagnitudeMuller = function (r, Delta, i) { + var I_50 = i - 50; + return 1.16 + 5 * Util.log10(r * Delta) + 0.02838 * I_50 + 0.0001023 * I_50 * I_50; +}; + +IFR.venusMagnitudeMuller = function (r, Delta, i) { + return -4 + 5 * Util.log10(r * Delta) + 0.01322 * i + 4.247E-07 * i * i * i; +}; + +IFR.marsMagnitudeMuller = function (r, Delta, i) { + return -1.3 + 5 * Util.log10(r * Delta) + 0.01486 * i; +}; + +IFR.jupiterMagnitudeMuller = function (r, Delta) { + return -8.93 + 5 * Util.log10(r * Delta); +}; + +IFR.saturnMagnitudeMuller = function (r, Delta, DeltaU, B) { + B = CT.d2R(B); + var sinB = Math.sin(B); + return -8.68 + 5 * Util.log10(r * Delta) + 0.044 * Math.abs(DeltaU) - 2.6 * Math.sin(Math.abs(B)) + 1.25 * sinB * sinB; +}; + +IFR.uranusMagnitudeMuller = function (r, Delta) { + return -6.85 + 5 * Util.log10(r * Delta); +}; + +IFR.neptuneMagnitudeMuller = function (r, Delta) { + return -7.05 + 5 * Util.log10(r * Delta); +}; + +IFR.mercuryMagnitudeAA = function (r, Delta, i) { + var i2 = i * i; + var i3 = i2 * i; + return -0.42 + 5 * Util.log10(r * Delta) + 0.038 * i - 0.000273 * i2 + 2E-06 * i3; +}; + +IFR.venusMagnitudeAA = function (r, Delta, i) { + var i2 = i * i; + var i3 = i2 * i; + return -4.4 + 5 * Util.log10(r * Delta) + 0.0009 * i + 0.000239 * i2 - 6.5E-07 * i3; +}; + +IFR.marsMagnitudeAA = function (r, Delta, i) { + return -1.52 + 5 * Util.log10(r * Delta) + 0.016 * i; +}; + +IFR.jupiterMagnitudeAA = function (r, Delta, i) { + return -9.4 + 5 * Util.log10(r * Delta) + 0.005 * i; +}; + +IFR.saturnMagnitudeAA = function (r, Delta, DeltaU, B) { + B = CT.d2R(B); + var sinB = Math.sin(B); + return -8.88 + 5 * Util.log10(r * Delta) + 0.044 * Math.abs(DeltaU) - 2.6 * Math.sin(Math.abs(B)) + 1.25 * sinB * sinB; +}; + +IFR.uranusMagnitudeAA = function (r, Delta) { + return -7.19 + 5 * Util.log10(r * Delta); +}; + +IFR.neptuneMagnitudeAA = function (r, Delta) { + return -6.87 + 5 * Util.log10(r * Delta); +}; + +IFR.plutoMagnitudeAA = function (r, Delta) { + return -1 + 5 * Util.log10(r * Delta); +}; + +var IFR$ = {}; + +registerType("IFR", [IFR, IFR$, null]); diff --git a/engine/esm/astrocalc/interpolate.js b/engine/esm/astrocalc/interpolate.js new file mode 100644 index 00000000..c1e1573a --- /dev/null +++ b/engine/esm/astrocalc/interpolate.js @@ -0,0 +1,167 @@ +// Originally `AAINTERPOLATE.CPP` +// "Purpose: Implementation for the algorithms for Interpolation" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; + + +// INTP - was CAAInterpoate + +export function INTP() { } + +INTP.interpolate = function (n, Y1, Y2, Y3) { + var a = Y2 - Y1; + var b = Y3 - Y2; + var c = Y1 + Y3 - 2 * Y2; + return Y2 + n / 2 * (a + b + n * c); +}; + +INTP.interpolate2 = function (n, Y1, Y2, Y3, Y4, Y5) { + var A = Y2 - Y1; + var B = Y3 - Y2; + var C = Y4 - Y3; + var D = Y5 - Y4; + var E = B - A; + var F = C - B; + var G = D - C; + var H = F - E; + var J = G - F; + var K = J - H; + var N2 = n * n; + var N3 = N2 * n; + var N4 = N3 * n; + return Y3 + n * ((B + C) / 2 - (H + J) / 12) + N2 * (F / 2 - K / 24) + N3 * ((H + J) / 12) + N4 * (K / 24); +}; + +INTP.interpolateToHalves = function (Y1, Y2, Y3, Y4) { + return (9 * (Y2 + Y3) - Y1 - Y4) / 16; +}; + +INTP.lagrangeInterpolate = function (X, n, pX, pY) { + var V = 0; + for (var i = 1; i <= n; i++) { + var C = 1; + for (var j = 1; j <= n; j++) { + if (j !== i) { + C = C * (X - pX[j - 1]) / (pX[i - 1] - pX[j - 1]); + } + } + V += C * pY[i - 1]; + } + return V; +}; + +INTP.zero = function (Y1, Y2, Y3) { + var a = Y2 - Y1; + var b = Y3 - Y2; + var c = Y1 + Y3 - 2 * Y2; + var bRecalc = true; + var n0prev = 0; + var n0 = n0prev; + while (bRecalc) { + n0 = -2 * Y2 / (a + b + c * n0prev); + bRecalc = (Math.abs(n0 - n0prev) > 1E-12); + if (bRecalc) { + n0prev = n0; + } + } + return n0; +}; + +INTP.zeroB = function (Y1, Y2, Y3, Y4, Y5) { + var A = Y2 - Y1; + var B = Y3 - Y2; + var C = Y4 - Y3; + var D = Y5 - Y4; + var E = B - A; + var F = C - B; + var G = D - C; + var H = F - E; + var J = G - F; + var K = J - H; + var bRecalc = true; + var n0prev = 0; + var n0 = n0prev; + while (bRecalc) { + var n0prev2 = n0prev * n0prev; + var n0prev3 = n0prev2 * n0prev; + var n0prev4 = n0prev3 * n0prev; + n0 = (-24 * Y3 + n0prev2 * (K - 12 * F) - 2 * n0prev3 * (H + J) - n0prev4 * K) / (2 * (6 * B + 6 * C - H - J)); + bRecalc = (Math.abs(n0 - n0prev) > 1E-12); + if (bRecalc) { + n0prev = n0; + } + } + return n0; +}; + +INTP.zero2 = function (Y1, Y2, Y3) { + var a = Y2 - Y1; + var b = Y3 - Y2; + var c = Y1 + Y3 - 2 * Y2; + var bRecalc = true; + var n0prev = 0; + var n0 = n0prev; + while (bRecalc) { + var deltan0 = -(2 * Y2 + n0prev * (a + b + c * n0prev)) / (a + b + 2 * c * n0prev); + n0 = n0prev + deltan0; + bRecalc = (Math.abs(deltan0) > 1E-12); + if (bRecalc) { + n0prev = n0; + } + } + return n0; +}; + +INTP.zero2B = function (Y1, Y2, Y3, Y4, Y5) { + var A = Y2 - Y1; + var B = Y3 - Y2; + var C = Y4 - Y3; + var D = Y5 - Y4; + var E = B - A; + var F = C - B; + var G = D - C; + var H = F - E; + var J = G - F; + var K = J - H; + var M = K / 24; + var N = (H + J) / 12; + var P = F / 2 - M; + var Q = (B + C) / 2 - N; + var bRecalc = true; + var n0prev = 0; + var n0 = n0prev; + while (bRecalc) { + var n0prev2 = n0prev * n0prev; + var n0prev3 = n0prev2 * n0prev; + var n0prev4 = n0prev3 * n0prev; + var deltan0 = -(M * n0prev4 + N * n0prev3 + P * n0prev2 + Q * n0prev + Y3) / (4 * M * n0prev3 + 3 * N * n0prev2 + 2 * P * n0prev + Q); + n0 = n0prev + deltan0; + bRecalc = (Math.abs(deltan0) > 1E-12); + if (bRecalc) { + n0prev = n0; + } + } + return n0; +}; + +var INTP$ = {}; + +registerType("INTP", [INTP, INTP$, null]); diff --git a/engine/esm/astrocalc/jupiter.js b/engine/esm/astrocalc/jupiter.js new file mode 100644 index 00000000..d2d62955 --- /dev/null +++ b/engine/esm/astrocalc/jupiter.js @@ -0,0 +1,180 @@ +// Originally `AAJUPITER.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Uranus [sic]" +// Last update of original: PJN / 31-05-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0JupiterCoefficients = [new VSC(59954691, 0, 0), new VSC(9695899, 5.0619179, 529.6909651), new VSC(573610, 1.444062, 7.113547), new VSC(306389, 5.417347, 1059.38193), new VSC(97178, 4.14265, 632.78374), new VSC(72903, 3.64043, 522.57742), new VSC(64264, 3.41145, 103.09277), new VSC(39806, 2.29377, 419.48464), new VSC(38858, 1.27232, 316.39187), new VSC(27965, 1.78455, 536.80451), new VSC(13590, 5.77481, 1589.0729), new VSC(8769, 3.63, 949.1756), new VSC(8246, 3.5823, 206.1855), new VSC(7368, 5.081, 735.8765), new VSC(6263, 0.025, 213.2991), new VSC(6114, 4.5132, 1162.4747), new VSC(5305, 4.1863, 1052.2684), new VSC(5305, 1.3067, 14.2271), new VSC(4905, 1.3208, 110.2063), new VSC(4647, 4.6996, 3.9322), new VSC(3045, 4.3168, 426.5982), new VSC(2610, 1.5667, 846.0828), new VSC(2028, 1.0638, 3.1814), new VSC(1921, 0.9717, 639.8973), new VSC(1765, 2.1415, 1066.4955), new VSC(1723, 3.8804, 1265.5675), new VSC(1633, 3.582, 515.4639), new VSC(1432, 4.2968, 625.6702), new VSC(973, 4.098, 95.979), new VSC(884, 2.437, 412.371), new VSC(733, 6.085, 838.969), new VSC(731, 3.806, 1581.959), new VSC(709, 1.293, 742.99), new VSC(692, 6.134, 2118.764), new VSC(614, 4.109, 1478.867), new VSC(582, 4.54, 309.278), new VSC(495, 3.756, 323.505), new VSC(441, 2.958, 454.909), new VSC(417, 1.036, 2.488), new VSC(390, 4.897, 1692.166), new VSC(376, 4.703, 1368.66), new VSC(341, 5.715, 533.623), new VSC(330, 4.74, 0.048), new VSC(262, 1.877, 0.963), new VSC(261, 0.82, 380.128), new VSC(257, 3.724, 199.072), new VSC(244, 5.22, 728.763), new VSC(235, 1.227, 909.819), new VSC(220, 1.651, 543.918), new VSC(207, 1.855, 525.759), new VSC(202, 1.807, 1375.774), new VSC(197, 5.293, 1155.361), new VSC(175, 3.73, 942.062), new VSC(175, 3.226, 1898.351), new VSC(175, 5.91, 956.289), new VSC(158, 4.365, 1795.258), new VSC(151, 3.906, 74.782), new VSC(149, 4.377, 1685.052), new VSC(141, 3.136, 491.558), new VSC(138, 1.318, 1169.588), new VSC(131, 4.169, 1045.155), new VSC(117, 2.5, 1596.186), new VSC(117, 3.389, 0.521), new VSC(106, 4.554, 526.51)]; +const g_L1JupiterCoefficients = [new VSC(52993480757, 0, 0), new VSC(489741, 4.220667, 529.690965), new VSC(228919, 6.026475, 7.113547), new VSC(27655, 4.57266, 1059.38193), new VSC(20721, 5.45939, 522.57742), new VSC(12106, 0.16986, 536.80451), new VSC(6068, 4.4242, 103.0928), new VSC(5434, 3.9848, 419.4846), new VSC(4238, 5.8901, 14.2271), new VSC(2212, 5.2677, 206.1855), new VSC(1746, 4.9267, 1589.0729), new VSC(1296, 5.5513, 3.1814), new VSC(1173, 5.8565, 1052.2684), new VSC(1163, 0.5145, 3.9322), new VSC(1099, 5.307, 515.4639), new VSC(1007, 0.4648, 735.8765), new VSC(1004, 3.1504, 426.5982), new VSC(848, 5.758, 110.206), new VSC(827, 4.803, 213.299), new VSC(816, 0.586, 1066.495), new VSC(725, 5.518, 639.897), new VSC(568, 5.989, 625.67), new VSC(474, 4.132, 412.371), new VSC(413, 5.737, 95.979), new VSC(345, 4.242, 632.784), new VSC(336, 3.732, 1162.475), new VSC(234, 4.035, 949.176), new VSC(234, 6.243, 309.278), new VSC(199, 1.505, 838.969), new VSC(195, 2.219, 323.505), new VSC(187, 6.086, 742.99), new VSC(184, 6.28, 543.918), new VSC(171, 5.417, 199.072), new VSC(131, 0.626, 728.763), new VSC(115, 0.68, 846.083), new VSC(115, 5.286, 2118.764), new VSC(108, 4.493, 956.289), new VSC(80, 5.82, 1045.15), new VSC(72, 5.34, 942.06), new VSC(70, 5.97, 532.87), new VSC(67, 5.73, 21.34), new VSC(66, 0.13, 526.51), new VSC(65, 6.09, 1581.96), new VSC(59, 0.59, 1155.36), new VSC(58, 0.99, 1596.19), new VSC(57, 5.97, 1169.59), new VSC(57, 1.41, 533.62), new VSC(55, 5.43, 10.29), new VSC(52, 5.73, 117.32), new VSC(52, 0.23, 1368.66), new VSC(50, 6.08, 525.76), new VSC(47, 3.63, 1478.87), new VSC(47, 0.51, 1265.57), new VSC(40, 4.16, 1692.17), new VSC(34, 0.1, 302.16), new VSC(33, 5.04, 220.41), new VSC(32, 5.37, 508.35), new VSC(29, 5.42, 1272.68), new VSC(29, 3.36, 4.67), new VSC(29, 0.76, 88.87), new VSC(25, 1.61, 831.86)]; +const g_L2JupiterCoefficients = [new VSC(47234, 4.32148, 7.11355), new VSC(38966, 0, 0), new VSC(30629, 2.93021, 529.69097), new VSC(3189, 1.055, 522.5774), new VSC(2729, 4.8455, 536.8045), new VSC(2723, 3.4141, 1059.3819), new VSC(1721, 4.1873, 14.2271), new VSC(383, 5.768, 419.485), new VSC(378, 0.76, 515.464), new VSC(367, 6.055, 103.093), new VSC(337, 3.786, 3.181), new VSC(308, 0.694, 206.186), new VSC(218, 3.814, 1589.073), new VSC(199, 5.34, 1066.495), new VSC(197, 2.484, 3.932), new VSC(156, 1.406, 1052.268), new VSC(146, 3.814, 639.897), new VSC(142, 1.634, 426.598), new VSC(130, 5.837, 412.371), new VSC(117, 1.414, 625.67), new VSC(97, 4.03, 110.21), new VSC(91, 1.11, 95.98), new VSC(87, 2.52, 632.78), new VSC(79, 4.64, 543.92), new VSC(72, 2.22, 735.88), new VSC(58, 0.83, 199.07), new VSC(57, 3.12, 213.3), new VSC(49, 1.67, 309.28), new VSC(40, 4.02, 21.34), new VSC(40, 0.62, 323.51), new VSC(36, 2.33, 728.76), new VSC(29, 3.61, 10.29), new VSC(28, 3.24, 838.97), new VSC(26, 4.5, 742.99), new VSC(26, 2.51, 1162.47), new VSC(25, 1.22, 1045.15), new VSC(24, 3.01, 956.29), new VSC(19, 4.29, 532.87), new VSC(18, 0.81, 508.35), new VSC(17, 4.2, 2118.76), new VSC(17, 1.83, 526.51), new VSC(15, 5.81, 1596.19), new VSC(15, 0.68, 942.06), new VSC(15, 4, 117.32), new VSC(14, 5.95, 316.39), new VSC(14, 1.8, 302.16), new VSC(13, 2.52, 88.87), new VSC(13, 4.37, 1169.59), new VSC(11, 4.44, 525.76), new VSC(10, 1.72, 1581.96), new VSC(9, 2.18, 1155.36), new VSC(9, 3.29, 220.41), new VSC(9, 3.32, 831.86), new VSC(8, 5.76, 846.08), new VSC(8, 2.71, 533.62), new VSC(7, 2.18, 1265.57), new VSC(6, 0.5, 949.18)]; +const g_L3JupiterCoefficients = [new VSC(6502, 2.5986, 7.1135), new VSC(1357, 1.3464, 529.691), new VSC(471, 2.475, 14.227), new VSC(417, 3.245, 536.805), new VSC(353, 2.974, 522.577), new VSC(155, 2.076, 1059.382), new VSC(87, 2.51, 515.46), new VSC(44, 0, 0), new VSC(34, 3.83, 1066.5), new VSC(28, 2.45, 206.19), new VSC(24, 1.28, 412.37), new VSC(23, 2.98, 543.92), new VSC(20, 2.1, 639.9), new VSC(20, 1.4, 419.48), new VSC(19, 1.59, 103.09), new VSC(17, 2.3, 21.34), new VSC(17, 2.6, 1589.07), new VSC(16, 3.15, 625.67), new VSC(16, 3.36, 1052.27), new VSC(13, 2.76, 95.98), new VSC(13, 2.54, 199.07), new VSC(13, 6.27, 426.6), new VSC(9, 1.76, 10.29), new VSC(9, 2.27, 110.21), new VSC(7, 3.43, 309.28), new VSC(7, 4.04, 728.76), new VSC(6, 2.52, 508.35), new VSC(5, 2.91, 1045.15), new VSC(5, 5.25, 323.51), new VSC(4, 4.3, 88.87), new VSC(4, 3.52, 302.16), new VSC(4, 4.09, 735.88), new VSC(3, 1.43, 956.29), new VSC(3, 4.36, 1596.19), new VSC(3, 1.25, 213.3), new VSC(3, 5.02, 838.97), new VSC(3, 2.24, 117.32), new VSC(2, 2.9, 742.99), new VSC(2, 2.36, 942.06)]; +const g_L4JupiterCoefficients = [new VSC(669, 0.853, 7.114), new VSC(114, 3.142, 0), new VSC(100, 0.743, 14.227), new VSC(50, 1.65, 536.8), new VSC(44, 5.82, 529.69), new VSC(32, 4.86, 522.58), new VSC(15, 4.29, 515.46), new VSC(9, 0.71, 1059.38), new VSC(5, 1.3, 543.92), new VSC(4, 2.32, 1066.5), new VSC(4, 0.48, 21.34), new VSC(3, 3, 412.37), new VSC(2, 0.4, 639.9), new VSC(2, 4.26, 199.07), new VSC(2, 4.91, 625.67), new VSC(2, 4.26, 206.19), new VSC(1, 5.26, 1052.27), new VSC(1, 4.72, 95.98), new VSC(1, 1.29, 1589.07)]; +const g_L5JupiterCoefficients = [new VSC(50, 5.26, 7.11), new VSC(16, 5.25, 14.23), new VSC(4, 0.01, 536.8), new VSC(2, 1.1, 522.58), new VSC(1, 3.14, 0)]; +const g_B0JupiterCoefficients = [new VSC(2268616, 3.5585261, 529.6909651), new VSC(110090, 0, 0), new VSC(109972, 3.908093, 1059.38193), new VSC(8101, 3.6051, 522.5774), new VSC(6438, 0.3063, 536.8045), new VSC(6044, 4.2588, 1589.0729), new VSC(1107, 2.9853, 1162.4747), new VSC(944, 1.675, 426.598), new VSC(942, 2.936, 1052.268), new VSC(894, 1.754, 7.114), new VSC(836, 5.179, 103.093), new VSC(767, 2.155, 632.784), new VSC(684, 3.678, 213.299), new VSC(629, 0.643, 1066.495), new VSC(559, 0.014, 846.083), new VSC(532, 2.703, 110.206), new VSC(464, 1.173, 949.176), new VSC(431, 2.608, 419.485), new VSC(351, 4.611, 2118.764), new VSC(132, 4.778, 742.99), new VSC(123, 3.35, 1692.166), new VSC(116, 1.387, 323.505), new VSC(115, 5.049, 316.392), new VSC(104, 3.701, 515.464), new VSC(103, 2.319, 1478.867), new VSC(102, 3.153, 1581.959)]; +const g_B1JupiterCoefficients = [new VSC(177352, 5.701665, 529.690965), new VSC(3230, 5.7794, 1059.3819), new VSC(3081, 5.4746, 522.5774), new VSC(2212, 4.7348, 536.8045), new VSC(1694, 3.1416, 0), new VSC(346, 4.746, 1052.268), new VSC(234, 5.189, 1066.495), new VSC(196, 6.186, 7.114), new VSC(150, 3.927, 1589.073), new VSC(114, 3.439, 632.784), new VSC(97, 2.91, 949.18), new VSC(82, 5.08, 1162.47), new VSC(77, 2.51, 103.09), new VSC(77, 0.61, 419.48), new VSC(74, 5.5, 515.46), new VSC(61, 5.45, 213.3), new VSC(50, 3.95, 735.88), new VSC(46, 0.54, 110.21), new VSC(45, 1.9, 846.08), new VSC(37, 4.7, 543.92), new VSC(36, 6.11, 316.39), new VSC(32, 4.92, 1581.96)]; +const g_B2JupiterCoefficients = [new VSC(8094, 1.4632, 529.691), new VSC(813, 3.1416, 0), new VSC(742, 0.957, 522.577), new VSC(399, 2.899, 536.805), new VSC(342, 1.447, 1059.382), new VSC(74, 0.41, 1052.27), new VSC(46, 3.48, 1066.5), new VSC(30, 1.93, 1589.07), new VSC(29, 0.99, 515.46), new VSC(23, 4.27, 7.11), new VSC(14, 2.92, 543.92), new VSC(12, 5.22, 632.78), new VSC(11, 4.88, 949.18), new VSC(6, 6.21, 1045.15)]; +const g_B3JupiterCoefficients = [new VSC(252, 3.381, 529.691), new VSC(122, 2.733, 522.577), new VSC(49, 1.04, 536.8), new VSC(11, 2.31, 1052.27), new VSC(8, 2.77, 515.46), new VSC(7, 4.25, 1059.38), new VSC(6, 1.78, 1066.5), new VSC(4, 1.13, 543.92), new VSC(3, 3.14, 0)]; +const g_B4JupiterCoefficients = [new VSC(15, 4.53, 522.58), new VSC(5, 4.47, 529.69), new VSC(4, 5.44, 536.8), new VSC(3, 0, 0), new VSC(2, 4.52, 515.46), new VSC(1, 4.2, 1052.27)]; +const g_B5JupiterCoefficients = [new VSC(1, 0.09, 522.58)]; +const g_R0JupiterCoefficients = [new VSC(520887429, 0, 0), new VSC(25209327, 3.4910864, 529.69096509), new VSC(610600, 3.841154, 1059.38193), new VSC(282029, 2.574199, 632.783739), new VSC(187647, 2.075904, 522.577418), new VSC(86793, 0.71001, 419.48464), new VSC(72063, 0.21466, 536.80451), new VSC(65517, 5.97996, 316.39187), new VSC(30135, 2.16132, 949.17561), new VSC(29135, 1.67759, 103.09277), new VSC(23947, 0.27458, 7.11355), new VSC(23453, 3.54023, 735.87651), new VSC(22284, 4.19363, 1589.0729), new VSC(13033, 2.96043, 1162.4747), new VSC(12749, 2.7155, 1052.26838), new VSC(9703, 1.9067, 206.1855), new VSC(9161, 4.4135, 213.2991), new VSC(7895, 2.4791, 426.5982), new VSC(7058, 2.1818, 1265.5675), new VSC(6138, 6.2642, 846.0828), new VSC(5477, 5.6573, 639.8973), new VSC(4170, 2.0161, 515.4639), new VSC(4137, 2.7222, 625.6702), new VSC(3503, 0.5653, 1066.4955), new VSC(2617, 2.0099, 1581.9593), new VSC(2500, 4.5518, 838.9693), new VSC(2128, 6.1275, 742.9901), new VSC(1912, 0.8562, 412.3711), new VSC(1611, 3.0887, 1368.6603), new VSC(1479, 2.6803, 1478.8666), new VSC(1231, 1.8904, 323.5054), new VSC(1217, 1.8017, 110.2063), new VSC(1015, 1.3867, 454.9094), new VSC(999, 2.872, 309.278), new VSC(961, 4.549, 2118.764), new VSC(886, 4.148, 533.623), new VSC(821, 1.593, 1898.351), new VSC(812, 5.941, 909.819), new VSC(777, 3.677, 728.763), new VSC(727, 3.988, 1155.361), new VSC(655, 2.791, 1685.052), new VSC(654, 3.382, 1692.166), new VSC(621, 4.823, 956.289), new VSC(615, 2.276, 942.062), new VSC(562, 0.081, 543.918), new VSC(542, 0.284, 525.759)]; +const g_R1JupiterCoefficients = [new VSC(1271802, 2.6493751, 529.6909651), new VSC(61662, 3.00076, 1059.38193), new VSC(53444, 3.89718, 522.57742), new VSC(41390, 0, 0), new VSC(31185, 4.88277, 536.80451), new VSC(11847, 2.4133, 419.48464), new VSC(9166, 4.7598, 7.1135), new VSC(3404, 3.3469, 1589.0729), new VSC(3203, 5.2108, 735.8765), new VSC(3176, 2.793, 103.0928), new VSC(2806, 3.7422, 515.4639), new VSC(2677, 4.3305, 1052.2684), new VSC(2600, 3.6344, 206.1855), new VSC(2412, 1.4695, 426.5982), new VSC(2101, 3.9276, 639.8973), new VSC(1646, 4.4163, 1066.4955), new VSC(1641, 4.4163, 625.6702), new VSC(1050, 3.1611, 213.2991), new VSC(1025, 2.5543, 412.3711), new VSC(806, 2.678, 632.784), new VSC(741, 2.171, 1162.475), new VSC(677, 6.25, 838.969), new VSC(567, 4.577, 742.99), new VSC(485, 2.469, 949.176), new VSC(469, 4.71, 543.918), new VSC(445, 0.403, 323.505), new VSC(416, 5.368, 728.763), new VSC(402, 4.605, 309.278), new VSC(347, 4.681, 14.227), new VSC(338, 3.168, 956.289), new VSC(261, 5.343, 846.083), new VSC(247, 3.923, 942.062), new VSC(220, 4.842, 1368.66), new VSC(203, 5.6, 1155.361), new VSC(200, 4.439, 1045.155), new VSC(197, 3.706, 2118.764), new VSC(196, 3.759, 199.072), new VSC(184, 4.265, 95.979), new VSC(180, 4.402, 532.872), new VSC(170, 4.846, 526.51), new VSC(146, 6.13, 533.623), new VSC(133, 1.322, 110.206), new VSC(132, 4.512, 525.759)]; +const g_R2JupiterCoefficients = [new VSC(79645, 1.35866, 529.69097), new VSC(8252, 5.7777, 522.5774), new VSC(7030, 3.2748, 536.8045), new VSC(5314, 1.8384, 1059.3819), new VSC(1861, 2.9768, 7.1135), new VSC(964, 5.48, 515.464), new VSC(836, 4.199, 419.485), new VSC(498, 3.142, 0), new VSC(427, 2.228, 639.897), new VSC(406, 3.783, 1066.495), new VSC(377, 2.242, 1589.073), new VSC(363, 5.368, 206.186), new VSC(342, 6.099, 1052.268), new VSC(339, 6.127, 625.67), new VSC(333, 0.003, 426.598), new VSC(280, 4.262, 412.371), new VSC(257, 0.963, 632.784), new VSC(230, 0.705, 735.877), new VSC(201, 3.069, 543.918), new VSC(200, 4.429, 103.093), new VSC(139, 2.932, 14.227), new VSC(114, 0.787, 728.763), new VSC(95, 1.7, 838.97), new VSC(86, 5.14, 323.51), new VSC(83, 0.06, 309.28), new VSC(80, 2.98, 742.99), new VSC(75, 1.6, 956.29), new VSC(70, 1.51, 213.3), new VSC(67, 5.47, 199.07), new VSC(62, 6.1, 1045.15), new VSC(56, 0.96, 1162.47), new VSC(52, 5.58, 942.06), new VSC(50, 2.72, 532.87), new VSC(45, 5.52, 508.35), new VSC(44, 0.27, 526.51), new VSC(40, 5.95, 95.98)]; +const g_R3JupiterCoefficients = [new VSC(3519, 6.058, 529.691), new VSC(1073, 1.6732, 536.8045), new VSC(916, 1.413, 522.577), new VSC(342, 0.523, 1059.382), new VSC(255, 1.196, 7.114), new VSC(222, 0.952, 515.464), new VSC(90, 3.14, 0), new VSC(69, 2.27, 1066.5), new VSC(58, 1.41, 543.92), new VSC(58, 0.53, 639.9), new VSC(51, 5.98, 412.37), new VSC(47, 1.58, 625.67), new VSC(43, 6.12, 419.48), new VSC(37, 1.18, 14.23), new VSC(34, 1.67, 1052.27), new VSC(34, 0.85, 206.19), new VSC(31, 1.04, 1589.07), new VSC(30, 4.63, 426.6), new VSC(21, 2.5, 728.76), new VSC(15, 0.89, 199.07), new VSC(14, 0.96, 508.35), new VSC(13, 1.5, 1045.15), new VSC(12, 2.61, 735.88), new VSC(12, 3.56, 323.51), new VSC(11, 1.79, 309.28), new VSC(11, 6.28, 956.29), new VSC(10, 6.26, 103.09), new VSC(9, 3.45, 838.97)]; +const g_R4JupiterCoefficients = [new VSC(129, 0.084, 536.805), new VSC(113, 4.249, 529.691), new VSC(83, 3.3, 522.58), new VSC(38, 2.73, 515.46), new VSC(27, 5.69, 7.11), new VSC(18, 5.4, 1059.38), new VSC(13, 6.02, 543.92), new VSC(9, 0.77, 1066.5), new VSC(8, 5.68, 14.23), new VSC(7, 1.43, 412.37), new VSC(6, 5.12, 639.9), new VSC(5, 3.34, 625.67), new VSC(3, 3.4, 1052.27), new VSC(3, 4.16, 728.76), new VSC(3, 2.9, 426.6)]; +const g_R5JupiterCoefficients = [new VSC(11, 4.75, 536.8), new VSC(4, 5.92, 522.58), new VSC(2, 5.57, 515.46), new VSC(2, 4.3, 543.92), new VSC(2, 3.69, 7.11), new VSC(2, 4.13, 1059.38), new VSC(2, 5.49, 1066.5)]; + + + +// CAAJupiter + +export function CAAJupiter() { } + +CAAJupiter.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0JupiterCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0JupiterCoefficients[i].a * Math.cos(g_L0JupiterCoefficients[i].b + g_L0JupiterCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1JupiterCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1JupiterCoefficients[i].a * Math.cos(g_L1JupiterCoefficients[i].b + g_L1JupiterCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2JupiterCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2JupiterCoefficients[i].a * Math.cos(g_L2JupiterCoefficients[i].b + g_L2JupiterCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3JupiterCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3JupiterCoefficients[i].a * Math.cos(g_L3JupiterCoefficients[i].b + g_L3JupiterCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4JupiterCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4JupiterCoefficients[i].a * Math.cos(g_L4JupiterCoefficients[i].b + g_L4JupiterCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5JupiterCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5JupiterCoefficients[i].a * Math.cos(g_L5JupiterCoefficients[i].b + g_L5JupiterCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAJupiter.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nB0Coefficients = g_B0JupiterCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0JupiterCoefficients[i].a * Math.cos(g_B0JupiterCoefficients[i].b + g_B0JupiterCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1JupiterCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1JupiterCoefficients[i].a * Math.cos(g_B1JupiterCoefficients[i].b + g_B1JupiterCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2JupiterCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2JupiterCoefficients[i].a * Math.cos(g_B2JupiterCoefficients[i].b + g_B2JupiterCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3JupiterCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3JupiterCoefficients[i].a * Math.cos(g_B3JupiterCoefficients[i].b + g_B3JupiterCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4JupiterCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4JupiterCoefficients[i].a * Math.cos(g_B4JupiterCoefficients[i].b + g_B4JupiterCoefficients[i].c * rho); + } + var nB5Coefficients = g_B5JupiterCoefficients.length; + var B5 = 0; + for (i = 0; i < nB5Coefficients; i++) { + B5 += g_B5JupiterCoefficients[i].a * Math.cos(g_B5JupiterCoefficients[i].b + g_B5JupiterCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4 + B5 * rho5) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAJupiter.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nR0Coefficients = g_R0JupiterCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0JupiterCoefficients[i].a * Math.cos(g_R0JupiterCoefficients[i].b + g_R0JupiterCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1JupiterCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1JupiterCoefficients[i].a * Math.cos(g_R1JupiterCoefficients[i].b + g_R1JupiterCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2JupiterCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2JupiterCoefficients[i].a * Math.cos(g_R2JupiterCoefficients[i].b + g_R2JupiterCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3JupiterCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3JupiterCoefficients[i].a * Math.cos(g_R3JupiterCoefficients[i].b + g_R3JupiterCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4JupiterCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4JupiterCoefficients[i].a * Math.cos(g_R4JupiterCoefficients[i].b + g_R4JupiterCoefficients[i].c * rho); + } + var nR5Coefficients = g_R5JupiterCoefficients.length; + var R5 = 0; + for (i = 0; i < nR5Coefficients; i++) { + R5 += g_R5JupiterCoefficients[i].a * Math.cos(g_R5JupiterCoefficients[i].b + g_R5JupiterCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4 + R5 * rho5) / 100000000; +}; + +var CAAJupiter$ = {}; + +registerType("CAAJupiter", [CAAJupiter, CAAJupiter$, null]); diff --git a/engine/esm/astrocalc/kepler.js b/engine/esm/astrocalc/kepler.js new file mode 100644 index 00000000..d77da4ba --- /dev/null +++ b/engine/esm/astrocalc/kepler.js @@ -0,0 +1,71 @@ +// Originally `AAKEPLER.CPP` +// "Purpose: Implementation for the algorithms which solve Kepler's equation" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { CT } from "./coordinate_transformation.js"; + + +// CAAKepler + +export function CAAKepler() { } + +CAAKepler.calculate = function (M, e) { + return CAAKepler.calculateIter(M, e, 53); +}; + +CAAKepler.calculateIter = function (M, e, nIterations) { + M = CT.d2R(M); + var PI = CT.PI(); + var F = 1; + if (M < 0) { + F = -1; + } + M = Math.abs(M) / (2 * PI); + M = (M - ss.truncate(M)) * 2 * PI * F; + if (M < 0) { + M += 2 * PI; + } + F = 1; + if (M > PI) { + F = -1; + } + if (M > PI) { + M = 2 * PI - M; + } + var E = PI / 2; + var scale = PI / 4; + for (var i = 0; i < nIterations; i++) { + var R = E - e * Math.sin(E); + if (M > R) { + E += scale; + } + else { + E -= scale; + } + scale /= 2; + } + return CT.r2D(E) * F; +}; + +var CAAKepler$ = {}; + +registerType("CAAKepler", [CAAKepler, CAAKepler$, null]); diff --git a/engine/esm/astrocalc/mars.js b/engine/esm/astrocalc/mars.js new file mode 100644 index 00000000..e1d30af1 --- /dev/null +++ b/engine/esm/astrocalc/mars.js @@ -0,0 +1,165 @@ +// Originally `AAMARS.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Uranus [sic]" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0MarsCoefficients = [new VSC(620347712, 0, 0), new VSC(18656368, 5.050371, 3340.6124267), new VSC(1108217, 5.4009984, 6681.2248534), new VSC(91798, 5.75479, 10021.83728), new VSC(27745, 5.9705, 3.52312), new VSC(12316, 0.84956, 2810.92146), new VSC(10610, 2.93959, 2281.2305), new VSC(8927, 4.157, 0.0173), new VSC(8716, 6.1101, 13362.4497), new VSC(7775, 3.3397, 5621.8429), new VSC(6798, 0.3646, 398.149), new VSC(4161, 0.2281, 2942.4634), new VSC(3575, 1.6619, 2544.3144), new VSC(3075, 0.857, 191.4483), new VSC(2938, 6.0789, 0.0673), new VSC(2628, 0.6481, 3337.0893), new VSC(2580, 0.03, 3344.1355), new VSC(2389, 5.039, 796.298), new VSC(1799, 0.6563, 529.691), new VSC(1546, 2.9158, 1751.5395), new VSC(1528, 1.1498, 6151.5339), new VSC(1286, 3.068, 2146.1654), new VSC(1264, 3.6228, 5092.152), new VSC(1025, 3.6933, 8962.4553), new VSC(892, 0.183, 16703.062), new VSC(859, 2.401, 2914.014), new VSC(833, 4.495, 3340.63), new VSC(833, 2.464, 3340.595), new VSC(749, 3.822, 155.42), new VSC(724, 0.675, 3738.761), new VSC(713, 3.663, 1059.382), new VSC(655, 0.489, 3127.313), new VSC(636, 2.922, 8432.764), new VSC(553, 4.475, 1748.016), new VSC(550, 3.81, 0.98), new VSC(472, 3.625, 1194.447), new VSC(426, 0.554, 6283.076), new VSC(415, 0.497, 213.299), new VSC(312, 0.999, 6677.702), new VSC(307, 0.381, 6684.748), new VSC(302, 4.486, 3532.061), new VSC(299, 2.783, 6254.627), new VSC(293, 4.221, 20.775), new VSC(284, 5.769, 3149.164), new VSC(281, 5.882, 1349.867), new VSC(274, 0.542, 3340.545), new VSC(274, 0.134, 3340.68), new VSC(239, 5.372, 4136.91), new VSC(236, 5.755, 3333.499), new VSC(231, 1.282, 3870.303), new VSC(221, 3.505, 382.897), new VSC(204, 2.821, 1221.849), new VSC(193, 3.357, 3.59), new VSC(189, 1.491, 9492.146), new VSC(179, 1.006, 951.718), new VSC(174, 2.414, 553.569), new VSC(172, 0.439, 5486.778), new VSC(160, 3.949, 4562.461), new VSC(144, 1.419, 135.065), new VSC(140, 3.326, 2700.715), new VSC(138, 4.301, 7.114), new VSC(131, 4.045, 12303.068), new VSC(128, 2.208, 1592.596), new VSC(128, 1.807, 5088.629), new VSC(117, 3.128, 7903.073), new VSC(113, 3.701, 1589.073), new VSC(110, 1.052, 242.729), new VSC(105, 0.785, 8827.39), new VSC(100, 3.243, 11773.377)]; +const g_L1MarsCoefficients = [new VSC(334085627474, 0, 0), new VSC(1458227, 3.6042605, 3340.6124267), new VSC(164901, 3.926313, 6681.224853), new VSC(19963, 4.26594, 10021.83728), new VSC(3452, 4.7321, 3.5231), new VSC(2485, 4.6128, 13362.4497), new VSC(842, 4.459, 2281.23), new VSC(538, 5.016, 398.149), new VSC(521, 4.994, 3344.136), new VSC(433, 2.561, 191.448), new VSC(430, 5.316, 155.42), new VSC(382, 3.539, 796.298), new VSC(314, 4.963, 16703.062), new VSC(283, 3.16, 2544.314), new VSC(206, 4.569, 2146.165), new VSC(169, 1.329, 3337.089), new VSC(158, 4.185, 1751.54), new VSC(134, 2.233, 0.98), new VSC(134, 5.974, 1748.016), new VSC(118, 6.024, 6151.534), new VSC(117, 2.213, 1059.382), new VSC(114, 2.129, 1194.447), new VSC(114, 5.428, 3738.761), new VSC(91, 1.1, 1349.87), new VSC(85, 3.91, 553.57), new VSC(83, 5.3, 6684.75), new VSC(81, 4.43, 529.69), new VSC(80, 2.25, 8962.46), new VSC(73, 2.5, 951.72), new VSC(73, 5.84, 242.73), new VSC(71, 3.86, 2914.01), new VSC(68, 5.02, 382.9), new VSC(65, 1.02, 3340.6), new VSC(65, 3.05, 3340.63), new VSC(62, 4.15, 3149.16), new VSC(57, 3.89, 4136.91), new VSC(48, 4.87, 213.3), new VSC(48, 1.18, 3333.5), new VSC(47, 1.31, 3185.19), new VSC(41, 0.71, 1592.6), new VSC(40, 2.73, 7.11), new VSC(40, 5.32, 20043.67), new VSC(33, 5.41, 6283.08), new VSC(28, 0.05, 9492.15), new VSC(27, 3.89, 1221.85), new VSC(27, 5.11, 2700.72)]; +const g_L2MarsCoefficients = [new VSC(58016, 2.04979, 3340.61243), new VSC(54188, 0, 0), new VSC(13908, 2.45742, 6681.22485), new VSC(2465, 2.8, 10021.8373), new VSC(398, 3.141, 13362.45), new VSC(222, 3.194, 3.523), new VSC(121, 0.543, 155.42), new VSC(62, 3.49, 16703.06), new VSC(54, 3.54, 3344.14), new VSC(34, 6, 2281.23), new VSC(32, 4.14, 191.45), new VSC(30, 2, 796.3), new VSC(23, 4.33, 242.73), new VSC(22, 3.45, 398.15), new VSC(20, 5.42, 553.57), new VSC(16, 0.66, 0.98), new VSC(16, 6.11, 2146.17), new VSC(16, 1.22, 1748.02), new VSC(15, 6.1, 3185.19), new VSC(14, 4.02, 951.72), new VSC(14, 2.62, 1349.87), new VSC(13, 0.6, 1194.45), new VSC(12, 3.86, 6684.75), new VSC(11, 4.72, 2544.31), new VSC(10, 0.25, 382.9), new VSC(9, 0.68, 1059.38), new VSC(9, 3.83, 20043.67), new VSC(9, 3.88, 3738.76), new VSC(8, 5.46, 1751.54), new VSC(7, 2.58, 3149.16), new VSC(7, 2.38, 4136.91), new VSC(6, 5.48, 1592.6), new VSC(6, 2.34, 3097.88)]; +const g_L3MarsCoefficients = [new VSC(1482, 0.4443, 3340.6124), new VSC(662, 0.885, 6681.225), new VSC(188, 1.288, 10021.837), new VSC(41, 1.65, 13362.45), new VSC(26, 0, 0), new VSC(23, 2.05, 155.42), new VSC(10, 1.58, 3.52), new VSC(8, 2, 16703.06), new VSC(5, 2.82, 242.73), new VSC(4, 2.02, 3344.14), new VSC(3, 4.59, 3185.19), new VSC(3, 0.65, 553.57)]; +const g_L4MarsCoefficients = [new VSC(114, 3.1416, 0), new VSC(29, 5.64, 6681.22), new VSC(24, 5.14, 3340.61), new VSC(11, 6.03, 10021.84), new VSC(3, 0.13, 13362.45), new VSC(3, 3.56, 155.42), new VSC(1, 0.49, 16703.06), new VSC(1, 1.32, 242.73)]; +const g_L5MarsCoefficients = [new VSC(1, 3.14, 0), new VSC(1, 4.04, 6681.22)]; +const g_B0MarsCoefficients = [new VSC(3197135, 3.7683204, 3340.6124267), new VSC(298033, 4.10617, 6681.224853), new VSC(289105, 0, 0), new VSC(31366, 4.44651, 10021.83728), new VSC(3484, 4.7881, 13362.4497), new VSC(443, 5.026, 3344.136), new VSC(443, 5.652, 3337.089), new VSC(399, 5.131, 16703.062), new VSC(293, 3.793, 2281.23), new VSC(182, 6.136, 6151.534), new VSC(163, 4.264, 529.691), new VSC(160, 2.232, 1059.382), new VSC(149, 2.165, 5621.843), new VSC(143, 1.182, 3340.595), new VSC(143, 3.213, 3340.63), new VSC(139, 2.418, 8962.455)]; +const g_B1MarsCoefficients = [new VSC(350069, 5.368478, 3340.612427), new VSC(14116, 3.14159, 0), new VSC(9671, 5.4788, 6681.2249), new VSC(1472, 3.2021, 10021.8373), new VSC(426, 3.408, 13362.45), new VSC(102, 0.776, 3337.089), new VSC(79, 3.72, 16703.06), new VSC(33, 3.46, 5621.84), new VSC(26, 2.48, 2281.23)]; +const g_B2MarsCoefficients = [new VSC(16727, 0.60221, 3340.61243), new VSC(4987, 4.1416, 0), new VSC(302, 3.559, 6681.225), new VSC(26, 1.9, 13362.45), new VSC(21, 0.92, 10021.84), new VSC(12, 2.24, 3337.09), new VSC(8, 2.25, 16703.06)]; +const g_B3MarsCoefficients = [new VSC(607, 1.981, 3340.612), new VSC(43, 0, 0), new VSC(14, 1.8, 6681.22), new VSC(3, 3.45, 10021.84)]; +const g_B4MarsCoefficients = [new VSC(13, 0, 0), new VSC(11, 3.46, 3340.61), new VSC(1, 0.5, 6681.22)]; +const g_R0MarsCoefficients = [new VSC(153033488, 0, 0), new VSC(14184953, 3.47971284, 3340.6124267), new VSC(660776, 3.817834, 6681.224853), new VSC(46179, 4.15595, 10021.83728), new VSC(8110, 5.5596, 2810.9215), new VSC(7485, 1.7724, 5621.8429), new VSC(5523, 1.3644, 2281.2305), new VSC(3825, 4.4941, 13362.4497), new VSC(2484, 4.9255, 2942.4634), new VSC(2307, 0.0908, 2544.3144), new VSC(1999, 5.3606, 3337.0893), new VSC(1960, 4.7425, 3344.1355), new VSC(1167, 2.1126, 5092.152), new VSC(1103, 5.0091, 398.149), new VSC(992, 5.839, 6151.534), new VSC(899, 4.408, 529.691), new VSC(807, 2.102, 1059.382), new VSC(798, 3.448, 796.298), new VSC(741, 1.499, 2146.165), new VSC(726, 1.245, 8432.764), new VSC(692, 2.134, 8962.455), new VSC(633, 0.894, 3340.595), new VSC(633, 2.924, 3340.63), new VSC(630, 1.287, 1751.54), new VSC(574, 0.829, 2914.014), new VSC(526, 5.383, 3738.761), new VSC(473, 5.199, 3127.313), new VSC(348, 4.832, 16703.062), new VSC(284, 2.907, 3532.061), new VSC(280, 5.257, 6283.076), new VSC(276, 1.218, 6254.627), new VSC(275, 2.908, 1748.016), new VSC(270, 3.764, 5884.927), new VSC(239, 2.037, 1194.447), new VSC(234, 5.105, 5486.778), new VSC(228, 3.255, 6872.673), new VSC(223, 4.199, 3149.164), new VSC(219, 5.583, 191.448), new VSC(208, 5.255, 3340.545), new VSC(208, 4.846, 3340.68), new VSC(186, 5.699, 6677.702), new VSC(183, 5.081, 6684.748), new VSC(179, 4.184, 3333.499), new VSC(176, 5.953, 3870.303), new VSC(164, 3.799, 4136.91)]; +const g_R1MarsCoefficients = [new VSC(1107433, 2.0325052, 3340.6124267), new VSC(103176, 2.370718, 6681.224853), new VSC(12877, 0, 0), new VSC(10816, 2.70888, 10021.83728), new VSC(1195, 3.047, 13362.4497), new VSC(439, 2.888, 2281.23), new VSC(396, 3.423, 3344.136), new VSC(183, 1.584, 2544.314), new VSC(136, 3.385, 16703.062), new VSC(128, 6.043, 3337.089), new VSC(128, 0.63, 1059.382), new VSC(127, 1.954, 796.298), new VSC(118, 2.998, 2146.165), new VSC(88, 3.42, 398.15), new VSC(83, 3.86, 3738.76), new VSC(76, 4.45, 6151.53), new VSC(72, 2.76, 529.69), new VSC(67, 2.55, 1751.54), new VSC(66, 4.41, 1748.02), new VSC(58, 0.54, 1194.45), new VSC(54, 0.68, 8962.46), new VSC(51, 3.73, 6684.75), new VSC(49, 5.73, 3340.6), new VSC(49, 1.48, 3340.63), new VSC(48, 2.58, 3149.16), new VSC(48, 2.29, 2914.01), new VSC(39, 2.32, 4136.91)]; +const g_R2MarsCoefficients = [new VSC(44242, 0.47931, 3340.61243), new VSC(8138, 0.87, 6681.2249), new VSC(1275, 1.2259, 10021.8373), new VSC(187, 1.573, 13362.45), new VSC(52, 3.14, 0), new VSC(41, 1.97, 3344.14), new VSC(27, 1.92, 16703.06), new VSC(18, 4.43, 2281.23), new VSC(12, 4.53, 3185.19), new VSC(10, 5.39, 1059.38), new VSC(10, 0.42, 796.3)]; +const g_R3MarsCoefficients = [new VSC(1113, 5.1499, 3340.6124), new VSC(424, 5.613, 6681.225), new VSC(100, 5.997, 10021.837), new VSC(20, 0.08, 13362.45), new VSC(5, 3.14, 0), new VSC(3, 0.43, 16703.06)]; +const g_R4MarsCoefficients = [new VSC(20, 3.58, 3340.61), new VSC(16, 4.05, 6681.22), new VSC(6, 4.46, 10021.84), new VSC(2, 4.84, 13362.45)]; + + +// CAAMars + +export function CAAMars() { } + +CAAMars.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0MarsCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0MarsCoefficients[i].a * Math.cos(g_L0MarsCoefficients[i].b + g_L0MarsCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1MarsCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1MarsCoefficients[i].a * Math.cos(g_L1MarsCoefficients[i].b + g_L1MarsCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2MarsCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2MarsCoefficients[i].a * Math.cos(g_L2MarsCoefficients[i].b + g_L2MarsCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3MarsCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3MarsCoefficients[i].a * Math.cos(g_L3MarsCoefficients[i].b + g_L3MarsCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4MarsCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4MarsCoefficients[i].a * Math.cos(g_L4MarsCoefficients[i].b + g_L4MarsCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5MarsCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5MarsCoefficients[i].a * Math.cos(g_L5MarsCoefficients[i].b + g_L5MarsCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAMars.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0MarsCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0MarsCoefficients[i].a * Math.cos(g_B0MarsCoefficients[i].b + g_B0MarsCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1MarsCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1MarsCoefficients[i].a * Math.cos(g_B1MarsCoefficients[i].b + g_B1MarsCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2MarsCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2MarsCoefficients[i].a * Math.cos(g_B2MarsCoefficients[i].b + g_B2MarsCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3MarsCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3MarsCoefficients[i].a * Math.cos(g_B3MarsCoefficients[i].b + g_B3MarsCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4MarsCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4MarsCoefficients[i].a * Math.cos(g_B4MarsCoefficients[i].b + g_B4MarsCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAMars.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nR0Coefficients = g_R0MarsCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0MarsCoefficients[i].a * Math.cos(g_R0MarsCoefficients[i].b + g_R0MarsCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1MarsCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1MarsCoefficients[i].a * Math.cos(g_R1MarsCoefficients[i].b + g_R1MarsCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2MarsCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2MarsCoefficients[i].a * Math.cos(g_R2MarsCoefficients[i].b + g_R2MarsCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3MarsCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3MarsCoefficients[i].a * Math.cos(g_R3MarsCoefficients[i].b + g_R3MarsCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4MarsCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4MarsCoefficients[i].a * Math.cos(g_R4MarsCoefficients[i].b + g_R4MarsCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; +}; + +var CAAMars$ = {}; + +registerType("CAAMars", [CAAMars, CAAMars$, null]); diff --git a/engine/esm/astrocalc/mercury.js b/engine/esm/astrocalc/mercury.js new file mode 100644 index 00000000..e5f53dbb --- /dev/null +++ b/engine/esm/astrocalc/mercury.js @@ -0,0 +1,158 @@ +// Originally `AAMERCURY.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Mercury" +// Last update of original: PJN / 12-05-2006 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0MercuryCoefficients = [new VSC(440250710, 0, 0), new VSC(40989415, 1.48302034, 26087.90314157), new VSC(5046294, 4.47785449, 52175.8062831), new VSC(855347, 1.165203, 78263.709425), new VSC(165590, 4.119692, 104351.612566), new VSC(34562, 0.77931, 130439.51571), new VSC(7583, 3.7135, 156527.4188), new VSC(3560, 1.512, 1109.3786), new VSC(1803, 4.1033, 5661.332), new VSC(1726, 0.3583, 182615.322), new VSC(1590, 2.9951, 25028.5212), new VSC(1365, 4.5992, 27197.2817), new VSC(1017, 0.8803, 31749.2352), new VSC(714, 1.541, 24978.525), new VSC(644, 5.303, 21535.95), new VSC(451, 6.05, 51116.424), new VSC(404, 3.282, 208703.225), new VSC(352, 5.242, 20426.571), new VSC(345, 2.792, 15874.618), new VSC(343, 5.765, 955.6), new VSC(339, 5.863, 25558.212), new VSC(325, 1.337, 53285.185), new VSC(273, 2.495, 529.691), new VSC(264, 3.917, 57837.138), new VSC(260, 0.987, 4551.953), new VSC(239, 0.113, 1059.382), new VSC(235, 0.267, 11322.664), new VSC(217, 0.66, 13521.751), new VSC(209, 2.092, 47623.853), new VSC(183, 2.629, 27043.503), new VSC(182, 2.434, 25661.305), new VSC(176, 4.536, 51066.428), new VSC(173, 2.452, 24498.83), new VSC(142, 3.36, 37410.567), new VSC(138, 0.291, 10213.286), new VSC(125, 3.721, 39609.655), new VSC(118, 2.781, 77204.327), new VSC(106, 4.206, 19804.827)]; +const g_L1MercuryCoefficients = [new VSC(2608814706223, 0, 0), new VSC(1126008, 6.2170397, 26087.9031416), new VSC(303471, 3.055655, 52175.806283), new VSC(80538, 6.10455, 78263.70942), new VSC(21245, 2.83532, 104351.61257), new VSC(5592, 5.8268, 130439.5157), new VSC(1472, 2.5185, 156527.4188), new VSC(388, 5.48, 182615.322), new VSC(352, 3.052, 1109.379), new VSC(103, 2.149, 208703.225), new VSC(94, 6.12, 27197.28), new VSC(91, 0, 24978.52), new VSC(52, 5.62, 5661.33), new VSC(44, 4.57, 25028.52), new VSC(28, 3.04, 51066.43), new VSC(27, 5.09, 234791.13)]; +const g_L2MercuryCoefficients = [new VSC(53050, 0, 0), new VSC(16904, 4.69072, 26087.90314), new VSC(7397, 1.3474, 52175.8063), new VSC(3018, 4.4564, 78263.7094), new VSC(1107, 1.264, 104351.6126), new VSC(378, 4.32, 130439.516), new VSC(123, 1.069, 156527.419), new VSC(39, 4.08, 182615.32), new VSC(15, 4.63, 1109.38), new VSC(12, 0.79, 208703.23)]; +const g_L3MercuryCoefficients = [new VSC(188, 0.035, 52175.806), new VSC(142, 3.125, 26087.903), new VSC(97, 3, 78263.71), new VSC(44, 6.02, 104351.61), new VSC(35, 0, 0), new VSC(18, 2.78, 130439.52), new VSC(7, 5.82, 156527.42), new VSC(3, 2.57, 182615.32)]; +const g_L4MercuryCoefficients = [new VSC(114, 3.1416, 0), new VSC(2, 2.03, 26087.9), new VSC(2, 1.42, 78263.71), new VSC(2, 4.5, 52175.81), new VSC(1, 4.5, 104351.61), new VSC(1, 1.27, 130439.52)]; +const g_L5MercuryCoefficients = [new VSC(1, 3.14, 0)]; +const g_B0MercuryCoefficients = [new VSC(11737529, 1.98357499, 26087.90314157), new VSC(2388077, 5.0373896, 52175.8062831), new VSC(1222840, 3.1415927, 0), new VSC(543252, 1.796444, 78263.709425), new VSC(129779, 4.832325, 104351.612566), new VSC(31867, 1.58088, 130439.51571), new VSC(7963, 4.6097, 156527.4188), new VSC(2014, 1.3532, 182615.322), new VSC(514, 4.378, 208703.325), new VSC(209, 2.02, 24978.525), new VSC(208, 4.918, 27197.282), new VSC(132, 1.119, 234791.128), new VSC(121, 1.813, 53285.185), new VSC(100, 5.657, 20426.571)]; +const g_B1MercuryCoefficients = [new VSC(429151, 3.501698, 26087.903142), new VSC(146234, 3.141593, 0), new VSC(22675, 0.01515, 52175.80628), new VSC(10895, 0.4854, 78263.70942), new VSC(6353, 3.4294, 104351.6126), new VSC(2496, 0.1605, 130439.5157), new VSC(860, 3.185, 156527.419), new VSC(278, 6.21, 182615.322), new VSC(86, 2.95, 208703.23), new VSC(28, 0.29, 27197.28), new VSC(26, 5.98, 234791.13)]; +const g_B2MercuryCoefficients = [new VSC(11831, 4.79066, 26087.90314), new VSC(1914, 0, 0), new VSC(1045, 1.2122, 52175.8063), new VSC(266, 4.434, 78263.709), new VSC(170, 1.623, 104351.613), new VSC(96, 4.8, 130439.52), new VSC(45, 1.61, 156527.42), new VSC(18, 4.67, 182615.32), new VSC(7, 1.43, 208703.23)]; +const g_B3MercuryCoefficients = [new VSC(235, 0.354, 26087.903), new VSC(161, 0, 0), new VSC(19, 4.36, 52175.81), new VSC(6, 2.51, 78263.71), new VSC(5, 6.14, 104351.61), new VSC(3, 3.12, 130439.52), new VSC(2, 6.27, 156527.42)]; +const g_B4MercuryCoefficients = [new VSC(4, 1.75, 26087.9), new VSC(1, 3.14, 0)]; +const g_R0MercuryCoefficients = [new VSC(39528272, 0, 0), new VSC(7834132, 6.1923372, 26087.9031416), new VSC(795526, 2.959897, 52175.806283), new VSC(121282, 6.010642, 78263.709425), new VSC(21922, 2.7782, 104351.61257), new VSC(4354, 5.8289, 130439.5157), new VSC(918, 2.597, 156527.419), new VSC(290, 1.424, 25028.521), new VSC(260, 3.028, 27197.282), new VSC(202, 5.647, 182615.322), new VSC(201, 5.592, 31749.235), new VSC(142, 6.253, 24978.525), new VSC(100, 3.734, 21535.95)]; +const g_R1MercuryCoefficients = [new VSC(217348, 4.656172, 26087.903142), new VSC(44142, 1.42386, 52175.80628), new VSC(10094, 4.47466, 78263.70942), new VSC(2433, 1.2423, 104351.6126), new VSC(1624, 0, 0), new VSC(604, 4.293, 130439.516), new VSC(153, 1.061, 156527.419), new VSC(39, 4.11, 182615.32)]; +const g_R2MercuryCoefficients = [new VSC(3118, 3.0823, 26087.9031), new VSC(1245, 6.1518, 52175.8063), new VSC(425, 2.926, 78263.709), new VSC(136, 5.98, 104351.613), new VSC(42, 2.75, 130439.52), new VSC(22, 3.14, 0), new VSC(13, 5.8, 156527.42)]; +const g_R3MercuryCoefficients = [new VSC(33, 1.68, 26087.9), new VSC(24, 4.63, 52175.81), new VSC(12, 1.39, 78263.71), new VSC(5, 4.44, 104351.61), new VSC(2, 1.21, 130439.52)]; + + +// CAAMercury + +export function CAAMercury() { } + +CAAMercury.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0MercuryCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0MercuryCoefficients[i].a * Math.cos(g_L0MercuryCoefficients[i].b + g_L0MercuryCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1MercuryCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1MercuryCoefficients[i].a * Math.cos(g_L1MercuryCoefficients[i].b + g_L1MercuryCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2MercuryCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2MercuryCoefficients[i].a * Math.cos(g_L2MercuryCoefficients[i].b + g_L2MercuryCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3MercuryCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3MercuryCoefficients[i].a * Math.cos(g_L3MercuryCoefficients[i].b + g_L3MercuryCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4MercuryCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4MercuryCoefficients[i].a * Math.cos(g_L4MercuryCoefficients[i].b + g_L4MercuryCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5MercuryCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5MercuryCoefficients[i].a * Math.cos(g_L5MercuryCoefficients[i].b + g_L5MercuryCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAMercury.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0MercuryCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0MercuryCoefficients[i].a * Math.cos(g_B0MercuryCoefficients[i].b + g_B0MercuryCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1MercuryCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1MercuryCoefficients[i].a * Math.cos(g_B1MercuryCoefficients[i].b + g_B1MercuryCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2MercuryCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2MercuryCoefficients[i].a * Math.cos(g_B2MercuryCoefficients[i].b + g_B2MercuryCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3MercuryCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3MercuryCoefficients[i].a * Math.cos(g_B3MercuryCoefficients[i].b + g_B3MercuryCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4MercuryCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4MercuryCoefficients[i].a * Math.cos(g_B4MercuryCoefficients[i].b + g_B4MercuryCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAMercury.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var nR0Coefficients = g_R0MercuryCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0MercuryCoefficients[i].a * Math.cos(g_R0MercuryCoefficients[i].b + g_R0MercuryCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1MercuryCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1MercuryCoefficients[i].a * Math.cos(g_R1MercuryCoefficients[i].b + g_R1MercuryCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2MercuryCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2MercuryCoefficients[i].a * Math.cos(g_R2MercuryCoefficients[i].b + g_R2MercuryCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3MercuryCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3MercuryCoefficients[i].a * Math.cos(g_R3MercuryCoefficients[i].b + g_R3MercuryCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed) / 100000000; +}; + +var CAAMercury$ = {}; + +registerType("CAAMercury", [CAAMercury, CAAMercury$, null]); diff --git a/engine/esm/astrocalc/moon.js b/engine/esm/astrocalc/moon.js new file mode 100644 index 00000000..9517e12e --- /dev/null +++ b/engine/esm/astrocalc/moon.js @@ -0,0 +1,255 @@ +// Originally `AAABERRATION.CPP` +// "Purpose: Implementation for the algorithms which obtain the position of the Moon" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAAEarth } from "./earth.js"; +import { CAANutation } from "./nutation.js"; + + +// MoonCoefficient1 + +export function MoonCoefficient1(d, m, mdash, f) { + this.d = 0; + this.m = 0; + this.mdash = 0; + this.f = 0; + this.d = d; + this.m = m; + this.mdash = mdash; + this.f = f; +} + +var MoonCoefficient1$ = {}; + +registerType("MoonCoefficient1", [MoonCoefficient1, MoonCoefficient1$, null]); + + +// MoonCoefficient2 + +export function MoonCoefficient2(a, b) { + this.a = 0; + this.b = 0; + this.a = a; + this.b = b; +} + +var MoonCoefficient2$ = {}; + +registerType("MoonCoefficient2", [MoonCoefficient2, MoonCoefficient2$, null]); + + +// Constants + +const g_MoonCoefficients1 = [new MoonCoefficient1(0, 0, 1, 0), new MoonCoefficient1(2, 0, -1, 0), new MoonCoefficient1(2, 0, 0, 0), new MoonCoefficient1(0, 0, 2, 0), new MoonCoefficient1(0, 1, 0, 0), new MoonCoefficient1(0, 0, 0, 2), new MoonCoefficient1(2, 0, -2, 0), new MoonCoefficient1(2, -1, -1, 0), new MoonCoefficient1(2, 0, 1, 0), new MoonCoefficient1(2, -1, 0, 0), new MoonCoefficient1(0, 1, -1, 0), new MoonCoefficient1(1, 0, 0, 0), new MoonCoefficient1(0, 1, 1, 0), new MoonCoefficient1(2, 0, 0, -2), new MoonCoefficient1(0, 0, 1, 2), new MoonCoefficient1(0, 0, 1, -2), new MoonCoefficient1(4, 0, -1, 0), new MoonCoefficient1(0, 0, 3, 0), new MoonCoefficient1(4, 0, -2, 0), new MoonCoefficient1(2, 1, -1, 0), new MoonCoefficient1(2, 1, 0, 0), new MoonCoefficient1(1, 0, -1, 0), new MoonCoefficient1(1, 1, 0, 0), new MoonCoefficient1(2, -1, 1, 0), new MoonCoefficient1(2, 0, 2, 0), new MoonCoefficient1(4, 0, 0, 0), new MoonCoefficient1(2, 0, -3, 0), new MoonCoefficient1(0, 1, -2, 0), new MoonCoefficient1(2, 0, -1, 2), new MoonCoefficient1(2, -1, -2, 0), new MoonCoefficient1(1, 0, 1, 0), new MoonCoefficient1(2, -2, 0, 0), new MoonCoefficient1(0, 1, 2, 0), new MoonCoefficient1(0, 2, 0, 0), new MoonCoefficient1(2, -2, -1, 0), new MoonCoefficient1(2, 0, 1, -2), new MoonCoefficient1(2, 0, 0, 2), new MoonCoefficient1(4, -1, -1, 0), new MoonCoefficient1(0, 0, 2, 2), new MoonCoefficient1(3, 0, -1, 0), new MoonCoefficient1(2, 1, 1, 0), new MoonCoefficient1(4, -1, -2, 0), new MoonCoefficient1(0, 2, -1, 0), new MoonCoefficient1(2, 2, -1, 0), new MoonCoefficient1(2, 1, -2, 0), new MoonCoefficient1(2, -1, 0, -2), new MoonCoefficient1(4, 0, 1, 0), new MoonCoefficient1(0, 0, 4, 0), new MoonCoefficient1(4, -1, 0, 0), new MoonCoefficient1(1, 0, -2, 0), new MoonCoefficient1(2, 1, 0, -2), new MoonCoefficient1(0, 0, 2, -2), new MoonCoefficient1(1, 1, 1, 0), new MoonCoefficient1(3, 0, -2, 0), new MoonCoefficient1(4, 0, -3, 0), new MoonCoefficient1(2, -1, 2, 0), new MoonCoefficient1(0, 2, 1, 0), new MoonCoefficient1(1, 1, -1, 0), new MoonCoefficient1(2, 0, 3, 0), new MoonCoefficient1(2, 0, -1, -2)]; +const g_MoonCoefficients2 = [new MoonCoefficient2(6288774, -20905355), new MoonCoefficient2(1274027, -3699111), new MoonCoefficient2(658314, -2955968), new MoonCoefficient2(213618, -569925), new MoonCoefficient2(-185116, 48888), new MoonCoefficient2(-114332, -3149), new MoonCoefficient2(58793, 246158), new MoonCoefficient2(57066, -152138), new MoonCoefficient2(53322, -170733), new MoonCoefficient2(45758, -204586), new MoonCoefficient2(-40923, -129620), new MoonCoefficient2(-34720, 108743), new MoonCoefficient2(-30383, 104755), new MoonCoefficient2(15327, 10321), new MoonCoefficient2(-12528, 0), new MoonCoefficient2(10980, 79661), new MoonCoefficient2(10675, -34782), new MoonCoefficient2(10034, -23210), new MoonCoefficient2(8548, -21636), new MoonCoefficient2(-7888, 24208), new MoonCoefficient2(-6766, 30824), new MoonCoefficient2(-5163, -8379), new MoonCoefficient2(4987, -16675), new MoonCoefficient2(4036, -12831), new MoonCoefficient2(3994, -10445), new MoonCoefficient2(3861, -11650), new MoonCoefficient2(3665, 14403), new MoonCoefficient2(-2689, -7003), new MoonCoefficient2(-2602, 0), new MoonCoefficient2(2390, 10056), new MoonCoefficient2(-2348, 6322), new MoonCoefficient2(2236, -9884), new MoonCoefficient2(-2120, 5751), new MoonCoefficient2(-2069, 0), new MoonCoefficient2(2048, -4950), new MoonCoefficient2(-1773, 4130), new MoonCoefficient2(-1595, 0), new MoonCoefficient2(1215, -3958), new MoonCoefficient2(-1110, 0), new MoonCoefficient2(-892, 3258), new MoonCoefficient2(-810, 2616), new MoonCoefficient2(759, -1897), new MoonCoefficient2(-713, -2117), new MoonCoefficient2(-700, 2354), new MoonCoefficient2(691, 0), new MoonCoefficient2(596, 0), new MoonCoefficient2(549, -1423), new MoonCoefficient2(537, -1117), new MoonCoefficient2(520, -1571), new MoonCoefficient2(-487, -1739), new MoonCoefficient2(-399, 0), new MoonCoefficient2(-381, -4421), new MoonCoefficient2(351, 0), new MoonCoefficient2(-340, 0), new MoonCoefficient2(330, 0), new MoonCoefficient2(327, 0), new MoonCoefficient2(-323, 1165), new MoonCoefficient2(299, 0), new MoonCoefficient2(294, 0), new MoonCoefficient2(0, 8752)]; +const g_MoonCoefficients3 = [new MoonCoefficient1(0, 0, 0, 1), new MoonCoefficient1(0, 0, 1, 1), new MoonCoefficient1(0, 0, 1, -1), new MoonCoefficient1(2, 0, 0, -1), new MoonCoefficient1(2, 0, -1, 1), new MoonCoefficient1(2, 0, -1, -1), new MoonCoefficient1(2, 0, 0, 1), new MoonCoefficient1(0, 0, 2, 1), new MoonCoefficient1(2, 0, 1, -1), new MoonCoefficient1(0, 0, 2, -1), new MoonCoefficient1(2, -1, 0, -1), new MoonCoefficient1(2, 0, -2, -1), new MoonCoefficient1(2, 0, 1, 1), new MoonCoefficient1(2, 1, 0, -1), new MoonCoefficient1(2, -1, -1, 1), new MoonCoefficient1(2, -1, 0, 1), new MoonCoefficient1(2, -1, -1, -1), new MoonCoefficient1(0, 1, -1, -1), new MoonCoefficient1(4, 0, -1, -1), new MoonCoefficient1(0, 1, 0, 1), new MoonCoefficient1(0, 0, 0, 3), new MoonCoefficient1(0, 1, -1, 1), new MoonCoefficient1(1, 0, 0, 1), new MoonCoefficient1(0, 1, 1, 1), new MoonCoefficient1(0, 1, 1, -1), new MoonCoefficient1(0, 1, 0, -1), new MoonCoefficient1(1, 0, 0, -1), new MoonCoefficient1(0, 0, 3, 1), new MoonCoefficient1(4, 0, 0, -1), new MoonCoefficient1(4, 0, -1, 1), new MoonCoefficient1(0, 0, 1, -3), new MoonCoefficient1(4, 0, -2, 1), new MoonCoefficient1(2, 0, 0, -3), new MoonCoefficient1(2, 0, 2, -1), new MoonCoefficient1(2, -1, 1, -1), new MoonCoefficient1(2, 0, -2, 1), new MoonCoefficient1(0, 0, 3, -1), new MoonCoefficient1(2, 0, 2, 1), new MoonCoefficient1(2, 0, -3, -1), new MoonCoefficient1(2, 1, -1, 1), new MoonCoefficient1(2, 1, 0, 1), new MoonCoefficient1(4, 0, 0, 1), new MoonCoefficient1(2, -1, 1, 1), new MoonCoefficient1(2, -2, 0, -1), new MoonCoefficient1(0, 0, 1, 3), new MoonCoefficient1(2, 1, 1, -1), new MoonCoefficient1(1, 1, 0, -1), new MoonCoefficient1(1, 1, 0, 1), new MoonCoefficient1(0, 1, -2, -1), new MoonCoefficient1(2, 1, -1, -1), new MoonCoefficient1(1, 0, 1, 1), new MoonCoefficient1(2, -1, -2, -1), new MoonCoefficient1(0, 1, 2, 1), new MoonCoefficient1(4, 0, -2, -1), new MoonCoefficient1(4, -1, -1, -1), new MoonCoefficient1(1, 0, 1, -1), new MoonCoefficient1(4, 0, 1, -1), new MoonCoefficient1(1, 0, -1, -1), new MoonCoefficient1(4, -1, 0, -1), new MoonCoefficient1(2, -2, 0, 1)]; +const g_MoonCoefficients4 = [5128122, 280602, 277693, 173237, 55413, 46271, 32573, 17198, 9266, 8822, 8216, 4324, 4200, -3359, 2463, 2211, 2065, -1870, 1828, -1794, -1749, -1565, -1491, -1475, -1410, -1344, -1335, 1107, 1021, 833, 777, 671, 607, 596, 491, -451, 439, 422, 421, -366, -351, 331, 315, 302, -283, -229, 223, 223, -220, -220, -185, 181, -177, 176, 166, -164, 132, -119, 115, 107]; + + +// CAAMoon + +export function CAAMoon() { } + +CAAMoon.meanLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(218.3164477 + 481267.88123421 * T - 0.0015786 * Tsquared + Tcubed / 538841 - T4 / 65194000); +}; + +CAAMoon.meanElongation = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(297.8501921 + 445267.1114034 * T - 0.0018819 * Tsquared + Tcubed / 545868 - T4 / 113065000); +}; + +CAAMoon.meanAnomaly = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(134.9633964 + 477198.8675055 * T + 0.0087414 * Tsquared + Tcubed / 69699 - T4 / 14712000); +}; + +CAAMoon.argumentOfLatitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(93.272095 + 483202.0175233 * T - 0.0036539 * Tsquared - Tcubed / 3526000 + T4 / 863310000); +}; + +CAAMoon.meanLongitudeAscendingNode = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(125.0445479 - 1934.1362891 * T + 0.0020754 * Tsquared + Tcubed / 467441 - T4 / 60616000); +}; + +CAAMoon.meanLongitudePerigee = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return CT.m360(83.3532465 + 4069.0137287 * T - 0.01032 * Tsquared - Tcubed / 80053 + T4 / 18999000); +}; + +CAAMoon.trueLongitudeAscendingNode = function (JD) { + var TrueAscendingNode = CAAMoon.meanLongitudeAscendingNode(JD); + var D = CAAMoon.meanElongation(JD); + D = CT.d2R(D); + var M = CAAEarth.sunMeanAnomaly(JD); + M = CT.d2R(M); + var Mdash = CAAMoon.meanAnomaly(JD); + Mdash = CT.d2R(Mdash); + var F = CAAMoon.argumentOfLatitude(JD); + F = CT.d2R(F); + TrueAscendingNode -= 1.4979 * Math.sin(2 * (D - F)); + TrueAscendingNode -= 0.15 * Math.sin(M); + TrueAscendingNode -= 0.1226 * Math.sin(2 * D); + TrueAscendingNode += 0.1176 * Math.sin(2 * F); + TrueAscendingNode -= 0.0801 * Math.sin(2 * (Mdash - F)); + return CT.m360(TrueAscendingNode); +}; + +CAAMoon.eclipticLongitude = function (JD) { + var Ldash = CAAMoon.meanLongitude(JD); + var LdashDegrees = Ldash; + Ldash = CT.d2R(Ldash); + var D = CAAMoon.meanElongation(JD); + D = CT.d2R(D); + var M = CAAEarth.sunMeanAnomaly(JD); + M = CT.d2R(M); + var Mdash = CAAMoon.meanAnomaly(JD); + Mdash = CT.d2R(Mdash); + var F = CAAMoon.argumentOfLatitude(JD); + F = CT.d2R(F); + var E = CAAEarth.eccentricity(JD); + var T = (JD - 2451545) / 36525; + var A1 = CT.m360(119.75 + 131.849 * T); + A1 = CT.d2R(A1); + var A2 = CT.m360(53.09 + 479264.29 * T); + A2 = CT.d2R(A2); + var A3 = CT.m360(313.45 + 481266.484 * T); + A3 = CT.d2R(A3); + var nLCoefficients = g_MoonCoefficients1.length; + console.assert(g_MoonCoefficients2.length === nLCoefficients); + var SigmaL = 0; + for (var i = 0; i < nLCoefficients; i++) { + var ThisSigma = g_MoonCoefficients2[i].a * Math.sin(g_MoonCoefficients1[i].d * D + g_MoonCoefficients1[i].m * M + g_MoonCoefficients1[i].mdash * Mdash + g_MoonCoefficients1[i].f * F); + if (!!g_MoonCoefficients1[i].m) { + ThisSigma *= E; + } + SigmaL += ThisSigma; + } + SigmaL += 3958 * Math.sin(A1); + SigmaL += 1962 * Math.sin(Ldash - F); + SigmaL += 318 * Math.sin(A2); + var NutationInLong = CAANutation.nutationInLongitude(JD); + return CT.m360(LdashDegrees + SigmaL / 1000000 + NutationInLong / 3600); +}; + +CAAMoon.eclipticLatitude = function (JD) { + var Ldash = CAAMoon.meanLongitude(JD); + Ldash = CT.d2R(Ldash); + var D = CAAMoon.meanElongation(JD); + D = CT.d2R(D); + var M = CAAEarth.sunMeanAnomaly(JD); + M = CT.d2R(M); + var Mdash = CAAMoon.meanAnomaly(JD); + Mdash = CT.d2R(Mdash); + var F = CAAMoon.argumentOfLatitude(JD); + F = CT.d2R(F); + var E = CAAEarth.eccentricity(JD); + var T = (JD - 2451545) / 36525; + var A1 = CT.m360(119.75 + 131.849 * T); + A1 = CT.d2R(A1); + var A2 = CT.m360(53.09 + 479264.29 * T); + A2 = CT.d2R(A2); + var A3 = CT.m360(313.45 + 481266.484 * T); + A3 = CT.d2R(A3); + var nBCoefficients = g_MoonCoefficients3.length; + console.assert(g_MoonCoefficients4.length === nBCoefficients); + var SigmaB = 0; + for (var i = 0; i < nBCoefficients; i++) { + var ThisSigma = g_MoonCoefficients4[i] * Math.sin(g_MoonCoefficients3[i].d * D + g_MoonCoefficients3[i].m * M + g_MoonCoefficients3[i].mdash * Mdash + g_MoonCoefficients3[i].f * F); + if (!!g_MoonCoefficients3[i].m) { + ThisSigma *= E; + } + SigmaB += ThisSigma; + } + SigmaB -= 2235 * Math.sin(Ldash); + SigmaB += 382 * Math.sin(A3); + SigmaB += 175 * Math.sin(A1 - F); + SigmaB += 175 * Math.sin(A1 + F); + SigmaB += 127 * Math.sin(Ldash - Mdash); + SigmaB -= 115 * Math.sin(Ldash + Mdash); + return SigmaB / 1000000; +}; + +CAAMoon.radiusVector = function (JD) { + var Ldash = CAAMoon.meanLongitude(JD); + Ldash = CT.d2R(Ldash); + var D = CAAMoon.meanElongation(JD); + D = CT.d2R(D); + var M = CAAEarth.sunMeanAnomaly(JD); + M = CT.d2R(M); + var Mdash = CAAMoon.meanAnomaly(JD); + Mdash = CT.d2R(Mdash); + var F = CAAMoon.argumentOfLatitude(JD); + F = CT.d2R(F); + var E = CAAEarth.eccentricity(JD); + var T = (JD - 2451545) / 36525; + var A1 = CT.m360(119.75 + 131.849 * T); + A1 = CT.d2R(A1); + var A2 = CT.m360(53.09 + 479264.29 * T); + A2 = CT.d2R(A2); + var A3 = CT.m360(313.45 + 481266.484 * T); + A3 = CT.d2R(A3); + var nRCoefficients = g_MoonCoefficients1.length; + console.assert(g_MoonCoefficients2.length === nRCoefficients); + var SigmaR = 0; + for (var i = 0; i < nRCoefficients; i++) { + var ThisSigma = g_MoonCoefficients2[i].b * Math.cos(g_MoonCoefficients1[i].d * D + g_MoonCoefficients1[i].m * M + g_MoonCoefficients1[i].mdash * Mdash + g_MoonCoefficients1[i].f * F); + if (!!g_MoonCoefficients1[i].m) { + ThisSigma *= E; + } + SigmaR += ThisSigma; + } + return 385000.56 + SigmaR / 1000; +}; + +CAAMoon.radiusVectorToHorizontalParallax = function (RadiusVector) { + return CT.r2D(Math.asin(6378.14 / RadiusVector)); +}; + +CAAMoon.horizontalParallaxToRadiusVector = function (Parallax) { + return 6378.14 / Math.sin(CT.d2R(Parallax)); +}; + +var CAAMoon$ = {}; + +registerType("CAAMoon", [CAAMoon, CAAMoon$, null]); diff --git a/engine/esm/astrocalc/moon_illuminated_fraction.js b/engine/esm/astrocalc/moon_illuminated_fraction.js new file mode 100644 index 00000000..6924b5a9 --- /dev/null +++ b/engine/esm/astrocalc/moon_illuminated_fraction.js @@ -0,0 +1,59 @@ +// Originally `AAMOONILLUMINATEDFRACTION.CPP` +// "Purpose: Implementation for the algorithms for the Moon's Elongation, Phase Angle and Illuminated Fraction" +// Last update of original: PJN / 26-01-2007 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// MIFR + +export function MIFR() { +} + +MIFR.geocentricElongation = function (ObjectAlpha, ObjectDelta, SunAlpha, SunDelta) { + ObjectAlpha = CT.d2R(ObjectAlpha * 15); + SunAlpha = CT.d2R(SunAlpha * 15); + ObjectDelta = CT.d2R(ObjectDelta); + SunDelta = CT.d2R(SunDelta); + return CT.r2D(Math.acos(Math.sin(SunDelta) * Math.sin(ObjectDelta) + Math.cos(SunDelta) * Math.cos(ObjectDelta) * Math.cos(SunAlpha - ObjectAlpha))); +}; + +MIFR.phaseAngle = function (GeocentricElongation, EarthObjectDistance, EarthSunDistance) { + GeocentricElongation = CT.d2R(GeocentricElongation); + return CT.m360(CT.r2D(Math.atan2(EarthSunDistance * Math.sin(GeocentricElongation), EarthObjectDistance - EarthSunDistance * Math.cos(GeocentricElongation)))); +}; + +MIFR.illuminatedFraction = function (PhaseAngle) { + PhaseAngle = CT.d2R(PhaseAngle); + return (1 + Math.cos(PhaseAngle)) / 2; +}; + +MIFR.positionAngle = function (Alpha0, Delta0, Alpha, Delta) { + Alpha0 = CT.h2R(Alpha0); + Alpha = CT.h2R(Alpha); + Delta0 = CT.d2R(Delta0); + Delta = CT.d2R(Delta); + return CT.m360(CT.r2D(Math.atan2(Math.cos(Delta0) * Math.sin(Alpha0 - Alpha), Math.sin(Delta0) * Math.cos(Delta) - Math.cos(Delta0) * Math.sin(Delta) * Math.cos(Alpha0 - Alpha)))); +}; + +var MIFR$ = {}; + +registerType("MIFR", [MIFR, MIFR$, null]); diff --git a/engine/esm/astrocalc/moon_nodes.js b/engine/esm/astrocalc/moon_nodes.js new file mode 100644 index 00000000..b89352f6 --- /dev/null +++ b/engine/esm/astrocalc/moon_nodes.js @@ -0,0 +1,61 @@ +// Originally `AAMOONNODES.CPP` +// "Purpose: Implementation for the algorithms which obtain the dates when the Moon passes thro its nodes" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// CAAMoonNodes + +export function CAAMoonNodes() { } + +CAAMoonNodes.k = function (Year) { + return 13.4223 * (Year - 2000.05); +}; + +CAAMoonNodes.passageThroNode = function (k) { + var T = k / 1342.23; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + var D = CT.m360(183.638 + 331.73735682 * k + 0.0014852 * Tsquared + 2.09E-06 * Tcubed - 1E-08 * T4); + var M = CT.m360(17.4006 + 26.8203725 * k + 0.0001186 * Tsquared + 6E-08 * Tcubed); + var Mdash = CT.m360(38.3776 + 355.52747313 * k + 0.0123499 * Tsquared + 1.4627E-05 * Tcubed - 6.9E-08 * T4); + var omega = CT.m360(123.9767 - 1.44098956 * k + 0.0020608 * Tsquared + 2.14E-06 * Tcubed - 1.6E-08 * T4); + var V = CT.m360(299.75 + 132.85 * T - 0.009173 * Tsquared); + var P = CT.m360(omega + 272.75 - 2.3 * T); + var E = 1 - 0.002516 * T - 7.4E-06 * Tsquared; + D = CT.d2R(D); + var D2 = 2 * D; + var D4 = D2 * D2; + M = CT.d2R(M); + Mdash = CT.d2R(Mdash); + var Mdash2 = 2 * Mdash; + omega = CT.d2R(omega); + V = CT.d2R(V); + P = CT.d2R(P); + var JD = 2451565.1619 + 27.212220817 * k + 0.0002762 * Tsquared + 2.1E-08 * Tcubed - 8.8E-11 * T4 - 0.4721 * Math.sin(Mdash) - 0.1649 * Math.sin(D2) - 0.0868 * Math.sin(D2 - Mdash) + 0.0084 * Math.sin(D2 + Mdash) - E * 0.0083 * Math.sin(D2 - M) - E * 0.0039 * Math.sin(D2 - M - Mdash) + 0.0034 * Math.sin(Mdash2) - 0.0031 * Math.sin(D2 - Mdash2) + E * 0.003 * Math.sin(D2 + M) + E * 0.0028 * Math.sin(M - Mdash) + E * 0.0026 * Math.sin(M) + 0.0025 * Math.sin(D4) + 0.0024 * Math.sin(D) + E * 0.0022 * Math.sin(M + Mdash) + 0.0017 * Math.sin(omega) + 0.0014 * Math.sin(D4 - Mdash) + E * 0.0005 * Math.sin(D2 + M - Mdash) + E * 0.0004 * Math.sin(D2 - M + Mdash) - E * 0.0003 * Math.sin(D2 - M * M) + E * 0.0003 * Math.sin(D4 - M) + 0.0003 * Math.sin(V) + 0.0003 * Math.sin(P); + return JD; +}; + +var CAAMoonNodes$ = {}; + +registerType("CAAMoonNodes", [CAAMoonNodes, CAAMoonNodes$, null]); diff --git a/engine/esm/astrocalc/moon_perigee_apogee.js b/engine/esm/astrocalc/moon_perigee_apogee.js new file mode 100644 index 00000000..4363fa16 --- /dev/null +++ b/engine/esm/astrocalc/moon_perigee_apogee.js @@ -0,0 +1,154 @@ +// Originally `AAMOONPERIGEEAPOGEE.CPP` +// "Purpose: Implementation for the algorithms which obtain the dates of Lunar Apogee and Perigee" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// MPAC - was MoonPerigeeApogeeCoefficient + +export function MPAC(D, M, F, C, T) { + this.d = 0; + this.m = 0; + this.f = 0; + this.c = 0; + this.t = 0; + this.d = D; + this.m = M; + this.f = F; + this.c = C; + this.t = T; +} + +var MPAC$ = {}; + +registerType("MPAC", [MPAC, MPAC$, null]); + + +// Constants + +const g_MoonPerigeeApogeeCoefficients1 = [new MPAC(2, 0, 0, -1.6769, 0), new MPAC(4, 0, 0, 0.4589, 0), new MPAC(6, 0, 0, -0.1856, 0), new MPAC(8, 0, 0, 0.0883, 0), new MPAC(2, -1, 0, -0.0773, 0.00019), new MPAC(0, 1, 0, 0.0502, -0.00013), new MPAC(10, 0, 0, -0.046, 0), new MPAC(4, -1, 0, 0.0422, -0.00011), new MPAC(6, -1, 0, -0.0256, 0), new MPAC(12, 0, 0, 0.0253, 0), new MPAC(1, 0, 0, 0.0237, 0), new MPAC(8, -1, 0, 0.0162, 0), new MPAC(14, 0, 0, -0.0145, 0), new MPAC(0, 0, 2, 0.0129, 0), new MPAC(3, 0, 0, -0.0112, 0), new MPAC(10, -1, 0, -0.0104, 0), new MPAC(16, 0, 0, 0.0086, 0), new MPAC(12, -1, 0, 0.0069, 0), new MPAC(5, 0, 0, 0.0066, 0), new MPAC(2, 0, 2, -0.0053, 0), new MPAC(18, 0, 0, -0.0052, 0), new MPAC(14, -1, 0, -0.0046, 0), new MPAC(7, 0, 0, -0.0041, 0), new MPAC(2, 1, 0, 0.004, 0), new MPAC(20, 0, 0, 0.0032, 0), new MPAC(1, 1, 0, -0.0032, 0), new MPAC(16, -1, 0, 0.0031, 0), new MPAC(4, 1, 0, -0.0029, 0), new MPAC(9, 0, 0, 0.0027, 0), new MPAC(4, 0, 2, 0.0027, 0), new MPAC(2, -2, 0, -0.0027, 0), new MPAC(4, -2, 0, 0.0024, 0), new MPAC(6, -2, 0, -0.0021, 0), new MPAC(22, 0, 0, -0.0021, 0), new MPAC(18, -1, 0, -0.0021, 0), new MPAC(6, 1, 0, 0.0019, 0), new MPAC(11, 0, 0, -0.0018, 0), new MPAC(8, 1, 0, -0.0014, 0), new MPAC(4, 0, -2, -0.0014, 0), new MPAC(6, 0, 2, -0.0014, 0), new MPAC(3, 1, 0, 0.0014, 0), new MPAC(5, 1, 0, -0.0014, 0), new MPAC(13, 0, 0, 0.0013, 0), new MPAC(20, -1, 0, 0.0013, 0), new MPAC(3, 2, 0, 0.0011, 0), new MPAC(4, -2, 2, -0.0011, 0), new MPAC(1, 2, 0, -0.0011, 0), new MPAC(22, -1, 0, -0.0009, 0), new MPAC(0, 0, 4, -0.0008, 0), new MPAC(6, 0, -2, 0.0008, 0), new MPAC(2, 1, -2, 0.0008, 0), new MPAC(0, 2, 0, 0.0007, 0), new MPAC(0, -1, 2, 0.0007, 0), new MPAC(2, 0, 4, 0.0007, 0), new MPAC(0, -2, 2, -0.0006, 0), new MPAC(2, 2, -2, -0.0006, 0), new MPAC(24, 0, 0, 0.0006, 0), new MPAC(4, 0, -4, 0.0005, 0), new MPAC(2, 2, 0, 0.0005, 0), new MPAC(1, -1, 0, -0.0004, 0)]; +const g_MoonPerigeeApogeeCoefficients2 = [new MPAC(2, 0, 0, 0.4392, 0), new MPAC(4, 0, 0, 0.0684, 0), new MPAC(0, 1, 0, 0.0456, -0.00011), new MPAC(2, -1, 0, 0.0426, -0.00011), new MPAC(0, 0, 2, 0.0212, 0), new MPAC(1, 0, 0, -0.0189, 0), new MPAC(6, 0, 0, 0.0144, 0), new MPAC(4, -1, 0, 0.0113, 0), new MPAC(2, 0, 2, 0.0047, 0), new MPAC(1, 1, 0, 0.0036, 0), new MPAC(8, 0, 0, 0.0035, 0), new MPAC(6, -1, 0, 0.0034, 0), new MPAC(2, 0, -2, -0.0034, 0), new MPAC(2, -2, 0, 0.0022, 0), new MPAC(3, 0, 0, -0.0017, 0), new MPAC(4, 0, 2, 0.0013, 0), new MPAC(8, -1, 0, 0.0011, 0), new MPAC(4, -2, 0, 0.001, 0), new MPAC(10, 0, 0, 0.0009, 0), new MPAC(3, 1, 0, 0.0007, 0), new MPAC(0, 2, 0, 0.0006, 0), new MPAC(2, 1, 0, 0.0005, 0), new MPAC(2, 2, 0, 0.0005, 0), new MPAC(6, 0, 2, 0.0004, 0), new MPAC(6, -2, 0, 0.0004, 0), new MPAC(10, -1, 0, 0.0004, 0), new MPAC(5, 0, 0, -0.0004, 0), new MPAC(4, 0, -2, -0.0004, 0), new MPAC(0, 1, 2, 0.0003, 0), new MPAC(12, 0, 0, 0.0003, 0), new MPAC(2, -1, 2, 0.0003, 0), new MPAC(1, -1, 0, -0.0003, 0)]; +const g_MoonPerigeeApogeeCoefficients3 = [new MPAC(2, 0, 0, 63.224, 0), new MPAC(4, 0, 0, -6.99, 0), new MPAC(2, -1, 0, 2.834, 0), new MPAC(2, -1, 0, 0, -0.0071), new MPAC(6, 0, 0, 1.927, 0), new MPAC(1, 0, 0, -1.263, 0), new MPAC(8, 0, 0, -0.702, 0), new MPAC(0, 1, 0, 0.696, 0), new MPAC(0, 1, 0, 0, -0.0017), new MPAC(0, 0, 2, -0.69, 0), new MPAC(4, -1, 0, -0.629, 0), new MPAC(4, -1, 0, 0, 0.0016), new MPAC(2, 0, -2, -0.392, 0), new MPAC(10, 0, 0, 0.297, 0), new MPAC(6, -1, 0, 0.26, 0), new MPAC(3, 0, 0, 0.201, 0), new MPAC(2, 1, 0, -0.161, 0), new MPAC(1, 1, 0, 0.157, 0), new MPAC(12, 0, 0, -0.138, 0), new MPAC(8, -1, 0, -0.127, 0), new MPAC(2, 0, 2, 0.104, 0), new MPAC(2, -2, 0, 0.104, 0), new MPAC(5, 0, 0, -0.079, 0), new MPAC(14, 0, 0, 0.068, 0), new MPAC(10, -1, 0, 0.067, 0), new MPAC(4, 1, 0, 0.054, 0), new MPAC(12, -1, 0, -0.038, 0), new MPAC(4, -2, 0, -0.038, 0), new MPAC(7, 0, 0, 0.037, 0), new MPAC(4, 0, 2, -0.037, 0), new MPAC(16, 0, 0, -0.035, 0), new MPAC(3, 1, 0, -0.03, 0), new MPAC(1, -1, 0, 0.029, 0), new MPAC(6, 1, 0, -0.025, 0), new MPAC(0, 2, 0, 0.023, 0), new MPAC(14, -1, 0, 0.023, 0), new MPAC(2, 2, 0, -0.023, 0), new MPAC(6, -2, 0, 0.022, 0), new MPAC(2, -1, -2, -0.021, 0), new MPAC(9, 0, 0, -0.02, 0), new MPAC(18, 0, 0, 0.019, 0), new MPAC(6, 0, 2, 0.017, 0), new MPAC(0, -1, 2, 0.014, 0), new MPAC(16, -1, 0, -0.014, 0), new MPAC(4, 0, -20, 0.013, 0), new MPAC(8, 1, 0, 0.012, 0), new MPAC(11, 0, 0, 0.011, 0), new MPAC(5, 1, 0, 0.01, 0), new MPAC(20, 0, 0, -0.01, 0)]; +const g_MoonPerigeeApogeeCoefficients4 = [new MPAC(2, 0, 0, -9.147, 0), new MPAC(1, 0, 0, -0.841, 0), new MPAC(0, 0, 2, 0.697, 0), new MPAC(0, 1, 0, -0.656, 0.0016), new MPAC(4, 0, 0, 0.355, 0), new MPAC(2, -1, 0, 0.159, 0), new MPAC(1, 1, 0, 0.127, 0), new MPAC(4, -1, 0, 0.065, 0), new MPAC(6, 0, 0, 0.052, 0), new MPAC(2, 1, 0, 0.043, 0), new MPAC(2, 0, 2, 0.031, 0), new MPAC(2, 0, -2, -0.023, 0), new MPAC(2, -2, 0, 0.022, 0), new MPAC(2, 2, 0, 0.019, 0), new MPAC(0, 2, 0, -0.016, 0), new MPAC(6, -1, 0, 0.014, 0), new MPAC(8, 0, 0, 0.01, 0)]; + + +// CAAMoonPerigeeApogee + +export function CAAMoonPerigeeApogee() { } + +CAAMoonPerigeeApogee.k = function (Year) { + return 13.2555 * (Year - 1999.97); +}; + +CAAMoonPerigeeApogee.meanPerigee = function (k) { + var T = k / 1325.55; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + return 2451534.6698 + 27.55454989 * k - 0.0006691 * Tsquared - 1.098E-06 * Tcubed + 5.2E-09 * T4; +}; + +CAAMoonPerigeeApogee.meanApogee = function (k) { + return CAAMoonPerigeeApogee.meanPerigee(k); +}; + +CAAMoonPerigeeApogee.truePerigee = function (k) { + var MeanJD = CAAMoonPerigeeApogee.meanPerigee(k); + var T = k / 1325.55; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); + D = CT.d2R(D); + var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); + M = CT.d2R(M); + var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); + F = CT.d2R(F); + var nPerigeeCoefficients = g_MoonPerigeeApogeeCoefficients1.length; + var Sigma = 0; + for (var i = 0; i < nPerigeeCoefficients; i++) { + Sigma += g_MoonPerigeeApogeeCoefficients1[i].c * Math.sin(D * g_MoonPerigeeApogeeCoefficients1[i].d + M * g_MoonPerigeeApogeeCoefficients1[i].m + F * g_MoonPerigeeApogeeCoefficients1[i].f + T * g_MoonPerigeeApogeeCoefficients1[i].t); + } + return MeanJD + Sigma; +}; + +CAAMoonPerigeeApogee.trueApogee = function (k) { + var MeanJD = CAAMoonPerigeeApogee.meanApogee(k); + var T = k / 1325.55; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); + D = CT.d2R(D); + var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); + M = CT.d2R(M); + var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); + F = CT.d2R(F); + var nApogeeCoefficients = g_MoonPerigeeApogeeCoefficients2.length; + var Sigma = 0; + for (var i = 0; i < nApogeeCoefficients; i++) { + Sigma += (g_MoonPerigeeApogeeCoefficients2[i].c + T * g_MoonPerigeeApogeeCoefficients2[i].t) * Math.sin(D * g_MoonPerigeeApogeeCoefficients2[i].d + M * g_MoonPerigeeApogeeCoefficients2[i].m + F * g_MoonPerigeeApogeeCoefficients2[i].f); + } + return MeanJD + Sigma; +}; + +CAAMoonPerigeeApogee.perigeeParallax = function (k) { + var T = k / 1325.55; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); + D = CT.d2R(D); + var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); + M = CT.d2R(M); + var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); + F = CT.d2R(F); + var nPerigeeCoefficients = g_MoonPerigeeApogeeCoefficients3.length; + var Parallax = 3629.215; + for (var i = 0; i < nPerigeeCoefficients; i++) { + Parallax += (g_MoonPerigeeApogeeCoefficients3[i].c + T * g_MoonPerigeeApogeeCoefficients3[i].t) * Math.cos(D * g_MoonPerigeeApogeeCoefficients3[i].d + M * g_MoonPerigeeApogeeCoefficients3[i].m + F * g_MoonPerigeeApogeeCoefficients3[i].f); + } + return Parallax / 3600; +}; + +CAAMoonPerigeeApogee.apogeeParallax = function (k) { + var T = k / 1325.55; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var T4 = Tcubed * T; + var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); + D = CT.d2R(D); + var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); + M = CT.d2R(M); + var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); + F = CT.d2R(F); + var nApogeeCoefficients = g_MoonPerigeeApogeeCoefficients4.length; + var Parallax = 3245.251; + for (var i = 0; i < nApogeeCoefficients; i++) { + Parallax += (g_MoonPerigeeApogeeCoefficients4[i].c + T * g_MoonPerigeeApogeeCoefficients4[i].t) * Math.cos(D * g_MoonPerigeeApogeeCoefficients4[i].d + M * g_MoonPerigeeApogeeCoefficients4[i].m + F * g_MoonPerigeeApogeeCoefficients4[i].f); + } + return Parallax / 3600; +}; + +var CAAMoonPerigeeApogee$ = {}; + +registerType("CAAMoonPerigeeApogee", [CAAMoonPerigeeApogee, CAAMoonPerigeeApogee$, null]); diff --git a/engine/esm/astrocalc/moon_phases.js b/engine/esm/astrocalc/moon_phases.js new file mode 100644 index 00000000..c19969e0 --- /dev/null +++ b/engine/esm/astrocalc/moon_phases.js @@ -0,0 +1,120 @@ +// Originally `AAMOONPHASES.CPP` +// "Purpose: Implementation for the algorithms which obtain the dates for the phases of the Moon" +// Last update of original: PJN / 22-02-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// CAAMoonPhases + +export function CAAMoonPhases() { } + +CAAMoonPhases.k = function (Year) { + return 12.3685 * (Year - 2000); +}; + +CAAMoonPhases.meanPhase = function (k) { + var T = k / 1236.85; + var T2 = T * T; + var T3 = T2 * T; + var T4 = T3 * T; + return 2451550.09766 + 29.530588861 * k + 0.00015437 * T2 - 1.5E-07 * T3 + 7.3E-10 * T4; +}; + +CAAMoonPhases.truePhase = function (k) { + var JD = CAAMoonPhases.meanPhase(k); + var T = k / 1236.85; + var T2 = T * T; + var T3 = T2 * T; + var T4 = T3 * T; + var E = 1 - 0.002516 * T - 7.4E-06 * T2; + var E2 = E * E; + var M = CT.m360(2.5534 + 29.1053567 * k - 1.4E-06 * T2 - 1.1E-07 * T3); + M = CT.d2R(M); + var Mdash = CT.m360(201.5643 + 385.81693528 * k + 0.0107582 * T2 + 1.238E-05 * T3 - 5.8E-08 * T4); + Mdash = CT.d2R(Mdash); + var F = CT.m360(160.7108 + 390.67050284 * k - 0.0016118 * T2 - 2.27E-06 * T3 + 1E-08 * T4); + F = CT.d2R(F); + var omega = CT.m360(124.7746 - 1.56375588 * k + 0.0020672 * T2 + 2.15E-06 * T3); + omega = CT.d2R(omega); + var A1 = CT.m360(299.77 + 0.107408 * k - 0.009173 * T2); + A1 = CT.d2R(A1); + var A2 = CT.m360(251.88 + 0.016321 * k); + A2 = CT.d2R(A2); + var A3 = CT.m360(251.83 + 26.651886 * k); + A3 = CT.d2R(A3); + var A4 = CT.m360(349.42 + 36.412478 * k); + A4 = CT.d2R(A4); + var A5 = CT.m360(84.66 + 18.206239 * k); + A5 = CT.d2R(A5); + var A6 = CT.m360(141.74 + 53.303771 * k); + A6 = CT.d2R(A6); + var A7 = CT.m360(207.14 + 2.453732 * k); + A7 = CT.d2R(A7); + var A8 = CT.m360(154.84 + 7.30686 * k); + A8 = CT.d2R(A8); + var A9 = CT.m360(34.52 + 27.261239 * k); + A9 = CT.d2R(A9); + var A10 = CT.m360(207.19 + 0.121824 * k); + A10 = CT.d2R(A10); + var A11 = CT.m360(291.34 + 1.844379 * k); + A11 = CT.d2R(A11); + var A12 = CT.m360(161.72 + 24.198154 * k); + A12 = CT.d2R(A12); + var A13 = CT.m360(239.56 + 25.513099 * k); + A13 = CT.d2R(A13); + var A14 = CT.m360(331.55 + 3.592518 * k); + A14 = CT.d2R(A14); + var kint = Math.floor(k); + var kfrac = k - kint; + if (kfrac < 0) { + kfrac = 1 + kfrac; + } + if (!kfrac) { + var DeltaJD = -0.4072 * Math.sin(Mdash) + 0.17241 * E * Math.sin(M) + 0.01608 * Math.sin(2 * Mdash) + 0.01039 * Math.sin(2 * F) + 0.00739 * E * Math.sin(Mdash - M) + -0.00514 * E * Math.sin(Mdash + M) + 0.00208 * E2 * Math.sin(2 * M) + -0.00111 * Math.sin(Mdash - 2 * F) + -0.00057 * Math.sin(Mdash + 2 * F) + 0.00056 * E * Math.sin(2 * Mdash + M) + -0.00042 * Math.sin(3 * Mdash) + 0.00042 * E * Math.sin(M + 2 * F) + 0.00038 * E * Math.sin(M - 2 * F) + -0.00024 * E * Math.sin(2 * Mdash - M) + -0.00017 * Math.sin(omega) + -7E-05 * Math.sin(Mdash + 2 * M) + 4E-05 * Math.sin(2 * Mdash - 2 * F) + 4E-05 * Math.sin(3 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(2 * Mdash + 2 * F) + -3E-05 * Math.sin(Mdash + M + 2 * F) + 3E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(Mdash - M - 2 * F) + -2E-05 * Math.sin(3 * Mdash + M) + 2E-05 * Math.sin(4 * Mdash); + JD += DeltaJD; + } + else if ((kfrac === 0.25) || (kfrac === 0.75)) { + var DeltaJD = -0.62801 * Math.sin(Mdash) + 0.17172 * E * Math.sin(M) + -0.01183 * E * Math.sin(Mdash + M) + 0.00862 * Math.sin(2 * Mdash) + 0.00804 * Math.sin(2 * F) + 0.00454 * E * Math.sin(Mdash - M) + 0.00204 * E2 * Math.sin(2 * M) + -0.0018 * Math.sin(Mdash - 2 * F) + -0.0007 * Math.sin(Mdash + 2 * F) + -0.0004 * Math.sin(3 * Mdash) + -0.00034 * E * Math.sin(2 * Mdash - M) + 0.00032 * E * Math.sin(M + 2 * F) + 0.00032 * E * Math.sin(M - 2 * F) + -0.00028 * E2 * Math.sin(Mdash + 2 * M) + 0.00027 * E * Math.sin(2 * Mdash + M) + -0.00017 * Math.sin(omega) + -5E-05 * Math.sin(Mdash - M - 2 * F) + 4E-05 * Math.sin(2 * Mdash + 2 * F) + -4E-05 * Math.sin(Mdash + M + 2 * F) + 4E-05 * Math.sin(Mdash - 2 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(3 * M) + 2E-05 * Math.sin(2 * Mdash - 2 * F) + 2E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(3 * Mdash + M); + JD += DeltaJD; + var W = 0.00306 - 0.00038 * E * Math.cos(M) + 0.00026 * Math.cos(Mdash) - 2E-05 * Math.cos(Mdash - M) + 2E-05 * Math.cos(Mdash + M) + 2E-05 * Math.cos(2 * F); + if (kfrac === 0.25) { + JD += W; + } + else { + JD -= W; + } + } + else if (kfrac === 0.5) { + var DeltaJD = -0.40614 * Math.sin(Mdash) + 0.17302 * E * Math.sin(M) + 0.01614 * Math.sin(2 * Mdash) + 0.01043 * Math.sin(2 * F) + 0.00734 * E * Math.sin(Mdash - M) + -0.00514 * E * Math.sin(Mdash + M) + 0.00209 * E2 * Math.sin(2 * M) + -0.00111 * Math.sin(Mdash - 2 * F) + -0.00057 * Math.sin(Mdash + 2 * F) + 0.00056 * E * Math.sin(2 * Mdash + M) + -0.00042 * Math.sin(3 * Mdash) + 0.00042 * E * Math.sin(M + 2 * F) + 0.00038 * E * Math.sin(M - 2 * F) + -0.00024 * E * Math.sin(2 * Mdash - M) + -0.00017 * Math.sin(omega) + -7E-05 * Math.sin(Mdash + 2 * M) + 4E-05 * Math.sin(2 * Mdash - 2 * F) + 4E-05 * Math.sin(3 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(2 * Mdash + 2 * F) + -3E-05 * Math.sin(Mdash + M + 2 * F) + 3E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(Mdash - M - 2 * F) + -2E-05 * Math.sin(3 * Mdash + M) + 2E-05 * Math.sin(4 * Mdash); + JD += DeltaJD; + } + else { + console.assert(false); + } + var DeltaJD2 = 0.000325 * Math.sin(A1) + 0.000165 * Math.sin(A2) + 0.000164 * Math.sin(A3) + 0.000126 * Math.sin(A4) + 0.00011 * Math.sin(A5) + 6.2E-05 * Math.sin(A6) + 6E-05 * Math.sin(A7) + 5.6E-05 * Math.sin(A8) + 4.7E-05 * Math.sin(A9) + 4.2E-05 * Math.sin(A10) + 4E-05 * Math.sin(A11) + 3.7E-05 * Math.sin(A12) + 3.5E-05 * Math.sin(A13) + 2.3E-05 * Math.sin(A14); + JD += DeltaJD2; + return JD; +}; + +var CAAMoonPhases$ = {}; + +registerType("CAAMoonPhases", [CAAMoonPhases, CAAMoonPhases$, null]); diff --git a/engine/esm/astrocalc/neptune.js b/engine/esm/astrocalc/neptune.js new file mode 100644 index 00000000..21183ce4 --- /dev/null +++ b/engine/esm/astrocalc/neptune.js @@ -0,0 +1,151 @@ +// Originally `AANEPTUNE.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Neptune" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0NC = [new VSC(531188633, 0, 0), new VSC(1798476, 2.9010127, 38.1330356), new VSC(1019728, 0.4858092, 1.4844727), new VSC(124532, 4.830081, 36.648563), new VSC(42064, 5.41055, 2.96895), new VSC(37715, 6.09222, 35.16409), new VSC(33785, 1.24489, 76.26607), new VSC(16483, 8E-05, 491.55793), new VSC(9199, 4.9375, 39.6175), new VSC(8994, 0.2746, 175.1661), new VSC(4216, 1.9871, 73.2971), new VSC(3365, 1.0359, 33.6796), new VSC(2285, 4.2061, 4.4534), new VSC(1434, 2.7834, 74.7816), new VSC(900, 2.076, 109.946), new VSC(745, 3.19, 71.813), new VSC(506, 5.748, 114.399), new VSC(400, 0.35, 1021.249), new VSC(345, 3.462, 41.102), new VSC(340, 3.304, 77.751), new VSC(323, 2.248, 32.195), new VSC(306, 0.497, 0.521), new VSC(287, 4.505, 0.048), new VSC(282, 2.246, 146.594), new VSC(267, 4.889, 0.963), new VSC(252, 5.782, 388.465), new VSC(245, 1.247, 9.561), new VSC(233, 2.505, 137.033), new VSC(227, 1.797, 453.425), new VSC(170, 3.324, 108.461), new VSC(151, 2.192, 33.94), new VSC(150, 2.997, 5.938), new VSC(148, 0.859, 111.43), new VSC(119, 3.677, 2.448), new VSC(109, 2.416, 183.243), new VSC(103, 0.041, 0.261), new VSC(103, 4.404, 70.328), new VSC(102, 5.705, 0.112)]; +const g_L1NC = [new VSC(3837687717, 0, 0), new VSC(16604, 4.86319, 1.48447), new VSC(15807, 2.27923, 38.13304), new VSC(3335, 3.682, 76.2661), new VSC(1306, 3.6732, 2.9689), new VSC(605, 1.505, 35.164), new VSC(179, 3.453, 39.618), new VSC(107, 2.451, 4.453), new VSC(106, 2.755, 33.68), new VSC(73, 5.49, 36.65), new VSC(57, 1.86, 114.4), new VSC(57, 5.22, 0.52), new VSC(35, 4.52, 74.78), new VSC(32, 5.9, 77.75), new VSC(30, 3.67, 388.47), new VSC(29, 5.17, 9.56), new VSC(29, 5.17, 2.45), new VSC(26, 5.25, 168.05)]; +const g_L2NC = [new VSC(53893, 0, 0), new VSC(296, 1.855, 1.484), new VSC(281, 1.191, 38.133), new VSC(270, 5.721, 76.266), new VSC(23, 1.21, 2.97), new VSC(9, 4.43, 35.16), new VSC(7, 0.54, 2.45)]; +const g_L3NC = [new VSC(31, 0, 0), new VSC(15, 1.35, 76.27), new VSC(12, 6.04, 1.48), new VSC(12, 6.11, 38.13)]; +const g_L4NC = [new VSC(114, 3.142, 0)]; +const g_B0NC = [new VSC(3088623, 1.4410437, 38.1330356), new VSC(27789, 5.91272, 76.26607), new VSC(27624, 0, 0), new VSC(15448, 3.50877, 39.61751), new VSC(15355, 2.52124, 36.64856), new VSC(2000, 1.51, 74.7816), new VSC(1968, 4.3778, 1.4845), new VSC(1015, 3.2156, 35.1641), new VSC(606, 2.802, 73.297), new VSC(595, 2.129, 41.102), new VSC(589, 3.187, 2.969), new VSC(402, 4.169, 114.399), new VSC(280, 1.682, 77.751), new VSC(262, 3.767, 213.299), new VSC(254, 3.271, 453.425), new VSC(206, 4.257, 529.691), new VSC(140, 3.53, 137.033)]; +const g_B1NC = [new VSC(227279, 3.807931, 38.133036), new VSC(1803, 1.9758, 76.2661), new VSC(1433, 3.1416, 0), new VSC(1386, 4.8256, 36.6486), new VSC(1073, 6.0805, 39.6175), new VSC(148, 3.858, 74.782), new VSC(136, 0.478, 1.484), new VSC(70, 6.19, 35.16), new VSC(52, 5.05, 73.3), new VSC(43, 0.31, 114.4), new VSC(37, 4.89, 41.1), new VSC(37, 5.76, 2.97), new VSC(26, 5.22, 213.3)]; +const g_B2NC = [new VSC(9691, 5.5712, 38.133), new VSC(79, 3.63, 76.27), new VSC(72, 0.45, 36.65), new VSC(59, 3.14, 0), new VSC(30, 1.61, 39.62), new VSC(6, 5.61, 74.78)]; +const g_B3NC = [new VSC(273, 1.017, 38.133), new VSC(2, 0, 0), new VSC(2, 2.37, 36.65), new VSC(2, 5.33, 76.27)]; +const g_B4NC = [new VSC(6, 2.67, 38.13)]; +const g_R0NC = [new VSC(3007013206, 0, 0), new VSC(27062259, 1.32999459, 38.13303564), new VSC(1691764, 3.2518614, 36.6485629), new VSC(807831, 5.185928, 1.484473), new VSC(537761, 4.521139, 35.16409), new VSC(495726, 1.571057, 491.557929), new VSC(274572, 1.845523, 175.16606), new VSC(135134, 3.372206, 39.617508), new VSC(121802, 5.797544, 76.266071), new VSC(100895, 0.377027, 73.297126), new VSC(69792, 3.79617, 2.96895), new VSC(46688, 5.74938, 33.67962), new VSC(24594, 0.50802, 109.94569), new VSC(16939, 1.59422, 71.81265), new VSC(14230, 1.07786, 74.7816), new VSC(12012, 1.92062, 1021.24889), new VSC(8395, 0.6782, 146.5943), new VSC(7572, 1.0715, 388.4652), new VSC(5721, 2.5906, 4.4534), new VSC(4840, 1.9069, 41.102), new VSC(4483, 2.9057, 529.691), new VSC(4421, 1.7499, 108.4612), new VSC(4354, 0.6799, 32.1951), new VSC(4270, 3.4134, 453.4249), new VSC(3381, 0.8481, 183.2428), new VSC(2881, 1.986, 137.033), new VSC(2879, 3.6742, 350.3321), new VSC(2636, 3.0976, 213.2991), new VSC(2530, 5.7984, 490.0735), new VSC(2523, 0.4863, 493.0424), new VSC(2306, 2.8096, 70.3282), new VSC(2087, 0.6186, 33.9402)]; +const g_R1NC = [new VSC(236339, 0.70498, 38.133036), new VSC(13220, 3.32015, 1.48447), new VSC(8622, 6.2163, 35.1641), new VSC(2702, 1.8814, 39.6175), new VSC(2155, 2.0943, 2.9689), new VSC(2153, 5.1687, 76.2661), new VSC(1603, 0, 0), new VSC(1464, 1.1842, 33.6796), new VSC(1136, 3.9189, 36.6486), new VSC(898, 5.241, 388.465), new VSC(790, 0.533, 168.053), new VSC(760, 0.021, 182.28), new VSC(607, 1.077, 1021.249), new VSC(572, 3.401, 484.444), new VSC(561, 2.887, 498.671)]; +const g_R2NC = [new VSC(4247, 5.8991, 38.133), new VSC(218, 0.346, 1.484), new VSC(163, 2.239, 168.053), new VSC(156, 4.594, 182.28), new VSC(127, 2.848, 35.164)]; +const g_R3NC = [new VSC(166, 4.552, 38.133)]; + + +// CAANeptune + +export function CAANeptune() { } + +CAANeptune.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nL0Coefficients = g_L0NC.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0NC[i].a * Math.cos(g_L0NC[i].b + g_L0NC[i].c * rho); + } + var nL1Coefficients = g_L1NC.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1NC[i].a * Math.cos(g_L1NC[i].b + g_L1NC[i].c * rho); + } + var nL2Coefficients = g_L2NC.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2NC[i].a * Math.cos(g_L2NC[i].b + g_L2NC[i].c * rho); + } + var nL3Coefficients = g_L3NC.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3NC[i].a * Math.cos(g_L3NC[i].b + g_L3NC[i].c * rho); + } + var nL4Coefficients = g_L4NC.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4NC[i].a * Math.cos(g_L4NC[i].b + g_L4NC[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAANeptune.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0NC.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0NC[i].a * Math.cos(g_B0NC[i].b + g_B0NC[i].c * rho); + } + var nB1Coefficients = g_B1NC.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1NC[i].a * Math.cos(g_B1NC[i].b + g_B1NC[i].c * rho); + } + var nB2Coefficients = g_B2NC.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2NC[i].a * Math.cos(g_B2NC[i].b + g_B2NC[i].c * rho); + } + var nB3Coefficients = g_B3NC.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3NC[i].a * Math.cos(g_B3NC[i].b + g_B3NC[i].c * rho); + } + var nB4Coefficients = g_B4NC.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4NC[i].a * Math.cos(g_B4NC[i].b + g_B4NC[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAANeptune.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var nR0Coefficients = g_R0NC.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0NC[i].a * Math.cos(g_R0NC[i].b + g_R0NC[i].c * rho); + } + var nR1Coefficients = g_R1NC.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1NC[i].a * Math.cos(g_R1NC[i].b + g_R1NC[i].c * rho); + } + var nR2Coefficients = g_R2NC.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2NC[i].a * Math.cos(g_R2NC[i].b + g_R2NC[i].c * rho); + } + var nR3Coefficients = g_R3NC.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3NC[i].a * Math.cos(g_R3NC[i].b + g_R3NC[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed) / 100000000; +}; + +var CAANeptune$ = {}; + +registerType("CAANeptune", [CAANeptune, CAANeptune$, null]); diff --git a/engine/esm/astrocalc/nutation.js b/engine/esm/astrocalc/nutation.js new file mode 100644 index 00000000..a236ed87 --- /dev/null +++ b/engine/esm/astrocalc/nutation.js @@ -0,0 +1,145 @@ +// Originally `AANUTATION.CPP` +// "Purpose: Implementation for the algorithms for Nutation" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { C3D, CT } from "./coordinate_transformation.js"; +import { CAAEarth } from "./earth.js"; + + +// NUC - was NutationCoefficient + +export function NUC(D, M, Mprime, F, omega, sincoeff1, sincoeff2, coscoeff1, coscoeff2) { + this.d = 0; + this.m = 0; + this.mprime = 0; + this.f = 0; + this.omega = 0; + this.sincoeff1 = 0; + this.sincoeff2 = 0; + this.coscoeff1 = 0; + this.coscoeff2 = 0; + this.d = D; + this.m = M; + this.mprime = Mprime; + this.f = F; + this.omega = omega; + this.sincoeff1 = sincoeff1; + this.sincoeff2 = sincoeff2; + this.coscoeff1 = coscoeff1; + this.coscoeff2 = coscoeff2; +} + +var NUC$ = {}; + +registerType("NUC", [NUC, NUC$, null]); + + +// Coefficients + +const g_NuC = [new NUC(0, 0, 0, 0, 1, -171996, -174.2, 92025, 8.9), new NUC(-2, 0, 0, 2, 2, -13187, -1.6, 5736, -3.1), new NUC(0, 0, 0, 2, 2, -2274, -0.2, 977, -0.5), new NUC(0, 0, 0, 0, 2, 2062, 0.2, -895, 0.5), new NUC(0, 1, 0, 0, 0, 1426, -3.4, 54, -0.1), new NUC(0, 0, 1, 0, 0, 712, 0.1, -7, 0), new NUC(-2, 1, 0, 2, 2, -517, 1.2, 224, -0.6), new NUC(0, 0, 0, 2, 1, -386, -0.4, 200, 0), new NUC(0, 0, 1, 2, 2, -301, 0, 129, -0.1), new NUC(-2, -1, 0, 2, 2, 217, -0.5, -95, 0.3), new NUC(-2, 0, 1, 0, 0, -158, 0, 0, 0), new NUC(-2, 0, 0, 2, 1, 129, 0.1, -70, 0), new NUC(0, 0, -1, 2, 2, 123, 0, -53, 0), new NUC(2, 0, 0, 0, 0, 63, 0, 0, 0), new NUC(0, 0, 1, 0, 1, 63, 0.1, -33, 0), new NUC(2, 0, -1, 2, 2, -59, 0, 26, 0), new NUC(0, 0, -1, 0, 1, -58, -0.1, 32, 0), new NUC(0, 0, 1, 2, 1, -51, 0, 27, 0), new NUC(-2, 0, 2, 0, 0, 48, 0, 0, 0), new NUC(0, 0, -2, 2, 1, 46, 0, -24, 0), new NUC(2, 0, 0, 2, 2, -38, 0, 16, 0), new NUC(0, 0, 2, 2, 2, -31, 0, 13, 0), new NUC(0, 0, 2, 0, 0, 29, 0, 0, 0), new NUC(-2, 0, 1, 2, 2, 29, 0, -12, 0), new NUC(0, 0, 0, 2, 0, 26, 0, 0, 0), new NUC(-2, 0, 0, 2, 0, -22, 0, 0, 0), new NUC(0, 0, -1, 2, 1, 21, 0, -10, 0), new NUC(0, 2, 0, 0, 0, 17, -0.1, 0, 0), new NUC(2, 0, -1, 0, 1, 16, 0, -8, 0), new NUC(-2, 2, 0, 2, 2, -16, 0.1, 7, 0), new NUC(0, 1, 0, 0, 1, -15, 0, 9, 0), new NUC(-2, 0, 1, 0, 1, -13, 0, 7, 0), new NUC(0, -1, 0, 0, 1, -12, 0, 6, 0), new NUC(0, 0, 2, -2, 0, 11, 0, 0, 0), new NUC(2, 0, -1, 2, 1, -10, 0, 5, 0), new NUC(2, 0, 1, 2, 2, -8, 0, 3, 0), new NUC(0, 1, 0, 2, 2, 7, 0, -3, 0), new NUC(-2, 1, 1, 0, 0, -7, 0, 0, 0), new NUC(0, -1, 0, 2, 2, -7, 0, 3, 0), new NUC(2, 0, 0, 2, 1, -7, 0, 3, 0), new NUC(2, 0, 1, 0, 0, 6, 0, 0, 0), new NUC(-2, 0, 2, 2, 2, 6, 0, -3, 0), new NUC(-2, 0, 1, 2, 1, 6, 0, -3, 0), new NUC(2, 0, -2, 0, 1, -6, 0, 3, 0), new NUC(2, 0, 0, 0, 1, -6, 0, 3, 0), new NUC(0, -1, 1, 0, 0, 5, 0, 0, 0), new NUC(-2, -1, 0, 2, 1, -5, 0, 3, 0), new NUC(-2, 0, 0, 0, 1, -5, 0, 3, 0), new NUC(0, 0, 2, 2, 1, -5, 0, 3, 0), new NUC(-2, 0, 2, 0, 1, 4, 0, 0, 0), new NUC(-2, 1, 0, 2, 1, 4, 0, 0, 0), new NUC(0, 0, 1, -2, 0, 4, 0, 0, 0), new NUC(-1, 0, 1, 0, 0, -4, 0, 0, 0), new NUC(-2, 1, 0, 0, 0, -4, 0, 0, 0), new NUC(1, 0, 0, 0, 0, -4, 0, 0, 0), new NUC(0, 0, 1, 2, 0, 3, 0, 0, 0), new NUC(0, 0, -2, 2, 2, -3, 0, 0, 0), new NUC(-1, -1, 1, 0, 0, -3, 0, 0, 0), new NUC(0, 1, 1, 0, 0, -3, 0, 0, 0), new NUC(0, -1, 1, 2, 2, -3, 0, 0, 0), new NUC(2, -1, -1, 2, 2, -3, 0, 0, 0), new NUC(0, 0, 3, 2, 2, -3, 0, 0, 0), new NUC(2, -1, 0, 2, 2, -3, 0, 0, 0)]; + + +// CAANutation + +export function CAANutation() { } + +CAANutation.nutationInLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var D = 297.85036 + 445267.11148 * T - 0.0019142 * Tsquared + Tcubed / 189474; + D = CT.m360(D); + var M = 357.52772 + 35999.05034 * T - 0.0001603 * Tsquared - Tcubed / 300000; + M = CT.m360(M); + var Mprime = 134.96298 + 477198.867398 * T + 0.0086972 * Tsquared + Tcubed / 56250; + Mprime = CT.m360(Mprime); + var F = 93.27191 + 483202.017538 * T - 0.0036825 * Tsquared + Tcubed / 327270; + F = CT.m360(F); + var omega = 125.04452 - 1934.136261 * T + 0.0020708 * Tsquared + Tcubed / 450000; + omega = CT.m360(omega); + var nCoefficients = g_NuC.length; + var vvalue = 0; + for (var i = 0; i < nCoefficients; i++) { + var argument = g_NuC[i].d * D + g_NuC[i].m * M + g_NuC[i].mprime * Mprime + g_NuC[i].f * F + g_NuC[i].omega * omega; + var radargument = CT.d2R(argument); + vvalue += (g_NuC[i].sincoeff1 + g_NuC[i].sincoeff2 * T) * Math.sin(radargument) * 0.0001; + } + return vvalue; +}; + +CAANutation.nutationInObliquity = function (JD) { + var T = (JD - 2451545) / 36525; + var Tsquared = T * T; + var Tcubed = Tsquared * T; + var D = 297.85036 + 445267.11148 * T - 0.0019142 * Tsquared + Tcubed / 189474; + D = CT.m360(D); + var M = 357.52772 + 35999.05034 * T - 0.0001603 * Tsquared - Tcubed / 300000; + M = CT.m360(M); + var Mprime = 134.96298 + 477198.867398 * T + 0.0086972 * Tsquared + Tcubed / 56250; + Mprime = CT.m360(Mprime); + var F = 93.27191 + 483202.017538 * T - 0.0036825 * Tsquared + Tcubed / 327270; + F = CT.m360(F); + var omega = 125.04452 - 1934.136261 * T + 0.0020708 * Tsquared + Tcubed / 450000; + omega = CT.m360(omega); + var nCoefficients = g_NuC.length; + var vvalue = 0; + for (var i = 0; i < nCoefficients; i++) { + var argument = g_NuC[i].d * D + g_NuC[i].m * M + g_NuC[i].mprime * Mprime + g_NuC[i].f * F + g_NuC[i].omega * omega; + var radargument = CT.d2R(argument); + vvalue += (g_NuC[i].coscoeff1 + g_NuC[i].coscoeff2 * T) * Math.cos(radargument) * 0.0001; + } + return vvalue; +}; + +CAANutation.nutationInRightAscension = function (Alpha, Delta, Obliquity, NutationInLongitude, NutationInObliquity) { + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + Obliquity = CT.d2R(Obliquity); + return (Math.cos(Obliquity) + Math.sin(Obliquity) * Math.sin(Alpha) * Math.tan(Delta)) * NutationInLongitude - Math.cos(Alpha) * Math.tan(Delta) * NutationInObliquity; +}; + +CAANutation.nutationInDeclination = function (Alpha, Delta, Obliquity, NutationInLongitude, NutationInObliquity) { + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + Obliquity = CT.d2R(Obliquity); + return Math.sin(Obliquity) * Math.cos(Alpha) * NutationInLongitude + Math.sin(Alpha) * NutationInObliquity; +}; + +CAANutation.meanObliquityOfEcliptic = function (JD) { + var U = (JD - 2451545) / 3652500; + var Usquared = U * U; + var Ucubed = Usquared * U; + var U4 = Ucubed * U; + var U5 = U4 * U; + var U6 = U5 * U; + var U7 = U6 * U; + var U8 = U7 * U; + var U9 = U8 * U; + var U10 = U9 * U; + return CT.dmS2D(23, 26, 21.448) - CT.dmS2D(0, 0, 4680.93) * U - CT.dmS2D(0, 0, 1.55) * Usquared + CT.dmS2D(0, 0, 1999.25) * Ucubed - CT.dmS2D(0, 0, 51.38) * U4 - CT.dmS2D(0, 0, 249.67) * U5 - CT.dmS2D(0, 0, 39.05) * U6 + CT.dmS2D(0, 0, 7.12) * U7 + CT.dmS2D(0, 0, 27.87) * U8 + CT.dmS2D(0, 0, 5.79) * U9 + CT.dmS2D(0, 0, 2.45) * U10; +}; + +CAANutation.trueObliquityOfEcliptic = function (JD) { + return CAANutation.meanObliquityOfEcliptic(JD) + CT.dmS2D(0, 0, CAANutation.nutationInObliquity(JD)); +}; + +var CAANutation$ = {}; + +registerType("CAANutation", [CAANutation, CAANutation$, null]); diff --git a/engine/esm/astrocalc/parallax.js b/engine/esm/astrocalc/parallax.js new file mode 100644 index 00000000..4128557c --- /dev/null +++ b/engine/esm/astrocalc/parallax.js @@ -0,0 +1,128 @@ +// Originally `AAPARALLAX.CPP` +// "Purpose: Implementation for the algorithms which convert a geocentric set of coordinates to their topocentric equivalent" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { COR, CT } from "./coordinate_transformation.js"; +import { CAAGlobe } from "./globe.js"; +import { CAASidereal } from "./sidereal.js"; + + +// CAATopocentricEclipticDetails + +export function CAATopocentricEclipticDetails() { + this.lambda = 0; + this.beta = 0; + this.semidiameter = 0; + this.lambda = 0; + this.beta = 0; + this.semidiameter = 0; +} + +var CAATopocentricEclipticDetails$ = {}; + +registerType("CAATopocentricEclipticDetails", [CAATopocentricEclipticDetails, CAATopocentricEclipticDetails$, null]); + + +// Constants + +const g_AAParallax_C1 = Math.sin(CT.d2R(CT.dmS2D(0, 0, 8.794))); + + +// CAAParallax + +export function CAAParallax() { } + +CAAParallax.equatorial2TopocentricDelta = function (Alpha, Delta, Distance, Longitude, Latitude, Height, JD) { + var RhoSinThetaPrime = CAAGlobe.rhoSinThetaPrime(Latitude, Height); + var RhoCosThetaPrime = CAAGlobe.rhoCosThetaPrime(Latitude, Height); + var theta = CAASidereal.apparentGreenwichSiderealTime(JD); + Delta = CT.d2R(Delta); + var cosDelta = Math.cos(Delta); + var pi = Math.asin(g_AAParallax_C1 / Distance); + var H = CT.h2R(theta - Longitude / 15 - Alpha); + var cosH = Math.cos(H); + var sinH = Math.sin(H); + var DeltaTopocentric = new COR(); + DeltaTopocentric.x = CT.r2H(-pi * RhoCosThetaPrime * sinH / cosDelta); + DeltaTopocentric.y = CT.r2D(-pi * (RhoSinThetaPrime * cosDelta - RhoCosThetaPrime * cosH * Math.sin(Delta))); + return DeltaTopocentric; +}; + +CAAParallax.equatorial2Topocentric = function (Alpha, Delta, Distance, Longitude, Latitude, Height, JD) { + var RhoSinThetaPrime = CAAGlobe.rhoSinThetaPrime(Latitude, Height); + var RhoCosThetaPrime = CAAGlobe.rhoCosThetaPrime(Latitude, Height); + var theta = CAASidereal.apparentGreenwichSiderealTime(JD); + Delta = CT.d2R(Delta); + var cosDelta = Math.cos(Delta); + var pi = Math.asin(g_AAParallax_C1 / Distance); + var sinpi = Math.sin(pi); + var H = CT.h2R(theta - Longitude / 15 - Alpha); + var cosH = Math.cos(H); + var sinH = Math.sin(H); + var DeltaAlpha = Math.atan2(-RhoCosThetaPrime * sinpi * sinH, cosDelta - RhoCosThetaPrime * sinpi * cosH); + var Topocentric = new COR(); + Topocentric.x = CT.m24(Alpha + CT.r2H(DeltaAlpha)); + Topocentric.y = CT.r2D(Math.atan2((Math.sin(Delta) - RhoSinThetaPrime * sinpi) * Math.cos(DeltaAlpha), cosDelta - RhoCosThetaPrime * sinpi * cosH)); + return Topocentric; +}; + +CAAParallax.ecliptic2Topocentric = function (Lambda, Beta, Semidiameter, Distance, Epsilon, Longitude, Latitude, Height, JD) { + var S = CAAGlobe.rhoSinThetaPrime(Latitude, Height); + var C = CAAGlobe.rhoCosThetaPrime(Latitude, Height); + Lambda = CT.d2R(Lambda); + Beta = CT.d2R(Beta); + Epsilon = CT.d2R(Epsilon); + Longitude = CT.d2R(Longitude); + Latitude = CT.d2R(Latitude); + Semidiameter = CT.d2R(Semidiameter); + var sine = Math.sin(Epsilon); + var cose = Math.cos(Epsilon); + var cosBeta = Math.cos(Beta); + var sinBeta = Math.sin(Beta); + var theta = CAASidereal.apparentGreenwichSiderealTime(JD); + theta = CT.h2R(theta); + var sintheta = Math.sin(theta); + var pi = Math.asin(g_AAParallax_C1 / Distance); + var sinpi = Math.sin(pi); + var N = Math.cos(Lambda) * cosBeta - C * sinpi * Math.cos(theta); + var Topocentric = new CAATopocentricEclipticDetails(); + Topocentric.lambda = Math.atan2(Math.sin(Lambda) * cosBeta - sinpi * (S * sine + C * cose * sintheta), N); + var cosTopocentricLambda = Math.cos(Topocentric.lambda); + Topocentric.beta = Math.atan(cosTopocentricLambda * (sinBeta - sinpi * (S * cose - C * sine * sintheta)) / N); + Topocentric.semidiameter = Math.asin(cosTopocentricLambda * Math.cos(Topocentric.beta) * Math.sin(Semidiameter) / N); + Topocentric.semidiameter = CT.r2D(Topocentric.semidiameter); + Topocentric.lambda = CT.m360(CT.r2D(Topocentric.lambda)); + Topocentric.beta = CT.r2D(Topocentric.beta); + return Topocentric; +}; + +CAAParallax.parallaxToDistance = function (Parallax) { + return g_AAParallax_C1 / Math.sin(CT.d2R(Parallax)); +}; + +CAAParallax.distanceToParallax = function (Distance) { + var pi = Math.asin(g_AAParallax_C1 / Distance); + return CT.r2D(pi); +}; + +var CAAParallax$ = {}; + +registerType("CAAParallax", [CAAParallax, CAAParallax$, null]); diff --git a/engine/esm/astrocalc/physical_jupiter.js b/engine/esm/astrocalc/physical_jupiter.js new file mode 100644 index 00000000..99f50638 --- /dev/null +++ b/engine/esm/astrocalc/physical_jupiter.js @@ -0,0 +1,138 @@ +// Originally `AAPHYSICALJUPITER.CPP` +// "Purpose: Implementation for the algorithms which obtain the physical parameters of the Jupiter" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAANutation } from "./nutation.js"; +import { CAAEarth } from "./earth.js"; +import { CAAJupiter } from "./jupiter.js"; + + +// CAAPhysicalJupiterDetails + +export function CAAPhysicalJupiterDetails() { + this.DE = 0; + this.DS = 0; + this.geometricw1 = 0; + this.geometricw2 = 0; + this.apparentw1 = 0; + this.apparentw2 = 0; + this.p = 0; + this.DE = 0; + this.DS = 0; + this.geometricw1 = 0; + this.geometricw2 = 0; + this.apparentw1 = 0; + this.apparentw2 = 0; + this.p = 0; +} + +var CAAPhysicalJupiterDetails$ = {}; + +registerType("CAAPhysicalJupiterDetails", [CAAPhysicalJupiterDetails, CAAPhysicalJupiterDetails$, null]); + + +// CAAPhysicalJupiter + +export function CAAPhysicalJupiter() { } + +CAAPhysicalJupiter.calculate = function (JD) { + var details = new CAAPhysicalJupiterDetails(); + var d = JD - 2433282.5; + var T1 = d / 36525; + var alpha0 = 268 + 0.1061 * T1; + var alpha0rad = CT.d2R(alpha0); + var delta0 = 64.5 - 0.0164 * T1; + var delta0rad = CT.d2R(delta0); + var W1 = CT.m360(17.71 + 877.90003539 * d); + var W2 = CT.m360(16.838 + 870.27003539 * d); + var l0 = CAAEarth.eclipticLongitude(JD); + var l0rad = CT.d2R(l0); + var b0 = CAAEarth.eclipticLatitude(JD); + var b0rad = CT.d2R(b0); + var R = CAAEarth.radiusVector(JD); + var l = CAAJupiter.eclipticLongitude(JD); + var lrad = CT.d2R(l); + var b = CAAJupiter.eclipticLatitude(JD); + var brad = CT.d2R(b); + var r = CAAJupiter.radiusVector(JD); + var x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); + var y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); + var z = r * Math.sin(brad) - R * Math.sin(b0rad); + var DELTA = Math.sqrt(x * x + y * y + z * z); + l -= 0.01299 * DELTA / (r * r); + lrad = CT.d2R(l); + x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); + y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); + z = r * Math.sin(brad) - R * Math.sin(b0rad); + DELTA = Math.sqrt(x * x + y * y + z * z); + var e0 = CAANutation.meanObliquityOfEcliptic(JD); + var e0rad = CT.d2R(e0); + var alphas = Math.atan2(Math.cos(e0rad) * Math.sin(lrad) - Math.sin(e0rad) * Math.tan(brad), Math.cos(lrad)); + var deltas = Math.asin(Math.cos(e0rad) * Math.sin(brad) + Math.sin(e0rad) * Math.cos(brad) * Math.sin(lrad)); + details.DS = CT.r2D(Math.asin(-Math.sin(delta0rad) * Math.sin(deltas) - Math.cos(delta0rad) * Math.cos(deltas) * Math.cos(alpha0rad - alphas))); + var u = y * Math.cos(e0rad) - z * Math.sin(e0rad); + var v = y * Math.sin(e0rad) + z * Math.cos(e0rad); + var alpharad = Math.atan2(u, x); + var alpha = CT.r2D(alpharad); + var deltarad = Math.atan2(v, Math.sqrt(x * x + u * u)); + var delta = CT.r2D(deltarad); + var xi = Math.atan2(Math.sin(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad) - Math.sin(deltarad) * Math.cos(delta0rad), Math.cos(deltarad) * Math.sin(alpha0rad - alpharad)); + details.DE = CT.r2D(Math.asin(-Math.sin(delta0rad) * Math.sin(deltarad) - Math.cos(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad))); + details.geometricw1 = CT.m360(W1 - CT.r2D(xi) - 5.07033 * DELTA); + details.geometricw2 = CT.m360(W2 - CT.r2D(xi) - 5.02626 * DELTA); + var C = 57.2958 * (2 * r * DELTA + R * R - r * r - DELTA * DELTA) / (4 * r * DELTA); + if (Math.sin(lrad - l0rad) > 0) { + details.apparentw1 = CT.m360(details.geometricw1 + C); + details.apparentw2 = CT.m360(details.geometricw2 + C); + } + else { + details.apparentw1 = CT.m360(details.geometricw1 - C); + details.apparentw2 = CT.m360(details.geometricw2 - C); + } + var NutationInLongitude = CAANutation.nutationInLongitude(JD); + var NutationInObliquity = CAANutation.nutationInObliquity(JD); + e0 += NutationInObliquity / 3600; + e0rad = CT.d2R(e0); + alpha += 0.005693 * (Math.cos(alpharad) * Math.cos(l0rad) * Math.cos(e0rad) + Math.sin(alpharad) * Math.sin(l0rad)) / Math.cos(deltarad); + alpha = CT.m360(alpha); + alpharad = CT.d2R(alpha); + delta += 0.005693 * (Math.cos(l0rad) * Math.cos(e0rad) * (Math.tan(e0rad) * Math.cos(deltarad) - Math.sin(alpharad) * Math.sin(deltarad)) + Math.cos(alpharad) * Math.sin(deltarad) * Math.sin(l0rad)); + deltarad = CT.d2R(delta); + var NutationRA = CAANutation.nutationInRightAscension(alpha / 15, delta, e0, NutationInLongitude, NutationInObliquity); + var alphadash = alpha + NutationRA / 3600; + var alphadashrad = CT.d2R(alphadash); + var NutationDec = CAANutation.nutationInDeclination(alpha / 15, delta, e0, NutationInLongitude, NutationInObliquity); + var deltadash = delta + NutationDec / 3600; + var deltadashrad = CT.d2R(deltadash); + NutationRA = CAANutation.nutationInRightAscension(alpha0 / 15, delta0, e0, NutationInLongitude, NutationInObliquity); + var alpha0dash = alpha0 + NutationRA / 3600; + var alpha0dashrad = CT.d2R(alpha0dash); + NutationDec = CAANutation.nutationInDeclination(alpha0 / 15, delta0, e0, NutationInLongitude, NutationInObliquity); + var delta0dash = delta0 + NutationDec / 3600; + var delta0dashrad = CT.d2R(delta0dash); + details.p = CT.m360(CT.r2D(Math.atan2(Math.cos(delta0dashrad) * Math.sin(alpha0dashrad - alphadashrad), Math.sin(delta0dashrad) * Math.cos(deltadashrad) - Math.cos(delta0dashrad) * Math.sin(deltadashrad) * Math.cos(alpha0dashrad - alphadashrad)))); + return details; +}; + +var CAAPhysicalJupiter$ = {}; + +registerType("CAAPhysicalJupiter", [CAAPhysicalJupiter, CAAPhysicalJupiter$, null]); diff --git a/engine/esm/astrocalc/physical_mars.js b/engine/esm/astrocalc/physical_mars.js new file mode 100644 index 00000000..9239437c --- /dev/null +++ b/engine/esm/astrocalc/physical_mars.js @@ -0,0 +1,158 @@ +// Originally `AAPHYSICALMARS.CPP` +// "Purpose: Implementation for the algorithms which obtain the physical parameters of Mars" +// Last update of original: PJN / 04-01-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAANutation } from "./nutation.js"; +import { CAASun } from "./sun.js"; +import { CAAEarth } from "./earth.js"; +import { CAAMars } from "./mars.js"; +import { ELL } from "./elliptical.js"; +import { IFR } from "./illuminated_fraction.js"; +import { MIFR } from "./moon_illuminated_fraction.js"; + +// CAAPhysicalMarsDetails + +export function CAAPhysicalMarsDetails() { + this.DE = 0; + this.DS = 0; + this.w = 0; + this.p = 0; + this.x = 0; + this.k = 0; + this.q = 0; + this.d = 0; + this.DE = 0; + this.DS = 0; + this.w = 0; + this.p = 0; + this.x = 0; + this.k = 0; + this.q = 0; + this.d = 0; +} + +var CAAPhysicalMarsDetails$ = {}; + +registerType("CAAPhysicalMarsDetails", [CAAPhysicalMarsDetails, CAAPhysicalMarsDetails$, null]); + + +// CAAPhysicalMars + +export function CAAPhysicalMars() { } + +CAAPhysicalMars.calculate = function (JD) { + var details = new CAAPhysicalMarsDetails(); + var T = (JD - 2451545) / 36525; + var Lambda0 = 352.9065 + 1.1733 * T; + var Lambda0rad = CT.d2R(Lambda0); + var Beta0 = 63.2818 - 0.00394 * T; + var Beta0rad = CT.d2R(Beta0); + var l0 = CAAEarth.eclipticLongitude(JD); + var l0rad = CT.d2R(l0); + var b0 = CAAEarth.eclipticLatitude(JD); + var b0rad = CT.d2R(b0); + var R = CAAEarth.radiusVector(JD); + var PreviousLightTravelTime = 0; + var LightTravelTime = 0; + var x = 0; + var y = 0; + var z = 0; + var bIterate = true; + var DELTA = 0; + var l = 0; + var lrad = 0; + var b = 0; + var brad = 0; + var r = 0; + while (bIterate) { + var JD2 = JD - LightTravelTime; + l = CAAMars.eclipticLongitude(JD2); + lrad = CT.d2R(l); + b = CAAMars.eclipticLatitude(JD2); + brad = CT.d2R(b); + r = CAAMars.radiusVector(JD2); + x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); + y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); + z = r * Math.sin(brad) - R * Math.sin(b0rad); + DELTA = Math.sqrt(x * x + y * y + z * z); + LightTravelTime = ELL.distanceToLightTime(DELTA); + bIterate = (Math.abs(LightTravelTime - PreviousLightTravelTime) > 2E-06); + if (bIterate) { + PreviousLightTravelTime = LightTravelTime; + } + } + var lambdarad = Math.atan2(y, x); + var lambda = CT.r2D(lambdarad); + var betarad = Math.atan2(z, Math.sqrt(x * x + y * y)); + var beta = CT.r2D(betarad); + details.DE = CT.r2D(Math.asin(-Math.sin(Beta0rad) * Math.sin(betarad) - Math.cos(Beta0rad) * Math.cos(betarad) * Math.cos(Lambda0rad - lambdarad))); + var N = 49.5581 + 0.7721 * T; + var Nrad = CT.d2R(N); + var ldash = l - 0.00697 / r; + var ldashrad = CT.d2R(ldash); + var bdash = b - 0.000225 * (Math.cos(lrad - Nrad) / r); + var bdashrad = CT.d2R(bdash); + details.DS = CT.r2D(Math.asin(-Math.sin(Beta0rad) * Math.sin(bdashrad) - Math.cos(Beta0rad) * Math.cos(bdashrad) * Math.cos(Lambda0rad - ldashrad))); + var W = CT.m360(11.504 + 350.89200025 * (JD - LightTravelTime - 2433282.5)); + var e0 = CAANutation.meanObliquityOfEcliptic(JD); + var e0rad = CT.d2R(e0); + var PoleEquatorial = CT.ec2Eq(Lambda0, Beta0, e0); + var alpha0rad = CT.h2R(PoleEquatorial.x); + var delta0rad = CT.d2R(PoleEquatorial.y); + var u = y * Math.cos(e0rad) - z * Math.sin(e0rad); + var v = y * Math.sin(e0rad) + z * Math.cos(e0rad); + var alpharad = Math.atan2(u, x); + var alpha = CT.r2H(alpharad); + var deltarad = Math.atan2(v, Math.sqrt(x * x + u * u)); + var delta = CT.r2D(deltarad); + var xi = Math.atan2(Math.sin(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad) - Math.sin(deltarad) * Math.cos(delta0rad), Math.cos(deltarad) * Math.sin(alpha0rad - alpharad)); + details.w = CT.m360(W - CT.r2D(xi)); + var NutationInLongitude = CAANutation.nutationInLongitude(JD); + var NutationInObliquity = CAANutation.nutationInObliquity(JD); + lambda += 0.005693 * Math.cos(l0rad - lambdarad) / Math.cos(betarad); + beta += 0.005693 * Math.sin(l0rad - lambdarad) * Math.sin(betarad); + Lambda0 += NutationInLongitude / 3600; + Lambda0rad = CT.d2R(Lambda0); + lambda += NutationInLongitude / 3600; + lambdarad = CT.d2R(lambda); + e0 += NutationInObliquity / 3600; + e0rad = CT.d2R(e0rad); + var ApparentPoleEquatorial = CT.ec2Eq(Lambda0, Beta0, e0); + var alpha0dash = CT.h2R(ApparentPoleEquatorial.x); + var delta0dash = CT.d2R(ApparentPoleEquatorial.y); + var ApparentMars = CT.ec2Eq(lambda, beta, e0); + var alphadash = CT.h2R(ApparentMars.x); + var deltadash = CT.d2R(ApparentMars.y); + details.p = CT.m360(CT.r2D(Math.atan2(Math.cos(delta0dash) * Math.sin(alpha0dash - alphadash), Math.sin(delta0dash) * Math.cos(deltadash) - Math.cos(delta0dash) * Math.sin(deltadash) * Math.cos(alpha0dash - alphadash)))); + var SunLambda = CAASun.geometricEclipticLongitude(JD); + var SunBeta = CAASun.geometricEclipticLatitude(JD); + var SunEquatorial = CT.ec2Eq(SunLambda, SunBeta, e0); + details.x = MIFR.positionAngle(SunEquatorial.x, SunEquatorial.y, alpha, delta); + details.d = 9.36 / DELTA; + details.k = IFR.illuminatedFraction2(r, R, DELTA); + details.q = (1 - details.k) * details.d; + return details; +}; + +var CAAPhysicalMars$ = {}; + +registerType("CAAPhysicalMars", [CAAPhysicalMars, CAAPhysicalMars$, null]); diff --git a/engine/esm/astrocalc/physical_sun.js b/engine/esm/astrocalc/physical_sun.js new file mode 100644 index 00000000..0d6ff315 --- /dev/null +++ b/engine/esm/astrocalc/physical_sun.js @@ -0,0 +1,83 @@ +// Originally `AAPHYSICALSUN.CPP` +// "Purpose: Implementation for the algorithms which obtain the physical parameters of the Sun" +// Last update of original: PJN / 16-06-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAANutation } from "./nutation.js"; +import { CAAEarth } from "./earth.js"; + + +// CAAPhysicalSunDetails + +export function CAAPhysicalSunDetails() { + this.p = 0; + this.b0 = 0; + this.l0 = 0; + this.p = 0; + this.b0 = 0; + this.l0 = 0; +} + +var CAAPhysicalSunDetails$ = {}; + +registerType("CAAPhysicalSunDetails", [CAAPhysicalSunDetails, CAAPhysicalSunDetails$, null]); + + +// CAAPhysicalSun + +export function CAAPhysicalSun() { } + +CAAPhysicalSun.calculate = function (JD) { + var theta = CT.m360((JD - 2398220) * 360 / 25.38); + var I = 7.25; + var K = 73.6667 + 1.3958333 * (JD - 2396758) / 36525; + var L = CAAEarth.eclipticLongitude(JD); + var R = CAAEarth.radiusVector(JD); + var SunLong = L + 180 - CT.dmS2D(0, 0, 20.4898 / R); + var SunLongDash = SunLong + CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)); + var epsilon = CAANutation.trueObliquityOfEcliptic(JD); + epsilon = CT.d2R(epsilon); + SunLong = CT.d2R(SunLong); + SunLongDash = CT.d2R(SunLongDash); + K = CT.d2R(K); + I = CT.d2R(I); + theta = CT.d2R(theta); + var x = Math.atan(-Math.cos(SunLong) * Math.tan(epsilon)); + var y = Math.atan(-Math.cos(SunLong - K) * Math.tan(I)); + var details = new CAAPhysicalSunDetails(); + details.p = CT.r2D(x + y); + details.b0 = CT.r2D(Math.asin(Math.sin(SunLong - K) * Math.sin(I))); + var eta = Math.atan(Math.tan(SunLong - K) * Math.cos(I)); + details.l0 = CT.m360(CT.r2D(eta - theta)); + return details; +}; + +CAAPhysicalSun.timeOfStartOfRotation = function (C) { + var JED = 2398140.227 + 27.2752316 * C; + var M = CT.m360(281.96 + 26.882476 * C); + M = CT.d2R(M); + JED += (0.1454 * Math.sin(M) - 0.0085 * Math.sin(2 * M) - 0.0141 * Math.cos(2 * M)); + return JED; +}; + +var CAAPhysicalSun$ = {}; + +registerType("CAAPhysicalSun", [CAAPhysicalSun, CAAPhysicalSun$, null]); diff --git a/engine/esm/astrocalc/pluto.js b/engine/esm/astrocalc/pluto.js new file mode 100644 index 00000000..5a36ba58 --- /dev/null +++ b/engine/esm/astrocalc/pluto.js @@ -0,0 +1,122 @@ +// Originally `AAPLUTO.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Pluto" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; + + +// PlutoCoefficient1 + +export function PlutoCoefficient1(j, s, p) { + this.j = 0; + this.s = 0; + this.p = 0; + this.j = j; + this.s = s; + this.p = p; +} + +var PlutoCoefficient1$ = {}; + +registerType("PlutoCoefficient1", [PlutoCoefficient1, PlutoCoefficient1$, null]); + + +// PlutoCoefficient2 + +export function PlutoCoefficient2(a, b) { + this.a = 0; + this.b = 0; + this.a = a; + this.b = b; +} + +var PlutoCoefficient2$ = {}; + +registerType("PlutoCoefficient2", [PlutoCoefficient2, PlutoCoefficient2$, null]); + + +// Coefficients + +const g_PlutoArgumentCoefficients = [new PlutoCoefficient1(0, 0, 1), new PlutoCoefficient1(0, 0, 2), new PlutoCoefficient1(0, 0, 3), new PlutoCoefficient1(0, 0, 4), new PlutoCoefficient1(0, 0, 5), new PlutoCoefficient1(0, 0, 6), new PlutoCoefficient1(0, 1, -1), new PlutoCoefficient1(0, 1, 0), new PlutoCoefficient1(0, 1, 1), new PlutoCoefficient1(0, 1, 2), new PlutoCoefficient1(0, 1, 3), new PlutoCoefficient1(0, 2, -2), new PlutoCoefficient1(0, 2, -1), new PlutoCoefficient1(0, 2, 0), new PlutoCoefficient1(1, -1, 0), new PlutoCoefficient1(1, -1, 1), new PlutoCoefficient1(1, 0, -3), new PlutoCoefficient1(1, 0, -2), new PlutoCoefficient1(1, 0, -1), new PlutoCoefficient1(1, 0, 0), new PlutoCoefficient1(1, 0, 1), new PlutoCoefficient1(1, 0, 2), new PlutoCoefficient1(1, 0, 3), new PlutoCoefficient1(1, 0, 4), new PlutoCoefficient1(1, 1, -3), new PlutoCoefficient1(1, 1, -2), new PlutoCoefficient1(1, 1, -1), new PlutoCoefficient1(1, 1, 0), new PlutoCoefficient1(1, 1, 1), new PlutoCoefficient1(1, 1, 3), new PlutoCoefficient1(2, 0, -6), new PlutoCoefficient1(2, 0, -5), new PlutoCoefficient1(2, 0, -4), new PlutoCoefficient1(2, 0, -3), new PlutoCoefficient1(2, 0, -2), new PlutoCoefficient1(2, 0, -1), new PlutoCoefficient1(2, 0, 0), new PlutoCoefficient1(2, 0, 1), new PlutoCoefficient1(2, 0, 2), new PlutoCoefficient1(2, 0, 3), new PlutoCoefficient1(3, 0, -2), new PlutoCoefficient1(3, 0, -1), new PlutoCoefficient1(3, 0, 0)]; +const g_PlutoLongitudeCoefficients = [new PlutoCoefficient2(-19799805, 19850055), new PlutoCoefficient2(897144, -4954829), new PlutoCoefficient2(611149, 1211027), new PlutoCoefficient2(-341243, -189585), new PlutoCoefficient2(129287, -34992), new PlutoCoefficient2(-38164, 30893), new PlutoCoefficient2(20442, -9987), new PlutoCoefficient2(-4063, -5071), new PlutoCoefficient2(-6016, -3336), new PlutoCoefficient2(-3956, 3039), new PlutoCoefficient2(-667, 3572), new PlutoCoefficient2(1276, 501), new PlutoCoefficient2(1152, -917), new PlutoCoefficient2(630, -1277), new PlutoCoefficient2(2571, -459), new PlutoCoefficient2(899, -1449), new PlutoCoefficient2(-1016, 1043), new PlutoCoefficient2(-2343, -1012), new PlutoCoefficient2(7042, 788), new PlutoCoefficient2(1199, -338), new PlutoCoefficient2(418, -67), new PlutoCoefficient2(120, -274), new PlutoCoefficient2(-60, -159), new PlutoCoefficient2(-82, -29), new PlutoCoefficient2(-36, -29), new PlutoCoefficient2(-40, 7), new PlutoCoefficient2(-14, 22), new PlutoCoefficient2(4, 13), new PlutoCoefficient2(5, 2), new PlutoCoefficient2(-1, 0), new PlutoCoefficient2(2, 0), new PlutoCoefficient2(-4, 5), new PlutoCoefficient2(4, -7), new PlutoCoefficient2(14, 24), new PlutoCoefficient2(-49, -34), new PlutoCoefficient2(163, -48), new PlutoCoefficient2(9, -24), new PlutoCoefficient2(-4, 1), new PlutoCoefficient2(-3, 1), new PlutoCoefficient2(1, 3), new PlutoCoefficient2(-3, -1), new PlutoCoefficient2(5, -3), new PlutoCoefficient2(0, 0)]; +const g_PlutoLatitudeCoefficients = [new PlutoCoefficient2(-5452852, -14974862), new PlutoCoefficient2(3527812, 1672790), new PlutoCoefficient2(-1050748, 327647), new PlutoCoefficient2(178690, -292153), new PlutoCoefficient2(18650, 100340), new PlutoCoefficient2(-30697, -25823), new PlutoCoefficient2(4878, 11248), new PlutoCoefficient2(226, -64), new PlutoCoefficient2(2030, -836), new PlutoCoefficient2(69, -604), new PlutoCoefficient2(-247, -567), new PlutoCoefficient2(-57, 1), new PlutoCoefficient2(-122, 175), new PlutoCoefficient2(-49, -164), new PlutoCoefficient2(-197, 199), new PlutoCoefficient2(-25, 217), new PlutoCoefficient2(589, -248), new PlutoCoefficient2(-269, 711), new PlutoCoefficient2(185, 193), new PlutoCoefficient2(315, 807), new PlutoCoefficient2(-130, -43), new PlutoCoefficient2(5, 3), new PlutoCoefficient2(2, 17), new PlutoCoefficient2(2, 5), new PlutoCoefficient2(2, 3), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(2, -1), new PlutoCoefficient2(1, -1), new PlutoCoefficient2(0, -1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-7, 0), new PlutoCoefficient2(10, -8), new PlutoCoefficient2(-3, 20), new PlutoCoefficient2(6, 5), new PlutoCoefficient2(14, 17), new PlutoCoefficient2(-2, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(1, 0)]; +const g_PlutoRadiusCoefficients = [new PlutoCoefficient2(66865439, 68951812), new PlutoCoefficient2(-11827535, -332538), new PlutoCoefficient2(1593179, -1438890), new PlutoCoefficient2(-18444, 483220), new PlutoCoefficient2(-65977, -85431), new PlutoCoefficient2(31174, -6032), new PlutoCoefficient2(-5794, 22161), new PlutoCoefficient2(4601, 4032), new PlutoCoefficient2(-1729, 234), new PlutoCoefficient2(-415, 702), new PlutoCoefficient2(239, 723), new PlutoCoefficient2(67, -67), new PlutoCoefficient2(1034, -451), new PlutoCoefficient2(-129, 504), new PlutoCoefficient2(480, -231), new PlutoCoefficient2(2, -441), new PlutoCoefficient2(-3359, 265), new PlutoCoefficient2(7856, -7832), new PlutoCoefficient2(36, 45763), new PlutoCoefficient2(8663, 8547), new PlutoCoefficient2(-809, -769), new PlutoCoefficient2(263, -144), new PlutoCoefficient2(-126, 32), new PlutoCoefficient2(-35, -16), new PlutoCoefficient2(-19, -4), new PlutoCoefficient2(-15, 8), new PlutoCoefficient2(-4, 12), new PlutoCoefficient2(5, 6), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(6, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-2, -2), new PlutoCoefficient2(14, 13), new PlutoCoefficient2(-63, 13), new PlutoCoefficient2(136, -236), new PlutoCoefficient2(273, 1065), new PlutoCoefficient2(251, 149), new PlutoCoefficient2(-25, -9), new PlutoCoefficient2(9, -2), new PlutoCoefficient2(-8, 7), new PlutoCoefficient2(2, -10), new PlutoCoefficient2(19, 35), new PlutoCoefficient2(10, 3)]; + + +// CAAPluto + +export function CAAPluto() { } + +CAAPluto.eclipticLongitude = function (JD) { + var T = (JD - 2451545) / 36525; + var J = 34.35 + 3034.9057 * T; + var S = 50.08 + 1222.1138 * T; + var P = 238.96 + 144.96 * T; + var L = 0; + var nPlutoCoefficients = g_PlutoArgumentCoefficients.length; + for (var i = 0; i < nPlutoCoefficients; i++) { + var Alpha = g_PlutoArgumentCoefficients[i].j * J + g_PlutoArgumentCoefficients[i].s * S + g_PlutoArgumentCoefficients[i].p * P; + Alpha = CT.d2R(Alpha); + L += ((g_PlutoLongitudeCoefficients[i].a * Math.sin(Alpha)) + (g_PlutoLongitudeCoefficients[i].b * Math.cos(Alpha))); + } + L = L / 1000000; + L += (238.958116 + 144.96 * T); + L = CT.m360(L); + return L; +}; + +CAAPluto.eclipticLatitude = function (JD) { + var T = (JD - 2451545) / 36525; + var J = 34.35 + 3034.9057 * T; + var S = 50.08 + 1222.1138 * T; + var P = 238.96 + 144.96 * T; + var L = 0; + var nPlutoCoefficients = g_PlutoArgumentCoefficients.length; + for (var i = 0; i < nPlutoCoefficients; i++) { + var Alpha = g_PlutoArgumentCoefficients[i].j * J + g_PlutoArgumentCoefficients[i].s * S + g_PlutoArgumentCoefficients[i].p * P; + Alpha = CT.d2R(Alpha); + L += ((g_PlutoLatitudeCoefficients[i].a * Math.sin(Alpha)) + (g_PlutoLatitudeCoefficients[i].b * Math.cos(Alpha))); + } + L = L / 1000000; + L += -3.908239; + return L; +}; + +CAAPluto.radiusVector = function (JD) { + var T = (JD - 2451545) / 36525; + var J = 34.35 + 3034.9057 * T; + var S = 50.08 + 1222.1138 * T; + var P = 238.96 + 144.96 * T; + var R = 0; + var nPlutoCoefficients = g_PlutoArgumentCoefficients.length; + for (var i = 0; i < nPlutoCoefficients; i++) { + var Alpha = g_PlutoArgumentCoefficients[i].j * J + g_PlutoArgumentCoefficients[i].s * S + g_PlutoArgumentCoefficients[i].p * P; + Alpha = CT.d2R(Alpha); + R += ((g_PlutoRadiusCoefficients[i].a * Math.sin(Alpha)) + (g_PlutoRadiusCoefficients[i].b * Math.cos(Alpha))); + } + R = R / 10000000; + R += 40.7241346; + return R; +}; + +var CAAPluto$ = {}; + +registerType("CAAPluto", [CAAPluto, CAAPluto$, null]); diff --git a/engine/esm/astrocalc/precession.js b/engine/esm/astrocalc/precession.js new file mode 100644 index 00000000..87e7632c --- /dev/null +++ b/engine/esm/astrocalc/precession.js @@ -0,0 +1,154 @@ +// Originally `AAPRECESSION.CPP` +// "Purpose: Implementation for the algorithms for Precession" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { COR, CT } from "./coordinate_transformation.js"; + + +// CAAPrecession + +export function CAAPrecession() { } + +CAAPrecession.precessEquatorial = function (Alpha, Delta, JD0, JD) { + var T = (JD0 - 2451545) / 36525; + var Tsquared = T * T; + var t = (JD - JD0) / 36525; + var tsquared = t * t; + var tcubed = tsquared * t; + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + var sigma = (2306.2181 + 1.39656 * T - 0.000139 * Tsquared) * t + (0.30188 - 3.44E-05 * T) * tsquared + 0.017988 * tcubed; + sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); + var zeta = (2306.2181 + 1.39656 * T - 0.000138 * Tsquared) * t + (1.09468 + 6.6E-05 * T) * tsquared + 0.018203 * tcubed; + zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); + var phi = (2004.3109 - 0.8533 * T - 0.000217 * Tsquared) * t - (0.42665 + 0.000217 * T) * tsquared - 0.041833 * tcubed; + phi = CT.d2R(CT.dmS2D(0, 0, phi)); + var A = Math.cos(Delta) * Math.sin(Alpha + sigma); + var B = Math.cos(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) - Math.sin(phi) * Math.sin(Delta); + var C = Math.sin(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) + Math.cos(phi) * Math.sin(Delta); + var vvalue = new COR(); + vvalue.x = CT.r2H(Math.atan2(A, B) + zeta); + if (vvalue.x < 0) { + vvalue.x += 24; + } + vvalue.y = CT.r2D(Math.asin(C)); + return vvalue; +}; + +CAAPrecession.precessEquatorialFK4 = function (Alpha, Delta, JD0, JD) { + var T = (JD0 - 2415020.3135) / 36524.2199; + var t = (JD - JD0) / 36524.2199; + var tsquared = t * t; + var tcubed = tsquared * t; + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + var sigma = (2304.25 + 1.396 * T) * t + 0.302 * tsquared + 0.018 * tcubed; + sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); + var zeta = 0.791 * tsquared + 0.001 * tcubed; + zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); + zeta += sigma; + var phi = (2004.682 - 0.853 * T) * t - 0.426 * tsquared - 0.042 * tcubed; + phi = CT.d2R(CT.dmS2D(0, 0, phi)); + var A = Math.cos(Delta) * Math.sin(Alpha + sigma); + var B = Math.cos(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) - Math.sin(phi) * Math.sin(Delta); + var C = Math.sin(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) + Math.cos(phi) * Math.sin(Delta); + var vvalue = new COR(); + vvalue.x = CT.r2H(Math.atan2(A, B) + zeta); + if (vvalue.x < 0) { + vvalue.x += 24; + } + vvalue.y = CT.r2D(Math.asin(C)); + return vvalue; +}; + +CAAPrecession.precessEcliptic = function (Lambda, Beta, JD0, JD) { + var T = (JD0 - 2451545) / 36525; + var Tsquared = T * T; + var t = (JD - JD0) / 36525; + var tsquared = t * t; + var tcubed = tsquared * t; + Lambda = CT.d2R(Lambda); + Beta = CT.d2R(Beta); + var eta = (47.0029 - 0.06603 * T + 0.000598 * Tsquared) * t + (-0.03302 + 0.000598 * T) * tsquared + 6E-05 * tcubed; + eta = CT.d2R(CT.dmS2D(0, 0, eta)); + var pi = 174.876384 * 3600 + 3289.4789 * T + 0.60622 * Tsquared - (869.8089 + 0.50491 * T) * t + 0.03536 * tsquared; + pi = CT.d2R(CT.dmS2D(0, 0, pi)); + var p = (5029.0966 + 2.22226 * T - 4.2E-05 * Tsquared) * t + (1.11113 - 4.2E-05 * T) * tsquared - 6E-06 * tcubed; + p = CT.d2R(CT.dmS2D(0, 0, p)); + var A = Math.cos(eta) * Math.cos(Beta) * Math.sin(pi - Lambda) - Math.sin(eta) * Math.sin(Beta); + var B = Math.cos(Beta) * Math.cos(pi - Lambda); + var C = Math.cos(eta) * Math.sin(Beta) + Math.sin(eta) * Math.cos(Beta) * Math.sin(pi - Lambda); + var vvalue = new COR(); + vvalue.x = CT.r2D(p + pi - Math.atan2(A, B)); + if (vvalue.x < 0) { + vvalue.x += 360; + } + vvalue.y = CT.r2D(Math.asin(C)); + return vvalue; +}; + +CAAPrecession.equatorialPMToEcliptic = function (Alpha, Delta, Beta, PMAlpha, PMDelta, Epsilon) { + Epsilon = CT.d2R(Epsilon); + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + Beta = CT.d2R(Beta); + var cosb = Math.cos(Beta); + var sinEpsilon = Math.sin(Epsilon); + var vvalue = new COR(); + vvalue.x = (PMDelta * sinEpsilon * Math.cos(Alpha) + PMAlpha * Math.cos(Delta) * (Math.cos(Epsilon) * Math.cos(Delta) + sinEpsilon * Math.sin(Delta) * Math.sin(Alpha))) / (cosb * cosb); + vvalue.y = (PMDelta * (Math.cos(Epsilon) * Math.cos(Delta) + sinEpsilon * Math.sin(Delta) * Math.sin(Alpha)) - PMAlpha * sinEpsilon * Math.cos(Alpha) * Math.cos(Delta)) / cosb; + return vvalue; +}; + +CAAPrecession.adjustPositionUsingUniformProperMotion = function (t, Alpha, Delta, PMAlpha, PMDelta) { + var vvalue = new COR(); + vvalue.x = Alpha + (PMAlpha * t / 3600); + vvalue.y = Delta + (PMDelta * t / 3600); + return vvalue; +}; + +CAAPrecession.adjustPositionUsingMotionInSpace = function (r, DeltaR, t, Alpha, Delta, PMAlpha, PMDelta) { + DeltaR /= 977792; + PMAlpha /= 13751; + PMDelta /= 206265; + Alpha = CT.h2R(Alpha); + Delta = CT.d2R(Delta); + var x = r * Math.cos(Delta) * Math.cos(Alpha); + var y = r * Math.cos(Delta) * Math.sin(Alpha); + var z = r * Math.sin(Delta); + var DeltaX = x / r * DeltaR - z * PMDelta * Math.cos(Alpha) - y * PMAlpha; + var DeltaY = y / r * DeltaR - z * PMDelta * Math.sin(Alpha) + x * PMAlpha; + var DeltaZ = z / r * DeltaR + r * PMDelta * Math.cos(Delta); + x += t * DeltaX; + y += t * DeltaY; + z += t * DeltaZ; + var vvalue = new COR(); + vvalue.x = CT.r2H(Math.atan2(y, x)); + if (vvalue.x < 0) { + vvalue.x += 24; + } + vvalue.y = CT.r2D(Math.atan2(z, Math.sqrt(x * x + y * y))); + return vvalue; +}; + +var CAAPrecession$ = {}; + +registerType("CAAPrecession", [CAAPrecession, CAAPrecession$, null]); diff --git a/engine/esm/astrocalc/rise_transit_set.js b/engine/esm/astrocalc/rise_transit_set.js new file mode 100644 index 00000000..770b9ce1 --- /dev/null +++ b/engine/esm/astrocalc/rise_transit_set.js @@ -0,0 +1,126 @@ +// Originally `AARISETRANSITSET.CPP` +// "Purpose: Implementation for the algorithms which obtain the Rise, Transit and Set times" +// Last update of original: PJN / 15-10-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { DYT } from "./dynamical_time.js"; +import { INTP } from "./interpolate.js"; +import { CAASidereal } from "./sidereal.js"; + + +// CAARiseTransitSetDetails + +export function CAARiseTransitSetDetails() { + this.bValid = false; + this.rise = 0; + this.transit = 0; + this.set = 0; + this.bValid = false; + this.rise = 0; + this.transit = 0; + this.set = 0; +} + +var CAARiseTransitSetDetails$ = {}; + +registerType("CAARiseTransitSetDetails", [CAARiseTransitSetDetails, CAARiseTransitSetDetails$, null]); + + +// CAARiseTransitSet + +export function CAARiseTransitSet() { } + +CAARiseTransitSet.rise = function (JD, Alpha1, Delta1, Alpha2, Delta2, Alpha3, Delta3, Longitude, Latitude, h0) { + var details = new CAARiseTransitSetDetails(); + details.bValid = false; + var theta0 = CAASidereal.apparentGreenwichSiderealTime(JD); + theta0 *= 15; + var deltaT = DYT.deltaT(JD); + var Delta2Rad = CT.d2R(Delta2); + var LatitudeRad = CT.d2R(Latitude); + var h0Rad = CT.d2R(h0); + var cosH0 = (Math.sin(h0Rad) - Math.sin(LatitudeRad) * Math.sin(Delta2Rad)) / (Math.cos(LatitudeRad) * Math.cos(Delta2Rad)); + if ((cosH0 > 1) || (cosH0 < -1)) { + return details; + } + var H0 = Math.acos(cosH0); + H0 = CT.r2D(H0); + var M0 = (Alpha2 * 15 + Longitude - theta0) / 360; + var M1 = M0 - H0 / 360; + var M2 = M0 + H0 / 360; + if (M0 > 1) { + M0 -= 1; + } + else if (M0 < 0) { + M0 += 1; + } + if (M1 > 1) { + M1 -= 1; + } + else if (M1 < 0) { + M1 += 1; + } + if (M2 > 1) { + M2 -= 1; + } + else if (M2 < 0) { + M2 += 1; + } + for (var i = 0; i < 2; i++) { + var theta1 = theta0 + 360.985647 * M1; + theta1 = CT.m360(theta1); + var n = M1 + deltaT / 86400; + var Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); + var Delta = INTP.interpolate(n, Delta1, Delta2, Delta3); + var H = theta1 - Longitude - Alpha * 15; + var Horizontal = CT.eq2H(H / 15, Delta, Latitude); + var DeltaM = (Horizontal.y - h0) / (360 * Math.cos(CT.d2R(Delta)) * Math.cos(LatitudeRad) * Math.sin(CT.d2R(H))); + M1 += DeltaM; + theta1 = theta0 + 360.985647 * M0; + theta1 = CT.m360(theta1); + n = M0 + deltaT / 86400; + Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); + H = theta1 - Longitude - Alpha * 15; + if (H < -180) { + H += 360; + } + DeltaM = -H / 360; + M0 += DeltaM; + theta1 = theta0 + 360.985647 * M2; + theta1 = CT.m360(theta1); + n = M2 + deltaT / 86400; + Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); + Delta = INTP.interpolate(n, Delta1, Delta2, Delta3); + H = theta1 - Longitude - Alpha * 15; + Horizontal = CT.eq2H(H / 15, Delta, Latitude); + DeltaM = (Horizontal.y - h0) / (360 * Math.cos(CT.d2R(Delta)) * Math.cos(LatitudeRad) * Math.sin(CT.d2R(H))); + M2 += DeltaM; + } + details.bValid = true; + details.rise = M1 * 24; + details.set = M2 * 24; + details.transit = M0 * 24; + return details; +}; + +var CAARiseTransitSet$ = {}; + +registerType("CAARiseTransitSet", [CAARiseTransitSet, CAARiseTransitSet$, null]); diff --git a/engine/esm/astrocalc/saturn.js b/engine/esm/astrocalc/saturn.js new file mode 100644 index 00000000..43a92596 --- /dev/null +++ b/engine/esm/astrocalc/saturn.js @@ -0,0 +1,179 @@ +// Originally `AASATURN.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Saturn" +// Last update of original: PJN / 31-05-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0SaturnCoefficients = [new VSC(87401354, 0, 0), new VSC(11107660, 3.9620509, 213.29909544), new VSC(1414151, 4.5858152, 7.113547), new VSC(398379, 0.52112, 206.185548), new VSC(350769, 3.303299, 426.598191), new VSC(206816, 0.246584, 103.092774), new VSC(79271, 3.84007, 220.41264), new VSC(23990, 4.66977, 110.20632), new VSC(16574, 0.43719, 419.48464), new VSC(15820, 0.93809, 632.78374), new VSC(15054, 2.7167, 639.89729), new VSC(14907, 5.76903, 316.39187), new VSC(14610, 1.56519, 3.93215), new VSC(13160, 4.44891, 14.22709), new VSC(13005, 5.98119, 11.0457), new VSC(10725, 3.1294, 202.2534), new VSC(6126, 1.7633, 277.035), new VSC(5863, 0.2366, 529.691), new VSC(5228, 4.2078, 3.1814), new VSC(5020, 3.1779, 433.7117), new VSC(4593, 0.6198, 199.072), new VSC(4006, 2.2448, 63.7359), new VSC(3874, 3.2228, 138.5175), new VSC(3269, 0.7749, 949.1756), new VSC(2954, 0.9828, 95.9792), new VSC(2461, 2.0316, 735.8765), new VSC(1758, 3.2658, 522.5774), new VSC(1640, 5.505, 846.0828), new VSC(1581, 4.3727, 309.2783), new VSC(1391, 4.0233, 323.5054), new VSC(1124, 2.8373, 415.5525), new VSC(1087, 4.1834, 2.4477), new VSC(1017, 3.717, 227.5262), new VSC(957, 0.507, 1265.567), new VSC(853, 3.421, 175.166), new VSC(849, 3.191, 209.367), new VSC(789, 5.007, 0.963), new VSC(749, 2.144, 853.196), new VSC(744, 5.253, 224.345), new VSC(687, 1.747, 1052.268), new VSC(654, 1.599, 0.048), new VSC(634, 2.299, 412.371), new VSC(625, 0.97, 210.118), new VSC(580, 3.093, 74.782), new VSC(546, 2.127, 350.332), new VSC(543, 1.518, 9.561), new VSC(530, 4.449, 117.32), new VSC(478, 2.965, 137.033), new VSC(474, 5.475, 742.99), new VSC(452, 1.044, 490.334), new VSC(449, 1.29, 127.472), new VSC(372, 2.278, 217.231), new VSC(355, 3.013, 838.969), new VSC(347, 1.539, 340.771), new VSC(343, 0.246, 0.521), new VSC(330, 0.247, 1581.959), new VSC(322, 0.961, 203.738), new VSC(322, 2.572, 647.011), new VSC(309, 3.495, 216.48), new VSC(287, 2.37, 351.817), new VSC(278, 0.4, 211.815), new VSC(249, 1.47, 1368.66), new VSC(227, 4.91, 12.53), new VSC(220, 4.204, 200.769), new VSC(209, 1.345, 625.67), new VSC(208, 0.483, 1162.475), new VSC(208, 1.283, 39.357), new VSC(204, 6.011, 265.989), new VSC(185, 3.503, 149.563), new VSC(184, 0.973, 4.193), new VSC(182, 5.491, 2.921), new VSC(174, 1.863, 0.751), new VSC(165, 0.44, 5.417), new VSC(149, 5.736, 52.69), new VSC(148, 1.535, 5.629), new VSC(146, 6.231, 195.14), new VSC(140, 4.295, 21.341), new VSC(131, 4.068, 10.295), new VSC(125, 6.277, 1898.351), new VSC(122, 1.976, 4.666), new VSC(118, 5.341, 554.07), new VSC(117, 2.679, 1155.361), new VSC(114, 5.594, 1059.382), new VSC(112, 1.105, 191.208), new VSC(110, 0.166, 1.484), new VSC(109, 3.438, 536.805), new VSC(107, 4.012, 956.289), new VSC(104, 2.192, 88.866), new VSC(103, 1.197, 1685.052), new VSC(101, 4.965, 269.921)]; +const g_L1SaturnCoefficients = [new VSC(21354295596, 0, 0), new VSC(1296855, 1.8282054, 213.2990954), new VSC(564348, 2.885001, 7.113547), new VSC(107679, 2.277699, 206.185548), new VSC(98323, 1.0807, 426.59819), new VSC(40255, 2.04128, 220.41264), new VSC(19942, 1.27955, 103.09277), new VSC(10512, 2.7488, 14.22709), new VSC(6939, 0.4049, 639.8973), new VSC(4803, 2.4419, 419.4846), new VSC(4056, 2.9217, 110.2063), new VSC(3769, 3.6497, 3.9322), new VSC(3385, 2.4169, 3.1814), new VSC(3302, 1.2626, 433.7117), new VSC(3071, 2.3274, 199.072), new VSC(1953, 3.5639, 11.0457), new VSC(1249, 2.628, 95.9792), new VSC(922, 1.961, 227.526), new VSC(706, 4.417, 529.691), new VSC(650, 6.174, 202.253), new VSC(628, 6.111, 309.278), new VSC(487, 6.04, 853.196), new VSC(479, 4.988, 522.577), new VSC(468, 4.617, 63.736), new VSC(417, 2.117, 323.505), new VSC(408, 1.299, 209.367), new VSC(352, 2.317, 632.784), new VSC(344, 3.959, 412.371), new VSC(340, 3.634, 316.392), new VSC(336, 3.772, 735.877), new VSC(332, 2.861, 210.118), new VSC(289, 2.733, 117.32), new VSC(281, 5.744, 2.448), new VSC(266, 0.543, 647.011), new VSC(230, 1.644, 216.48), new VSC(192, 2.965, 224.345), new VSC(173, 4.077, 846.083), new VSC(167, 2.597, 21.341), new VSC(136, 2.286, 10.295), new VSC(131, 3.441, 742.99), new VSC(128, 4.095, 217.231), new VSC(109, 6.161, 415.552), new VSC(98, 4.73, 838.97), new VSC(94, 3.48, 1052.27), new VSC(92, 3.95, 88.87), new VSC(87, 1.22, 440.83), new VSC(83, 3.11, 625.67), new VSC(78, 6.24, 302.16), new VSC(67, 0.29, 4.67), new VSC(66, 5.65, 9.56), new VSC(62, 4.29, 127.47), new VSC(62, 1.83, 195.14), new VSC(58, 2.48, 191.96), new VSC(57, 5.02, 137.03), new VSC(55, 0.28, 74.78), new VSC(54, 5.13, 490.33), new VSC(51, 1.46, 536.8), new VSC(47, 1.18, 149.56), new VSC(47, 5.15, 515.46), new VSC(46, 2.23, 956.29), new VSC(44, 2.71, 5.42), new VSC(40, 0.41, 269.92), new VSC(40, 3.89, 728.76), new VSC(38, 0.65, 422.67), new VSC(38, 2.53, 12.53), new VSC(37, 3.78, 2.92), new VSC(35, 6.08, 5.63), new VSC(34, 3.21, 1368.66), new VSC(33, 4.64, 277.03), new VSC(33, 5.43, 1066.5), new VSC(33, 0.3, 351.82), new VSC(32, 4.39, 1155.36), new VSC(31, 2.43, 52.69), new VSC(30, 2.84, 203), new VSC(30, 6.19, 284.15), new VSC(30, 3.39, 1059.38), new VSC(29, 2.03, 330.62), new VSC(28, 2.74, 265.99), new VSC(26, 4.51, 340.77)]; +const g_L2SaturnCoefficients = [new VSC(116441, 1.179879, 7.113547), new VSC(91921, 0.07425, 213.2991), new VSC(90592, 0, 0), new VSC(15277, 4.06492, 206.18555), new VSC(10631, 0.25778, 220.41264), new VSC(10605, 5.40964, 426.59819), new VSC(4265, 1.046, 14.2271), new VSC(1216, 2.9186, 103.0928), new VSC(1165, 4.6094, 639.8973), new VSC(1082, 5.6913, 433.7117), new VSC(1045, 4.0421, 199.072), new VSC(1020, 0.6337, 3.1814), new VSC(634, 4.388, 419.485), new VSC(549, 5.573, 3.932), new VSC(457, 1.268, 110.206), new VSC(425, 0.209, 227.526), new VSC(274, 4.288, 95.979), new VSC(162, 1.381, 11.046), new VSC(129, 1.566, 309.278), new VSC(117, 3.881, 853.196), new VSC(105, 4.9, 647.011), new VSC(101, 0.893, 21.341), new VSC(96, 2.91, 316.39), new VSC(95, 5.63, 412.37), new VSC(85, 5.73, 209.37), new VSC(83, 6.05, 216.48), new VSC(82, 1.02, 117.32), new VSC(75, 4.76, 210.12), new VSC(67, 0.46, 522.58), new VSC(66, 0.48, 10.29), new VSC(64, 0.35, 323.51), new VSC(61, 4.88, 632.78), new VSC(53, 2.75, 529.69), new VSC(46, 5.69, 440.83), new VSC(45, 1.67, 202.25), new VSC(42, 5.71, 88.87), new VSC(32, 0.07, 63.74), new VSC(32, 1.67, 302.16), new VSC(31, 4.16, 191.96), new VSC(27, 0.83, 224.34), new VSC(25, 5.66, 735.88), new VSC(20, 5.94, 217.23), new VSC(18, 4.9, 625.67), new VSC(17, 1.63, 742.99), new VSC(16, 0.58, 515.46), new VSC(14, 0.21, 838.97), new VSC(14, 3.76, 195.14), new VSC(12, 4.72, 203), new VSC(12, 0.13, 234.64), new VSC(12, 3.12, 846.08), new VSC(11, 5.92, 536.8), new VSC(11, 5.6, 728.76), new VSC(11, 3.2, 1066.5), new VSC(10, 4.99, 422.67), new VSC(10, 0.26, 330.62), new VSC(10, 4.15, 860.31), new VSC(9, 0.46, 956.29), new VSC(8, 2.14, 269.92), new VSC(8, 5.25, 429.78), new VSC(8, 4.03, 9.56), new VSC(7, 5.4, 1052.27), new VSC(6, 4.46, 284.15), new VSC(6, 5.93, 405.26)]; +const g_L3SaturnCoefficients = [new VSC(16039, 5.73945, 7.11355), new VSC(4250, 4.5854, 213.2991), new VSC(1907, 4.7608, 220.4126), new VSC(1466, 5.9133, 206.1855), new VSC(1162, 5.6197, 14.2271), new VSC(1067, 3.6082, 426.5982), new VSC(239, 3.861, 433.712), new VSC(237, 5.768, 199.072), new VSC(166, 5.116, 3.181), new VSC(151, 2.736, 639.897), new VSC(131, 4.743, 227.526), new VSC(63, 0.23, 419.48), new VSC(62, 4.74, 103.09), new VSC(40, 5.47, 21.34), new VSC(40, 5.96, 95.98), new VSC(39, 5.83, 110.21), new VSC(28, 3.01, 647.01), new VSC(25, 0.99, 3.93), new VSC(19, 1.92, 853.2), new VSC(18, 4.97, 10.29), new VSC(18, 1.03, 412.37), new VSC(18, 4.2, 216.48), new VSC(18, 3.32, 309.28), new VSC(16, 3.9, 440.83), new VSC(16, 5.62, 117.32), new VSC(13, 1.18, 88.87), new VSC(11, 5.58, 11.05), new VSC(11, 5.93, 191.96), new VSC(10, 3.95, 209.37), new VSC(9, 3.39, 302.16), new VSC(8, 4.88, 323.51), new VSC(7, 0.38, 632.78), new VSC(6, 2.25, 522.58), new VSC(6, 1.06, 210.12), new VSC(5, 4.64, 234.64), new VSC(4, 3.14, 0), new VSC(4, 2.31, 515.46), new VSC(3, 2.2, 860.31), new VSC(3, 0.59, 529.69), new VSC(3, 4.93, 224.34), new VSC(3, 0.42, 625.67), new VSC(2, 4.77, 330.62), new VSC(2, 3.35, 429.78), new VSC(2, 3.2, 202.25), new VSC(2, 1.19, 1066.5), new VSC(2, 1.35, 405.26), new VSC(2, 4.16, 223.59), new VSC(2, 3.07, 654.12)]; +const g_L4SaturnCoefficients = [new VSC(1662, 3.9983, 7.1135), new VSC(257, 2.984, 220.413), new VSC(236, 3.902, 14.227), new VSC(149, 2.741, 213.299), new VSC(114, 3.142, 0), new VSC(110, 1.515, 206.186), new VSC(68, 1.72, 426.6), new VSC(40, 2.05, 433.71), new VSC(38, 1.24, 199.07), new VSC(31, 3.01, 227.53), new VSC(15, 0.83, 639.9), new VSC(9, 3.71, 21.34), new VSC(6, 2.42, 419.48), new VSC(6, 1.16, 647.01), new VSC(4, 1.45, 95.98), new VSC(4, 2.12, 440.83), new VSC(3, 4.09, 110.21), new VSC(3, 2.77, 412.37), new VSC(3, 3.01, 88.87), new VSC(3, 0, 853.2), new VSC(3, 0.39, 103.09), new VSC(2, 3.78, 117.32), new VSC(2, 2.83, 234.64), new VSC(2, 5.08, 309.28), new VSC(2, 2.24, 216.48), new VSC(2, 5.19, 302.16), new VSC(1, 1.55, 191.96)]; +const g_L5SaturnCoefficients = [new VSC(124, 2.259, 7.114), new VSC(34, 2.16, 14.23), new VSC(28, 1.2, 220.41), new VSC(6, 1.22, 227.53), new VSC(5, 0.24, 433.71), new VSC(4, 6.23, 426.6), new VSC(3, 2.97, 199.07), new VSC(3, 4.29, 206.19), new VSC(2, 6.25, 213.3), new VSC(1, 5.28, 639.9), new VSC(1, 0.24, 440.83), new VSC(1, 3.14, 0)]; +const g_B0SaturnCoefficients = [new VSC(4330678, 3.6028443, 213.2990954), new VSC(240348, 2.852385, 426.598191), new VSC(84746, 0, 0), new VSC(34116, 0.57297, 206.18555), new VSC(30863, 3.48442, 220.41264), new VSC(14734, 2.11847, 639.89729), new VSC(9917, 5.79, 419.4846), new VSC(6994, 4.736, 7.1135), new VSC(4808, 5.4331, 316.3919), new VSC(4788, 4.9651, 110.2063), new VSC(3432, 2.7326, 433.7117), new VSC(1506, 6.013, 103.0928), new VSC(1060, 5.631, 529.691), new VSC(969, 5.204, 632.784), new VSC(942, 1.396, 853.196), new VSC(708, 3.803, 323.505), new VSC(552, 5.131, 202.253), new VSC(400, 3.359, 227.526), new VSC(319, 3.626, 209.367), new VSC(316, 1.997, 647.011), new VSC(314, 0.465, 217.231), new VSC(284, 4.886, 224.345), new VSC(236, 2.139, 11.046), new VSC(215, 5.95, 846.083), new VSC(209, 2.12, 415.552), new VSC(207, 0.73, 199.072), new VSC(179, 2.954, 63.736), new VSC(141, 0.644, 490.334), new VSC(139, 4.595, 14.227), new VSC(139, 1.998, 735.877), new VSC(135, 5.245, 742.99), new VSC(122, 3.115, 522.577), new VSC(116, 3.109, 216.48), new VSC(114, 0.963, 210.118)]; +const g_B1SaturnCoefficients = [new VSC(397555, 5.3329, 213.299095), new VSC(49479, 3.14159, 0), new VSC(18572, 6.09919, 426.59819), new VSC(14801, 2.30586, 206.18555), new VSC(9644, 1.6967, 220.4126), new VSC(3757, 1.2543, 419.4846), new VSC(2717, 5.9117, 639.8973), new VSC(1455, 0.8516, 433.7117), new VSC(1291, 2.9177, 7.1135), new VSC(853, 0.436, 316.392), new VSC(298, 0.919, 632.784), new VSC(292, 5.316, 853.196), new VSC(284, 1.619, 227.526), new VSC(275, 3.889, 103.093), new VSC(172, 0.052, 647.011), new VSC(166, 2.444, 199.072), new VSC(158, 5.209, 110.206), new VSC(128, 1.207, 529.691), new VSC(110, 2.457, 217.231), new VSC(82, 2.76, 210.12), new VSC(81, 2.86, 14.23), new VSC(69, 1.66, 202.25), new VSC(65, 1.26, 216.48), new VSC(61, 1.25, 209.37), new VSC(59, 1.82, 323.51), new VSC(46, 0.82, 440.83), new VSC(36, 1.82, 224.34), new VSC(34, 2.84, 117.32), new VSC(33, 1.31, 412.37), new VSC(32, 1.19, 846.08), new VSC(27, 4.65, 1066.5), new VSC(27, 4.44, 11.05)]; +const g_B2SaturnCoefficients = [new VSC(20630, 0.50482, 213.2991), new VSC(3720, 3.9983, 206.1855), new VSC(1627, 6.1819, 220.4126), new VSC(1346, 0, 0), new VSC(706, 3.039, 419.485), new VSC(365, 5.099, 426.598), new VSC(330, 5.279, 433.712), new VSC(219, 3.828, 639.897), new VSC(139, 1.043, 7.114), new VSC(104, 6.157, 227.526), new VSC(93, 1.98, 316.39), new VSC(71, 4.15, 199.07), new VSC(52, 2.88, 632.78), new VSC(49, 4.43, 647.01), new VSC(41, 3.16, 853.2), new VSC(29, 4.53, 210.12), new VSC(24, 1.12, 14.23), new VSC(21, 4.35, 217.23), new VSC(20, 5.31, 440.83), new VSC(18, 0.85, 110.21), new VSC(17, 5.68, 216.48), new VSC(16, 4.26, 103.09), new VSC(14, 3, 412.37), new VSC(12, 2.53, 529.69), new VSC(8, 3.32, 202.25), new VSC(7, 5.56, 209.37), new VSC(7, 0.29, 323.51), new VSC(6, 1.16, 117.32), new VSC(6, 3.61, 869.31)]; +const g_B3SaturnCoefficients = [new VSC(666, 1.99, 213.299), new VSC(632, 5.698, 206.186), new VSC(398, 0, 0), new VSC(188, 4.338, 220.413), new VSC(92, 4.84, 419.48), new VSC(52, 3.42, 433.71), new VSC(42, 2.38, 426.6), new VSC(26, 4.4, 227.53), new VSC(21, 5.85, 199.07), new VSC(18, 1.99, 639.9), new VSC(11, 5.37, 7.11), new VSC(10, 2.55, 647.01), new VSC(7, 3.46, 316.39), new VSC(6, 4.8, 632.78), new VSC(6, 0.02, 210.12), new VSC(6, 3.52, 440.83), new VSC(5, 5.64, 14.23), new VSC(5, 1.22, 853.2), new VSC(4, 4.71, 412.37), new VSC(3, 0.63, 103.09), new VSC(2, 3.72, 216.48)]; +const g_B4SaturnCoefficients = [new VSC(80, 1.12, 206.19), new VSC(32, 3.12, 213.3), new VSC(17, 2.48, 220.41), new VSC(12, 3.14, 0), new VSC(9, 0.38, 419.48), new VSC(6, 1.56, 433.71), new VSC(5, 2.63, 227.53), new VSC(5, 1.28, 199.07), new VSC(1, 1.43, 426.6), new VSC(1, 0.67, 647.01), new VSC(1, 1.72, 440.83), new VSC(1, 6.18, 639.9)]; +const g_B5SaturnCoefficients = [new VSC(8, 2.82, 206.19), new VSC(1, 0.51, 220.41)]; +const g_R0SaturnCoefficients = [new VSC(955758136, 0, 0), new VSC(52921382, 2.3922622, 213.29909544), new VSC(1873680, 5.2354961, 206.1855484), new VSC(1464664, 1.6476305, 426.5981909), new VSC(821891, 5.9352, 316.39187), new VSC(547507, 5.015326, 103.092774), new VSC(371684, 2.271148, 220.412642), new VSC(361778, 3.139043, 7.113547), new VSC(140618, 5.704067, 632.783739), new VSC(108975, 3.293136, 110.206321), new VSC(69007, 5.941, 419.48464), new VSC(61053, 0.94038, 639.89729), new VSC(48913, 1.55733, 202.2534), new VSC(34144, 0.19519, 277.03499), new VSC(32402, 5.47085, 949.17561), new VSC(20937, 0.46349, 735.87651), new VSC(20839, 1.52103, 433.71174), new VSC(20747, 5.33256, 199.072), new VSC(15298, 3.05944, 529.69097), new VSC(14296, 2.60434, 323.50542), new VSC(12884, 1.64892, 138.5175), new VSC(11993, 5.98051, 846.08283), new VSC(11380, 1.73106, 522.57742), new VSC(9796, 5.2048, 1265.5675), new VSC(7753, 5.8519, 95.9792), new VSC(6771, 3.0043, 14.2271), new VSC(6466, 0.1773, 1052.2684), new VSC(5850, 1.4552, 415.5525), new VSC(5307, 0.5974, 63.7359), new VSC(4696, 2.1492, 227.5262), new VSC(4044, 1.6401, 209.3669), new VSC(3688, 0.7802, 412.3711), new VSC(3461, 1.8509, 175.1661), new VSC(3420, 4.9455, 1581.9593), new VSC(3401, 0.5539, 350.3321), new VSC(3376, 3.6953, 224.3448), new VSC(2976, 5.6847, 210.1177), new VSC(2885, 1.3876, 838.9693), new VSC(2881, 0.1796, 853.1964), new VSC(2508, 3.5385, 742.9901), new VSC(2448, 6.1841, 1368.6603), new VSC(2406, 2.9656, 117.3199), new VSC(2174, 0.0151, 340.7709), new VSC(2024, 5.0541, 11.0457)]; +const g_R1SaturnCoefficients = [new VSC(6182981, 0.2584352, 213.2990954), new VSC(506578, 0.711147, 206.185548), new VSC(341394, 5.796358, 426.598191), new VSC(188491, 0.472157, 220.412642), new VSC(186262, 3.141593, 0), new VSC(143891, 1.407449, 7.113547), new VSC(49621, 6.01744, 103.09277), new VSC(20928, 5.09246, 639.89729), new VSC(19953, 1.1756, 419.48464), new VSC(18840, 1.6082, 110.20632), new VSC(13877, 0.75886, 199.072), new VSC(12893, 5.9433, 433.71174), new VSC(5397, 1.2885, 14.2271), new VSC(4869, 0.8679, 323.5054), new VSC(4247, 0.393, 227.5262), new VSC(3252, 1.2585, 95.9792), new VSC(3081, 3.4366, 522.5774), new VSC(2909, 4.6068, 202.2534), new VSC(2856, 2.1673, 735.8765), new VSC(1988, 2.4505, 412.3711), new VSC(1941, 6.0239, 209.3669), new VSC(1581, 1.2919, 210.1177), new VSC(1340, 4.308, 853.1964), new VSC(1316, 1.253, 117.3199), new VSC(1203, 1.8665, 316.3919), new VSC(1091, 0.0753, 216.4805), new VSC(966, 0.48, 632.784), new VSC(954, 5.152, 647.011), new VSC(898, 0.983, 529.691), new VSC(882, 1.885, 1052.268), new VSC(874, 1.402, 224.345), new VSC(785, 3.064, 838.969), new VSC(740, 1.382, 625.67), new VSC(658, 4.144, 309.278), new VSC(650, 1.725, 742.99), new VSC(613, 3.033, 63.736), new VSC(599, 2.549, 217.231), new VSC(503, 2.13, 3.932)]; +const g_R2SaturnCoefficients = [new VSC(436902, 4.786717, 213.299095), new VSC(71923, 2.5007, 206.18555), new VSC(49767, 4.97168, 220.41264), new VSC(43221, 3.8694, 426.59819), new VSC(29646, 5.9631, 7.11355), new VSC(4721, 2.4753, 199.072), new VSC(4142, 4.1067, 433.7117), new VSC(3789, 3.0977, 639.8973), new VSC(2964, 1.3721, 103.0928), new VSC(2556, 2.8507, 419.4846), new VSC(2327, 0, 0), new VSC(2208, 6.2759, 110.2063), new VSC(2188, 5.8555, 14.2271), new VSC(1957, 4.9245, 227.5262), new VSC(924, 5.464, 323.505), new VSC(706, 2.971, 95.979), new VSC(546, 4.129, 412.371), new VSC(431, 5.178, 522.577), new VSC(405, 4.173, 209.367), new VSC(391, 4.481, 216.48), new VSC(374, 5.834, 117.32), new VSC(361, 3.277, 647.011), new VSC(356, 3.192, 210.118), new VSC(326, 2.269, 853.196), new VSC(207, 4.022, 735.877), new VSC(204, 0.088, 202.253), new VSC(180, 3.597, 632.784), new VSC(178, 4.097, 440.825), new VSC(154, 3.135, 625.67), new VSC(148, 0.136, 302.165), new VSC(133, 2.594, 191.958), new VSC(132, 5.933, 309.278)]; +const g_R3SaturnCoefficients = [new VSC(20315, 3.02187, 213.2991), new VSC(8924, 3.1914, 220.4126), new VSC(6909, 4.3517, 206.1855), new VSC(4087, 4.2241, 7.1135), new VSC(3879, 2.0106, 426.5982), new VSC(1071, 4.2036, 199.072), new VSC(907, 2.283, 433.712), new VSC(606, 3.175, 227.526), new VSC(597, 4.135, 14.227), new VSC(483, 1.173, 639.897), new VSC(393, 0, 0), new VSC(229, 4.698, 419.485), new VSC(188, 4.59, 110.206), new VSC(150, 3.202, 103.093), new VSC(121, 3.768, 323.505), new VSC(102, 4.71, 95.979), new VSC(101, 5.819, 412.371), new VSC(93, 1.44, 647.01), new VSC(84, 2.63, 216.48), new VSC(73, 4.15, 117.32), new VSC(62, 2.31, 440.83), new VSC(55, 0.31, 853.2), new VSC(50, 2.39, 209.37), new VSC(45, 4.37, 191.96), new VSC(41, 0.69, 522.58), new VSC(40, 1.84, 302.16), new VSC(38, 5.94, 88.87), new VSC(32, 4.01, 21.34)]; +const g_R4SaturnCoefficients = [new VSC(1202, 1.415, 220.4126), new VSC(708, 1.162, 213.299), new VSC(516, 6.24, 206.186), new VSC(427, 2.469, 7.114), new VSC(268, 0.187, 426.598), new VSC(170, 5.959, 199.072), new VSC(150, 0.48, 433.712), new VSC(145, 1.442, 227.526), new VSC(121, 2.405, 14.227), new VSC(47, 5.57, 639.9), new VSC(19, 5.86, 647.01), new VSC(17, 0.53, 440.83), new VSC(16, 2.9, 110.21), new VSC(15, 0.3, 419.48), new VSC(14, 1.3, 412.37), new VSC(13, 2.09, 323.51), new VSC(11, 0.22, 95.98), new VSC(11, 2.46, 117.32), new VSC(10, 3.14, 0), new VSC(9, 1.56, 88.87), new VSC(9, 2.28, 21.34), new VSC(9, 0.68, 216.48), new VSC(8, 1.27, 234.64)]; +const g_R5SaturnCoefficients = [new VSC(129, 5.913, 220.413), new VSC(32, 0.69, 7.11), new VSC(27, 5.91, 227.53), new VSC(20, 4.95, 433.71), new VSC(20, 0.67, 14.23), new VSC(14, 2.67, 206.19), new VSC(14, 1.46, 199.07), new VSC(13, 4.59, 426.6), new VSC(7, 4.63, 213.3), new VSC(5, 3.61, 639.9), new VSC(4, 4.9, 440.83), new VSC(3, 4.07, 647.01), new VSC(3, 4.66, 191.96), new VSC(3, 0.49, 323.51), new VSC(3, 3.18, 419.48), new VSC(2, 3.7, 88.87), new VSC(2, 3.32, 95.98), new VSC(2, 0.56, 117.32)]; + + +// CAASaturn + +export function CAASaturn() { } + +CAASaturn.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0SaturnCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0SaturnCoefficients[i].a * Math.cos(g_L0SaturnCoefficients[i].b + g_L0SaturnCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1SaturnCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1SaturnCoefficients[i].a * Math.cos(g_L1SaturnCoefficients[i].b + g_L1SaturnCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2SaturnCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2SaturnCoefficients[i].a * Math.cos(g_L2SaturnCoefficients[i].b + g_L2SaturnCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3SaturnCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3SaturnCoefficients[i].a * Math.cos(g_L3SaturnCoefficients[i].b + g_L3SaturnCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4SaturnCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4SaturnCoefficients[i].a * Math.cos(g_L4SaturnCoefficients[i].b + g_L4SaturnCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5SaturnCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5SaturnCoefficients[i].a * Math.cos(g_L5SaturnCoefficients[i].b + g_L5SaturnCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAASaturn.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nB0Coefficients = g_B0SaturnCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0SaturnCoefficients[i].a * Math.cos(g_B0SaturnCoefficients[i].b + g_B0SaturnCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1SaturnCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1SaturnCoefficients[i].a * Math.cos(g_B1SaturnCoefficients[i].b + g_B1SaturnCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2SaturnCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2SaturnCoefficients[i].a * Math.cos(g_B2SaturnCoefficients[i].b + g_B2SaturnCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3SaturnCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3SaturnCoefficients[i].a * Math.cos(g_B3SaturnCoefficients[i].b + g_B3SaturnCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4SaturnCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4SaturnCoefficients[i].a * Math.cos(g_B4SaturnCoefficients[i].b + g_B4SaturnCoefficients[i].c * rho); + } + var nB5Coefficients = g_B5SaturnCoefficients.length; + var B5 = 0; + for (i = 0; i < nB5Coefficients; i++) { + B5 += g_B5SaturnCoefficients[i].a * Math.cos(g_B5SaturnCoefficients[i].b + g_B5SaturnCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4 + B5 * rho5) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAASaturn.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nR0Coefficients = g_R0SaturnCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0SaturnCoefficients[i].a * Math.cos(g_R0SaturnCoefficients[i].b + g_R0SaturnCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1SaturnCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1SaturnCoefficients[i].a * Math.cos(g_R1SaturnCoefficients[i].b + g_R1SaturnCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2SaturnCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2SaturnCoefficients[i].a * Math.cos(g_R2SaturnCoefficients[i].b + g_R2SaturnCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3SaturnCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3SaturnCoefficients[i].a * Math.cos(g_R3SaturnCoefficients[i].b + g_R3SaturnCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4SaturnCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4SaturnCoefficients[i].a * Math.cos(g_R4SaturnCoefficients[i].b + g_R4SaturnCoefficients[i].c * rho); + } + var nR5Coefficients = g_R5SaturnCoefficients.length; + var R5 = 0; + for (i = 0; i < nR5Coefficients; i++) { + R5 += g_R5SaturnCoefficients[i].a * Math.cos(g_R5SaturnCoefficients[i].b + g_R5SaturnCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4 + R5 * rho5) / 100000000; +}; + +var CAASaturn$ = {}; + +registerType("CAASaturn", [CAASaturn, CAASaturn$, null]); diff --git a/engine/esm/astrocalc/saturn_rings.js b/engine/esm/astrocalc/saturn_rings.js new file mode 100644 index 00000000..37cf6042 --- /dev/null +++ b/engine/esm/astrocalc/saturn_rings.js @@ -0,0 +1,141 @@ +// Originally `AASATURNRINGS.CPP` +// "Purpose: Implementation for the algorithms which calculate various parameters related to the Rings of Saturn" +// Last update of original: PJN / 08-01-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAAFK5 } from "./fk5.js"; +import { ELL } from "./elliptical.js"; +import { CAANutation } from "./nutation.js"; +import { CAAEarth } from "./earth.js"; +import { CAASaturn } from "./saturn.js"; + +// CAASaturnRingDetails + +export function CAASaturnRingDetails() { + this.b = 0; + this.bdash = 0; + this.p = 0; + this.a = 0; + this.b = 0; + this.deltaU = 0; + this.b = 0; + this.bdash = 0; + this.p = 0; + this.a = 0; + this.b = 0; + this.deltaU = 0; +} + +var CAASaturnRingDetails$ = {}; + +registerType("CAASaturnRingDetails", [CAASaturnRingDetails, CAASaturnRingDetails$, null]); + + +// CAASaturnRings + +export function CAASaturnRings() { } + +CAASaturnRings.calculate = function (JD) { + var details = new CAASaturnRingDetails(); + var T = (JD - 2451545) / 36525; + var T2 = T * T; + var i = 28.075216 - 0.012998 * T + 4E-06 * T2; + var irad = CT.d2R(i); + var omega = 169.50847 + 1.394681 * T + 0.000412 * T2; + var omegarad = CT.d2R(omega); + var l0 = CAAEarth.eclipticLongitude(JD); + var b0 = CAAEarth.eclipticLatitude(JD); + l0 += CAAFK5.correctionInLongitude(l0, b0, JD); + var l0rad = CT.d2R(l0); + b0 += CAAFK5.correctionInLatitude(l0, JD); + var b0rad = CT.d2R(b0); + var R = CAAEarth.radiusVector(JD); + var DELTA = 9; + var PreviousEarthLightTravelTime = 0; + var EarthLightTravelTime = ELL.distanceToLightTime(DELTA); + var JD1 = JD - EarthLightTravelTime; + var bIterate = true; + var x = 0; + var y = 0; + var z = 0; + var l = 0; + var b = 0; + var r = 0; + while (bIterate) { + l = CAASaturn.eclipticLongitude(JD1); + b = CAASaturn.eclipticLatitude(JD1); + l += CAAFK5.correctionInLongitude(l, b, JD1); + b += CAAFK5.correctionInLatitude(l, JD1); + var lrad = CT.d2R(l); + var brad = CT.d2R(b); + r = CAASaturn.radiusVector(JD1); + x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); + y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); + z = r * Math.sin(brad) - R * Math.sin(b0rad); + DELTA = Math.sqrt(x * x + y * y + z * z); + EarthLightTravelTime = ELL.distanceToLightTime(DELTA); + bIterate = (Math.abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-06); + if (bIterate) { + JD1 = JD - EarthLightTravelTime; + PreviousEarthLightTravelTime = EarthLightTravelTime; + } + } + var lambda = Math.atan2(y, x); + var beta = Math.atan2(z, Math.sqrt(x * x + y * y)); + details.b = Math.asin(Math.sin(irad) * Math.cos(beta) * Math.sin(lambda - omegarad) - Math.cos(irad) * Math.sin(beta)); + details.a = 375.35 / DELTA; + details.b = details.a * Math.sin(Math.abs(details.b)); + details.b = CT.r2D(details.b); + var N = 113.6655 + 0.8771 * T; + var Nrad = CT.d2R(N); + var ldash = l - 0.01759 / r; + var ldashrad = CT.d2R(ldash); + var bdash = b - 0.000764 * Math.cos(ldashrad - Nrad) / r; + var bdashrad = CT.d2R(bdash); + details.bdash = CT.r2D(Math.asin(Math.sin(irad) * Math.cos(bdashrad) * Math.sin(ldashrad - omegarad) - Math.cos(irad) * Math.sin(bdashrad))); + var U1 = Math.atan2(Math.sin(irad) * Math.sin(bdashrad) + Math.cos(irad) * Math.cos(bdashrad) * Math.sin(ldashrad - omegarad), Math.cos(bdashrad) * Math.cos(ldashrad - omegarad)); + var U2 = Math.atan2(Math.sin(irad) * Math.sin(beta) + Math.cos(irad) * Math.cos(beta) * Math.sin(lambda - omegarad), Math.cos(beta) * Math.cos(lambda - omegarad)); + details.deltaU = CT.r2D(Math.abs(U1 - U2)); + var Obliquity = CAANutation.trueObliquityOfEcliptic(JD); + var NutationInLongitude = CAANutation.nutationInLongitude(JD); + var lambda0 = omega - 90; + var beta0 = 90 - i; + lambda += CT.d2R(0.005693 * Math.cos(l0rad - lambda) / Math.cos(beta)); + beta += CT.d2R(0.005693 * Math.sin(l0rad - lambda) * Math.sin(beta)); + lambda = CT.r2D(lambda); + lambda += NutationInLongitude / 3600; + lambda = CT.m360(lambda); + lambda0 += NutationInLongitude / 3600; + lambda0 = CT.m360(lambda0); + beta = CT.r2D(beta); + var GeocentricEclipticSaturn = CT.ec2Eq(lambda, beta, Obliquity); + var alpha = CT.h2R(GeocentricEclipticSaturn.x); + var delta = CT.d2R(GeocentricEclipticSaturn.y); + var GeocentricEclipticNorthPole = CT.ec2Eq(lambda0, beta0, Obliquity); + var alpha0 = CT.h2R(GeocentricEclipticNorthPole.x); + var delta0 = CT.d2R(GeocentricEclipticNorthPole.y); + details.p = CT.r2D(Math.atan2(Math.cos(delta0) * Math.sin(alpha0 - alpha), Math.sin(delta0) * Math.cos(delta) - Math.cos(delta0) * Math.sin(delta) * Math.cos(alpha0 - alpha))); + return details; +}; + +var CAASaturnRings$ = {}; + +registerType("CAASaturnRings", [CAASaturnRings, CAASaturnRings$, null]); diff --git a/engine/esm/astrocalc/sidereal.js b/engine/esm/astrocalc/sidereal.js new file mode 100644 index 00000000..33ba1de8 --- /dev/null +++ b/engine/esm/astrocalc/sidereal.js @@ -0,0 +1,64 @@ +// Originally `AASIDEREAL.CPP` +// "Purpose: Implementation for the algorithms which obtain sidereal time" +// Last update of original: PJN / 28-01-2007 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { DT } from "./date.js"; +import { CT } from "./coordinate_transformation.js"; +import { CAANutation } from "./nutation.js"; + + +// CAASidereal + +export function CAASidereal() { } + +CAASidereal.meanGreenwichSiderealTime = function (JD) { + var date = new DT(); + date.setJD(JD, DT.afterPapalReformJD(JD)); + var D = date.get(); + var Year = ss.truncate(D[0]); + var Month = ss.truncate(D[1]); + var Day = ss.truncate(D[2]); + var Hour = ss.truncate(D[3]); + var Minute = ss.truncate(D[4]); + var Second = D[5]; + date.set(Year, Month, Day, 0, 0, 0, date.inGregorianCalendar()); + var JDMidnight = date.julian(); + var T = (JDMidnight - 2451545) / 36525; + var TSquared = T * T; + var TCubed = TSquared * T; + var Value = 100.46061837 + (36000.770053608 * T) + (0.000387933 * TSquared) - (TCubed / 38710000); + Value += (((Hour * 15) + (Minute * 0.25) + (Second * 0.00416666666666667)) * 1.00273790935); + Value = CT.d2H(Value); + return CT.m24(Value); +}; + +CAASidereal.apparentGreenwichSiderealTime = function (JD) { + var MeanObliquity = CAANutation.meanObliquityOfEcliptic(JD); + var TrueObliquity = MeanObliquity + CAANutation.nutationInObliquity(JD) / 3600; + var NutationInLongitude = CAANutation.nutationInLongitude(JD); + var Value = CAASidereal.meanGreenwichSiderealTime(JD) + (NutationInLongitude * Math.cos(CT.d2R(TrueObliquity)) / 54000); + return CT.m24(Value); +}; + +var CAASidereal$ = {}; + +registerType("CAASidereal", [CAASidereal, CAASidereal$, null]); diff --git a/engine/esm/astrocalc/stellar_magnitudes.js b/engine/esm/astrocalc/stellar_magnitudes.js new file mode 100644 index 00000000..6126d3b7 --- /dev/null +++ b/engine/esm/astrocalc/stellar_magnitudes.js @@ -0,0 +1,54 @@ +// Originally `AASTELLARMAGNITUDES.CPP` +// "Purpose: Implementation for the algorithms which operate on the stellar magntidue system" +// Last update of original: PJN / 12-02-2004 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { Util } from "../baseutil.js"; + + +// CAAStellarMagnitudes + +export function CAAStellarMagnitudes() { } + +CAAStellarMagnitudes.combinedMagnitude = function (m1, m2) { + var x = 0.4 * (m2 - m1); + return m2 - 2.5 * Util.log10(Math.pow(10, x) + 1); +}; + +CAAStellarMagnitudes.combinedMagnitude2 = function (Magnitudes, pMagnitudes) { + var vvalue = 0; + for (var i = 0; i < Magnitudes; i++) { + vvalue += Math.pow(10, -0.4 * pMagnitudes[i]); + } + return -2.5 * Util.log10(vvalue); +}; + +CAAStellarMagnitudes.brightnessRatio = function (m1, m2) { + var x = 0.4 * (m2 - m1); + return Math.pow(10, x); +}; + +CAAStellarMagnitudes.magnitudeDifference = function (brightnessRatio) { + return 2.5 * Util.log10(brightnessRatio); +}; + +var CAAStellarMagnitudes$ = {}; + +registerType("CAAStellarMagnitudes", [CAAStellarMagnitudes, CAAStellarMagnitudes$, null]); diff --git a/engine/esm/astrocalc/sun.js b/engine/esm/astrocalc/sun.js new file mode 100644 index 00000000..d28b2132 --- /dev/null +++ b/engine/esm/astrocalc/sun.js @@ -0,0 +1,120 @@ +// Originally `AASUN.CPP` +// "Purpose: Implementation for the algorithms which calculate the position of Earth" +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { C3D, CT } from "./coordinate_transformation.js"; +import { CAAEarth } from "./earth.js"; +import { CAAFK5 } from "./fk5.js"; +import { CAANutation } from "./nutation.js"; + +// CAASun + +export function CAASun() { } + +CAASun.geometricEclipticLongitude = function (JD) { + return CT.m360(CAAEarth.eclipticLongitude(JD) + 180); +}; + +CAASun.geometricEclipticLatitude = function (JD) { + return -CAAEarth.eclipticLatitude(JD); +}; + +CAASun.geometricEclipticLongitudeJ2000 = function (JD) { + return CT.m360(CAAEarth.eclipticLongitudeJ2000(JD) + 180); +}; + +CAASun.geometricEclipticLatitudeJ2000 = function (JD) { + return -CAAEarth.eclipticLatitudeJ2000(JD); +}; + +CAASun.geometricFK5EclipticLongitude = function (JD) { + var Longitude = CAASun.geometricEclipticLongitude(JD); + var Latitude = CAASun.geometricEclipticLatitude(JD); + Longitude += CAAFK5.correctionInLongitude(Longitude, Latitude, JD); + return Longitude; +}; + +CAASun.geometricFK5EclipticLatitude = function (JD) { + var Longitude = CAASun.geometricEclipticLongitude(JD); + var Latitude = CAASun.geometricEclipticLatitude(JD); + var SunLatCorrection = CAAFK5.correctionInLatitude(Longitude, JD); + Latitude += SunLatCorrection; + return Latitude; +}; + +CAASun.apparentEclipticLongitude = function (JD) { + var Longitude = CAASun.geometricFK5EclipticLongitude(JD); + Longitude += CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)); + var R = CAAEarth.radiusVector(JD); + Longitude -= CT.dmS2D(0, 0, 20.4898 / R); + return Longitude; +}; + +CAASun.apparentEclipticLatitude = function (JD) { + return CAASun.geometricFK5EclipticLatitude(JD); +}; + +CAASun.eclipticRectangularCoordinatesMeanEquinox = function (JD) { + var Longitude = CT.d2R(CAASun.geometricFK5EclipticLongitude(JD)); + var Latitude = CT.d2R(CAASun.geometricFK5EclipticLatitude(JD)); + var R = CAAEarth.radiusVector(JD); + var epsilon = CT.d2R(CAANutation.meanObliquityOfEcliptic(JD)); + var vvalue = new C3D(); + vvalue.x = R * Math.cos(Latitude) * Math.cos(Longitude); + vvalue.y = R * (Math.cos(Latitude) * Math.sin(Longitude) * Math.cos(epsilon) - Math.sin(Latitude) * Math.sin(epsilon)); + vvalue.z = R * (Math.cos(Latitude) * Math.sin(Longitude) * Math.sin(epsilon) + Math.sin(Latitude) * Math.cos(epsilon)); + return vvalue; +}; + +CAASun.eclipticRectangularCoordinatesJ2000 = function (JD) { + var Longitude = CAASun.geometricEclipticLongitudeJ2000(JD); + Longitude = CT.d2R(Longitude); + var Latitude = CAASun.geometricEclipticLatitudeJ2000(JD); + Latitude = CT.d2R(Latitude); + var R = CAAEarth.radiusVector(JD); + var vvalue = new C3D(); + var coslatitude = Math.cos(Latitude); + vvalue.x = R * coslatitude * Math.cos(Longitude); + vvalue.y = R * coslatitude * Math.sin(Longitude); + vvalue.z = R * Math.sin(Latitude); + return vvalue; +}; + +CAASun.equatorialRectangularCoordinatesJ2000 = function (JD) { + var vvalue = CAASun.eclipticRectangularCoordinatesJ2000(JD); + vvalue = CAAFK5.convertVSOPToFK5J2000(vvalue); + return vvalue; +}; + +CAASun.equatorialRectangularCoordinatesB1950 = function (JD) { + var vvalue = CAASun.eclipticRectangularCoordinatesJ2000(JD); + vvalue = CAAFK5.convertVSOPToFK5B1950(vvalue); + return vvalue; +}; + +CAASun.equatorialRectangularCoordinatesAnyEquinox = function (JD, JDEquinox) { + var vvalue = CAASun.equatorialRectangularCoordinatesJ2000(JD); + vvalue = CAAFK5.convertVSOPToFK5AnyEquinox(vvalue, JDEquinox); + return vvalue; +}; + +var CAASun$ = {}; + +registerType("CAASun", [CAASun, CAASun$, null]); diff --git a/engine/esm/astrocalc/uranus.js b/engine/esm/astrocalc/uranus.js new file mode 100644 index 00000000..47e6c404 --- /dev/null +++ b/engine/esm/astrocalc/uranus.js @@ -0,0 +1,159 @@ +// Originally `AAURANUS.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Uranus" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0UranusCoefficients = [new VSC(548129294, 0, 0), new VSC(9260408, 0.8910642, 74.7815986), new VSC(1504248, 3.6271926, 1.4844727), new VSC(365982, 1.899622, 73.297126), new VSC(272328, 3.358237, 149.563197), new VSC(70328, 5.39254, 63.7359), new VSC(68893, 6.09292, 76.26607), new VSC(61999, 2.26952, 2.96895), new VSC(61951, 2.85099, 11.0457), new VSC(26469, 3.14152, 71.81265), new VSC(25711, 6.1138, 454.90937), new VSC(21079, 4.36059, 148.07872), new VSC(17819, 1.74437, 36.64856), new VSC(14613, 4.73732, 3.93215), new VSC(11163, 5.82682, 224.3448), new VSC(10998, 0.48865, 138.5175), new VSC(9527, 2.9552, 35.1641), new VSC(7546, 5.2363, 109.9457), new VSC(4220, 3.2333, 70.8494), new VSC(4052, 2.2775, 151.0477), new VSC(3490, 5.4831, 146.5943), new VSC(3355, 1.0655, 4.4534), new VSC(3144, 4.752, 77.7505), new VSC(2927, 4.629, 9.5612), new VSC(2922, 5.3524, 85.8273), new VSC(2273, 4.366, 70.3282), new VSC(2149, 0.6075, 38.133), new VSC(2051, 1.5177, 0.1119), new VSC(1992, 4.9244, 277.035), new VSC(1667, 3.6274, 380.1278), new VSC(1533, 2.5859, 52.6902), new VSC(1376, 2.0428, 65.2204), new VSC(1372, 4.1964, 111.4302), new VSC(1284, 3.1135, 202.2534), new VSC(1282, 0.5427, 222.8603), new VSC(1244, 0.9161, 2.4477), new VSC(1221, 0.199, 108.4612), new VSC(1151, 4.179, 33.6796), new VSC(1150, 0.9334, 3.1814), new VSC(1090, 1.775, 12.5302), new VSC(1072, 0.2356, 62.2514), new VSC(946, 1.192, 127.472), new VSC(708, 5.183, 213.299), new VSC(653, 0.966, 78.714), new VSC(628, 0.182, 984.6), new VSC(607, 5.432, 529.691), new VSC(559, 3.358, 0.521), new VSC(524, 2.013, 299.126), new VSC(483, 2.106, 0.963), new VSC(471, 1.407, 184.727), new VSC(467, 0.415, 145.11), new VSC(434, 5.521, 183.243), new VSC(405, 5.987, 8.077), new VSC(399, 0.338, 415.552), new VSC(396, 5.87, 351.817), new VSC(379, 2.35, 56.622), new VSC(310, 5.833, 145.631), new VSC(300, 5.644, 22.091), new VSC(294, 5.839, 39.618), new VSC(252, 1.637, 221.376), new VSC(249, 4.746, 225.829), new VSC(239, 2.35, 137.033), new VSC(224, 0.516, 84.343), new VSC(223, 2.843, 0.261), new VSC(220, 1.922, 67.668), new VSC(217, 6.142, 5.938), new VSC(216, 4.778, 340.771), new VSC(208, 5.58, 68.844), new VSC(202, 1.297, 0.048), new VSC(199, 0.956, 152.532), new VSC(194, 1.888, 456.394), new VSC(193, 0.916, 453.425), new VSC(187, 1.319, 0.16), new VSC(182, 3.536, 79.235), new VSC(173, 1.539, 160.609), new VSC(172, 5.68, 219.891), new VSC(170, 3.677, 5.417), new VSC(169, 5.879, 18.159), new VSC(165, 1.424, 106.977), new VSC(163, 3.05, 112.915), new VSC(158, 0.738, 54.175), new VSC(147, 1.263, 59.804), new VSC(143, 1.3, 35.425), new VSC(139, 5.386, 32.195), new VSC(139, 4.26, 909.819), new VSC(124, 1.374, 7.114), new VSC(110, 2.027, 554.07), new VSC(109, 5.706, 77.963), new VSC(104, 5.028, 0.751), new VSC(104, 1.458, 24.379), new VSC(103, 0.681, 14.978)]; +const g_L1UranusCoefficients = [new VSC(7502543122, 0, 0), new VSC(154458, 5.242017, 74.781599), new VSC(24456, 1.71256, 1.48447), new VSC(9258, 0.4284, 11.0457), new VSC(8266, 1.5022, 63.7359), new VSC(7842, 1.3198, 149.5632), new VSC(3899, 0.4648, 3.9322), new VSC(2284, 4.1737, 76.2661), new VSC(1927, 0.5301, 2.9689), new VSC(1233, 1.5863, 70.8494), new VSC(791, 5.436, 3.181), new VSC(767, 1.996, 73.297), new VSC(482, 2.984, 85.827), new VSC(450, 4.138, 138.517), new VSC(446, 3.723, 224.345), new VSC(427, 4.731, 71.813), new VSC(354, 2.583, 148.079), new VSC(348, 2.454, 9.561), new VSC(317, 5.579, 52.69), new VSC(206, 2.363, 2.448), new VSC(189, 4.202, 56.622), new VSC(184, 0.284, 151.048), new VSC(180, 5.684, 12.53), new VSC(171, 3.001, 78.714), new VSC(158, 2.909, 0.963), new VSC(155, 5.591, 4.453), new VSC(154, 4.652, 35.164), new VSC(152, 2.942, 77.751), new VSC(143, 2.59, 62.251), new VSC(121, 4.148, 127.472), new VSC(116, 3.732, 65.22), new VSC(102, 4.188, 145.631), new VSC(102, 6.034, 0.112), new VSC(88, 3.99, 18.16), new VSC(88, 6.16, 202.25), new VSC(81, 2.64, 22.09), new VSC(72, 6.05, 70.33), new VSC(69, 4.05, 77.96), new VSC(59, 3.7, 67.67), new VSC(47, 3.54, 351.82), new VSC(44, 5.91, 7.11), new VSC(43, 5.72, 5.42), new VSC(39, 4.92, 222.86), new VSC(36, 5.9, 33.68), new VSC(36, 3.29, 8.08), new VSC(36, 3.33, 71.6), new VSC(35, 5.08, 38.13), new VSC(31, 5.62, 984.6), new VSC(31, 5.5, 59.8), new VSC(31, 5.46, 160.61), new VSC(30, 1.66, 447.8), new VSC(29, 1.15, 462.02), new VSC(29, 4.52, 84.34), new VSC(27, 5.54, 131.4), new VSC(27, 6.15, 299.13), new VSC(26, 4.99, 137.03), new VSC(25, 5.74, 380.13)]; +const g_L2UranusCoefficients = [new VSC(53033, 0, 0), new VSC(2358, 2.2601, 74.7816), new VSC(769, 4.526, 11.046), new VSC(552, 3.258, 63.736), new VSC(542, 2.276, 3.932), new VSC(529, 4.923, 1.484), new VSC(258, 3.691, 3.181), new VSC(239, 5.858, 149.563), new VSC(182, 6.218, 70.849), new VSC(54, 1.44, 76.27), new VSC(49, 6.03, 56.62), new VSC(45, 3.91, 2.45), new VSC(45, 0.81, 85.83), new VSC(38, 1.78, 52.69), new VSC(37, 4.46, 2.97), new VSC(33, 0.86, 9.56), new VSC(29, 5.1, 73.3), new VSC(24, 2.11, 18.16), new VSC(22, 5.99, 138.52), new VSC(22, 4.82, 78.71), new VSC(21, 2.4, 77.96), new VSC(21, 2.17, 224.34), new VSC(17, 2.54, 145.63), new VSC(17, 3.47, 12.53), new VSC(12, 0.02, 22.09), new VSC(11, 0.08, 127.47), new VSC(10, 5.16, 71.6), new VSC(10, 4.46, 62.25), new VSC(9, 4.26, 7.11), new VSC(8, 5.5, 67.67), new VSC(7, 1.25, 5.42), new VSC(6, 3.36, 447.8), new VSC(6, 5.45, 65.22), new VSC(6, 4.52, 151.05), new VSC(6, 5.73, 462.02)]; +const g_L3UranusCoefficients = [new VSC(121, 0.024, 74.782), new VSC(68, 4.12, 3.93), new VSC(53, 2.39, 11.05), new VSC(46, 0, 0), new VSC(45, 2.04, 3.18), new VSC(44, 2.96, 1.48), new VSC(25, 4.89, 63.74), new VSC(21, 4.55, 70.85), new VSC(20, 2.31, 149.56), new VSC(9, 1.58, 56.62), new VSC(4, 0.23, 18.16), new VSC(4, 5.39, 76.27), new VSC(4, 0.95, 77.96), new VSC(3, 4.98, 85.83), new VSC(3, 4.13, 52.69), new VSC(3, 0.37, 78.71), new VSC(2, 0.86, 145.63), new VSC(2, 5.66, 9.56)]; +const g_L4UranusCoefficients = [new VSC(114, 3.142, 0), new VSC(6, 4.58, 74.78), new VSC(3, 0.35, 11.05), new VSC(1, 3.42, 56.62)]; +const g_B0UranusCoefficients = [new VSC(1346278, 2.6187781, 74.7815986), new VSC(62341, 5.08111, 149.5632), new VSC(61601, 3.14159, 0), new VSC(9964, 1.616, 76.2661), new VSC(9926, 0.5763, 73.2971), new VSC(3259, 1.2612, 224.3448), new VSC(2972, 2.2437, 1.4845), new VSC(2010, 6.0555, 148.0787), new VSC(1522, 0.2796, 63.7359), new VSC(924, 4.038, 151.048), new VSC(761, 6.14, 71.813), new VSC(522, 3.321, 138.517), new VSC(463, 0.743, 85.827), new VSC(437, 3.381, 529.691), new VSC(435, 0.341, 77.751), new VSC(431, 3.554, 213.299), new VSC(420, 5.213, 11.046), new VSC(245, 0.788, 2.969), new VSC(233, 2.257, 222.86), new VSC(216, 1.591, 38.133), new VSC(180, 3.725, 299.126), new VSC(175, 1.236, 146.594), new VSC(174, 1.937, 380.128), new VSC(160, 5.336, 111.43), new VSC(144, 5.962, 35.164), new VSC(116, 5.739, 70.849), new VSC(106, 0.941, 70.328), new VSC(102, 2.619, 78.714)]; +const g_B1UranusCoefficients = [new VSC(206366, 4.123943, 74.781599), new VSC(8563, 0.3382, 149.5632), new VSC(1726, 2.1219, 73.2971), new VSC(1374, 0, 0), new VSC(1369, 3.0686, 76.2661), new VSC(451, 3.777, 1.484), new VSC(400, 2.848, 224.345), new VSC(307, 1.255, 148.079), new VSC(154, 3.786, 63.736), new VSC(112, 5.573, 151.048), new VSC(111, 5.329, 138.517), new VSC(83, 3.59, 71.81), new VSC(56, 3.4, 85.83), new VSC(54, 1.7, 77.75), new VSC(42, 1.21, 11.05), new VSC(41, 4.45, 78.71), new VSC(32, 3.77, 222.86), new VSC(30, 2.56, 2.97), new VSC(27, 5.34, 213.3), new VSC(26, 0.42, 380.13)]; +const g_B2UranusCoefficients = [new VSC(9212, 5.8004, 74.7816), new VSC(557, 0, 0), new VSC(286, 2.177, 149.563), new VSC(95, 3.84, 73.3), new VSC(45, 4.88, 76.27), new VSC(20, 5.46, 1.48), new VSC(15, 0.88, 138.52), new VSC(14, 2.85, 148.08), new VSC(14, 5.07, 63.74), new VSC(10, 5, 224.34), new VSC(8, 6.27, 78.71)]; +const g_B3UranusCoefficients = [new VSC(268, 1.251, 74.782), new VSC(11, 3.14, 0), new VSC(6, 4.01, 149.56), new VSC(3, 5.78, 73.3)]; +const g_B4UranusCoefficients = [new VSC(6, 2.85, 74.78)]; +const g_R0UranusCoefficients = [new VSC(1921264848, 0, 0), new VSC(88784984, 5.60377527, 74.78159857), new VSC(3440836, 0.328361, 73.2971259), new VSC(2055653, 1.7829517, 149.5631971), new VSC(649322, 4.522473, 76.266071), new VSC(602248, 3.860038, 63.735898), new VSC(496404, 1.401399, 454.909367), new VSC(338526, 1.580027, 138.517497), new VSC(243508, 1.570866, 71.812653), new VSC(190522, 1.998094, 1.484473), new VSC(161858, 2.791379, 148.078724), new VSC(143706, 1.383686, 11.0457), new VSC(93192, 0.17437, 36.64856), new VSC(89806, 3.66105, 109.94569), new VSC(71424, 4.24509, 224.3448), new VSC(46677, 1.39977, 35.16409), new VSC(39026, 3.36235, 277.03499), new VSC(39010, 1.66971, 70.84945), new VSC(36755, 3.88649, 146.59425), new VSC(30349, 0.701, 151.04767), new VSC(29156, 3.18056, 77.75054), new VSC(25786, 3.78538, 85.8273), new VSC(25620, 5.25656, 380.12777), new VSC(22637, 0.72519, 529.69097), new VSC(20473, 2.7964, 70.32818), new VSC(20472, 1.55589, 202.2534), new VSC(17901, 0.55455, 2.96895), new VSC(15503, 5.35405, 38.13304), new VSC(14702, 4.90434, 108.46122), new VSC(12897, 2.62154, 111.43016), new VSC(12328, 5.96039, 127.4718), new VSC(11959, 1.75044, 984.60033), new VSC(11853, 0.99343, 52.6902), new VSC(11696, 3.29826, 3.93215), new VSC(11495, 0.43774, 65.22037), new VSC(10793, 1.42105, 213.2991), new VSC(9111, 4.9964, 62.2514), new VSC(8421, 5.2535, 222.8603), new VSC(8402, 5.0388, 415.5525), new VSC(7449, 0.7949, 351.8166), new VSC(7329, 3.9728, 183.2428), new VSC(6046, 5.6796, 78.7138), new VSC(5524, 3.115, 9.5612), new VSC(5445, 5.1058, 145.1098), new VSC(5238, 2.6296, 33.6796), new VSC(4079, 3.2206, 340.7709), new VSC(3919, 4.2502, 39.6175), new VSC(3802, 6.1099, 184.7273), new VSC(3781, 3.4584, 456.3938), new VSC(3687, 2.4872, 453.4249), new VSC(3102, 4.1403, 219.8914), new VSC(2963, 0.8298, 56.6224), new VSC(2942, 0.4239, 299.1264), new VSC(2940, 2.1464, 137.033), new VSC(2938, 3.6766, 140.002), new VSC(2865, 0.31, 12.5302), new VSC(2538, 4.8546, 131.4039), new VSC(2364, 0.4425, 554.07), new VSC(2183, 2.9404, 305.3462)]; +const g_R1UranusCoefficients = [new VSC(1479896, 3.6720571, 74.7815986), new VSC(71212, 6.22601, 63.7359), new VSC(68627, 6.13411, 149.5632), new VSC(24060, 3.14159, 0), new VSC(21468, 2.60177, 76.26607), new VSC(20857, 5.24625, 11.0457), new VSC(11405, 0.01848, 70.84945), new VSC(7497, 0.4236, 73.2971), new VSC(4244, 1.4169, 85.8273), new VSC(3927, 3.1551, 71.8127), new VSC(3578, 2.3116, 224.3448), new VSC(3506, 2.5835, 138.5175), new VSC(3229, 5.255, 3.9322), new VSC(3060, 0.1532, 1.4845), new VSC(2564, 0.9808, 148.0787), new VSC(2429, 3.9944, 52.6902), new VSC(1645, 2.6535, 127.4718), new VSC(1584, 1.4305, 78.7138), new VSC(1508, 5.06, 151.0477), new VSC(1490, 2.6756, 56.6224), new VSC(1413, 4.5746, 202.2534), new VSC(1403, 1.3699, 77.7505), new VSC(1228, 1.047, 62.2514), new VSC(1033, 0.2646, 131.4039), new VSC(992, 2.172, 65.22), new VSC(862, 5.055, 351.817), new VSC(744, 3.076, 35.164), new VSC(687, 2.499, 77.963), new VSC(647, 4.473, 70.328), new VSC(624, 0.863, 9.561), new VSC(604, 0.907, 984.6), new VSC(575, 3.231, 447.796), new VSC(562, 2.718, 462.023), new VSC(530, 5.917, 213.299), new VSC(528, 5.151, 2.969)]; +const g_R2UranusCoefficients = [new VSC(22440, 0.69953, 74.7816), new VSC(4727, 1.699, 63.7359), new VSC(1682, 4.6483, 70.8494), new VSC(1650, 3.0966, 11.0457), new VSC(1434, 3.5212, 149.5632), new VSC(770, 0, 0), new VSC(500, 6.172, 76.266), new VSC(461, 0.767, 3.932), new VSC(390, 4.496, 56.622), new VSC(390, 5.527, 85.827), new VSC(292, 0.204, 52.69), new VSC(287, 3.534, 73.297), new VSC(273, 3.847, 138.517), new VSC(220, 1.964, 131.404), new VSC(216, 0.848, 77.963), new VSC(205, 3.248, 78.714), new VSC(149, 4.898, 127.472), new VSC(129, 2.081, 3.181)]; +const g_R3UranusCoefficients = [new VSC(1164, 4.7345, 74.7816), new VSC(212, 3.343, 63.736), new VSC(196, 2.98, 70.849), new VSC(105, 0.958, 11.046), new VSC(73, 1, 149.56), new VSC(72, 0.03, 56.62), new VSC(55, 2.59, 3.93), new VSC(36, 5.65, 77.96), new VSC(34, 3.82, 76.27), new VSC(32, 3.6, 131.4)]; +const g_R4UranusCoefficients = [new VSC(53, 3.01, 74.78), new VSC(10, 1.91, 56.62)]; + + +// CAAUranus + +export function CAAUranus() { } + +CAAUranus.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nL0Coefficients = g_L0UranusCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0UranusCoefficients[i].a * Math.cos(g_L0UranusCoefficients[i].b + g_L0UranusCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1UranusCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1UranusCoefficients[i].a * Math.cos(g_L1UranusCoefficients[i].b + g_L1UranusCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2UranusCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2UranusCoefficients[i].a * Math.cos(g_L2UranusCoefficients[i].b + g_L2UranusCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3UranusCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3UranusCoefficients[i].a * Math.cos(g_L3UranusCoefficients[i].b + g_L3UranusCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4UranusCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4UranusCoefficients[i].a * Math.cos(g_L4UranusCoefficients[i].b + g_L4UranusCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAUranus.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0UranusCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0UranusCoefficients[i].a * Math.cos(g_B0UranusCoefficients[i].b + g_B0UranusCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1UranusCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1UranusCoefficients[i].a * Math.cos(g_B1UranusCoefficients[i].b + g_B1UranusCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2UranusCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2UranusCoefficients[i].a * Math.cos(g_B2UranusCoefficients[i].b + g_B2UranusCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3UranusCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3UranusCoefficients[i].a * Math.cos(g_B3UranusCoefficients[i].b + g_B3UranusCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4UranusCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4UranusCoefficients[i].a * Math.cos(g_B4UranusCoefficients[i].b + g_B4UranusCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAUranus.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nR0Coefficients = g_R0UranusCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0UranusCoefficients[i].a * Math.cos(g_R0UranusCoefficients[i].b + g_R0UranusCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1UranusCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1UranusCoefficients[i].a * Math.cos(g_R1UranusCoefficients[i].b + g_R1UranusCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2UranusCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2UranusCoefficients[i].a * Math.cos(g_R2UranusCoefficients[i].b + g_R2UranusCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3UranusCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3UranusCoefficients[i].a * Math.cos(g_R3UranusCoefficients[i].b + g_R3UranusCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4UranusCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4UranusCoefficients[i].a * Math.cos(g_R4UranusCoefficients[i].b + g_R4UranusCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; +}; + +var CAAUranus$ = {}; + +registerType("CAAUranus", [CAAUranus, CAAUranus$, null]); + diff --git a/engine/esm/astrocalc/venus.js b/engine/esm/astrocalc/venus.js new file mode 100644 index 00000000..9b62ce41 --- /dev/null +++ b/engine/esm/astrocalc/venus.js @@ -0,0 +1,165 @@ +// Originally `AAVENUS.CPP` +// "Purpose: Implementation for the algorithms which obtain the heliocentric position of Venus" +// Last update of original: PJN / 29-12-2003 +// +// Translated into C# and released by Microsoft, then transpiled into JavaScript +// by ScriptSharp, for the WorldWide Telescope project. +// +// The legal notices in the original code are as follows: +// +// Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) +// +// All rights reserved. +// +// Copyright / Usage Details: +// +// You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) +// when your product is released in binary form. You are allowed to modify the source code in any way you want +// except you cannot modify the copyright details at the top of each module. If you want to distribute source +// code with your application, then you are only allowed to distribute versions released by the author. This is +// to maintain a single distribution point for the source code. + +import { registerType } from "../typesystem.js"; +import { CT } from "./coordinate_transformation.js"; +import { VSC } from "./earth.js"; + + +// Coefficients + +const g_L0VenusCoefficients = [new VSC(317614667, 0, 0), new VSC(1353968, 5.5931332, 10213.2855462), new VSC(89892, 5.3065, 20426.57109), new VSC(5477, 4.4163, 7860.4194), new VSC(3456, 2.6996, 11790.6291), new VSC(2372, 2.9938, 3930.2097), new VSC(1664, 4.2502, 1577.3435), new VSC(1438, 4.1575, 9683.5946), new VSC(1317, 5.1867, 26.2983), new VSC(1201, 6.1536, 30639.8566), new VSC(769, 0.816, 9437.763), new VSC(761, 1.95, 529.691), new VSC(708, 1.065, 775.523), new VSC(585, 3.998, 191.448), new VSC(500, 4.123, 15720.839), new VSC(429, 3.586, 19367.189), new VSC(327, 5.677, 5507.553), new VSC(326, 4.591, 10404.734), new VSC(232, 3.163, 9153.904), new VSC(180, 4.653, 1109.379), new VSC(155, 5.57, 19651.048), new VSC(128, 4.226, 20.775), new VSC(128, 0.962, 5661.332), new VSC(106, 1.537, 801.821)]; +const g_L1VenusCoefficients = [new VSC(1021352943053, 0, 0), new VSC(95708, 2.46424, 10213.28555), new VSC(14445, 0.51625, 20426.57109), new VSC(213, 1.795, 30639.857), new VSC(174, 2.655, 26.298), new VSC(152, 6.106, 1577.344), new VSC(82, 5.7, 191.45), new VSC(70, 2.68, 9437.76), new VSC(52, 3.6, 775.52), new VSC(38, 1.03, 529.69), new VSC(30, 1.25, 5507.55), new VSC(25, 6.11, 10404.73)]; +const g_L2VenusCoefficients = [new VSC(54127, 0, 0), new VSC(3891, 0.3451, 10213.2855), new VSC(1338, 2.0201, 20426.5711), new VSC(24, 2.05, 26.3), new VSC(19, 3.54, 30639.86), new VSC(10, 3.97, 775.52), new VSC(7, 1.52, 1577.34), new VSC(6, 1, 191.45)]; +const g_L3VenusCoefficients = [new VSC(136, 4.804, 10213.286), new VSC(78, 3.67, 20426.57), new VSC(26, 0, 0)]; +const g_L4VenusCoefficients = [new VSC(114, 3.1416, 0), new VSC(3, 5.21, 20426.57), new VSC(2, 2.51, 10213.29)]; +const g_L5VenusCoefficients = [new VSC(1, 3.14, 0)]; +const g_B0VenusCoefficients = [new VSC(5923638, 0.2670278, 10213.2855462), new VSC(40108, 1.14737, 20426.57109), new VSC(32815, 3.14737, 0), new VSC(1011, 1.0895, 30639.8566), new VSC(149, 6.254, 18073.705), new VSC(138, 0.86, 1577.344), new VSC(130, 3.672, 9437.763), new VSC(120, 3.705, 2352.866), new VSC(108, 4.539, 22003.915)]; +const g_B1VenusCoefficients = [new VSC(513348, 1.803643, 10213.285546), new VSC(4380, 3.3862, 20426.5711), new VSC(199, 0, 0), new VSC(197, 2.53, 30639.857)]; +const g_B2VenusCoefficients = [new VSC(22378, 3.38509, 10213.28555), new VSC(282, 0, 0), new VSC(173, 5.256, 20426.571), new VSC(27, 3.87, 30639.86)]; +const g_B3VenusCoefficients = [new VSC(647, 4.992, 10213.286), new VSC(20, 3.14, 0), new VSC(6, 0.77, 20426.57), new VSC(3, 5.44, 30639.86)]; +const g_B4VenusCoefficients = [new VSC(14, 0.32, 10213.29)]; +const g_R0VenusCoefficients = [new VSC(72334821, 0, 0), new VSC(489824, 4.021518, 10213.285546), new VSC(1658, 4.9021, 20426.5711), new VSC(1632, 2.8455, 7860.4194), new VSC(1378, 1.1285, 11790.6291), new VSC(498, 2.587, 9683.595), new VSC(374, 1.423, 3930.21), new VSC(264, 5.529, 9437.763), new VSC(237, 2.551, 15720.839), new VSC(222, 2.013, 19367.189), new VSC(126, 2.728, 1577.344), new VSC(119, 3.02, 10404.734)]; +const g_R1VenusCoefficients = [new VSC(34551, 0.89199, 10213.28555), new VSC(234, 1.772, 20426.571), new VSC(234, 3.142, 0)]; +const g_R2VenusCoefficients = [new VSC(1407, 5.0637, 10213.2855), new VSC(16, 5.47, 20426.57), new VSC(13, 0, 0)]; +const g_R3VenusCoefficients = [new VSC(50, 3.22, 10213.29)]; +const g_R4VenusCoefficients = [new VSC(1, 0.92, 10213.29)]; + + +// CAAVenus + +export function CAAVenus() { } + +CAAVenus.eclipticLongitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var rho5 = rho4 * rho; + var nL0Coefficients = g_L0VenusCoefficients.length; + var L0 = 0; + var i; + for (i = 0; i < nL0Coefficients; i++) { + L0 += g_L0VenusCoefficients[i].a * Math.cos(g_L0VenusCoefficients[i].b + g_L0VenusCoefficients[i].c * rho); + } + var nL1Coefficients = g_L1VenusCoefficients.length; + var L1 = 0; + for (i = 0; i < nL1Coefficients; i++) { + L1 += g_L1VenusCoefficients[i].a * Math.cos(g_L1VenusCoefficients[i].b + g_L1VenusCoefficients[i].c * rho); + } + var nL2Coefficients = g_L2VenusCoefficients.length; + var L2 = 0; + for (i = 0; i < nL2Coefficients; i++) { + L2 += g_L2VenusCoefficients[i].a * Math.cos(g_L2VenusCoefficients[i].b + g_L2VenusCoefficients[i].c * rho); + } + var nL3Coefficients = g_L3VenusCoefficients.length; + var L3 = 0; + for (i = 0; i < nL3Coefficients; i++) { + L3 += g_L3VenusCoefficients[i].a * Math.cos(g_L3VenusCoefficients[i].b + g_L3VenusCoefficients[i].c * rho); + } + var nL4Coefficients = g_L4VenusCoefficients.length; + var L4 = 0; + for (i = 0; i < nL4Coefficients; i++) { + L4 += g_L4VenusCoefficients[i].a * Math.cos(g_L4VenusCoefficients[i].b + g_L4VenusCoefficients[i].c * rho); + } + var nL5Coefficients = g_L5VenusCoefficients.length; + var L5 = 0; + for (i = 0; i < nL5Coefficients; i++) { + L5 += g_L5VenusCoefficients[i].a * Math.cos(g_L5VenusCoefficients[i].b + g_L5VenusCoefficients[i].c * rho); + } + var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; + vvalue = CT.m360(CT.r2D(vvalue)); + return vvalue; +}; + +CAAVenus.eclipticLatitude = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nB0Coefficients = g_B0VenusCoefficients.length; + var B0 = 0; + var i; + for (i = 0; i < nB0Coefficients; i++) { + B0 += g_B0VenusCoefficients[i].a * Math.cos(g_B0VenusCoefficients[i].b + g_B0VenusCoefficients[i].c * rho); + } + var nB1Coefficients = g_B1VenusCoefficients.length; + var B1 = 0; + for (i = 0; i < nB1Coefficients; i++) { + B1 += g_B1VenusCoefficients[i].a * Math.cos(g_B1VenusCoefficients[i].b + g_B1VenusCoefficients[i].c * rho); + } + var nB2Coefficients = g_B2VenusCoefficients.length; + var B2 = 0; + for (i = 0; i < nB2Coefficients; i++) { + B2 += g_B2VenusCoefficients[i].a * Math.cos(g_B2VenusCoefficients[i].b + g_B2VenusCoefficients[i].c * rho); + } + var nB3Coefficients = g_B3VenusCoefficients.length; + var B3 = 0; + for (i = 0; i < nB3Coefficients; i++) { + B3 += g_B3VenusCoefficients[i].a * Math.cos(g_B3VenusCoefficients[i].b + g_B3VenusCoefficients[i].c * rho); + } + var nB4Coefficients = g_B4VenusCoefficients.length; + var B4 = 0; + for (i = 0; i < nB4Coefficients; i++) { + B4 += g_B4VenusCoefficients[i].a * Math.cos(g_B4VenusCoefficients[i].b + g_B4VenusCoefficients[i].c * rho); + } + var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; + vvalue = CT.r2D(vvalue); + return vvalue; +}; + +CAAVenus.radiusVector = function (JD) { + var rho = (JD - 2451545) / 365250; + var rhosquared = rho * rho; + var rhocubed = rhosquared * rho; + var rho4 = rhocubed * rho; + var nR0Coefficients = g_R0VenusCoefficients.length; + var R0 = 0; + var i; + for (i = 0; i < nR0Coefficients; i++) { + R0 += g_R0VenusCoefficients[i].a * Math.cos(g_R0VenusCoefficients[i].b + g_R0VenusCoefficients[i].c * rho); + } + var nR1Coefficients = g_R1VenusCoefficients.length; + var R1 = 0; + for (i = 0; i < nR1Coefficients; i++) { + R1 += g_R1VenusCoefficients[i].a * Math.cos(g_R1VenusCoefficients[i].b + g_R1VenusCoefficients[i].c * rho); + } + var nR2Coefficients = g_R2VenusCoefficients.length; + var R2 = 0; + for (i = 0; i < nR2Coefficients; i++) { + R2 += g_R2VenusCoefficients[i].a * Math.cos(g_R2VenusCoefficients[i].b + g_R2VenusCoefficients[i].c * rho); + } + var nR3Coefficients = g_R3VenusCoefficients.length; + var R3 = 0; + for (i = 0; i < nR3Coefficients; i++) { + R3 += g_R3VenusCoefficients[i].a * Math.cos(g_R3VenusCoefficients[i].b + g_R3VenusCoefficients[i].c * rho); + } + var nR4Coefficients = g_R4VenusCoefficients.length; + var R4 = 0; + for (i = 0; i < nR4Coefficients; i++) { + R4 += g_R4VenusCoefficients[i].a * Math.cos(g_R4VenusCoefficients[i].b + g_R4VenusCoefficients[i].c * rho); + } + return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; +}; + +var CAAVenus$ = {}; + +registerType("CAAVenus", [CAAVenus, CAAVenus$, null]); diff --git a/engine/esm/baseplanets.js b/engine/esm/baseplanets.js new file mode 100644 index 00000000..d0259371 --- /dev/null +++ b/engine/esm/baseplanets.js @@ -0,0 +1,51 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Planet-related code that can come lower in the dependency graph. + +import { registerType } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { Dates, PointList } from "./graphics/primitives3d.js"; + + +// BasePlanets + +export function BasePlanets() { } + +BasePlanets.drawPointPlanet = function (renderContext, location, size, color, zOrder) { + var center = location; + var rad = size / 2; + if (renderContext.gl != null) { + var ppList = new PointList(renderContext); + ppList.minSize = 20; + ppList.addPoint(location.copy(), color._clone(), new Dates(0, 1), size / 100); + ppList.depthBuffered = true; + ppList.draw(renderContext, 1, false); + } + else { + var screenSpacePnt = renderContext.WVP.transform(center); + if (screenSpacePnt.z < 0) { + return; + } + if (!zOrder) { + if (Vector3d.dot(renderContext.get_viewPoint(), center) < 0.55) { + return; + } + } + var ctx = renderContext.device; + ctx.save(); + ctx.beginPath(); + ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); + ctx.lineWidth = 1; + ctx.fillStyle = color.toString(); + if (true) { + ctx.fill(); + } + ctx.globalAlpha = 1; + ctx.strokeStyle = color.toString(); + ctx.stroke(); + ctx.restore(); + } +}; + +registerType("BasePlanets", [BasePlanets, {}, null]); diff --git a/engine/esm/baseutil.js b/engine/esm/baseutil.js new file mode 100644 index 00000000..4b65f185 --- /dev/null +++ b/engine/esm/baseutil.js @@ -0,0 +1,207 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Miscellaneous utilities. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; + +// wwtlib.Util + +export function Util() { +} + +Util.splitString = function (target, split) { + var parts = []; + var start = 0; + var end = 0; + for (var i = 0; i < target.length; i++) { + var found = false; + for (var j = 0; j < split.length; j++) { + if (target[i] === split[j]) { + parts.push(target.substring(start, end - start)); + found = true; + continue; + } + start = i + 1; + end = i + 1; + } + if (!found) { + end++; + } + } + if (end > start) { + parts.push(target.substring(start, end - start)); + } + return parts; +}; + +Util.stringContains = function (target, chars) { + for (var i = 0; i < chars.length; i++) { + if (target.indexOf(chars[i]) > -1) { + return true; + } + } + return false; +}; + +Util.getHashCode = function (target) { + var hash = 0; + if (!target.length) { + return hash; + } + for (var i = 0; i < target.length; i++) { + var c = target.charCodeAt(i); + hash = ((hash << 5) - hash) + c; + } + return hash; +}; + +Util.compare = function (l, r) { + if (l === r) { + return 0; + } + if (l > r) { + return 1; + } + return -1; +}; + +Util.logN = function (num, b) { + return Math.log(num) / Math.log(b); +}; + +// Parse timespan into int with milliseconds +Util.parseTimeSpan = function (timespan) { + var val = 0; + var parts = timespan.split(':'); + if (parts.length === 3) { + val += parseInt(parts[0]) * 3600000; + val += parseInt(parts[1]) * 60000; + val += ss.truncate((parseFloat(parts[2]) * 1000)); + } + return val; +}; + +// convert duration to HH:MM:SS.S +Util.xmlDuration = function (duration) { + var s = duration / 1000; + var hours = Math.floor(s / 3600); + var min = Math.floor(s / 60) - (hours * 60); + var sec = s - ((hours * 3600) + min * 60); + return ss.format('{0}:{1}:{2}', hours, min, sec); +}; + +Util.xmlDate = function (d) { + var hours = d.getHours(); + var amPm = 'AM'; + if (hours > 12) { + hours -= 12; + amPm = 'PM'; + } + return (d.getMonth() + 1).toString() + '/' + d.getDate().toString() + '/' + d.getFullYear().toString() + ' ' + hours.toString() + ':' + d.getMinutes().toString() + ':' + d.getSeconds().toString() + ' ' + amPm; +}; + +Util.selectSingleNode = function (parent, name) { + var node = null; + var $enum1 = ss.enumerate(parent.childNodes); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child.nodeName === name) { + node = child; + break; + } + } + return node; +}; + +Util.getInnerText = function (node) { + if (ss.emptyString(node.text)) { + var cn = node; + return cn.textContent; + } + else { + return node.text; + } +}; + +Util.getWrappedText = function (ctx, text, width) { + var lines = []; + lines.push(text); + return lines; +}; + +Util.toHex = function (number) { + var num = Math.max(0, Math.min(ss.truncate(number), 255)); + return '0123456789ABCDEF'.substr((num - num % 16) / 16, 1) + '0123456789ABCDEF'.substr(num % 16, 1); +}; + +Util.fromHex = function (data) { + var val = 0; + switch (data.substr(1, 1).toUpperCase()) { + case 'A': + val += 10; + break; + case 'B': + val += 11; + break; + case 'C': + val += 12; + break; + case 'D': + val += 13; + break; + case 'E': + val += 14; + break; + case 'F': + val += 15; + break; + default: + val += parseInt(data.substr(1, 1)); + break; + } + switch (data.substr(0, 1).toUpperCase()) { + case 'A': + val += 10 * 16; + break; + case 'B': + val += 11 * 16; + break; + case 'C': + val += 12 * 16; + break; + case 'D': + val += 13 * 16; + break; + case 'E': + val += 14 * 16; + break; + case 'F': + val += 15 * 16; + break; + default: + val += parseInt(data.substr(0, 1)) * 16; + break; + } + return val; +}; + +Util._openUrl = function (url) { + window.open(url); +}; + +Util.log10 = function (num) { + return Math.log(num) / 2.30258509299405; +}; + +Util.sign = function (num) { + if (num < 0) { + return -1; + } + return 1; +}; + +var Util$ = {}; + +registerType("Util", [Util, Util$, null]); diff --git a/engine/esm/blend_state.js b/engine/esm/blend_state.js new file mode 100644 index 00000000..9ac83e31 --- /dev/null +++ b/engine/esm/blend_state.js @@ -0,0 +1,82 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Blend state. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; + + +// wwtlib.BlendState + +export function BlendState() { + this._switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); + this._state = false; + this._targetState = this._state; + this._delayTime = 1000; +} + +BlendState.create = function (initialState, delayTime) { + var temp = new BlendState(); + temp._state = initialState; + temp._targetState = initialState; + temp._delayTime = delayTime; + return temp; +}; + +var BlendState$ = { + get_state: function () { + if (this._targetState !== this._state) { + var ts = ss.now() - this._switchedTime; + if (ts > this._delayTime) { + this._state = this._targetState; + } + return true; + } + return this._state; + }, + + set_state: function (value) { + this._switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); + this._state = value; + this._targetState = this._state; + return value; + }, + + get_targetState: function () { + return this._targetState; + }, + + set_targetState: function (value) { + if (this._targetState !== value) { + this._switchedTime = ss.now(); + this._targetState = value; + } + return value; + }, + + get_opacity: function () { + if (this._targetState !== this._state) { + var ts = ss.now() - this._switchedTime; + if (ts > this._delayTime) { + this._state = this._targetState; + } + else { + var opacity = (ts / this._delayTime); + return (this._targetState) ? opacity : 1 - opacity; + } + } + return (this._state) ? 1 : 0; + }, + + get_delayTime: function () { + return this._delayTime; + }, + + set_delayTime: function (value) { + this._delayTime = value; + return value; + } +}; + +registerType("BlendState", [BlendState, BlendState$, null]); diff --git a/engine/esm/camera_parameters.js b/engine/esm/camera_parameters.js new file mode 100644 index 00000000..64bdabc3 --- /dev/null +++ b/engine/esm/camera_parameters.js @@ -0,0 +1,221 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Camera parameters. + +import { registerType, registerEnum } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Vector3d } from "./double3d.js"; +import { Coordinates } from "./coordinates.js"; + + +// wwtlib.SolarSystemObjects + +export var SolarSystemObjects = { + sun: 0, + mercury: 1, + venus: 2, + mars: 3, + jupiter: 4, + saturn: 5, + uranus: 6, + neptune: 7, + pluto: 8, + moon: 9, + io: 10, + europa: 11, + ganymede: 12, + callisto: 13, + ioShadow: 14, + europaShadow: 15, + ganymedeShadow: 16, + callistoShadow: 17, + sunEclipsed: 18, + earth: 19, + custom: 20, + undefined: 65536 +}; + +registerType("SolarSystemObjects", SolarSystemObjects); +registerEnum("SolarSystemObjects", SolarSystemObjects); + + +// wwtlib.InterpolationType + +export var InterpolationType = { + linear: 0, + easeIn: 1, + easeOut: 2, + easeInOut: 3, + exponential: 4, + defaultV: 5 +}; + +registerType("InterpolationType", InterpolationType); +registerEnum("InterpolationType", InterpolationType); + + + +// wwtlib.CameraParameters + +export function CameraParameters() { + this.lat = 0; + this.lng = 0; + this.zoom = 0; + this.rotation = 0; + this.angle = 0; + this.raDec = false; + this.opacity = 0; + this.target = 0; + this.zoom = 360; + this.viewTarget = new Vector3d(); +} + +CameraParameters.create = function (lat, lng, zoom, rotation, angle, opactity) { + var temp = new CameraParameters(); + temp.lat = lat; + temp.lng = lng; + temp.zoom = zoom; + temp.rotation = rotation; + temp.angle = angle; + temp.raDec = false; + temp.opacity = opactity; + temp.viewTarget = Vector3d.create(0, 0, 0); + temp.target = 20; + temp.targetReferenceFrame = ''; + return temp; +}; + +CameraParameters.logN = function (num, b) { + return Math.log(num) / Math.log(b); +}; + +CameraParameters.sinh = function (v) { + return (Math.exp(v) - Math.exp(-v)) / 2; +}; + +CameraParameters.interpolate = function (from, to, alphaIn, type, fastDirectionMove) { + var result = new CameraParameters(); + var alpha = CameraParameters.easeCurve(alphaIn, type); + var alphaBIn = Math.min(1, alphaIn * 2); + var alphaB = CameraParameters.easeCurve(alphaBIn, type); + result.angle = to.angle * alpha + from.angle * (1 - alpha); + result.rotation = to.rotation * alpha + from.rotation * (1 - alpha); + if (fastDirectionMove) { + result.lat = to.lat * alphaB + from.lat * (1 - alphaB); + result.lng = to.lng * alphaB + from.lng * (1 - alphaB); + } + else { + result.lat = to.lat * alpha + from.lat * (1 - alpha); + result.lng = to.lng * alpha + from.lng * (1 - alpha); + } + result.zoom = Math.pow(2, CameraParameters.logN(to.zoom, 2) * alpha + CameraParameters.logN(from.zoom, 2) * (1 - alpha)); + result.opacity = (to.opacity * alpha + from.opacity * (1 - alpha)); + result.viewTarget = Vector3d.lerp(from.viewTarget, to.viewTarget, alpha); + result.targetReferenceFrame = to.targetReferenceFrame; + if (to.target === from.target) { + result.target = to.target; + } + else { + result.target = 20; + } + return result; +}; + +CameraParameters.interpolateGreatCircle = function (from, to, alphaIn, type, fastDirectionMove) { + var result = new CameraParameters(); + var alpha = CameraParameters.easeCurve(alphaIn, type); + var alphaBIn = Math.min(1, alphaIn * 2); + var alphaB = CameraParameters.easeCurve(alphaBIn, type); + result.angle = to.angle * alpha + from.angle * (1 - alpha); + result.rotation = to.rotation * alpha + from.rotation * (1 - alpha); + var left = Coordinates.geoTo3dDouble(from.lat, from.lng); + var right = Coordinates.geoTo3dDouble(to.lat, to.lng); + var mid = Vector3d.slerp(left, right, alpha); + var midV2 = Coordinates.cartesianToLatLng(mid); + result.lat = midV2.y; + result.lng = midV2.x; + result.zoom = Math.pow(2, CameraParameters.logN(to.zoom, 2) * alpha + CameraParameters.logN(from.zoom, 2) * (1 - alpha)); + result.opacity = (to.opacity * alpha + from.opacity * (1 - alpha)); + result.viewTarget = Vector3d.lerp(from.viewTarget, to.viewTarget, alpha); + result.targetReferenceFrame = to.targetReferenceFrame; + if (to.target === from.target) { + result.target = to.target; + } + else { + result.target = 20; + } + return result; +}; + +CameraParameters.easeCurve = function (alpha, type) { + switch (type) { + case 0: + return alpha; + case 4: + return Math.pow(alpha, 2); + case 1: + return ((1 - alpha) * CameraParameters.sinh(alpha / (0.1085712344 * 2)) / 100) + alpha * alpha; + case 2: + return (alpha * (1 - CameraParameters.sinh((1 - alpha) / (0.1085712344 * 2)) / 100)) + (1 - alpha) * alpha; + case 3: + if (alpha < 0.5) { + return CameraParameters.sinh(alpha / 0.1085712344) / 100; + } + else { + return 1 - (CameraParameters.sinh((1 - alpha) / 0.1085712344) / 100); + } + default: + return alpha; + } +}; + +var CameraParameters$ = { + copy: function () { + var temp = new CameraParameters(); + temp.lat = this.lat; + temp.lng = this.lng; + temp.zoom = this.zoom; + temp.rotation = this.rotation; + temp.angle = this.angle; + temp.raDec = this.raDec; + temp.opacity = this.opacity; + temp.viewTarget = this.viewTarget.copy(); + temp.target = this.target; + temp.targetReferenceFrame = this.targetReferenceFrame; + return temp; + }, + + get_RA: function () { + return ((((180 - (this.lng - 180)) / 360) * 24) % 24); + }, + + set_RA: function (value) { + this.lng = 180 - (value / 24 * 360) - 180; + this.raDec = true; + return value; + }, + + get_dec: function () { + return this.lat; + }, + + set_dec: function (value) { + this.lat = value; + return value; + }, + + equals: function (obj) { + if (ss.canCast(obj, CameraParameters)) { + var cam = obj; + if (Math.abs(cam.angle - this.angle) > 0.01 || Math.abs(cam.lat - this.lat) > (cam.zoom / 10000) || Math.abs(cam.get_RA() - this.get_RA()) > (cam.zoom / 1000) || Math.abs(cam.rotation - this.rotation) > 0.1 || Math.abs(cam.zoom - this.zoom) > (Math.abs(cam.zoom) / 1000)) { + return false; + } + return true; + } else { + return false; + } + } +}; + +registerType("CameraParameters", [CameraParameters, CameraParameters$, null]); diff --git a/engine/esm/color.js b/engine/esm/color.js new file mode 100644 index 00000000..c9a93da7 --- /dev/null +++ b/engine/esm/color.js @@ -0,0 +1,556 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Basic color types. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Util } from "./util.js"; + +// wwtlib.Color + +export function Color() { + this.a = 255; + this.b = 255; + this.g = 255; + this.r = 255; + this.name = ''; +} + +Color.fromArgb = function (a, r, g, b) { + var temp = new Color(); + temp.a = a; + temp.r = r; + temp.g = g; + temp.b = b; + return temp; +}; + +Color._fromArgbColor = function (a, col) { + var temp = new Color(); + temp.a = a; + temp.r = col.r; + temp.g = col.g; + temp.b = col.b; + return temp; +}; + +Color.fromName = function (name) { + var temp = Color.load(name); + return temp; +}; + +Color.load = function (color) { + var a = 255, r = 255, g = 255, b = 255; + var pieces = color.split(':'); + if (pieces.length === 5) { + a = parseInt(pieces[1]); + r = parseInt(pieces[2]); + g = parseInt(pieces[3]); + b = parseInt(pieces[4]); + } + else if (pieces.length === 2) { + return Color.fromName(pieces[1].toLowerCase()); + } + else if (pieces.length === 1 && ss.startsWith(pieces[0], '#')) { + return Color.fromHex(pieces[0]); + } + else if (pieces.length === 1 && pieces[0].length === 8) { + return Color.fromSimpleHex(pieces[0]); + } + else if (pieces.length === 1) { + return Color._fromWindowsNamedColor(pieces[0]); + } + return Color.fromArgb(a, r, g, b); +}; + +Color._fromWindowsNamedColor = function (color) { + switch (color.toLowerCase()) { + case 'activeborder': + return Color.fromArgb(255, 180, 180, 180); + case 'activecaption': + return Color.fromArgb(255, 153, 180, 209); + case 'activecaptiontext': + return Color.fromArgb(255, 0, 0, 0); + case 'appworkspace': + return Color.fromArgb(255, 171, 171, 171); + case 'control': + return Color.fromArgb(255, 240, 240, 240); + case 'controldark': + return Color.fromArgb(255, 160, 160, 160); + case 'controldarkdark': + return Color.fromArgb(255, 105, 105, 105); + case 'controllight': + return Color.fromArgb(255, 227, 227, 227); + case 'controllightlight': + return Color.fromArgb(255, 255, 255, 255); + case 'controltext': + return Color.fromArgb(255, 0, 0, 0); + case 'desktop': + return Color.fromArgb(255, 255, 255, 255); + case 'graytext': + return Color.fromArgb(255, 109, 109, 109); + case 'highlight': + return Color.fromArgb(255, 51, 153, 255); + case 'highlighttext': + return Color.fromArgb(255, 255, 255, 255); + case 'hottrack': + return Color.fromArgb(255, 0, 102, 204); + case 'inactiveborder': + return Color.fromArgb(255, 244, 247, 252); + case 'inactivecaption': + return Color.fromArgb(255, 191, 205, 219); + case 'inactivecaptiontext': + return Color.fromArgb(255, 0, 0, 0); + case 'info': + return Color.fromArgb(255, 255, 255, 225); + case 'infotext': + return Color.fromArgb(255, 0, 0, 0); + case 'menu': + return Color.fromArgb(255, 240, 240, 240); + case 'menutext': + return Color.fromArgb(255, 0, 0, 0); + case 'scrollbar': + return Color.fromArgb(255, 200, 200, 200); + case 'window': + return Color.fromArgb(255, 255, 255, 255); + case 'windowframe': + return Color.fromArgb(255, 100, 100, 100); + case 'windowtext': + return Color.fromArgb(255, 0, 0, 0); + case 'transparent': + return Color.fromArgb(0, 255, 255, 255); + case 'aliceblue': + return Color.fromArgb(255, 240, 248, 255); + case 'antiquewhite': + return Color.fromArgb(255, 250, 235, 215); + case 'aqua': + return Color.fromArgb(255, 0, 255, 255); + case 'aquamarine': + return Color.fromArgb(255, 127, 255, 212); + case 'azure': + return Color.fromArgb(255, 240, 255, 255); + case 'beige': + return Color.fromArgb(255, 245, 245, 220); + case 'bisque': + return Color.fromArgb(255, 255, 228, 196); + case 'black': + return Color.fromArgb(255, 0, 0, 0); + case 'blanchedalmond': + return Color.fromArgb(255, 255, 235, 205); + case 'blue': + return Color.fromArgb(255, 0, 0, 255); + case 'blueviolet': + return Color.fromArgb(255, 138, 43, 226); + case 'brown': + return Color.fromArgb(255, 165, 42, 42); + case 'burlywood': + return Color.fromArgb(255, 222, 184, 135); + case 'cadetblue': + return Color.fromArgb(255, 95, 158, 160); + case 'chartreuse': + return Color.fromArgb(255, 127, 255, 0); + case 'chocolate': + return Color.fromArgb(255, 210, 105, 30); + case 'coral': + return Color.fromArgb(255, 255, 127, 80); + case 'cornflowerblue': + return Color.fromArgb(255, 100, 149, 237); + case 'cornsilk': + return Color.fromArgb(255, 255, 248, 220); + case 'crimson': + return Color.fromArgb(255, 220, 20, 60); + case 'cyan': + return Color.fromArgb(255, 0, 255, 255); + case 'darkblue': + return Color.fromArgb(255, 0, 0, 139); + case 'darkcyan': + return Color.fromArgb(255, 0, 139, 139); + case 'darkgoldenrod': + return Color.fromArgb(255, 184, 134, 11); + case 'darkgray': + return Color.fromArgb(255, 169, 169, 169); + case 'darkgreen': + return Color.fromArgb(255, 0, 100, 0); + case 'darkkhaki': + return Color.fromArgb(255, 189, 183, 107); + case 'darkmagenta': + return Color.fromArgb(255, 139, 0, 139); + case 'darkolivegreen': + return Color.fromArgb(255, 85, 107, 47); + case 'darkorange': + return Color.fromArgb(255, 255, 140, 0); + case 'darkorchid': + return Color.fromArgb(255, 153, 50, 204); + case 'darkred': + return Color.fromArgb(255, 139, 0, 0); + case 'darksalmon': + return Color.fromArgb(255, 233, 150, 122); + case 'darkseagreen': + return Color.fromArgb(255, 143, 188, 139); + case 'darkslateblue': + return Color.fromArgb(255, 72, 61, 139); + case 'darkslategray': + return Color.fromArgb(255, 47, 79, 79); + case 'darkturquoise': + return Color.fromArgb(255, 0, 206, 209); + case 'darkviolet': + return Color.fromArgb(255, 148, 0, 211); + case 'deeppink': + return Color.fromArgb(255, 255, 20, 147); + case 'deepskyblue': + return Color.fromArgb(255, 0, 191, 255); + case 'dimgray': + return Color.fromArgb(255, 105, 105, 105); + case 'dodgerblue': + return Color.fromArgb(255, 30, 144, 255); + case 'firebrick': + return Color.fromArgb(255, 178, 34, 34); + case 'floralwhite': + return Color.fromArgb(255, 255, 250, 240); + case 'forestgreen': + return Color.fromArgb(255, 34, 139, 34); + case 'fuchsia': + return Color.fromArgb(255, 255, 0, 255); + case 'gainsboro': + return Color.fromArgb(255, 220, 220, 220); + case 'ghostwhite': + return Color.fromArgb(255, 248, 248, 255); + case 'gold': + return Color.fromArgb(255, 255, 215, 0); + case 'goldenrod': + return Color.fromArgb(255, 218, 165, 32); + case 'gray': + return Color.fromArgb(255, 128, 128, 128); + case 'green': + return Color.fromArgb(255, 0, 128, 0); + case 'greenyellow': + return Color.fromArgb(255, 173, 255, 47); + case 'honeydew': + return Color.fromArgb(255, 240, 255, 240); + case 'hotpink': + return Color.fromArgb(255, 255, 105, 180); + case 'indianred': + return Color.fromArgb(255, 205, 92, 92); + case 'indigo': + return Color.fromArgb(255, 75, 0, 130); + case 'ivory': + return Color.fromArgb(255, 255, 255, 240); + case 'khaki': + return Color.fromArgb(255, 240, 230, 140); + case 'lavender': + return Color.fromArgb(255, 230, 230, 250); + case 'lavenderblush': + return Color.fromArgb(255, 255, 240, 245); + case 'lawngreen': + return Color.fromArgb(255, 124, 252, 0); + case 'lemonchiffon': + return Color.fromArgb(255, 255, 250, 205); + case 'lightblue': + return Color.fromArgb(255, 173, 216, 230); + case 'lightcoral': + return Color.fromArgb(255, 240, 128, 128); + case 'lightcyan': + return Color.fromArgb(255, 224, 255, 255); + case 'lightgoldenrodyellow': + return Color.fromArgb(255, 250, 250, 210); + case 'lightgray': + return Color.fromArgb(255, 211, 211, 211); + case 'lightgreen': + return Color.fromArgb(255, 144, 238, 144); + case 'lightpink': + return Color.fromArgb(255, 255, 182, 193); + case 'lightsalmon': + return Color.fromArgb(255, 255, 160, 122); + case 'lightseagreen': + return Color.fromArgb(255, 32, 178, 170); + case 'lightskyblue': + return Color.fromArgb(255, 135, 206, 250); + case 'lightslategray': + return Color.fromArgb(255, 119, 136, 153); + case 'lightsteelblue': + return Color.fromArgb(255, 176, 196, 222); + case 'lightyellow': + return Color.fromArgb(255, 255, 255, 224); + case 'lime': + return Color.fromArgb(255, 0, 255, 0); + case 'limegreen': + return Color.fromArgb(255, 50, 205, 50); + case 'linen': + return Color.fromArgb(255, 250, 240, 230); + case 'magenta': + return Color.fromArgb(255, 255, 0, 255); + case 'maroon': + return Color.fromArgb(255, 128, 0, 0); + case 'mediumaquamarine': + return Color.fromArgb(255, 102, 205, 170); + case 'mediumblue': + return Color.fromArgb(255, 0, 0, 205); + case 'mediumorchid': + return Color.fromArgb(255, 186, 85, 211); + case 'mediumpurple': + return Color.fromArgb(255, 147, 112, 219); + case 'mediumseagreen': + return Color.fromArgb(255, 60, 179, 113); + case 'mediumslateblue': + return Color.fromArgb(255, 123, 104, 238); + case 'mediumspringgreen': + return Color.fromArgb(255, 0, 250, 154); + case 'mediumturquoise': + return Color.fromArgb(255, 72, 209, 204); + case 'mediumvioletred': + return Color.fromArgb(255, 199, 21, 133); + case 'midnightblue': + return Color.fromArgb(255, 25, 25, 112); + case 'mintcream': + return Color.fromArgb(255, 245, 255, 250); + case 'mistyrose': + return Color.fromArgb(255, 255, 228, 225); + case 'moccasin': + return Color.fromArgb(255, 255, 228, 181); + case 'navajowhite': + return Color.fromArgb(255, 255, 222, 173); + case 'navy': + return Color.fromArgb(255, 0, 0, 128); + case 'oldlace': + return Color.fromArgb(255, 253, 245, 230); + case 'olive': + return Color.fromArgb(255, 128, 128, 0); + case 'olivedrab': + return Color.fromArgb(255, 107, 142, 35); + case 'orange': + return Color.fromArgb(255, 255, 165, 0); + case 'orangered': + return Color.fromArgb(255, 255, 69, 0); + case 'orchid': + return Color.fromArgb(255, 218, 112, 214); + case 'palegoldenrod': + return Color.fromArgb(255, 238, 232, 170); + case 'palegreen': + return Color.fromArgb(255, 152, 251, 152); + case 'paleturquoise': + return Color.fromArgb(255, 175, 238, 238); + case 'palevioletred': + return Color.fromArgb(255, 219, 112, 147); + case 'papayawhip': + return Color.fromArgb(255, 255, 239, 213); + case 'peachpuff': + return Color.fromArgb(255, 255, 218, 185); + case 'peru': + return Color.fromArgb(255, 205, 133, 63); + case 'pink': + return Color.fromArgb(255, 255, 192, 203); + case 'plum': + return Color.fromArgb(255, 221, 160, 221); + case 'powderblue': + return Color.fromArgb(255, 176, 224, 230); + case 'purple': + return Color.fromArgb(255, 128, 0, 128); + case 'red': + return Color.fromArgb(255, 255, 0, 0); + case 'rosybrown': + return Color.fromArgb(255, 188, 143, 143); + case 'royalblue': + return Color.fromArgb(255, 65, 105, 225); + case 'saddlebrown': + return Color.fromArgb(255, 139, 69, 19); + case 'salmon': + return Color.fromArgb(255, 250, 128, 114); + case 'sandybrown': + return Color.fromArgb(255, 244, 164, 96); + case 'seagreen': + return Color.fromArgb(255, 46, 139, 87); + case 'seashell': + return Color.fromArgb(255, 255, 245, 238); + case 'sienna': + return Color.fromArgb(255, 160, 82, 45); + case 'silver': + return Color.fromArgb(255, 192, 192, 192); + case 'skyblue': + return Color.fromArgb(255, 135, 206, 235); + case 'slateblue': + return Color.fromArgb(255, 106, 90, 205); + case 'slategray': + return Color.fromArgb(255, 112, 128, 144); + case 'snow': + return Color.fromArgb(255, 255, 250, 250); + case 'springgreen': + return Color.fromArgb(255, 0, 255, 127); + case 'steelblue': + return Color.fromArgb(255, 70, 130, 180); + case 'tan': + return Color.fromArgb(255, 210, 180, 140); + case 'teal': + return Color.fromArgb(255, 0, 128, 128); + case 'thistle': + return Color.fromArgb(255, 216, 191, 216); + case 'tomato': + return Color.fromArgb(255, 255, 99, 71); + case 'turquoise': + return Color.fromArgb(255, 64, 224, 208); + case 'violet': + return Color.fromArgb(255, 238, 130, 238); + case 'wheat': + return Color.fromArgb(255, 245, 222, 179); + case 'white': + return Color.fromArgb(255, 255, 255, 255); + case 'whitesmoke': + return Color.fromArgb(255, 245, 245, 245); + case 'yellow': + return Color.fromArgb(255, 255, 255, 0); + case 'yellowgreen': + return Color.fromArgb(255, 154, 205, 50); + case 'buttonface': + return Color.fromArgb(255, 240, 240, 240); + case 'buttonhighlight': + return Color.fromArgb(255, 255, 255, 255); + case 'buttonshadow': + return Color.fromArgb(255, 160, 160, 160); + case 'gradientactivecaption': + return Color.fromArgb(255, 185, 209, 234); + case 'gradientinactivecaption': + return Color.fromArgb(255, 215, 228, 242); + case 'menubar': + return Color.fromArgb(255, 240, 240, 240); + case 'menuhighlight': + return Color.fromArgb(255, 51, 153, 255); + } + return Color.fromArgb(255, 255, 255, 255); +}; + +Color.fromHex = function (data) { + var r = Util.fromHex(data.substr(1, 2)); + var g = Util.fromHex(data.substr(3, 2)); + var b = Util.fromHex(data.substr(5, 2)); + var a = 255; + return Color.fromArgb(a, r, g, b); +}; + +Color.fromSimpleHex = function (data) { + var a = Util.fromHex(data.substr(0, 2)); + var r = Util.fromHex(data.substr(2, 2)); + var g = Util.fromHex(data.substr(4, 2)); + var b = Util.fromHex(data.substr(6, 2)); + return Color.fromArgb(a, r, g, b); +}; + +Color.fromInt = function (color) { + var r = (color & 4278190080) >>> 24; + var g = (color & 16711680) >>> 16; + var b = (color & 65280) >>> 8; + var a = (color & 255); + return Color.fromArgb(a, r, g, b); +}; + +var Color$ = { + toFormat: function () { + if (ss.emptyString(this.name)) { + return ss.format('rgb({0},{1},{2})', this.r.toString(), this.g.toString(), this.b.toString()); + } + else { + return this.name; + } + }, + + save: function () { + if (!ss.emptyString(this.name)) { + return ss.format('{0}:{1}', 0, this.name); + } + else { + return ss.format('{0}:{1}:{2}:{3}:{4}', 1, this.a, this.r, this.g, this.b); + } + }, + + toString: function () { + if (ss.emptyString(this.name)) { + return ss.format('#{0}{1}{2}', Util.toHex(this.r), Util.toHex(this.g), Util.toHex(this.b)); + } + else { + return this.name; + } + }, + + toSimpleHex: function () { + if (ss.emptyString(this.name)) { + return ss.format('{0}{1}{2}{3}', Util.toHex(this.a), Util.toHex(this.r), Util.toHex(this.g), Util.toHex(this.b)); + } + else { + return this.name; + } + }, + + _clone: function () { + return Color.fromArgb(this.a, this.r, this.g, this.b); + } +}; + +registerType("Color", [Color, Color$, null]); + + +// wwtlib.Colors + +export function Colors() { } + +Colors.get_black = function () { + return Color.fromArgb(255, 0, 0, 0); +}; + +Colors.get_blue = function () { + return Color.fromArgb(255, 0, 0, 255); +}; + +Colors.get_brown = function () { + return Color.fromArgb(255, 165, 42, 42); +}; + +Colors.get_cyan = function () { + return Color.fromArgb(255, 0, 255, 255); +}; + +Colors.get_darkGray = function () { + return Color.fromArgb(255, 169, 169, 169); +}; + +Colors.get_gray = function () { + return Color.fromArgb(255, 128, 128, 128); +}; + +Colors.get_green = function () { + return Color.fromArgb(255, 0, 255, 0); +}; + +Colors.get_lightGray = function () { + return Color.fromArgb(255, 211, 211, 211); +}; + +Colors.get_magenta = function () { + return Color.fromArgb(255, 255, 0, 255); +}; + +Colors.get_orange = function () { + return Color.fromArgb(255, 255, 165, 0); +}; + +Colors.get_purple = function () { + return Color.fromArgb(255, 128, 0, 128); +}; + +Colors.get_red = function () { + return Color.fromArgb(255, 255, 0, 0); +}; + +Colors.get_transparent = function () { + return Color.fromArgb(0, 255, 255, 255); +}; + +Colors.get_white = function () { + return Color.fromArgb(255, 255, 255, 255); +}; + +Colors.get_yellow = function () { + return Color.fromArgb(255, 255, 255, 0); +}; + +var Colors$ = {}; + +registerType("Colors", [Colors, Colors$, null]); diff --git a/engine/esm/constellation_filter.js b/engine/esm/constellation_filter.js new file mode 100644 index 00000000..0d36dd32 --- /dev/null +++ b/engine/esm/constellation_filter.js @@ -0,0 +1,340 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A filter that can match various sets of constellations. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { BlendState } from "./blend_state.js"; + + +// wwtlib.ConstellationFilter +// +// This type was defined in `Constellations.js`, but we've moved it here to +// break circular dependencies. + +export function ConstellationFilter() { + this.bits = new Array(3); + this.oldBits = new Array(3); + this.blendState = BlendState.create(false, 1000); + this.internal = false; + this.settingsOwned = false; + for (var i = 0; i < 3; i++) { + this.bits[i] = ~this.bits[i]; + this.oldBits[i] = this.bits[i]; + } +} + +ConstellationFilter.families = {}; + +// These are populated in `Constellations._centroidsReady()`. +ConstellationFilter.bitIDs = {}; + +ConstellationFilter.buildConstellationFilters = function () { + var all = ConstellationFilter.get_allConstellation(); + all.internal = true; + ConstellationFilter.families['AllConstellation'] = all; + ConstellationFilter.families['Zodiacal'] = ConstellationFilter.get_zodiacal(); + ConstellationFilter.families['Ursa Major Family'] = ConstellationFilter.get_ursaMajorFamily(); + ConstellationFilter.families['Perseus Family'] = ConstellationFilter.get_perseusFamily(); + ConstellationFilter.families['Hercules Family'] = ConstellationFilter.get_herculesFamily(); + ConstellationFilter.families['Orion Family'] = ConstellationFilter.get_orionFamily(); + ConstellationFilter.families['Heavenly Waters'] = ConstellationFilter.get_heavenlyWaters(); + ConstellationFilter.families['Bayer Family'] = ConstellationFilter.get_bayerFamily(); + ConstellationFilter.families['La Caille Family'] = ConstellationFilter.get_laCaileFamily(); +}; + +ConstellationFilter.saveCustomFilters = function () { + var sb = new ss.StringBuilder(); + var $dict1 = ConstellationFilter.families; + for (var $key2 in $dict1) { + var kv = { key: $key2, value: $dict1[$key2] }; + if (!kv.value.internal) { + sb.append(kv.key); + sb.append(';'); + sb.appendLine(kv.value.toString()); + } + } +}; + +ConstellationFilter.get_allConstellation = function () { + var all = new ConstellationFilter(); + all.setAll(true); + return all; +}; + +ConstellationFilter.get_zodiacal = function () { + var zodiacal = new ConstellationFilter(); + zodiacal.set('ARI', true); + zodiacal.set('TAU', true); + zodiacal.set('GEM', true); + zodiacal.set('CNC', true); + zodiacal.set('LEO', true); + zodiacal.set('VIR', true); + zodiacal.set('LIB', true); + zodiacal.set('SCO', true); + zodiacal.set('SGR', true); + zodiacal.set('CAP', true); + zodiacal.set('AQR', true); + zodiacal.set('PSC', true); + zodiacal.internal = true; + return zodiacal; +}; + +ConstellationFilter.get_ursaMajorFamily = function () { + var uma = new ConstellationFilter(); + uma.set('UMA', true); + uma.set('UMI', true); + uma.set('DRA', true); + uma.set('CVN', true); + uma.set('BOO', true); + uma.set('COM', true); + uma.set('CRB', true); + uma.set('CAM', true); + uma.set('LYN', true); + uma.set('LMI', true); + uma.internal = true; + return uma; +}; + +ConstellationFilter.get_perseusFamily = function () { + var Perseus = new ConstellationFilter(); + Perseus.set('CAS', true); + Perseus.set('CEP', true); + Perseus.set('AND', true); + Perseus.set('PER', true); + Perseus.set('PEG', true); + Perseus.set('CET', true); + Perseus.set('AUR', true); + Perseus.set('LAC', true); + Perseus.set('TRI', true); + Perseus.internal = true; + return Perseus; +}; + +ConstellationFilter.get_herculesFamily = function () { + var hercules = new ConstellationFilter(); + hercules.set('HER', true); + hercules.set('SGE', true); + hercules.set('AQL', true); + hercules.set('LYR', true); + hercules.set('CYG', true); + hercules.set('VUL', true); + hercules.set('HYA', true); + hercules.set('SEX', true); + hercules.set('CRT', true); + hercules.set('CRV', true); + hercules.set('OPH', true); + hercules.set('SER1', true); + hercules.set('SER2', true); + hercules.set('SCT', true); + hercules.set('CEN', true); + hercules.set('LUP', true); + hercules.set('CRA', true); + hercules.set('ARA', true); + hercules.set('TRA', true); + hercules.set('CRU', true); + hercules.internal = true; + return hercules; +}; + +ConstellationFilter.get_orionFamily = function () { + var orion = new ConstellationFilter(); + orion.set('ORI', true); + orion.set('CMA', true); + orion.set('CMI', true); + orion.set('MON', true); + orion.set('LEP', true); + orion.internal = true; + return orion; +}; + +ConstellationFilter.get_heavenlyWaters = function () { + var waters = new ConstellationFilter(); + waters.set('DEL', true); + waters.set('EQU', true); + waters.set('ERI', true); + waters.set('PSA', true); + waters.set('CAR', true); + waters.set('PUP', true); + waters.set('VEL', true); + waters.set('PYX', true); + waters.set('COL', true); + waters.internal = true; + return waters; +}; + +ConstellationFilter.get_bayerFamily = function () { + var bayer = new ConstellationFilter(); + bayer.set('HYA', true); + bayer.set('DOR', true); + bayer.set('VOL', true); + bayer.set('APS', true); + bayer.set('PAV', true); + bayer.set('GRU', true); + bayer.set('PHE', true); + bayer.set('TUC', true); + bayer.set('IND', true); + bayer.set('CHA', true); + bayer.set('MUS', true); + bayer.internal = true; + return bayer; +}; + +ConstellationFilter.get_laCaileFamily = function () { + var LaCaile = new ConstellationFilter(); + LaCaile.set('NOR', true); + LaCaile.set('CIR', true); + LaCaile.set('TEL', true); + LaCaile.set('MIC', true); + LaCaile.set('SCL', true); + LaCaile.set('FOR', true); + LaCaile.set('CAE', true); + LaCaile.set('HOR', true); + LaCaile.set('OCT', true); + LaCaile.set('MEN', true); + LaCaile.set('RET', true); + LaCaile.set('PIC', true); + LaCaile.set('ANT', true); + LaCaile.internal = true; + return LaCaile; +}; + +ConstellationFilter.parse = function (val) { + var parts = (val).split(','); + var cf = new ConstellationFilter(); + try { + for (var i = 0; i < 3; i++) { + cf.bits[i] = parseInt(parts[i]); + } + } + catch ($e1) { } + return cf; +}; + +var ConstellationFilter$ = { + _saveBits: function () { + for (var i = 0; i < 3; i++) { + this.oldBits[i] = this.bits[i]; + } + }, + + _isChanged: function () { + for (var i = 0; i < 3; i++) { + if (this.oldBits[i] !== this.bits[i]) { + return true; + } + } + return false; + }, + + _checkChanged: function () { + if (this._isChanged()) { + this._fireChanged(); + } + }, + + isEnabled: function (abbrev) { + var bitID = ConstellationFilter.bitIDs[abbrev]; + var index = bitID / 32; + bitID = bitID % 32; + return this.blendState.get_state() && !!((1 << bitID) & this.bits[index]); + }, + + isSet: function (abbrev) { + this._saveBits(); + var bitID = ConstellationFilter.bitIDs[abbrev]; + var index = ss.truncate((bitID / 32)); + bitID = bitID % 32; + return !!((1 << bitID) & this.bits[index]); + }, + + set: function (abbrev, state) { + this._saveBits(); + var bitID = ConstellationFilter.bitIDs[abbrev]; + var index = bitID / 32; + bitID = bitID % 32; + if (state) { + this.bits[index] = this.bits[index] | (1 << bitID); + } else { + this.bits[index] = this.bits[index] ^ (1 << bitID); + } + this._checkChanged(); + }, + + setAll: function (state) { + this._saveBits(); + for (var bitID = 0; bitID < 89; bitID++) { + var index = bitID / 32; + var bit = bitID % 32; + if (state) { + this.bits[index] = this.bits[index] | (1 << bit); + } + else { + this.bits[index] = this.bits[index] ^ (1 << bit); + } + } + this._checkChanged(); + }, + + setBits: function (bits) { + this._saveBits(); + for (var i = 0; i < 3; i++) { + this.bits[i] = (bits[i * 4]) + ((bits[i * 4 + 1]) << 8) + ((bits[i * 4 + 2]) << 16) + ((bits[i * 4 + 3]) << 24); + } + this._checkChanged(); + }, + + getBits: function () { + var bits = new Array(12); + var index = 0; + for (var i = 0; i < 3; i++) { + bits[index++] = this.bits[i]; + bits[index++] = (this.bits[i] >> 8); + bits[index++] = (this.bits[i] >> 16); + bits[index++] = (this.bits[i] >> 24); + } + return bits; + }, + + cloneFilter: function (filter) { + this._saveBits(); + for (var i = 0; i < 3; i++) { + this.bits[i] = filter.bits[i]; + } + this._checkChanged(); + }, + + clone: function () { + var newFilter = new ConstellationFilter(); + newFilter.cloneFilter(this); + return newFilter; + }, + + combine: function (filter) { + this._saveBits(); + for (var i = 0; i < 3; i++) { + this.bits[i] = this.bits[i] | filter.bits[i]; + } + this._checkChanged(); + }, + + remove: function (filter) { + this._saveBits(); + for (var i = 0; i < 3; i++) { + this.bits[i] = this.bits[i] & ~filter.bits[i]; + } + this._checkChanged(); + }, + + _fireChanged: function () { + if (this.settingsOwned) { + } + }, + + toString: function () { + return ss.format('{0},{1},{2}', this.bits[0], this.bits[1], this.bits[2]); + } +}; + +registerType("ConstellationFilter", [ConstellationFilter, ConstellationFilter$, null]); diff --git a/engine/esm/constellations.js b/engine/esm/constellations.js new file mode 100644 index 00000000..87e4d225 --- /dev/null +++ b/engine/esm/constellations.js @@ -0,0 +1,514 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Constellations in the sky. + +import { ss } from "./ss.js"; +import { registerType, registerEnum } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { createPlace, makeNewFolder } from "./data_globals.js"; +import { SimpleLineList } from "./graphics/primitives3d.js"; +import { BlendState } from "./blend_state.js"; +import { Color } from "./color.js"; +import { ConstellationFilter } from "./constellation_filter.js"; +import { Coordinates } from "./coordinates.js"; +import { Settings } from "./settings.js"; +import { Text3d, Text3dBatch } from "./sky_text.js"; +import { URLHelpers } from "./url_helpers.js"; +import { WebFile } from "./web_file.js"; + + +// wwtlib.PointType + +export var PointType = { + move: 0, + line: 1, + dash: 2, + start: 3 +}; + +registerType("PointType", PointType); +registerEnum("PointType", PointType); + + +// wwtlib.Lineset + +export function Lineset(name) { + this._name = name; + this.points = []; +} + +var Lineset$ = { + get_name: function () { + return this._name; + }, + + set_name: function (value) { + this._name = value; + return value; + }, + + add: function (ra, dec, pointType, name) { + this.points.push(new Linepoint(ra, dec, pointType, name)); + } +}; + +registerType("Lineset", [Lineset, Lineset$, null]); + + +// wwtlib.Linepoint + +export function Linepoint(ra, dec, type, name) { + this.RA = 0; + this.dec = 0; + this.pointType = 0; + this.name = null; + this.RA = ra; + this.dec = dec; + this.pointType = type; + this.name = name; +} + +var Linepoint$ = { + toString: function () { + if (ss.emptyString(this.name)) { + return Coordinates.formatDMS((((this.RA / 360) * 24 + 12) % 24)) + ', ' + Coordinates.formatDMS(this.dec) + ', ' + this.pointType.toString(); + } else { + return this.name + ', ' + this.pointType.toString(); + } + } +}; + +registerType("Linepoint", [Linepoint, Linepoint$, null]); + + +// wwtlib.Constellations + +export function Constellations() { + this._pointCount = 0; + this._boundry = false; + this._noInterpollation = false; + this.readOnly = false; + this.radius = 1; + this._drawCount = 0; + this._constellationVertexBuffers = {}; +} + +Constellations.RC = 0.017453292519943; +Constellations._maxSeperation = 0.745; +Constellations.containment = null; // initialized in InitializeConstellations +Constellations._constToDraw = ''; +Constellations.selectedSegment = null; +Constellations._artFile = null; +Constellations.artwork = null; +Constellations.boundries = null; +Constellations.pictureBlendStates = {}; + +Constellations.createBasic = function (name) { + var temp = new Constellations(); + temp._name = name; + temp._url = null; + temp.lines = []; + var $enum1 = ss.enumerate(ss.keys(Constellations.fullNames)); + while ($enum1.moveNext()) { + var abbrv = $enum1.current; + temp.lines.push(new Lineset(abbrv)); + } + return temp; +}; + +Constellations.create = function (name, url, boundry, noInterpollation, resource) { + var temp = new Constellations(); + temp._noInterpollation = noInterpollation; + temp._boundry = boundry; + temp._name = name; + temp._url = url; + temp.getFile(); + return temp; +}; + +Constellations.drawConstellationNames = function (renderContext, opacity, drawColor) { + if (Constellations._namesBatch == null) { + Constellations.initializeConstellationNames(); + if (Constellations._namesBatch == null) { + return; + } + } + Constellations._namesBatch.draw(renderContext, opacity, drawColor); +}; + +Constellations.initializeConstellationNames = function () { + if (Constellations.constellationCentroids == null) { + return; + } + Constellations._namesBatch = new Text3dBatch(Settings.get_active().get_constellationLabelsHeight()); + var $enum1 = ss.enumerate(ss.keys(Constellations.constellationCentroids)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var centroid = Constellations.constellationCentroids[key]; + var center = Coordinates.raDecTo3dAu(centroid.get_RA(), centroid.get_dec(), 1); + var up = Vector3d.create(0, 1, 0); + var name = centroid.get_name(); + if (centroid.get_name() === 'Triangulum Australe') { + name = ss.replaceString(name, ' ', '\n '); + } + Constellations._namesBatch.add(new Text3d(center, up, name, Settings.get_active().get_constellationLabelsHeight(), 0.000125)); + } +}; + +// The WWTControl driver will not (and should not) call this function in +// "freestanding mode", because the functionality depends on a +// worldwidetelescope.org API. +Constellations.drawArtwork = function (renderContext) { + if (Constellations.artwork == null) { + if (Constellations._artFile == null) { + Constellations._artFile = makeNewFolder(); + Constellations._artFile.loadFromUrl(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?W=hevelius'), Constellations._onArtReady); + } + return; + } + Constellations._maxSeperation = Math.max(0.5, Math.cos((renderContext.get_fovAngle() * 2) / 180 * Math.PI)); + var $enum1 = ss.enumerate(Constellations.artwork); + while ($enum1.moveNext()) { + var place = $enum1.current; + var bs = Constellations.pictureBlendStates[place.get_constellation()]; + bs.set_targetState(Settings.get_active().get_constellationArtFilter().isSet(place.get_constellation())); + if (bs.get_state()) { + var reverse = false; + var centroid = Constellations.constellationCentroids[place.get_constellation()]; + if (centroid != null) { + var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); + if (Vector3d.dot(renderContext.get_viewPoint(), pos) > Constellations._maxSeperation) { + renderContext.drawImageSet(place.get_studyImageset(), 100); + } + } + } + } +}; + +Constellations._onArtReady = function () { + Constellations._artFile.childLoadCallback(Constellations._loadArtList); +}; + +Constellations._loadArtList = function () { + Constellations.artwork = Constellations._artFile.get_places(); +}; + +// Repeated invocations of this function are OK. +Constellations.initializeConstellations = function () { + if (Constellations.containment == null) { + var url = URLHelpers.singleton.engineAssetUrl('ConstellationNamePositions_EN.txt'); + Constellations._webFileConstNames = new WebFile(url); + Constellations._webFileConstNames.onStateChange = Constellations._loadNames; + Constellations._webFileConstNames.send(); + Constellations.containment = Constellations.create( + 'Constellations', + URLHelpers.singleton.engineAssetUrl('constellations.txt'), + true, // "boundry" + true, // "noInterpollation" + true, // "resource" + ); + } +}; + +Constellations._loadNames = function () { + if (Constellations._webFileConstNames.get_state() === 2) { + alert(Constellations._webFileConstNames.get_message()); + } + else if (Constellations._webFileConstNames.get_state() === 1) { + Constellations._centroidsReady(Constellations._webFileConstNames.getText()); + } +}; + +Constellations._centroidsReady = function (file) { + Constellations.constellationCentroids = {}; + Constellations.fullNames = {}; + Constellations.abbreviations = {}; + var rows = file.split('\r\n'); + var id = 0; + var line; + var $enum1 = ss.enumerate(rows); + + while ($enum1.moveNext()) { + var row = $enum1.current; + line = row; + var data = line.split(','); + Constellations.fullNames[data[1]] = data[0]; + Constellations.abbreviations[data[0]] = data[1]; + ConstellationFilter.bitIDs[data[1]] = id++; + Constellations.pictureBlendStates[data[1]] = BlendState.create(true, 1000); + Constellations.constellationCentroids[data[1]] = createPlace(data[0], parseFloat(data[3]), parseFloat(data[2]), 128, data[1], 2, 360); + } + + ConstellationFilter.buildConstellationFilters(); +}; + +Constellations.fullName = function (name) { + if (ss.keyExists(Constellations.fullNames, name)) { + return Constellations.fullNames[name]; + } + return name; +}; + +Constellations.abbreviation = function (name) { + if (Constellations.abbreviations != null && !ss.emptyString(name) && ss.keyExists(Constellations.abbreviations, name)) { + return Constellations.abbreviations[name]; + } + return name; +}; + +var Constellations$ = { + get_name: function () { + return this._name; + }, + + set_name: function (value) { + this._name = value; + return value; + }, + + getFile: function () { + this._webFile = new WebFile(this._url); + this._webFile.onStateChange = ss.bind('fileStateChange', this); + this._webFile.send(); + }, + + fileStateChange: function () { + if (this._webFile.get_state() === 2) { + alert(this._webFile.get_message()); + } else if (this._webFile.get_state() === 1) { + this._loadConstellationData(this._webFile.getText()); + } + }, + + _loadConstellationData: function (data) { + if (this._boundry && !this._noInterpollation) { + Constellations.boundries = {}; + } + this.lines = []; + var lineSet = null; + try { + var rows = data.split('\r\n'); + var abrv; + var abrvOld = ''; + var ra; + var dec; + var lastRa = 0; + var type = 0; + var $enum1 = ss.enumerate(rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + var line = row; + if (line.substr(11, 2) === '- ') { + line = line.substr(0, 11) + ' -' + line.substr(13, (line.length - 13)); + } + if (line.substr(11, 2) === '+ ') { + line = line.substr(0, 11) + ' +' + line.substr(13, (line.length - 13)); + } + dec = parseFloat(line.substr(11, 10)); + if (this._noInterpollation) { + ra = parseFloat(line.substr(0, 10)); + } + else { + ra = parseFloat(line.substr(0, 10)); + } + abrv = ss.trim(line.substr(23, 4)); + if (!this._boundry) { + if (!!ss.trim(line.substr(28, 1))) { + type = parseInt(line.substr(28, 1)); + } + } + else { + if (this._noInterpollation && line.substr(28, 1) !== 'O') { + continue; + } + } + if (abrv !== abrvOld) { + type = 3; + lineSet = new Lineset(abrv); + this.lines.push(lineSet); + if (this._boundry && !this._noInterpollation) { + Constellations.boundries[abrv] = lineSet; + } + abrvOld = abrv; + lastRa = 0; + } + if (this._noInterpollation) { + if (Math.abs(ra - lastRa) > 12) { + ra = ra - (24 * (((ra - lastRa) < 0) ? -1 : 1)); + } + lastRa = ra; + } + var starName = null; + if (line.length > 30) { + starName = ss.trim(line.substr(30)); + } + if (starName == null || starName !== 'Empty') { + lineSet.add(ra, dec, type, starName); + } + this._pointCount++; + type = 1; + } + } + catch ($e2) { + } + }, + + draw: function (renderContext, showOnlySelected, focusConsteallation, clearExisting) { + Constellations._maxSeperation = Math.max(0.6, Math.cos((renderContext.get_fovAngle() * 2) / 180 * Math.PI)); + this._drawCount = 0; + var lsSelected = null; + if (this.lines == null || Constellations.constellationCentroids == null) { + return; + } + Constellations._constToDraw = focusConsteallation; + var $enum1 = ss.enumerate(this.lines); + while ($enum1.moveNext()) { + var ls = $enum1.current; + if (Constellations._constToDraw === ls.get_name() && this._boundry) { + lsSelected = ls; + } + else if (!showOnlySelected || !this._boundry) { + this._drawSingleConstellation(renderContext, ls, 1); + } + } + if (lsSelected != null) { + this._drawSingleConstellation(renderContext, lsSelected, 1); + } + }, + + _drawSingleConstellation: function (renderContext, ls, opacity) { + var reverse = false; + var centroid = Constellations.constellationCentroids[ls.get_name()]; + if (centroid != null) { + var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); + if (Vector3d.dot(renderContext.get_viewPoint(), pos) < Constellations._maxSeperation) { + return; + } + } + if (!ss.keyExists(this._constellationVertexBuffers, ls.get_name())) { + var count = ls.points.length; + var linelist = new SimpleLineList(); + linelist.set_depthBuffered(false); + this._constellationVertexBuffers[ls.get_name()] = linelist; + var currentPoint = new Vector3d(); + var temp; + for (var i = 0; i < count; i++) { + if (!ls.points[i].pointType || !i) { + currentPoint = Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec); + } + else { + temp = Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec); + linelist.addLine(currentPoint, temp); + currentPoint = temp; + } + } + if (this._boundry) { + temp = Coordinates.raDecTo3d(ls.points[0].RA, ls.points[0].dec); + linelist.addLine(currentPoint, temp); + } + } + var col = 'red'; + if (this._boundry) { + if (Constellations._constToDraw !== ls.get_name()) { + col = Settings.get_globalSettings().get_constellationBoundryColor(); + } + else { + col = Settings.get_globalSettings().get_constellationSelectionColor(); + } + } else { + col = Settings.get_globalSettings().get_constellationFigureColor(); + } + this._constellationVertexBuffers[ls.get_name()].drawLines(renderContext, opacity, Color.load(col)); + }, + + _drawSingleConstellationOld: function (renderContext, ls) { + var reverse = false; + var centroid = Constellations.constellationCentroids[ls.get_name()]; + if (centroid != null) { + var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); + if (Vector3d.dot(renderContext.get_viewPoint(), pos) < Constellations._maxSeperation) { + return; + } + } + this._drawCount++; + var col; + if (this._boundry) { + if (Constellations._constToDraw !== ls.get_name()) { + col = Settings.get_globalSettings().get_constellationBoundryColor(); + } + else { + col = Settings.get_globalSettings().get_constellationSelectionColor(); + } + } else { + col = Settings.get_globalSettings().get_constellationFigureColor(); + } + if (renderContext.gl == null) { + var ctx = renderContext.device; + var count = ls.points.length; + var lastPoint = new Vector3d(); + ctx.save(); + var linePending = false; + ctx.beginPath(); + ctx.strokeStyle = col; + ctx.lineWidth = 2; + ctx.globalAlpha = 0.25; + for (var i = 0; i < count; i++) { + if (!ls.points[i].pointType || !i) { + if (linePending) { + ctx.stroke(); + } + lastPoint = renderContext.WVP.transform(Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec)); + ctx.moveTo(lastPoint.x, lastPoint.y); + } + else { + var newPoint = renderContext.WVP.transform(Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec)); + ctx.lineTo(newPoint.x, newPoint.y); + linePending = true; + } + } + if (this._boundry) { + ctx.closePath(); + } + ctx.stroke(); + ctx.restore(); + } else { + //todo add webgl method of drawing + } + }, + + findConstellationForPoint: function (ra, dec) { + if (dec > 88.402 || this.lines == null) { + return 'UMI'; + } + var $enum1 = ss.enumerate(this.lines); + while ($enum1.moveNext()) { + var ls = $enum1.current; + var count = ls.points.length; + var i; + var j; + var inside = false; + for (i = 0, j = count - 1; i < count; j = i++) { + if ((((ls.points[i].dec <= dec) && (dec < ls.points[j].dec)) || ((ls.points[j].dec <= dec) && (dec < ls.points[i].dec))) && (ra < (ls.points[j].RA - ls.points[i].RA) * (dec - ls.points[i].dec) / (ls.points[j].dec - ls.points[i].dec) + ls.points[i].RA)) { + inside = !inside; + } + } + if (inside) { + return ls.get_name(); + } + } + if (ra > 0) { + return this.findConstellationForPoint(ra - 24, dec); + } + // Ursa Minor is tricky since it wraps around the poles. It can evade the point in rect test + if (dec > 65.5) { + return 'UMI'; + } + if (dec < -65.5) { + return 'OCT'; + } + return 'Error'; + } +}; + +registerType("Constellations", [Constellations, Constellations$, null]); diff --git a/engine/esm/coordinates.js b/engine/esm/coordinates.js new file mode 100644 index 00000000..5293acf5 --- /dev/null +++ b/engine/esm/coordinates.js @@ -0,0 +1,582 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Routines for coordinate transformations +// +// NB: these functions are redundant in the webclient because we don't have the +// single-precision `Vector3` type that's distinguished from `Vector3d`. To +// minimize the code delta from Windows, we keep both names for simplicity. But +// the `...Rad` functions are added because ScriptSharp can't deal with +// overloads. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Util } from "./baseutil.js"; +import { Vector2d, Vector3d } from "./double3d.js"; + + +// wwtlib.Coordinates + +export function Coordinates(ascention, declination) { + // Held in radians + this._ascention = 0; + this._declination = 0; + this._ascention = ascention + (Math.PI * 80) % (Math.PI * 2); + this._declination = declination; +} + +Coordinates.RC = (3.1415927 / 180); +Coordinates.RCRA = (3.1415927 / 12); +Coordinates.radius = 1; +Coordinates._rotationMatrix = null; + +Coordinates.geoTo3d = function (lat, lng) { + return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1, Math.sin(lat * Coordinates.RC) * 1, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1); +}; + +Coordinates.geoTo3dDouble = function (lat, lng) { + return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1, Math.sin(lat * Coordinates.RC) * 1, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1); +}; + +Coordinates.geoTo3dRad = function (lat, lng, radius) { + return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * radius, Math.sin(lat * Coordinates.RC) * radius, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * radius); +}; + +Coordinates.raDecTo3d = function (ra, dec) { + return Vector3d.create(Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1, Math.sin(dec * Coordinates.RC) * 1, Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1); +}; + +Coordinates.raDecTo3dAu = function (ra, dec, au) { + return Vector3d.create(Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * au, Math.sin(dec * Coordinates.RC) * au, Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * au); +}; + +Coordinates.raDecTo3dMat = function (ra, dec, mat) { + return Vector3d._transformCoordinate(Vector3d.create((Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1), (Math.sin(dec * Coordinates.RC) * 1), (Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1)), mat); +}; + +Coordinates.raDecTo3dPointRad = function (point, radius) { + point.set_dec(-point.get_dec()); + return Vector3d.create((Math.cos(point.get_RA() * Coordinates.RCRA) * Math.cos(point.get_dec() * Coordinates.RC) * radius), (Math.sin(point.get_dec() * Coordinates.RC) * radius), (Math.sin(point.get_RA() * Coordinates.RCRA) * Math.cos(point.get_dec() * Coordinates.RC) * radius)); +}; + +Coordinates.sterographicTo3d = function (x, y, radius, standardLat, meridean, falseEasting, falseNorthing, scale, north) { + var lat = 90; + var lng = 0; + x -= falseEasting; + y -= falseNorthing; + if (!!x || !!y) { + var re = (1 + Math.sin(Math.abs(standardLat) / 180 * Math.PI)) * 6371000 / scale; + var rere = re * re; + var c1 = 180 / Math.PI; + if (!x) { + lng = (90 * y < 0) ? -1 : 1; + } else { + lng = Math.atan2(y, x) * c1; + } + var len = (x * x) + (y * y); + lat = (rere - len) / (rere + len); + lat = Math.asin(lat) * c1; + if (!north) { + lat = -lat; + lng = -lng; + meridean = -meridean; + } + } + return Coordinates.geoTo3dRad(lat, 90 + lng + meridean, radius); +}; + +Coordinates.equitorialToHorizon = function (equitorial, location, utc) { + var hourAngle = Coordinates.mstFromUTC2(utc, location.get_lng()) - (equitorial.get_RA() * 15); + if (hourAngle < 0) { + hourAngle += 360; + } + var ha = hourAngle * Coordinates.RC; + var dec = equitorial.get_dec() * Coordinates.RC; + var lat = location.get_lat() * Coordinates.RC; + var sinAlt = Math.sin(dec) * Math.sin(lat) + Math.cos(dec) * Math.cos(lat) * Math.cos(ha); + var altitude = Math.asin(sinAlt); + var cosAzimith = (Math.sin(dec) - Math.sin(altitude) * Math.sin(lat)) / (Math.cos(altitude) * Math.cos(lat)); + var azimuth = Math.acos(cosAzimith); + var altAz = new Coordinates(azimuth, altitude); + if (Math.sin(ha) > 0) { + altAz.set_az((360 - altAz.get_az())); + } + return altAz; +}; + +Coordinates.horizonToEquitorial = function (altAz, location, utc) { + var hourAngle = Coordinates.mstFromUTC2(utc, location.get_lng()); + var haLocal; + var declination; + var raDec = Coordinates._altAzToRaDec(altAz.get_alt() * Coordinates.RC, altAz.get_az() * Coordinates.RC, location.get_lat() * Coordinates.RC); + haLocal = raDec.x; + declination = raDec.y; + var ha = (haLocal / Coordinates.RC); + hourAngle += ha; + if (hourAngle < 0) { + hourAngle += 360; + } + if (hourAngle > 360) { + hourAngle -= 360; + } + return Coordinates.fromRaDec(hourAngle / 15, declination / Coordinates.RC); +}; + +Coordinates._altAzToRaDec = function (Altitude, Azimuth, Latitude) { + var hrAngle = 0; + var dec = 0; + Azimuth = Math.PI - Azimuth; + if (Azimuth < 0) { + Azimuth += Math.PI * 2; + } + hrAngle = Math.atan2(Math.sin(Azimuth), Math.cos(Azimuth) * Math.sin(Latitude) + Math.tan(Altitude) * Math.cos(Latitude)); + if (hrAngle < 0) { + hrAngle += Math.PI * 2; + } + dec = Math.asin(Math.sin(Latitude) * Math.sin(Altitude) - Math.cos(Latitude) * Math.cos(Altitude) * Math.cos(Azimuth)); + return Vector2d.create(hrAngle, dec); +}; + +Coordinates.mstFromUTC2 = function (utc, lng) { + var year = utc.getUTCFullYear(); + var month = utc.getUTCMonth() + 1; + var day = utc.getUTCDate(); + var hour = utc.getUTCHours(); + var minute = utc.getUTCMinutes(); + var second = utc.getUTCSeconds() + utc.getUTCMilliseconds() / 1000; + if (month === 1 || month === 2) { + year -= 1; + month += 12; + } + var a = ss.truncate((year / 100)); + var b = 2 - a + Math.floor((a / 4)); + var c = Math.floor(365.25 * year); + var d = Math.floor(30.6001 * (month + 1)); + var julianDays; + var julianCenturies; + var mst; + julianDays = b + c + d - 730550.5 + day + (hour + minute / 60 + second / 3600) / 24; + julianCenturies = julianDays / 36525; + mst = 280.46061837 + 360.98564736629 * julianDays + 0.000387933 * julianCenturies * julianCenturies - julianCenturies * julianCenturies * julianCenturies / 38710000 + lng; + if (mst > 0) { + while (mst > 360) { + mst = mst - 360; + } + } + else { + while (mst < 0) { + mst = mst + 360; + } + } + return mst; +}; + +Coordinates.cartesianToSpherical = function (vector) { + var ascention; + var declination; + var radius = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var XZ = Math.sqrt(vector.x * vector.x + vector.z * vector.z); + declination = Math.asin(vector.y / radius); + if (0 < vector.x) { + ascention = Math.asin(vector.z / XZ); + } + else if (0 > vector.x) { + ascention = Math.PI - Math.asin(vector.z / XZ); + } + else { + ascention = 0; + } + return new Coordinates(ascention, declination); +}; + +Coordinates.cartesianToSpherical2 = function (vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var longitude = Math.atan2(vector.z, vector.x); + var latitude = Math.asin(vector.y / rho); + return new Coordinates(longitude, latitude); +}; + +Coordinates.cartesianToSphericalSky = function (vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var ra = Math.atan2(vector.z, vector.x); + var dec = Math.asin(-vector.y / rho); + return Vector2d.create(ra / Math.PI * 12, dec / Math.PI * 180); +}; + +Coordinates.sphericalSkyToCartesian = function (vector) { + var ra = vector.x * (Math.PI / 12); + var dec = vector.y * (Math.PI / 180); + var x = Math.cos(ra) * Math.cos(dec); + var y = -Math.sin(dec); + var z = Math.sin(ra) * Math.cos(dec); + return Vector3d.create(x, y, z); +}; + +Coordinates.cartesianToLatLng = function (vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var longitude = Math.atan2(vector.z, vector.x); + var latitude = Math.asin(vector.y / rho); + return Vector2d.create(longitude * 180 / Math.PI, latitude * 180 / Math.PI); +}; + +Coordinates.cartesianToSpherical3 = function (vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var longitude = Math.atan2(vector.z, vector.x); + var latitude = Math.asin(vector.y / rho); + return new Coordinates(longitude, latitude); +}; + +Coordinates.sign = function (target) { + return (target < 0) ? -1 : 1; +}; + +Coordinates.formatDMSSign = function (angle, sign) { + try { + angle += (Coordinates.sign(angle) * 0.0001388888888889); + var degrees = ss.truncate(angle); + var minutes = ((angle - ss.truncate(angle)) * 60); + var seconds = ((minutes - ss.truncate(minutes)) * 60); + if (sign) { + var signString = (angle > 0) ? '+' : '-'; + return ss.format('{3}{0:00;00}:{1:00}:{2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds)), signString); + } else { + return ss.format('{0:00}:{1:00}:{2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds))); + } + } + catch ($e1) { + return ''; + } +}; + +Coordinates.twoPlaces = function (val) { + var num = val.toString(); + if (num.length < 2) { + num = '0' + num; + } + return num; +}; + +Coordinates.formatDMS = function (angle) { + try { + angle += (((angle < 0) ? -1 : 1) * 0.0001388888888889); + var degrees = Math.abs(ss.truncate(angle)); + var minutes = ((angle - ss.truncate(angle)) * 60); + var seconds = ((minutes - ss.truncate(minutes)) * 60); + var sign = (angle < 0) ? '-' : ''; + return ss.format('{3}{0}:{1}:{2}', Math.abs(degrees), Coordinates.twoPlaces(Math.abs(ss.truncate(minutes))), Coordinates.twoPlaces(Math.abs(ss.truncate(seconds))), sign); + } + catch ($e1) { + return ''; + } +}; + +Coordinates.formatDMSWide = function (angle) { + try { + angle += (Coordinates.sign(angle) * 0.0001388888888889); + var degrees = Math.abs(ss.truncate(angle)); + var minutes = ((angle - ss.truncate(angle)) * 60); + var seconds = ((minutes - ss.truncate(minutes)) * 60); + var sign = (angle < 0) ? '-' : ''; + return ss.format('{3}{0:00} : {1:00} : {2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds)), sign); + } + catch ($e1) { + return ''; + } +}; + +Coordinates.formatHMS = function (angle) { + try { + angle += (Coordinates.sign(angle) * 0.0001388888888889); + var degrees = ss.truncate(angle); + var minutes = ((angle - ss.truncate(angle)) * 60); + var seconds = ((minutes - ss.truncate(minutes)) * 60); + return ss.format('{0:00}h{1:00}m{2:00}s', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds))); + } + catch ($e1) { + return ''; + } +}; + +Coordinates.parseRA = function (data, degrees) { + data = ss.trim(data).toLowerCase(); + if (data.indexOf('d') > -1 || data.indexOf('\u00b0') > -1) { + degrees = true; + } + if (data.indexOf('h') > -1 || data.indexOf(':') > -1) { + degrees = false; + } + var ra = Coordinates.parse(data) / ((degrees) ? 15 : 1); + return Math.max(Math.min(ra, 24), 0); +}; + +Coordinates.parseDec = function (data) { + var dec = Coordinates.parse(data); + return Math.max(Math.min(dec, 90), -90); +}; + +Coordinates.parse = function (data) { + try { + data = ss.trim(data).toLowerCase(); + data = ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(data, 'd ', 'd'), 'h ', 'h'), 'm ', 'm'), 's ', 's'), "' ", "'"), '" ', '"'); + if (Util.stringContains(data, [':', ' ', 'd', 'h', 'm', 's', "'", '"', '\u00b0'])) { + var hours = 0; + var minutes = 0; + var seconds = 0; + var sign = 0; + var parts = Util.splitString(data, [':', ' ', 'd', 'h', 'm', 's', "'", '"', '\u00b0']); + if (parts.length > 0) { + if (!ss.emptyString(parts[0])) { + hours = Math.abs(parseFloat(parts[0])); + sign = (parseFloat(parts[0]) < 0) ? -1 : 1; + if (parts[0].indexOf('-') > -1) { + sign = -1; + } + } + } + if (parts.length > 1) { + if (!ss.emptyString(parts[1])) { + minutes = parseFloat(parts[1]); + } + } + if (parts.length > 2) { + if (!ss.emptyString(parts[2])) { + seconds = parseFloat(parts[2]); + } + } + if (!sign) { + sign = 1; + } + return sign * (hours + minutes / 60 + seconds / 3600); + } else { + var val = 0; + try { + val = parseFloat(data); + } + catch ($e1) { + val = 0; + } + return val; + } + } + catch ($e2) { + return 0; + } +}; + +Coordinates.fromRaDec = function (ra, dec) { + return new Coordinates((ra - 12) * 15 * Coordinates.RC, dec * Coordinates.RC); +}; + +Coordinates.fromLatLng = function (lat, lng) { + return new Coordinates(lng * Coordinates.RC, lat * Coordinates.RC); +}; + +Coordinates.dmsToDegrees = function (Degrees, Minutes, Seconds) { + return Degrees + Minutes / 60 + Seconds / 3600; +}; + +Coordinates.degreesToRadians = function (Degrees) { + return Degrees * 0.0174532925199433; +}; + +Coordinates.radiansToDegrees = function (Radians) { + return Radians * 57.2957795130823; +}; + +Coordinates.radiansToHours = function (Radians) { + return Radians * 3.81971863420549; +}; + +Coordinates.hoursToRadians = function (Hours) { + return Hours * 0.261799387799149; +}; + +Coordinates.hoursToDegrees = function (Hours) { + return Hours * 15; +}; + +Coordinates.degreesToHours = function (Degrees) { + return Degrees / 15; +}; + +Coordinates.PI = function () { + return 3.14159265358979; +}; + +Coordinates.mapTo0To360Range = function (Degrees) { + var Value = Degrees; + while (Value < 0) { + Value += 360; + } + while (Value > 360) { + Value -= 360; + } + return Value; +}; + +Coordinates.mapTo0To24Range = function (HourAngle) { + var Value = HourAngle; + while (Value < 0) { + Value += 24; + } + while (Value > 24) { + Value -= 24; + } + return Value; +}; + +Coordinates.meanObliquityOfEcliptic = function (JD) { + var U = (JD - 2451545) / 3652500; + var Usquared = U * U; + var Ucubed = Usquared * U; + var U4 = Ucubed * U; + var U5 = U4 * U; + var U6 = U5 * U; + var U7 = U6 * U; + var U8 = U7 * U; + var U9 = U8 * U; + var U10 = U9 * U; + return Coordinates.dmsToDegrees(23, 26, 21.448) - Coordinates.dmsToDegrees(0, 0, 4680.93) * U - Coordinates.dmsToDegrees(0, 0, 1.55) * Usquared + Coordinates.dmsToDegrees(0, 0, 1999.25) * Ucubed - Coordinates.dmsToDegrees(0, 0, 51.38) * U4 - Coordinates.dmsToDegrees(0, 0, 249.67) * U5 - Coordinates.dmsToDegrees(0, 0, 39.05) * U6 + Coordinates.dmsToDegrees(0, 0, 7.12) * U7 + Coordinates.dmsToDegrees(0, 0, 27.87) * U8 + Coordinates.dmsToDegrees(0, 0, 5.79) * U9 + Coordinates.dmsToDegrees(0, 0, 2.45) * U10; +}; + +Coordinates.j2000toGalactic = function (J2000RA, J2000DEC) { + var J2000pos = [Math.cos(J2000RA / 180 * Math.PI) * Math.cos(J2000DEC / 180 * Math.PI), Math.sin(J2000RA / 180 * Math.PI) * Math.cos(J2000DEC / 180 * Math.PI), Math.sin(J2000DEC / 180 * Math.PI)]; + if (Coordinates._rotationMatrix == null) { + Coordinates._rotationMatrix = new Array(3); + Coordinates._rotationMatrix[0] = [-0.0548755604, -0.8734370902, -0.4838350155]; + Coordinates._rotationMatrix[1] = [0.4941094279, -0.44482963, 0.7469822445]; + Coordinates._rotationMatrix[2] = [-0.867666149, -0.1980763734, 0.4559837762]; + } + var Galacticpos = new Array(3); + for (var i = 0; i < 3; i++) { + Galacticpos[i] = J2000pos[0] * Coordinates._rotationMatrix[i][0] + J2000pos[1] * Coordinates._rotationMatrix[i][1] + J2000pos[2] * Coordinates._rotationMatrix[i][2]; + } + var GalacticL2 = Math.atan2(Galacticpos[1], Galacticpos[0]); + if (GalacticL2 < 0) { + GalacticL2 = GalacticL2 + 2 * Math.PI; + } + if (GalacticL2 > 2 * Math.PI) { + GalacticL2 = GalacticL2 - 2 * Math.PI; + } + var GalacticB2 = Math.atan2(Galacticpos[2], Math.sqrt(Galacticpos[0] * Galacticpos[0] + Galacticpos[1] * Galacticpos[1])); + return [GalacticL2 / Math.PI * 180, GalacticB2 / Math.PI * 180]; +}; + +Coordinates.galacticTo3dDouble = function (l, b) { + var result = Coordinates.galactictoJ2000(l, b); + return Coordinates.raDecTo3dAu(result[0] / 15, result[1], 1); +}; + +Coordinates.galactictoJ2000 = function (GalacticL2, GalacticB2) { + var Galacticpos = [Math.cos(GalacticL2 / 180 * Math.PI) * Math.cos(GalacticB2 / 180 * Math.PI), Math.sin(GalacticL2 / 180 * Math.PI) * Math.cos(GalacticB2 / 180 * Math.PI), Math.sin(GalacticB2 / 180 * Math.PI)]; + if (Coordinates._rotationMatrix == null) { + Coordinates._rotationMatrix = new Array(3); + Coordinates._rotationMatrix[0] = [-0.0548755604, -0.8734370902, -0.4838350155]; + Coordinates._rotationMatrix[1] = [0.4941094279, -0.44482963, 0.7469822445]; + Coordinates._rotationMatrix[2] = [-0.867666149, -0.1980763734, 0.4559837762]; + } + var J2000pos = new Array(3); + for (var i = 0; i < 3; i++) { + J2000pos[i] = Galacticpos[0] * Coordinates._rotationMatrix[0][i] + Galacticpos[1] * Coordinates._rotationMatrix[1][i] + Galacticpos[2] * Coordinates._rotationMatrix[2][i]; + } + var J2000RA = Math.atan2(J2000pos[1], J2000pos[0]); + if (J2000RA < 0) { + J2000RA = J2000RA + 2 * Math.PI; + } + if (J2000RA > 2 * Math.PI) { + J2000RA = J2000RA - 2 * Math.PI; + } + var J2000DEC = Math.atan2(J2000pos[2], Math.sqrt(J2000pos[0] * J2000pos[0] + J2000pos[1] * J2000pos[1])); + return [J2000RA / Math.PI * 180, J2000DEC / Math.PI * 180]; +}; + +var Coordinates$ = { + distance: function (pointB) { + var y = this.get_lat(); + var x = this.get_lng() * Math.cos(y * Coordinates.RC); + var y1 = pointB.get_lat(); + var x1 = pointB.get_lng() * Math.cos(y1 * Coordinates.RC); + return Math.sqrt((y - y1) * (y - y1) + (x - x1) * (x - x1)); + }, + + distance3d: function (pointB) { + var pnt1 = Coordinates.geoTo3dDouble(pointB.get_lat(), pointB.get_lng()); + var pnt2 = Coordinates.geoTo3dDouble(this.get_lat(), this.get_lng()); + var pntDiff = Vector3d.subtractVectors(pnt1, pnt2); + return pntDiff.length() / Coordinates.RC; + }, + + angle: function (pointB) { + var y = this.get_lat(); + var x = this.get_lng() * Math.cos(y * Coordinates.RC); + var y1 = pointB.get_lat(); + var x1 = pointB.get_lng() * Math.cos(y1 * Coordinates.RC); + return Math.atan2((y1 - y), (x1 - x)); + }, + + get_RA: function () { + return (((this._ascention / Math.PI) * 12) + 12) % 24; + }, + + set_RA: function (value) { + this._ascention = (value / 12) * Math.PI; + return value; + }, + + get_dec: function () { + return this._declination / Coordinates.RC; + }, + + set_dec: function (value) { + this._declination = value * Coordinates.RC; + return value; + }, + + get_lat: function () { + return this._declination / Coordinates.RC; + }, + + set_lat: function (value) { + this._declination = value * Coordinates.RC; + return value; + }, + + get_lng: function () { + var lng = this._ascention / Coordinates.RC; + if (lng <= 180) { + return lng; + } else { + return (-180 + (180 - lng)); + } + }, + + set_lng: function (value) { + //todo This was broken check callers to see what effect it had. + this._ascention = ((value * Coordinates.RC) + (Math.PI * 2) % (Math.PI * 2)); + return value; + }, + + get_alt: function () { + return this._declination / Coordinates.RC; + }, + + set_alt: function (value) { + this._declination = value * Coordinates.RC; + return value; + }, + + get_az: function () { + return this._ascention / Coordinates.RC; + }, + + set_az: function (value) { + this._ascention = value * Coordinates.RC; + return value; + }, + + toString: function () { + return ss.format('Lat: {0}, Lng: {1}', this.get_lat(), this.get_lng()); + } +}; + +registerType("Coordinates", [Coordinates, Coordinates$, null]); diff --git a/engine/esm/data_globals.js b/engine/esm/data_globals.js new file mode 100644 index 00000000..8e629d07 --- /dev/null +++ b/engine/esm/data_globals.js @@ -0,0 +1,91 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Various global variables associated with data assets. +// +// See `render_globals.js` for a general rationale for this kind of module. + +// This used to be WWTControl(.singleton).freestandingMode. It sets whether the +// engine will avoid accessing the central WWT servers. +export var freestandingMode = false; + +export function set_freestandingMode(value) { + freestandingMode = !!value; +} + +// This is equivalent to `new HipsProperties(imageset)`. We abstract +// the function to avoid circular dependencies in the type hierarchy. +export var makeNewHipsProperties = null; + +export function set_makeNewHipsProperties(value) { + makeNewHipsProperties = value; +} + +// This is equivalent to `new Folder()`. We abstract +// the function to avoid circular dependencies in the type hierarchy. +export var makeNewFolder = null; + +export function set_makeNewFolder(value) { + makeNewFolder = value; +} + +// This is equivalent to `Place.create(name, lat, lng, classification, +// constellation, type, zoomFactor)`. We abstract the function to avoid circular +// dependencies in the type hierarchy. +export var createPlace = null; + +export function set_createPlace(value) { + createPlace = value; +} + +// This is another way to access `WWTControl.singleton`. It's the +// global singleton WWTControl instance. +export var globalWWTControl = null; + +export function set_globalWWTControl(value) { + globalWWTControl = value; +} + +// This is another way to access the `WWTControl.scriptInterface` singleton. It's +// the global singleton ScriptInterface instance. +export var globalScriptInterface = null; + +export function set_globalScriptInterface(value) { + globalScriptInterface = value; +} + +// This is another way to access `LayerManager.setVisibleLayerList()`. Once +// again, we need this to break some circular dependencies in the module +// structure. +export var setManagerVisibleLayerList = null; + +export function set_setManagerVisibleLayerList(value) { + setManagerVisibleLayerList = value; +} + +// This is another way to access `TourDocument.fromUrlRaw()`. Once again, we +// need this to break some circular dependencies in the module structure. + +export var tourDocumentFromUrlRaw = null; + +export function set_tourDocumentFromUrlRaw(value) { + tourDocumentFromUrlRaw = value; +} + +// This is another way to access `LayerManager.getAllMaps()`. Once again, we +// need this to break some circular dependencies in the module structure. + +export var layerManagerGetAllMaps = null; + +export function set_layerManagerGetAllMaps(value) { + layerManagerGetAllMaps = value; +} + +// This is another way to access `Wtml.getWtmlFile()`. Once again, we +// need this to break some circular dependencies in the module structure. + +export var loadWtmlFile = null; + +export function set_loadWtmlFile(value) { + loadWtmlFile = value; +} diff --git a/engine/esm/double3d.js b/engine/esm/double3d.js new file mode 100644 index 00000000..be1516f2 --- /dev/null +++ b/engine/esm/double3d.js @@ -0,0 +1,2326 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Basic vector datatypes and the like. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { Color } from "./color.js"; +import { tileUvMultiple } from "./render_globals.js"; + + +// Break some circular dependencies +// +// `Vector2d.cartesianToSpherical2` is almost the same as +// `Coordinates.cartesianToSpherical2`, but the resulting angles are measured in +// degrees rather than radians, and the Coordinates class applies some +// transformations in various places. Out of an abundance of caution we +// reproduce its calculations rotely. + +const RC = (3.1415927 / 180); // not thrilled about the low precision! + +function geoTo3dDouble(lat, lng) { + return Vector3d.create( + Math.cos(lng * RC) * Math.cos(lat * RC) * 1, + Math.sin(lat * RC) * 1, + Math.sin(lng * RC) * Math.cos(lat * RC) * 1 + ); +} + +function coords_cartesianToSpherical2(vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var longitude = Math.atan2(vector.z, vector.x); + var latitude = Math.asin(vector.y / rho); + + // I don't love this approach but it's what the Coords constructor does + longitude = longitude + (Math.PI * 80) % (Math.PI * 2); + + // Coordinates.get_lng(): + var lng = longitude / RC; + if (lng > 180) { + lng = (-180 + (180 - lng)); + } + + // Coordinates.get_lat(): + var lat = latitude / RC; + + return [lat, lng]; +} + + +// wwtlib.LocationHint +// +// Summary: +// Describes a custom vertex format structure that contains position and one +// set of texture coordinates. + +export var LocationHint = { + slash: 0, + backslash: 1, + top: 2 +}; + +registerType("LocationHint", LocationHint); + + +// wwtlib.PositionTexture + +export function PositionTexture() { + this.tu = 0; + this.tv = 0; + this.position = new Vector3d(); +} + +// Summary: +// Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured +// class. +// +// Parameters: +// pos: +// A Microsoft.DirectX.Vector3d object that contains the vertex position. +// +// u: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +PositionTexture.createPos = function (pos, u, v) { + var temp = new PositionTexture(); + temp.tu = u * tileUvMultiple; + temp.tv = v * tileUvMultiple; + temp.position = pos; + return temp; +}; + +PositionTexture.createPosRaw = function (pos, u, v) { + var temp = new PositionTexture(); + temp.tu = u; + temp.tv = v; + temp.position = pos; + return temp; +}; + +PositionTexture.createPosSize = function (pos, u, v, width, height) { + var temp = new PositionTexture(); + temp.tu = u * width; + temp.tv = v * height; + temp.position = pos; + return temp; +}; + +// Summary: +// Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured +// class. +// +// Parameters: +// xvalue: +// Floating-point value that represents the x coordinate of the position. +// +// yvalue: +// Floating-point value that represents the y coordinate of the position. +// +// zvalue: +// Floating-point value that represents the z coordinate of the position. +// +// u: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +PositionTexture.create = function (xvalue, yvalue, zvalue, u, v) { + var temp = new PositionTexture(); + temp.position = Vector3d.create(xvalue, yvalue, zvalue); + temp.tu = u * tileUvMultiple; + temp.tv = v * tileUvMultiple; + return temp; +}; + +var PositionTexture$ = { + copy: function () { + var temp = new PositionTexture(); + temp.position = Vector3d.makeCopy(this.position); + temp.tu = this.tu; + temp.tv = this.tv; + return temp; + }, + + toString: function () { + return ss.format('{0}, {1}, {2}, {3}, {4}', this.position.x, this.position.y, this.position.z, this.tu, this.tv); + } +}; + +registerType("PositionTexture", [PositionTexture, PositionTexture$, null]); + + +// wwtlib.PositionColoredTextured + +export function PositionColoredTextured() { + this.tu = 0; + this.tv = 0; + this.color = new Color(); + this.position = new Vector3d(); +} + +// Summary: +// Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured +// class. +// +// Parameters: +// pos: +// A Microsoft.DirectX.Vector3d object that contains the vertex position. +// +// u: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +PositionColoredTextured.createPos = function (pos, u, v) { + var temp = new PositionColoredTextured(); + temp.tu = u * tileUvMultiple; + temp.tv = v * tileUvMultiple; + temp.position = pos; + return temp; +}; + +PositionColoredTextured.createPosRaw = function (pos, u, v) { + var temp = new PositionColoredTextured(); + temp.tu = u; + temp.tv = v; + temp.position = pos; + return temp; +}; + +PositionColoredTextured.createPosSize = function (pos, u, v, width, height) { + var temp = new PositionColoredTextured(); + temp.tu = u * width; + temp.tv = v * height; + temp.position = pos; + return temp; +}; + +// ** Is it a mistake that this is creating a PositionTexture, not PositionColoredTextured? ** +// +// Summary: +// Initializes a new instance of the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured +// class. +// +// Parameters: +// xvalue: +// Floating-point value that represents the x coordinate of the position. +// +// yvalue: +// Floating-point value that represents the y coordinate of the position. +// +// zvalue: +// Floating-point value that represents the z coordinate of the position. +// +// u: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured.#ctor() +// component of the texture coordinate. +PositionColoredTextured.create = function (xvalue, yvalue, zvalue, u, v) { + var temp = new PositionTexture(); + temp.position = Vector3d.create(xvalue, yvalue, zvalue); + temp.tu = u * tileUvMultiple; + temp.tv = v * tileUvMultiple; + return temp; +}; + +var PositionColoredTextured$ = { + copy: function () { + var temp = new PositionTexture(); + temp.position = Vector3d.makeCopy(this.position); + temp.tu = this.tu; + temp.tv = this.tv; + return temp; + }, + toString: function () { + return ss.format('{0}, {1}, {2}, {3}, {4}', this.position.x, this.position.y, this.position.z, this.tu, this.tv); + } +}; + +registerType("PositionColoredTextured", [PositionColoredTextured, PositionColoredTextured$, null]); + + +// wwtlib.PositionColored + +export function PositionColored(pos, color) { + this.color = new Color(); + this.color = color._clone(); + this.position = pos.copy(); +} + +var PositionColored$ = { + copy: function () { + var temp = new PositionColored(this.position, this.color); + return temp; + }, + + toString: function () { + return ss.format('{0}, {1}, {2}, {3}', this.position.x, this.position.y, this.position.z, this.color.toString()); + } +}; + +registerType("PositionColored", [PositionColored, PositionColored$, null]); + + +// wwtlib.PositionNormalTexturedTangent +// +// Summary: +// Custom vertex format with position, normal, texture coordinate, and tangent vector. The +// tangent vector is stored in the second texture coordinate. + +export function PositionNormalTexturedTangent(position, normal, texCoord, tangent) { + this.x = 0; + this.y = 0; + this.z = 0; + this.nx = 0; + this.ny = 0; + this.nz = 0; + this.tu = 0; + this.tv = 0; + this.tanx = 0; + this.tany = 0; + this.tanz = 0; + this.x = position.x; + this.y = position.y; + this.z = position.z; + this.nx = normal.x; + this.ny = normal.y; + this.nz = normal.z; + this.tu = texCoord.x; + this.tv = texCoord.y; + this.tanx = tangent.x; + this.tany = tangent.y; + this.tanz = tangent.z; +} + +var PositionNormalTexturedTangent$ = { + get_normal: function () { + return Vector3d.create(this.nx, this.ny, this.nz); + }, + + set_normal: function (value) { + this.nx = value.x; + this.ny = value.y; + this.nz = value.z; + return value; + }, + + get_position: function () { + return Vector3d.create(this.x, this.y, this.z); + }, + + set_position: function (value) { + this.x = value.x; + this.y = value.y; + this.z = value.z; + return value; + }, + + get_texCoord: function () { + return Vector2d.create(this.tu, this.tv); + }, + + set_texCoord: function (value) { + this.tu = value.x; + this.tv = value.y; + return value; + }, + + get_tangent: function () { + return Vector3d.create(this.tanx, this.tany, this.tanz); + }, + + set_tangent: function (value) { + this.tanx = value.x; + this.tany = value.y; + this.tanz = value.z; + return value; + }, + + toString: function () { + return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, TanX={8}, TanY={9}, TanZ={10}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv, this.tanx, this.tany, this.tanz); + } +}; + +registerType("PositionNormalTexturedTangent", [PositionNormalTexturedTangent, PositionNormalTexturedTangent$, null]); + + +// wwtlib.Vector3d + +export function Vector3d() { + this.x = 0; + this.y = 0; + this.z = 0; +} + +Vector3d.create = function (valueX, valueY, valueZ) { + var temp = new Vector3d(); + temp.x = valueX; + temp.y = valueY; + temp.z = valueZ; + return temp; +}; + +Vector3d.makeCopy = function (value) { + var temp = new Vector3d(); + temp.x = value.x; + temp.y = value.y; + temp.z = value.z; + return temp; +}; + +Vector3d.negate = function (vec) { + return Vector3d.create(-vec.x, -vec.y, -vec.z); +}; + +Vector3d.midPoint = function (left, right) { + var result = Vector3d.create((left.x + right.x) / 2, (left.y + right.y) / 2, (left.z + right.z) / 2); + return result; +}; + +Vector3d.midPointByLength = function (left, right) { + var result = Vector3d.create((left.x + right.x) / 2, (left.y + right.y) / 2, (left.z + right.z) / 2); + result.normalize(); + result.multiply(left.length()); + return result; +}; + +Vector3d.get_empty = function () { + return Vector3d.create(0, 0, 0); +}; + +Vector3d.addVectors = function (left, right) { + return Vector3d.create(left.x + right.x, left.y + right.y, left.z + right.z); +}; + +Vector3d.cross = function (left, right) { + return Vector3d.create(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); +}; + +Vector3d.dot = function (left, right) { + return left.x * right.x + left.y * right.y + left.z * right.z; +}; + +Vector3d.getLength = function (source) { + return Math.sqrt(source.x * source.x + source.y * source.y + source.z * source.z); +}; + +Vector3d.getLengthSq = function (source) { + return source.x * source.x + source.y * source.y + source.z * source.z; +}; + +// Summary: +// Performs a linear interpolation between two 3-D vectors. +// +// Parameters: +// left: +// Source Microsoft.DirectX.Vector3d structure. +// +// right: +// Source Microsoft.DirectX.Vector3d structure. +// +// interpolater: +// Parameter that linearly interpolates between the vectors. +// +// Returns: +// A Microsoft.DirectX.Vector3d structure that is the result of the linear interpolation. +Vector3d.lerp = function (left, right, interpolater) { + return Vector3d.create(left.x * (1 - interpolater) + right.x * interpolater, left.y * (1 - interpolater) + right.y * interpolater, left.z * (1 - interpolater) + right.z * interpolater); +}; + +Vector3d.midpoint = function (left, right) { + var tmp = Vector3d.create(left.x * (0.5) + right.x * 0.5, left.y * (0.5) + right.y * 0.5, left.z * (0.5) + right.z * 0.5); + tmp.normalize(); + return tmp; +}; + +Vector3d.slerp = function (left, right, interpolater) { + var dot = Vector3d.dot(left, right); + while (dot < 0.98) { + var middle = Vector3d.midpoint(left, right); + if (interpolater > 0.5) { + left = middle; + interpolater -= 0.5; + interpolater *= 2; + } + else { + right = middle; + interpolater *= 2; + } + dot = Vector3d.dot(left, right); + } + var tmp = Vector3d.lerp(left, right, interpolater); + tmp.normalize(); + return tmp; +}; + +Vector3d.multiplyScalar = function (source, f) { + var result = source.copy(); + result.multiply(f); + return result; +}; + +Vector3d.scale = function (source, scalingFactor) { + var result = source; + result.multiply(scalingFactor); + return result; +}; + +Vector3d.subtractVectors = function (left, right) { + var result = left.copy(); + result.subtract(right); + return result; +}; + +Vector3d.parse = function (data) { + var newVector = new Vector3d(); + var list = data.split(','); + if (list.length === 3) { + newVector.x = parseFloat(list[0]); + newVector.y = parseFloat(list[1]); + newVector.z = parseFloat(list[2]); + } + return newVector; +}; + +Vector3d._transformCoordinate = function (vector3d, mat) { + return mat.transform(vector3d); +}; + +var Vector3d$ = { + set: function (valueX, valueY, valueZ) { + this.x = valueX; + this.y = valueY; + this.z = valueZ; + }, + + copy: function () { + var temp = new Vector3d(); + temp.x = this.x; + temp.y = this.y; + temp.z = this.z; + return temp; + }, + + round: function () { + this.x = ss.truncate((this.x * 65536)) / 65536; + this.y = ss.truncate((this.y * 65536)) / 65536; + this.z = ss.truncate((this.z * 65536)) / 65536; + }, + + add: function (source) { + this.x += source.x; + this.y += source.y; + this.z += source.z; + }, + + length: function () { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + }, + + lengthSq: function () { + return this.x * this.x + this.y * this.y + this.z * this.z; + }, + + multiply: function (s) { + this.x *= s; + this.y *= s; + this.z *= s; + }, + + normalize: function () { + var length = this.length(); + if (!!length) { + this.x /= length; + this.y /= length; + this.z /= length; + } + }, + + rotateX: function (radians) { + var zTemp; + var yTemp; + yTemp = this.y * Math.cos(radians) - this.z * Math.sin(radians); + zTemp = this.y * Math.sin(radians) + this.z * Math.cos(radians); + this.z = zTemp; + this.y = yTemp; + }, + + rotateZ: function (radians) { + var xTemp; + var yTemp; + xTemp = this.x * Math.cos(radians) - this.y * Math.sin(radians); + yTemp = this.x * Math.sin(radians) + this.y * Math.cos(radians); + this.y = yTemp; + this.x = xTemp; + }, + + rotateY: function (radians) { + var zTemp; + var xTemp; + zTemp = this.z * Math.cos(radians) - this.x * Math.sin(radians); + xTemp = this.z * Math.sin(radians) + this.x * Math.cos(radians); + this.x = xTemp; + this.z = zTemp; + }, + + subtract: function (source) { + this.x -= source.x; + this.y -= source.y; + this.z -= source.z; + return this; + }, + + toString: function () { + return ss.format('{0}, {1}, {2}', this.x, this.y, this.z); + }, + + toSpherical: function () { + var ascention; + var declination; + var radius = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + var XZ = Math.sqrt(this.x * this.x + this.z * this.z); + declination = Math.asin(this.y / radius); + if (!XZ) { + ascention = 0; + } + else if (0 <= this.x) { + ascention = Math.asin(this.z / XZ); + } + else { + ascention = Math.PI - Math.asin(this.z / XZ); + } + return Vector2d.create(((ascention + Math.PI) % (2 * Math.PI)), (declination + (Math.PI / 2))); + }, + + toRaDec: function () { + var point = this.toSpherical(); + point.x = point.x / Math.PI * 12; + point.y = (point.y / Math.PI * 180) - 90; + return point; + }, + + distanceToLine: function (x1, x2) { + var t1 = Vector3d.subtractVectors(x2, x1); + var t2 = Vector3d.subtractVectors(x1, this); + var t3 = Vector3d.cross(t1, t2); + var d1 = t3.length(); + var t4 = Vector3d.subtractVectors(x2, x1); + var d2 = t4.length(); + return d1 / d2; + }, + + _transformByMatrics: function (lookAtAdjust) { + var temp = lookAtAdjust.transform(this); + this.x = temp.x; + this.y = temp.y; + this.z = temp.z; + } +}; + +registerType("Vector3d", [Vector3d, Vector3d$, null]); + +Vector3d.zero = new Vector3d(); + + +// wwtlib.Vector2d + +export function Vector2d() { + this.x = 0; + this.y = 0; +} + +Vector2d.lerp = function (left, right, interpolater) { + return Vector2d.create(left.x * (1 - interpolater) + right.x * interpolater, left.y * (1 - interpolater) + right.y * interpolater); +}; + +Vector2d.cartesianToSpherical2 = function (vector) { + var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + var longitude = Math.atan2(vector.z, vector.x); + var latitude = Math.asin(vector.y / rho); + return Vector2d.create(longitude / Math.PI * 180, latitude / Math.PI * 180); +}; + +Vector2d.average3d = function (left, right) { + var pntLeft = geoTo3dDouble(left.y, left.x); + var pntRight = geoTo3dDouble(right.y, right.x); + var pntOut = Vector3d.addVectors(pntLeft, pntRight); + pntOut.multiply(0.5); + pntOut.normalize(); + return Vector2d.cartesianToSpherical2(pntOut); +}; + +Vector2d.create = function (x, y) { + var temp = new Vector2d(); + temp.x = x; + temp.y = y; + return temp; +}; + +Vector2d.subtract = function (left, right) { + return Vector2d.create(left.x - right.x, left.y - right.y); +}; + +var Vector2d$ = { + distance3d: function (pointB) { + var pnt1 = geoTo3dDouble(pointB.y, pointB.x); + var pnt2 = geoTo3dDouble(this.y, this.x); + var pntDiff = Vector3d.subtractVectors(pnt1, pnt2); + return pntDiff.length() / Math.PI * 180; + }, + + get_length: function () { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + normalize: function () { + var length = this.get_length(); + if (!!length) { + this.x /= length; + this.y /= length; + } + }, + + extend: function (factor) { + this.x = this.x * factor; + this.y = this.y * factor; + } +}; + +registerType("Vector2d", [Vector2d, Vector2d$, null]); + + +// wwtlib.Matrix3d + +export function Matrix3d() { + this._m11 = 0; + this._m12 = 0; + this._m13 = 0; + this._m14 = 0; + this._m21 = 0; + this._m22 = 0; + this._m23 = 0; + this._m24 = 0; + this._m31 = 0; + this._m32 = 0; + this._m33 = 0; + this._m34 = 0; + this._offsetX = 0; + this._offsetY = 0; + this._offsetZ = 0; + this._m44 = 0; + this._isNotKnownToBeIdentity = false; +} + +Matrix3d.create = function (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, offsetX, offsetY, offsetZ, m44) { + var temp = new Matrix3d(); + temp._m11 = m11; + temp._m12 = m12; + temp._m13 = m13; + temp._m14 = m14; + temp._m21 = m21; + temp._m22 = m22; + temp._m23 = m23; + temp._m24 = m24; + temp._m31 = m31; + temp._m32 = m32; + temp._m33 = m33; + temp._m34 = m34; + temp._offsetX = offsetX; + temp._offsetY = offsetY; + temp._offsetZ = offsetZ; + temp._m44 = m44; + temp._isNotKnownToBeIdentity = true; + return temp; +}; + +Matrix3d.get_identity = function () { + var temp = new Matrix3d(); + temp.set(Matrix3d._s_identity); + return temp; +}; + +Matrix3d.multiplyMatrix = function (matrix1, matrix2) { + if (matrix1.get__isDistinguishedIdentity()) { + return matrix2; + } + if (matrix2.get__isDistinguishedIdentity()) { + return matrix1; + } + return Matrix3d.create((((matrix1._m11 * matrix2._m11) + (matrix1._m12 * matrix2._m21)) + (matrix1._m13 * matrix2._m31)) + (matrix1._m14 * matrix2._offsetX), (((matrix1._m11 * matrix2._m12) + (matrix1._m12 * matrix2._m22)) + (matrix1._m13 * matrix2._m32)) + (matrix1._m14 * matrix2._offsetY), (((matrix1._m11 * matrix2._m13) + (matrix1._m12 * matrix2._m23)) + (matrix1._m13 * matrix2._m33)) + (matrix1._m14 * matrix2._offsetZ), (((matrix1._m11 * matrix2._m14) + (matrix1._m12 * matrix2._m24)) + (matrix1._m13 * matrix2._m34)) + (matrix1._m14 * matrix2._m44), (((matrix1._m21 * matrix2._m11) + (matrix1._m22 * matrix2._m21)) + (matrix1._m23 * matrix2._m31)) + (matrix1._m24 * matrix2._offsetX), (((matrix1._m21 * matrix2._m12) + (matrix1._m22 * matrix2._m22)) + (matrix1._m23 * matrix2._m32)) + (matrix1._m24 * matrix2._offsetY), (((matrix1._m21 * matrix2._m13) + (matrix1._m22 * matrix2._m23)) + (matrix1._m23 * matrix2._m33)) + (matrix1._m24 * matrix2._offsetZ), (((matrix1._m21 * matrix2._m14) + (matrix1._m22 * matrix2._m24)) + (matrix1._m23 * matrix2._m34)) + (matrix1._m24 * matrix2._m44), (((matrix1._m31 * matrix2._m11) + (matrix1._m32 * matrix2._m21)) + (matrix1._m33 * matrix2._m31)) + (matrix1._m34 * matrix2._offsetX), (((matrix1._m31 * matrix2._m12) + (matrix1._m32 * matrix2._m22)) + (matrix1._m33 * matrix2._m32)) + (matrix1._m34 * matrix2._offsetY), (((matrix1._m31 * matrix2._m13) + (matrix1._m32 * matrix2._m23)) + (matrix1._m33 * matrix2._m33)) + (matrix1._m34 * matrix2._offsetZ), (((matrix1._m31 * matrix2._m14) + (matrix1._m32 * matrix2._m24)) + (matrix1._m33 * matrix2._m34)) + (matrix1._m34 * matrix2._m44), (((matrix1._offsetX * matrix2._m11) + (matrix1._offsetY * matrix2._m21)) + (matrix1._offsetZ * matrix2._m31)) + (matrix1._m44 * matrix2._offsetX), (((matrix1._offsetX * matrix2._m12) + (matrix1._offsetY * matrix2._m22)) + (matrix1._offsetZ * matrix2._m32)) + (matrix1._m44 * matrix2._offsetY), (((matrix1._offsetX * matrix2._m13) + (matrix1._offsetY * matrix2._m23)) + (matrix1._offsetZ * matrix2._m33)) + (matrix1._m44 * matrix2._offsetZ), (((matrix1._offsetX * matrix2._m14) + (matrix1._offsetY * matrix2._m24)) + (matrix1._offsetZ * matrix2._m34)) + (matrix1._m44 * matrix2._m44)); +}; + +Matrix3d.lookAtLH = function (cameraPosition, cameraTarget, cameraUpVector) { + var zaxis = Vector3d.subtractVectors(cameraTarget, cameraPosition); + zaxis.normalize(); + var xaxis = Vector3d.cross(cameraUpVector, zaxis); + xaxis.normalize(); + var yaxis = Vector3d.cross(zaxis, xaxis); + var mat = Matrix3d.create(xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, -Vector3d.dot(xaxis, cameraPosition), -Vector3d.dot(yaxis, cameraPosition), -Vector3d.dot(zaxis, cameraPosition), 1); + return mat; +}; + +Matrix3d._createIdentity = function () { + var matrixd = Matrix3d.create(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + matrixd.set__isDistinguishedIdentity(true); + return matrixd; +}; + +Matrix3d.equals = function (matrix1, matrix2) { + if (matrix1.get__isDistinguishedIdentity() || matrix2.get__isDistinguishedIdentity()) { + return (matrix1.get_isIdentity() === matrix2.get_isIdentity()); + } + if ((((matrix1.get_m11() === matrix2.get_m11() && matrix1.get_m12() === matrix2.get_m12()) && (matrix1.get_m13() === matrix2.get_m13() && matrix1.get_m14() === matrix2.get_m14())) && ((matrix1.get_m21() === matrix2.get_m21() && matrix1.get_m22() === matrix2.get_m22()) && (matrix1.get_m23() === matrix2.get_m23() && matrix1.get_m24() === matrix2.get_m24()))) && (((matrix1.get_m31() === matrix2.get_m31() && matrix1.get_m32() === matrix2.get_m32()) && (matrix1.get_m33() === matrix2.get_m33() && matrix1.get_m34() === matrix2.get_m34())) && ((matrix1.get_offsetX() === matrix2.get_offsetX() && matrix1.get_offsetY() === matrix2.get_offsetY()) && matrix1.get_offsetZ() === matrix2.get_offsetZ()))) { + return matrix1.get_m44() === matrix2.get_m44(); + } + return false; +}; + +Matrix3d.fromMatrix2d = function (mat) { + var mat3d = Matrix3d._createIdentity(); + mat3d.set_m11(mat.m11); + mat3d.set_m12(mat.m12); + mat3d.set_m13(mat.m13); + mat3d.set_m21(mat.m21); + mat3d.set_m22(mat.m22); + mat3d.set_m23(mat.m23); + mat3d.set_m31(mat.m31); + mat3d.set_m32(mat.m32); + mat3d.set_m33(mat.m33); + mat3d._isNotKnownToBeIdentity = true; + return mat3d; +}; + +Matrix3d.rotationYawPitchRoll = function (heading, pitch, roll) { + var matX = Matrix3d._rotationX(pitch); + var matY = Matrix3d._rotationY(heading); + var matZ = Matrix3d._rotationZ(roll); + return Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(matY, matX), matZ); +}; + +Matrix3d._rotationY = function (p) { + var v = p; + var matNew = Matrix3d.get_identity(); + matNew._m11 = Math.cos(v); + matNew._m22 = 1; + matNew._m31 = Math.sin(v); + matNew._m13 = -Math.sin(v); + matNew._m33 = Math.cos(v); + matNew._isNotKnownToBeIdentity = true; + return matNew; +}; + +Matrix3d._rotationX = function (p) { + var v = p; + var matNew = Matrix3d.get_identity(); + matNew._m11 = 1; + matNew._m22 = Math.cos(v); + matNew._m32 = -Math.sin(v); + matNew._m23 = Math.sin(v); + matNew._m33 = Math.cos(v); + matNew._isNotKnownToBeIdentity = true; + return matNew; +}; + +Matrix3d._rotationZ = function (p) { + var v = p; + var matNew = Matrix3d.get_identity(); + matNew._m11 = Math.cos(v); + matNew._m21 = -Math.sin(v); + matNew._m12 = Math.sin(v); + matNew._m22 = Math.cos(v); + matNew._m33 = 1; + matNew._isNotKnownToBeIdentity = true; + return matNew; +}; + +Matrix3d._scaling = function (x, y, z) { + var matNew = Matrix3d.get_identity(); + matNew._m11 = x; + matNew._m22 = y; + matNew._m33 = z; + matNew._isNotKnownToBeIdentity = true; + return matNew; +}; + +Matrix3d._translationXYZ = function (x, y, z) { + var matNew = Matrix3d.get_identity(); + matNew.set_offsetX(x); + matNew.set_offsetY(y); + matNew.set_offsetZ(z); + matNew._isNotKnownToBeIdentity = true; + return matNew; +}; + +Matrix3d.perspectiveFovLH = function (fieldOfViewY, aspectRatio, znearPlane, zfarPlane) { + var h = 1 / Math.tan(fieldOfViewY / 2); + var w = h / aspectRatio; + return Matrix3d.create(w, 0, 0, 0, 0, h, 0, 0, 0, 0, zfarPlane / (zfarPlane - znearPlane), 1, 0, 0, -znearPlane * zfarPlane / (zfarPlane - znearPlane), 0); +}; + +Matrix3d.perspectiveOffCenterLH = function (left, right, bottom, top, znearPlane, zfarPlane) { + return Matrix3d.create(2 * znearPlane / (right - left), 0, 0, 0, 0, 2 * znearPlane / (top - bottom), 0, 0, (left + right) / (left - right), (top + bottom) / (bottom - top), zfarPlane / (zfarPlane - znearPlane), 1, 0, 0, znearPlane * zfarPlane / (znearPlane - zfarPlane), 0); +}; + +Matrix3d.invertMatrix = function (matrix3d) { + var mat = matrix3d.clone(); + mat.invert(); + return mat; +}; + +Matrix3d.translation = function (vector3d) { + return Matrix3d._translationXYZ(vector3d.x, vector3d.y, vector3d.z); +}; + +Matrix3d.getMapMatrix = function (center, fieldWidth, fieldHeight, rotation) { + var offsetX = 0; + var offsetY = 0; + offsetX = -((center.get_lng() + 180 - (fieldWidth / 2)) / 360); + offsetY = -(1 - ((center.get_lat() + 90 + (fieldHeight / 2)) / 180)); + var mat = new Matrix2d(); + var scaleX = 0; + var scaleY = 0; + scaleX = 360 / fieldWidth; + scaleY = 180 / fieldHeight; + mat = Matrix2d.multiply(mat, Matrix2d.translation(offsetX, offsetY)); + mat = Matrix2d.multiply(mat, Matrix2d.scaling(scaleX, scaleY)); + if (!!rotation) { + mat = Matrix2d.multiply(mat, Matrix2d.translation(-0.5, -0.5)); + mat = Matrix2d.multiply(mat, Matrix2d.rotation(rotation)); + mat = Matrix2d.multiply(mat, Matrix2d.translation(0.5, 0.5)); + } + return Matrix3d.fromMatrix2d(mat); +}; + +var Matrix3d$ = { + clone: function () { + var tmp = new Matrix3d(); + tmp.set(this); + return tmp; + }, + + setIdentity: function () { + this.set(Matrix3d._s_identity); + }, + + set: function (mat) { + this._m11 = mat._m11; + this._m12 = mat._m12; + this._m13 = mat._m13; + this._m14 = mat._m14; + this._m21 = mat._m21; + this._m22 = mat._m22; + this._m23 = mat._m23; + this._m24 = mat._m24; + this._m31 = mat._m31; + this._m32 = mat._m32; + this._m33 = mat._m33; + this._m34 = mat._m34; + this._offsetX = mat._offsetX; + this._offsetY = mat._offsetY; + this._offsetZ = mat._offsetZ; + this._m44 = mat._m44; + this._isNotKnownToBeIdentity = true; + }, + + floatArray: function () { + var array = new Array(16); + array[0] = this._m11; + array[1] = this._m12; + array[2] = this._m13; + array[3] = this._m14; + array[4] = this._m21; + array[5] = this._m22; + array[6] = this._m23; + array[7] = this._m24; + array[8] = this._m31; + array[9] = this._m32; + array[10] = this._m33; + array[11] = this._m34; + array[12] = this._offsetX; + array[13] = this._offsetY; + array[14] = this._offsetZ; + array[15] = this._m44; + return array; + }, + + get_isIdentity: function () { + if (this.get__isDistinguishedIdentity()) { + return true; + } + if (((((this._m11 === 1) && (!this._m12)) && ((!this._m13) && (!this._m14))) && (((!this._m21) && (this._m22 === 1)) && ((!this._m23) && (!this._m24)))) && ((((!this._m31) && (!this._m32)) && ((this._m33 === 1) && (!this._m34))) && (((!this._offsetX) && (!this._offsetY)) && ((!this._offsetZ) && (this._m44 === 1))))) { + this.set__isDistinguishedIdentity(true); + return true; + } + return false; + }, + + prepend: function (matrix) { + this.set(Matrix3d.multiplyMatrix(matrix, this)); + }, + + append: function (matrix) { + this._multiply(matrix); + }, + + scale: function (scale) { + if (this.get__isDistinguishedIdentity()) { + this._setScaleMatrix(scale); + } + else { + this._m11 *= scale.x; + this._m12 *= scale.y; + this._m13 *= scale.z; + this._m21 *= scale.x; + this._m22 *= scale.y; + this._m23 *= scale.z; + this._m31 *= scale.x; + this._m32 *= scale.y; + this._m33 *= scale.z; + this._offsetX *= scale.x; + this._offsetY *= scale.y; + this._offsetZ *= scale.z; + } + }, + + scalePrepend: function (scale) { + if (this.get__isDistinguishedIdentity()) { + this._setScaleMatrix(scale); + } + else { + this._m11 *= scale.x; + this._m12 *= scale.x; + this._m13 *= scale.x; + this._m14 *= scale.x; + this._m21 *= scale.y; + this._m22 *= scale.y; + this._m23 *= scale.y; + this._m24 *= scale.y; + this._m31 *= scale.z; + this._m32 *= scale.z; + this._m33 *= scale.z; + this._m34 *= scale.z; + } + }, + + scaleAt: function (scale, center) { + if (this.get__isDistinguishedIdentity()) { + this._setScaleMatrixCenter(scale, center); + } + else { + var num = this._m14 * center.x; + this._m11 = num + (scale.x * (this._m11 - num)); + num = this._m14 * center.y; + this._m12 = num + (scale.y * (this._m12 - num)); + num = this._m14 * center.z; + this._m13 = num + (scale.z * (this._m13 - num)); + num = this._m24 * center.x; + this._m21 = num + (scale.x * (this._m21 - num)); + num = this._m24 * center.y; + this._m22 = num + (scale.y * (this._m22 - num)); + num = this._m24 * center.z; + this._m23 = num + (scale.z * (this._m23 - num)); + num = this._m34 * center.x; + this._m31 = num + (scale.x * (this._m31 - num)); + num = this._m34 * center.y; + this._m32 = num + (scale.y * (this._m32 - num)); + num = this._m34 * center.z; + this._m33 = num + (scale.z * (this._m33 - num)); + num = this._m44 * center.x; + this._offsetX = num + (scale.x * (this._offsetX - num)); + num = this._m44 * center.y; + this._offsetY = num + (scale.y * (this._offsetY - num)); + num = this._m44 * center.z; + this._offsetZ = num + (scale.z * (this._offsetZ - num)); + } + }, + + scaleAtPrepend: function (scale, center) { + if (this.get__isDistinguishedIdentity()) { + this._setScaleMatrixCenter(scale, center); + } + else { + var num3 = center.x - (center.x * scale.x); + var num2 = center.y - (center.y * scale.y); + var num = center.z - (center.z * scale.z); + this._offsetX += ((this._m11 * num3) + (this._m21 * num2)) + (this._m31 * num); + this._offsetY += ((this._m12 * num3) + (this._m22 * num2)) + (this._m32 * num); + this._offsetZ += ((this._m13 * num3) + (this._m23 * num2)) + (this._m33 * num); + this._m44 += ((this._m14 * num3) + (this._m24 * num2)) + (this._m34 * num); + this._m11 *= scale.x; + this._m12 *= scale.x; + this._m13 *= scale.x; + this._m14 *= scale.x; + this._m21 *= scale.y; + this._m22 *= scale.y; + this._m23 *= scale.y; + this._m24 *= scale.y; + this._m31 *= scale.z; + this._m32 *= scale.z; + this._m33 *= scale.z; + this._m34 *= scale.z; + } + }, + + translate: function (offset) { + if (this.get__isDistinguishedIdentity()) { + this._setTranslationMatrix(offset); + } + else { + this._m11 += this._m14 * offset.x; + this._m12 += this._m14 * offset.y; + this._m13 += this._m14 * offset.z; + this._m21 += this._m24 * offset.x; + this._m22 += this._m24 * offset.y; + this._m23 += this._m24 * offset.z; + this._m31 += this._m34 * offset.x; + this._m32 += this._m34 * offset.y; + this._m33 += this._m34 * offset.z; + this._offsetX += this._m44 * offset.x; + this._offsetY += this._m44 * offset.y; + this._offsetZ += this._m44 * offset.z; + } + }, + + translatePrepend: function (offset) { + if (this.get__isDistinguishedIdentity()) { + this._setTranslationMatrix(offset); + } + else { + this._offsetX += ((this._m11 * offset.x) + (this._m21 * offset.y)) + (this._m31 * offset.z); + this._offsetY += ((this._m12 * offset.x) + (this._m22 * offset.y)) + (this._m32 * offset.z); + this._offsetZ += ((this._m13 * offset.x) + (this._m23 * offset.y)) + (this._m33 * offset.z); + this._m44 += ((this._m14 * offset.x) + (this._m24 * offset.y)) + (this._m34 * offset.z); + } + }, + + transform: function (point) { + var temp = new Vector3d(); + if (!this.get__isDistinguishedIdentity()) { + var x = point.x; + var y = point.y; + var z = point.z; + temp.x = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; + temp.y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; + temp.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; + if (!this.get_isAffine()) { + var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; + temp.x /= num4; + temp.y /= num4; + temp.z /= num4; + } + } + return temp; + }, + + _transformTo: function (input, output) { + output.x = (((input.x * this._m11) + (input.y * this._m21)) + (input.z * this._m31)) + this._offsetX; + output.y = (((input.x * this._m12) + (input.y * this._m22)) + (input.z * this._m32)) + this._offsetY; + output.z = (((input.x * this._m13) + (input.y * this._m23)) + (input.z * this._m33)) + this._offsetZ; + var num4 = (((input.x * this._m14) + (input.y * this._m24)) + (input.z * this._m34)) + this._m44; + output.x /= num4; + output.y /= num4; + output.z /= num4; + }, + + transformArray: function (points) { + if (points != null) { + for (var i = 0; i < points.length; i++) { + this._multiplyPoint(points[i]); + } + } + }, + + projectArrayToScreen: function (input, output) { + if (input != null && output != null) { + var affine = this.get_isAffine(); + for (var i = 0; i < input.length; i++) { + var x = input[i].x; + var y = input[i].y; + var z = input[i].z; + if (affine) { + output[i].x = ((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX); + output[i].y = ((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY); + output[i].z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; + } + else { + var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; + output[i].x = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4); + output[i].y = (((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4); + output[i].z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; + } + } + } + }, + + projectToScreen: function (input, width, height) { + var output = new Vector3d(); + var x = input.x; + var y = input.y; + var z = input.z; + if (this.get_isAffine()) { + output.x = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) + 0.5) * width; + output.y = (-((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) + 0.5) * height; + output.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; + } + else { + var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; + output.x = ((((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4) + 0.5) * width; + output.y = (-(((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4) + 0.5) * height; + output.z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; + } + return output; + }, + + get_isAffine: function () { + if (this.get__isDistinguishedIdentity()) { + return true; + } + if (((!this._m14) && (!this._m24)) && (!this._m34)) { + return (this._m44 === 1); + } + return false; + }, + + get_determinant: function () { + if (this.get__isDistinguishedIdentity()) { + return 1; + } + if (this.get_isAffine()) { + return this._getNormalizedAffineDeterminant(); + } + var num6 = (this._m13 * this._m24) - (this._m23 * this._m14); + var num5 = (this._m13 * this._m34) - (this._m33 * this._m14); + var num4 = (this._m13 * this._m44) - (this._offsetZ * this._m14); + var num3 = (this._m23 * this._m34) - (this._m33 * this._m24); + var num2 = (this._m23 * this._m44) - (this._offsetZ * this._m24); + var num = (this._m33 * this._m44) - (this._offsetZ * this._m34); + var num10 = ((this._m22 * num5) - (this._m32 * num6)) - (this._m12 * num3); + var num9 = ((this._m12 * num2) - (this._m22 * num4)) + (this._offsetY * num6); + var num8 = ((this._m32 * num4) - (this._offsetY * num5)) - (this._m12 * num); + var num7 = ((this._m22 * num) - (this._m32 * num2)) + (this._offsetY * num3); + return ((((this._offsetX * num10) + (this._m31 * num9)) + (this._m21 * num8)) + (this._m11 * num7)); + }, + + get_hasInverse: function () { + return !DoubleUtilities.isZero(this.get_determinant()); + }, + + invert: function () { + if (!this._invertCore()) { + return; + } + }, + + transpose: function () { + var that = new Matrix3d(); + that.set(this); + this._m12 = that._m21; + this._m13 = that._m31; + this._m14 = that._offsetX; + this._m23 = that._m32; + this._m24 = that._offsetY; + this._m34 = that._offsetZ; + this._m21 = that._m12; + this._m31 = that._m13; + this._offsetX = that._m14; + this._m32 = that._m23; + this._offsetY = that._m24; + this._offsetZ = that._m34; + }, + + get_m11: function () { + if (this.get__isDistinguishedIdentity()) { + return 1; + } + return this._m11; + }, + + set_m11: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m11 = value; + return value; + }, + + get_m12: function () { + return this._m12; + }, + + set_m12: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m12 = value; + return value; + }, + + get_m13: function () { + return this._m13; + }, + + set_m13: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m13 = value; + return value; + }, + + get_m14: function () { + return this._m14; + }, + + set_m14: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m14 = value; + return value; + }, + + get_m21: function () { + return this._m21; + }, + + set_m21: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m21 = value; + return value; + }, + + get_m22: function () { + if (this.get__isDistinguishedIdentity()) { + return 1; + } + return this._m22; + }, + + set_m22: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m22 = value; + return value; + }, + + get_m23: function () { + return this._m23; + }, + + set_m23: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m23 = value; + return value; + }, + + get_m24: function () { + return this._m24; + }, + + set_m24: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m24 = value; + return value; + }, + + get_m31: function () { + return this._m31; + }, + + set_m31: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m31 = value; + return value; + }, + + get_m32: function () { + return this._m32; + }, + + set_m32: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m32 = value; + return value; + }, + + get_m33: function () { + if (this.get__isDistinguishedIdentity()) { + return 1; + } + return this._m33; + }, + + set_m33: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m33 = value; + return value; + }, + + get_m34: function () { + return this._m34; + }, + + set_m34: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m34 = value; + return value; + }, + + get_m41: function () { + return this.get_offsetX(); + }, + + set_m41: function (value) { + this.set_offsetX(value); + return value; + }, + + get_m42: function () { + return this.get_offsetY(); + }, + + set_m42: function (value) { + this.set_offsetY(value); + return value; + }, + + get_m43: function () { + return this.get_offsetZ(); + }, + + set_m43: function (value) { + this.set_offsetZ(value); + return value; + }, + + get_offsetX: function () { + return this._offsetX; + }, + + set_offsetX: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._offsetX = value; + return value; + }, + + get_offsetY: function () { + return this._offsetY; + }, + + set_offsetY: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._offsetY = value; + return value; + }, + + get_offsetZ: function () { + return this._offsetZ; + }, + + set_offsetZ: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._offsetZ = value; + return value; + }, + + get_m44: function () { + if (this.get__isDistinguishedIdentity()) { + return 1; + } + return this._m44; + }, + + set_m44: function (value) { + if (this.get__isDistinguishedIdentity()) { + this.set(Matrix3d._s_identity); + this.set__isDistinguishedIdentity(false); + } + this._m44 = value; + return value; + }, + + _setScaleMatrix: function (scale) { + this._m11 = scale.x; + this._m22 = scale.y; + this._m33 = scale.z; + this._m44 = 1; + this.set__isDistinguishedIdentity(false); + }, + + _setScaleMatrixCenter: function (scale, center) { + this._m11 = scale.x; + this._m22 = scale.y; + this._m33 = scale.z; + this._m44 = 1; + this._offsetX = center.x - (center.x * scale.x); + this._offsetY = center.y - (center.y * scale.y); + this._offsetZ = center.z - (center.z * scale.z); + this.set__isDistinguishedIdentity(false); + }, + + _setTranslationMatrix: function (offset) { + this._m11 = this._m22 = this._m33 = this._m44 = 1; + this._offsetX = offset.x; + this._offsetY = offset.y; + this._offsetZ = offset.z; + this.set__isDistinguishedIdentity(false); + }, + + _multiplyPoint: function (point) { + if (!this.get__isDistinguishedIdentity()) { + var x = point.x; + var y = point.y; + var z = point.z; + point.x = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; + point.y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; + point.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; + if (!this.get_isAffine()) { + var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; + point.x /= num4; + point.y /= num4; + point.z /= num4; + } + } + }, + + multiplyVector: function (vector) { + if (!this.get__isDistinguishedIdentity()) { + var x = vector.x; + var y = vector.y; + var z = vector.z; + vector.x = ((x * this._m11) + (y * this._m21)) + (z * this._m31); + vector.y = ((x * this._m12) + (y * this._m22)) + (z * this._m32); + vector.z = ((x * this._m13) + (y * this._m23)) + (z * this._m33); + } + }, + + _getNormalizedAffineDeterminant: function () { + var num3 = (this._m12 * this._m23) - (this._m22 * this._m13); + var num2 = (this._m32 * this._m13) - (this._m12 * this._m33); + var num = (this._m22 * this._m33) - (this._m32 * this._m23); + return (((this._m31 * num3) + (this._m21 * num2)) + (this._m11 * num)); + }, + + _normalizedAffineInvert: function () { + var num11 = (this._m12 * this._m23) - (this._m22 * this._m13); + var num10 = (this._m32 * this._m13) - (this._m12 * this._m33); + var num9 = (this._m22 * this._m33) - (this._m32 * this._m23); + var num8 = ((this._m31 * num11) + (this._m21 * num10)) + (this._m11 * num9); + if (DoubleUtilities.isZero(num8)) { + return false; + } + var num20 = (this._m21 * this._m13) - (this._m11 * this._m23); + var num19 = (this._m11 * this._m33) - (this._m31 * this._m13); + var num18 = (this._m31 * this._m23) - (this._m21 * this._m33); + var num7 = (this._m11 * this._m22) - (this._m21 * this._m12); + var num6 = (this._m11 * this._m32) - (this._m31 * this._m12); + var num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); + var num4 = (this._m21 * this._m32) - (this._m31 * this._m22); + var num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); + var num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); + var num17 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); + var num16 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); + var num15 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); + var num14 = num7; + var num13 = -num6; + var num12 = num4; + var num = 1 / num8; + this._m11 = num9 * num; + this._m12 = num10 * num; + this._m13 = num11 * num; + this._m21 = num18 * num; + this._m22 = num19 * num; + this._m23 = num20 * num; + this._m31 = num12 * num; + this._m32 = num13 * num; + this._m33 = num14 * num; + this._offsetX = num15 * num; + this._offsetY = num16 * num; + this._offsetZ = num17 * num; + return true; + }, + + _invertCore: function () { + if (!this.get__isDistinguishedIdentity()) { + if (this.get_isAffine()) { + return this._normalizedAffineInvert(); + } + var num7 = (this._m13 * this._m24) - (this._m23 * this._m14); + var num6 = (this._m13 * this._m34) - (this._m33 * this._m14); + var num5 = (this._m13 * this._m44) - (this._offsetZ * this._m14); + var num4 = (this._m23 * this._m34) - (this._m33 * this._m24); + var num3 = (this._m23 * this._m44) - (this._offsetZ * this._m24); + var num2 = (this._m33 * this._m44) - (this._offsetZ * this._m34); + var num12 = ((this._m22 * num6) - (this._m32 * num7)) - (this._m12 * num4); + var num11 = ((this._m12 * num3) - (this._m22 * num5)) + (this._offsetY * num7); + var num10 = ((this._m32 * num5) - (this._offsetY * num6)) - (this._m12 * num2); + var num9 = ((this._m22 * num2) - (this._m32 * num3)) + (this._offsetY * num4); + var num8 = (((this._offsetX * num12) + (this._m31 * num11)) + (this._m21 * num10)) + (this._m11 * num9); + if (DoubleUtilities.isZero(num8)) { + return false; + } + var num24 = ((this._m11 * num4) - (this._m21 * num6)) + (this._m31 * num7); + var num23 = ((this._m21 * num5) - (this._offsetX * num7)) - (this._m11 * num3); + var num22 = ((this._m11 * num2) - (this._m31 * num5)) + (this._offsetX * num6); + var num21 = ((this._m31 * num3) - (this._offsetX * num4)) - (this._m21 * num2); + num7 = (this._m11 * this._m22) - (this._m21 * this._m12); + num6 = (this._m11 * this._m32) - (this._m31 * this._m12); + num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); + num4 = (this._m21 * this._m32) - (this._m31 * this._m22); + num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); + num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); + var num20 = ((this._m13 * num4) - (this._m23 * num6)) + (this._m33 * num7); + var num19 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); + var num18 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); + var num17 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); + var num16 = ((this._m24 * num6) - (this._m34 * num7)) - (this._m14 * num4); + var num15 = ((this._m14 * num3) - (this._m24 * num5)) + (this._m44 * num7); + var num14 = ((this._m34 * num5) - (this._m44 * num6)) - (this._m14 * num2); + var num13 = ((this._m24 * num2) - (this._m34 * num3)) + (this._m44 * num4); + var num = 1 / num8; + this._m11 = num9 * num; + this._m12 = num10 * num; + this._m13 = num11 * num; + this._m14 = num12 * num; + this._m21 = num21 * num; + this._m22 = num22 * num; + this._m23 = num23 * num; + this._m24 = num24 * num; + this._m31 = num13 * num; + this._m32 = num14 * num; + this._m33 = num15 * num; + this._m34 = num16 * num; + this._offsetX = num17 * num; + this._offsetY = num18 * num; + this._offsetZ = num19 * num; + this._m44 = num20 * num; + } + return true; + }, + + get__isDistinguishedIdentity: function () { + return !this._isNotKnownToBeIdentity; + }, + + set__isDistinguishedIdentity: function (value) { + this._isNotKnownToBeIdentity = !value; + return value; + }, + + _multiply: function (mat) { + this.set(Matrix3d.multiplyMatrix(this, mat)); + } +}; + +registerType("Matrix3d", [Matrix3d, Matrix3d$, null]); + +Matrix3d._s_identity = Matrix3d._createIdentity(); + + +// wwtlib.Matrix2d + +export function Matrix2d() { + this.m11 = 1; + this.m12 = 0; + this.m13 = 0; + this.m21 = 0; + this.m22 = 1; + this.m23 = 0; + this.m31 = 0; + this.m32 = 0; + this.m33 = 1; +} + +Matrix2d.create = function (m11, m12, m13, m21, m22, m23, m31, m32, m33) { + var mat = new Matrix2d(); + mat.m11 = m11; + mat.m12 = m12; + mat.m13 = m13; + mat.m21 = m21; + mat.m22 = m22; + mat.m23 = m23; + mat.m31 = m31; + mat.m32 = m32; + mat.m33 = m33; + return mat; +}; + +Matrix2d.rotation = function (angle) { + var mat = new Matrix2d(); + mat.m11 = Math.cos(angle); + mat.m21 = -Math.sin(angle); + mat.m12 = Math.sin(angle); + mat.m22 = Math.cos(angle); + return mat; +}; + +Matrix2d.translation = function (x, y) { + var mat = new Matrix2d(); + mat.m31 = x; + mat.m32 = y; + return mat; +}; + +Matrix2d.scaling = function (x, y) { + var mat = new Matrix2d(); + mat.m11 = x; + mat.m22 = y; + return mat; +}; + +Matrix2d.multiply = function (matrix1, matrix2) { + return Matrix2d.create((((matrix1.m11 * matrix2.m11) + (matrix1.m12 * matrix2.m21)) + (matrix1.m13 * matrix2.m31)), (((matrix1.m11 * matrix2.m12) + (matrix1.m12 * matrix2.m22)) + (matrix1.m13 * matrix2.m32)), (((matrix1.m11 * matrix2.m13) + (matrix1.m12 * matrix2.m23)) + (matrix1.m13 * matrix2.m33)), (((matrix1.m21 * matrix2.m11) + (matrix1.m22 * matrix2.m21)) + (matrix1.m23 * matrix2.m31)), (((matrix1.m21 * matrix2.m12) + (matrix1.m22 * matrix2.m22)) + (matrix1.m23 * matrix2.m32)), (((matrix1.m21 * matrix2.m13) + (matrix1.m22 * matrix2.m23)) + (matrix1.m23 * matrix2.m33)), (((matrix1.m31 * matrix2.m11) + (matrix1.m32 * matrix2.m21)) + (matrix1.m33 * matrix2.m31)), (((matrix1.m31 * matrix2.m12) + (matrix1.m32 * matrix2.m22)) + (matrix1.m33 * matrix2.m32)), (((matrix1.m31 * matrix2.m13) + (matrix1.m32 * matrix2.m23)) + (matrix1.m33 * matrix2.m33))); +}; + +Matrix2d.rotateAt = function (angle, pnt) { + var matT0 = Matrix2d.translation(-pnt.x, -pnt.y); + var matR = Matrix2d.rotation(angle); + var matT1 = Matrix2d.translation(pnt.x, pnt.y); + return Matrix2d.multiply(Matrix2d.multiply(matT0, matR), matT1); +}; + +var Matrix2d$ = { + _transformPoints: function (points) { + var $enum1 = ss.enumerate(points); + while ($enum1.moveNext()) { + var pnt = $enum1.current; + this.multiplyPoint(pnt); + } + }, + + multiplyPoint: function (point) { + var x = point.x; + var y = point.y; + point.x = (((x * this.m11) + (y * this.m21)) + this.m31); + point.y = (((x * this.m12) + (y * this.m22)) + this.m32); + } +}; + +registerType("Matrix2d", [Matrix2d, Matrix2d$, null]); + + +// wwtlib.DoubleUtilities + +export function DoubleUtilities() { } + +DoubleUtilities.isZero = function (value) { + return (Math.abs(value) < 2.22044604925031E-50); +}; + +DoubleUtilities.isOne = function (value) { + return (Math.abs(value - 1) < 2.22044604925031E-50); +}; + +DoubleUtilities.radiansToDegrees = function (radians) { + return radians * 180 / Math.PI; +}; + +DoubleUtilities.degreesToRadians = function (degrees) { + return degrees * Math.PI / 180; +}; + +DoubleUtilities.clamp = function (x, min, max) { + return Math.max(min, Math.min(x, max)); +}; + +registerType("DoubleUtilities", [DoubleUtilities, null, null]); + + +// wwtlib.PlaneD + +export function PlaneD(valuePointA, valuePointB, valuePointC, valuePointD) { + this.a = 0; + this.b = 0; + this.c = 0; + this.d = 0; + this.a = valuePointA; + this.b = valuePointB; + this.c = valuePointC; + this.d = valuePointD; +} + +var PlaneD$ = { + normalize: function () { + var length = Math.sqrt(this.a * this.a + this.b * this.b + this.c * this.c); + this.a /= length; + this.b /= length; + this.c /= length; + this.d /= length; + }, + + dot: function (v) { + return this.b * v.y + this.c * v.z + this.d * v.w + this.a * v.x; + } +}; + +registerType("PlaneD", [PlaneD, PlaneD$, null]); + + +// wwtlib.Vector4d + +export function Vector4d(valueX, valueY, valueZ, valueW) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + this.x = valueX; + this.y = valueY; + this.z = valueZ; + this.w = valueW; +} + +var Vector4d$ = {}; + +registerType("Vector4d", [Vector4d, Vector4d$, null]); + + +// wwtlib.PositionNormalTexturedX2 + +// Summary: +// Initializes a new instance of the PositionNormalTexturedX2 +// class. +// +// Parameters: +// pos: +// A Microsoft.DirectX.Vector3 object that contains the vertex position. +// +// nor: +// A Microsoft.DirectX.Vector3 object that contains the vertex normal data. +// +// u: +// Floating-point value that represents the PositionNormalTexturedX2.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the PositionNormalTexturedX2.#ctor() +// component of the texture coordinate. +export function PositionNormalTexturedX2() { + this.x = 0; + this.y = 0; + this.z = 0; + this.nx = 0; + this.ny = 0; + this.nz = 0; + this.tu = 0; + this.tv = 0; + this.tu1 = 0; + this.tv1 = 0; +} + +PositionNormalTexturedX2.create2UV = function (pos, nor, u, v, u1, v1) { + var temp = new PositionNormalTexturedX2(); + temp.x = pos.x; + temp.y = pos.y; + temp.z = pos.z; + temp.nx = nor.x; + temp.ny = nor.y; + temp.nz = nor.z; + temp.tu = u; + temp.tv = v; + temp.tu1 = u1; + temp.tv1 = v1; + return temp; +}; + +PositionNormalTexturedX2.create = function (pos, nor, u, v) { + var temp = new PositionNormalTexturedX2(); + temp.x = pos.x; + temp.y = pos.y; + temp.z = pos.z; + temp.nx = nor.x; + temp.ny = nor.y; + temp.nz = nor.z; + temp.tu = u; + temp.tv = v; + var result = coords_cartesianToSpherical2(nor); + temp.tu1 = ((result[1] + 180) / 360); + temp.tv1 = (1 - ((result[0] + 90) / 180)); + return temp; +}; + +// Summary: +// Initializes a new instance of the PositionNormalTexturedX2 +// class. +// +// Parameters: +// xvalue: +// Floating-point value that represents the x coordinate of the position. +// +// yvalue: +// Floating-point value that represents the y coordinate of the position. +// +// zvalue: +// Floating-point value that represents the z coordinate of the position. +// +// nxvalue: +// Floating-point value that represents the nx coordinate of the vertex normal. +// +// nyvalue: +// Floating-point value that represents the ny coordinate of the vertex normal. +// +// nzvalue: +// Floating-point value that represents the nz coordinate of the vertex normal. +// +// u: +// Floating-point value that represents the PositionNormalTexturedX2.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the PositionNormalTexturedX2.#ctor() +// component of the texture coordinate. +PositionNormalTexturedX2.createLong2UV = function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v, u1, v1) { + var temp = new PositionNormalTexturedX2(); + temp.x = xvalue; + temp.y = yvalue; + temp.z = zvalue; + temp.nx = nxvalue; + temp.ny = nyvalue; + temp.nz = nzvalue; + temp.tu = u; + temp.tv = v; + temp.tu1 = u1; + temp.tv1 = v1; + return temp; +}; + +PositionNormalTexturedX2.get_strideSize = function () { + return 40; +}; + +var PositionNormalTexturedX2$ = { + get_lat: function () { + return (1 - this.tv1) * 180 - 90; + }, + + set_lat: function (value) { + this.tv1 = (1 - ((value + 90) / 180)); + return value; + }, + + get_lng: function () { + return this.tu1 * 360 - 180; + }, + + set_lng: function (value) { + this.tu1 = ((value + 180) / 360); + return value; + }, + + createLong: function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v) { + var temp = new PositionNormalTexturedX2(); + temp.x = xvalue; + temp.y = yvalue; + temp.z = zvalue; + temp.nx = nxvalue; + temp.ny = nyvalue; + temp.nz = nzvalue; + temp.tu = u; + temp.tv = v; + var result = coords_cartesianToSpherical2(Vector3d.create(this.nx, this.ny, this.nz)); + temp.tu1 = ((result[1] + 180) / 360); + temp.tv1 = (1 - ((result[0] + 90) / 180)); + return temp; + }, + + get_normal: function () { + return Vector3d.create(this.nx, this.ny, this.nz); + }, + + set_normal: function (value) { + this.nx = value.x; + this.ny = value.y; + this.nz = value.z; + return value; + }, + + get_position: function () { + return Vector3d.create(this.x, this.y, this.y); + }, + + set_position: function (value) { + this.x = value.x; + this.y = value.y; + this.z = value.z; + return value; + }, + + toString: function () { + return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv, this.tu1, this.tv1); + } +}; + +registerType("PositionNormalTexturedX2", [PositionNormalTexturedX2, PositionNormalTexturedX2$, null]); + + +// wwtlib.PositionNormalTextured + +// Summary: +// Initializes a new instance of the PositionNormalTextured +// class. +// +// Parameters: +// pos: +// A Microsoft.DirectX.Vector3 object that contains the vertex position. +// +// nor: +// A Microsoft.DirectX.Vector3 object that contains the vertex normal data. +// +// u: +// Floating-point value that represents the PositionNormalTextured.#ctor() +// component of the texture coordinate. +// +// v: +// Floating-point value that represents the PositionNormalTextured.#ctor() +// component of the texture coordinate. +export function PositionNormalTextured() { + this.x = 0; + this.y = 0; + this.z = 0; + this.nx = 0; + this.ny = 0; + this.nz = 0; + this.tu = 0; + this.tv = 0; +} + +PositionNormalTextured.createShort = function (pos, nor, u, v) { + var temp = new PositionNormalTextured(); + temp.x = pos.x; + temp.y = pos.y; + temp.z = pos.z; + temp.nx = nor.x; + temp.ny = nor.y; + temp.nz = nor.z; + temp.tu = u; + temp.tv = v; + return temp; +}; + +PositionNormalTextured._create = function (x, y, z, nx, ny, nz, tu, tv) { + var temp = new PositionNormalTextured(); + temp.x = x; + temp.y = y; + temp.z = z; + temp.nx = nx; + temp.ny = ny; + temp.nz = nz; + temp.tu = tu; + temp.tv = tv; + return temp; +}; + +PositionNormalTextured.createUV = function (pos, nor, uv) { + var temp = new PositionNormalTextured(); + temp.x = pos.x; + temp.y = pos.y; + temp.z = pos.z; + temp.nx = nor.x; + temp.ny = nor.y; + temp.nz = nor.z; + temp.tu = uv.x; + temp.tv = uv.y; + return temp; +}; + +var PositionNormalTextured$ = { + // ** is it a mistake that this returns an X2 class? almost surely! ** + // + // Summary: + // Initializes a new instance of the PositionNormalTextured + // class. + // + // Parameters: + // xvalue: + // Floating-point value that represents the x coordinate of the position. + // + // yvalue: + // Floating-point value that represents the y coordinate of the position. + // + // zvalue: + // Floating-point value that represents the z coordinate of the position. + // + // nxvalue: + // Floating-point value that represents the nx coordinate of the vertex normal. + // + // nyvalue: + // Floating-point value that represents the ny coordinate of the vertex normal. + // + // nzvalue: + // Floating-point value that represents the nz coordinate of the vertex normal. + // + // u: + // Floating-point value that represents the PositionNormalTexturedX2.#ctor() + // component of the texture coordinate. + // + // v: + // Floating-point value that represents the PositionNormalTexturedX2.#ctor() + // component of the texture coordinate. + createLong: function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v) { + var temp = new PositionNormalTexturedX2(); + temp.x = xvalue; + temp.y = yvalue; + temp.z = zvalue; + temp.nx = nxvalue; + temp.ny = nyvalue; + temp.nz = nzvalue; + temp.tu = u; + temp.tv = v; + return temp; + }, + + get_normal: function () { + return Vector3d.create(this.nx, this.ny, this.nz); + }, + + set_normal: function (value) { + this.nx = value.x; + this.ny = value.y; + this.nz = value.z; + return value; + }, + + get_position: function () { + return Vector3d.create(this.x, this.y, this.z); + }, + + set_position: function (value) { + this.x = value.x; + this.y = value.y; + this.z = value.z; + return value; + }, + + toString: function () { + return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv); + } +}; + +registerType("PositionNormalTextured", [PositionNormalTextured, PositionNormalTextured$, null]); + + +// wwtlib.SphereHull + +export function SphereHull() { + this.radius = 0; +} + +SphereHull._create = function (Center, Radius) { + var temp = new SphereHull(); + temp.center = Center; + temp.radius = Radius; + return temp; +}; + +var SphereHull$ = {}; + +registerType("SphereHull", [SphereHull, SphereHull$, null]); + + + +// wwtlib.ConvexHull + +export function ConvexHull() { +} + +ConvexHull.findEnclosingSphereFast = function (points) { + var result = new SphereHull(); + + //Find the center of all points. + + var count = points.length; + var center = Vector3d.zero; + for (var i = 0; i < count; ++i) { + center.add(points[i]); + } + + //This is the center of our sphere. + center.multiply(1 / count); + + //Find the radius of the sphere + var radius = 0; + for (var i = 0; i < count; ++i) { + //We are doing a relative distance comparison to find the maximum + //distance from the center of our sphere. + var distance = Vector3d.getLengthSq(Vector3d.subtractVectors(points[i], center)); + if (distance > radius) { + radius = distance; + } + } + + //Find the real distance from the DistanceSquared. + radius = Math.sqrt(radius); + + //Construct the sphere. + result.center = center; + result.radius = radius; + return result; +}; + +ConvexHull.findEnclosingSphere = function (list) { + var Center = new Vector3d(); + var Radius = 0; + var count = list.length; + var i; + var dx; + var dy; + var dz; + var rad_sq; + var xspan; + var yspan; + var zspan; + var maxspan; + var old_to_p; + var old_to_p_sq; + var old_to_new; + var xmin = new Vector3d(); + var xmax = new Vector3d(); + var ymin = new Vector3d(); + var ymax = new Vector3d(); + var zmin = new Vector3d(); + var zmax = new Vector3d(); + var dia1 = new Vector3d(); + var dia2 = new Vector3d(); + + // FIRST PASS: find 6 minima/maxima points + xmin.x = ymin.y = zmin.z = 100000000; + xmax.x = ymax.y = zmax.z = -1000000000; + for (i = 0; i < count; i++) { + var current = list[i]; + if (current.x < xmin.x) { + xmin = current; + } + if (current.x > xmax.x) { + xmax = current; + } + if (current.y < ymin.y) { + ymin = current; + } + if (current.y > ymax.y) { + ymax = current; + } + if (current.z < zmin.z) { + zmin = current; + } + if (current.z > zmax.z) { + zmax = current; + } + } + + // Set xspan = distance between the 2 points xmin & xmax (squared) + dx = xmax.x - xmin.x; + dy = xmax.y - xmin.y; + dz = xmax.z - xmin.z; + xspan = dx * dx + dy * dy + dz * dz; + + // Same for y & z spans + dx = ymax.x - ymin.x; + dy = ymax.y - ymin.y; + dz = ymax.z - ymin.z; + yspan = dx * dx + dy * dy + dz * dz; + dx = zmax.x - zmin.x; + dy = zmax.y - zmin.y; + dz = zmax.z - zmin.z; + zspan = dx * dx + dy * dy + dz * dz; + dia1 = xmin; + dia2 = xmax; + maxspan = xspan; + if (yspan > maxspan) { + maxspan = yspan; + dia1 = ymin; + dia2 = ymax; + } + if (zspan > maxspan) { + dia1 = zmin; + dia2 = zmax; + } + + // dia1,dia2 is a diameter of initial sphere + // calc initial center + Center.x = (dia1.x + dia2.x) / 2; + Center.y = (dia1.y + dia2.y) / 2; + Center.z = (dia1.z + dia2.z) / 2; + + // calculate initial radius**2 and radius + dx = dia2.x - Center.x; + dy = dia2.y - Center.y; + dz = dia2.z - Center.z; + rad_sq = dx * dx + dy * dy + dz * dz; + Radius = Math.sqrt(rad_sq); + + // SECOND PASS: increment current sphere + for (i = 0; i < count; i++) { + var current = list[i]; + dx = current.x - Center.x; + dy = current.y - Center.y; + dz = current.z - Center.z; + old_to_p_sq = dx * dx + dy * dy + dz * dz; + if (old_to_p_sq > rad_sq) { + // this point is outside of current sphere + old_to_p = Math.sqrt(old_to_p_sq); + + // calc radius of new sphere + Radius = (Radius + old_to_p) / 2; + rad_sq = Radius * Radius; + old_to_new = old_to_p - Radius; + + // calc center of new sphere + Center.x = (Radius * Center.x + old_to_new * current.x) / old_to_p; + Center.y = (Radius * Center.y + old_to_new * current.y) / old_to_p; + Center.z = (Radius * Center.z + old_to_new * current.z) / old_to_p; + } + } + + return SphereHull._create(Center, Radius); +}; + +var ConvexHull$ = {}; + +registerType("ConvexHull", [ConvexHull, ConvexHull$, null]); diff --git a/engine/esm/equirectangular_tile.js b/engine/esm/equirectangular_tile.js new file mode 100644 index 00000000..629fd59a --- /dev/null +++ b/engine/esm/equirectangular_tile.js @@ -0,0 +1,309 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses an equirectangular projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { tilePrepDevice } from "./render_globals.js"; +import { PositionTexture } from "./double3d.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Tile } from "./tile.js"; + + +// wwtlib.EquirectangularTile + +export function EquirectangularTile() { + this._tileDegrees$1 = 0; + this._topDown$1 = true; + this._subDivisionLevel$1 = 1; + Tile.call(this); +} + +EquirectangularTile.create = function (level, x, y, dataset, parent) { + var temp = new EquirectangularTile(); + temp.parent = parent; + temp.level = level; + temp.tileX = x; + temp.tileY = y; + temp.dataset = dataset; + temp._topDown$1 = !dataset.get_bottomsUp(); + temp.computeBoundingSphere(); + return temp; +}; + +var EquirectangularTile$ = { + computeBoundingSphere: function () { + if (!this._topDown$1) { + this.computeBoundingSphereBottomsUp(); + return; + } + this._tileDegrees$1 = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var latMin = (90 - ((this.tileY) * this._tileDegrees$1)); + var latMax = (90 - (((this.tileY + 1)) * this._tileDegrees$1)); + var lngMin = ((this.tileX * this._tileDegrees$1) - 180); + var lngMax = ((((this.tileX + 1)) * this._tileDegrees$1) - 180); + var latCenter = (latMin + latMax) / 2; + var lngCenter = (lngMin + lngMax) / 2; + this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); + this.topLeft = this.geoTo3d(latMin, lngMin, false); + this.bottomRight = this.geoTo3d(latMax, lngMax, false); + this.topRight = this.geoTo3d(latMin, lngMax, false); + this.bottomLeft = this.geoTo3d(latMax, lngMin, false); + var distVect = this.geoTo3d(latMin, lngMin, false); + distVect.subtract(this.sphereCenter); + this.sphereRadius = distVect.length(); + this._tileDegrees$1 = lngMax - lngMin; + }, + + computeBoundingSphereBottomsUp: function () { + var tileDegrees = this.dataset.get_baseTileDegrees() / (Math.pow(2, this.level)); + var latMin = (-90 + (((this.tileY + 1)) * tileDegrees)); + var latMax = (-90 + ((this.tileY) * tileDegrees)); + var lngMin = ((this.tileX * tileDegrees) - 180); + var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); + var latCenter = (latMin + latMax) / 2; + var lngCenter = (lngMin + lngMax) / 2; + this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); + this.topLeft = this.geoTo3d(latMin, lngMin, false); + this.bottomRight = this.geoTo3d(latMax, lngMax, false); + this.topRight = this.geoTo3d(latMin, lngMax, false); + this.bottomLeft = this.geoTo3d(latMax, lngMin, false); + var distVect = this.topLeft; + distVect.subtract(this.sphereCenter); + this.sphereRadius = distVect.length(); + tileDegrees = lngMax - lngMin; + }, + + createGeometry: function (renderContext) { + Tile.prototype.createGeometry.call(this, renderContext); + if (renderContext.gl == null) { + if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { + this._subDivisionLevel$1 = Math.max(2, (4 - this.level) * 2); + } + } else { + this._subDivisionLevel$1 = 32; + } + try { + for (var i = 0; i < 4; i++) { + this._renderTriangleLists[i] = []; + } + if (!this._topDown$1) { + return this._createGeometryBottomsUp$1(renderContext); + } + var lat, lng; + var index = 0; + var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var latMin = (90 - ((this.tileY) * tileDegrees)); + var latMax = (90 - (((this.tileY + 1)) * tileDegrees)); + var lngMin = ((this.tileX * tileDegrees) - 180); + var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); + var tileDegreesX = lngMax - lngMin; + var tileDegreesY = latMax - latMin; + this.topLeft = this.geoTo3d(latMin, lngMin, false); + this.bottomRight = this.geoTo3d(latMax, lngMax, false); + this.topRight = this.geoTo3d(latMin, lngMax, false); + this.bottomLeft = this.geoTo3d(latMax, lngMin, false); + + // Create a vertex buffer + var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); + var x, y; + var textureStep = 1 / this._subDivisionLevel$1; + for (y = 0; y <= this._subDivisionLevel$1; y++) { + if (y !== this._subDivisionLevel$1) { + lat = latMin + (textureStep * tileDegreesY * y); + } + else { + lat = latMax; + } + for (x = 0; x <= this._subDivisionLevel$1; x++) { + if (x !== this._subDivisionLevel$1) { + lng = lngMin + (textureStep * tileDegreesX * x); + } + else { + lng = lngMax; + } + index = y * (this._subDivisionLevel$1 + 1) + x; + verts[index] = PositionTexture.createPos(this.geoTo3d(lat, lng, false), x * textureStep, y * textureStep); + } + } + this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; + var quarterDivisions = this._subDivisionLevel$1 / 2; + var part = 0; + if (renderContext.gl == null) { + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + index = 0; + for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + var p1; + var p2; + var p3; + + // First triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); + + // Second triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); + } + } + part++; + } + } + } else { + //process vertex list + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(verts.length * 5); + var buffer = f32array; + index = 0; + var $enum1 = ss.enumerate(verts); + while ($enum1.moveNext()) { + var pt = $enum1.current; + index = this.addVertex(buffer, index, pt); + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + var ui16array = new Uint16Array(this.triangleCount * 3); + var indexArray = ui16array; + index = 0; + for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + // First triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + + // Second triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + } + } + this._indexBuffers[part] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this._indexBuffers[part]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, ui16array, WEBGL.STATIC_DRAW); + part++; + } + } + } + } + catch ($e2) { + } + return true; + }, + + _createGeometryBottomsUp$1: function (renderContext) { + var lat, lng; + var index = 0; + var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var latMin = (-90 + (((this.tileY + 1)) * tileDegrees)); + var latMax = (-90 + ((this.tileY) * tileDegrees)); + var lngMin = ((this.tileX * tileDegrees) - 180); + var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); + var tileDegreesX = lngMax - lngMin; + var tileDegreesY = latMax - latMin; + + // Create a vertex buffer + var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); + var x, y; + var textureStep = 1 / this._subDivisionLevel$1; + for (y = 0; y <= this._subDivisionLevel$1; y++) { + if (y !== this._subDivisionLevel$1) { + lat = latMin + (textureStep * tileDegreesY * y); + } + else { + lat = latMax; + } + for (x = 0; x <= this._subDivisionLevel$1; x++) { + if (x !== this._subDivisionLevel$1) { + lng = lngMin + (textureStep * tileDegreesX * x); + } + else { + lng = lngMax; + } + index = y * (this._subDivisionLevel$1 + 1) + x; + verts[index] = PositionTexture.createPos(this.geoTo3d(lat, lng, false), x * textureStep, y * textureStep); + } + } + this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; + var quarterDivisions = this._subDivisionLevel$1 / 2; + var part = 0; + if (renderContext.gl == null) { + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + index = 0; + for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + var p1; + var p2; + var p3; + + // First triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); + + // Second triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); + } + } + part++; + } + } + } else { + //process vertex list + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(verts.length * 5); + var buffer = f32array; + index = 0; + var $enum1 = ss.enumerate(verts); + while ($enum1.moveNext()) { + var pt = $enum1.current; + index = this.addVertex(buffer, index, pt); + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + var ui16array = new Uint16Array(this.triangleCount * 3); + var indexArray = ui16array; + index = 0; + for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + // First triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + + // Second triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + } + } + this._indexBuffers[part] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this._indexBuffers[part]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, ui16array, WEBGL.STATIC_DRAW); + part++; + } + } + } + + return true; + } +}; + +registerType("EquirectangularTile", [EquirectangularTile, EquirectangularTile$, Tile]); diff --git a/engine/esm/fast_math.js b/engine/esm/fast_math.js new file mode 100644 index 00000000..b521e155 --- /dev/null +++ b/engine/esm/fast_math.js @@ -0,0 +1,176 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// "Fast math" routines "from Healpix Java package" + +import { registerType } from "./typesystem.js"; + + +// wwtlib.FastMath + +export function FastMath() { } + +const pI4_A = 0.785398155450821; +const pI4_B = 7.94662735614793E-09; +const pI4_C = 3.06161699786838E-17; +const m_1_PI = 0.318309886183791; + +FastMath._mulsign = function (x, y) { + return FastMath._sign(y) * x; +}; + +FastMath._isnan = function (d) { + return d !== d; +}; + +FastMath._isinf = function (d) { + // TODO: this was documented as checking for negative infinity as well, and + // almost surely should do that! + return Math.abs(d) === Number.POSITIVE_INFINITY; +}; + +FastMath._sign = function (d) { + if (!d) { + return 0; + } + return (d > 0) ? 1 : -1; +}; + +FastMath._atanhelper = function (s) { + var t = s * s; + var u = -1.88796008463073E-05; + u = u * t + (0.000209850076645817); + u = u * t + (-0.00110611831486672); + u = u * t + (0.00370026744188713); + u = u * t + (-0.00889896195887655); + u = u * t + (0.0165993297735292); + u = u * t + (-0.0254517624932313); + u = u * t + (0.0337852580001353); + u = u * t + (-0.0407629191276837); + u = u * t + (0.0466667150077841); + u = u * t + (-0.0523674852303482); + u = u * t + (0.0587666392926674); + u = u * t + (-0.0666573579361081); + u = u * t + (0.076921953831177); + u = u * t + (-0.090908995008245); + u = u * t + (0.111111105648261); + u = u * t + (-0.142857142667713); + u = u * t + (0.199999999996591); + u = u * t + (-0.333333333333311); + return u * t * s + s; +}; + +FastMath._atan2k = function (y, x) { + var q = 0; + if (x < 0) { + x = -x; + q = -2; + } + if (y > x) { + var t = x; + x = y; + y = -t; + q += 1; + } + return FastMath._atanhelper(y / x) + q * (Math.PI / 2); +}; + +// This method calculates the arc tangent of y/x in radians, using the signs of +// the two arguments to determine the quadrant of the result. The results may +// have maximum error of 2 ulps. +FastMath.atan2 = function (y, x) { + var r = FastMath._atan2k(Math.abs(y), x); + r = FastMath._mulsign(r, x); + if (FastMath._isinf(x) || !x) { + r = Math.PI / 2 - ((FastMath._isinf(x)) ? (FastMath._sign(x) * (Math.PI / 2)) : 0); + } + if (FastMath._isinf(y)) { + r = Math.PI / 2 - ((FastMath._isinf(x)) ? (FastMath._sign(x) * (Math.PI * 1 / 4)) : 0); + } + if (!y) { + r = ((FastMath._sign(x) === -1) ? Math.PI : 0); + } + return (FastMath._isnan(x) || FastMath._isnan(y)) ? Number.NaN : FastMath._mulsign(r, y); +}; + +// This method calculates the arc sine of x in radians. The return value is in +// the range [-pi/2, pi/2]. The results may have maximum error of 3 ulps. +FastMath.asin = function (d) { + return FastMath._mulsign(FastMath._atan2k(Math.abs(d), Math.sqrt((1 + d) * (1 - d))), d); +}; + +// This method calculates the arc cosine of x in radians. The return value is in +// the range [0, pi]. The results may have maximum error of 3 ulps. +FastMath.acos = function (d) { + return FastMath._mulsign(FastMath._atan2k(Math.sqrt((1 + d) * (1 - d)), Math.abs(d)), d) + ((d < 0) ? Math.PI : 0); +}; + +// Returns the arc tangent of an angle. The results may have maximum error of 2 +// ulps. +FastMath.atan = function (s) { + var q = 0; + if (s < 0) { + s = -s; + q = 2; + } + if (s > 1) { + s = 1 / s; + q |= 1; + } + var t = FastMath._atanhelper(s); + if (!!(q & 1)) { + t = 1.5707963267949 - t; + } + if (!!(q & 2)) { + t = -t; + } + return t; +}; + +FastMath._sincoshelper = function (d) { + var s = d * d; + var u = -7.97255955009038E-18; + u = u * s + 2.81009972710863E-15; + u = u * s - 7.64712219118159E-13; + u = u * s + 1.60590430605665E-10; + u = u * s - 2.50521083763502E-08; + u = u * s + 2.75573192239199E-06; + u = u * s - 0.000198412698412696; + u = u * s + 0.00833333333333333; + u = u * s - 0.166666666666667; + return s * u * d + d; +}; + +// Returns the trigonometric sine of an angle. The results may have maximum +// error of 2 ulps. +FastMath.sin = function (d) { + var u = d * m_1_PI; + var q = Math.floor((u < 0) ? u - 0.5 : u + 0.5); + var x = 4 * q; + d -= x * pI4_A; + d -= x * pI4_B; + d -= x * pI4_C; + if (!!(q & 1)) { + d = -d; + } + return FastMath._sincoshelper(d); +}; + +// Returns the trigonometric cosine of an angle. The results may have maximum +// error of 2 ulps. +FastMath.cos = function (d) { + var u = d * m_1_PI - 0.5; + var q = 1 + 2 * Math.floor((u < 0) ? u - 0.5 : u + 0.5); + var x = 2 * q; + d -= x * pI4_A; + d -= x * pI4_B; + d -= x * pI4_C; + if (!(q & 2)) { + d = -d; + } + return FastMath._sincoshelper(d); +}; + +var FastMath$ = {}; + +registerType("FastMath", [FastMath, FastMath$, null]); diff --git a/engine/esm/fits_properties.js b/engine/esm/fits_properties.js new file mode 100644 index 00000000..b58f02ba --- /dev/null +++ b/engine/esm/fits_properties.js @@ -0,0 +1,74 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Properties about FITS data. + +import { registerType, registerEnum } from "./typesystem.js"; + + +// wwtlib.ScaleTypes + +export var ScaleTypes = { + linear: 0, + log: 1, + power: 2, + squareRoot: 3, + histogramEqualization: 4 +}; + +registerType("ScaleTypes", ScaleTypes); +registerEnum("ScaleTypes", ScaleTypes); + + +// wwtlib.FitsProperties + +export function FitsProperties() { + this.bZero = 0; + this.bScale = 1; + this.containsBlanks = false; + this.blankValue = Number.MIN_VALUE; + this.maxVal = Number.MIN_VALUE; + this.minVal = Number.MAX_VALUE; + this.upperCut = Number.MIN_VALUE; + this.lowerCut = Number.MAX_VALUE; + this.transparentBlack = false; + this.colorMapName = 'viridis'; + this.scaleType = 0; + + // This field exists to support non-HiPS tiled FITS imagesets. We need a + // mechanism to notify callers when the top-level tile is loaded, + // because only after that has happened is it possible to set up + // trustworthy values for properties like LowerCut here. *HiPS* tiled + // FITS imagesets don't need this because they have a separate top-level + // "properties" file that can be used to trigger a callback. + // + // We need to load the top-level tile to properly set up the properties + // here because (1) they can't be determined well from the level-0 tile + // data alone, (2) we want to give the dataset author a chance to + // customize them, and (3) the tiled FITS data-loaders don't calculate + // min/max from the data for performance reasons. And we'd prefer not to + // add the relevant values to the ImageSet XML definition. + // + // Anyway, the tangent tile image loading code will cause this action to + // be triggered when the level-0 tile loads successfully. It would make + // sense to also trigger this action for when a non-tiled FITS file is + // loaded, but in that use case the existing WcsLoaded callback + // suffices. The tiling framework already uses WcsLoaded so for that + // case we need to add this extra hook. + this.onMainImageLoaded = null; + this.mainImageLoadedEventHasFired = false; +} + +var FitsProperties$ = { + // See description of the onMainImageLoaded field. This method exists to + // help non-HiPS tiled FITS datasets notify callers when the initial + // data have loaded and these FitsProperties can be trusted. + _fireMainImageLoaded: function (image) { + if (this.onMainImageLoaded != null && !this.mainImageLoadedEventHasFired) { + this.mainImageLoadedEventHasFired = true; + this.onMainImageLoaded(image); + } + } +}; + +registerType("FitsProperties", [FitsProperties, FitsProperties$, null]); diff --git a/engine/esm/folder.js b/engine/esm/folder.js new file mode 100644 index 00000000..0222d266 --- /dev/null +++ b/engine/esm/folder.js @@ -0,0 +1,524 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A WTML folder of different kinds of WWT content. + +import { ss } from "./ss.js"; +import { registerType, registerEnum } from "./typesystem.js"; +import { set_makeNewFolder } from "./data_globals.js"; +import { Util } from "./baseutil.js"; +import { IThumbnail } from "./interfaces.js"; +import { URLHelpers } from "./url_helpers.js"; +import { FolderUp } from "./folder_up.js"; +import { Imageset } from "./imageset.js"; +import { Place } from "./place.js"; +import { Tour } from "./tour.js"; +import { WebFile } from "./web_file.js"; + + +// wwtlib.FolderGroup + +export var FolderGroup = { + explorer: 0, + tour: 1, + search: 2, + constellation: 3, + view: 4, + goTo: 5, + community: 6, + context: 7, + voTable: 8, + imageStack: 9 +}; + +registerType("FolderGroup", FolderGroup); +registerEnum("FolderGroup", FolderGroup); + + +// wwtlib.FolderRefreshType + +export var FolderRefreshType = { + interval: 0, + conditionalGet: 1, + viewChange: 2 +}; + +registerType("FolderRefreshType", FolderRefreshType); +registerEnum("FolderRefreshType", FolderRefreshType); + + +// wwtlib.FolderType + +export var FolderType = { + earth: 0, + planet: 1, + sky: 2, + panorama: 3 +}; + +registerType("FolderType", FolderType); +registerEnum("FolderType", FolderType); + + +// wwtlib.Folder + +export function Folder() { + this.parent = null; + this.isProxy = false; + this._versionDependent = false; + this._readOnly = true; + this._dirty = false; + this._thumbnail = null; + this._proxyFolder = null; + this._lastUpdate = new Date(); + this._childList = []; + this._itemsField = []; + this._imagesets = []; + this._tours = []; + this._folders = []; + this._places = []; + this._groupField = 0; + this._refreshTypeField = 0; + this._refreshTypeFieldSpecified = false; + this._browseableField = true; + this._browseableFieldSpecified = false; + this._searchableField = false; + this._typeField = 0; + this._communityIdField = 0; + this._componentIdField = 0; + this._permissionField = 0; +} + +var Folder$ = { + toString: function () { + return this._nameField; + }, + + get_versionDependent: function () { + return this._versionDependent; + }, + + set_versionDependent: function (value) { + this._versionDependent = value; + var $enum1 = ss.enumerate(this._folders); + while ($enum1.moveNext()) { + var folder = $enum1.current; + folder.set_versionDependent(this._versionDependent); + } + return value; + }, + + get_readOnly: function () { + return this._readOnly; + }, + + set_readOnly: function (value) { + this._readOnly = value; + return value; + }, + + get_dirty: function () { + return this._dirty; + }, + + set_dirty: function (value) { + this._dirty = value; + return value; + }, + + loadFromUrlWithErrorCallback: function (url, complete, onError) { + this._onError = onError; + this.loadFromUrl(url, complete); + }, + + loadFromUrl: function (url, complete) { + this._onComplete = complete; + this._webFile = new WebFile(URLHelpers.singleton.rewrite(url, 1)); + this._webFile.onStateChange = ss.bind('_loadData', this); + this._webFile.send(); + }, + + _loadData: function () { + if (this._webFile.get_state() === 2) { + console.error(this._webFile.get_message()); + if (this._onError != null) { + this._onError(); + } + } else if (this._webFile.get_state() === 1) { + var node = Util.selectSingleNode(this._webFile.getXml(), 'Folder'); + if (node == null) { + var doc = this._webFile.getXml(); + if (doc != null) { + node = Util.selectSingleNode(doc, 'Folder'); + } + } + if (node != null) { + this._clearChildren(); + this._parseXML(node); + } + if (this._onComplete != null) { + this._onComplete(); + } + } + }, + + _clearChildren: function () { + this._folders.length = 0; + this._tours.length = 0; + this._places.length = 0; + this.get_imagesets().length = 0; + }, + + _parseXML: function (node) { + if (node.attributes.getNamedItem('Name') != null) { + this._nameField = node.attributes.getNamedItem('Name').nodeValue; + } else { + this._nameField = ''; + } + if (node.attributes.getNamedItem('Url') != null) { + this._urlField = node.attributes.getNamedItem('Url').nodeValue; + } + if (node.attributes.getNamedItem('Thumbnail') != null) { + this._thumbnailUrlField = node.attributes.getNamedItem('Thumbnail').nodeValue; + } + + // load Children + + var $enum1 = ss.enumerate(node.childNodes); + while ($enum1.moveNext()) { + var child = $enum1.current; + switch (child.nodeName) { + case 'Folder': + var temp = new Folder(); + temp.parent = this; + temp._parseXML(child); + this._folders.push(temp); + break; + case 'Place': + this._places.push(Place._fromXml(child)); + break; + case 'ImageSet': + this.get_imagesets().push(Imageset.fromXMLNode(child)); + break; + case 'Tour': + this.get_tours().push(Tour._fromXml(child)); + break; + } + } + }, + + addChildFolder: function (child) { + this._folders.push(child); + this._dirty = true; + }, + + removeChildFolder: function (child) { + ss.remove(this._folders, child); + this._dirty = true; + }, + + addChildPlace: function (child) { + this._places.push(child); + this._dirty = true; + }, + + removeChildPlace: function (child) { + ss.remove(this._places, child); + this._dirty = true; + }, + + get_thumbnail: function () { + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + return value; + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_isImage: function () { + return false; + }, + + get_isTour: function () { + return false; + }, + + get_isFolder: function () { + return true; + }, + + get_isCloudCommunityItem: function () { + return !!this._communityIdField || this._permissionField > 0; + }, + + refresh: function () { + if (this._proxyFolder == null) { + this._proxyFolder = new Folder(); + this._proxyFolder.isProxy = true; + this._proxyFolder.parent = this.parent; + } + + //Also listening to errors, to make sure clients do not wait forever in + //the case of a 404 or similar. Especially useful for recursive + //downloads, where potentially dozens of URL's are downloaded. In case + //of errors during downloads, the clients will have an empty folder + //during the callback. + this._proxyFolder.loadFromUrlWithErrorCallback(this._urlField, this._childReadyCallback, this._childReadyCallback); + this._childReadyCallback = null; + }, + + childLoadCallback: function (callback) { + this._childReadyCallback = callback; + var temp = this.get_children(); + if (this._proxyFolder == null) { + callback(); + } + }, + + get_children: function () { + if (ss.emptyString(this._urlField)) { + this._childList.length = 0; + if (this.parent != null) { + var folderUp = new FolderUp(); + folderUp.parent = this.parent; + this._childList.push(folderUp); + } + if (this.get_folders() != null) { + var $enum1 = ss.enumerate(this.get_folders()); + while ($enum1.moveNext()) { + var folder = $enum1.current; + this._childList.push(folder); + } + } + if (this.get_imagesets() != null) { + var $enum2 = ss.enumerate(this.get_imagesets()); + while ($enum2.moveNext()) { + var imset = $enum2.current; + this._childList.push(imset); + } + } + if (this.get_places() != null) { + var $enum3 = ss.enumerate(this.get_places()); + while ($enum3.moveNext()) { + var place = $enum3.current; + this._childList.push(place); + } + } + if (this.get_tours() != null) { + var $enum4 = ss.enumerate(this.get_tours()); + while ($enum4.moveNext()) { + var tour = $enum4.current; + this._childList.push(tour); + } + } + return this._childList; + } else { + var ts = (this._lastUpdate - ss.now()) / 1000; + if (this.get_refreshType() === 1 || this._proxyFolder == null || (!this.get_refreshType() && (parseInt(this._refreshIntervalField) < ts))) { + this.refresh(); + } + if (this._proxyFolder != null) { + return this._proxyFolder.get_children(); + } + else { + return null; + } + } + }, + + get_msrCommunityId: function () { + return this._communityIdField; + }, + + set_msrCommunityId: function (value) { + this._communityIdField = value; + return value; + }, + + get_msrComponentId: function () { + return this._componentIdField; + }, + + set_msrComponentId: function (value) { + this._componentIdField = value; + return value; + }, + + get_permission: function () { + return this._permissionField; + }, + + set_permission: function (value) { + this._permissionField = value; + return value; + }, + + get_folders: function () { + return this._folders; + }, + + set_folders: function (value) { + this._folders = value; + return value; + }, + + get_places: function () { + return this._places; + }, + + set_places: function (value) { + this._places = value; + return value; + }, + + get_imagesets: function () { + return this._imagesets; + }, + + set_imagesets: function (value) { + this._imagesets = value; + return value; + }, + + get_tours: function () { + return this._tours; + }, + + set_tours: function (value) { + this._tours = value; + return value; + }, + + get_name: function () { + if (this._nameField == null) { + return ''; + } else { + return this._nameField; + } + }, + + set_name: function (value) { + this._nameField = value; + return value; + }, + + get_group: function () { + return this._groupField; + }, + + set_group: function (value) { + this._groupField = value; + return value; + }, + + get_url: function () { + return this._urlField; + }, + + set_url: function (value) { + this._urlField = value; + return value; + }, + + get_thumbnailUrl: function () { + if (ss.emptyString(this._thumbnailUrlField)) { + return URLHelpers.singleton.engineAssetUrl('thumb_folder.jpg'); + } + return this._thumbnailUrlField; + }, + + set_thumbnailUrl: function (value) { + this._thumbnailUrlField = value; + return value; + }, + + get_refreshType: function () { + return this._refreshTypeField; + }, + + set_refreshType: function (value) { + this._refreshTypeField = value; + this.set_refreshTypeSpecified(true); + return value; + }, + + get_refreshTypeSpecified: function () { + return this._refreshTypeFieldSpecified; + }, + + set_refreshTypeSpecified: function (value) { + this._refreshTypeFieldSpecified = value; + return value; + }, + + get_refreshInterval: function () { + return this._refreshIntervalField; + }, + + set_refreshInterval: function (value) { + this._refreshIntervalField = value; + return value; + }, + + get_browseable: function () { + return this._browseableField; + }, + + set_browseable: function (value) { + this._browseableField = value; + this._browseableFieldSpecified = true; + return value; + }, + + get_browseableSpecified: function () { + return this._browseableFieldSpecified; + }, + + set_browseableSpecified: function (value) { + this._browseableFieldSpecified = value; + return value; + }, + + get_searchable: function () { + return this._searchableField; + }, + + set_searchable: function (value) { + this._searchableField = value; + return value; + }, + + get_type: function () { + return this._typeField; + }, + + set_type: function (value) { + this._typeField = value; + return value; + }, + + get_subType: function () { + return this._subTypeField; + }, + + set_subType: function (value) { + this._subTypeField = value; + return value; + } +}; + +registerType("Folder", [Folder, Folder$, null, IThumbnail]); + +set_makeNewFolder(function () { + return new Folder(); +}); diff --git a/engine/esm/folder_browser.js b/engine/esm/folder_browser.js new file mode 100644 index 00000000..3b955db7 --- /dev/null +++ b/engine/esm/folder_browser.js @@ -0,0 +1,483 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Infrastructure for browsing the WWT folder structure. + +import { ss } from "./ss.js"; +import { registerType, registerEnum } from "./typesystem.js"; +import { globalWWTControl } from "./data_globals.js"; +import { globalRenderContext } from "./render_globals.js"; +import { Vector2d } from "./double3d.js"; +import { Folder } from "./folder.js"; +import { FolderUp } from "./folder_up.js"; +import { Imageset } from "./imageset.js"; +import { Place } from "./place.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Tour } from "./tour.js"; +import { Mouse, Rectangle } from "./util.js"; + + +// wwtlib.ThumbnailSize + +export var ThumbnailSize = { + small: 0, + big: 1 +}; + +registerType("ThumbnailSize", ThumbnailSize); +registerEnum("ThumbnailSize", ThumbnailSize); + + +// wwtlib.FolderBrowser + +export function FolderBrowser() { + this._items = []; + this.top = 10; + this.left = 10; + this._indexTouchDown = -1; + this._mouseDown = false; + this._lastX = 0; + this._lastY = 0; + this._ignoreClick = false; + this._thumbnailSize = 0; + this._horzSpacing = 110; + this._vertSpacing = 75; + this._thumbHeight = 65; + this._thumbWidth = 110; + this._horzMultiple = 110; + this._rowCount = 1; + this._colCount = 6; + this._dragging = false; + this._startIndex = 0; + this._startOffset = 0; + this._selectedItem = -1; + this._hoverItem = -1; + this.showAddButton = false; + this.width = 0; + this.height = 0; + this._addButtonHover = false; + this.imageClicked = false; +} + +FolderBrowser._downloading = false; +FolderBrowser._imagesLoaded = false; +FolderBrowser._imageLoadCount = 0; + +FolderBrowser.create = function () { + var temp = new FolderBrowser(); + temp.height = 85; + temp.width = 1920; + temp.canvas = document.createElement('canvas'); + temp.canvas.width = temp.width; + temp.canvas.height = temp.height; + temp.setup(); + temp.loadImages(); + return temp; +}; + +var FolderBrowser$ = { + setup: function () { + this.canvas.addEventListener('click', ss.bind('onClick', this), false); + this.canvas.addEventListener('dblclick', ss.bind('onDoubleClick', this), false); + this.canvas.addEventListener('mousemove', ss.bind('onMouseMove', this), false); + this.canvas.addEventListener('mouseup', ss.bind('onMouseUp', this), false); + this.canvas.addEventListener('mousedown', ss.bind('onMouseDown', this), false); + this.canvas.addEventListener('touchstart', ss.bind('onTouchStart', this), false); + this.canvas.addEventListener('touchmove', ss.bind('onTouchMove', this), false); + this.canvas.addEventListener('touchend', ss.bind('onTouchEnd', this), false); + this.canvas.addEventListener('mouseout', ss.bind('onMouseUp', this), false); + }, + + onTouchStart: function (e) { + var ev = e; + ev.preventDefault(); + this._mouseDown = true; + this._lastX = ev.targetTouches[0].pageX; + this._lastY = ev.targetTouches[0].pageY; + this._indexTouchDown = this._getItemIndexFromCursor(Vector2d.create(ev.targetTouches[0].pageX, ev.targetTouches[0].pageY)); + }, + + onTouchMove: function (e) { + var ev = e; + ev.preventDefault(); + if (this._mouseDown) { + var curX = ev.targetTouches[0].pageX - this._lastX; + var curY = ev.targetTouches[0].pageY - this._lastY; + if (this._mouseDown) { + this._dragging = true; + } + if (!this._dragging) { + var newHover = this._getItemIndexFromCursor(Vector2d.create(ev.targetTouches[0].pageX, ev.targetTouches[0].pageY)); + if (this._hoverItem !== newHover) { + this._hoverItem = newHover; + } + } + else { + var tiles = Math.round(((ev.targetTouches[0].pageX - this._lastX) + this._startOffset) / this._horzSpacing); + var offset = Math.round(((ev.targetTouches[0].pageX - this._lastX) + this._startOffset) - (tiles * this._horzSpacing)); + this._startOffset = offset; + this._startIndex -= tiles; + if (this._startIndex < 0) { + this._startOffset -= (this._horzSpacing * this._startIndex); + this._startIndex = 0; + } + this._lastX = ev.targetTouches[0].pageX; + this._lastY = ev.targetTouches[0].pageY; + } + this.refresh(); + } + }, + + onTouchEnd: function (e) { + var ev = e; + ev.preventDefault(); + if (this._dragging) { + this._dragging = false; + this._ignoreClick = true; + } else if (this._indexTouchDown > -1 && this._mouseDown) { + this._handleClick(this._indexTouchDown); + } + this._startOffset = 0; + this._mouseDown = false; + this.refresh(); + }, + + onClick: function (e) { + if (!this._ignoreClick) { + var index = this._getItemIndexFromCursor(Vector2d.create(e.offsetX, e.offsetY)); + this._handleClick(index); + } else { + this._ignoreClick = false; + } + }, + + _handleClick: function (index) { + var $this = this; + + if (index > -1) { + if (ss.canCast(this._items[index], Place)) { + var place = this._items[index]; + globalWWTControl.gotoTarget(place, false, false, true); + return; + } + if (ss.canCast(this._items[index], Imageset)) { + var imageset = this._items[index]; + globalRenderContext.set_backgroundImageset(imageset); + return; + } + if (ss.canCast(this._items[index], Tour)) { + var tour = this._items[index]; + globalWWTControl.playTour(tour.get_tourUrl()); + return; + } + if (ss.canCast(this._items[index], Folder)) { + var folder = this._items[index]; + this._startIndex = 0; + folder.childLoadCallback(function () { + $this._items = folder.get_children(); + $this.refresh(); + }); + return; + } + if (ss.canCast(this._items[index], FolderUp)) { + var folderUp = this._items[index]; + if (folderUp.parent != null) { + this._startIndex = 0; + folderUp.parent.childLoadCallback(function () { + $this._items = folderUp.parent.get_children(); + $this.refresh(); + }); + } + return; + } + } + return; + }, + + onDoubleClick: function (e) { + RenderTriangle.renderingOn = !RenderTriangle.renderingOn; + }, + + onGestureChange: function (e) { + var g = e; + this._mouseDown = false; + var delta = g.scale; + }, + + onMouseDown: function (e) { + this._mouseDown = true; + this._lastX = Mouse.offsetX(this.canvas, e); + this._lastY = Mouse.offsetY(this.canvas, e); + }, + + onMouseMove: function (e) { + if (this._mouseDown) { + this._dragging = true; + } + if (!this._dragging) { + var newHover = this._getItemIndexFromCursor(Vector2d.create(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e))); + if (this._hoverItem !== newHover) { + this._hoverItem = newHover; + } + } else { + var tiles = Math.round(((Mouse.offsetX(this.canvas, e) - this._lastX) + this._startOffset) / this._horzSpacing); + var offset = Math.round(((Mouse.offsetX(this.canvas, e) - this._lastX) + this._startOffset) - (tiles * this._horzSpacing)); + this._startOffset = offset; + this._startIndex -= tiles; + if (this._startIndex < 0) { + this._startOffset -= (this._horzSpacing * this._startIndex); + this._startIndex = 0; + } + this._lastX = Mouse.offsetX(this.canvas, e); + this._lastY = Mouse.offsetY(this.canvas, e); + } + this.refresh(); + }, + + onMouseUp: function (e) { + if (this._dragging) { + this._startOffset = 0; + this._dragging = false; + this._ignoreClick = true; + } + this._mouseDown = false; + this.refresh(); + }, + + loadImages: function () { + var $this = this; + + if (!FolderBrowser._imagesLoaded && !FolderBrowser._downloading) { + FolderBrowser._imageLoadCount = 0; + FolderBrowser._imagesLoaded = false; + FolderBrowser._downloading = true; + FolderBrowser._bmpBackground = document.createElement('img'); + FolderBrowser._bmpBackground.src = 'images/thumbBackground.png'; + FolderBrowser._bmpBackground.addEventListener('load', function (e) { + FolderBrowser._imageLoadCount++; + if (FolderBrowser._imageLoadCount === 5) { + FolderBrowser._downloading = false; + FolderBrowser._imagesLoaded = true; + $this.refresh(); + } + }, false); + FolderBrowser._bmpBackgroundHover = document.createElement('img'); + FolderBrowser._bmpBackgroundHover.src = 'images/thumbBackgroundHover.png'; + FolderBrowser._bmpBackgroundHover.addEventListener('load', function (e) { + FolderBrowser._imageLoadCount++; + if (FolderBrowser._imageLoadCount === 5) { + FolderBrowser._downloading = false; + FolderBrowser._imagesLoaded = true; + $this.refresh(); + } + }, false); + FolderBrowser._bmpBackgroundWide = document.createElement('img'); + FolderBrowser._bmpBackgroundWide.src = 'images/thumbBackgroundWide.png'; + FolderBrowser._bmpBackgroundWide.addEventListener('load', function (e) { + FolderBrowser._imageLoadCount++; + if (FolderBrowser._imageLoadCount === 5) { + FolderBrowser._downloading = false; + FolderBrowser._imagesLoaded = true; + $this.refresh(); + } + }, false); + FolderBrowser._bmpBackgroundWideHover = document.createElement('img'); + FolderBrowser._bmpBackgroundWideHover.src = 'images/thumbBackgroundWideHover.png'; + FolderBrowser._bmpBackgroundWideHover.addEventListener('load', function (e) { + FolderBrowser._imageLoadCount++; + if (FolderBrowser._imageLoadCount === 5) { + FolderBrowser._downloading = false; + FolderBrowser._imagesLoaded = true; + $this.refresh(); + } + }, false); + FolderBrowser._bmpDropInsertMarker = document.createElement('img'); + FolderBrowser._bmpDropInsertMarker.src = 'images/dragInsertMarker.png'; + FolderBrowser._bmpDropInsertMarker.addEventListener('load', function (e) { + FolderBrowser._imageLoadCount++; + if (FolderBrowser._imageLoadCount === 5) { + FolderBrowser._downloading = false; + FolderBrowser._imagesLoaded = true; + $this.refresh(); + } + }, false); + } + }, + + get_thumbnailSize: function () { + return this._thumbnailSize; + }, + + set_thumbnailSize: function (value) { + this._thumbnailSize = value; + switch (value) { + case 1: + this._horzSpacing = 180; + this._vertSpacing = 75; + this._thumbHeight = 65; + this._thumbWidth = 180; + break; + case 0: + this._horzSpacing = 110; + this._vertSpacing = 75; + this._thumbHeight = 65; + this._thumbWidth = 110; + break; + } + this._updatePaginator(); + this.refresh(); + return value; + }, + + refresh: function () { + if (this.width !== window.innerWidth) { + this.width = window.innerWidth; + } + this.paint(); + }, + + get_rowCount: function () { + return this._rowCount; + }, + + set_rowCount: function (value) { + if (this._rowCount !== value) { + this._rowCount = value; + this._updatePaginator(); + } + return value; + }, + + _updatePaginator: function () { }, + + get_colCount: function () { + return this._colCount; + }, + + set_colCount: function (value) { + if (this._colCount !== value) { + this._colCount = value; + this._updatePaginator(); + } + return value; + }, + + get_itemsPerPage: function () { + return this._rowCount * this._colCount; + }, + + get_currentPage: function () { + return this._startIndex / this.get_itemsPerPage(); + }, + + get_pageCount: function () { + return Math.max(1, ((this._items.length + this.get_itemsPerPage() - 1) + ((this.showAddButton) ? 1 : 0)) / this.get_itemsPerPage()); + }, + + paint: function () { + var $this = this; + + var g = this.canvas.getContext('2d'); + g.fillStyle = 'rgb(20, 22, 31)'; + g.fillRect(0, 0, this.width, this.height); + if (!FolderBrowser._imagesLoaded) { + return; + } + var netHeight = (this.height - 10 * 2); + var netWidth = (this.width - 10 * 2); + this.set_rowCount(Math.round(Math.max(netHeight / this._thumbHeight, 1))); + this.set_colCount(Math.round(Math.max(netWidth / this._horzSpacing, 1))); + this._horzMultiple = (netWidth + 13) / this.get_colCount(); + this._startIndex = Math.round((this._startIndex / this.get_itemsPerPage()) * this.get_itemsPerPage()); + var rectf; + var index = this._startIndex; + for (var y = 0; y < this._rowCount; y++) { + for (var x = 0; x < this._colCount; x++) { + if (index >= this._items.length) { + if (!this._items.length || this.showAddButton) { + rectf = Rectangle.create(this.left + x * this._horzMultiple + 3 + this._startOffset, this.top + y * this._vertSpacing, this._thumbWidth - 10, 60); + g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWide : FolderBrowser._bmpBackground, ss.truncate((x * this._horzMultiple)) + this._startOffset, y * this._vertSpacing); + } + break; + } + rectf = Rectangle.create(this.left + x * this._horzMultiple + 3 + this._startOffset, this.top + y * this._vertSpacing, this._thumbWidth - 14, 60); + var textBrush = 'white'; + if (index === this._hoverItem || (index === this._selectedItem && this._hoverItem === -1)) { + g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWideHover : FolderBrowser._bmpBackgroundHover, this.left + ss.truncate((x * this._horzMultiple)) + this._startOffset, this.top + y * this._vertSpacing); + textBrush = 'yellow'; + } + else { + g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWide : FolderBrowser._bmpBackground, this.left + ss.truncate((x * this._horzMultiple)) + this._startOffset, this.top + y * this._vertSpacing); + } + this._items[index].set_bounds(Rectangle.create((this.left + x * this._horzMultiple) + this._startOffset, this.top + (y * this._vertSpacing), ss.truncate(this._horzMultiple), this._vertSpacing)); + try { + var bmpThumb = this._items[index].get_thumbnail(); + if (bmpThumb != null) { + g.drawImage(bmpThumb, this.left + (x * this._horzMultiple) + 2 + this._startOffset, this.top + y * this._vertSpacing + 3); + g.strokeStyle = 'rgb(0,0,0)'; + g.rect(this.left + ss.truncate((x * this._horzMultiple)) + 2 + this._startOffset, this.top + y * this._vertSpacing + 3, this._items[index].get_thumbnail().width, this._items[index].get_thumbnail().height); + } + else { + this._items[index].set_thumbnail(document.createElement('img')); + this._items[index].get_thumbnail().src = this._items[index].get_thumbnailUrl(); + this._items[index].get_thumbnail().addEventListener('load', function (e) { + $this.refresh(); + }, false); + } + } + catch ($e1) { + } + g.fillStyle = textBrush; + g.strokeStyle = textBrush; + g.lineWidth = 1; + g.font = 'normal 8pt Arial'; + g.fillText(this._items[index].get_name(), rectf.x, rectf.y + rectf.height, rectf.width); + index++; + } + if (index >= this._items.length) { + break; + } + } + }, + + _getItemIndexFromCursor: function (testPointIn) { + var testPoint = Vector2d.create(testPointIn.x + this.left, testPointIn.y + this.top); + this.imageClicked = false; + var index = -1; + var xpos = ss.truncate((testPoint.x / this._horzMultiple)); + var xPart = ss.truncate((testPoint.x % this._horzMultiple)); + if (xpos >= this._colCount) { + return -1; + } + if (xpos < 0) { + return -1; + } + var ypos = ss.truncate((testPoint.y / this._vertSpacing)); + var yPart = ss.truncate((testPoint.y % this._vertSpacing)); + if (ypos >= this._rowCount) { + return -1; + } + if (ypos < 0) { + return -1; + } + index = this._startIndex + ypos * this._colCount + xpos; + if (index === this._items.length) { + this._addButtonHover = true; + } else { + this._addButtonHover = false; + } + if (index > this._items.length - 1) { + return -1; + } + if ((this._items[index]).get_isImage() && yPart < 16 && xPart > 78) { + this.imageClicked = true; + } + return index; + }, + + _addItems: function (list) { + this._items = list; + } +}; + +registerType("FolderBrowser", [FolderBrowser, FolderBrowser$, null]); diff --git a/engine/esm/folder_up.js b/engine/esm/folder_up.js new file mode 100644 index 00000000..eeba5050 --- /dev/null +++ b/engine/esm/folder_up.js @@ -0,0 +1,79 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// An icon for a "move up one folder" item. + +import { registerType } from "./typesystem.js"; +import { IThumbnail } from "./interfaces.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Rectangle } from "./util.js"; + + +// wwtlib.FolderUp + +export function FolderUp() { + this.parent = null; + this._bounds = new Rectangle(); +} + +var FolderUp$ = { + get_name: function () { + return 'Up Level'; + }, + + get_thumbnail: function () { + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + return value; + }, + + get_thumbnailUrl: function () { + return URLHelpers.singleton.engineAssetUrl('thumb_folderup.jpg'); + }, + + set_thumbnailUrl: function (value) { + return value; + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_isImage: function () { + return false; + }, + + get_isTour: function () { + return false; + }, + + get_isFolder: function () { + return false; + }, + + get_isCloudCommunityItem: function () { + return false; + }, + + get_readOnly: function () { + return false; + }, + + get_children: function () { + if (this.parent == null) { + return []; + } else { + return this.parent.get_children(); + } + } +}; + +registerType("FolderUp", [FolderUp, FolderUp$, null, IThumbnail]); diff --git a/engine/esm/fxyf.js b/engine/esm/fxyf.js new file mode 100644 index 00000000..72124bea --- /dev/null +++ b/engine/esm/fxyf.js @@ -0,0 +1,132 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Numerical routines supporting the Healpix implementation. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { HealpixTables } from "./healpix_tables.js"; +import { HealpixUtils } from "./healpix_utils.js"; +import { Hploc } from "./hploc.js"; + + +// wwtlib.Fxyf + +export function Fxyf() { + // x-coordinate within the basis pixel, range [0.0;1.0] + this.fx = 0; + + // y-coordinate within the basis pixel, range [0.0;1.0] + this.fy = 0; + + // index of the HEALPix basis pixel, range [0;11] + this.face = 0; + HealpixTables.call(this); +} + +Fxyf._halfpi$1 = Math.PI / 2; +Fxyf._inv_halfpi$1 = 2 / Math.PI; +Fxyf._twothird$1 = 2 / 3; + +Fxyf.create = function (x, y, f) { + var temp = new Fxyf(); + temp.fx = x; + temp.fy = y; + temp.face = f; + return temp; +}; + +Fxyf._fromHploc$1 = function (loc) { + var temp = new Fxyf(); + var z = loc.z, phi = loc.phi; + var za = Math.abs(z); + var tt = HealpixUtils.fmodulo((phi * Fxyf._inv_halfpi$1), 4); // in [0,4) + + if (za <= Fxyf._twothird$1) { // Equatorial region + var temp1 = 0.5 + tt; + var temp2 = z * 0.75; + var jp = temp1 - temp2; // index of ascending edge line + var jm = temp1 + temp2; // index of descending edge line + var ifp = jp; // in {0,4} + var ifm = jm; + var face_num = (ifp === ifm) ? (ifp | 4) : ((ifp < ifm) ? ifp : (ifm + 8)); + temp.fx = HealpixUtils.fmodulo(jm, 1); + temp.fy = 1 - HealpixUtils.fmodulo(jp, 1); + temp.face = face_num; + } else { // polar region, za > 2/3 + var ntt = Math.min(3, ss.truncate(tt)); + var tp = tt - ntt; + var tmp; + if ((za < 0.99) || (!loc.have_sth)) { + tmp = Math.sqrt(3 * (1 - za)); + } else { + tmp = loc.sth / Math.sqrt((1 + za) / 3); + } + var jp = tp * tmp; // increasing edge line index + var jm = (1 - tp) * tmp; // decreasing edge line index + if (jp >= 1) { + jp = 1; // for points too close to the boundary + } + if (jm >= 1) { + jm = 1; + } + if (z >= 0) { + temp.fx = 1 - jm; + temp.fy = 1 - jp; + temp.face = ntt; + } else { + temp.fx = jp; + temp.fy = jm; + temp.face = ntt + 8; + } + } + return temp; +}; + +Fxyf.fromVector = function (v) { + return Fxyf._fromHploc$1(Hploc.create(v)); +}; + +var Fxyf$ = { + toHploc: function () { + var loc = new Hploc(); + var jr = HealpixTables.jrll[this.face] - this.fx - this.fy; + var nr; + var tmp; + if (jr < 1) { + nr = jr; + tmp = nr * nr / 3; + loc.z = 1 - tmp; + if (loc.z > 0.99) { + loc.sth = Math.sqrt(tmp * (2 - tmp)); + loc.have_sth = true; + } + } else if (jr > 3) { + nr = 4 - jr; + tmp = nr * nr / 3; + loc.z = tmp - 1; + if (loc.z < -0.99) { + loc.sth = Math.sqrt(tmp * (2 - tmp)); + loc.have_sth = true; + } + } else { + nr = 1; + loc.z = (2 - jr) * 2 / 3; + } + tmp = HealpixTables.jpll[this.face] * nr + this.fx - this.fy; + if (tmp < 0) { + tmp += 8; + } + if (tmp >= 8) { + tmp -= 8; + } + loc.phi = (nr < 1E-15) ? 0 : (0.5 * Fxyf._halfpi$1 * tmp) / nr; + return loc; + }, + + toVec3: function () { + return this.toHploc().toVec3(); + } +}; + +registerType("Fxyf", [Fxyf, Fxyf$, HealpixTables]); diff --git a/engine/esm/graphics/gl_buffers.js b/engine/esm/graphics/gl_buffers.js new file mode 100644 index 00000000..b4e943c4 --- /dev/null +++ b/engine/esm/graphics/gl_buffers.js @@ -0,0 +1,458 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// WebGL buffer types. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { tilePrepDevice } from "../render_globals.js"; +import { WEBGL } from "./webgl_constants.js"; + + +// wwtlib.ShortIndexBuffer + +export function ShortIndexBuffer(indexes) { + this.buffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this.buffer); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, indexes, WEBGL.STATIC_DRAW); +} + +var ShortIndexBuffer$ = {}; + +registerType("ShortIndexBuffer", [ShortIndexBuffer, ShortIndexBuffer$, null]); + + +// wwtlib.IndexBuffer + +export function IndexBuffer(indexes) { + this.buffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this.buffer); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, indexes, WEBGL.STATIC_DRAW); +} + +var IndexBuffer$ = { + dispose: function () { + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + tilePrepDevice.deleteBuffer(this.buffer); + this.buffer = null; + } +}; + +registerType("IndexBuffer", [IndexBuffer, IndexBuffer$, null, ss.IDisposable]); + + +// wwtlib.VertexBufferBase + +export function VertexBufferBase() { } + +var VertexBufferBase$ = { + dispose: function () { + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, null); + tilePrepDevice.deleteBuffer(this.vertexBuffer); + this.vertexBuffer = null; + } +}; + +registerType("VertexBufferBase", [VertexBufferBase, VertexBufferBase$, null, ss.IDisposable]); + + +// wwtlib.PositionVertexBuffer + +export function PositionVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +var PositionVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 3); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.x; + buffer[index++] = pt.y; + buffer[index++] = pt.z; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionVertexBuffer", [PositionVertexBuffer, PositionVertexBuffer$, VertexBufferBase]); + + +// wwtlib.PositionTextureVertexBuffer + +export function PositionTextureVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +PositionTextureVertexBuffer.create = function (data) { + var buffer = new PositionTextureVertexBuffer(data.length); + buffer._verts$1 = data; + buffer.unlock(); + return buffer; +}; + +var PositionTextureVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 5); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionTextureVertexBuffer", [PositionTextureVertexBuffer, PositionTextureVertexBuffer$, VertexBufferBase]); + + +// wwtlib.PositionNormalTexturedVertexBuffer + +export function PositionNormalTexturedVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +PositionNormalTexturedVertexBuffer.create = function (data) { + var buffer = new PositionNormalTexturedVertexBuffer(data.length); + buffer._verts$1 = data; + buffer.unlock(); + return buffer; +}; + +var PositionNormalTexturedVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 8); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.x; + buffer[index++] = pt.y; + buffer[index++] = pt.z; + buffer[index++] = pt.nx; + buffer[index++] = pt.ny; + buffer[index++] = pt.nz; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionNormalTexturedVertexBuffer", [PositionNormalTexturedVertexBuffer, PositionNormalTexturedVertexBuffer$, VertexBufferBase]); + + +// wwtlib.PositionNormalTexturedTangentVertexBuffer + +export function PositionNormalTexturedTangentVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +PositionNormalTexturedTangentVertexBuffer.create = function (data) { + var buffer = new PositionNormalTexturedTangentVertexBuffer(data.length); + buffer._verts$1 = data; + buffer.unlock(); + return buffer; +}; + +var PositionNormalTexturedTangentVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 11); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.x; + buffer[index++] = pt.y; + buffer[index++] = pt.z; + buffer[index++] = pt.nx; + buffer[index++] = pt.ny; + buffer[index++] = pt.nz; + buffer[index++] = pt.tanx; + buffer[index++] = pt.tany; + buffer[index++] = pt.tanz; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionNormalTexturedTangentVertexBuffer", [PositionNormalTexturedTangentVertexBuffer, PositionNormalTexturedTangentVertexBuffer$, VertexBufferBase]); + + +// wwtlib.KeplerVertexBuffer + +export function KeplerVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +KeplerVertexBuffer.create = function (items) { + var tmp = new KeplerVertexBuffer(items.length); + tmp._verts$1 = items; + return tmp; +}; + +var KeplerVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 19); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.ABC.x; + buffer[index++] = pt.ABC.y; + buffer[index++] = pt.ABC.z; + buffer[index++] = pt.abc1.x; + buffer[index++] = pt.abc1.y; + buffer[index++] = pt.abc1.z; + buffer[index++] = pt.pointSize; + buffer[index++] = pt.color.r / 255; + buffer[index++] = pt.color.g / 255; + buffer[index++] = pt.color.b / 255; + buffer[index++] = pt.color.a / 255; + buffer[index++] = pt.w; + buffer[index++] = pt.e; + buffer[index++] = pt.n; + buffer[index++] = pt.t; + buffer[index++] = pt.a; + buffer[index++] = pt.z; + buffer[index++] = pt.orbitPos; + buffer[index++] = pt.orbits; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("KeplerVertexBuffer", [KeplerVertexBuffer, KeplerVertexBuffer$, VertexBufferBase]); + + +// wwtlib.TimeSeriesLineVertexBuffer + +export function TimeSeriesLineVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +var TimeSeriesLineVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 9); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.get_color().r / 255; + buffer[index++] = pt.get_color().g / 255; + buffer[index++] = pt.get_color().b / 255; + buffer[index++] = pt.get_color().a / 255; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("TimeSeriesLineVertexBuffer", [TimeSeriesLineVertexBuffer, TimeSeriesLineVertexBuffer$, VertexBufferBase]); + + +// wwtlib.TimeSeriesPointVertexBuffer + +export function TimeSeriesPointVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +var TimeSeriesPointVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 10); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.get_color().r / 255; + buffer[index++] = pt.get_color().g / 255; + buffer[index++] = pt.get_color().b / 255; + buffer[index++] = pt.get_color().a / 255; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + buffer[index++] = pt.pointSize; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + }, + + dispose: function () { + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, null); + tilePrepDevice.deleteBuffer(this.vertexBuffer); + this.vertexBuffer = null; + } +}; + +registerType("TimeSeriesPointVertexBuffer", [TimeSeriesPointVertexBuffer, TimeSeriesPointVertexBuffer$, VertexBufferBase]); + + +// wwtlib.PositionColoredVertexBuffer + +export function PositionColoredVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +var PositionColoredVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 7); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.color.r / 255; + buffer[index++] = pt.color.g / 255; + buffer[index++] = pt.color.b / 255; + buffer[index++] = pt.color.a / 255; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionColoredVertexBuffer", [PositionColoredVertexBuffer, PositionColoredVertexBuffer$, VertexBufferBase]); + + +// wwtlib.PositionColoredTexturedVertexBuffer + +export function PositionColoredTexturedVertexBuffer(count) { + this.count = 0; + this._verts$1 = null; + VertexBufferBase.call(this); + this.count = count; +} + +var PositionColoredTexturedVertexBuffer$ = { + lock: function () { + this._verts$1 = new Array(this.count); + return this._verts$1; + }, + + unlock: function () { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(this.count * 9); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._verts$1); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.color.r / 255; + buffer[index++] = pt.color.g / 255; + buffer[index++] = pt.color.b / 255; + buffer[index++] = pt.color.a / 255; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + } +}; + +registerType("PositionColoredTexturedVertexBuffer", [PositionColoredTexturedVertexBuffer, PositionColoredTexturedVertexBuffer$, VertexBufferBase]); diff --git a/engine/esm/graphics/primitives3d.js b/engine/esm/graphics/primitives3d.js new file mode 100644 index 00000000..aa19410a --- /dev/null +++ b/engine/esm/graphics/primitives3d.js @@ -0,0 +1,929 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Various GL primitives. + +import { registerType, registerEnum } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { Matrix3d, Vector3d, PositionColored } from "../double3d.js"; +import { Color } from "../color.js"; +import { URLHelpers } from "../url_helpers.js"; +import { WEBGL } from "./webgl_constants.js"; +import { + PositionVertexBuffer, + PositionColoredVertexBuffer, + TimeSeriesLineVertexBuffer, + TimeSeriesPointVertexBuffer, +} from "./gl_buffers.js"; +import { Texture } from "./texture.js"; +import { + SimpleLineShader, + SimpleLineShader2D, + OrbitLineShader, + LineShaderNormalDates, + TimeSeriesPointSpriteShader, +} from "./shaders.js"; + + +// wwtlib.CullMode + +export var CullMode = { + none: 0, + counterClockwise: 2, + clockwise: 1 +}; + +registerType("CullMode", CullMode); +registerEnum("CullMode", CullMode); + + +// wwtlib.PointScaleTypes + +export var PointScaleTypes = { + linear: 0, + power: 1, + log: 2, + constant: 3, + stellarMagnitude: 4 +}; + +registerType("PointScaleTypes", PointScaleTypes); +registerEnum("PointScaleTypes", PointScaleTypes); + + +// wwtlib.DataItem +// +// This type was originally defined in VizLayer.cs, but it's quite simple +// and is used here. + +export function DataItem() { + this.size = 0; +} + +var DataItem$ = { + getColor: function () { + return 'Red'; + } +}; + +registerType("DataItem", [DataItem, DataItem$, null]); + + +// wwtlib.Dates + +export function Dates(start, end) { + this.startDate = 0; + this.endDate = 0; + this.startDate = start; + this.endDate = end; +} + +Dates.empty = function () { + return new Dates(0, 0); +}; + +var Dates$ = { + copy: function () { + return new Dates(this.startDate, this.endDate); + } +}; + +registerType("Dates", [Dates, Dates$, null]); + + +// wwtlib.SimpleLineList + +export function SimpleLineList() { + this._zBuffer = true; + this._linePoints = []; + this._usingLocalCenter = false; + this.sky = true; + this.aaFix = true; + this.pure2D = false; + this.viewTransform = Matrix3d.get_identity(); + this._lineBuffers = []; + this._lineBufferCounts = []; + this.useLocalCenters = false; +} + +var SimpleLineList$ = { + get_depthBuffered: function () { + return this._zBuffer; + }, + + set_depthBuffered: function (value) { + this._zBuffer = value; + return value; + }, + + addLine: function (v1, v2) { + this._linePoints.push(v1); + this._linePoints.push(v2); + this._emptyLineBuffer(); + }, + + clear: function () { + this._linePoints.length = 0; + this._emptyLineBuffer(); + }, + + drawLines: function (renderContext, opacity, color) { + if (this._linePoints.length < 2) { + return; + } + this._initLineBuffer(renderContext); + var count = this._linePoints.length; + if (renderContext.gl == null) { + var viewPoint = Vector3d._transformCoordinate(renderContext.get_viewPoint(), this.viewTransform); + var ctx = renderContext.device; + ctx.save(); + ctx.strokeStyle = color.toString(); + ctx.lineWidth = 2; + ctx.globalAlpha = 0.25; + var firstPoint = new Vector3d(); + var secondPoint = new Vector3d(); + for (var i = 0; i < count; i += 2) { + firstPoint = renderContext.WVP.transform(this._linePoints[i]); + secondPoint = renderContext.WVP.transform(this._linePoints[i + 1]); + if (Vector3d.dot(this._linePoints[i], viewPoint) > 0.6) { + ctx.beginPath(); + ctx.moveTo(firstPoint.x, firstPoint.y); + ctx.lineTo(secondPoint.x, secondPoint.y); + ctx.stroke(); + } + } + ctx.restore(); + } else { + var $enum1 = ss.enumerate(this._lineBuffers); + while ($enum1.moveNext()) { + var lineBuffer = $enum1.current; + if (this.pure2D) { + SimpleLineShader2D.use(renderContext, lineBuffer.vertexBuffer, color, this._zBuffer); + } + else { + SimpleLineShader.use(renderContext, lineBuffer.vertexBuffer, color, this._zBuffer); + } + renderContext.gl.drawArrays(WEBGL.LINES, 0, lineBuffer.count); + } + } + }, + + _initLineBuffer: function (renderContext) { + if (renderContext.gl != null) { + if (!this._lineBuffers.length) { + var count = this._linePoints.length; + var lineBuffer = null; + var linePointList = null; + this._localCenter = new Vector3d(); + if (this.get_depthBuffered()) { + var $enum1 = ss.enumerate(this._linePoints); + + // compute the local center + while ($enum1.moveNext()) { + var point = $enum1.current; + this._localCenter.add(point); + } + this._localCenter.x /= count; + this._localCenter.y /= count; + this._localCenter.z /= count; + } + var countLeft = count; + var index = 0; + var counter = 0; + var temp; + var $enum2 = ss.enumerate(this._linePoints); + while ($enum2.moveNext()) { + var point = $enum2.current; + if (counter >= 100000 || linePointList == null) { + if (lineBuffer != null) { + lineBuffer.unlock(); + } + var thisCount = Math.min(100000, countLeft); + countLeft -= thisCount; + lineBuffer = new PositionVertexBuffer(thisCount); + linePointList = lineBuffer.lock(); // Lock the buffer (which will return our structs) + this._lineBuffers.push(lineBuffer); + this._lineBufferCounts.push(thisCount); + counter = 0; + } + if (this.useLocalCenters) { + temp = Vector3d.subtractVectors(point, this._localCenter); + linePointList[counter] = temp; + } + else { + linePointList[counter] = point; + } + index++; + counter++; + } + if (lineBuffer != null) { + lineBuffer.unlock(); + } + } + } + }, + + _emptyLineBuffer: function () { } +}; + +registerType("SimpleLineList", [SimpleLineList, SimpleLineList$, null]); + + +// wwtlib.OrbitLineList + +export function OrbitLineList() { + this._zBuffer = true; + this._linePoints = []; + this._lineColors = []; + this.sky = true; + this.aaFix = true; + this.viewTransform = Matrix3d.get_identity(); + this._lineBuffers = []; + this._lineBufferCounts = []; + this.useLocalCenters = false; +} + +var OrbitLineList$ = { + get_depthBuffered: function () { + return this._zBuffer; + }, + + set_depthBuffered: function (value) { + this._zBuffer = value; + return value; + }, + + addLine: function (v1, v2, c1, c2) { + this._linePoints.push(v1); + this._lineColors.push(c1); + this._linePoints.push(v2); + this._lineColors.push(c2); + this._emptyLineBuffer(); + }, + + clear: function () { + this._linePoints.length = 0; + this._emptyLineBuffer(); + }, + + drawLines: function (renderContext, opacity, color) { + if (this._linePoints.length < 2) { + return; + } + this._initLineBuffer(renderContext); + var count = this._linePoints.length; + var $enum1 = ss.enumerate(this._lineBuffers); + while ($enum1.moveNext()) { + var lineBuffer = $enum1.current; + OrbitLineShader.use(renderContext, lineBuffer.vertexBuffer, color); + renderContext.gl.drawArrays(WEBGL.LINES, 0, lineBuffer.count); + } + }, + + _initLineBuffer: function (renderContext) { + if (renderContext.gl != null) { + if (!this._lineBuffers.length) { + var count = this._linePoints.length; + var lineBuffer = null; + var linePointList = null; + this._localCenter = new Vector3d(); + if (this.get_depthBuffered()) { + var $enum1 = ss.enumerate(this._linePoints); + + // compute the local center + while ($enum1.moveNext()) { + var point = $enum1.current; + this._localCenter.add(point); + } + this._localCenter.x /= count; + this._localCenter.y /= count; + this._localCenter.z /= count; + } + var countLeft = count; + var index = 0; + var counter = 0; + var temp; + var $enum2 = ss.enumerate(this._linePoints); + while ($enum2.moveNext()) { + var point = $enum2.current; + if (counter >= 100000 || linePointList == null) { + if (lineBuffer != null) { + lineBuffer.unlock(); + } + var thisCount = Math.min(100000, countLeft); + countLeft -= thisCount; + lineBuffer = new PositionColoredVertexBuffer(thisCount); + linePointList = lineBuffer.lock(); // Lock the buffer (which will return our structs) + this._lineBuffers.push(lineBuffer); + this._lineBufferCounts.push(thisCount); + counter = 0; + } + if (this.useLocalCenters) { + temp = Vector3d.subtractVectors(point, this._localCenter); + linePointList[counter] = new PositionColored(temp, this._lineColors[index]); + } + else { + linePointList[counter] = new PositionColored(point, this._lineColors[index]); + } + index++; + counter++; + } + if (lineBuffer != null) { + lineBuffer.unlock(); + } + } + } + }, + + _emptyLineBuffer: function () { + var $enum1 = ss.enumerate(this._lineBuffers); + while ($enum1.moveNext()) { + var lineBuffer = $enum1.current; + lineBuffer.dispose(); + } + this._lineBuffers.length = 0; + } +}; + +registerType("OrbitLineList", [OrbitLineList, OrbitLineList$, null]); + + +// wwtlib.LineList + +export function LineList() { + this._zBuffer = true; + this.timeSeries = false; + this.showFarSide = true; + this.sky = false; + this.decay = 0; + this.useNonRotatingFrame = false; + this.jNow = 0; + this._linePoints = []; + this._lineColors = []; + this._lineDates = []; + this._usingLocalCenter = true; + this._lineBuffers = []; + this._lineBufferCounts = []; +} + +var LineList$ = { + get_depthBuffered: function () { + return this._zBuffer; + }, + + set_depthBuffered: function (value) { + this._zBuffer = value; + return value; + }, + + addLine: function (v1, v2, color, date) { + this._linePoints.push(v1); + this._linePoints.push(v2); + this._lineColors.push(color); + this._lineDates.push(date); + this._emptyLineBuffer(); + }, + + addLineNoDate: function (v1, v2, color) { + this._linePoints.push(v1); + this._linePoints.push(v2); + this._lineColors.push(color); + this._lineDates.push(new Dates(0, 0)); + this._emptyLineBuffer(); + }, + + clear: function () { + this._linePoints.length = 0; + this._lineColors.length = 0; + this._lineDates.length = 0; + }, + + drawLines: function (renderContext, opacity) { + if (this._linePoints.length < 2 || opacity <= 0) { + return; + } + if (renderContext.gl == null) { + //todo draw with HTML5 + } else { + this._initLineBuffer(); + var $enum1 = ss.enumerate(this._lineBuffers); + while ($enum1.moveNext()) { + var lineBuffer = $enum1.current; + LineShaderNormalDates.use(renderContext, lineBuffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this._zBuffer, this.jNow, (this.timeSeries) ? this.decay : 0); + renderContext.gl.drawArrays(WEBGL.LINES, 0, lineBuffer.count); + } + } + }, + + _initLineBuffer: function () { + if (!this._lineBuffers.length) { + var count = this._linePoints.length; + var lineBuffer = null; + var linePointList = null; + var countLeft = count; + var index = 0; + var counter = 0; + var temp; + var $enum1 = ss.enumerate(this._linePoints); + while ($enum1.moveNext()) { + var point = $enum1.current; + if (counter >= 100000 || linePointList == null) { + if (lineBuffer != null) { + lineBuffer.unlock(); + } + var thisCount = Math.min(100000, countLeft); + countLeft -= thisCount; + lineBuffer = new TimeSeriesLineVertexBuffer(thisCount); + linePointList = lineBuffer.lock(); // Lock the buffer (which will return our structs) + this._lineBuffers.push(lineBuffer); + this._lineBufferCounts.push(thisCount); + counter = 0; + } + var div2 = ss.truncate((index / 2)); + temp = point; // -localCenter; + linePointList[counter] = new TimeSeriesLineVertex(); + linePointList[counter].position = temp; + linePointList[counter].normal = point; + linePointList[counter].tu = this._lineDates[div2].startDate; + linePointList[counter].tv = this._lineDates[div2].endDate; + linePointList[counter].set_color(this._lineColors[div2]); + index++; + counter++; + } + if (lineBuffer != null) { + lineBuffer.unlock(); + } + } + }, + + _emptyLineBuffer: function () { } +}; + +registerType("LineList", [LineList, LineList$, null]); + + +// wwtlib.TriangleList + +export function TriangleList() { + this._trianglePoints = []; + this._triangleColors = []; + this._triangleDates = []; + this.timeSeries = false; + this.showFarSide = false; + this.sky = false; + this.depthBuffered = true; + this.writeZbuffer = false; + this.decay = 0; + this.autoTime = true; + this.jNow = 0; + this._dataToDraw = false; + this._triangleBuffers = []; + this._triangleBufferCounts = []; +} + +var TriangleList$ = { + addTriangle: function (v1, v2, v3, color, date) { + this._trianglePoints.push(v1); + this._trianglePoints.push(v2); + this._trianglePoints.push(v3); + this._triangleColors.push(color); + this._triangleDates.push(date); + this._emptyTriangleBuffer(); + }, + + addSubdividedTriangles: function (v1, v2, v3, color, date, subdivisions) { + subdivisions--; + if (subdivisions < 0) { + this.addTriangle(v1, v2, v3, color, date); + } else { + var v12; + var v23; + var v31; + v12 = Vector3d.midPointByLength(v1, v2); + v23 = Vector3d.midPointByLength(v2, v3); + v31 = Vector3d.midPointByLength(v3, v1); + this.addSubdividedTriangles(v1, v12, v31, color, date, subdivisions); + this.addSubdividedTriangles(v12, v23, v31, color, date, subdivisions); + this.addSubdividedTriangles(v12, v2, v23, color, date, subdivisions); + this.addSubdividedTriangles(v23, v3, v31, color, date, subdivisions); + } + }, + + addQuad: function (v1, v2, v3, v4, color, date) { + this._trianglePoints.push(v1); + this._trianglePoints.push(v3); + this._trianglePoints.push(v2); + this._trianglePoints.push(v2); + this._trianglePoints.push(v3); + this._trianglePoints.push(v4); + this._triangleColors.push(color); + this._triangleDates.push(date); + this._triangleColors.push(color); + this._triangleDates.push(date); + this._emptyTriangleBuffer(); + }, + + clear: function () { + this._triangleColors.length = 0; + this._trianglePoints.length = 0; + this._triangleDates.length = 0; + this._emptyTriangleBuffer(); + }, + + _emptyTriangleBuffer: function () { }, + + _initTriangleBuffer: function () { + if (!this._triangleBuffers.length) { + var count = this._trianglePoints.length; + var triangleBuffer = null; + var triPointList = null; + var countLeft = count; + var index = 0; + var counter = 0; + var $enum1 = ss.enumerate(this._trianglePoints); + while ($enum1.moveNext()) { + var point = $enum1.current; + if (counter >= 90000 || triangleBuffer == null) { + if (triangleBuffer != null) { + triangleBuffer.unlock(); + } + var thisCount = Math.min(90000, countLeft); + countLeft -= thisCount; + triangleBuffer = new TimeSeriesLineVertexBuffer(thisCount); + this._triangleBuffers.push(triangleBuffer); + this._triangleBufferCounts.push(thisCount); + triPointList = triangleBuffer.lock(); // Lock the buffer (which will return our structs) + counter = 0; + } + triPointList[counter] = new TimeSeriesLineVertex(); + triPointList[counter].position = point; + triPointList[counter].normal = point; + var div3 = ss.truncate((index / 3)); + triPointList[counter].set_color(this._triangleColors[div3]); + triPointList[counter].tu = this._triangleDates[div3].startDate; + triPointList[counter].tv = this._triangleDates[div3].endDate; + index++; + counter++; + } + if (triangleBuffer != null) { + triangleBuffer.unlock(); + } + this._triangleColors.length = 0; + this._triangleDates.length = 0; + this._trianglePoints.length = 0; + this._dataToDraw = true; + } + }, + + draw: function (renderContext, opacity, cull) { + if (this._trianglePoints.length < 1 && !this._dataToDraw) { + return; + } + if (renderContext.gl == null) { + //todo implement HTML5 version + } else { + this._initTriangleBuffer(); + var $enum1 = ss.enumerate(this._triangleBuffers); + while ($enum1.moveNext()) { + var triBuffer = $enum1.current; + LineShaderNormalDates.use(renderContext, triBuffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this.depthBuffered, this.jNow, (this.timeSeries) ? this.decay : 0); + renderContext.gl.drawArrays(WEBGL.TRIANGLES, 0, triBuffer.count); + } + } + } +}; + +registerType("TriangleList", [TriangleList, TriangleList$, null]); + + +// wwtlib.TriangleFanList + +export function TriangleFanList() { + this._zBuffer = true; + this.timeSeries = false; + this.decay = 0; + this.jNow = 0; + this._shapes = []; + this._colors = []; + this._dates = []; + this._buffers = []; + this._bufferCounts = []; +} + +var TriangleFanList$ = { + get_depthBuffered: function () { + return this._zBuffer; + }, + + set_depthBuffered: function (value) { + this._zBuffer = value; + return value; + }, + + addShape: function (shapePoints, color, date) { + this._shapes.push(shapePoints); + this._colors.push(color); + this._dates.push(date); + }, + + draw: function (renderContext, opacity) { + if (opacity <= 0) { + return; + } + if (renderContext.gl != null) { + this._initBuffer(); + var $enum1 = ss.enumerate(this._buffers); + while ($enum1.moveNext()) { + var buffer = $enum1.current; + LineShaderNormalDates.use(renderContext, buffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this._zBuffer, this.jNow, (this.timeSeries) ? this.decay : 0); + renderContext.gl.drawArrays(WEBGL.TRIANGLE_FAN, 0, buffer.count); + } + } + }, + + _initBuffer: function () { + if (this._buffers.length !== this._shapes.length) { + this._buffers.length = 0; + var index = 0; + var $enum1 = ss.enumerate(this._shapes); + while ($enum1.moveNext()) { + var shape = $enum1.current; + var buffer = new TimeSeriesLineVertexBuffer(shape.length); + var pointList = buffer.lock(); // Lock the buffer (which will return our structs) + this._buffers.push(buffer); + this._bufferCounts.push(shape.length); + var counter = 0; + var $enum2 = ss.enumerate(shape); + while ($enum2.moveNext()) { + var point = $enum2.current; + pointList[counter] = new TimeSeriesLineVertex(); + pointList[counter].position = point; + pointList[counter].tu = this._dates[index].startDate; + pointList[counter].tv = this._dates[index].endDate; + pointList[counter].set_color(this._colors[index]); + counter++; + } + index++; + if (buffer != null) { + buffer.unlock(); + } + } + } + } +}; + +registerType("TriangleFanList", [TriangleFanList, TriangleFanList$, null]); + + +// wwtlib.PointList + +export function PointList(device) { + this._points = []; + this._colors = []; + this._dates = []; + this._sizes = []; + this.timeSeries = false; + this.showFarSide = false; + this.sky = false; + this.depthBuffered = true; + this.decay = 0; + this.scale = 1; + this.autoTime = true; + this.jNow = 0; + this._dataToDraw = false; + this.items = []; + this._imageReady = false; + this._init = false; + this.minSize = 2; + this._pointBuffers = []; + this._pointBufferCounts = []; + this._device = device; +} + +PointList.starTexture = null; + +var PointList$ = { + addPoint: function (v1, color, date, size) { + this._points.push(v1); + this._colors.push(color._clone()); + this._dates.push(date); + this._sizes.push(size); + this._emptyPointBuffer(); + }, + + clear: function () { + this._colors.length = 0; + this._points.length = 0; + this._dates.length = 0; + this._sizes.length = 0; + this._emptyPointBuffer(); + }, + + _emptyPointBuffer: function () { + var $enum1 = ss.enumerate(this._pointBuffers); + while ($enum1.moveNext()) { + var pointBuffer = $enum1.current; + pointBuffer.dispose(); + } + this._pointBuffers.length = 0; + this._init = false; + }, + + _initBuffer: function (renderContext) { + var $this = this; + + if (!this._init) { + if (renderContext.gl == null) { + this._starProfile = document.createElement('img'); + this._starProfile.addEventListener('load', function (e) { + $this._imageReady = true; + }, false); + this._starProfile.src = URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png'); + this._worldList = new Array(this._points.length); + this._transformedList = new Array(this._points.length); + var index = 0; + var $enum1 = ss.enumerate(this._points); + while ($enum1.moveNext()) { + // todo filter by date + var pnt = $enum1.current; + var item = new DataItem(); + item.location = pnt; + item.tranformed = new Vector3d(); + item.size = this._sizes[index]; + item.color = this._colors[index]; + this._worldList[index] = item.location; + this._transformedList[index] = item.tranformed; + this.items.push(item); + index++; + } + } else { + if (!this._pointBuffers.length) { + if (PointList.starTexture == null) { + PointList.starTexture = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png')); + } + var count = this._points.length; + var pointBuffer = null; + var pointList = null; + var countLeft = count; + var index = 0; + var counter = 0; + var $enum2 = ss.enumerate(this._points); + while ($enum2.moveNext()) { + var point = $enum2.current; + if (counter >= 100000 || pointList == null) { + if (pointBuffer != null) { + pointBuffer.unlock(); + } + var thisCount = Math.min(100000, countLeft); + countLeft -= thisCount; + pointBuffer = new TimeSeriesPointVertexBuffer(thisCount); + pointList = pointBuffer.lock(); // Lock the buffer (which will return our structs) + this._pointBuffers.push(pointBuffer); + this._pointBufferCounts.push(thisCount); + counter = 0; + } + pointList[counter] = new TimeSeriesPointVertex(); + pointList[counter].position = point; + pointList[counter].pointSize = this._sizes[index]; + pointList[counter].tu = this._dates[index].startDate; + pointList[counter].tv = this._dates[index].endDate; + pointList[counter].set_color(this._colors[index]); + index++; + counter++; + } + if (pointBuffer != null) { + pointBuffer.unlock(); + } + } + } + this._init = true; + } + }, + + draw: function (renderContext, opacity, cull) { + this._initBuffer(renderContext); + if (renderContext.gl == null) { + if (!this._imageReady) { + return; + } + renderContext.device.save(); + renderContext.WVP.projectArrayToScreen(this._worldList, this._transformedList); + var ctx = renderContext.device; + ctx.globalAlpha = 0.4; + var width = renderContext.width; + var height = renderContext.height; + var viewPoint = Vector3d.makeCopy(renderContext.get_viewPoint()); + var scaleFactor = renderContext.get_fovScale() / 100; + var $enum1 = ss.enumerate(this.items); + while ($enum1.moveNext()) { + // todo filter by date + var item = $enum1.current; + if (item.tranformed.z < 1) { + var x = item.tranformed.x; + var y = item.tranformed.y; + var size = 0.1 * item.size / scaleFactor; + var half = size / 2; + if (x > -half && x < width + half && y > -half && y < height + half) { + ctx.beginPath(); + ctx.fillStyle = item.color.toFormat(); + ctx.arc(x, y, size, 0, Math.PI * 2, true); + ctx.fill(); + } + } + } + renderContext.device.restore(); + } else { + var zero = new Vector3d(); + var matInv = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + matInv.invert(); + var cam = Vector3d._transformCoordinate(zero, matInv); + var $enum2 = ss.enumerate(this._pointBuffers); + while ($enum2.moveNext()) { + var pointBuffer = $enum2.current; + TimeSeriesPointSpriteShader.use(renderContext, pointBuffer.vertexBuffer, PointList.starTexture.texture2d, Color.fromArgb(255 * opacity, 255, 255, 255), this.depthBuffered, this.jNow, (this.timeSeries) ? this.decay : 0, cam, (this.scale * (renderContext.height / 960)), this.minSize, this.showFarSide, this.sky); + renderContext.gl.drawArrays(WEBGL.POINTS, 0, pointBuffer.count); + } + } + }, + + drawTextured: function (renderContext, texture, opacity) { + this._initBuffer(renderContext); + var zero = new Vector3d(); + var matInv = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + matInv.invert(); + var cam = Vector3d._transformCoordinate(zero, matInv); + var $enum1 = ss.enumerate(this._pointBuffers); + while ($enum1.moveNext()) { + var pointBuffer = $enum1.current; + TimeSeriesPointSpriteShader.use(renderContext, pointBuffer.vertexBuffer, texture, Color.fromArgb(255 * opacity, 255, 255, 255), this.depthBuffered, this.jNow, this.decay, cam, (this.scale * (renderContext.height / 960)), this.minSize, this.showFarSide, this.sky); + renderContext.gl.drawArrays(WEBGL.POINTS, 0, pointBuffer.count); + } + } +}; + +registerType("PointList", [PointList, PointList$, null]); + + +// wwtlib.TimeSeriesLineVertex + +export function TimeSeriesLineVertex() { + this.position = new Vector3d(); + this.normal = new Vector3d(); + this.tu = 0; + this.tv = 0; +} + +TimeSeriesLineVertex.create = function (position, normal, time, color) { + var temp = new TimeSeriesLineVertex(); + temp.position = position; + temp.normal = normal; + temp.tu = time; + temp.tv = 0; + temp.color = color; + return temp; +}; + +var TimeSeriesLineVertex$ = { + get_color: function () { + return this.color; + }, + + set_color: function (value) { + this.color = value; + return value; + } +}; + +registerType("TimeSeriesLineVertex", [TimeSeriesLineVertex, TimeSeriesLineVertex$, null]); + + +// wwtlib.TimeSeriesPointVertex + +export function TimeSeriesPointVertex() { + this.pointSize = 0; + this.tu = 0; + this.tv = 0; +} + +TimeSeriesPointVertex.create = function (position, size, time, color) { + var tmp = new TimeSeriesPointVertex(); + tmp.position = position; + tmp.pointSize = size; + tmp.tu = time; + tmp.tv = 0; + tmp.color = color; + return tmp; +}; + +var TimeSeriesPointVertex$ = { + get_color: function () { + return this.color; + }, + + set_color: function (value) { + this.color = value; + return value; + } +}; + +registerType("TimeSeriesPointVertex", [TimeSeriesPointVertex, TimeSeriesPointVertex$, null]); diff --git a/engine/esm/graphics/shaders.js b/engine/esm/graphics/shaders.js new file mode 100644 index 00000000..2e162a46 --- /dev/null +++ b/engine/esm/graphics/shaders.js @@ -0,0 +1,2181 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Core WebGL shaders for the WWT engine. + +import { registerType } from "../typesystem.js"; +import { Matrix3d, Vector3d } from "../double3d.js"; +import { Color } from "../color.js"; +import { set_tileUvMultiple, set_tileDemEnabled } from "../render_globals.js"; +import { WEBGL } from "./webgl_constants.js"; +import { Texture } from "./texture.js"; + + +// wwtlib.SimpleLineShader + +export function SimpleLineShader() { } + +SimpleLineShader.vertLoc = 0; +SimpleLineShader.initialized = false; +SimpleLineShader._prog = null; + +SimpleLineShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision highp float; + uniform vec4 lineColor; + + void main(void) { + gl_FragColor = lineColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + } + `; + + SimpleLineShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(SimpleLineShader._frag, fragShaderText); + gl.compileShader(SimpleLineShader._frag); + var stat = gl.getShaderParameter(SimpleLineShader._frag, WEBGL.COMPILE_STATUS); + SimpleLineShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(SimpleLineShader._vert, vertexShaderText); + gl.compileShader(SimpleLineShader._vert); + var stat1 = gl.getShaderParameter(SimpleLineShader._vert, WEBGL.COMPILE_STATUS); + SimpleLineShader._prog = gl.createProgram(); + gl.attachShader(SimpleLineShader._prog, SimpleLineShader._vert); + gl.attachShader(SimpleLineShader._prog, SimpleLineShader._frag); + gl.linkProgram(SimpleLineShader._prog); + var errcode = gl.getProgramParameter(SimpleLineShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(SimpleLineShader._prog); + SimpleLineShader.vertLoc = gl.getAttribLocation(SimpleLineShader._prog, 'aVertexPosition'); + SimpleLineShader.lineColorLoc = gl.getUniformLocation(SimpleLineShader._prog, 'lineColor'); + SimpleLineShader.projMatLoc = gl.getUniformLocation(SimpleLineShader._prog, 'uPMatrix'); + SimpleLineShader.mvMatLoc = gl.getUniformLocation(SimpleLineShader._prog, 'uMVMatrix'); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + SimpleLineShader.initialized = true; +}; + +SimpleLineShader.use = function (renderContext, vertex, lineColor, useDepth) { + var gl = renderContext.gl; + if (gl != null) { + if (!SimpleLineShader.initialized) { + SimpleLineShader.init(renderContext); + } + gl.useProgram(SimpleLineShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(SimpleLineShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(SimpleLineShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform4f(SimpleLineShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); + if (renderContext.space || !useDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.enableVertexAttribArray(SimpleLineShader.vertLoc); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.vertexAttribPointer(SimpleLineShader.vertLoc, 3, WEBGL.FLOAT, false, 0, 0); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var SimpleLineShader$ = {}; + +registerType("SimpleLineShader", [SimpleLineShader, SimpleLineShader$, null]); + + +// wwtlib.SimpleLineShader2D + +export function SimpleLineShader2D() { } + +SimpleLineShader2D.vertLoc = 0; +SimpleLineShader2D.initialized = false; +SimpleLineShader2D._prog = null; + +SimpleLineShader2D.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision highp float; + uniform vec4 lineColor; + + void main(void) { + gl_FragColor = lineColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + + void main(void) { + gl_Position = vec4(aVertexPosition, 1.0); + } + `; + + SimpleLineShader2D._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(SimpleLineShader2D._frag, fragShaderText); + gl.compileShader(SimpleLineShader2D._frag); + var stat = gl.getShaderParameter(SimpleLineShader2D._frag, WEBGL.COMPILE_STATUS); + SimpleLineShader2D._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(SimpleLineShader2D._vert, vertexShaderText); + gl.compileShader(SimpleLineShader2D._vert); + var stat1 = gl.getShaderParameter(SimpleLineShader2D._vert, WEBGL.COMPILE_STATUS); + SimpleLineShader2D._prog = gl.createProgram(); + gl.attachShader(SimpleLineShader2D._prog, SimpleLineShader2D._vert); + gl.attachShader(SimpleLineShader2D._prog, SimpleLineShader2D._frag); + gl.linkProgram(SimpleLineShader2D._prog); + var errcode = gl.getProgramParameter(SimpleLineShader2D._prog, WEBGL.LINK_STATUS); + gl.useProgram(SimpleLineShader2D._prog); + SimpleLineShader2D.vertLoc = gl.getAttribLocation(SimpleLineShader2D._prog, 'aVertexPosition'); + SimpleLineShader2D.lineColorLoc = gl.getUniformLocation(SimpleLineShader2D._prog, 'lineColor'); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + SimpleLineShader2D.initialized = true; +}; + +SimpleLineShader2D.use = function (renderContext, vertex, lineColor, useDepth) { + var gl = renderContext.gl; + if (gl != null) { + if (!SimpleLineShader2D.initialized) { + SimpleLineShader2D.init(renderContext); + } + gl.useProgram(SimpleLineShader2D._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform4f(SimpleLineShader2D.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); + if (renderContext.space || !useDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.enableVertexAttribArray(SimpleLineShader2D.vertLoc); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.vertexAttribPointer(SimpleLineShader2D.vertLoc, 3, WEBGL.FLOAT, false, 0, 0); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var SimpleLineShader2D$ = {}; + +registerType("SimpleLineShader2D", [SimpleLineShader2D, SimpleLineShader2D$, null]); + + +// wwtlib.OrbitLineShader + +export function OrbitLineShader() { } + +OrbitLineShader.vertLoc = 0; +OrbitLineShader.colorLoc = 0; +OrbitLineShader.initialized = false; +OrbitLineShader._prog = null; + +OrbitLineShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision highp float; + uniform vec4 lineColor; + varying lowp vec4 vColor; + + void main(void) { + gl_FragColor = lineColor * vColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec4 aVertexColor; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + varying lowp vec4 vColor; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vColor = aVertexColor; + } + `; + + OrbitLineShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(OrbitLineShader._frag, fragShaderText); + gl.compileShader(OrbitLineShader._frag); + var stat = gl.getShaderParameter(OrbitLineShader._frag, WEBGL.COMPILE_STATUS); + OrbitLineShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(OrbitLineShader._vert, vertexShaderText); + gl.compileShader(OrbitLineShader._vert); + var stat1 = gl.getShaderParameter(OrbitLineShader._vert, WEBGL.COMPILE_STATUS); + OrbitLineShader._prog = gl.createProgram(); + gl.attachShader(OrbitLineShader._prog, OrbitLineShader._vert); + gl.attachShader(OrbitLineShader._prog, OrbitLineShader._frag); + gl.linkProgram(OrbitLineShader._prog); + var errcode = gl.getProgramParameter(OrbitLineShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(OrbitLineShader._prog); + OrbitLineShader.vertLoc = gl.getAttribLocation(OrbitLineShader._prog, 'aVertexPosition'); + OrbitLineShader.colorLoc = gl.getAttribLocation(OrbitLineShader._prog, 'aVertexColor'); + OrbitLineShader.lineColorLoc = gl.getUniformLocation(OrbitLineShader._prog, 'lineColor'); + OrbitLineShader.projMatLoc = gl.getUniformLocation(OrbitLineShader._prog, 'uPMatrix'); + OrbitLineShader.mvMatLoc = gl.getUniformLocation(OrbitLineShader._prog, 'uMVMatrix'); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + OrbitLineShader.initialized = true; +}; + +OrbitLineShader.use = function (renderContext, vertex, lineColor) { + var gl = renderContext.gl; + if (gl != null) { + if (!OrbitLineShader.initialized) { + OrbitLineShader.init(renderContext); + } + gl.useProgram(OrbitLineShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(OrbitLineShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(OrbitLineShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform4f(OrbitLineShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); + if (renderContext.space) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enableVertexAttribArray(OrbitLineShader.vertLoc); + gl.enableVertexAttribArray(OrbitLineShader.colorLoc); + gl.vertexAttribPointer(OrbitLineShader.vertLoc, 3, WEBGL.FLOAT, false, 28, 0); + gl.vertexAttribPointer(OrbitLineShader.colorLoc, 4, WEBGL.FLOAT, false, 28, 12); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var OrbitLineShader$ = {}; + +registerType("OrbitLineShader", [OrbitLineShader, OrbitLineShader$, null]); + + +// wwtlib.LineShaderNormalDates + +export function LineShaderNormalDates() { } + +LineShaderNormalDates.vertLoc = 0; +LineShaderNormalDates.colorLoc = 0; +LineShaderNormalDates.timeLoc = 0; +LineShaderNormalDates.initialized = false; +LineShaderNormalDates._prog = null; + +LineShaderNormalDates.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision highp float; + uniform vec4 lineColor; + varying lowp vec4 vColor; + + void main(void) + { + gl_FragColor = lineColor * vColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec4 aVertexColor; + attribute vec2 aTime; + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + uniform float jNow; + uniform float decay; + + varying lowp vec4 vColor; + + void main(void) + { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + float dAlpha = 1.0; + + if (decay > 0.0) + { + dAlpha = 1.0 - ((jNow - aTime.y) / decay); + if (dAlpha > 1.0 ) + { + dAlpha = 1.0; + } + } + + if (jNow < aTime.x && decay > 0.0) + { + vColor = vec4(1, 1, 1, 1); + } + else + { + vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha * aVertexColor.a); + } + } + `; + + LineShaderNormalDates._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(LineShaderNormalDates._frag, fragShaderText); + gl.compileShader(LineShaderNormalDates._frag); + var stat = gl.getShaderParameter(LineShaderNormalDates._frag, WEBGL.COMPILE_STATUS); + LineShaderNormalDates._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(LineShaderNormalDates._vert, vertexShaderText); + gl.compileShader(LineShaderNormalDates._vert); + var stat1 = gl.getShaderParameter(LineShaderNormalDates._vert, WEBGL.COMPILE_STATUS); + LineShaderNormalDates._prog = gl.createProgram(); + gl.attachShader(LineShaderNormalDates._prog, LineShaderNormalDates._vert); + gl.attachShader(LineShaderNormalDates._prog, LineShaderNormalDates._frag); + gl.linkProgram(LineShaderNormalDates._prog); + var errcode = gl.getProgramParameter(LineShaderNormalDates._prog, WEBGL.LINK_STATUS); + gl.useProgram(LineShaderNormalDates._prog); + LineShaderNormalDates.vertLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aVertexPosition'); + LineShaderNormalDates.colorLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aVertexColor'); + LineShaderNormalDates.timeLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aTime'); + LineShaderNormalDates.lineColorLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'lineColor'); + LineShaderNormalDates.projMatLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'uPMatrix'); + LineShaderNormalDates.mvMatLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'uMVMatrix'); + LineShaderNormalDates.jNowLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'jNow'); + LineShaderNormalDates.decayLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'decay'); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + LineShaderNormalDates.initialized = true; +}; + +LineShaderNormalDates.use = function (renderContext, vertex, lineColor, zBuffer, jNow, decay) { + var gl = renderContext.gl; + if (gl != null) { + if (!LineShaderNormalDates.initialized) { + LineShaderNormalDates.init(renderContext); + } + gl.useProgram(LineShaderNormalDates._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(LineShaderNormalDates.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(LineShaderNormalDates.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform4f(LineShaderNormalDates.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); + gl.uniform1f(LineShaderNormalDates.jNowLoc, jNow); + gl.uniform1f(LineShaderNormalDates.decayLoc, decay); + if (zBuffer) { + gl.enable(WEBGL.DEPTH_TEST); + } else { + gl.disable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enableVertexAttribArray(LineShaderNormalDates.vertLoc); + gl.enableVertexAttribArray(LineShaderNormalDates.colorLoc); + gl.vertexAttribPointer(LineShaderNormalDates.vertLoc, 3, WEBGL.FLOAT, false, 36, 0); + gl.vertexAttribPointer(LineShaderNormalDates.colorLoc, 4, WEBGL.FLOAT, false, 36, 12); + gl.vertexAttribPointer(LineShaderNormalDates.timeLoc, 2, WEBGL.FLOAT, false, 36, 28); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var LineShaderNormalDates$ = {}; + +registerType("LineShaderNormalDates", [LineShaderNormalDates, LineShaderNormalDates$, null]); + + +// wwtlib.TimeSeriesPointSpriteShader + +export function TimeSeriesPointSpriteShader() { } + +TimeSeriesPointSpriteShader.vertLoc = 0; +TimeSeriesPointSpriteShader.colorLoc = 0; +TimeSeriesPointSpriteShader.pointSizeLoc = 0; +TimeSeriesPointSpriteShader.timeLoc = 0; +TimeSeriesPointSpriteShader.initialized = false; +TimeSeriesPointSpriteShader._prog = null; + +TimeSeriesPointSpriteShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + uniform vec4 lineColor; + varying lowp vec4 vColor; + uniform sampler2D uSampler; + + void main(void) + { + vec4 texColor; + texColor = texture2D(uSampler, gl_PointCoord); + gl_FragColor = lineColor * vColor * texColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec4 aVertexColor; + attribute vec2 aTime; + attribute float aPointSize; + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + uniform float jNow; + uniform vec3 cameraPosition; + uniform float decay; + uniform float scale; + uniform float minSize; + uniform float sky; + uniform float showFarSide; + + varying lowp vec4 vColor; + + void main(void) + { + float dotCam = dot( normalize(cameraPosition-aVertexPosition), normalize(aVertexPosition)); + float dist = distance(aVertexPosition, cameraPosition); + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + float dAlpha = 1.0; + + if ( decay > 0.0) + { + dAlpha = 1.0 - ((jNow - aTime.y) / decay); + if (dAlpha > 1.0 ) + { + dAlpha = 1.0; + } + } + + if ( showFarSide == 0.0 && (dotCam * sky) < 0.0 || (jNow < aTime.x && decay > 0.0)) + { + vColor = vec4(0.0, 0.0, 0.0, 0.0); + } + else + { + vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha); + } + + float lSize = scale; + + if (scale < 0.0) + { + lSize = -scale; + dist = 1.0; + } + + gl_PointSize = max(minSize, (lSize * ( aPointSize ) / dist)); + } + `; + + TimeSeriesPointSpriteShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(TimeSeriesPointSpriteShader._frag, fragShaderText); + gl.compileShader(TimeSeriesPointSpriteShader._frag); + var stat = gl.getShaderParameter(TimeSeriesPointSpriteShader._frag, WEBGL.COMPILE_STATUS); + TimeSeriesPointSpriteShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(TimeSeriesPointSpriteShader._vert, vertexShaderText); + gl.compileShader(TimeSeriesPointSpriteShader._vert); + var stat1 = gl.getShaderParameter(TimeSeriesPointSpriteShader._vert, WEBGL.COMPILE_STATUS); + var compilationLog = gl.getShaderInfoLog(TimeSeriesPointSpriteShader._vert); + TimeSeriesPointSpriteShader._prog = gl.createProgram(); + gl.attachShader(TimeSeriesPointSpriteShader._prog, TimeSeriesPointSpriteShader._vert); + gl.attachShader(TimeSeriesPointSpriteShader._prog, TimeSeriesPointSpriteShader._frag); + gl.linkProgram(TimeSeriesPointSpriteShader._prog); + var errcode = gl.getProgramParameter(TimeSeriesPointSpriteShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(TimeSeriesPointSpriteShader._prog); + TimeSeriesPointSpriteShader.vertLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aVertexPosition'); + TimeSeriesPointSpriteShader.colorLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aVertexColor'); + TimeSeriesPointSpriteShader.pointSizeLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aPointSize'); + TimeSeriesPointSpriteShader.timeLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aTime'); + TimeSeriesPointSpriteShader.projMatLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uPMatrix'); + TimeSeriesPointSpriteShader.mvMatLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uMVMatrix'); + TimeSeriesPointSpriteShader.sampLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uSampler'); + TimeSeriesPointSpriteShader.jNowLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'jNow'); + TimeSeriesPointSpriteShader.decayLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'decay'); + TimeSeriesPointSpriteShader.lineColorLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'lineColor'); + TimeSeriesPointSpriteShader.cameraPosLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'cameraPosition'); + TimeSeriesPointSpriteShader.scaleLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'scale'); + TimeSeriesPointSpriteShader.skyLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'sky'); + TimeSeriesPointSpriteShader.showFarSideLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'showFarSide'); + TimeSeriesPointSpriteShader.minSizeLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'minSize'); + gl.enable(WEBGL.BLEND); + TimeSeriesPointSpriteShader.initialized = true; +}; + +TimeSeriesPointSpriteShader.use = function (renderContext, vertex, texture, lineColor, zBuffer, jNow, decay, camera, scale, minSize, showFarSide, sky) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!TimeSeriesPointSpriteShader.initialized) { + TimeSeriesPointSpriteShader.init(renderContext); + } + gl.useProgram(TimeSeriesPointSpriteShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(TimeSeriesPointSpriteShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(TimeSeriesPointSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(TimeSeriesPointSpriteShader.sampLoc, 0); + gl.uniform1f(TimeSeriesPointSpriteShader.jNowLoc, jNow); + gl.uniform1f(TimeSeriesPointSpriteShader.decayLoc, decay); + gl.uniform4f(TimeSeriesPointSpriteShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); + gl.uniform3f(TimeSeriesPointSpriteShader.cameraPosLoc, camera.x, camera.y, camera.z); + gl.uniform1f(TimeSeriesPointSpriteShader.scaleLoc, scale); + gl.uniform1f(TimeSeriesPointSpriteShader.minSizeLoc, minSize); + gl.uniform1f(TimeSeriesPointSpriteShader.showFarSideLoc, (showFarSide) ? 1 : 0); + gl.uniform1f(TimeSeriesPointSpriteShader.skyLoc, (sky) ? -1 : 1); + if (zBuffer) { + gl.enable(WEBGL.DEPTH_TEST); + } else { + gl.disable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.vertLoc); + gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.colorLoc); + gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.pointSizeLoc); + gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.timeLoc); + gl.vertexAttribPointer(TimeSeriesPointSpriteShader.vertLoc, 3, WEBGL.FLOAT, false, 40, 0); + gl.vertexAttribPointer(TimeSeriesPointSpriteShader.colorLoc, 4, WEBGL.FLOAT, false, 40, 12); + gl.vertexAttribPointer(TimeSeriesPointSpriteShader.pointSizeLoc, 1, WEBGL.FLOAT, false, 40, 36); + gl.vertexAttribPointer(TimeSeriesPointSpriteShader.timeLoc, 2, WEBGL.FLOAT, false, 40, 28); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } +}; + +var TimeSeriesPointSpriteShader$ = {}; + +registerType("TimeSeriesPointSpriteShader", [TimeSeriesPointSpriteShader, TimeSeriesPointSpriteShader$, null]); + +// wwtlib.KeplerPointSpriteShader + +export function KeplerPointSpriteShader() { } + +KeplerPointSpriteShader.abcLoc = 0; +KeplerPointSpriteShader.abcLoc1 = 0; +KeplerPointSpriteShader.pointSizeLoc = 0; +KeplerPointSpriteShader.colorLoc = 0; +KeplerPointSpriteShader.weLoc = 0; +KeplerPointSpriteShader.nTLoc = 0; +KeplerPointSpriteShader.azLoc = 0; +KeplerPointSpriteShader.orbitLoc = 0; +KeplerPointSpriteShader.initialized = false; +KeplerPointSpriteShader._prog = null; + +KeplerPointSpriteShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + uniform vec4 lineColor; + varying lowp vec4 vColor; + uniform sampler2D uSampler; + + void main(void) + { + vec4 texColor; + texColor = texture2D(uSampler, gl_PointCoord); + gl_FragColor = lineColor * vColor * texColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 ABC; + attribute vec3 abc; + attribute float PointSize; + attribute vec4 Color; + attribute vec2 we; + attribute vec2 nT; + attribute vec2 az; + attribute vec2 orbit; + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + uniform float jNow; + uniform vec3 cameraPosition; + uniform float MM; + uniform float scaling; + uniform float minSize; + uniform float opacity; + varying lowp vec4 vColor; + + void main(void) + { + float M = nT.x * (jNow - nT.y) * 0.01745329251994; + float e = we.y; + float a = az.x; + float PI = 3.1415926535897932384; + float w = we.x* 0.01745329251994; + float F = 1.0; + + if (M < 0.0) + F = -1.0; + + M = abs(M) / (2.0 * PI); + M = (M - float(int(M)))*2.0 *PI *F; + + if (MM != 0.0) + { + M = MM + (1.0- orbit.x) *2.0 *PI; + if (M > (2.0*PI)) + M = M - (2.0*PI); + } + + if (M < 0.0) + M += 2.0 *PI; + + F = 1.0; + if (M > PI) + F = -1.0; + + if (M > PI) + M = 2.0 *PI - M; + + float E = PI / 2.0; + float scale = PI / 4.0; + + for (int i =0; i<23; i++) + { + float R = E - e *sin(E); + if (M > R) + E += scale; + else + E -= scale; + scale /= 2.0; + } + + E = E * F; + + float v = 2.0 * atan(sqrt((1.0 + e) / (1.0 -e )) * tan(E/2.0)); + float r = a * (1.0-e * cos(E)); + + vec4 pnt; + pnt.x = r * abc.x * sin(ABC.x + w + v); + pnt.z = r * abc.y * sin(ABC.y + w + v); + pnt.y = r * abc.z * sin(ABC.z + w + v); + pnt.w = 1.0; + + float dist = distance(pnt.xyz, cameraPosition.xyz); + gl_Position = uPMatrix * uMVMatrix * pnt; + vColor.a = opacity * (1.0-(orbit.x)); + vColor.r = Color.r; + vColor.g = Color.g; + vColor.b = Color.b; + gl_PointSize = max(minSize, scaling * (PointSize / dist)); + } + `; + + KeplerPointSpriteShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(KeplerPointSpriteShader._frag, fragShaderText); + gl.compileShader(KeplerPointSpriteShader._frag); + var stat = gl.getShaderParameter(KeplerPointSpriteShader._frag, WEBGL.COMPILE_STATUS); + KeplerPointSpriteShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(KeplerPointSpriteShader._vert, vertexShaderText); + gl.compileShader(KeplerPointSpriteShader._vert); + var stat1 = gl.getShaderParameter(KeplerPointSpriteShader._vert, WEBGL.COMPILE_STATUS); + var compilationLog = gl.getShaderInfoLog(KeplerPointSpriteShader._vert); + KeplerPointSpriteShader._prog = gl.createProgram(); + gl.attachShader(KeplerPointSpriteShader._prog, KeplerPointSpriteShader._vert); + gl.attachShader(KeplerPointSpriteShader._prog, KeplerPointSpriteShader._frag); + gl.linkProgram(KeplerPointSpriteShader._prog); + var errcode = gl.getProgramParameter(KeplerPointSpriteShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(KeplerPointSpriteShader._prog); + KeplerPointSpriteShader.abcLoc1 = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'abc'); + KeplerPointSpriteShader.abcLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'ABC'); + KeplerPointSpriteShader.pointSizeLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'PointSize'); + KeplerPointSpriteShader.colorLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'Color'); + KeplerPointSpriteShader.weLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'we'); + KeplerPointSpriteShader.nTLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'nT'); + KeplerPointSpriteShader.azLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'az'); + KeplerPointSpriteShader.orbitLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'orbit'); + KeplerPointSpriteShader.projMatLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uPMatrix'); + KeplerPointSpriteShader.mvMatLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uMVMatrix'); + KeplerPointSpriteShader.jNowLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'jNow'); + KeplerPointSpriteShader.cameraPosLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'cameraPosition'); + KeplerPointSpriteShader.mmLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'MM'); + KeplerPointSpriteShader.scaleLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'scaling'); + KeplerPointSpriteShader.minSizeLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'minSize'); + KeplerPointSpriteShader.lineColorLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'lineColor'); + KeplerPointSpriteShader.opacityLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'opacity'); + KeplerPointSpriteShader.sampLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uSampler'); + gl.enable(WEBGL.BLEND); + KeplerPointSpriteShader.initialized = true; +}; + +KeplerPointSpriteShader.use = function (renderContext, worldView, vertex, texture, lineColor, opacity, zBuffer, jNow, MM, camera, scale, minSize) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!KeplerPointSpriteShader.initialized) { + KeplerPointSpriteShader.init(renderContext); + } + gl.useProgram(KeplerPointSpriteShader._prog); + gl.uniformMatrix4fv(KeplerPointSpriteShader.mvMatLoc, false, worldView.floatArray()); + gl.uniformMatrix4fv(KeplerPointSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(KeplerPointSpriteShader.sampLoc, 0); + gl.uniform1f(KeplerPointSpriteShader.jNowLoc, jNow); + gl.uniform1f(KeplerPointSpriteShader.mmLoc, MM); + gl.uniform4f(KeplerPointSpriteShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); + gl.uniform1f(KeplerPointSpriteShader.opacityLoc, opacity); + gl.uniform3f(KeplerPointSpriteShader.cameraPosLoc, camera.x, camera.y, camera.z); + gl.uniform1f(KeplerPointSpriteShader.scaleLoc, scale); + gl.uniform1f(KeplerPointSpriteShader.minSizeLoc, minSize); + if (zBuffer) { + gl.enable(WEBGL.DEPTH_TEST); + } else { + gl.disable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enableVertexAttribArray(KeplerPointSpriteShader.abcLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.abcLoc1); + gl.enableVertexAttribArray(KeplerPointSpriteShader.colorLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.pointSizeLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.weLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.nTLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.azLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.orbitLoc); + gl.enableVertexAttribArray(KeplerPointSpriteShader.weLoc); + gl.vertexAttribPointer(KeplerPointSpriteShader.abcLoc, 3, WEBGL.FLOAT, false, 76, 0); + gl.vertexAttribPointer(KeplerPointSpriteShader.abcLoc1, 3, WEBGL.FLOAT, false, 76, 12); + gl.vertexAttribPointer(KeplerPointSpriteShader.pointSizeLoc, 1, WEBGL.FLOAT, false, 76, 24); + gl.vertexAttribPointer(KeplerPointSpriteShader.colorLoc, 4, WEBGL.FLOAT, false, 76, 28); + gl.vertexAttribPointer(KeplerPointSpriteShader.weLoc, 2, WEBGL.FLOAT, false, 76, 44); + gl.vertexAttribPointer(KeplerPointSpriteShader.nTLoc, 2, WEBGL.FLOAT, false, 76, 52); + gl.vertexAttribPointer(KeplerPointSpriteShader.azLoc, 2, WEBGL.FLOAT, false, 76, 60); + gl.vertexAttribPointer(KeplerPointSpriteShader.orbitLoc, 2, WEBGL.FLOAT, false, 76, 68); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } +}; + +var KeplerPointSpriteShader$ = {}; + +registerType("KeplerPointSpriteShader", [KeplerPointSpriteShader, KeplerPointSpriteShader$, null]); + + +// wwtlib.EllipseShader + +export function EllipseShader() { } + +EllipseShader.angleLoc = 0; +EllipseShader.initialized = false; +EllipseShader._prog = null; + +EllipseShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + varying lowp vec4 vColor; + + void main(void) + { + gl_FragColor = vColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 Angle; + uniform mat4 matWVP; + uniform mat4 matPosition; + uniform vec3 positionNow; + uniform float semiMajorAxis; + uniform float eccentricity; + uniform vec4 color; + uniform float eccentricAnomaly; + varying lowp vec4 vColor; + + void main(void) + { + float fade = (1.0 - Angle.x); + float PI = 3.1415927; + float E = eccentricAnomaly - Angle.x * 2.0 * PI; + vec2 semiAxes = vec2(1.0, sqrt(1.0 - eccentricity * eccentricity)) * semiMajorAxis; + vec2 planePos = semiAxes * vec2(cos(E) - eccentricity, sin(E)); + + if (Angle.x == 0.0) + gl_Position = matPosition * vec4(positionNow, 1.0); + else + gl_Position = matWVP * vec4(planePos.x, planePos.y, 0.0, 1.0); + + vColor = vec4(color.rgb, fade * color.a); + } + `; + + EllipseShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(EllipseShader._frag, fragShaderText); + gl.compileShader(EllipseShader._frag); + var stat = gl.getShaderParameter(EllipseShader._frag, WEBGL.COMPILE_STATUS); + EllipseShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(EllipseShader._vert, vertexShaderText); + gl.compileShader(EllipseShader._vert); + var stat1 = gl.getShaderParameter(EllipseShader._vert, WEBGL.COMPILE_STATUS); + var compilationLog = gl.getShaderInfoLog(EllipseShader._vert); + EllipseShader._prog = gl.createProgram(); + gl.attachShader(EllipseShader._prog, EllipseShader._vert); + gl.attachShader(EllipseShader._prog, EllipseShader._frag); + gl.linkProgram(EllipseShader._prog); + var errcode = gl.getProgramParameter(EllipseShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(EllipseShader._prog); + EllipseShader.angleLoc = gl.getAttribLocation(EllipseShader._prog, 'Angle'); + EllipseShader.matWVPLoc = gl.getUniformLocation(EllipseShader._prog, 'matWVP'); + EllipseShader.matPositionLoc = gl.getUniformLocation(EllipseShader._prog, 'matPosition'); + EllipseShader.positionNowLoc = gl.getUniformLocation(EllipseShader._prog, 'positionNow'); + EllipseShader.colorLoc = gl.getUniformLocation(EllipseShader._prog, 'color'); + EllipseShader.semiMajorAxisLoc = gl.getUniformLocation(EllipseShader._prog, 'semiMajorAxis'); + EllipseShader.eccentricityLoc = gl.getUniformLocation(EllipseShader._prog, 'eccentricity'); + EllipseShader.eccentricAnomalyLoc = gl.getUniformLocation(EllipseShader._prog, 'eccentricAnomaly'); + gl.enable(WEBGL.BLEND); + EllipseShader.initialized = true; +}; + +EllipseShader.use = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, lineColor, opacity, world, positionNow) { + var gl = renderContext.gl; + if (gl != null) { + if (!EllipseShader.initialized) { + EllipseShader.init(renderContext); + } + gl.useProgram(EllipseShader._prog); + var WVPPos = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(world, renderContext.get_view()), renderContext.get_projection()); + var WVP = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()), renderContext.get_projection()); + gl.uniformMatrix4fv(EllipseShader.matWVPLoc, false, WVP.floatArray()); + gl.uniformMatrix4fv(EllipseShader.matPositionLoc, false, WVPPos.floatArray()); + gl.uniform3f(EllipseShader.positionNowLoc, positionNow.x, positionNow.y, positionNow.z); + gl.uniform4f(EllipseShader.colorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); + gl.uniform1f(EllipseShader.semiMajorAxisLoc, semiMajorAxis); + gl.uniform1f(EllipseShader.eccentricityLoc, eccentricity); + gl.uniform1f(EllipseShader.eccentricAnomalyLoc, eccentricAnomaly); + gl.disable(WEBGL.DEPTH_TEST); + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.enableVertexAttribArray(EllipseShader.angleLoc); + gl.vertexAttribPointer(EllipseShader.angleLoc, 3, WEBGL.FLOAT, false, 0, 0); + gl.lineWidth(1); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } +}; + +var EllipseShader$ = {}; + +registerType("EllipseShader", [EllipseShader, EllipseShader$, null]); + + +// wwtlib.ModelShader + +export function ModelShader() { } + +ModelShader.vertLoc = 0; +ModelShader.normalLoc = 0; +ModelShader.textureLoc = 0; +ModelShader.initialized = false; +ModelShader._prog = null; +ModelShader.sunPosition = Vector3d.create(-1, -1, -1); +ModelShader.minLightingBrightness = 1; +ModelShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); + +ModelShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + uniform sampler2D uSampler; + uniform float opacity; + uniform vec3 uSunPosition; + uniform float uMinBrightness; + uniform vec3 uAtmosphereColor; + + void main(void) { + vec3 normal = normalize(vNormal); + vec3 camVN = normalize(vCamVector); + vec3 cam = normalize(vec3(0.0,0.0,-1.0)); + float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); + float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; + atm = (dt > uMinBrightness) ? atm : 0.0; + if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } + vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + gl_FragColor = col * opacity; + gl_FragColor.rgb *= dt; + gl_FragColor.rgb += atm * uAtmosphereColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec3 aNormal; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); + vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); + vTextureCoord = aTextureCoord; + vNormal = normalT; + } + `; + + ModelShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(ModelShader._frag, fragShaderText); + gl.compileShader(ModelShader._frag); + var stat = gl.getShaderParameter(ModelShader._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(ModelShader._frag); + } + ModelShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(ModelShader._vert, vertexShaderText); + gl.compileShader(ModelShader._vert); + var stat1 = gl.getShaderParameter(ModelShader._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(ModelShader._vert); + } + ModelShader._prog = gl.createProgram(); + gl.attachShader(ModelShader._prog, ModelShader._vert); + gl.attachShader(ModelShader._prog, ModelShader._frag); + gl.linkProgram(ModelShader._prog); + var errcode = gl.getProgramParameter(ModelShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(ModelShader._prog); + ModelShader.vertLoc = gl.getAttribLocation(ModelShader._prog, 'aVertexPosition'); + ModelShader.normalLoc = gl.getAttribLocation(ModelShader._prog, 'aNormal'); + ModelShader.textureLoc = gl.getAttribLocation(ModelShader._prog, 'aTextureCoord'); + ModelShader.projMatLoc = gl.getUniformLocation(ModelShader._prog, 'uPMatrix'); + ModelShader.mvMatLoc = gl.getUniformLocation(ModelShader._prog, 'uMVMatrix'); + ModelShader.sampLoc = gl.getUniformLocation(ModelShader._prog, 'uSampler'); + ModelShader.sunLoc = gl.getUniformLocation(ModelShader._prog, 'uSunPosition'); + ModelShader.minBrightnessLoc = gl.getUniformLocation(ModelShader._prog, 'uMinBrightness'); + ModelShader.opacityLoc = gl.getUniformLocation(ModelShader._prog, 'opacity'); + ModelShader.atmosphereColorLoc = gl.getUniformLocation(ModelShader._prog, 'uAtmosphereColor'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + ModelShader.initialized = true; +}; + +ModelShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, stride) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!ModelShader.initialized) { + ModelShader.init(renderContext); + } + gl.useProgram(ModelShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(ModelShader.opacityLoc, opacity); + gl.uniform1f(ModelShader.minBrightnessLoc, (renderContext.lighting) ? ModelShader.minLightingBrightness : 1); + if (renderContext.lighting) { + gl.uniform3f(ModelShader.atmosphereColorLoc, ModelShader.atmosphereColor.r / 255, ModelShader.atmosphereColor.g / 255, ModelShader.atmosphereColor.b / 255); + } else { + gl.uniform3f(ModelShader.atmosphereColorLoc, 0, 0, 0); + } + gl.uniformMatrix4fv(ModelShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(ModelShader.projMatLoc, false, renderContext.get_projection().floatArray()); + ModelShader.sunPosition.normalize(); + var mvInv = renderContext.get_view().clone(); + mvInv.set_m41(0); + mvInv.set_m42(0); + mvInv.set_m43(0); + mvInv.set_m44(1); + var sp = Vector3d._transformCoordinate(ModelShader.sunPosition, mvInv); + sp.normalize(); + gl.uniform3f(ModelShader.sunLoc, sp.x, sp.y, sp.z); + gl.uniform1i(ModelShader.sampLoc, 0); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(ModelShader.vertLoc); + gl.enableVertexAttribArray(ModelShader.normalLoc); + gl.enableVertexAttribArray(ModelShader.textureLoc); + gl.vertexAttribPointer(ModelShader.vertLoc, 3, WEBGL.FLOAT, false, stride, 0); + gl.vertexAttribPointer(ModelShader.normalLoc, 3, WEBGL.FLOAT, false, stride, 12); + gl.vertexAttribPointer(ModelShader.textureLoc, 2, WEBGL.FLOAT, false, stride, stride - 8); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var ModelShader$ = {}; + +registerType("ModelShader", [ModelShader, ModelShader$, null]); + + +// wwtlib.ModelShaderTan + +export function ModelShaderTan() { } + +ModelShaderTan.vertLoc = 0; +ModelShaderTan.normalLoc = 0; +ModelShaderTan.textureLoc = 0; +ModelShaderTan.initialized = false; +ModelShaderTan._prog = null; +ModelShaderTan.sunPosition = Vector3d.create(-1, -1, -1); +ModelShaderTan.minLightingBrightness = 1; +ModelShaderTan.atmosphereColor = Color.fromArgb(0, 0, 0, 0); + +ModelShaderTan.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + uniform sampler2D uSampler; + uniform float opacity; + uniform vec3 uSunPosition; + uniform float uMinBrightness; + uniform vec3 uAtmosphereColor; + + void main(void) { + vec3 normal = normalize(vNormal); + vec3 camVN = normalize(vCamVector); + vec3 cam = normalize(vec3(0.0,0.0,-1.0)); + float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); + float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; + atm = (dt > uMinBrightness) ? atm : 0.0; + if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } + vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + gl_FragColor = col * opacity; + gl_FragColor.rgb *= dt; + gl_FragColor.rgb += atm * uAtmosphereColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec3 aNormal; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); + vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); + vTextureCoord = aTextureCoord; + vNormal = normalT; + } + `; + + ModelShaderTan._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(ModelShaderTan._frag, fragShaderText); + gl.compileShader(ModelShaderTan._frag); + var stat = gl.getShaderParameter(ModelShaderTan._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(ModelShaderTan._frag); + } + ModelShaderTan._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(ModelShaderTan._vert, vertexShaderText); + gl.compileShader(ModelShaderTan._vert); + var stat1 = gl.getShaderParameter(ModelShaderTan._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(ModelShaderTan._vert); + } + ModelShaderTan._prog = gl.createProgram(); + gl.attachShader(ModelShaderTan._prog, ModelShaderTan._vert); + gl.attachShader(ModelShaderTan._prog, ModelShaderTan._frag); + gl.linkProgram(ModelShaderTan._prog); + var errcode = gl.getProgramParameter(ModelShaderTan._prog, WEBGL.LINK_STATUS); + gl.useProgram(ModelShaderTan._prog); + ModelShaderTan.vertLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aVertexPosition'); + ModelShaderTan.normalLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aNormal'); + ModelShaderTan.textureLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aTextureCoord'); + ModelShaderTan.projMatLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uPMatrix'); + ModelShaderTan.mvMatLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uMVMatrix'); + ModelShaderTan.sampLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uSampler'); + ModelShaderTan.sunLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uSunPosition'); + ModelShaderTan.minBrightnessLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uMinBrightness'); + ModelShaderTan.opacityLoc = gl.getUniformLocation(ModelShaderTan._prog, 'opacity'); + ModelShaderTan.atmosphereColorLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uAtmosphereColor'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + ModelShaderTan.initialized = true; +}; + +ModelShaderTan.use = function (renderContext, vertex, index, texture, opacity, noDepth, stride) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!ModelShaderTan.initialized) { + ModelShaderTan.init(renderContext); + } + gl.useProgram(ModelShaderTan._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(ModelShaderTan.opacityLoc, opacity); + gl.uniform1f(ModelShaderTan.minBrightnessLoc, (renderContext.lighting) ? ModelShaderTan.minLightingBrightness : 1); + if (renderContext.lighting) { + gl.uniform3f(ModelShaderTan.atmosphereColorLoc, ModelShaderTan.atmosphereColor.r / 255, ModelShaderTan.atmosphereColor.g / 255, ModelShaderTan.atmosphereColor.b / 255); + } else { + gl.uniform3f(ModelShaderTan.atmosphereColorLoc, 0, 0, 0); + } + gl.uniformMatrix4fv(ModelShaderTan.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(ModelShaderTan.projMatLoc, false, renderContext.get_projection().floatArray()); + ModelShaderTan.sunPosition.normalize(); + var mvInv = renderContext.get_view().clone(); + mvInv.set_m41(0); + mvInv.set_m42(0); + mvInv.set_m43(0); + mvInv.set_m44(1); + var sp = Vector3d._transformCoordinate(ModelShaderTan.sunPosition, mvInv); + sp.normalize(); + gl.uniform3f(ModelShaderTan.sunLoc, -sp.x, -sp.y, -sp.z); + gl.uniform1i(ModelShaderTan.sampLoc, 0); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(ModelShaderTan.vertLoc); + gl.enableVertexAttribArray(ModelShaderTan.normalLoc); + gl.enableVertexAttribArray(ModelShaderTan.textureLoc); + gl.vertexAttribPointer(ModelShaderTan.vertLoc, 3, WEBGL.FLOAT, false, stride, 0); + gl.vertexAttribPointer(ModelShaderTan.normalLoc, 3, WEBGL.FLOAT, false, stride, 12); + gl.vertexAttribPointer(ModelShaderTan.textureLoc, 2, WEBGL.FLOAT, false, stride, stride - 8); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var ModelShaderTan$ = {}; + +registerType("ModelShaderTan", [ModelShaderTan, ModelShaderTan$, null]); + + +// wwtlib.TileShader + +export function TileShader() { } + +TileShader.vertLoc = 0; +TileShader.textureLoc = 0; +TileShader.initialized = false; +TileShader._prog = null; +TileShader.sunPosition = Vector3d.create(-1, -1, -1); +TileShader.minLightingBrightness = 1; +TileShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); + +TileShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + uniform sampler2D uSampler; + uniform float opacity; + uniform vec3 uSunPosition; + uniform float uMinBrightness; + uniform vec3 uAtmosphereColor; + + void main(void) { + vec3 normal = normalize(vNormal); + vec3 camVN = normalize(vCamVector); + vec3 cam = normalize(vec3(0.0,0.0,-1.0)); + float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); + float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; + atm = (dt > uMinBrightness) ? atm : 0.0; + if ( uMinBrightness == 1.0 ) { dt = 1.0; atm = 0.0; } + vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + gl_FragColor = col * opacity; + gl_FragColor.rgb *= dt; + gl_FragColor.rgb += atm * uAtmosphereColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + uniform vec3 uCenterScreen; + uniform vec3 uCenterWorld; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + void main(void) { + vec3 normal; + + if (length(uCenterWorld) > 0.00001) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0); + vCamVector = normalize((mat3(uMVMatrix) * (aVertexPosition + uCenterWorld)).xyz); + normal = normalize(aVertexPosition + uCenterWorld); + } else { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); + normal = normalize(aVertexPosition); + } + + vec3 normalT = normalize(mat3(uMVMatrix) * normal); + vTextureCoord = aTextureCoord; + vNormal = normalT; + } + `; + + TileShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(TileShader._frag, fragShaderText); + gl.compileShader(TileShader._frag); + var stat = gl.getShaderParameter(TileShader._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(TileShader._frag); + } + TileShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(TileShader._vert, vertexShaderText); + gl.compileShader(TileShader._vert); + var stat1 = gl.getShaderParameter(TileShader._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(TileShader._vert); + } + TileShader._prog = gl.createProgram(); + gl.attachShader(TileShader._prog, TileShader._vert); + gl.attachShader(TileShader._prog, TileShader._frag); + gl.linkProgram(TileShader._prog); + var errcode = gl.getProgramParameter(TileShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(TileShader._prog); + TileShader.vertLoc = gl.getAttribLocation(TileShader._prog, 'aVertexPosition'); + TileShader.textureLoc = gl.getAttribLocation(TileShader._prog, 'aTextureCoord'); + TileShader.projMatLoc = gl.getUniformLocation(TileShader._prog, 'uPMatrix'); + TileShader.mvMatLoc = gl.getUniformLocation(TileShader._prog, 'uMVMatrix'); + TileShader.sampLoc = gl.getUniformLocation(TileShader._prog, 'uSampler'); + TileShader.centerScreenLoc = gl.getUniformLocation(TileShader._prog, 'uCenterScreen'); + TileShader.centerWorldLoc = gl.getUniformLocation(TileShader._prog, 'uCenterWorld'); + TileShader.sunLoc = gl.getUniformLocation(TileShader._prog, 'uSunPosition'); + TileShader.minBrightnessLoc = gl.getUniformLocation(TileShader._prog, 'uMinBrightness'); + TileShader.opacityLoc = gl.getUniformLocation(TileShader._prog, 'opacity'); + TileShader.atmosphereColorLoc = gl.getUniformLocation(TileShader._prog, 'uAtmosphereColor'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + TileShader.initialized = true; +}; + +TileShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, centerWorld) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!TileShader.initialized) { + TileShader.init(renderContext); + } + gl.useProgram(TileShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(TileShader.opacityLoc, opacity); + gl.uniform1f(TileShader.minBrightnessLoc, (renderContext.lighting) ? TileShader.minLightingBrightness : 1); + if (renderContext.lighting) { + gl.uniform3f(TileShader.atmosphereColorLoc, TileShader.atmosphereColor.r / 255, TileShader.atmosphereColor.g / 255, TileShader.atmosphereColor.b / 255); + } else { + gl.uniform3f(TileShader.atmosphereColorLoc, 0, 0, 0); + } + gl.uniform3f(TileShader.centerWorldLoc, centerWorld.x, centerWorld.y, centerWorld.z); + + // "This would be clearer by making the 'centerWorld' parameter optional. Unfortunately, that's not allowed in C# 2.0" + if (centerWorld.lengthSq() > 0.001) { + var wvp = Matrix3d.multiplyMatrix(mvMat, renderContext.get_projection()); + var centerScreen = wvp.transform(centerWorld); + gl.uniform3f(TileShader.centerScreenLoc, centerScreen.x, centerScreen.y, centerScreen.z); + } else { + gl.uniform3f(TileShader.centerScreenLoc, 0, 0, 0); + } + gl.uniformMatrix4fv(TileShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(TileShader.projMatLoc, false, renderContext.get_projection().floatArray()); + TileShader.sunPosition.normalize(); + var mvInv = renderContext.get_view().clone(); + mvInv.set_m41(0); + mvInv.set_m42(0); + mvInv.set_m43(0); + mvInv.set_m44(1); + var sp = Vector3d._transformCoordinate(TileShader.sunPosition, mvInv); + sp.normalize(); + gl.uniform3f(TileShader.sunLoc, -sp.x, -sp.y, -sp.z); + gl.uniform1i(TileShader.sampLoc, 0); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(TileShader.vertLoc); + gl.enableVertexAttribArray(TileShader.textureLoc); + gl.vertexAttribPointer(TileShader.vertLoc, 3, WEBGL.FLOAT, false, 20, 0); + gl.vertexAttribPointer(TileShader.textureLoc, 2, WEBGL.FLOAT, false, 20, 12); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var TileShader$ = {}; + +registerType("TileShader", [TileShader, TileShader$, null]); + + +// wwtlib.FitsShader + +export function FitsShader() { } + +FitsShader.vertLoc = 0; +FitsShader.textureLoc = 0; +FitsShader.initialized = false; +FitsShader._prog = null; +FitsShader.blankValue = 0; +FitsShader.bScale = 1; +FitsShader.bZero = 0; +FitsShader.min = 0; +FitsShader.max = 0; +FitsShader.transparentBlack = false; +FitsShader.containsBlanks = false; +FitsShader.scaleType = 0; + +FitsShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + #version 300 es + + precision mediump float; + in vec2 vTextureCoord; + in vec3 vNormal; + in vec3 vCamVector; + out vec4 fragmentColor; + + uniform sampler2D uSampler; + uniform sampler2D colorSampler; + uniform float blank; + uniform float bzero; + uniform float bscale; + uniform float min; + uniform float max; + uniform bool containsBlanks; + uniform bool transparentBlack; + uniform int scaleType; + uniform float opacity; + + bool isNaN(float value) { + // See https://stackoverflow.com/questions/9446888/best-way-to-detect-nans-in-opengl-shaders + // PKGW also finds that we need "value != value" on his Dell laptop running + // Chrome on Linux. + return (value != value) || !(value < 0.0 || 0.0 < value || value == 0.0); + } + + void main(void) { + //FITS images are flipped on the y axis + vec4 color = texture(uSampler, vec2(vTextureCoord.x, 1.0 - vTextureCoord.y)); + + if(isNaN(color.r) || (containsBlanks && abs(blank - color.r) < 0.00000001)){ + fragmentColor = vec4(0.0, 0.0, 0.0, 0.0); + } else { + float physicalValue = (bzero + bscale * color.r - min) / (max - min); + if(transparentBlack && physicalValue <= 0.0){ + fragmentColor = vec4(0.0, 0.0, 0.0, 0.0); + return; + } + + physicalValue = clamp(physicalValue, 0.0, 1.0); + + switch(scaleType){ + case 1: + physicalValue = log(physicalValue * 255.0 + 1.0 ) / log(256.0); + break; + case 2: + physicalValue = physicalValue * physicalValue; + break; + case 3: + physicalValue = sqrt(physicalValue); + break; + } + vec4 colorFromColorMapper = texture(colorSampler, vec2(physicalValue, 0.5)); + fragmentColor = vec4(colorFromColorMapper.rgb, opacity); + } + } + `; + + const vertexShaderText = `\ + #version 300 es + + in vec3 aVertexPosition; + in vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + uniform vec3 uCenterScreen; + + out vec2 vTextureCoord; + + void main(void) { + if(length(uCenterScreen) > 0.0000001) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0); + } else { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + } + + vTextureCoord = aTextureCoord; + } + `; + + FitsShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(FitsShader._frag, fragShaderText); + gl.compileShader(FitsShader._frag); + var stat = gl.getShaderParameter(FitsShader._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(FitsShader._frag); + console.log(errorF); + } + FitsShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(FitsShader._vert, vertexShaderText); + gl.compileShader(FitsShader._vert); + var stat1 = gl.getShaderParameter(FitsShader._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(FitsShader._vert); + console.log(errorV); + } + FitsShader._prog = gl.createProgram(); + gl.attachShader(FitsShader._prog, FitsShader._vert); + gl.attachShader(FitsShader._prog, FitsShader._frag); + gl.linkProgram(FitsShader._prog); + var errcode = gl.getProgramParameter(FitsShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(FitsShader._prog); + FitsShader.vertLoc = gl.getAttribLocation(FitsShader._prog, 'aVertexPosition'); + FitsShader.textureLoc = gl.getAttribLocation(FitsShader._prog, 'aTextureCoord'); + FitsShader.projMatLoc = gl.getUniformLocation(FitsShader._prog, 'uPMatrix'); + FitsShader.mvMatLoc = gl.getUniformLocation(FitsShader._prog, 'uMVMatrix'); + FitsShader.sampLoc = gl.getUniformLocation(FitsShader._prog, 'uSampler'); + FitsShader.colorLoc = gl.getUniformLocation(FitsShader._prog, 'colorSampler'); + FitsShader.centerScreenLoc = gl.getUniformLocation(FitsShader._prog, 'uCenterScreen'); + FitsShader.blank = gl.getUniformLocation(FitsShader._prog, 'blank'); + FitsShader.bzero = gl.getUniformLocation(FitsShader._prog, 'bzero'); + FitsShader.bscale = gl.getUniformLocation(FitsShader._prog, 'bscale'); + FitsShader.minLoc = gl.getUniformLocation(FitsShader._prog, 'min'); + FitsShader.maxLoc = gl.getUniformLocation(FitsShader._prog, 'max'); + FitsShader.transparentBlackLoc = gl.getUniformLocation(FitsShader._prog, 'transparentBlack'); + FitsShader.containsBlanksLoc = gl.getUniformLocation(FitsShader._prog, 'containsBlanks'); + FitsShader.scalingLocation = gl.getUniformLocation(FitsShader._prog, 'scaleType'); + FitsShader.opacityLoc = gl.getUniformLocation(FitsShader._prog, 'opacity'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + FitsShader.initialized = true; +}; + +FitsShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, centerWorld) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!FitsShader.initialized) { + FitsShader.init(renderContext); + } + gl.useProgram(FitsShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(FitsShader.opacityLoc, opacity); + gl.uniformMatrix4fv(FitsShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(FitsShader.projMatLoc, false, renderContext.get_projection().floatArray()); + + // "This would be clearer by making the 'centerWorld' parameter optional. Unfortunately, that's not allowed in C# 2.0" + if (centerWorld.lengthSq() > 0.001) { + var wvp = Matrix3d.multiplyMatrix(mvMat, renderContext.get_projection()); + var centerScreen = wvp.transform(centerWorld); + gl.uniform3f(FitsShader.centerScreenLoc, centerScreen.x, centerScreen.y, centerScreen.z); + } else { + gl.uniform3f(FitsShader.centerScreenLoc, 0, 0, 0); + } + + gl.uniform1i(FitsShader.sampLoc, 0); + gl.uniform1i(FitsShader.colorLoc, 1); + gl.uniform1f(FitsShader.blank, FitsShader.blankValue); + gl.uniform1f(FitsShader.bzero, FitsShader.bZero); + gl.uniform1f(FitsShader.bscale, FitsShader.bScale); + gl.uniform1f(FitsShader.minLoc, FitsShader.min); + gl.uniform1f(FitsShader.maxLoc, FitsShader.max); + gl.uniform1i(FitsShader.transparentBlackLoc, FitsShader.transparentBlack); + gl.uniform1i(FitsShader.containsBlanksLoc, FitsShader.containsBlanks); + gl.uniform1i(FitsShader.scalingLocation, FitsShader.scaleType); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(FitsShader.vertLoc); + gl.enableVertexAttribArray(FitsShader.textureLoc); + gl.vertexAttribPointer(FitsShader.vertLoc, 3, WEBGL.FLOAT, false, 20, 0); + gl.vertexAttribPointer(FitsShader.textureLoc, 2, WEBGL.FLOAT, false, 20, 12); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var FitsShader$ = {}; + +registerType("FitsShader", [FitsShader, FitsShader$, null]); + + +// wwtlib.ImageShader + +export function ImageShader() { } + +ImageShader.vertLoc = 0; +ImageShader.textureLoc = 0; +ImageShader.initialized = false; +ImageShader._prog = null; + +ImageShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + + uniform sampler2D uSampler; + uniform float opacity; + + void main(void) { + vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + gl_FragColor = col * opacity; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vTextureCoord = aTextureCoord; + } + `; + + ImageShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(ImageShader._frag, fragShaderText); + gl.compileShader(ImageShader._frag); + var stat = gl.getShaderParameter(ImageShader._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(ImageShader._frag); + } + ImageShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(ImageShader._vert, vertexShaderText); + gl.compileShader(ImageShader._vert); + var stat1 = gl.getShaderParameter(ImageShader._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(ImageShader._vert); + } + ImageShader._prog = gl.createProgram(); + gl.attachShader(ImageShader._prog, ImageShader._vert); + gl.attachShader(ImageShader._prog, ImageShader._frag); + gl.linkProgram(ImageShader._prog); + var errcode = gl.getProgramParameter(ImageShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(ImageShader._prog); + ImageShader.vertLoc = gl.getAttribLocation(ImageShader._prog, 'aVertexPosition'); + ImageShader.textureLoc = gl.getAttribLocation(ImageShader._prog, 'aTextureCoord'); + ImageShader.projMatLoc = gl.getUniformLocation(ImageShader._prog, 'uPMatrix'); + ImageShader.mvMatLoc = gl.getUniformLocation(ImageShader._prog, 'uMVMatrix'); + ImageShader.sampLoc = gl.getUniformLocation(ImageShader._prog, 'uSampler'); + ImageShader.opacityLoc = gl.getUniformLocation(ImageShader._prog, 'opacity'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + ImageShader.initialized = true; +}; + +ImageShader.use = function (renderContext, vertex, index, texture, opacity, noDepth) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!ImageShader.initialized) { + ImageShader.init(renderContext); + } + gl.useProgram(ImageShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(ImageShader.opacityLoc, opacity); + gl.uniformMatrix4fv(ImageShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(ImageShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(ImageShader.sampLoc, 0); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(ImageShader.vertLoc); + gl.enableVertexAttribArray(ImageShader.textureLoc); + gl.vertexAttribPointer(ImageShader.vertLoc, 3, WEBGL.FLOAT, false, 20, 0); + gl.vertexAttribPointer(ImageShader.textureLoc, 2, WEBGL.FLOAT, false, 20, 12); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var ImageShader$ = {}; + +registerType("ImageShader", [ImageShader, ImageShader$, null]); + + +// wwtlib.ImageShader2 + +export function ImageShader2() { } + +ImageShader2.vertLoc = 0; +ImageShader2.textureLoc = 0; +ImageShader2.initialized = false; +ImageShader2._prog = null; + +ImageShader2.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + + uniform sampler2D uSampler; + uniform float opacity; + + void main(void) { + vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + gl_FragColor = col * opacity; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec3 vNormal; + varying vec3 vCamVector; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vTextureCoord = aTextureCoord; + } + `; + + ImageShader2._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(ImageShader2._frag, fragShaderText); + gl.compileShader(ImageShader2._frag); + var stat = gl.getShaderParameter(ImageShader2._frag, WEBGL.COMPILE_STATUS); + if (!stat) { + var errorF = gl.getShaderInfoLog(ImageShader2._frag); + } + ImageShader2._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(ImageShader2._vert, vertexShaderText); + gl.compileShader(ImageShader2._vert); + var stat1 = gl.getShaderParameter(ImageShader2._vert, WEBGL.COMPILE_STATUS); + if (!stat1) { + var errorV = gl.getShaderInfoLog(ImageShader2._vert); + } + ImageShader2._prog = gl.createProgram(); + gl.attachShader(ImageShader2._prog, ImageShader2._vert); + gl.attachShader(ImageShader2._prog, ImageShader2._frag); + gl.linkProgram(ImageShader2._prog); + var errcode = gl.getProgramParameter(ImageShader2._prog, WEBGL.LINK_STATUS); + gl.useProgram(ImageShader2._prog); + ImageShader2.vertLoc = gl.getAttribLocation(ImageShader2._prog, 'aVertexPosition'); + ImageShader2.textureLoc = gl.getAttribLocation(ImageShader2._prog, 'aTextureCoord'); + ImageShader2.projMatLoc = gl.getUniformLocation(ImageShader2._prog, 'uPMatrix'); + ImageShader2.mvMatLoc = gl.getUniformLocation(ImageShader2._prog, 'uMVMatrix'); + ImageShader2.sampLoc = gl.getUniformLocation(ImageShader2._prog, 'uSampler'); + ImageShader2.opacityLoc = gl.getUniformLocation(ImageShader2._prog, 'opacity'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + ImageShader2.initialized = true; +}; + +ImageShader2.use = function (renderContext, vertex, index, texture, opacity, noDepth) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!ImageShader2.initialized) { + ImageShader2.init(renderContext); + } + gl.useProgram(ImageShader2._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniform1f(ImageShader2.opacityLoc, opacity); + gl.uniformMatrix4fv(ImageShader2.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(ImageShader2.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(ImageShader2.sampLoc, 0); + if (renderContext.space || noDepth) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(ImageShader2.vertLoc); + gl.enableVertexAttribArray(ImageShader2.textureLoc); + gl.vertexAttribPointer(ImageShader2.vertLoc, 3, WEBGL.FLOAT, false, 32, 0); + gl.vertexAttribPointer(ImageShader2.textureLoc, 2, WEBGL.FLOAT, false, 32, 24); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, index); + gl.enable(WEBGL.BLEND); + if (noDepth) { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE); + } else { + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } + } +}; + +var ImageShader2$ = {}; + +registerType("ImageShader2", [ImageShader2, ImageShader2$, null]); + + +// wwtlib.SpriteShader + +export function SpriteShader() { } + +SpriteShader.vertLoc = 0; +SpriteShader.textureLoc = 0; +SpriteShader.colorLoc = 0; +SpriteShader.initialized = false; +SpriteShader._prog = null; + +SpriteShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + varying lowp vec4 vColor; + uniform sampler2D uSampler; + + void main(void) { + gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * vColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + attribute lowp vec4 aColor; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec4 vColor; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + } + `; + + SpriteShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(SpriteShader._frag, fragShaderText); + gl.compileShader(SpriteShader._frag); + var stat = gl.getShaderParameter(SpriteShader._frag, WEBGL.COMPILE_STATUS); + SpriteShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(SpriteShader._vert, vertexShaderText); + gl.compileShader(SpriteShader._vert); + var stat1 = gl.getShaderParameter(SpriteShader._vert, WEBGL.COMPILE_STATUS); + SpriteShader._prog = gl.createProgram(); + gl.attachShader(SpriteShader._prog, SpriteShader._vert); + gl.attachShader(SpriteShader._prog, SpriteShader._frag); + gl.linkProgram(SpriteShader._prog); + var errcode = gl.getProgramParameter(SpriteShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(SpriteShader._prog); + SpriteShader.vertLoc = gl.getAttribLocation(SpriteShader._prog, 'aVertexPosition'); + SpriteShader.textureLoc = gl.getAttribLocation(SpriteShader._prog, 'aTextureCoord'); + SpriteShader.colorLoc = gl.getAttribLocation(SpriteShader._prog, 'aColor'); + SpriteShader.projMatLoc = gl.getUniformLocation(SpriteShader._prog, 'uPMatrix'); + SpriteShader.mvMatLoc = gl.getUniformLocation(SpriteShader._prog, 'uMVMatrix'); + SpriteShader.sampLoc = gl.getUniformLocation(SpriteShader._prog, 'uSampler'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + SpriteShader.initialized = true; +}; + +SpriteShader.use = function (renderContext, vertex, texture) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!SpriteShader.initialized) { + SpriteShader.init(renderContext); + } + gl.useProgram(SpriteShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(SpriteShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(SpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(SpriteShader.sampLoc, 0); + gl.disable(WEBGL.DEPTH_TEST); + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(SpriteShader.vertLoc); + gl.enableVertexAttribArray(SpriteShader.textureLoc); + gl.enableVertexAttribArray(SpriteShader.colorLoc); + gl.vertexAttribPointer(SpriteShader.vertLoc, 3, WEBGL.FLOAT, false, 36, 0); + gl.vertexAttribPointer(SpriteShader.colorLoc, 4, WEBGL.FLOAT, false, 36, 12); + gl.vertexAttribPointer(SpriteShader.textureLoc, 2, WEBGL.FLOAT, false, 36, 28); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var SpriteShader$ = {}; + +registerType("SpriteShader", [SpriteShader, SpriteShader$, null]); + + +// wwtlib.ShapeSpriteShader + +export function ShapeSpriteShader() { } + +ShapeSpriteShader.vertLoc = 0; +ShapeSpriteShader.textureLoc = 0; +ShapeSpriteShader.colorLoc = 0; +ShapeSpriteShader.initialized = false; +ShapeSpriteShader._prog = null; + +ShapeSpriteShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying lowp vec4 vColor; + + void main(void) { + gl_FragColor = vColor; + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute lowp vec4 aColor; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + varying vec4 vColor; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vColor = aColor; + } + `; + + ShapeSpriteShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(ShapeSpriteShader._frag, fragShaderText); + gl.compileShader(ShapeSpriteShader._frag); + var stat = gl.getShaderParameter(ShapeSpriteShader._frag, WEBGL.COMPILE_STATUS); + ShapeSpriteShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(ShapeSpriteShader._vert, vertexShaderText); + gl.compileShader(ShapeSpriteShader._vert); + var stat1 = gl.getShaderParameter(ShapeSpriteShader._vert, WEBGL.COMPILE_STATUS); + ShapeSpriteShader._prog = gl.createProgram(); + gl.attachShader(ShapeSpriteShader._prog, ShapeSpriteShader._vert); + gl.attachShader(ShapeSpriteShader._prog, ShapeSpriteShader._frag); + gl.linkProgram(ShapeSpriteShader._prog); + var errcode = gl.getProgramParameter(ShapeSpriteShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(ShapeSpriteShader._prog); + ShapeSpriteShader.vertLoc = gl.getAttribLocation(ShapeSpriteShader._prog, 'aVertexPosition'); + ShapeSpriteShader.colorLoc = gl.getAttribLocation(ShapeSpriteShader._prog, 'aColor'); + ShapeSpriteShader.projMatLoc = gl.getUniformLocation(ShapeSpriteShader._prog, 'uPMatrix'); + ShapeSpriteShader.mvMatLoc = gl.getUniformLocation(ShapeSpriteShader._prog, 'uMVMatrix'); + gl.disable(WEBGL.DEPTH_TEST); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + ShapeSpriteShader.initialized = true; +}; + +ShapeSpriteShader.use = function (renderContext, vertex) { + var gl = renderContext.gl; + if (gl != null) { + if (!ShapeSpriteShader.initialized) { + ShapeSpriteShader.init(renderContext); + } + gl.useProgram(ShapeSpriteShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(ShapeSpriteShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(ShapeSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(ShapeSpriteShader.sampLoc, 0); + gl.disable(WEBGL.DEPTH_TEST); + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(ShapeSpriteShader.vertLoc); + gl.enableVertexAttribArray(ShapeSpriteShader.textureLoc); + gl.enableVertexAttribArray(ShapeSpriteShader.colorLoc); + gl.vertexAttribPointer(ShapeSpriteShader.vertLoc, 3, WEBGL.FLOAT, false, 36, 0); + gl.vertexAttribPointer(ShapeSpriteShader.colorLoc, 4, WEBGL.FLOAT, false, 36, 12); + gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var ShapeSpriteShader$ = {}; + +registerType("ShapeSpriteShader", [ShapeSpriteShader, ShapeSpriteShader$, null]); + + +// wwtlib.TextShader + +export function TextShader() { } + +TextShader.vertLoc = 0; +TextShader.textureLoc = 0; +TextShader.initialized = false; +TextShader._prog = null; + +TextShader.init = function (renderContext) { + var gl = renderContext.gl; + + const fragShaderText = `\ + precision mediump float; + + varying vec2 vTextureCoord; + + uniform sampler2D uSampler; + + void main(void) { + gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); + } + `; + + const vertexShaderText = `\ + attribute vec3 aVertexPosition; + attribute vec2 aTextureCoord; + + uniform mat4 uMVMatrix; + uniform mat4 uPMatrix; + + varying vec2 vTextureCoord; + + void main(void) { + gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); + vTextureCoord = aTextureCoord; + } + `; + + TextShader._frag = gl.createShader(WEBGL.FRAGMENT_SHADER); + gl.shaderSource(TextShader._frag, fragShaderText); + gl.compileShader(TextShader._frag); + var stat = gl.getShaderParameter(TextShader._frag, WEBGL.COMPILE_STATUS); + TextShader._vert = gl.createShader(WEBGL.VERTEX_SHADER); + gl.shaderSource(TextShader._vert, vertexShaderText); + gl.compileShader(TextShader._vert); + var stat1 = gl.getShaderParameter(TextShader._vert, WEBGL.COMPILE_STATUS); + TextShader._prog = gl.createProgram(); + gl.attachShader(TextShader._prog, TextShader._vert); + gl.attachShader(TextShader._prog, TextShader._frag); + gl.linkProgram(TextShader._prog); + var errcode = gl.getProgramParameter(TextShader._prog, WEBGL.LINK_STATUS); + gl.useProgram(TextShader._prog); + TextShader.vertLoc = gl.getAttribLocation(TextShader._prog, 'aVertexPosition'); + TextShader.textureLoc = gl.getAttribLocation(TextShader._prog, 'aTextureCoord'); + TextShader.projMatLoc = gl.getUniformLocation(TextShader._prog, 'uPMatrix'); + TextShader.mvMatLoc = gl.getUniformLocation(TextShader._prog, 'uMVMatrix'); + TextShader.sampLoc = gl.getUniformLocation(TextShader._prog, 'uSampler'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + TextShader.initialized = true; +}; + +TextShader.use = function (renderContext, vertex, texture) { + if (texture == null) { + texture = Texture.getEmpty(); + } + var gl = renderContext.gl; + if (gl != null) { + if (!TextShader.initialized) { + TextShader.init(renderContext); + } + gl.useProgram(TextShader._prog); + var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + gl.uniformMatrix4fv(TextShader.mvMatLoc, false, mvMat.floatArray()); + gl.uniformMatrix4fv(TextShader.projMatLoc, false, renderContext.get_projection().floatArray()); + gl.uniform1i(TextShader.sampLoc, 0); + if (renderContext.space) { + gl.disable(WEBGL.DEPTH_TEST); + } else { + gl.enable(WEBGL.DEPTH_TEST); + } + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(1); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(3); + gl.bindBuffer(WEBGL.ARRAY_BUFFER, vertex); + gl.enableVertexAttribArray(TextShader.vertLoc); + gl.enableVertexAttribArray(TextShader.textureLoc); + gl.vertexAttribPointer(TextShader.vertLoc, 3, WEBGL.FLOAT, false, 20, 0); + gl.vertexAttribPointer(TextShader.textureLoc, 2, WEBGL.FLOAT, false, 20, 12); + gl.activeTexture(WEBGL.TEXTURE0); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); + gl.enable(WEBGL.BLEND); + gl.blendFunc(WEBGL.SRC_ALPHA, WEBGL.ONE_MINUS_SRC_ALPHA); + } +}; + +var TextShader$ = {}; + +registerType("TextShader", [TextShader, TextShader$, null]); diff --git a/engine/esm/graphics/sprite2d.js b/engine/esm/graphics/sprite2d.js new file mode 100644 index 00000000..51310457 --- /dev/null +++ b/engine/esm/graphics/sprite2d.js @@ -0,0 +1,84 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Sprites. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { tilePrepDevice } from "../render_globals.js"; +import { SpriteShader, ShapeSpriteShader } from "./shaders.js"; +import { WEBGL } from "./webgl_constants.js"; + + +// wwtlib.Sprite2d + +export function Sprite2d() { + this.vertCount = 0; +} + +var Sprite2d$ = { + draw: function (renderContext, points, count, texture, triangleStrips, opacity) { + if (this.vertexBuffer == null) { + this.create(points); + } else { + this.update(points); + } + if (texture == null) { + ShapeSpriteShader.use(renderContext, this.vertexBuffer); + renderContext.gl.drawArrays(triangleStrips ? WEBGL.TRIANGLE_STRIP : WEBGL.TRIANGLES, 0, points.length); + } else { + SpriteShader.use(renderContext, this.vertexBuffer, (texture != null) ? texture.texture2d : null); + renderContext.gl.drawArrays(triangleStrips ? WEBGL.TRIANGLE_STRIP : WEBGL.TRIANGLES, 0, points.length); + } + }, + + create: function (verts) { + this.vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(verts.length * 9); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(verts); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.color.r / 255; + buffer[index++] = pt.color.g / 255; + buffer[index++] = pt.color.b / 255; + buffer[index++] = pt.color.a / 255; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.DYNAMIC_DRAW); + }, + + update: function (verts) { + if (this.vertCount < verts.length) { + tilePrepDevice.deleteBuffer(this.vertexBuffer); + this.create(verts); + return; + } + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this.vertexBuffer); + var f32array = new Float32Array(verts.length * 9); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(verts); + while ($enum1.moveNext()) { + var pt = $enum1.current; + buffer[index++] = pt.position.x; + buffer[index++] = pt.position.y; + buffer[index++] = pt.position.z; + buffer[index++] = pt.color.r / 255; + buffer[index++] = pt.color.g / 255; + buffer[index++] = pt.color.b / 255; + buffer[index++] = pt.color.a / 255; + buffer[index++] = pt.tu; + buffer[index++] = pt.tv; + } + tilePrepDevice.bufferSubData(WEBGL.ARRAY_BUFFER, 0, f32array); + } +}; + +registerType("Sprite2d", [Sprite2d, Sprite2d$, null]); diff --git a/engine/esm/graphics/tessellator.js b/engine/esm/graphics/tessellator.js new file mode 100644 index 00000000..4402f016 --- /dev/null +++ b/engine/esm/graphics/tessellator.js @@ -0,0 +1,124 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tessellator algorithm. + +import { registerType } from "../typesystem.js"; +import { Vector3d } from "../double3d.js"; + + +// wwtlib.Tessellator + +export function Tessellator() { } + +Tessellator.tesselateSimplePoly = function (inputList) { + var results = []; + var tess = new Tessellator(); + tess.process(inputList, results); + return results; +}; + +var Tessellator$ = { + _isLeftOfHalfSpace: function (pntA, pntB, pntTest) { + pntA.normalize(); + pntB.normalize(); + var cross = Vector3d.cross(pntA, pntB); + var dot = Vector3d.dot(cross, pntTest); + return dot > 0; + }, + + _insideTriangle: function (pntA, pntB, pntC, pntTest) { + if (!this._isLeftOfHalfSpace(pntA, pntB, pntTest)) { + return false; + } + if (!this._isLeftOfHalfSpace(pntB, pntC, pntTest)) { + return false; + } + if (!this._isLeftOfHalfSpace(pntC, pntA, pntTest)) { + return false; + } + return true; + }, + + _canClipEar: function (poly, u, v, w, n, verts) { + var p; + var a = poly[verts[u]].copy(); + var b = poly[verts[v]].copy(); + var c = poly[verts[w]].copy(); + var P; + var d = Vector3d.subtractVectors(b, a); + d.normalize(); + var e = Vector3d.subtractVectors(b, c); + e.normalize(); + var g = Vector3d.cross(d, e); + var bn = b.copy(); + bn.normalize(); + + // Determine if convex edge + if (Vector3d.dot(g, bn) > 0) { + return false; + } + + // Check for any intersecting vertices that would invalidate this ear + for (p = 0; p < n; p++) { + if ((p === u) || (p === v) || (p === w)) { + continue; + } + P = poly[verts[p]].copy(); + + // don't clip earth if other intersecting vertex + if (this._insideTriangle(a, b, c, P)) { + return false; + } + } + return true; + }, + + process: function (poly, result) { + var n = poly.length; + if (poly.length < 3) { + return false; + } + var verts = new Array(poly.length); + for (var i = 0; i < n; i++) { + verts[i] = i; + } + var nv = n; + var count = 2 * nv; + for (var m = 0, v = nv - 1; nv > 2;) { + if (0 >= (count--)) { + // not enough ears to clip. Non-Simple Polygon + return false; + } + var u = v; + if (nv <= u) { + u = 0; + } + v = u + 1; + if (nv <= v) { + v = 0; + } + var w = v + 1; + if (nv <= w) { + w = 0; + } + if (this._canClipEar(poly, u, v, w, nv, verts)) { + var s, t; + result.push(verts[u]); + result.push(verts[v]); + result.push(verts[w]); + m++; + + // remove clipped ear + for (s = v, t = v + 1; t < nv; s++, t++) { + verts[s] = verts[t]; + } + nv--; + count = 2 * nv; + } + } + return true; + } +}; + +registerType("Tessellator", [Tessellator, Tessellator$, null]); diff --git a/engine/esm/graphics/texture.js b/engine/esm/graphics/texture.js new file mode 100644 index 00000000..0cbb0381 --- /dev/null +++ b/engine/esm/graphics/texture.js @@ -0,0 +1,128 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The basic GL texture type. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { tilePrepDevice } from "../render_globals.js"; +import { URLHelpers } from "../url_helpers.js"; +import { WEBGL } from "./webgl_constants.js"; + + +// wwtlib.Texture + +export function Texture() { + this.imageElement = null; + this.texture2d = null; + this._downloading = false; + this._ready = false; + this._errored = false; + this.URL = ''; +} + +Texture.empty = null; + +Texture.getEmpty = function () { + if (Texture.empty == null) { + Texture.empty = tilePrepDevice.createTexture(); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, Texture.empty); + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGBA, 1, 1, 0, WEBGL.RGBA, WEBGL.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 0])); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, null); + } + return Texture.empty; +}; + +Texture.fromUrl = function (url) { + var tex = new Texture(); + tex.load(url); + return tex; +}; + +Texture.isPowerOfTwo = function (val) { + return !(val & (val - 1)); +}; + +Texture.fitPowerOfTwo = function (val) { + val--; + for (var i = 1; i < 32; i <<= 1) { + val = val | val >> i; + } + return val + 1; +}; + +var Texture$ = { + cleanUp: function () { + this.imageElement = null; + tilePrepDevice.deleteTexture(this.texture2d); + }, + + dispose: function () { + this.cleanUp(); + }, + + load: function (url) { + var $this = this; + + this.URL = url; + if (typeof document === "undefined") { return; } + if (!this._downloading) { + this._downloading = true; + this.imageElement = document.createElement('img'); + var xdomimg = this.imageElement; + this.imageElement.addEventListener('load', function (e) { + $this._ready = true; + $this._downloading = false; + $this._errored = false; + $this.makeTexture(); + }, false); + this.imageElement.addEventListener('error', function (e) { + if (!$this.imageElement.hasAttribute('proxyattempt')) { + $this.imageElement.setAttribute('proxyattempt', true); + var new_url = URLHelpers.singleton.activateProxy($this.URL); + if (new_url != null) { // null => don't bother: we know that the proxy won't help + $this.imageElement.src = new_url; + return; + } + } + $this._downloading = false; + $this._ready = false; + $this._errored = true; + }, false); + xdomimg.crossOrigin = 'anonymous'; + this.imageElement.src = this.URL; + } + }, + + makeTexture: function () { + if (tilePrepDevice != null) { + try { + this.texture2d = tilePrepDevice.createTexture(); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, this.texture2d); + var image = this.imageElement; + + // Before we bind resize to a power of two if nessesary so we can MIPMAP + if ((!Texture.isPowerOfTwo(this.imageElement.height) | !Texture.isPowerOfTwo(this.imageElement.width)) === 1) { + var temp = document.createElement('canvas'); + temp.height = Texture.fitPowerOfTwo(image.height); + temp.width = Texture.fitPowerOfTwo(image.width); + var ctx = temp.getContext('2d'); + ctx.drawImage(image, 0, 0, temp.width, temp.height); + //Substitute the resized image + image = temp; + } + + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_S, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_T, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGBA, WEBGL.RGBA, WEBGL.UNSIGNED_BYTE, image); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.LINEAR_MIPMAP_NEAREST); + tilePrepDevice.generateMipmap(WEBGL.TEXTURE_2D); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, null); + } catch ($e1) { + this._errored = true; + } + } + } +}; + +registerType("Texture", [Texture, Texture$, null, ss.IDisposable]); diff --git a/engine/esm/graphics/webgl_constants.js b/engine/esm/graphics/webgl_constants.js new file mode 100644 index 00000000..8f59df68 --- /dev/null +++ b/engine/esm/graphics/webgl_constants.js @@ -0,0 +1,314 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Magic constants defined by WebGL. + +export const WEBGL = { + ACTIVE_ATTRIBUTE_MAX_LENGTH: 35722, + ACTIVE_ATTRIBUTES: 35721, + ACTIVE_TEXTURE: 34016, + ACTIVE_UNIFORM_MAX_LENGTH: 35719, + ACTIVE_UNIFORMS: 35718, + ALIASED_LINE_WIDTH_RANGE: 33902, + ALIASED_POINT_SIZE_RANGE: 33901, + ALPHA: 6406, + ALPHA_BITS: 3413, + ALWAYS: 519, + ARRAY_BUFFER: 34962, + ARRAY_BUFFER_BINDING: 34964, + ATTACHED_SHADERS: 35717, + BACK: 1029, + BLEND: 3042, + BLEND_COLOR: 32773, + BLEND_DST_ALPHA: 32970, + BLEND_DST_RGB: 32968, + BLEND_EQUATION: 32777, + BLEND_EQUATION_ALPHA: 34877, + BLEND_EQUATION_RGB: 32777, + BLEND_SRC_ALPHA: 32971, + BLEND_SRC_RGB: 32969, + BLUE_BITS: 3412, + BOOL: 35670, + BOOL_VEC2: 35671, + BOOL_VEC3: 35672, + BOOL_VEC4: 35673, + BUFFER_SIZE: 34660, + BUFFER_USAGE: 34661, + BYTE: 5120, + CCW: 2305, + CLAMP_TO_EDGE: 33071, + COLOR_ATTACHMENT0: 36064, + COLOR_BUFFER_BIT: 16384, + COLOR_CLEAR_VALUE: 3106, + COLOR_WRITEMASK: 3107, + COMPILE_STATUS: 35713, + COMPRESSED_TEXTURE_FORMATS: 34467, + CONSTANT_ALPHA: 32771, + CONSTANT_COLOR: 32769, + CULL_FACE: 2884, + CULL_FACE_MODE: 2885, + CURRENT_PROGRAM: 35725, + CURRENT_VERTEX_ATTRIB: 34342, + CW: 2304, + DECR: 7683, + DECR_WRAP: 34056, + DELETE_STATUS: 35712, + DEPTH_ATTACHMENT: 36096, + DEPTH_BITS: 3414, + DEPTH_BUFFER_BIT: 256, + DEPTH_CLEAR_VALUE: 2931, + DEPTH_COMPONENT: 6402, + DEPTH_COMPONENT16: 33189, + DEPTH_FUNC: 2932, + DEPTH_RANGE: 2928, + DEPTH_STENCIL: 34041, + DEPTH_STENCIL_ATTACHMENT: 33306, + DEPTH_TEST: 2929, + DEPTH_WRITEMASK: 2930, + DITHER: 3024, + DONT_CARE: 4352, + DST_ALPHA: 772, + DST_COLOR: 774, + DYNAMIC_DRAW: 35048, + ELEMENT_ARRAY_BUFFER: 34963, + ELEMENT_ARRAY_BUFFER_BINDING: 34965, + EQUAL: 514, + EXTENSIONS: 7939, + FASTEST: 4353, + FLOAT: 5126, + FLOAT_MAT2: 35674, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + FRAGMENT_SHADER: 35632, + FRAMEBUFFER: 36160, + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: 36049, + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: 36048, + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: 36051, + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: 36050, + FRAMEBUFFER_BINDING: 36006, + FRAMEBUFFER_COMPLETE: 36053, + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 36054, + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: 36057, + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 36055, + FRAMEBUFFER_UNSUPPORTED: 36061, + FRONT: 1028, + FRONT_AND_BACK: 1032, + FRONT_FACE: 2886, + FUNC_ADD: 32774, + FUNC_REVERSE_SUBTRACT: 32779, + FUNC_SUBTRACT: 32778, + GENERATE_MIPMAP_HINT: 33170, + GEQUAL: 518, + GREATER: 516, + GREEN_BITS: 3411, + HIGH_FLOAT: 36338, + HIGH_INT: 36341, + IMPLEMENTATION_COLOR_READ_FORMAT: 35739, + IMPLEMENTATION_COLOR_READ_TYPE: 35738, + INCR: 7682, + INCR_WRAP: 34055, + INFO_LOG_LENGTH: 35716, + INT: 5124, + INT_VEC2: 35667, + INT_VEC3: 35668, + INT_VEC4: 35669, + INVALID_ENUM: 1280, + INVALID_FRAMEBUFFER_OPERATION: 1286, + INVALID_OPERATION: 1282, + INVALID_VALUE: 1281, + INVERT: 5386, + KEEP: 7680, + LEQUAL: 515, + LESS: 513, + LINE_LOOP: 2, + LINE_STRIP: 3, + LINE_WIDTH: 2849, + LINEAR: 9729, + LINEAR_MIPMAP_LINEAR: 9987, + LINEAR_MIPMAP_NEAREST: 9985, + LINES: 1, + LINK_STATUS: 35714, + LOW_FLOAT: 36336, + LOW_INT: 36339, + LUMINANCE: 6409, + LUMINANCE_ALPHA: 6410, + MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661, + MAX_CUBE_MAP_TEXTURE_SIZE: 34076, + MAX_FRAGMENT_UNIFORM_VECTORS: 36349, + MAX_RENDERBUFFER_SIZE: 34024, + MAX_TEXTURE_IMAGE_UNITS: 34930, + MAX_TEXTURE_SIZE: 3379, + MAX_VARYING_VECTORS: 36348, + MAX_VERTEX_ATTRIBS: 34921, + MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660, + MAX_VERTEX_UNIFORM_VECTORS: 36347, + MAX_VIEWPORT_DIMS: 3386, + MEDIUM_FLOAT: 36337, + MEDIUM_INT: 36340, + MIRRORED_REPEAT: 33648, + NEAREST: 9728, + NEAREST_MIPMAP_LINEAR: 9986, + NEAREST_MIPMAP_NEAREST: 9984, + NEVER: 512, + NICEST: 4354, + NO_ERROR: 0, + NONE: 0, + NOTEQUAL: 517, + NUM_COMPRESSED_TEXTURE_FORMATS: 34466, + ONE: 1, + ONE_MINUS_CONSTANT_ALPHA: 32772, + ONE_MINUS_CONSTANT_COLOR: 32770, + ONE_MINUS_DST_ALPHA: 773, + ONE_MINUS_DST_COLOR: 775, + ONE_MINUS_SRC_ALPHA: 771, + ONE_MINUS_SRC_COLOR: 769, + OUT_OF_MEMORY: 1285, + PACK_ALIGNMENT: 3333, + POINTS: 0, + POLYGON_OFFSET_FACTOR: 32824, + POLYGON_OFFSET_FILL: 32823, + POLYGON_OFFSET_UNITS: 10752, + RED_BITS: 3410, + RENDERBUFFER: 36161, + RENDERBUFFER_ALPHA_SIZE: 36179, + RENDERBUFFER_BINDING: 36007, + RENDERBUFFER_BLUE_SIZE: 36178, + RENDERBUFFER_DEPTH_SIZE: 36180, + RENDERBUFFER_GREEN_SIZE: 36177, + RENDERBUFFER_HEIGHT: 36163, + RENDERBUFFER_INTERNAL_FORMAT: 36164, + RENDERBUFFER_RED_SIZE: 36176, + RENDERBUFFER_STENCIL_SIZE: 36181, + RENDERBUFFER_WIDTH: 36162, + RENDERER: 7937, + REPEAT: 10497, + REPLACE: 7681, + RGB: 6407, + RGB8: 32849, + RGB5_A1: 32855, + RGB565: 36194, + RGBA: 6408, + RGBA8: 32856, + RGBA16I: 36232, + RED_INTEGER: 36244, + RED: 6403, + R32F: 33326, + R16I: 33331, + RGBA4: 32854, + SAMPLE_ALPHA_TO_COVERAGE: 32926, + SAMPLE_BUFFERS: 32936, + SAMPLE_COVERAGE: 32928, + SAMPLE_COVERAGE_INVERT: 32939, + SAMPLE_COVERAGE_VALUE: 32938, + SAMPLER_2D: 35678, + SAMPLER_CUBE: 35680, + SAMPLES: 32937, + SCISSOR_BOX: 3088, + SCISSOR_TEST: 3089, + SHADER_COMPILER: 36346, + SHADER_SOURCE_LENGTH: 35720, + SHADER_TYPE: 35663, + SHADING_LANGUAGE_VERSION: 35724, + SHORT: 5122, + SRC_ALPHA: 770, + SRC_ALPHA_SATURATE: 776, + SRC_COLOR: 768, + STATIC_DRAW: 35044, + STENCIL_ATTACHMENT: 36128, + STENCIL_BACK_FAIL: 34817, + STENCIL_BACK_FUNC: 34816, + STENCIL_BACK_PASS_DEPTH_FAIL: 34818, + STENCIL_BACK_PASS_DEPTH_PASS: 34819, + STENCIL_BACK_REF: 36003, + STENCIL_BACK_VALUE_MASK: 36004, + STENCIL_BACK_WRITEMASK: 36005, + STENCIL_BITS: 3415, + STENCIL_BUFFER_BIT: 1024, + STENCIL_CLEAR_VALUE: 2961, + STENCIL_FAIL: 2964, + STENCIL_FUNC: 2962, + STENCIL_INDEX: 6401, + STENCIL_INDEX8: 36168, + STENCIL_PASS_DEPTH_FAIL: 2965, + STENCIL_PASS_DEPTH_PASS: 2966, + STENCIL_REF: 2967, + STENCIL_TEST: 2960, + STENCIL_VALUE_MASK: 2963, + STENCIL_WRITEMASK: 2968, + STREAM_DRAW: 35040, + SUBPIXEL_BITS: 3408, + TEXTURE: 5890, + TEXTURE_2D: 3553, + TEXTURE_BINDING_2D: 32873, + TEXTURE_BINDING_CUBE_MAP: 34068, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + UNPACK_FLIP_Y_WEBGL: 37440, + TEXTURE_MAG_FILTER: 10240, + TEXTURE_MIN_FILTER: 10241, + TEXTURE_WRAP_S: 10242, + TEXTURE_WRAP_T: 10243, + TEXTURE0: 33984, + TEXTURE1: 33985, + TEXTURE10: 33994, + TEXTURE11: 33995, + TEXTURE12: 33996, + TEXTURE13: 33997, + TEXTURE14: 33998, + TEXTURE15: 33999, + TEXTURE16: 34000, + TEXTURE17: 34001, + TEXTURE18: 34002, + TEXTURE19: 34003, + TEXTURE2: 33986, + TEXTURE20: 34004, + TEXTURE21: 34005, + TEXTURE22: 34006, + TEXTURE23: 34007, + TEXTURE24: 34008, + TEXTURE25: 34009, + TEXTURE26: 34010, + TEXTURE27: 34011, + TEXTURE28: 34012, + TEXTURE29: 34013, + TEXTURE3: 33987, + TEXTURE30: 34014, + TEXTURE31: 34015, + TEXTURE4: 33988, + TEXTURE5: 33989, + TEXTURE6: 33990, + TEXTURE7: 33991, + TEXTURE8: 33992, + TEXTURE9: 33993, + TRIANGLE_FAN: 6, + TRIANGLE_STRIP: 5, + TRIANGLES: 4, + UNPACK_ALIGNMENT: 3317, + UNSIGNED_BYTE: 5121, + UNSIGNED_INT: 5125, + UNSIGNED_SHORT: 5123, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + UNSIGNED_SHORT_5_6_5: 33635, + VALIDATE_STATUS: 35715, + VENDOR: 7936, + VERSION: 7938, + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: 34975, + VERTEX_ATTRIB_ARRAY_ENABLED: 34338, + VERTEX_ATTRIB_ARRAY_NORMALIZED: 34922, + VERTEX_ATTRIB_ARRAY_POINTER: 34373, + VERTEX_ATTRIB_ARRAY_SIZE: 34339, + VERTEX_ATTRIB_ARRAY_STRIDE: 34340, + VERTEX_ATTRIB_ARRAY_TYPE: 34341, + VERTEX_SHADER: 35633, + VIEWPORT: 2978, + ZERO: 0, +}; diff --git a/engine/esm/grids.js b/engine/esm/grids.js new file mode 100644 index 00000000..6521fc64 --- /dev/null +++ b/engine/esm/grids.js @@ -0,0 +1,974 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Various grids that can overlay the sky view. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Vector3d, Matrix3d, PositionTexture } from "./double3d.js"; +import { DT } from "./astrocalc/date.js"; +import { CT } from "./astrocalc/coordinate_transformation.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { PointList, SimpleLineList, Dates } from "./graphics/primitives3d.js"; +import { PositionTextureVertexBuffer } from "./graphics/gl_buffers.js"; +import { Texture } from "./graphics/texture.js"; +import { ImageShader } from "./graphics/shaders.js"; +import { Colors } from "./color.js"; +import { freestandingMode } from "./data_globals.js"; +import { globalRenderContext, tilePrepDevice } from "./render_globals.js"; +import { BinaryReader } from "./utilities/binary_reader.js"; +import { Coordinates } from "./coordinates.js"; +import { Text3d, Text3dBatch } from "./sky_text.js"; +import { Planets } from "./planets.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { Star, Galaxy } from "./star.js"; +import { WebFile } from "./web_file.js"; + + +// wwtlib.Grids + +export function Grids() { } + +Grids._galaxyImageIndexBuffer = null; +Grids._galaxyImageTriangleCount = 0; +Grids._milkyWayImage = null; +Grids._starSprites = null; +Grids._starCount = 0; +Grids._starsDownloading = false; +Grids._stars = null; +Grids._hipparcosIndex = {}; +Grids._limitingMagnitude = 16; +Grids._galaxyTextures = null; +Grids._galaxyVertexCounts = null; +Grids._largeSet = true; +Grids._cosmosReady = false; +Grids._cosmos = null; +Grids._downloadingGalaxy = false; +Grids._eclipticCount = 0; +Grids._eclipticYear = 0; +Grids._monthDays = [31, 28.2421, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +Grids._monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; +Grids._eclipticTextYear = 0; + +Grids._createGalaxyImage = function (renderContext) { + if (Grids._milkyWayImage == null) { + Grids._milkyWayImage = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('milkywaybar.jpg')); + } + var subdivs = 50; + var lat, lng; + var index = 0; + var latMin = 64; + var latMax = -64; + var lngMin = -64; + var lngMax = 64; + Grids._galaxyImageVertexBuffer = new PositionTextureVertexBuffer((subdivs + 1) * (subdivs + 1)); + var verts = Grids._galaxyImageVertexBuffer.lock(); + var x1, y1; + var latDegrees = latMax - latMin; + var lngDegrees = lngMax - lngMin; + var scaleFactor = 60800000; + var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; + var point; + var textureStepX = 1 / subdivs; + var textureStepY = 1 / subdivs; + for (y1 = 0; y1 <= subdivs; y1++) { + if (y1 !== subdivs) { + lat = latMax - (textureStepY * latDegrees * y1); + } else { + lat = latMin; + } + for (x1 = 0; x1 <= subdivs; x1++) { + if (x1 !== subdivs) { + lng = lngMin + (textureStepX * lngDegrees * x1); + } + else { + lng = lngMax; + } + index = y1 * (subdivs + 1) + x1; + point = Vector3d.create(lng * scaleFactor, 0, (lat - 28) * scaleFactor); + point.rotateY(213 / 180 * Math.PI); + point.rotateZ((-62.87175) / 180 * Math.PI); + point.rotateY((-192.8595083) / 180 * Math.PI); + point.rotateX(ecliptic); + verts[index] = PositionTexture.createPosRaw(point, (1 - x1 * textureStepX), (y1 * textureStepY)); + } + } + Grids._galaxyImageVertexBuffer.unlock(); + Grids._galaxyImageTriangleCount = subdivs * subdivs * 2; + var ui16array = new Uint16Array(subdivs * subdivs * 6); + var indexArray = ui16array; + for (y1 = 0; y1 < subdivs; y1++) { + for (x1 = 0; x1 < subdivs; x1++) { + index = (y1 * subdivs * 6) + 6 * x1; + + // First triangle in quad + indexArray[index] = (y1 * (subdivs + 1) + x1); + indexArray[index + 2] = ((y1 + 1) * (subdivs + 1) + x1); + indexArray[index + 1] = (y1 * (subdivs + 1) + (x1 + 1)); + + // Second triangle in quad + indexArray[index + 3] = (y1 * (subdivs + 1) + (x1 + 1)); + indexArray[index + 5] = ((y1 + 1) * (subdivs + 1) + x1); + indexArray[index + 4] = ((y1 + 1) * (subdivs + 1) + (x1 + 1)); + } + } + Grids._galaxyImageIndexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, Grids._galaxyImageIndexBuffer); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, ui16array, WEBGL.STATIC_DRAW); +}; + +Grids.drawGalaxyImage = function (renderContext, opacity) { + if (Grids._galaxyImageIndexBuffer == null) { + Grids._createGalaxyImage(renderContext); + } + var zoom = renderContext.viewCamera.zoom; + var log = Math.log(Math.max(1, zoom)) / Math.log(4); + var distAlpha = (log - 14) * 128; + var alpha = (Math.min(255, Math.max(0, distAlpha)) * opacity); + ImageShader.use(renderContext, Grids._galaxyImageVertexBuffer.vertexBuffer, Grids._galaxyImageIndexBuffer, Grids._milkyWayImage.texture2d, opacity, true); + renderContext.gl.drawElements(WEBGL.TRIANGLES, Grids._galaxyImageTriangleCount * 3, WEBGL.UNSIGNED_SHORT, 0); +}; + +Grids.drawStars3D = function (renderContext, opacity) { + var zoom = renderContext.viewCamera.zoom; + var distAlpha = Math.max(Math.min(255, (Math.log(zoom) - 15.5) * 40.8), 0); + var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); + if (alpha > 254) { + return; + } + alpha = ((255 - alpha) * opacity); + if (Grids._starSprites == null) { + Grids.initStarVertexBuffer(renderContext); + } + if (Grids._starSprites != null) { + Grids._starSprites.draw(renderContext, alpha / 255, false); + } +}; + +Grids.initStarVertexBuffer = function (renderContext) { + if (!Grids._starsDownloading && !freestandingMode) { + Grids.getStarFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=hipparcos')); + Grids._starsDownloading = true; + } + if (Grids._starSprites == null && Grids._starCount > 0) { + var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; + var count = Grids._stars.length; + Grids._starCount = count; + Grids._starSprites = new PointList(renderContext); + Grids._starSprites.depthBuffered = false; + Grids._starSprites.showFarSide = true; + var $enum1 = ss.enumerate(Grids._stars); + while ($enum1.moveNext()) { + var star = $enum1.current; + var pos = Coordinates.raDecTo3dAu(star.RA, star.dec, star.distance); + pos.rotateX(ecliptic); + star.position = pos; + var radDec = (1200000) / Math.pow(1.6, star.absoluteMagnitude); + Grids._starSprites.addPoint(pos, star.col, new Dates(0, 1), radDec * 100); + } + } +}; + +Grids.initializeStarDB = function (text) { + if (Grids._stars == null) { + if (Grids._stars == null) { + Grids._stars = []; + var rows = text.split('\r\n'); + var star; + var $enum1 = ss.enumerate(rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + var line = row; + star = new Star(line); + if (star.magnitude < Grids._limitingMagnitude && star.par > 0.001) { + Grids._stars.push(star); + Grids._hipparcosIndex[star.id] = star; + } + } + Grids._starCount = Grids._stars.length; + } + } +}; + +Grids.getStarFile = function (url) { + Grids._webFileStar = new WebFile(url); + Grids._webFileStar.onStateChange = Grids.starFileStateChange; + Grids._webFileStar.send(); +}; + +Grids.starFileStateChange = function () { + if (Grids._webFileStar.get_state() === 2) { + alert(Grids._webFileStar.get_message()); + } + else if (Grids._webFileStar.get_state() === 1) { + Grids.initializeStarDB(Grids._webFileStar.getText()); + } +}; + +Grids.getGalaxyFile = function (url) { + Grids._webFileGalaxy = new WebFile(url); + Grids._webFileGalaxy.responseType = 'blob'; + Grids._webFileGalaxy.onStateChange = Grids.galaxyFileStateChange; + Grids._webFileGalaxy.send(); +}; + +Grids.galaxyFileStateChange = function () { + if (Grids._webFileGalaxy.get_state() === 2) { + alert(Grids._webFileGalaxy.get_message()); + } + else if (Grids._webFileGalaxy.get_state() === 1) { + var mainBlob = Grids._webFileGalaxy.getBlob(); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + var br = new BinaryReader(new Uint8Array(chunck.result)); + Grids.initializeCosmos(br); + }; + chunck.readAsArrayBuffer(mainBlob); + } +}; + +Grids.drawCosmos3D = function (renderContext, opacity) { + var device = renderContext.gl; + var zoom = renderContext.viewCamera.zoom; + var distAlpha = ((Math.log(Math.max(1, zoom)) / Math.log(4)) - 15.5) * 90; + var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); + if (alpha < 3) { + return; + } + Grids.initCosmosVertexBuffer(); + if (Grids._galaxyTextures == null) { + if (Grids._largeSet) { + Grids._galaxyTextures = new Array(256); + for (var i = 0; i < 256; i++) { + var num = i.toString(); + while (num.length < 4) { + num = '0' + num; + } + var name = ss.format(URLHelpers.singleton.engineAssetUrl('galimg/gal_{0}.jpg'), num); + Grids._galaxyTextures[i] = Texture.fromUrl(name); + } + } + } + if (Grids._cosmosReady) { + var count = 256; + for (var i = 0; i < count; i++) { + Grids._cosmosSprites[i].drawTextured(renderContext, Grids._galaxyTextures[i].texture2d, (alpha * opacity) / 255); + } + } +}; + +Grids.initCosmosVertexBuffer = function () { + if (Grids._cosmosSprites == null) { + Grids._downloadCosmosFile(); + } +}; + +Grids._createCosmosVertexBuffer = function (renderContext) { + var device = tilePrepDevice; + var bucketCount = 256; + if (Grids._cosmosSprites != null) { + for (var ij = 0; ij < bucketCount; ij++) { + if (Grids._cosmosSprites[ij] != null) { + Grids._cosmosSprites[ij] = null; + } + } + } + Grids._cosmosSprites = null; + var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; + Grids._cosmosSprites = new Array(bucketCount); + var indexList = new Array(bucketCount); + for (var i = 0; i < bucketCount; i++) { + var count = Grids._galaxyVertexCounts[i]; + Grids._cosmosSprites[i] = new PointList(renderContext); + Grids._cosmosSprites[i].depthBuffered = false; + Grids._cosmosSprites[i].showFarSide = true; + indexList[i] = 0; + } + var $enum1 = ss.enumerate(Grids._cosmos); + while ($enum1.moveNext()) { + var galaxy = $enum1.current; + var bucket = galaxy.eTypeBucket; + var index = indexList[bucket]; + var pos = Coordinates.raDecTo3dAu(galaxy.RA, galaxy.dec, (galaxy.distance * 206264.806 * 1000000) / 0.73); + pos.rotateX(ecliptic); + galaxy.position = pos; + Grids._cosmosSprites[bucket].addPoint(pos, Colors.get_white(), new Dates(0, 1), (1E+09 * galaxy.size * 100)); + indexList[bucket]++; + } + Grids._cosmosReady = true; +}; + +Grids.initializeCosmos = function (br) { + var max = Math.pow(100, 2.849485002); + if (Grids._cosmos == null) { + Grids._galaxyVertexCounts = new Array((Grids._largeSet) ? 256 : 20); + if (Grids._cosmos == null) { + Grids._cosmos = []; + var galaxy; + try { + var count = 0; + while (br.get_position() < br.get_length()) { + galaxy = new Galaxy(br); + Grids._cosmos.push(galaxy); + Grids._galaxyVertexCounts[galaxy.eTypeBucket]++; + count++; + } + } + catch ($e1) { + } + br.close(); + } + Grids._createCosmosVertexBuffer(globalRenderContext); + } +}; + +Grids._downloadCosmosFile = function () { + if (!Grids._downloadingGalaxy && !freestandingMode) { + Grids.getGalaxyFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=cosmosnewbin')); + Grids._downloadingGalaxy = true; + } + return false; +}; + +Grids.drawEquitorialGrid = function (renderContext, opacity, drawColor) { + if (Grids._equLineList == null) { + Grids._equLineList = new SimpleLineList(); + Grids._equLineList.set_depthBuffered(false); + for (var hour = 0; hour < 24; hour++) { + for (var dec = -80; dec < 80; dec += 2) { + Grids._equLineList.addLine(Coordinates.raDecTo3dAu(hour, dec, 1), Coordinates.raDecTo3dAu(hour, dec + 2, 1)); + } + } + for (var dec = -80; dec <= 80; dec += 10) { + for (var hour = 0; hour < 23.8; hour += 0.2) { + Grids._equLineList.addLine(Coordinates.raDecTo3dAu(hour, dec, 1), Coordinates.raDecTo3dAu(hour + 0.2, dec, 1)); + //todo fix for color bright + } + } + var counter = 0; + for (var ra = 0; ra < 24; ra += 0.25) { + var dec = 0.5; + switch (counter % 4) { + case 0: + counter++; + continue; + case 3: + case 1: + dec = 0.25; + break; + } + counter++; + Grids._equLineList.addLine(Coordinates.raDecTo3dAu(ra, dec, 1), Coordinates.raDecTo3dAu(ra, -dec, 1)); + } + counter = 0; + for (var ra = 0; ra < 24; ra += 3) { + counter = 0; + for (var dec = -80; dec <= 80; dec += 1) { + var width = 0.5 / 30; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + width = 0.5 / 15; + break; + } + counter++; + Grids._equLineList.addLine(Coordinates.raDecTo3dAu(ra + width, dec, 1), Coordinates.raDecTo3dAu(ra - width, dec, 1)); + } + } + } + Grids._equLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids.drawEquitorialGridText = function (renderContext, opacity, drawColor) { + Grids._makeEquitorialGridText(); + Grids._equTextBatch.draw(renderContext, opacity, drawColor); + return true; +}; + +Grids._makeEquitorialGridText = function () { + if (Grids._equTextBatch == null) { + Grids._equTextBatch = new Text3dBatch(30); + var index = 0; + for (var ra = 0; ra < 24; ra++) { + var text = ra.toString() + ' hr'; + if (ra < 10) { + text = ' ' + ra.toString() + ' hr'; + } + Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra + 0.005, 0.4, 1), Coordinates.raDecTo3dAu(ra + 0.005, 0.5, 1), text, 45, 0.00018)); + } + index = 0; + for (var ra = 0; ra < 24; ra += 3) { + for (var dec = -80; dec <= 80; dec += 10) { + if (!dec) { + continue; + } + var text = dec.toString(); + if (dec > 0) { + text = ' +' + dec.toString(); + Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra, dec - 0.4, 1), Coordinates.raDecTo3dAu(ra, dec - 0.3, 1), text, 45, 0.00018)); + } + else { + text = ' - ' + text.substr(1); + Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra, dec + 0.4, 1), Coordinates.raDecTo3dAu(ra, dec + 0.5, 1), text, 45, 0.00018)); + } + index++; + } + } + } +}; + +Grids.drawEcliptic = function (renderContext, opacity, drawColor) { + var col = drawColor; + var year = SpaceTimeController.get_now().getUTCFullYear(); + if (Grids._eclipticOverviewLineList == null || year !== Grids._eclipticYear) { + if (Grids._eclipticOverviewLineList != null) { + Grids._eclipticOverviewLineList.clear(); + Grids._eclipticOverviewLineList = null; + } + Grids._eclipticYear = year; + var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); + var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); + var daysPerYear = 365.25; + if (DT.isLeap(year, true)) { + Grids._monthDays[1] = 29; + daysPerYear = 366; + } else { + Grids._monthDays[1] = 28; + daysPerYear = 365; + } + var count = 2 * ss.truncate(daysPerYear); + Grids._eclipticCount = ss.truncate(daysPerYear); + var jYear = SpaceTimeController.utcToJulian(new Date(year, 0, 1, 12, 0, 0)); + var index = 0; + var d = 0; + Grids._eclipticOverviewLineList = new SimpleLineList(); + Grids._eclipticOverviewLineList.set_depthBuffered(false); + for (var m = 0; m < 12; m++) { + var daysThisMonth = ss.truncate(Grids._monthDays[m]); + for (var i = 0; i < daysThisMonth; i++) { + var sunRaDec = Planets.getPlanetLocationJD('Sun', jYear); + var sunEcliptic = CT.eq2Ec(sunRaDec.RA, sunRaDec.dec, obliquity); + d = sunEcliptic.x; + var width = 0.005; + if (!i) { + width = 0.01; + } + var dd = d; + Grids._eclipticOverviewLineList.addLine(Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), width, Math.sin((dd * Math.PI * 2) / 360)), mat), Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), -width, Math.sin((dd * Math.PI * 2) / 360)), mat)); + index++; + jYear += 1; + } + d += Grids._monthDays[m]; + } + } + Grids._eclipticOverviewLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids.drawEclipticText = function (renderContext, opacity, drawColor) { + Grids._makeEclipticText(); + Grids._eclipOvTextBatch.draw(renderContext, opacity, drawColor); + return true; +}; + +Grids._makeEclipticText = function () { + var year = SpaceTimeController.get_now().getUTCFullYear(); + if (Grids._eclipOvTextBatch == null) { + Grids._eclipOvTextBatch = new Text3dBatch(80); + Grids._eclipticTextYear = year; + var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); + var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); + var daysPerYear = 365.25; + if (DT.isLeap(year, true)) { + Grids._monthDays[1] = 29; + daysPerYear = 366; + } else { + Grids._monthDays[1] = 28; + daysPerYear = 365; + } + var count = 2 * ss.truncate(daysPerYear); + Grids._eclipticCount = ss.truncate(daysPerYear); + var jYear = SpaceTimeController.utcToJulian(new Date(year, 0, 1, 12, 0, 0)); + var index = 0; + var d = 0; + for (var m = 0; m < 12; m++) { + var daysThisMonth = ss.truncate(Grids._monthDays[m]); + for (var i = 0; i < daysThisMonth; i++) { + var sunRaDec = Planets.getPlanetLocationJD('Sun', jYear); + var sunEcliptic = CT.eq2Ec(sunRaDec.RA, sunRaDec.dec, obliquity); + d = sunEcliptic.x; + var dd = d; + if (i === Math.floor(daysThisMonth / 2)) { + var center = Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), 0.025, Math.sin((dd * Math.PI * 2) / 360)), mat); + var up = Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), 0.045, Math.sin((dd * Math.PI * 2) / 360)), mat); + up.subtract(center); + up.normalize(); + Grids._eclipOvTextBatch.add(new Text3d(center, up, Grids._monthNames[m], 80, 0.000159375)); + } + index++; + index++; + jYear += 1; + } + d += Grids._monthDays[m]; + } + } +}; + +Grids.drawPrecessionChart = function (renderContext, opacity, drawColor) { + Grids._makePrecessionChart(); + Grids._precTextBatch.draw(renderContext, opacity, drawColor); + Grids._precLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids._makePrecessionChart = function () { + var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); + var mat = Matrix3d._rotationX((obliquity / 360 * (Math.PI * 2))); + var col = Colors.get_white(); + if (Grids._precLineList == null) { + Grids._precLineList = new SimpleLineList(); + Grids._precLineList.set_depthBuffered(false); + for (var l = 0; l < 360; l++) { + var b = 90 - obliquity; + Grids._precLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + 1) / 15, b, 1), mat)); + } + for (var l = -12000; l < 13000; l += 2000) { + var b = 90 - obliquity; + var p = -((l - 2000) / 25772 * 24) - 6; + Grids._precLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b - 0.5, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b + 0.5, 1), mat)); + } + } + if (Grids._precTextBatch == null) { + Grids._precTextBatch = new Text3dBatch(50); + for (var l = -12000; l < 13000; l += 2000) { + var b = 90 - obliquity + 3; + var p = -((l - 2000) / 25772 * 24) - 6; + var text = l.toString(); + if (!l) { + b = 90 - obliquity + 2; + text = '1 CE'; + } + else if (l < 0) { + text = ' ' + Math.abs(l).toString() + ' BCE'; + } + else { + text = Math.abs(l).toString() + ' CE'; + } + if (text.length === 9) { + text = ' ' + text; + } + Grids._precTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p + 0.01, b, 1), mat), text, 75, 0.00015)); + } + } + return; +}; + +Grids.drawAltAzGrid = function (renderContext, opacity, drawColor) { + var zenithAltAz = new Coordinates(0, 0); + var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); + var raPart = -((zenith.get_RA() + 6) / 24 * (Math.PI * 2)); + var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); + var raText = Coordinates.formatDMS(zenith.get_RA()); + var mat = Matrix3d._rotationY(-raPart); + mat._multiply(Matrix3d._rotationX(decPart)); + mat.invert(); + if (Grids._altAzLineList == null) { + Grids._altAzLineList = new SimpleLineList(); + Grids._altAzLineList.set_depthBuffered(false); + for (var l = 0; l < 360; l += 10) { + for (var b = -80; b < 80; b += 2) { + Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu(l / 15, b + 2, 1)); + } + } + for (var b = -80; b <= 80; b += 10) { + for (var l = 0; l < 360; l += 5) { + Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu((l + 5) / 15, b, 1)); + } + } + var counter = 0; + for (var l = 0; l < 360; l += 1) { + var b = 0.25; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + b = 0.5; + break; + } + counter++; + Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu(l / 15, -b, 1)); + } + counter = 0; + for (var l = 0; l < 360; l += 90) { + counter = 0; + for (var b = -80; b <= 80; b += 1) { + var width = 0.5 / 2; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + width = 0.5; + break; + } + counter++; + Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu((l + width) / 15, b, 1), Coordinates.raDecTo3dAu((l - width) / 15, b, 1)); + } + } + } + var matOldWorld = renderContext.get_world().clone(); + var matOldWorldBase = renderContext.get_worldBase().clone(); + renderContext.set_worldBase(Matrix3d.multiplyMatrix(mat, renderContext.get_world())); + renderContext.set_world(renderContext.get_worldBase().clone()); + renderContext.makeFrustum(); + Grids._altAzLineList.viewTransform = Matrix3d.invertMatrix(mat); + Grids._altAzLineList.drawLines(renderContext, opacity, drawColor); + renderContext.set_worldBase(matOldWorldBase); + renderContext.set_world(matOldWorld); + renderContext.makeFrustum(); + return true; +}; + +Grids.drawAltAzGridText = function (renderContext, opacity, drawColor) { + var zenithAltAz = new Coordinates(0, 0); + var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); + var raPart = -((zenith.get_RA() - 6) / 24 * (Math.PI * 2)); + var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); + var raText = Coordinates.formatDMS(zenith.get_RA()); + var mat = Matrix3d._rotationY(-raPart - Math.PI); + mat._multiply(Matrix3d._rotationX(decPart)); + mat.invert(); + Grids._makeAltAzGridText(); + var matOldWorld = renderContext.get_world().clone(); + var matOldWorldBase = renderContext.get_worldBase().clone(); + renderContext.set_worldBase(Matrix3d.multiplyMatrix(mat, renderContext.get_world())); + renderContext.set_world(renderContext.get_worldBase().clone()); + renderContext.makeFrustum(); + Grids._altAzTextBatch.viewTransform = Matrix3d.invertMatrix(mat); + Grids._altAzTextBatch.draw(renderContext, opacity, drawColor); + renderContext.set_worldBase(matOldWorldBase); + renderContext.set_world(matOldWorld); + renderContext.makeFrustum(); + return true; +}; + +Grids._makeAltAzGridText = function () { + var drawColor = Colors.get_white(); + var index = 0; + if (Grids._altAzTextBatch == null) { + Grids._altAzTextBatch = new Text3dBatch(30); + for (var l = 0; l < 360; l += 10) { + var text = ' ' + l.toString(); + if (l < 10) { + text = ' ' + l.toString(); + } + else if (l < 100) { + text = ' ' + l.toString(); + } + var lc = 360 - l; + Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(lc / 15 - 6, 0.4, 1), Coordinates.raDecTo3dAu(lc / 15 - 6, 0.5, 1), text, 75, 0.00018)); + } + index = 0; + for (var l = 0; l < 360; l += 90) { + for (var b = -80; b <= 80; b += 10) { + if (!b) { + continue; + } + var text = b.toString(); + if (b > 0) { + text = ' +' + b.toString(); + Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(l / 15, b - 0.4, 1), Coordinates.raDecTo3dAu(l / 15, b - 0.3, 1), text, 75, 0.00018)); + } + else { + text = ' - ' + text.substr(1); + Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(l / 15, b + 0.4, 1), Coordinates.raDecTo3dAu(l / 15, b + 0.5, 1), text, 75, 0.00018)); + } + index++; + } + } + } + return; +}; + +Grids.drawEclipticGrid = function (renderContext, opacity, drawColor) { + if (Grids._eclipticLineList == null) { + Grids._eclipticLineList = new SimpleLineList(); + Grids._eclipticLineList.set_depthBuffered(false); + var obliquity = Coordinates.meanObliquityOfEcliptic(2451545); + var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); + for (var l = 0; l < 360; l += 10) { + for (var b = -80; b < 80; b += 2) { + Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 2, 1), mat)); + } + } + for (var b = -80; b <= 80; b += 10) { + for (var l = 0; l < 360; l += 5) { + Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + 5) / 15, b, 1), mat)); + } + } + var counter = 0; + for (var l = 0; l < 360; l += 1) { + var b = 0.25; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + b = 0.5; + break; + } + counter++; + Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, -b, 1), mat)); + } + counter = 0; + for (var l = 0; l < 360; l += 90) { + counter = 0; + for (var b = -80; b <= 80; b += 1) { + var width = 0.5 / 2; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + width = 0.5; + break; + } + counter++; + Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + width) / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l - width) / 15, b, 1), mat)); + } + } + } + Grids._eclipticLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids.drawEclipticGridText = function (renderContext, opacity, drawColor) { + Grids._makeEclipticGridText(); + Grids._eclipticTextBatch.draw(renderContext, opacity, drawColor); + return true; +}; + +Grids._makeEclipticGridText = function () { + var drawColor = Colors.get_white(); + var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); + var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); + if (Grids._eclipticTextBatch == null) { + Grids._eclipticTextBatch = new Text3dBatch(30); + for (var l = 0; l < 360; l += 10) { + var text = ' ' + l.toString(); + if (l < 10) { + text = ' ' + l.toString(); + } + else if (l < 100) { + text = ' ' + l.toString(); + } + Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, 0.5, 1), mat), text, 75, 0.00018)); + } + for (var l = 0; l < 360; l += 90) { + for (var b = -80; b <= 80; b += 10) { + if (!b) { + continue; + } + var text = b.toString(); + if (b > 0) { + text = ' +' + b.toString(); + Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b - 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b - 0.3, 1), mat), text, 75, 0.00018)); + } + else { + text = ' - ' + text.substr(1); + Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 0.5, 1), mat), text, 75, 0.00018)); + } + } + } + } + return; +}; + +Grids.drawGalacticGrid = function (renderContext, opacity, drawColor) { + if (Grids._galLineList == null) { + Grids._galLineList = new SimpleLineList(); + Grids._galLineList.set_depthBuffered(false); + for (var l = 0; l < 360; l += 10) { + for (var b = -80; b < 80; b += 2) { + Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l, b + 2)); + } + } + for (var b = -80; b <= 80; b += 10) { + for (var l = 0; l < 360; l += 5) { + Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l + 5, b)); + } + } + var counter = 0; + for (var l = 0; l < 360; l += 1) { + var b = 0.25; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + b = 0.5; + break; + } + counter++; + Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l, -b)); + } + counter = 0; + for (var l = 0; l < 360; l += 90) { + counter = 0; + for (var b = -80; b <= 80; b += 1) { + var width = 0.5 / 2; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + width = 0.5; + break; + } + counter++; + Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l + width, b), Coordinates.galacticTo3dDouble(l - width, b)); + } + } + } + Grids._galLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids.drawGalacticGridText = function (renderContext, opacity, drawColor) { + Grids._makeGalacticGridText(); + Grids._galTextBatch.draw(renderContext, opacity, drawColor); + return true; +}; + +Grids._makeGalacticGridText = function () { + if (Grids._galTextBatch == null) { + Grids._galTextBatch = new Text3dBatch(30); + for (var l = 0; l < 360; l += 10) { + var text = ' ' + l.toString(); + if (l < 10) { + text = ' ' + l.toString(); + } + else if (l < 100) { + text = ' ' + l.toString(); + } + Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, 0.4), Coordinates.galacticTo3dDouble(l, 0.5), text, 75, 0.00018)); + } + for (var l = 0; l < 360; l += 90) { + for (var b = -80; b <= 80; b += 10) { + if (!b) { + continue; + } + var text = b.toString(); + if (b > 0) { + text = ' +' + b.toString(); + Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, b - 0.4), Coordinates.galacticTo3dDouble(l, b - 0.3), text, 75, 0.00018)); + } + else { + text = ' - ' + text.substr(1); + Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, b + 0.4), Coordinates.galacticTo3dDouble(l, b + 0.5), text, 75, 0.00018)); + } + } + } + } +}; + +Grids.drawPlanetGrid = function (renderContext, opacity, drawColor) { + if (Grids._planetLineList == null) { + Grids._planetLineList = new SimpleLineList(); + Grids._planetLineList.set_depthBuffered(true); + var col = drawColor; + for (var lng = 0; lng < 360; lng += 10) { + for (var lat = -80; lat < 80; lat += 2) { + Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, lng), Coordinates.geoTo3dDouble(lat + 2, lng)); + } + } + for (var lat = -80; lat <= 80; lat += 10) { + for (var l = 0; l < 360; l += 5) { + Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, l), Coordinates.geoTo3dDouble(lat, l + 5)); + } + } + var counter = 0; + for (var lng = 0; lng < 360; lng += 1) { + var lat = 0.25; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + lat = 0.5; + break; + } + counter++; + Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, lng), Coordinates.geoTo3dDouble(-lat, lng)); + } + counter = 0; + for (var lng = 0; lng < 360; lng += 90) { + counter = 0; + for (var b = -80; b <= 80; b += 1) { + var width = 0.5 / 2; + switch (counter % 10) { + case 0: + counter++; + continue; + case 5: + width = 0.5; + break; + } + counter++; + Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(b, lng + width), Coordinates.geoTo3dDouble(b, lng - width)); + } + } + } + Grids._planetLineList.aaFix = false; + Grids._planetLineList.set_depthBuffered(true); + Grids._planetLineList.sky = false; + Grids._planetLineList.drawLines(renderContext, opacity, drawColor); + return true; +}; + +Grids.drawPlanetGridText = function (renderContext, opacity, drawColor) { + Grids._makePlanetGridText(); + Grids._planetTextBatch.draw(renderContext, opacity, drawColor); + return true; +}; + +Grids._makePlanetGridText = function () { + if (Grids._planetTextBatch == null) { + Grids._planetTextBatch = new Text3dBatch(80); + for (var lng = -180; lng < 180; lng += 10) { + var text = ' ' + lng.toString(); + if (lng < 10) { + text = ' ' + lng.toString(); + } + else if (lng < 100) { + text = ' ' + lng.toString(); + } + Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(0.4, lng), Coordinates.geoTo3dDouble(0.5, lng), text, -80, 6E-05)); + } + for (var lng = 0; lng < 360; lng += 90) { + for (var lat = -80; lat <= 80; lat += 10) { + if (!lat) { + continue; + } + var text = lat.toString(); + if (lat > 0) { + text = ' +' + lat.toString(); + Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(lat - 0.4, lng), Coordinates.geoTo3dDouble(lat - 0.3, lng), text, -80, 6E-05)); + } + else { + text = ' - ' + text.substring(1); + Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(lat + 0.4, lng), Coordinates.geoTo3dDouble(lat + 0.5, lng), text, -80, 6E-05)); + } + } + } + } +}; + +var Grids$ = {}; + +registerType("Grids", [Grids, Grids$, null]); diff --git a/engine/esm/healpix_tables.js b/engine/esm/healpix_tables.js new file mode 100644 index 00000000..e3447cbf --- /dev/null +++ b/engine/esm/healpix_tables.js @@ -0,0 +1,24 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Data tables relating to HEALPix. + +import { registerType } from "./typesystem.js"; + + +// wwtlib.HealpixTables + +export function HealpixTables() { } + +HealpixTables.ctab = [0, 1, 256, 257, 2, 3, 258, 259, 512, 513, 768, 769, 514, 515, 770, 771, 4, 5, 260, 261, 6, 7, 262, 263, 516, 517, 772, 773, 518, 519, 774, 775, 1024, 1025, 1280, 1281, 1026, 1027, 1282, 1283, 1536, 1537, 1792, 1793, 1538, 1539, 1794, 1795, 1028, 1029, 1284, 1285, 1030, 1031, 1286, 1287, 1540, 1541, 1796, 1797, 1542, 1543, 1798, 1799, 8, 9, 264, 265, 10, 11, 266, 267, 520, 521, 776, 777, 522, 523, 778, 779, 12, 13, 268, 269, 14, 15, 270, 271, 524, 525, 780, 781, 526, 527, 782, 783, 1032, 1033, 1288, 1289, 1034, 1035, 1290, 1291, 1544, 1545, 1800, 1801, 1546, 1547, 1802, 1803, 1036, 1037, 1292, 1293, 1038, 1039, 1294, 1295, 1548, 1549, 1804, 1805, 1550, 1551, 1806, 1807, 2048, 2049, 2304, 2305, 2050, 2051, 2306, 2307, 2560, 2561, 2816, 2817, 2562, 2563, 2818, 2819, 2052, 2053, 2308, 2309, 2054, 2055, 2310, 2311, 2564, 2565, 2820, 2821, 2566, 2567, 2822, 2823, 3072, 3073, 3328, 3329, 3074, 3075, 3330, 3331, 3584, 3585, 3840, 3841, 3586, 3587, 3842, 3843, 3076, 3077, 3332, 3333, 3078, 3079, 3334, 3335, 3588, 3589, 3844, 3845, 3590, 3591, 3846, 3847, 2056, 2057, 2312, 2313, 2058, 2059, 2314, 2315, 2568, 2569, 2824, 2825, 2570, 2571, 2826, 2827, 2060, 2061, 2316, 2317, 2062, 2063, 2318, 2319, 2572, 2573, 2828, 2829, 2574, 2575, 2830, 2831, 3080, 3081, 3336, 3337, 3082, 3083, 3338, 3339, 3592, 3593, 3848, 3849, 3594, 3595, 3850, 3851, 3084, 3085, 3340, 3341, 3086, 3087, 3342, 3343, 3596, 3597, 3852, 3853, 3598, 3599, 3854, 3855]; +HealpixTables.utab = [0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85, 256, 257, 260, 261, 272, 273, 276, 277, 320, 321, 324, 325, 336, 337, 340, 341, 1024, 1025, 1028, 1029, 1040, 1041, 1044, 1045, 1088, 1089, 1092, 1093, 1104, 1105, 1108, 1109, 1280, 1281, 1284, 1285, 1296, 1297, 1300, 1301, 1344, 1345, 1348, 1349, 1360, 1361, 1364, 1365, 4096, 4097, 4100, 4101, 4112, 4113, 4116, 4117, 4160, 4161, 4164, 4165, 4176, 4177, 4180, 4181, 4352, 4353, 4356, 4357, 4368, 4369, 4372, 4373, 4416, 4417, 4420, 4421, 4432, 4433, 4436, 4437, 5120, 5121, 5124, 5125, 5136, 5137, 5140, 5141, 5184, 5185, 5188, 5189, 5200, 5201, 5204, 5205, 5376, 5377, 5380, 5381, 5392, 5393, 5396, 5397, 5440, 5441, 5444, 5445, 5456, 5457, 5460, 5461, 16384, 16385, 16388, 16389, 16400, 16401, 16404, 16405, 16448, 16449, 16452, 16453, 16464, 16465, 16468, 16469, 16640, 16641, 16644, 16645, 16656, 16657, 16660, 16661, 16704, 16705, 16708, 16709, 16720, 16721, 16724, 16725, 17408, 17409, 17412, 17413, 17424, 17425, 17428, 17429, 17472, 17473, 17476, 17477, 17488, 17489, 17492, 17493, 17664, 17665, 17668, 17669, 17680, 17681, 17684, 17685, 17728, 17729, 17732, 17733, 17744, 17745, 17748, 17749, 20480, 20481, 20484, 20485, 20496, 20497, 20500, 20501, 20544, 20545, 20548, 20549, 20560, 20561, 20564, 20565, 20736, 20737, 20740, 20741, 20752, 20753, 20756, 20757, 20800, 20801, 20804, 20805, 20816, 20817, 20820, 20821, 21504, 21505, 21508, 21509, 21520, 21521, 21524, 21525, 21568, 21569, 21572, 21573, 21584, 21585, 21588, 21589, 21760, 21761, 21764, 21765, 21776, 21777, 21780, 21781, 21824, 21825, 21828, 21829, 21840, 21841, 21844, 21845]; + +// coordinate of the lowest corner of each face +HealpixTables.jrll = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]; +HealpixTables.jpll = [1, 3, 5, 7, 0, 2, 4, 6, 1, 3, 5, 7]; +HealpixTables.xoffset = [-1, -1, 0, 1, 1, 1, 0, -1]; +HealpixTables.yoffset = [0, 1, 1, 1, 0, -1, -1, -1]; + +var HealpixTables$ = {}; + +registerType("HealpixTables", [HealpixTables, HealpixTables$, null]); diff --git a/engine/esm/healpix_tile.js b/engine/esm/healpix_tile.js new file mode 100644 index 00000000..9cfc56e7 --- /dev/null +++ b/engine/esm/healpix_tile.js @@ -0,0 +1,654 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses a HEALPix projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { + tileCacheAddTileToQueue, + tileCacheGetTile, + tileCacheRemoveFromQueue, + tilePrepDevice, + set_tileDemEnabled, +} from "./render_globals.js"; +import { Vector3d, Matrix3d, ConvexHull, PositionTexture } from "./double3d.js"; +import { DistanceCalc } from "./util.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { Coordinates } from "./coordinates.js"; +import { Fxyf } from "./fxyf.js"; +import { WebFile } from "./web_file.js"; +import { UiTools } from "./ui_tools.js"; +import { Tile } from "./tile.js"; + + +// wwtlib.Xyf + +export function Xyf() { + this.ix = 0; + this.iy = 0; + this.face = 0; +} + +Xyf.create = function (x, y, f) { + var temp = new Xyf(); + temp.ix = x; + temp.iy = y; + temp.face = f; + return temp; +}; + +var Xyf$ = {}; + +registerType("Xyf", [Xyf, Xyf$, null]); + + +// wwtlib.HealpixTile + +export function HealpixTile(level, x, y, dataset, parent) { + this.ipix = 0; + this.indexBuffer = new Array(4); + this._vertexList$1 = null; + this._nside$1 = 0; + this._tileIndex$1 = 0; + this._face$1 = 0; + this._faceX$1 = 0; + this._faceY$1 = 0; + this._step$1 = 0; + this._subDivided$1 = false; + this._catalogRows$1 = []; + Tile.call(this); + this.level = level; + this.tileX = x; + this.tileY = y; + this.dataset = dataset; + set_tileDemEnabled(false); + + if (!level) { + this._nside$1 = 4; + } else { + this._nside$1 = Math.pow(2, level + 1); + } + + if (parent == null) { + this._face$1 = x * 4 + y; + this.ipix = this._face$1; + } else { + this.parent = parent; + var parentTile = parent; + this._face$1 = parentTile._face$1; + this._tileIndex$1 = parentTile._tileIndex$1 * 4 + y * 2 + x; + this.ipix = this._face$1 * this._nside$1 * this._nside$1 / 4 + this._tileIndex$1; + this._faceX$1 = parentTile._faceX$1 * 2 + x; + this._faceY$1 = parentTile._faceY$1 * 2 + y; + } + this.isCatalogTile = ss.keyExists(dataset.get_hipsProperties().get_properties(), 'dataproduct_type') && dataset.get_hipsProperties().get_properties()['dataproduct_type'].toLowerCase() === 'catalog'; + this._computeBoundingSphere$1(); +} + +HealpixTile._galacticMatrix$1 = Matrix3d.create(-0.0548755604024359, -0.483835015526738, -0.873437090247923, 0, -0.867666148981161, 0.455983776232537, -0.198076373464674, 0, 0.494109427943568, 0.746982244476371, -0.444829629919504, 0, 0, 0, 0, 1); + +var HealpixTile$ = { + get_URL: function () { + if (this._url$1 == null) { + this._url$1 = this._getUrl$1(this.dataset, this.level, this.tileX, this.tileY); + return this._url$1; + } else { + return this._url$1; + } + }, + + _computeBoundingSphere$1: function () { + this._setStep$1(); + this.createGeometry(null); + var pointList = new Array(this._vertexList$1.length); + for (var i = 0; i < this._vertexList$1.length; i++) { + pointList[i] = this._vertexList$1[i].position; + } + this._calcSphere$1(pointList); + this._setCorners$1(); + }, + + createGeometry: function (renderContext) { + if (this._vertexList$1 != null) { + return true; + } + this._vertexList$1 = []; + this._populateVertexList$1(this._vertexList$1, this._step$1); + if (ss.keyExists(this.dataset.get_hipsProperties().get_properties(), 'hips_frame') && this.dataset.get_hipsProperties().get_properties()['hips_frame'] === 'galactic') { + for (var i = 0; i < this._vertexList$1.length; i++) { + var vert = this._vertexList$1[i]; + HealpixTile._galacticMatrix$1.multiplyVector(vert.position); + } + } + this.triangleCount = this._step$1 * this._step$1 / 2; + var ui16array = new Uint16Array(3 * this.triangleCount); + var indexArray = ui16array; + if (!this._subDivided$1) { + try { + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(this._vertexList$1.length * 5); + var buffer = f32array; + var index = 0; + var $enum1 = ss.enumerate(this._vertexList$1); + while ($enum1.moveNext()) { + var vert = $enum1.current; + index = this.addVertex(buffer, index, vert); + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + index = 0; + var offset = this._vertexList$1.length / (4 * this._step$1); + + //0 0 = left + //1 0 = top + //1 1 = right + this._setIndexBufferForQuadrant$1(indexArray, 0, 1); + if (this._step$1 > 1) { + this._setIndexBufferForQuadrant$1(indexArray, 0, 0); + this._setIndexBufferForQuadrant$1(indexArray, 1, 1); + this._setIndexBufferForQuadrant$1(indexArray, 1, 0); + } + } + catch (exception) { + } + } + return true; + }, + + _setIndexBufferForQuadrant$1: function (indexArray, x, y) { + var index = 0; + for (var i = x * this._step$1 / 2; i < (this._step$1 / 2) * (x + 1); i++) { + for (var j = y * this._step$1 / 2; j < (this._step$1 / 2) * (y + 1); j++) { + indexArray[index++] = (i * (this._step$1 + 1) + j); + indexArray[index++] = (1 + i * (this._step$1 + 1) + j); + indexArray[index++] = (this._step$1 + 1 + i * (this._step$1 + 1) + j); + indexArray[index++] = (1 + i * (this._step$1 + 1) + j); + indexArray[index++] = (this._step$1 + 1 + i * (this._step$1 + 1) + j); + indexArray[index++] = (this._step$1 + 2 + i * (this._step$1 + 1) + j); + } + } + this._processIndexBuffer$1(indexArray, x * 2 + y); + }, + + _getUrl$1: function (dataset, level, x, y) { + var extension = this._getHipsFileExtension$1(); + var tileTextureIndex = -1; + if (!level) { + tileTextureIndex = this._face$1; + } else { + tileTextureIndex = this._face$1 * this._nside$1 * this._nside$1 / 4 + this._tileIndex$1; + } + var sb = new ss.StringBuilder(); + var subDirIndex = Math.floor(tileTextureIndex / 10000) * 10000; + return ss.format(dataset.get_url(), level.toString(), subDirIndex.toString(), tileTextureIndex.toString() + extension); + }, + + _getHipsFileExtension$1: function () { + // The extension will contain either a space-separated list of types + // or a single type. We currently match preferred filetypes + // greedily. The extension must be exactly ".fits" in order to + // render correctly -- not only because of the greedy matching here, + // but because there are other parts of the code that check for an + // exact match. + + //prioritize transparent Png over other image formats + if (this.dataset.get_extension().toLowerCase().indexOf('png') > -1) { + return '.png'; + } + if (this.dataset.get_extension().toLowerCase().indexOf('jpeg') > -1 || this.dataset.get_extension().toLowerCase().indexOf('jpg') > -1) { + return '.jpg'; + } + if (this.dataset.get_extension().toLowerCase().indexOf('tsv') > -1) { + return '.tsv'; + } + if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1) { + return '.fits'; + } + + //default to most common + return '.jpg'; + }, + + isTileBigEnough: function (renderContext) { + if (this.dataset.get_dataSetType() === 1) { + var arcPixels = (180 / (Math.pow(2, this.level) * 4)); + return (renderContext.get_fovScale() < arcPixels); + } else { + var arcPixels = (3600 / (Math.pow(2, this.level) * 4)); + return (renderContext.get_fovScale() < arcPixels); + } + }, + + _boundaries$1: function (x, y, step) { + var nside = step * Math.pow(2, this.level); + var points = new Array(4); + var xyf = Xyf.create(x + this._faceX$1 * step, y + this._faceY$1 * step, this._face$1); + var dc = 0.5 / nside; + var xc = (xyf.ix + 0.5) / nside; + var yc = (xyf.iy + 0.5) / nside; + points[0] = Fxyf.create(xc + dc, yc + dc, xyf.face).toVec3(); + points[1] = Fxyf.create(xc - dc, yc + dc, xyf.face).toVec3(); + points[2] = Fxyf.create(xc - dc, yc - dc, xyf.face).toVec3(); + points[3] = Fxyf.create(xc + dc, yc - dc, xyf.face).toVec3(); + return points; + }, + + _setCorners$1: function () { + var xyf = Xyf.create(this.tileX, this.tileY, this._face$1); + var dc = 0.5 / this._nside$1; + var xc = (xyf.ix + 0.5) / this._nside$1; + var yc = (xyf.iy + 0.5) / this._nside$1; + this.topLeft = Fxyf.create(xc + dc, yc + dc, xyf.face).toVec3(); + this.bottomLeft = Fxyf.create(xc - dc, yc + dc, xyf.face).toVec3(); + this.bottomRight = Fxyf.create(xc - dc, yc - dc, xyf.face).toVec3(); + this.topRight = Fxyf.create(xc + dc, yc - dc, xyf.face).toVec3(); + }, + + draw3D: function (renderContext, opacity) { + if (this.isCatalogTile) { + this.drawCatalogTile(renderContext, opacity); + return true; + } + this.renderedGeneration = Tile.currentRenderGeneration; + Tile.tilesTouched++; + this.inViewFrustum = true; + var onlyDrawChildren = false; + if (!this.readyToRender) { + if (!this.errored) { + tileCacheAddTileToQueue(this); + return false; + } + if (this.errored && this.level < 3) { + //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv + onlyDrawChildren = true; + } + else { + return false; + } + } + var partCount = this.triangleCount; + Tile.trianglesRendered += partCount; + var anythingToRender = false; + var childRendered = false; + var childIndex = 0; + for (var y1 = 0; y1 < 2; y1++) { + for (var x1 = 0; x1 < 2; x1++) { + if (this.level < this.dataset.get_levels()) { + if (this.children[childIndex] == null) { + this.children[childIndex] = tileCacheGetTile(this.level + 1, x1, y1, this.dataset, this); + } + if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { + this.inViewFrustum = true; + if (this.children[childIndex].isTileBigEnough(renderContext) || onlyDrawChildren) { + this.renderChildPart[childIndex].set_targetState(!this.children[childIndex].draw3D(renderContext, opacity)); + if (this.renderChildPart[childIndex].get_targetState()) { + childRendered = true; + } + } + else { + this.renderChildPart[childIndex].set_targetState(true); + } + } + else { + this.renderChildPart[childIndex].set_targetState(this.renderChildPart[childIndex].set_state(false)); + } + } + else { + this.renderChildPart[childIndex].set_state(true); + } + if (!!this.renderChildPart[childIndex].get_state()) { + anythingToRender = true; + } + childIndex++; + } + } + if (childRendered || anythingToRender) { + this.renderedAtOrBelowGeneration = Tile.currentRenderGeneration; + if (this.parent != null) { + this.parent.renderedAtOrBelowGeneration = this.renderedAtOrBelowGeneration; + } + } + if (!anythingToRender) { + return true; + } + if (!this.createGeometry(renderContext)) { + return false; + } + if (onlyDrawChildren) { + return true; + } + Tile.tilesInView++; + for (var i = 0; i < 4; i++) { + if (this.renderChildPart[i].get_targetState()) { + this.renderPart(renderContext, i, opacity / 100, false); + } + } + return true; + }, + + drawCatalogTile: function (renderContext, opacity) { + this.renderedGeneration = Tile.currentRenderGeneration; + Tile.tilesTouched++; + this.inViewFrustum = true; + var onlyDrawChildren = false; + if (!this.readyToRender) { + if (!this.errored) { + tileCacheAddTileToQueue(this); + return; + } + if (this.errored && this.level < 3) { + //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv + onlyDrawChildren = true; + } + else { + return; + } + } + var anyChildInFrustum = false; + var childIndex = 0; + for (var y1 = 0; y1 < 2; y1++) { + for (var x1 = 0; x1 < 2; x1++) { + if (this.level < this.dataset.get_levels()) { + if (this.children[childIndex] == null) { + this.children[childIndex] = tileCacheGetTile(this.level + 1, x1, y1, this.dataset, this); + } + if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { + this.inViewFrustum = true; + anyChildInFrustum = true; + if (this.children[childIndex].isTileBigEnough(renderContext) || onlyDrawChildren) { + (this.children[childIndex]).drawCatalogTile(renderContext, opacity); + } + else { + (this.children[childIndex]).removeCatalogTile(); + } + } + else { + (this.children[childIndex]).removeCatalogTile(); + } + } + childIndex++; + } + } + if (!this.level && !anyChildInFrustum && !onlyDrawChildren) { + this.removeCatalogTile(); + } else if (anyChildInFrustum) { + Tile.tilesInView++; + this._addCatalogTile$1(); + } + }, + + removeCatalogTile: function () { + this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().removeTileRows(this.get_key(), this._catalogRows$1); + }, + + _addCatalogTile$1: function () { + this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().addTileRows(this.get_key(), this._catalogRows$1); + }, + + _extractCatalogTileRows$1: function () { + var headerRemoved = false; + var $enum1 = ss.enumerate(this._catalogData$1.getText().split('\n')); + while ($enum1.moveNext()) { + var line = $enum1.current; + if (!ss.startsWith(line, '#') && !headerRemoved) { + headerRemoved = true; + continue; + } + if (!ss.startsWith(line, '#')) { + var rowData = UiTools.splitString(line, this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().get__table().delimiter); + this._catalogRows$1.push(rowData); + } + } + }, + + getDataInView: function (renderContext, limit, catalogSpreadSheetLayer) { + if (!this.readyToRender) { + if (!this.errored) { + this.requestImage(); + if (limit) { + return false; + } + } + else if (this.level >= 3) { + //Level 0-2 sometimes deleted in favor of allsky.jpg/tsv + return true; + } + } + var allChildrenReady = true; + var anyChildInFrustum = false; + var childIndex = 0; + for (var y1 = 0; y1 < 2; y1++) { + for (var x1 = 0; x1 < 2; x1++) { + if (this.level < this.dataset.get_levels()) { + if (this.children[childIndex] == null) { + this.children[childIndex] = tileCacheGetTile(this.level + 1, x1, y1, this.dataset, this); + } + if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { + anyChildInFrustum = true; + allChildrenReady = allChildrenReady && (this.children[childIndex]).getDataInView(renderContext, limit, catalogSpreadSheetLayer); + } + } + childIndex++; + } + } + if (anyChildInFrustum) { + catalogSpreadSheetLayer.addTileRows(this.get_key(), this._catalogRows$1); + } + return allChildrenReady && !this.downloading; + }, + + _setStep$1: function () { + if (this.isCatalogTile) { + this._step$1 = 2; + } else { + switch (this.level) { + case 0: + case 1: + case 2: + case 3: + case 4: + this._step$1 = 16; + break; + case 5: + this._step$1 = 8; + break; + case 6: + this._step$1 = 4; + break; + default: + this._step$1 = 2; + break; + } + } + }, + + requestImage: function () { + if (this.isCatalogTile) { + if (!this.downloading && !this.readyToRender) { + this.downloading = true; + this._catalogData$1 = new WebFile(this.get_URL()); + this._catalogData$1.onStateChange = ss.bind('_loadCatalogData$1', this); + this._catalogData$1.send(); + } + } else { + Tile.prototype.requestImage.call(this); + } + }, + + _loadCatalogData$1: function () { + if (this._catalogData$1.get_state() === 2) { + this.requestPending = false; + this.downloading = false; + this.errored = true; + tileCacheRemoveFromQueue(this.get_key(), true); + } else if (this._catalogData$1.get_state() === 1) { + this._extractCatalogTileRows$1(); + this.texReady = true; + this.downloading = false; + this.errored = false; + this.readyToRender = true; + this.requestPending = false; + tileCacheRemoveFromQueue(this.get_key(), true); + } + }, + + getIndexBuffer: function (index, accomidation) { + return this.indexBuffer[index]; + }, + + _calcSphere$1: function (list) { + var result = ConvexHull.findEnclosingSphere(list); + this.sphereCenter = result.center; + this.sphereRadius = result.radius; + }, + + isPointInTile: function (lat, lng) { + if (!this.level) { + return true; + } + if (this.level === 1) { + if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { + return true; + } + if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { + return true; + } + if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { + return true; + } + if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { + return true; + } + } + var testPoint = Coordinates.geoTo3dDouble(lat, lng); + var top = this._isLeftOfHalfSpace$1(this.topLeft, this.topRight, testPoint); + var right = this._isLeftOfHalfSpace$1(this.topRight, this.bottomRight, testPoint); + var bottom = this._isLeftOfHalfSpace$1(this.bottomRight, this.bottomLeft, testPoint); + var left = this._isLeftOfHalfSpace$1(this.bottomLeft, this.topLeft, testPoint); + if (top && right && bottom && left) { + return true; + } + return false; + }, + + _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { + pntA.normalize(); + pntB.normalize(); + var cross = Vector3d.cross(pntA, pntB); + var dot = Vector3d.dot(cross, pntTest); + return dot > 0; + }, + + getSurfacePointAltitude: function (lat, lng, meters) { + if (this.level < Tile.lastDeepestLevel) { + var $enum1 = ss.enumerate(this.children); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child != null) { + if (child.isPointInTile(lat, lng)) { + var retVal = child.getSurfacePointAltitude(lat, lng, meters); + if (!!retVal) { + return retVal; + } + else { + break; + } + } + } + } + } + return this._getAltitudeFromLatLng$1(lat, lng, meters); + }, + + _getAltitudeFromLatLng$1: function (lat, lng, meters) { + var testPoint = Coordinates.geoTo3dDouble(lat, lng); + var uv = DistanceCalc.getUVFromInnerPoint(this.topLeft, this.topRight, this.bottomLeft, this.bottomRight, testPoint); + + // Get 4 samples and interpolate + var uud = Math.max(0, Math.min(16, (uv.x * 16))); + var vvd = Math.max(0, Math.min(16, (uv.y * 16))); + var uu = Math.max(0, Math.min(15, ss.truncate((uv.x * 16)))); + var vv = Math.max(0, Math.min(15, ss.truncate((uv.y * 16)))); + var ha = uud - uu; + var va = vvd - vv; + if (this.demArray != null) { + // 4 nearest neighbors + var ul = this.demArray[uu + 17 * vv]; + var ur = this.demArray[(uu + 1) + 17 * vv]; + var ll = this.demArray[uu + 17 * (vv + 1)]; + var lr = this.demArray[(uu + 1) + 17 * (vv + 1)]; + var top = ul * (1 - ha) + ha * ur; + var bottom = ll * (1 - ha) + ha * lr; + var val = top * (1 - va) + va * bottom; + return val / ((meters) ? 1 : this.get__demScaleFactor()); + } + return this.demAverage / ((meters) ? 1 : this.get__demScaleFactor()); + }, + + _processIndexBuffer$1: function (indexArray, part) { + this.indexBuffer[part] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this.indexBuffer[part]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, indexArray, WEBGL.STATIC_DRAW); + }, + + cleanUp: function (removeFromParent) { + Tile.prototype.cleanUp.call(this, removeFromParent); + this._returnBuffers$1(); + this._subDivided$1 = false; + }, + + _returnBuffers$1: function () { + if (this._vertexList$1 != null) { + this._vertexList$1 = null; + } + }, + + // Vertices distributed in a grid pattern like the example below + // Example for pattern with step set to 4 + // 24 + // 19 23 + // 14 18 22 + // 9 13 17 21 + // 4 8 12 16 20 + // 3 7 11 15 + // 2 6 10 + // 1 5 + // 0 + _populateVertexList$1: function (vertexList, step) { + for (var i = 0; i < step; i += 2) { + for (var j = 0; j < step; j += 2) { + var points = this._boundaries$1(j, i, step); + vertexList[i * (step + 1) + j] = PositionTexture.createPos(points[2], (1 / step) * i, (1 / step) * j); + vertexList[i * (step + 1) + j + 1] = PositionTexture.createPos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); + vertexList[(i + 1) * (step + 1) + j] = PositionTexture.createPos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); + vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); + if (j + 2 >= step && step > 1) { + j = step - 1; + points = this._boundaries$1(j, i, step); + vertexList[i * (step + 1) + step] = PositionTexture.createPos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); + vertexList[(i + 1) * (step + 1) + step] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); + } + } + } + if (step > 1) { + this._vertexOfLastRow$1(vertexList, step); + } + }, + + _vertexOfLastRow$1: function (vertexList, step) { + var i = step - 1; + for (var j = 0; j < step; j += 2) { + var points = this._boundaries$1(j, i, step); + vertexList[(i + 1) * (step + 1) + j] = PositionTexture.createPos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); + vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); + if (j + 2 >= step) { + j = step - 1; + points = this._boundaries$1(j, i, step); + vertexList[(i + 1) * (step + 1) + step] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); + } + } + } +}; + +registerType("HealpixTile", [HealpixTile, HealpixTile$, Tile]); diff --git a/engine/esm/healpix_utils.js b/engine/esm/healpix_utils.js new file mode 100644 index 00000000..ef62bab8 --- /dev/null +++ b/engine/esm/healpix_utils.js @@ -0,0 +1,51 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Utilities relating to HEALPix. + +import { registerType } from "./typesystem.js"; +import { FastMath } from "./fast_math.js"; + + +// wwtlib.HealpixUtils + +export function HealpixUtils() { } + +HealpixUtils.check = function (cond, errtxt) { + if (!cond) { + throw new Error(errtxt); + } +}; + +// Integer square root. +HealpixUtils.isqrt = function (arg) { + var res = Math.sqrt((arg) + 0.5); + if (arg < (1 << 50)) { + return res; + } + if (res * res > arg) { + --res; + } + else if ((res + 1) * (res + 1) <= arg) { + ++res; + } + return res; +}; + +// Computes the cosine of the angular distance between two z, phi positions on +// the unit sphere +HealpixUtils.cosdist_zphi = function (z1, phi1, z2, phi2) { + return z1 * z2 + FastMath.cos(phi1 - phi2) * Math.sqrt((1 - z1 * z1) * (1 - z2 * z2)); +}; + +HealpixUtils.fmodulo = function (v1, v2) { + if (v1 >= 0) { + return (v1 < v2) ? v1 : v1 % v2; + } + var tmp = v1 % v2 + v2; + return (tmp === v2) ? 0 : tmp; +}; + +var HealpixUtils$ = {}; + +registerType("HealpixUtils", [HealpixUtils, HealpixUtils$, null]); diff --git a/engine/esm/hips_properties.js b/engine/esm/hips_properties.js new file mode 100644 index 00000000..d5d8d03e --- /dev/null +++ b/engine/esm/hips_properties.js @@ -0,0 +1,136 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Summary properties about HiPS datasets. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { set_makeNewHipsProperties } from "./data_globals.js"; +import { WebFile } from "./web_file.js"; +import { Guid } from "./util.js"; +import { CatalogSpreadSheetLayer } from "./layers/spreadsheet_layer.js"; +import { VoTable } from "./layers/vo_table.js"; +import { LayerManager } from "./layers/layer_manager.js"; + + +// wwtlib.HipsProperties + +export function HipsProperties(dataset) { + this._properties = {}; + this._catalogColumnInfo = null; + this._catalogSpreadSheetLayer = new CatalogSpreadSheetLayer(); + this._downloadComplete = false; + this.dataset = dataset; + this._datasetName = dataset.get_name(); + this._url = dataset.get_url(); + if (this._url.toLowerCase().indexOf('norder') > -1) { + this._url = this._url.substring(0, this._url.toLowerCase().indexOf('norder')); + } + this._url += 'properties'; + this._download(); +} + +var HipsProperties$ = { + get_properties: function () { + return this._properties; + }, + + get_catalogSpreadSheetLayer: function () { + return this._catalogSpreadSheetLayer; + }, + + set_catalogSpreadSheetLayer: function (value) { + this._catalogSpreadSheetLayer = value; + return value; + }, + + get_catalogColumnInfo: function () { + return this._catalogColumnInfo; + }, + + set_catalogColumnInfo: function (value) { + this._catalogColumnInfo = value; + return value; + }, + + get_downloadComplete: function () { + return this._downloadComplete; + }, + + _download: function () { + this._webFile = new WebFile(this._url); + this._webFile.onStateChange = ss.bind('_onPropertiesDownloadComplete', this); + this._webFile.send(); + }, + + _onPropertiesDownloadComplete: function () { + if (this._webFile.get_state() === 1) { + this._parseProperties(this._webFile.getText()); + if (ss.keyExists(this.get_properties(), 'dataproduct_type') && this.get_properties()['dataproduct_type'].toLowerCase() === 'catalog') { + this._catalogColumnInfo = VoTable.loadFromUrl(ss.replaceString(this._url, '/properties', '/metadata.xml'), ss.bind('_onCatalogMetadataDownloadComplete', this)); + } + else { + if (ss.keyExists(this.get_properties(), 'hips_data_range')) { + var hips_data_range = this.get_properties()['hips_data_range']; + this.dataset.get_fitsProperties().minVal = parseFloat(hips_data_range.split(' ')[0]); + this.dataset.get_fitsProperties().maxVal = parseFloat(hips_data_range.split(' ')[1]); + this.dataset.get_fitsProperties().lowerCut = this.dataset.get_fitsProperties().minVal; + this.dataset.get_fitsProperties().upperCut = this.dataset.get_fitsProperties().maxVal; + } + if (ss.keyExists(this.get_properties(), 'hips_pixel_cut')) { + var hips_pixel_cut = this.get_properties()['hips_pixel_cut']; + this.dataset.get_fitsProperties().lowerCut = parseFloat(hips_pixel_cut.split(' ')[0]); + this.dataset.get_fitsProperties().upperCut = parseFloat(hips_pixel_cut.split(' ')[1]); + if (!ss.keyExists(this.get_properties(), 'hips_data_range')) { + this.dataset.get_fitsProperties().minVal = this.dataset.get_fitsProperties().lowerCut; + this.dataset.get_fitsProperties().maxVal = this.dataset.get_fitsProperties().upperCut; + } + } + this._downloadComplete = true; + if (this._onDownloadComplete != null) { + this._onDownloadComplete(); + } + } + } + }, + + _onCatalogMetadataDownloadComplete: function () { + this._catalogSpreadSheetLayer.useHeadersFromVoTable(this._catalogColumnInfo); + this._catalogSpreadSheetLayer.set_name(this._datasetName); + this._catalogSpreadSheetLayer.id = Guid.createFrom(this._datasetName); + LayerManager.addSpreadsheetLayer(this.get_catalogSpreadSheetLayer(), 'Sky'); + this._downloadComplete = true; + if (this._onDownloadComplete != null) { + this._onDownloadComplete(); + } + }, + + setDownloadCompleteListener: function (listener) { + this._onDownloadComplete = listener; + }, + + _parseProperties: function (data) { + var lines = data.split('\n'); + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var line = $enum1.current; + if (!ss.whitespace(line) && !ss.startsWith(line, '#')) { + var parts = line.split('='); + if (parts.length === 2) { + var key = ss.trim(parts[0]); + var val = ss.trim(parts[1]); + if (!ss.whitespace(key) && !ss.whitespace(val)) { + this.get_properties()[key] = val; + } + } + } + } + } +}; + +registerType("HipsProperties", [HipsProperties, HipsProperties$, null]); + +set_makeNewHipsProperties(function (imageset) { + return new HipsProperties(imageset); +}); + diff --git a/engine/esm/hploc.js b/engine/esm/hploc.js new file mode 100644 index 00000000..fef4cb65 --- /dev/null +++ b/engine/esm/hploc.js @@ -0,0 +1,46 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A HEALPix location type. + +import { registerType } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { FastMath } from "./fast_math.js"; + + +// wwtlib.Hploc + +export function Hploc() { + this.z = 0; + this.phi = 0; + this.sth = 0; + this.have_sth = false; +} + +Hploc.create = function (v) { + var temp = new Hploc(); + var xl = 1 / v.length(); + temp.z = v.z * xl; + temp.phi = FastMath.atan2(v.y, v.x); + if (Math.abs(temp.z) > 0.99) { + temp.sth = Math.sqrt(v.x * v.x + v.y * v.y) * xl; + temp.have_sth = true; + } + return temp; +}; + +var Hploc$ = { + toVec3: function () { + var st; + if (this.have_sth) { + st = this.sth; + } else { + st = Math.sqrt((1 - this.z) * (1 + this.z)); + } + var x = st * FastMath.cos(this.phi); + var y = st * FastMath.sin(this.phi); + return Vector3d.create(x, this.z, y); + } +}; + +registerType("Hploc", [Hploc, Hploc$, null]); diff --git a/engine/esm/imageset.js b/engine/esm/imageset.js new file mode 100644 index 00000000..6dfa22d8 --- /dev/null +++ b/engine/esm/imageset.js @@ -0,0 +1,910 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// An image tile pyramid. + +import { ss } from "./ss.js"; +import { registerType, registerEnum, Enums } from "./typesystem.js"; +import { freestandingMode, makeNewHipsProperties } from "./data_globals.js"; +import { Matrix3d } from "./double3d.js"; +import { Util } from "./baseutil.js"; +import { IThumbnail } from "./interfaces.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Coordinates } from "./coordinates.js"; +import { FitsProperties } from "./fits_properties.js"; +import { FitsImage } from "./layers/fits_image.js"; +import { EquirectangularTile } from "./equirectangular_tile.js"; +import { HealpixTile } from "./healpix_tile.js"; +import { MercatorTile } from "./mercator_tile.js"; +import { PlotTile } from "./plot_tile.js"; +import { TangentTile } from "./tangent_tile.js"; +import { SkyImageTile } from "./sky_image_tile.js"; +import { ToastTile } from "./toast_tile.js"; + + +// wwtlib.ProjectionType +// +// This was originally defined in `IImageset.cs`, not `Imageset.cs`, but we've +// folded it into this file. + +export var ProjectionType = { + mercator: 0, + equirectangular: 1, + tangent: 2, + tan: 2, + toast: 3, + spherical: 4, + skyImage: 5, + plotted: 6, + healpix: 7 +}; + +registerType("ProjectionType", ProjectionType); +registerEnum("ProjectionType", ProjectionType); + + +// wwtlib.ImageSetType +// +// This was originally defined in `IImageset.cs`, not `Imageset.cs`, but we've +// folded it into this file. + +export var ImageSetType = { + earth: 0, + planet: 1, + sky: 2, + panorama: 3, + solarSystem: 4, + sandbox: 5 +}; + +registerType("ImageSetType", ImageSetType); +registerEnum("ImageSetType", ImageSetType); + + +// wwtlib.BandPass +// +// This was originally defined in `IImageset.cs`, not `Imageset.cs`, but we've +// folded it into this file. + +export var BandPass = { + gamma: 0, + xRay: 1, + ultraviolet: 2, + visible: 3, + hydrogenAlpha: 4, + IR: 4, + microwave: 5, + radio: 6, + visibleNight: 6 +}; + +registerType("BandPass", BandPass); +registerEnum("BandPass", BandPass); + + +// wwtlib.Imageset + +export function Imageset() { + this._projection = 0; + this._imageSetID = 0; + this._baseTileDegrees = 0; + this._widthFactor = 1; + this.demUrl = ''; + this._levels = 0; + this._mercator = false; + this._bottomsUp = false; + this._baseLevel = 1; + this._quadTreeTileMap = '0123'; + this._centerX = 0; + this._centerY = 0; + this._rotation = 0; + this._meanRadius = 0; + this._dataSetType = 0; + this._bandPass = 3; + this._altUrl = ''; + this._singleImage = false; + this._fitsProperties = new FitsProperties(); + this._matrixComputed = false; + this._name = ''; + this._sparse = false; + this._thumbnailUrl = ''; + this._generic = false; + this._defaultSet = false; + this._elevationModel = false; + this._offsetX = 0; + this._offsetY = 0; +} + +Imageset.getNewTile = function (imageset, level, x, y, parent) { + // Note: "spherical" projection type not handled in the WebGL engine. + switch (imageset.get_projection()) { + case ProjectionType.mercator: + var newTile = MercatorTile.create(level, x, y, imageset, parent); + return newTile; + case ProjectionType.equirectangular: + return EquirectangularTile.create(level, x, y, imageset, parent); + case ProjectionType.toast: + default: + return ToastTile.create(level, x, y, imageset, parent); + case ProjectionType.skyImage: + return new SkyImageTile(level, x, y, imageset, parent); + case ProjectionType.plotted: + return PlotTile.create(level, x, y, imageset, parent); + case ProjectionType.healpix: + if (imageset.get_hipsProperties() == null) { + imageset.set_hipsProperties(makeNewHipsProperties(imageset)); + } + if (imageset.get_hipsProperties().get_downloadComplete()) { + return new HealpixTile(level, x, y, imageset, parent); + } + else { + return null; + } + case ProjectionType.tangent: + var newTile = new TangentTile(level, x, y, imageset, parent); + return newTile; + } +}; + +Imageset.fromXMLNode = function (node) { + try { + var type = 2; + var projection = 2; + if (node.attributes.getNamedItem('DataSetType') != null) { + type = Enums.parse('ImageSetType', node.attributes.getNamedItem('DataSetType').nodeValue); + } + var bandPass = 3; + bandPass = Enums.parse('BandPass', node.attributes.getNamedItem('BandPass').nodeValue); + var wf = 1; + if (node.attributes.getNamedItem('WidthFactor') != null) { + wf = parseInt(node.attributes.getNamedItem('WidthFactor').nodeValue); + } + if (node.attributes.getNamedItem('Generic') == null || !ss.boolean(node.attributes.getNamedItem('Generic').nodeValue)) { + projection = Enums.parse('ProjectionType', node.attributes.getNamedItem('Projection').nodeValue); + var fileType = node.attributes.getNamedItem('FileType').nodeValue; + if (!ss.startsWith(fileType, '.')) { + fileType = '.' + fileType; + } + var thumbnailUrl = ''; + var thumbUrl = Util.selectSingleNode(node, 'ThumbnailUrl'); + if (thumbUrl != null) { + if (ss.emptyString(thumbUrl.text)) { + var cn = thumbUrl; + thumbnailUrl = cn.textContent; + } + else { + thumbnailUrl = thumbUrl.text; + } + } + var stockSet = false; + var elevationModel = false; + if (node.attributes.getNamedItem('StockSet') != null) { + stockSet = ss.boolean(node.attributes.getNamedItem('StockSet').nodeValue); + } + if (node.attributes.getNamedItem('ElevationModel') != null) { + elevationModel = ss.boolean(node.attributes.getNamedItem('ElevationModel').nodeValue); + } + var demUrl = ''; + if (node.attributes.getNamedItem('DemUrl') != null) { + demUrl = node.attributes.getNamedItem('DemUrl').nodeValue; + } + var alturl = ''; + if (node.attributes.getNamedItem('AltUrl') != null) { + alturl = node.attributes.getNamedItem('AltUrl').nodeValue; + } + var offsetX = 0; + if (node.attributes.getNamedItem('OffsetX') != null) { + offsetX = parseFloat(node.attributes.getNamedItem('OffsetX').nodeValue); + } + var offsetY = 0; + if (node.attributes.getNamedItem('OffsetY') != null) { + offsetY = parseFloat(node.attributes.getNamedItem('OffsetY').nodeValue); + } + var creditText = ''; + var credits = Util.selectSingleNode(node, 'Credits'); + if (credits != null) { + creditText = Util.getInnerText(credits); + } + var creditsUrl = ''; + credits = Util.selectSingleNode(node, 'CreditsUrl'); + if (credits != null) { + creditsUrl = Util.getInnerText(credits); + } + var meanRadius = 0; + if (node.attributes.getNamedItem('MeanRadius') != null) { + meanRadius = parseFloat(node.attributes.getNamedItem('MeanRadius').nodeValue); + } + var referenceFrame = null; + if (node.attributes.getNamedItem('ReferenceFrame') != null) { + referenceFrame = node.attributes.getNamedItem('ReferenceFrame').nodeValue; + } + var name = ''; + if (node.attributes.getNamedItem('Name') != null) { + name = node.attributes.getNamedItem('Name').nodeValue; + } + var url = ''; + if (node.attributes.getNamedItem('Url') != null) { + url = node.attributes.getNamedItem('Url').nodeValue; + } + var baseTileLevel = 0; + if (node.attributes.getNamedItem('BaseTileLevel') != null) { + baseTileLevel = parseInt(node.attributes.getNamedItem('BaseTileLevel').nodeValue); + } + var tileLevels = 0; + if (node.attributes.getNamedItem('TileLevels') != null) { + tileLevels = parseInt(node.attributes.getNamedItem('TileLevels').nodeValue); + } + var baseDegreesPerTile = 0; + if (node.attributes.getNamedItem('BaseDegreesPerTile') != null) { + baseDegreesPerTile = parseFloat(node.attributes.getNamedItem('BaseDegreesPerTile').nodeValue); + } + var bottomsUp = false; + if (node.attributes.getNamedItem('BottomsUp') != null) { + bottomsUp = ss.boolean(node.attributes.getNamedItem('BottomsUp').nodeValue); + } + var quadTreeMap = ''; + if (node.attributes.getNamedItem('QuadTreeMap') != null) { + quadTreeMap = node.attributes.getNamedItem('QuadTreeMap').nodeValue; + } + var centerX = 0; + if (node.attributes.getNamedItem('CenterX') != null) { + centerX = parseFloat(node.attributes.getNamedItem('CenterX').nodeValue); + } + var centerY = 0; + if (node.attributes.getNamedItem('CenterY') != null) { + centerY = parseFloat(node.attributes.getNamedItem('CenterY').nodeValue); + } + var rotation = 0; + if (node.attributes.getNamedItem('Rotation') != null) { + rotation = parseFloat(node.attributes.getNamedItem('Rotation').nodeValue); + } + var sparse = false; + if (node.attributes.getNamedItem('Sparse') != null) { + sparse = ss.boolean(node.attributes.getNamedItem('Sparse').nodeValue); + } + return Imageset.create(name, url, type, bandPass, projection, Math.abs(Util.getHashCode(url)), baseTileLevel, tileLevels, 256, baseDegreesPerTile, fileType, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, stockSet, elevationModel, wf, offsetX, offsetY, creditText, creditsUrl, demUrl, alturl, meanRadius, referenceFrame); + } else { + return Imageset.createGeneric(type, bandPass); + } + } + catch ($e1) { + return null; + } +}; + +Imageset.saveToXml = function (xmlWriter, imageset, alternateUrl) { + xmlWriter._writeStartElement('ImageSet'); + xmlWriter._writeAttributeString('Generic', imageset.get_generic().toString()); + xmlWriter._writeAttributeString('DataSetType', Enums.toXml('ImageSetType', imageset.get_dataSetType())); + xmlWriter._writeAttributeString('BandPass', Enums.toXml('BandPass', imageset.get_bandPass())); + if (!imageset.get_generic()) { + xmlWriter._writeAttributeString('Name', imageset.get_name()); + if (ss.emptyString(alternateUrl)) { + xmlWriter._writeAttributeString('Url', imageset.get_url()); + } else { + xmlWriter._writeAttributeString('Url', alternateUrl); + } + xmlWriter._writeAttributeString('DemUrl', imageset.get_demUrl()); + xmlWriter._writeAttributeString('BaseTileLevel', imageset.get_baseLevel().toString()); + xmlWriter._writeAttributeString('TileLevels', imageset.get_levels().toString()); + xmlWriter._writeAttributeString('BaseDegreesPerTile', imageset.get_baseTileDegrees().toString()); + xmlWriter._writeAttributeString('FileType', imageset.get_extension()); + xmlWriter._writeAttributeString('BottomsUp', imageset.get_bottomsUp().toString()); + xmlWriter._writeAttributeString('Projection', Enums.toXml('ProjectionType', imageset.get_projection())); + xmlWriter._writeAttributeString('QuadTreeMap', imageset.get_quadTreeTileMap()); + xmlWriter._writeAttributeString('CenterX', imageset.get_centerX().toString()); + xmlWriter._writeAttributeString('CenterY', imageset.get_centerY().toString()); + xmlWriter._writeAttributeString('OffsetX', imageset.get_offsetX().toString()); + xmlWriter._writeAttributeString('OffsetY', imageset.get_offsetY().toString()); + xmlWriter._writeAttributeString('Rotation', imageset.get_rotation().toString()); + xmlWriter._writeAttributeString('Sparse', imageset.get_sparse().toString()); + xmlWriter._writeAttributeString('ElevationModel', imageset.get_elevationModel().toString()); + xmlWriter._writeAttributeString('StockSet', imageset.get_defaultSet().toString()); + xmlWriter._writeAttributeString('WidthFactor', imageset.get_widthFactor().toString()); + xmlWriter._writeAttributeString('MeanRadius', imageset.get_meanRadius().toString()); + xmlWriter._writeAttributeString('ReferenceFrame', imageset.get_referenceFrame()); + if (ss.emptyString(alternateUrl)) { + xmlWriter._writeElementString('ThumbnailUrl', imageset.get_thumbnailUrl()); + } else { + xmlWriter._writeElementString('ThumbnailUrl', imageset.get_url()); + } + } + xmlWriter._writeEndElement(); +}; + +Imageset.createGeneric = function (dataSetType, bandPass) { + var temp = new Imageset(); + temp._generic = true; + temp._name = 'Generic'; + temp._sparse = false; + temp._dataSetType = dataSetType; + temp._bandPass = bandPass; + temp._quadTreeTileMap = ''; + temp.url = ''; + temp._levels = 0; + temp._baseTileDegrees = 0; + temp._imageSetID = 0; + temp._extension = ''; + temp._projection = 1; + temp._bottomsUp = false; + temp._baseLevel = 0; + temp._mercator = (!temp._projection); + temp._centerX = 0; + temp._centerY = 0; + temp._rotation = 0; + temp._thumbnailUrl = ''; + temp._matrix = Matrix3d.get_identity(); + temp._matrix._multiply(Matrix3d._rotationX((temp.get_rotation() / 180 * Math.PI))); + temp._matrix._multiply(Matrix3d._rotationZ((temp.get_centerY() / 180 * Math.PI))); + temp._matrix._multiply(Matrix3d._rotationY((((360 - temp.get_centerX()) + 180) / 180 * Math.PI))); + return temp; +}; + +Imageset.create = function (name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, tileSize, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame) { + var temp = new Imageset(); + temp.setInitialParameters(name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame); + return temp; +}; + +var Imageset$ = { + get_wcsImage: function () { + return this._wcsImage; + }, + + set_wcsImage: function (value) { + this._wcsImage = value; + return value; + }, + + get_projection: function () { + return this._projection; + }, + + set_projection: function (value) { + this._projection = value; + return value; + }, + + get_referenceFrame: function () { + return this._referenceFrame; + }, + + set_referenceFrame: function (value) { + this._referenceFrame = value; + return value; + }, + + get_imageSetID: function () { + return this._imageSetID; + }, + + set_imageSetID: function (value) { + this._imageSetID = value; + return value; + }, + + get_baseTileDegrees: function () { + return this._baseTileDegrees; + }, + + set_baseTileDegrees: function (value) { + this._baseTileDegrees = value; + return value; + }, + + get_widthFactor: function () { + return this._widthFactor; + }, + + set_widthFactor: function (value) { + this._widthFactor = value; + return value; + }, + + getHashCode: function () { + return Util.getHashCode(this.get_url()); + }, + + get_url: function () { + return this.url; + }, + + set_url: function (value) { + this.url = value; + return value; + }, + + get_demUrl: function () { + if (ss.emptyString(this.demUrl) && !this._projection && !freestandingMode) { + return URLHelpers.singleton.coreStaticUrl('wwtweb/BingDemTile.aspx?Q={0},{1},{2}'); + } + return this.demUrl; + }, + + set_demUrl: function (value) { + this.demUrl = value; + return value; + }, + + get_extension: function () { + return this._extension; + }, + + set_extension: function (value) { + this._extension = value; + return value; + }, + + get_levels: function () { + return this._levels; + }, + + set_levels: function (value) { + this._levels = value; + return value; + }, + + get_bottomsUp: function () { + return this._bottomsUp; + }, + + set_bottomsUp: function (value) { + this._bottomsUp = value; + return value; + }, + + get_mercator: function () { + return this._mercator; + }, + + set_mercator: function (value) { + this._mercator = value; + return value; + }, + + get_baseLevel: function () { + return this._baseLevel; + }, + + set_baseLevel: function (value) { + this._baseLevel = value; + return value; + }, + + get_quadTreeTileMap: function () { + return this._quadTreeTileMap; + }, + + set_quadTreeTileMap: function (value) { + this._quadTreeTileMap = value; + return value; + }, + + get_centerX: function () { + return this._centerX; + }, + + set_centerX: function (value) { + if (this._centerX !== value) { + this._centerX = value; + this._computeMatrix(); + } + return value; + }, + + get_centerY: function () { + return this._centerY; + }, + + set_centerY: function (value) { + if (this._centerY !== value) { + this._centerY = value; + this._computeMatrix(); + } + return value; + }, + + get_rotation: function () { + return this._rotation; + }, + + set_rotation: function (value) { + if (this._rotation !== value) { + this._rotation = value; + this._computeMatrix(); + } + return value; + }, + + get_meanRadius: function () { + return this._meanRadius; + }, + + set_meanRadius: function (value) { + this._meanRadius = value; + return value; + }, + + get_bandPass: function () { + return this._bandPass; + }, + + set_bandPass: function (value) { + this._bandPass = value; + return value; + }, + + get_dataSetType: function () { + return this._dataSetType; + }, + + set_dataSetType: function (value) { + this._dataSetType = value; + return value; + }, + + get_altUrl: function () { + return this._altUrl; + }, + + set_altUrl: function (value) { + this._altUrl = value; + return value; + }, + + get_singleImage: function () { + return this._singleImage; + }, + + set_singleImage: function (value) { + this._singleImage = value; + return value; + }, + + get_hipsProperties: function () { + return this._hipsProperties; + }, + + set_hipsProperties: function (value) { + this._hipsProperties = value; + return value; + }, + + get_fitsProperties: function () { + return this._fitsProperties; + }, + + set_fitsProperties: function (value) { + this._fitsProperties = value; + return value; + }, + + toString: function () { + if (this.get_defaultSet()) { + return this._name + ' *'; + } else { + return this._name; + } + }, + + get_stockImageSet: function () { + if (this._generic || !this._defaultSet) { + return this; + } else { + return Imageset.createGeneric(this.get_dataSetType(), this.get_bandPass()); + } + }, + + equals: function (obj) { + if (obj == null) { + return false; + } + if (!(ss.canCast(obj, Imageset))) { + return false; + } + var b = obj; + return (Util.getHashCode(b.get_url()) === Util.getHashCode(this.get_url()) && b.get_dataSetType() === this.get_dataSetType() && b.get_bandPass() === this.get_bandPass() && b.get_generic() === this.get_generic()); + }, + + get_matrix: function () { + if (!this._matrixComputed) { + this._computeMatrix(); + } + return this._matrix; + }, + + set_matrix: function (value) { + this._matrix = value; + return value; + }, + + _computeMatrix: function () { + this._matrixComputed = true; + this._matrix = Matrix3d.get_identity(); + this._matrix._multiply(Matrix3d._rotationX((this.get_rotation() / 180 * Math.PI))); + this._matrix._multiply(Matrix3d._rotationZ((this.get_centerY() / 180 * Math.PI))); + this._matrix._multiply(Matrix3d._rotationY(((360 - this.get_centerX()) / 180 * Math.PI))); + }, + + get_name: function () { + return this._name; + }, + + set_name: function (value) { + this._name = value; + return value; + }, + + get_sparse: function () { + return this._sparse; + }, + + set_sparse: function (value) { + this._sparse = value; + return value; + }, + + get_thumbnailUrl: function () { + return this._thumbnailUrl; + }, + + set_thumbnailUrl: function (value) { + this._thumbnailUrl = value; + return value; + }, + + get_generic: function () { + return this._generic; + }, + + set_generic: function (value) { + this._generic = value; + return value; + }, + + get_elevationModel: function () { + return this._elevationModel; + }, + + set_elevationModel: function (value) { + this._elevationModel = value; + return value; + }, + + get_defaultSet: function () { + return this._defaultSet; + }, + + set_defaultSet: function (value) { + this._defaultSet = value; + return value; + }, + + get_offsetX: function () { + return this._offsetX; + }, + + set_offsetX: function (value) { + this._offsetX = value; + return value; + }, + + get_offsetY: function () { + return this._offsetY; + }, + + set_offsetY: function (value) { + this._offsetY = value; + return value; + }, + + get_creditsText: function () { + return this._creditsText; + }, + + set_creditsText: function (value) { + this._creditsText = value; + return value; + }, + + get_creditsUrl: function () { + return this._creditsUrl; + }, + + set_creditsUrl: function (value) { + this._creditsUrl = value; + return value; + }, + + get_isMandelbrot: function () { + return false; + }, + + // Calculate either the X or Y coordinate of the estimated image center. + // + // This estimate has some important limitations. First, because images + // might contain transparent regions, the "center" of the image that a + // user will perceive might have nothing to do with the center of the + // image bitmap. For instance, imagine that the bitmap is 100x100 but + // that everything is transparent except for 10x10 pixels in the + // top-left corner. We don't know anything about the "barycenter" of the + // image here, so we can't account for that. + // + // Second, for untiled SkyImage imagesets, to properly compute the + // bitmap center we need its dimensions, which simply aren't available + // here. All we can do is guess a "reasonable" image size. + // + // For these reasons, this method should be avoided when possible. The + // preferred way to "know" the location of an image's center is to wrap + // the image in a Place object, which can just specify the exact + // coordinates and zoom level too. + // + // Even disregarding the above, it's non-trivial to locate the image + // center because of the OffsetX/Y parameters and potential rotation of + // the image's coordinate system relative to the sky. + _calcViewCenterCoordinate: function (isX) { + var rot = Coordinates.degreesToRadians(this._rotation); + var crot = Math.cos(rot); + var srot = Math.sin(rot); + var dx = 0, dy = 0; + if (this.get_levels() > 0) { + dx = -this._offsetX; + dy = this._offsetY; + } else { + // This is the part where we need the image's dimensions to + // be able to compute the center coordinate correctly. Since + // we don't have that information, we just guess :-( + var effWidth = 800; + var effHeight = 800; + dx = (this._offsetX - effWidth / 2) * this._baseTileDegrees; + dy = (effHeight / 2 - this._offsetY) * this._baseTileDegrees; + } + if (this._bottomsUp) { + dx = -dx; + } + if (isX) { + return this._centerX + dx * crot + dy * srot; + } else { + return this._centerY - dx * srot + dy * crot; + } + }, + + get_viewCenterX: function () { + if (this.get_wcsImage() != null) { + return (this.get_wcsImage()).get_viewCenterX(); + } else { + return this._calcViewCenterCoordinate(true); + } + }, + + get_viewCenterY: function () { + if (this.get_wcsImage() != null) { + return (this.get_wcsImage()).get_viewCenterY(); + } else { + return this._calcViewCenterCoordinate(false); + } + }, + + setInitialParameters: function (name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame) { + this.set_referenceFrame(referenceFrame); + this.set_meanRadius(meanRadius); + this._altUrl = alturl; + this.demUrl = demUrlIn; + this._creditsText = credits; + this._creditsUrl = creditsUrl; + this._offsetY = offsetY; + this._offsetX = offsetX; + this._widthFactor = wf; + this._elevationModel = elevationModel; + this._defaultSet = defaultSet; + this._name = name; + this._sparse = sparse; + this._dataSetType = dataSetType; + this._bandPass = bandPass; + this._quadTreeTileMap = quadTreeMap; + this.url = url; + this._levels = levels; + this._baseTileDegrees = baseTileDegrees; + this._imageSetID = imageSetID; + this._extension = extension; + this._projection = projection; + this._bottomsUp = bottomsUp; + this._baseLevel = baseLevel; + this._mercator = (!projection); + this._centerX = centerX; + this._centerY = centerY; + this._rotation = rotation; + this._thumbnailUrl = thumbnailUrl; + this._computeMatrix(); + }, + + // Ideally, imagesets will be associated with Places that specify + // exactly how the view should be set up when "going to" them, but + // sometimes (especially research datasets) we're interested in deriving + // a reasonable zoom setting without that extra information. The returned value + // isn't going to be perfect but it should hopefully be OK. + _guessZoomSetting: function (currentZoom) { + const FOV_FACTOR = 1.7; + var zoom = currentZoom; + var aswcs = ss.safeCast(this._wcsImage, FitsImage); + if (this.get_projection() === ProjectionType.skyImage) { + // Untiled SkyImage: basetiledegrees is degrees per pixel + if (aswcs != null) { + zoom = this.get_baseTileDegrees() * aswcs.get_sizeY() * 6 * FOV_FACTOR; + } + } else if (aswcs != null) { + zoom = aswcs.get_scaleY() * aswcs.get_sizeY() * 6 * FOV_FACTOR; + } else { + // Tiled. basetiledegrees is angular height of whole image after + // power-of-2 padding. + zoom = this.get_baseTileDegrees() * 6 * FOV_FACTOR; + } + + // Only zoom in, not out. Usability-wise this tends to make the most + // sense. + if (zoom > currentZoom) { + zoom = currentZoom; + } + return zoom; + }, + + // URL parameters + //{0} ImageSetID + //{1} level + //{2} x tile id + //{3} y tile id + //{4} quadtree address (VE style) + //{5} quadtree address (Google maps style) + //{6} top left corner RA + //{7} top left corner Dec + //{8} bottom right corner RA + //{9} bottom right corner dec + //{10} bottom left corner RA + //{11} bottom left corner dec + //{12} top right corner RA + //{13} top right corner dec + + get_thumbnail: function () { + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + return value; + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_isImage: function () { + return true; + }, + + get_isTour: function () { + return false; + }, + + get_isFolder: function () { + return false; + }, + + get_isCloudCommunityItem: function () { + return false; + }, + + get_readOnly: function () { + return false; + }, + + get_children: function () { + return []; + } +}; + +registerType("Imageset", [Imageset, Imageset$, null, IThumbnail]); diff --git a/engine/esm/index.js b/engine/esm/index.js new file mode 100644 index 00000000..8c6127d1 --- /dev/null +++ b/engine/esm/index.js @@ -0,0 +1,408 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The toplevel WorldWide Telescope WebGL engine API module. +// +// To maintain compatibility with a *lot* of legacy code, we export way more +// types and interfaces than we would if we were starting from scratch, often +// with confusing or misspelled names. So it goes. +// +// The import/exports here are in rough dependency order throughout the +// codebase, although there are numerous places where circular references sneak +// in. + +export { ss } from "./ss.js"; + +export { Util } from "./baseutil.js"; + +export { CalD, DAY_OF_WEEK, DT } from "./astrocalc/date.js"; +export { COR, C3D, CT } from "./astrocalc/coordinate_transformation.js"; +export { ASEP } from "./astrocalc/angular_separation.js"; +export { CAAEarth, VSC, } from "./astrocalc/earth.js"; +export { CAAFK5 } from "./astrocalc/fk5.js"; +export { NUC, CAANutation } from "./astrocalc/nutation.js"; +export { CAASun } from "./astrocalc/sun.js"; +export { CAAMercury } from "./astrocalc/mercury.js"; +export { CAAVenus } from "./astrocalc/venus.js"; +export { CAAMars } from "./astrocalc/mars.js"; +export { CAAJupiter } from "./astrocalc/jupiter.js"; +export { CAASaturn } from "./astrocalc/saturn.js"; +export { CAAUranus } from "./astrocalc/uranus.js"; +export { CAANeptune } from "./astrocalc/neptune.js"; +export { CAAPluto, PlutoCoefficient1, PlutoCoefficient2 } from "./astrocalc/pluto.js"; +export { CAAKepler } from "./astrocalc/kepler.js"; +export { ABR, ACFT } from "./astrocalc/aberration.js"; +export { DYT } from "./astrocalc/dynamical_time.js"; +export { CAAEclipticalElementDetails, CAAEclipticalElements } from "./astrocalc/ecliptical_elements.js"; +export { EPO } from "./astrocalc/elements_planetary_orbit.js"; +export { EOE, EPD, EOD, EO, ELL } from "./astrocalc/elliptical.js"; +export { EOT } from "./astrocalc/equation_of_time.js"; +export { GMD, GMDS, GM } from "./astrocalc/galilean_moons.js"; +export { CAAGlobe } from "./astrocalc/globe.js"; +export { IFR } from "./astrocalc/illuminated_fraction.js"; +export { INTP } from "./astrocalc/interpolate.js"; +export { CAAMoon, MoonCoefficient1, MoonCoefficient2 } from "./astrocalc/moon.js"; +export { MIFR } from "./astrocalc/moon_illuminated_fraction.js"; +export { CAAMoonNodes } from "./astrocalc/moon_nodes.js"; +export { CAAMoonPerigeeApogee, MPAC } from "./astrocalc/moon_perigee_apogee.js"; +export { CAAMoonPhases } from "./astrocalc/moon_phases.js"; +export { CAAParallax, CAATopocentricEclipticDetails } from "./astrocalc/parallax.js"; +export { CAASidereal } from "./astrocalc/sidereal.js"; +export { CAAPhysicalJupiterDetails, CAAPhysicalJupiter } from "./astrocalc/physical_jupiter.js"; +export { CAAPhysicalMarsDetails, CAAPhysicalMars } from "./astrocalc/physical_mars.js"; +export { CAAPhysicalSunDetails, CAAPhysicalSun } from "./astrocalc/physical_sun.js"; +export { CAAPrecession } from "./astrocalc/precession.js"; +export { CAARiseTransitSetDetails, CAARiseTransitSet } from "./astrocalc/rise_transit_set.js"; +export { CAASaturnRingDetails, CAASaturnRings } from "./astrocalc/saturn_rings.js"; +export { CAAStellarMagnitudes } from "./astrocalc/stellar_magnitudes.js"; + +export { BlendState } from "./blend_state.js"; +export { Color, Colors } from "./color.js"; +export { URLHelpers, URLRewriteMode } from "./url_helpers.js"; + +export { + LocationHint, + PositionTexture, + PositionColoredTextured, + PositionColored, + PositionNormalTexturedTangent, + Vector3d, + Vector2d, + Matrix3d, + Matrix2d, + DoubleUtilities, + PlaneD, + Vector4d, + PositionNormalTexturedX2, + PositionNormalTextured, + SphereHull, + ConvexHull +} from "./double3d.js"; + +export { + Rectangle, + Guid, + Mouse, + Language, + Cursor, + Cursors, + Keys, + SelectLink, + PopupVolume, + PopupColorPicker, + OverlayProperties, + DialogResult, +} from "./util.js"; + +export { AstroRaDec, RiseSetDetails, AstroCalc } from "./astrocalc.js"; + +export { + ShortIndexBuffer, + IndexBuffer, + VertexBufferBase, + PositionVertexBuffer, + PositionNormalTexturedVertexBuffer, + PositionNormalTexturedTangentVertexBuffer, +} from "./graphics/gl_buffers.js" + +export { Texture } from "./graphics/texture.js"; +export { Tessellator } from "./graphics/tessellator.js"; + +export { + SimpleLineShader, + SimpleLineShader2D, + OrbitLineShader, + LineShaderNormalDates, + TimeSeriesPointSpriteShader, + KeplerPointSpriteShader, + EllipseShader, + ModelShader, + ModelShaderTan, + TileShader, + FitsShader, + ImageShader, + ImageShader2, + SpriteShader, + ShapeSpriteShader, + TextShader, +} from "./graphics/shaders.js"; + +export { + CullMode, + PointScaleTypes, + DataItem, + Dates, + SimpleLineList, + OrbitLineList, + LineList, + TriangleList, + TriangleFanList, + PointList, + TimeSeriesLineVertex, + TimeSeriesPointVertex, +} from "./graphics/primitives3d.js"; + +// These are new, post-C# APIs that we wouldn't normally expose, but they +// support the test suite. +export { + set_tilePrepDevice, + set_useGlVersion2 +} from "./render_globals.js"; + +export { Bitmap } from "./utilities/bitmap.js"; + +export { + ContextMenuStrip, + ToolStripMenuItem, + ToolStripSeparator, + TagMe, +} from "./utilities/context_menu_strip.js"; + +export { BinaryReader } from "./utilities/binary_reader.js"; +export { SimpleInput } from "./utilities/simple_input.js"; +export { XmlTextWriter, Formatting } from "./utilities/xml_text_writer.js"; + +export { Coordinates } from "./coordinates.js"; +export { FastMath } from "./fast_math.js"; +export { HealpixTables } from "./healpix_tables.js"; +export { HealpixUtils } from "./healpix_utils.js"; +export { Hploc } from "./hploc.js"; +export { Fxyf } from "./fxyf.js"; +export { + IThumbnail, + IPlace, + IUiController, + IViewMover, + IUIServicesCallbacks, + ISettings, + IUndoStep, +} from "./interfaces.js"; +export { Annotation, Circle, Poly, PolyLine } from "./annotation.js"; +export { SolarSystemObjects, InterpolationType, CameraParameters } from "./camera_parameters.js"; +export { ConstellationFilter } from "./constellation_filter.js"; +export { FitsProperties, ScaleTypes } from "./fits_properties.js"; +export { Star, Galaxy } from "./star.js"; +export { UiTools } from "./ui_tools.js"; +export { StateType, WebFile } from "./web_file.js"; + +export { ColorMapContainer } from "./layers/color_map_container.js"; +export { WcsImage } from "./layers/wcs_image.js"; +export { FitsImage } from "./layers/fits_image.js"; +export { + DataTypes, + ScaleMap, + ScaleLinear, + ScaleLog, + ScalePow, + ScaleSqrt, + HistogramEqualization, + FitsImageJs, +} from "./layers/fits_image_js.js"; +export { FitsImageTile } from "./layers/fits_image_tile.js"; + +export { Tile } from "./tile.js"; +export { RenderTriangle } from "./render_triangle.js"; +export { EquirectangularTile } from "./equirectangular_tile.js"; +export { HealpixTile, Xyf } from "./healpix_tile.js"; +export { MercatorTile } from "./mercator_tile.js"; +export { PlotTile } from "./plot_tile.js"; +export { LatLngEdges, TangentTile } from "./tangent_tile.js"; +export { SkyImageTile } from "./sky_image_tile.js"; +export { ToastTile } from "./toast_tile.js"; +export { ProjectionType, ImageSetType, BandPass, Imageset } from "./imageset.js"; +export { Settings, SettingParameter, StockSkyOverlayTypes } from "./settings.js"; +export { TextBorderStyle, TextObject } from "./tours/text_object.js"; +export { Alignment, Text3dBatch, Text3d, GlyphItem, GlyphCache } from "./sky_text.js"; +export { PointType, Lineset, Linepoint, Constellations } from "./constellations.js"; +export { SpaceTimeController } from "./space_time_controller.js"; +export { KeplerianElements, BodyAngles, Planets } from "./planets.js"; +export { Place, Classification } from "./place.js"; +export { FolderUp } from "./folder_up.js"; +export { Grids } from "./grids.js"; +export { KeplerVertex } from "./kepler_vertex.js"; +export { Pointing } from "./pointing.js"; +export { Tour } from "./tour.js"; +export { VideoOutputType } from "./video_output_type.js"; +export { ViewMoverKenBurnsStyle } from "./view_mover.js"; +export { VizLayer } from "./viz_layer.js"; +export { ColorPicker } from "./utilities/color_picker.js"; +export { Dialog } from "./utilities/dialog.js"; +export { Histogram } from "./utilities/histogram.js"; + +export { Layer, DomainValue, AltUnits, FadeType } from "./layers/layer.js"; +export { + LayerUI, + LayerUIMenuItem, + LayerUITreeNode, +} from "./layers/layer_ui.js"; + +// To keep API compatibility, we can't fix this typo. +export { GreatCirlceRouteLayer } from "./layers/great_circle_route_layer.js"; + +export { GridLayer } from "./layers/grid_layer.js"; +export { ImageSetLayer } from "./layers/imageset_layer.js"; +export { + Group, + Material, + Mesh, + Object3d, + ObjectNode, + Object3dLayer, + Object3dLayerUI, +} from "./layers/object3d.js"; +export { Orbit, EllipseRenderer } from "./layers/orbit.js"; +export { ReferenceFrame, ReferenceFrameTypes } from "./layers/reference_frame.js"; +export { OrbitLayer, OrbitLayerUI } from "./layers/orbit_layer.js"; +export { Table } from "./layers/table.js"; +export { Primitives, VoTable, VoRow, VoColumn } from "./layers/vo_table.js"; + +export { FileEntry, FileCabinet } from "./tours/file_cabinet.js"; +export { + OverlayAnchor, + AudioType, + ShapeType, + LoopTypes, + Overlay, + AudioOverlay, + BitmapOverlay, + FlipbookOverlay, + ShapeOverlay, + TextOverlay, +} from "./tours/overlay.js"; +export { Selection, SelectionAnchor } from "./tours/selection.js"; +export { + TransitionType, + TourStop, + LayerInfo, + UndoTourStopChange, +} from "./tours/tour_stop.js"; +export { + Undo, + UndoStep, + UndoTourSlidelistChange, + UndoTourPropertiesChange, +} from "./tours/undo.js"; +export { + TourEditor, + OverlayList, + TourEdit, + SoundEditor, + TourStopList, + TimeLine, +} from "./tours/tour_editor.js"; +export { TourPlayer, MasterTime } from "./tours/tour_player.js"; + +export { ISSLayer } from "./layers/iss_layer.js"; +export { + CoordinatesTypes, + AltTypes, + MarkerMixes, + ColorMaps, + PlotTypes, + MarkerScales, + RAUnits, + TimeSeriesLayer, +} from "./layers/time_series_layer.js"; +export { + KmlCoordinate, + KmlLineList, + PushPin, + SpreadSheetLayer, + CatalogSpreadSheetLayer, +} from "./layers/spreadsheet_layer.js"; +export { VoTableLayer } from "./layers/vo_table_layer.js"; +export { + ReferenceFrames, + LayerManager, + LayerMap, + SkyOverlays, + GroundOverlayLayer, + FrameTarget, +} from "./layers/layer_manager.js"; + +// When we import this module, we install the `Layer.fromXml()` function, which +// depends on the specific layer types established above. I am probably being +// too conservative about circular module dependencies but there are worse ways +// to be. +import { layerFromXml as _ } from "./layers/from_xml.js"; + +// And when we import *this* module, we also attach some instances to the +// LayerManager class. I'm not sure if they're even used in the webclient, which +// would be the only place that reasonably would. +export { + FrameWizard, + ReferenceFrameProps, + GreatCircleDialog, + DataVizWizard, +} from "./layers/manager_dialogs.js"; + +export { UserLevel, TourDocument } from "./tours/tour_document.js"; +export { TourEditTab } from "./tours/tour_edit.js"; + +export { + FolderGroup, + FolderRefreshType, + FolderType, + Folder, +} from "./folder.js"; +export { FolderBrowser, ThumbnailSize } from "./folder_browser.js"; +export { HipsProperties } from "./hips_properties.js"; +export { InViewReturnMessage, RenderContext } from "./render_context.js"; +export { + SlideChangedEventArgs, + ArrivedEventArgs, + AnnotationClickEventArgs, + CollectionLoadedEventArgs, + ScriptInterface, +} from "./script_interface.js"; + +export { + WWTControl, + WWTControlBuilder, + WWTElementEvent, +} from "./wwt_control.js"; + +export { + FolderDownloadAction, + Wtml, +} from "./wtml.js"; + + +// GFX +// +// This was a global holder for constants used in the AstroCalc component. We've +// moved those constants into their specific modules, but still expose the name +// just in case someone actually referenced it. Since we've removed all of the +// constants that it contains, though, if someone was reckless enough to try to +// use this variable their usage would almost surely be broken by now. + +import { registerType } from "./typesystem.js"; + +export function GFX() { } + +registerType("GFX", [GFX, null, null]); + + +// Nontrivial initializations. + +import { ss } from "./ss.js"; +import { set_globalRenderContext } from "./render_globals.js"; +import { set_globalWWTControl } from "./data_globals.js"; +import { KeplerVertex } from "./kepler_vertex.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { Folder } from "./folder.js"; +import { RenderContext } from "./render_context.js"; +import { WWTControl } from "./wwt_control.js"; + +WWTControl.exploreRoot = new Folder(); +WWTControl.singleton = new WWTControl(); +WWTControl.singleton.renderContext = new RenderContext(); +set_globalWWTControl(WWTControl.singleton); +set_globalRenderContext(WWTControl.singleton.renderContext); + +SpaceTimeController._metaNow = ss.now(); +SpaceTimeController._now = ss.now(); +SpaceTimeController.last = SpaceTimeController.get_metaNow(); +SpaceTimeController.updateClock(); + +KeplerVertex.baseDate = ss.truncate(SpaceTimeController.utcToJulian(ss.now())); diff --git a/engine/esm/interfaces.js b/engine/esm/interfaces.js new file mode 100644 index 00000000..d20de1f4 --- /dev/null +++ b/engine/esm/interfaces.js @@ -0,0 +1,74 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// "Classes" corresponding to C# interfaces +// +// In our current JS translation, these classes don't declare anything +// themselves. They can in principle be used in `canCast()` calls for dynamic +// type checking, but it appears that we don't use this functionality in the +// current codebase. +// +// If/when we translate to TypeScript, these could become TypeScript interfaces +// that are more useful. +// +// Files in this module used to be in +// `I{Folder,IThumbnail,Place,UIController,ViewMover,Tours/ISettings}.cs`. Note +// that the source file was indeed (incorrectly) named `IIThumbnail.cs`. + +import { registerType } from "./typesystem.js"; + + +// wwtlib.IFolder + +export function IFolder() { } + +registerType("IFolder", [IFolder]); + + +// wwtlib.IThumbnail + +export function IThumbnail() { } + +registerType("IThumbnail", [IThumbnail]); + + +// wwtlib.IPlace + +export function IPlace() { } + +registerType("IPlace", [IPlace]); + + +// wwtlib.IUiController + +export function IUiController() { } + +registerType("IUiController", [IUiController]); + + +// wwtlib.IViewMover + +export function IViewMover() { } + +registerType("IViewMover", [IViewMover]); + + +// wwtlib.IUIServicesCallbacks + +export function IUIServicesCallbacks() { } + +registerType("IUIServicesCallbacks", [IUIServicesCallbacks]); + + +// wwtlib.ISettings + +export function ISettings() { } + +registerType("ISettings", [ISettings]); + + +// wwtlib.IUndoStep + +export function IUndoStep() { } + +registerType("IUndoStep", [IUndoStep]); diff --git a/engine/esm/kepler_vertex.js b/engine/esm/kepler_vertex.js new file mode 100644 index 00000000..95e69f69 --- /dev/null +++ b/engine/esm/kepler_vertex.js @@ -0,0 +1,85 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Kepler Vertex. + +import { registerType } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { Colors } from "./color.js"; + + +// wwtlib.KeplerVertex + +export function KeplerVertex() { + this.ABC = new Vector3d(); + this.abc1 = new Vector3d(); + this.pointSize = 0; + this.w = 0; + this.e = 0; + this.n = 0; + this.t = 0; + this.a = 0; + this.z = 0; + this.orbitPos = 0; + this.orbits = 0; +} + +KeplerVertex._sine = 0; +KeplerVertex._cose = 1; +KeplerVertex._degrad = Math.PI / 180; + +var KeplerVertex$ = { + fill: function (ee) { + var F = Math.cos(ee.omega * KeplerVertex._degrad); + var sinOmega = Math.sin(ee.omega * KeplerVertex._degrad); + var cosi = Math.cos(ee.i * KeplerVertex._degrad); + var sini = Math.sin(ee.i * KeplerVertex._degrad); + var G = sinOmega * KeplerVertex._cose; + var H = sinOmega * KeplerVertex._sine; + var P = -sinOmega * cosi; + var Q = (F * cosi * KeplerVertex._cose) - (sini * KeplerVertex._sine); + var R = (F * cosi * KeplerVertex._sine) + (sini * KeplerVertex._cose); + var checkA = (F * F) + (G * G) + (H * H); // Should be 1.0 + var checkB = (P * P) + (Q * Q) + (R * R); // Should be 1.0 as well + this.ABC.x = Math.atan2(F, P); + this.ABC.y = Math.atan2(G, Q); + this.ABC.z = Math.atan2(H, R); + this.abc1.x = Math.sqrt((F * F) + (P * P)); + this.abc1.y = Math.sqrt((G * G) + (Q * Q)); + this.abc1.z = Math.sqrt((H * H) + (R * R)); + this.pointSize = 0.1; + if (ee.a < 2.5) { + this.color = Colors.get_white(); + } else if (ee.a < 2.83) { + this.color = Colors.get_red(); + } else if (ee.a < 2.96) { + this.color = Colors.get_green(); + } else if (ee.a < 3.3) { + this.color = Colors.get_magenta(); + } else if (ee.a < 5) { + this.color = Colors.get_cyan(); + } else if (ee.a < 10) { + this.color = Colors.get_yellow(); + this.pointSize = 0.9; + } else { + this.color = Colors.get_white(); + this.pointSize = 8; + } + this.w = ee.w; + this.e = ee.e; + if (!ee.n) { + this.n = (0.9856076686 / (ee.a * Math.sqrt(ee.a))); + } else { + this.n = ee.n; + } + this.t = (ee.t - KeplerVertex.baseDate); + this.a = ee.a; + this.z = 0; + this.orbitPos = 0; + this.orbits = 0; + } +}; + +registerType("KeplerVertex", [KeplerVertex, KeplerVertex$, null]); + +// KeplerVertex.baseDate is initialized at the bottom of the main module. diff --git a/engine/esm/layers/color_map_container.js b/engine/esm/layers/color_map_container.js new file mode 100644 index 00000000..77b82bf5 --- /dev/null +++ b/engine/esm/layers/color_map_container.js @@ -0,0 +1,638 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A collection of named colormaps. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Color } from "../color.js"; +import { WEBGL } from "../graphics/webgl_constants.js"; + + +// wwtlib.ColorMapContainer +// +// This class is intended to be used to store colormaps. It does not handle any +// interpolation and when using FindClosestColor it will simply check which +// color is closest to the requested value. Therefore, continuous colormaps should +// be created by providing a sufficient number of colors (ideally 256 or more). + +export function ColorMapContainer() { + this.colors = []; +} + +ColorMapContainer.colorTextures = {}; + +// Class method to create a new colormap from a list of [a, r, g, b] lists. +ColorMapContainer.fromArgbList = function (color_list) { + var temp = new ColorMapContainer(); + var $enum1 = ss.enumerate(color_list); + while ($enum1.moveNext()) { + var color = $enum1.current; + temp.colors.push(Color.fromArgb(color[0], color[1], color[2], color[3])); + } + return temp; +}; + +// Class method to create a new colormap from a list of strings. +ColorMapContainer.fromStringList = function (color_list) { + var temp = new ColorMapContainer(); + var $enum1 = ss.enumerate(color_list); + while ($enum1.moveNext()) { + var color = $enum1.current; + temp.colors.push(Color.load(color)); + } + return temp; +}; + +// Names are chosen to match matplotlib (which explains why some are +// less-than-ideal). +ColorMapContainer.fromNamedColormap = function (name) { + if (name == null) { + return null; + } + switch (name.toLowerCase()) { + case 'viridis': + return ColorMapContainer.viridis; + case 'plasma': + return ColorMapContainer.plasma; + case 'inferno': + return ColorMapContainer.inferno; + case 'magma': + return ColorMapContainer.magma; + case 'cividis': + return ColorMapContainer.cividis; + case 'greys': // this is 0=>white, 1=>black + return ColorMapContainer.greys; + case 'gray': // this is 0=>black, 1=>white + return ColorMapContainer.gray; + case 'purples': + return ColorMapContainer.purples; + case 'blues': + return ColorMapContainer.blues; + case 'greens': + return ColorMapContainer.greens; + case 'oranges': + return ColorMapContainer.oranges; + case 'reds': + return ColorMapContainer.reds; + case 'rdylbu': + return ColorMapContainer.rdYlBu; + } + return null; +}; + +ColorMapContainer._getTextureFromName = function (gl, name) { + var texture = ColorMapContainer.colorTextures[name]; + if (texture == null) { + var colorMapContainer = ColorMapContainer.fromNamedColormap(name); + if (colorMapContainer != null) { + texture = ColorMapContainer._initColorTexture(gl, colorMapContainer); + ColorMapContainer.colorTextures[name.toLowerCase()] = texture; + } + } + return texture; +}; + +ColorMapContainer.bindColorMapTexture = function (gl, colorMapName) { + var texture = ColorMapContainer._getTextureFromName(gl, colorMapName); + if (texture == null) { + texture = ColorMapContainer._getTextureFromName(gl, 'gray'); + } + gl.activeTexture(WEBGL.TEXTURE1); + gl.bindTexture(WEBGL.TEXTURE_2D, texture); +}; + +ColorMapContainer._initColorTexture = function (gl, colorMapContainer) { + var colorTexture = gl.createTexture(); + gl.activeTexture(WEBGL.TEXTURE1); + gl.bindTexture(WEBGL.TEXTURE_2D, colorTexture); + gl.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_S, WEBGL.CLAMP_TO_EDGE); + gl.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_T, WEBGL.CLAMP_TO_EDGE); + var colorBuffer = ColorMapContainer._extractColorArray(colorMapContainer.colors); + gl.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGB8, colorBuffer.length / 3, 1, 0, WEBGL.RGB, WEBGL.UNSIGNED_BYTE, colorBuffer); + gl.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.NEAREST); + gl.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MAG_FILTER, WEBGL.NEAREST); + return colorTexture; +}; + +ColorMapContainer._extractColorArray = function (colors) { + var index = 0; + var colorBuffer = new Uint8Array(colors.length * 3); + var $enum1 = ss.enumerate(colors); + while ($enum1.moveNext()) { + var color = $enum1.current; + colorBuffer[index++] = color.r; + colorBuffer[index++] = color.g; + colorBuffer[index++] = color.b; + } + return colorBuffer; +}; + +var ColorMapContainer$ = { + // Given a floating-point value in the range 0 to 1, find the color that is + // the closest to it. + findClosestColor: function (value) { + var index; + if (value <= 0) { + return this.colors[0]; + } else if (value >= 1) { + return this.colors[this.colors.length - 1]; + } else { + index = ss.truncate((value * this.colors.length)); + return this.colors[index]; + } + } +}; + +registerType("ColorMapContainer", [ColorMapContainer, ColorMapContainer$, null]); + +// The colormaps below were produced using the following Python code: +// +// import numpy as np +// from matplotlib import cm +// from matplotlib.colors import to_hex +// from textwrap import wrap, indent +// +// TEMPLATE = """ +// public static ColorMapContainer {name} = ColorMapContainer.FromStringList(new List( +// {colors} +// )); +// """ +// +// TEMPLATE_CASE = """ +// case "{name_lower}": +// return {name};""" +// COLORMAPS = ["viridis", "plasma", "inferno", "magma", "cividis", +// "Greys", "gray", "Purples", "Blues", "Greens", "Oranges", "Reds", "RdYlBu"] +// +// named_code = "" +// case_code = "" +// +// for name in COLORMAPS: +// cmap = cm.get_cmap(name) +// x = np.linspace(0.5 / 256, 255.5/256, 256) +// colors = ", ".join(['"{0}"'.format(to_hex(c)) for c in cmap(x)]) +// pretty_name = name[0].upper() + name[1:] +// named_code += TEMPLATE.format(name=pretty_name, colors=indent('\n'.join(wrap(colors, 90)), " " * 10)) +// case_code += TEMPLATE_CASE.format(name=pretty_name, name_lower=name.lower()) +// +// named_code = indent(named_code, " " * 8) +// +// print(named_code) +// print('-' * 72) +// print(case_code) + +ColorMapContainer.viridis = ColorMapContainer.fromStringList([ + '#440154', '#440256', '#450457', '#450559', '#46075a', '#46085c', '#460a5d', '#460b5e', + '#470d60', '#470e61', '#471063', '#471164', '#471365', '#481467', '#481668', '#481769', + '#48186a', '#481a6c', '#481b6d', '#481c6e', '#481d6f', '#481f70', '#482071', '#482173', + '#482374', '#482475', '#482576', '#482677', '#482878', '#482979', '#472a7a', '#472c7a', + '#472d7b', '#472e7c', '#472f7d', '#46307e', '#46327e', '#46337f', '#463480', '#453581', + '#453781', '#453882', '#443983', '#443a83', '#443b84', '#433d84', '#433e85', '#423f85', + '#424086', '#424186', '#414287', '#414487', '#404588', '#404688', '#3f4788', '#3f4889', + '#3e4989', '#3e4a89', '#3e4c8a', '#3d4d8a', '#3d4e8a', '#3c4f8a', '#3c508b', '#3b518b', + '#3b528b', '#3a538b', '#3a548c', '#39558c', '#39568c', '#38588c', '#38598c', '#375a8c', + '#375b8d', '#365c8d', '#365d8d', '#355e8d', '#355f8d', '#34608d', '#34618d', '#33628d', + '#33638d', '#32648e', '#32658e', '#31668e', '#31678e', '#31688e', '#30698e', '#306a8e', + '#2f6b8e', '#2f6c8e', '#2e6d8e', '#2e6e8e', '#2e6f8e', '#2d708e', '#2d718e', '#2c718e', + '#2c728e', '#2c738e', '#2b748e', '#2b758e', '#2a768e', '#2a778e', '#2a788e', '#29798e', + '#297a8e', '#297b8e', '#287c8e', '#287d8e', '#277e8e', '#277f8e', '#27808e', '#26818e', + '#26828e', '#26828e', '#25838e', '#25848e', '#25858e', '#24868e', '#24878e', '#23888e', + '#23898e', '#238a8d', '#228b8d', '#228c8d', '#228d8d', '#218e8d', '#218f8d', '#21908d', + '#21918c', '#20928c', '#20928c', '#20938c', '#1f948c', '#1f958b', '#1f968b', '#1f978b', + '#1f988b', '#1f998a', '#1f9a8a', '#1e9b8a', '#1e9c89', '#1e9d89', '#1f9e89', '#1f9f88', + '#1fa088', '#1fa188', '#1fa187', '#1fa287', '#20a386', '#20a486', '#21a585', '#21a685', + '#22a785', '#22a884', '#23a983', '#24aa83', '#25ab82', '#25ac82', '#26ad81', '#27ad81', + '#28ae80', '#29af7f', '#2ab07f', '#2cb17e', '#2db27d', '#2eb37c', '#2fb47c', '#31b57b', + '#32b67a', '#34b679', '#35b779', '#37b878', '#38b977', '#3aba76', '#3bbb75', '#3dbc74', + '#3fbc73', '#40bd72', '#42be71', '#44bf70', '#46c06f', '#48c16e', '#4ac16d', '#4cc26c', + '#4ec36b', '#50c46a', '#52c569', '#54c568', '#56c667', '#58c765', '#5ac864', '#5cc863', + '#5ec962', '#60ca60', '#63cb5f', '#65cb5e', '#67cc5c', '#69cd5b', '#6ccd5a', '#6ece58', + '#70cf57', '#73d056', '#75d054', '#77d153', '#7ad151', '#7cd250', '#7fd34e', '#81d34d', + '#84d44b', '#86d549', '#89d548', '#8bd646', '#8ed645', '#90d743', '#93d741', '#95d840', + '#98d83e', '#9bd93c', '#9dd93b', '#a0da39', '#a2da37', '#a5db36', '#a8db34', '#aadc32', + '#addc30', '#b0dd2f', '#b2dd2d', '#b5de2b', '#b8de29', '#bade28', '#bddf26', '#c0df25', + '#c2df23', '#c5e021', '#c8e020', '#cae11f', '#cde11d', '#d0e11c', '#d2e21b', '#d5e21a', + '#d8e219', '#dae319', '#dde318', '#dfe318', '#e2e418', '#e5e419', '#e7e419', '#eae51a', + '#ece51b', '#efe51c', '#f1e51d', '#f4e61e', '#f6e620', '#f8e621', '#fbe723', '#fde725' +]); + +ColorMapContainer.plasma = ColorMapContainer.fromStringList([ + '#0d0887', '#100788', '#130789', '#16078a', '#19068c', '#1b068d', '#1d068e', '#20068f', + '#220690', '#240691', '#260591', '#280592', '#2a0593', '#2c0594', '#2e0595', '#2f0596', + '#310597', '#330597', '#350498', '#370499', '#38049a', '#3a049a', '#3c049b', '#3e049c', + '#3f049c', '#41049d', '#43039e', '#44039e', '#46039f', '#48039f', '#4903a0', '#4b03a1', + '#4c02a1', '#4e02a2', '#5002a2', '#5102a3', '#5302a3', '#5502a4', '#5601a4', '#5801a4', + '#5901a5', '#5b01a5', '#5c01a6', '#5e01a6', '#6001a6', '#6100a7', '#6300a7', '#6400a7', + '#6600a7', '#6700a8', '#6900a8', '#6a00a8', '#6c00a8', '#6e00a8', '#6f00a8', '#7100a8', + '#7201a8', '#7401a8', '#7501a8', '#7701a8', '#7801a8', '#7a02a8', '#7b02a8', '#7d03a8', + '#7e03a8', '#8004a8', '#8104a7', '#8305a7', '#8405a7', '#8606a6', '#8707a6', '#8808a6', + '#8a09a5', '#8b0aa5', '#8d0ba5', '#8e0ca4', '#8f0da4', '#910ea3', '#920fa3', '#9410a2', + '#9511a1', '#9613a1', '#9814a0', '#99159f', '#9a169f', '#9c179e', '#9d189d', '#9e199d', + '#a01a9c', '#a11b9b', '#a21d9a', '#a31e9a', '#a51f99', '#a62098', '#a72197', '#a82296', + '#aa2395', '#ab2494', '#ac2694', '#ad2793', '#ae2892', '#b02991', '#b12a90', '#b22b8f', + '#b32c8e', '#b42e8d', '#b52f8c', '#b6308b', '#b7318a', '#b83289', '#ba3388', '#bb3488', + '#bc3587', '#bd3786', '#be3885', '#bf3984', '#c03a83', '#c13b82', '#c23c81', '#c33d80', + '#c43e7f', '#c5407e', '#c6417d', '#c7427c', '#c8437b', '#c9447a', '#ca457a', '#cb4679', + '#cc4778', '#cc4977', '#cd4a76', '#ce4b75', '#cf4c74', '#d04d73', '#d14e72', '#d24f71', + '#d35171', '#d45270', '#d5536f', '#d5546e', '#d6556d', '#d7566c', '#d8576b', '#d9586a', + '#da5a6a', '#da5b69', '#db5c68', '#dc5d67', '#dd5e66', '#de5f65', '#de6164', '#df6263', + '#e06363', '#e16462', '#e26561', '#e26660', '#e3685f', '#e4695e', '#e56a5d', '#e56b5d', + '#e66c5c', '#e76e5b', '#e76f5a', '#e87059', '#e97158', '#e97257', '#ea7457', '#eb7556', + '#eb7655', '#ec7754', '#ed7953', '#ed7a52', '#ee7b51', '#ef7c51', '#ef7e50', '#f07f4f', + '#f0804e', '#f1814d', '#f1834c', '#f2844b', '#f3854b', '#f3874a', '#f48849', '#f48948', + '#f58b47', '#f58c46', '#f68d45', '#f68f44', '#f79044', '#f79143', '#f79342', '#f89441', + '#f89540', '#f9973f', '#f9983e', '#f99a3e', '#fa9b3d', '#fa9c3c', '#fa9e3b', '#fb9f3a', + '#fba139', '#fba238', '#fca338', '#fca537', '#fca636', '#fca835', '#fca934', '#fdab33', + '#fdac33', '#fdae32', '#fdaf31', '#fdb130', '#fdb22f', '#fdb42f', '#fdb52e', '#feb72d', + '#feb82c', '#feba2c', '#febb2b', '#febd2a', '#febe2a', '#fec029', '#fdc229', '#fdc328', + '#fdc527', '#fdc627', '#fdc827', '#fdca26', '#fdcb26', '#fccd25', '#fcce25', '#fcd025', + '#fcd225', '#fbd324', '#fbd524', '#fbd724', '#fad824', '#fada24', '#f9dc24', '#f9dd25', + '#f8df25', '#f8e125', '#f7e225', '#f7e425', '#f6e626', '#f6e826', '#f5e926', '#f5eb27', + '#f4ed27', '#f3ee27', '#f3f027', '#f2f227', '#f1f426', '#f1f525', '#f0f724', '#f0f921' +]); + +ColorMapContainer.inferno = ColorMapContainer.fromStringList([ + '#000004', '#010005', '#010106', '#010108', '#02010a', '#02020c', '#02020e', '#030210', + '#040312', '#040314', '#050417', '#060419', '#07051b', '#08051d', '#09061f', '#0a0722', + '#0b0724', '#0c0826', '#0d0829', '#0e092b', '#10092d', '#110a30', '#120a32', '#140b34', + '#150b37', '#160b39', '#180c3c', '#190c3e', '#1b0c41', '#1c0c43', '#1e0c45', '#1f0c48', + '#210c4a', '#230c4c', '#240c4f', '#260c51', '#280b53', '#290b55', '#2b0b57', '#2d0b59', + '#2f0a5b', '#310a5c', '#320a5e', '#340a5f', '#360961', '#380962', '#390963', '#3b0964', + '#3d0965', '#3e0966', '#400a67', '#420a68', '#440a68', '#450a69', '#470b6a', '#490b6a', + '#4a0c6b', '#4c0c6b', '#4d0d6c', '#4f0d6c', '#510e6c', '#520e6d', '#540f6d', '#550f6d', + '#57106e', '#59106e', '#5a116e', '#5c126e', '#5d126e', '#5f136e', '#61136e', '#62146e', + '#64156e', '#65156e', '#67166e', '#69166e', '#6a176e', '#6c186e', '#6d186e', '#6f196e', + '#71196e', '#721a6e', '#741a6e', '#751b6e', '#771c6d', '#781c6d', '#7a1d6d', '#7c1d6d', + '#7d1e6d', '#7f1e6c', '#801f6c', '#82206c', '#84206b', '#85216b', '#87216b', '#88226a', + '#8a226a', '#8c2369', '#8d2369', '#8f2469', '#902568', '#922568', '#932667', '#952667', + '#972766', '#982766', '#9a2865', '#9b2964', '#9d2964', '#9f2a63', '#a02a63', '#a22b62', + '#a32c61', '#a52c60', '#a62d60', '#a82e5f', '#a92e5e', '#ab2f5e', '#ad305d', '#ae305c', + '#b0315b', '#b1325a', '#b3325a', '#b43359', '#b63458', '#b73557', '#b93556', '#ba3655', + '#bc3754', '#bd3853', '#bf3952', '#c03a51', '#c13a50', '#c33b4f', '#c43c4e', '#c63d4d', + '#c73e4c', '#c83f4b', '#ca404a', '#cb4149', '#cc4248', '#ce4347', '#cf4446', '#d04545', + '#d24644', '#d34743', '#d44842', '#d54a41', '#d74b3f', '#d84c3e', '#d94d3d', '#da4e3c', + '#db503b', '#dd513a', '#de5238', '#df5337', '#e05536', '#e15635', '#e25734', '#e35933', + '#e45a31', '#e55c30', '#e65d2f', '#e75e2e', '#e8602d', '#e9612b', '#ea632a', '#eb6429', + '#eb6628', '#ec6726', '#ed6925', '#ee6a24', '#ef6c23', '#ef6e21', '#f06f20', '#f1711f', + '#f1731d', '#f2741c', '#f3761b', '#f37819', '#f47918', '#f57b17', '#f57d15', '#f67e14', + '#f68013', '#f78212', '#f78410', '#f8850f', '#f8870e', '#f8890c', '#f98b0b', '#f98c0a', + '#f98e09', '#fa9008', '#fa9207', '#fa9407', '#fb9606', '#fb9706', '#fb9906', '#fb9b06', + '#fb9d07', '#fc9f07', '#fca108', '#fca309', '#fca50a', '#fca60c', '#fca80d', '#fcaa0f', + '#fcac11', '#fcae12', '#fcb014', '#fcb216', '#fcb418', '#fbb61a', '#fbb81d', '#fbba1f', + '#fbbc21', '#fbbe23', '#fac026', '#fac228', '#fac42a', '#fac62d', '#f9c72f', '#f9c932', + '#f9cb35', '#f8cd37', '#f8cf3a', '#f7d13d', '#f7d340', '#f6d543', '#f6d746', '#f5d949', + '#f5db4c', '#f4dd4f', '#f4df53', '#f4e156', '#f3e35a', '#f3e55d', '#f2e661', '#f2e865', + '#f2ea69', '#f1ec6d', '#f1ed71', '#f1ef75', '#f1f179', '#f2f27d', '#f2f482', '#f3f586', + '#f3f68a', '#f4f88e', '#f5f992', '#f6fa96', '#f8fb9a', '#f9fc9d', '#fafda1', '#fcffa4' +]); + +ColorMapContainer.magma = ColorMapContainer.fromStringList([ + '#000004', '#010005', '#010106', '#010108', '#020109', '#02020b', '#02020d', '#03030f', + '#030312', '#040414', '#050416', '#060518', '#06051a', '#07061c', '#08071e', '#090720', + '#0a0822', '#0b0924', '#0c0926', '#0d0a29', '#0e0b2b', '#100b2d', '#110c2f', '#120d31', + '#130d34', '#140e36', '#150e38', '#160f3b', '#180f3d', '#19103f', '#1a1042', '#1c1044', + '#1d1147', '#1e1149', '#20114b', '#21114e', '#221150', '#241253', '#251255', '#271258', + '#29115a', '#2a115c', '#2c115f', '#2d1161', '#2f1163', '#311165', '#331067', '#341069', + '#36106b', '#38106c', '#390f6e', '#3b0f70', '#3d0f71', '#3f0f72', '#400f74', '#420f75', + '#440f76', '#451077', '#471078', '#491078', '#4a1079', '#4c117a', '#4e117b', '#4f127b', + '#51127c', '#52137c', '#54137d', '#56147d', '#57157e', '#59157e', '#5a167e', '#5c167f', + '#5d177f', '#5f187f', '#601880', '#621980', '#641a80', '#651a80', '#671b80', '#681c81', + '#6a1c81', '#6b1d81', '#6d1d81', '#6e1e81', '#701f81', '#721f81', '#732081', '#752181', + '#762181', '#782281', '#792282', '#7b2382', '#7c2382', '#7e2482', '#802582', '#812581', + '#832681', '#842681', '#862781', '#882781', '#892881', '#8b2981', '#8c2981', '#8e2a81', + '#902a81', '#912b81', '#932b80', '#942c80', '#962c80', '#982d80', '#992d80', '#9b2e7f', + '#9c2e7f', '#9e2f7f', '#a02f7f', '#a1307e', '#a3307e', '#a5317e', '#a6317d', '#a8327d', + '#aa337d', '#ab337c', '#ad347c', '#ae347b', '#b0357b', '#b2357b', '#b3367a', '#b5367a', + '#b73779', '#b83779', '#ba3878', '#bc3978', '#bd3977', '#bf3a77', '#c03a76', '#c23b75', + '#c43c75', '#c53c74', '#c73d73', '#c83e73', '#ca3e72', '#cc3f71', '#cd4071', '#cf4070', + '#d0416f', '#d2426f', '#d3436e', '#d5446d', '#d6456c', '#d8456c', '#d9466b', '#db476a', + '#dc4869', '#de4968', '#df4a68', '#e04c67', '#e24d66', '#e34e65', '#e44f64', '#e55064', + '#e75263', '#e85362', '#e95462', '#ea5661', '#eb5760', '#ec5860', '#ed5a5f', '#ee5b5e', + '#ef5d5e', '#f05f5e', '#f1605d', '#f2625d', '#f2645c', '#f3655c', '#f4675c', '#f4695c', + '#f56b5c', '#f66c5c', '#f66e5c', '#f7705c', '#f7725c', '#f8745c', '#f8765c', '#f9785d', + '#f9795d', '#f97b5d', '#fa7d5e', '#fa7f5e', '#fa815f', '#fb835f', '#fb8560', '#fb8761', + '#fc8961', '#fc8a62', '#fc8c63', '#fc8e64', '#fc9065', '#fd9266', '#fd9467', '#fd9668', + '#fd9869', '#fd9a6a', '#fd9b6b', '#fe9d6c', '#fe9f6d', '#fea16e', '#fea36f', '#fea571', + '#fea772', '#fea973', '#feaa74', '#feac76', '#feae77', '#feb078', '#feb27a', '#feb47b', + '#feb67c', '#feb77e', '#feb97f', '#febb81', '#febd82', '#febf84', '#fec185', '#fec287', + '#fec488', '#fec68a', '#fec88c', '#feca8d', '#fecc8f', '#fecd90', '#fecf92', '#fed194', + '#fed395', '#fed597', '#fed799', '#fed89a', '#fdda9c', '#fddc9e', '#fddea0', '#fde0a1', + '#fde2a3', '#fde3a5', '#fde5a7', '#fde7a9', '#fde9aa', '#fdebac', '#fcecae', '#fceeb0', + '#fcf0b2', '#fcf2b4', '#fcf4b6', '#fcf6b8', '#fcf7b9', '#fcf9bb', '#fcfbbd', '#fcfdbf' +]); + +ColorMapContainer.cividis = ColorMapContainer.fromStringList([ + '#00224e', '#00234f', '#002451', '#002553', '#002554', '#002656', '#002758', '#002859', + '#00285b', '#00295d', '#002a5f', '#002a61', '#002b62', '#002c64', '#002c66', '#002d68', + '#002e6a', '#002e6c', '#002f6d', '#00306f', '#003070', '#003170', '#003171', '#013271', + '#053371', '#083370', '#0c3470', '#0f3570', '#123570', '#143670', '#163770', '#18376f', + '#1a386f', '#1c396f', '#1e3a6f', '#203a6f', '#213b6e', '#233c6e', '#243c6e', '#263d6e', + '#273e6e', '#293f6e', '#2a3f6d', '#2b406d', '#2d416d', '#2e416d', '#2f426d', '#31436d', + '#32436d', '#33446d', '#34456c', '#35456c', '#36466c', '#38476c', '#39486c', '#3a486c', + '#3b496c', '#3c4a6c', '#3d4a6c', '#3e4b6c', '#3f4c6c', '#404c6c', '#414d6c', '#424e6c', + '#434e6c', '#444f6c', '#45506c', '#46516c', '#47516c', '#48526c', '#49536c', '#4a536c', + '#4b546c', '#4c556c', '#4d556c', '#4e566c', '#4f576c', '#50576c', '#51586d', '#52596d', + '#535a6d', '#545a6d', '#555b6d', '#555c6d', '#565c6d', '#575d6d', '#585e6d', '#595e6e', + '#5a5f6e', '#5b606e', '#5c616e', '#5d616e', '#5e626e', '#5e636f', '#5f636f', '#60646f', + '#61656f', '#62656f', '#636670', '#646770', '#656870', '#656870', '#666970', '#676a71', + '#686a71', '#696b71', '#6a6c71', '#6b6d72', '#6c6d72', '#6c6e72', '#6d6f72', '#6e6f73', + '#6f7073', '#707173', '#717274', '#727274', '#727374', '#737475', '#747475', '#757575', + '#767676', '#777776', '#777777', '#787877', '#797977', '#7a7a78', '#7b7a78', '#7c7b78', + '#7d7c78', '#7e7c78', '#7e7d78', '#7f7e78', '#807f78', '#817f78', '#828079', '#838179', + '#848279', '#858279', '#868379', '#878478', '#888578', '#898578', '#8a8678', '#8b8778', + '#8c8878', '#8d8878', '#8e8978', '#8f8a78', '#908b78', '#918b78', '#928c78', '#928d78', + '#938e78', '#948e77', '#958f77', '#969077', '#979177', '#989277', '#999277', '#9a9376', + '#9b9476', '#9c9576', '#9d9576', '#9e9676', '#9f9775', '#a09875', '#a19975', '#a29975', + '#a39a74', '#a49b74', '#a59c74', '#a69c74', '#a79d73', '#a89e73', '#a99f73', '#aaa073', + '#aba072', '#aca172', '#ada272', '#aea371', '#afa471', '#b0a571', '#b1a570', '#b3a670', + '#b4a76f', '#b5a86f', '#b6a96f', '#b7a96e', '#b8aa6e', '#b9ab6d', '#baac6d', '#bbad6d', + '#bcae6c', '#bdae6c', '#beaf6b', '#bfb06b', '#c0b16a', '#c1b26a', '#c2b369', '#c3b369', + '#c4b468', '#c5b568', '#c6b667', '#c7b767', '#c8b866', '#c9b965', '#cbb965', '#ccba64', + '#cdbb63', '#cebc63', '#cfbd62', '#d0be62', '#d1bf61', '#d2c060', '#d3c05f', '#d4c15f', + '#d5c25e', '#d6c35d', '#d7c45c', '#d9c55c', '#dac65b', '#dbc75a', '#dcc859', '#ddc858', + '#dec958', '#dfca57', '#e0cb56', '#e1cc55', '#e2cd54', '#e4ce53', '#e5cf52', '#e6d051', + '#e7d150', '#e8d24f', '#e9d34e', '#ead34c', '#ebd44b', '#edd54a', '#eed649', '#efd748', + '#f0d846', '#f1d945', '#f2da44', '#f3db42', '#f5dc41', '#f6dd3f', '#f7de3e', '#f8df3c', + '#f9e03a', '#fbe138', '#fce236', '#fde334', '#fee434', '#fee535', '#fee636', '#fee838' +]); + +ColorMapContainer.greys = ColorMapContainer.fromStringList([ + '#ffffff', '#ffffff', '#fefefe', '#fefefe', '#fdfdfd', '#fdfdfd', '#fcfcfc', '#fcfcfc', + '#fbfbfb', '#fbfbfb', '#fafafa', '#fafafa', '#f9f9f9', '#f9f9f9', '#f8f8f8', '#f8f8f8', + '#f7f7f7', '#f7f7f7', '#f7f7f7', '#f6f6f6', '#f6f6f6', '#f5f5f5', '#f5f5f5', '#f4f4f4', + '#f4f4f4', '#f3f3f3', '#f3f3f3', '#f2f2f2', '#f2f2f2', '#f1f1f1', '#f1f1f1', '#f0f0f0', + '#f0f0f0', '#efefef', '#eeeeee', '#eeeeee', '#ededed', '#ececec', '#ececec', '#ebebeb', + '#eaeaea', '#e9e9e9', '#e9e9e9', '#e8e8e8', '#e7e7e7', '#e7e7e7', '#e6e6e6', '#e5e5e5', + '#e4e4e4', '#e4e4e4', '#e3e3e3', '#e2e2e2', '#e1e1e1', '#e1e1e1', '#e0e0e0', '#dfdfdf', + '#dfdfdf', '#dedede', '#dddddd', '#dcdcdc', '#dcdcdc', '#dbdbdb', '#dadada', '#dadada', + '#d9d9d9', '#d8d8d8', '#d7d7d7', '#d6d6d6', '#d5d5d5', '#d4d4d4', '#d4d4d4', '#d3d3d3', + '#d2d2d2', '#d1d1d1', '#d0d0d0', '#cfcfcf', '#cecece', '#cdcdcd', '#cccccc', '#cccccc', + '#cbcbcb', '#cacaca', '#c9c9c9', '#c8c8c8', '#c7c7c7', '#c6c6c6', '#c5c5c5', '#c5c5c5', + '#c4c4c4', '#c3c3c3', '#c2c2c2', '#c1c1c1', '#c0c0c0', '#bfbfbf', '#bebebe', '#bebebe', + '#bdbdbd', '#bbbbbb', '#bababa', '#b9b9b9', '#b8b8b8', '#b6b6b6', '#b5b5b5', '#b4b4b4', + '#b3b3b3', '#b2b2b2', '#b0b0b0', '#afafaf', '#aeaeae', '#adadad', '#ababab', '#aaaaaa', + '#a9a9a9', '#a8a8a8', '#a7a7a7', '#a5a5a5', '#a4a4a4', '#a3a3a3', '#a2a2a2', '#a0a0a0', + '#9f9f9f', '#9e9e9e', '#9d9d9d', '#9c9c9c', '#9a9a9a', '#999999', '#989898', '#979797', + '#959595', '#949494', '#939393', '#929292', '#919191', '#909090', '#8f8f8f', '#8e8e8e', + '#8d8d8d', '#8c8c8c', '#8a8a8a', '#898989', '#888888', '#878787', '#868686', '#858585', + '#848484', '#838383', '#828282', '#818181', '#7f7f7f', '#7e7e7e', '#7d7d7d', '#7c7c7c', + '#7b7b7b', '#7a7a7a', '#797979', '#787878', '#777777', '#767676', '#757575', '#737373', + '#727272', '#717171', '#707070', '#6f6f6f', '#6e6e6e', '#6d6d6d', '#6c6c6c', '#6b6b6b', + '#6a6a6a', '#696969', '#686868', '#676767', '#666666', '#656565', '#646464', '#636363', + '#626262', '#616161', '#606060', '#5f5f5f', '#5e5e5e', '#5d5d5d', '#5c5c5c', '#5b5b5b', + '#5a5a5a', '#585858', '#575757', '#565656', '#555555', '#545454', '#535353', '#525252', + '#515151', '#505050', '#4e4e4e', '#4d4d4d', '#4b4b4b', '#4a4a4a', '#484848', '#474747', + '#464646', '#444444', '#434343', '#414141', '#404040', '#3f3f3f', '#3d3d3d', '#3c3c3c', + '#3a3a3a', '#393939', '#383838', '#363636', '#353535', '#333333', '#323232', '#303030', + '#2f2f2f', '#2e2e2e', '#2c2c2c', '#2b2b2b', '#292929', '#282828', '#272727', '#252525', + '#242424', '#232323', '#222222', '#212121', '#1f1f1f', '#1e1e1e', '#1d1d1d', '#1c1c1c', + '#1b1b1b', '#1a1a1a', '#181818', '#171717', '#161616', '#151515', '#141414', '#131313', + '#111111', '#101010', '#0f0f0f', '#0e0e0e', '#0d0d0d', '#0c0c0c', '#0a0a0a', '#090909', + '#080808', '#070707', '#060606', '#050505', '#030303', '#020202', '#010101', '#000000' +]); + +ColorMapContainer.gray = ColorMapContainer.fromStringList([ + '#000000', '#010101', '#020202', '#030303', '#040404', '#050505', '#060606', '#070707', + '#080808', '#090909', '#0a0a0a', '#0b0b0b', '#0c0c0c', '#0d0d0d', '#0e0e0e', '#0f0f0f', + '#101010', '#111111', '#121212', '#131313', '#141414', '#151515', '#161616', '#171717', + '#181818', '#191919', '#1a1a1a', '#1b1b1b', '#1c1c1c', '#1d1d1d', '#1e1e1e', '#1f1f1f', + '#202020', '#212121', '#222222', '#232323', '#242424', '#252525', '#262626', '#272727', + '#282828', '#292929', '#2a2a2a', '#2b2b2b', '#2c2c2c', '#2d2d2d', '#2e2e2e', '#2f2f2f', + '#303030', '#313131', '#323232', '#333333', '#343434', '#353535', '#363636', '#373737', + '#383838', '#393939', '#3a3a3a', '#3b3b3b', '#3c3c3c', '#3d3d3d', '#3e3e3e', '#3f3f3f', + '#404040', '#414141', '#424242', '#434343', '#444444', '#454545', '#464646', '#474747', + '#484848', '#494949', '#4a4a4a', '#4b4b4b', '#4c4c4c', '#4d4d4d', '#4e4e4e', '#4f4f4f', + '#505050', '#515151', '#525252', '#535353', '#545454', '#555555', '#565656', '#575757', + '#585858', '#595959', '#5a5a5a', '#5b5b5b', '#5c5c5c', '#5d5d5d', '#5e5e5e', '#5f5f5f', + '#606060', '#616161', '#626262', '#636363', '#646464', '#656565', '#666666', '#676767', + '#686868', '#696969', '#6a6a6a', '#6b6b6b', '#6c6c6c', '#6d6d6d', '#6e6e6e', '#6f6f6f', + '#707070', '#717171', '#727272', '#737373', '#747474', '#757575', '#767676', '#777777', + '#787878', '#797979', '#7a7a7a', '#7b7b7b', '#7c7c7c', '#7d7d7d', '#7e7e7e', '#7f7f7f', + '#808080', '#818181', '#828282', '#838383', '#848484', '#858585', '#868686', '#878787', + '#888888', '#898989', '#8a8a8a', '#8b8b8b', '#8c8c8c', '#8d8d8d', '#8e8e8e', '#8f8f8f', + '#909090', '#919191', '#929292', '#939393', '#949494', '#959595', '#969696', '#979797', + '#989898', '#999999', '#9a9a9a', '#9b9b9b', '#9c9c9c', '#9d9d9d', '#9e9e9e', '#9f9f9f', + '#a0a0a0', '#a1a1a1', '#a2a2a2', '#a3a3a3', '#a4a4a4', '#a5a5a5', '#a6a6a6', '#a7a7a7', + '#a8a8a8', '#a9a9a9', '#aaaaaa', '#ababab', '#acacac', '#adadad', '#aeaeae', '#afafaf', + '#b0b0b0', '#b1b1b1', '#b2b2b2', '#b3b3b3', '#b4b4b4', '#b5b5b5', '#b6b6b6', '#b7b7b7', + '#b8b8b8', '#b9b9b9', '#bababa', '#bbbbbb', '#bcbcbc', '#bdbdbd', '#bebebe', '#bfbfbf', + '#c0c0c0', '#c1c1c1', '#c2c2c2', '#c3c3c3', '#c4c4c4', '#c5c5c5', '#c6c6c6', '#c7c7c7', + '#c8c8c8', '#c9c9c9', '#cacaca', '#cbcbcb', '#cccccc', '#cdcdcd', '#cecece', '#cfcfcf', + '#d0d0d0', '#d1d1d1', '#d2d2d2', '#d3d3d3', '#d4d4d4', '#d5d5d5', '#d6d6d6', '#d7d7d7', + '#d8d8d8', '#d9d9d9', '#dadada', '#dbdbdb', '#dcdcdc', '#dddddd', '#dedede', '#dfdfdf', + '#e0e0e0', '#e1e1e1', '#e2e2e2', '#e3e3e3', '#e4e4e4', '#e5e5e5', '#e6e6e6', '#e7e7e7', + '#e8e8e8', '#e9e9e9', '#eaeaea', '#ebebeb', '#ececec', '#ededed', '#eeeeee', '#efefef', + '#f0f0f0', '#f1f1f1', '#f2f2f2', '#f3f3f3', '#f4f4f4', '#f5f5f5', '#f6f6f6', '#f7f7f7', + '#f8f8f8', '#f9f9f9', '#fafafa', '#fbfbfb', '#fcfcfc', '#fdfdfd', '#fefefe', '#ffffff' +]); + +ColorMapContainer.purples = ColorMapContainer.fromStringList([ + '#fcfbfd', '#fcfbfd', '#fbfafc', '#fbfafc', '#faf9fc', '#faf9fc', '#faf8fb', '#f9f8fb', + '#f9f7fb', '#f8f7fb', '#f8f7fa', '#f8f6fa', '#f7f6fa', '#f7f5fa', '#f6f5f9', '#f6f4f9', + '#f5f4f9', '#f5f4f9', '#f5f3f8', '#f4f3f8', '#f4f2f8', '#f3f2f8', '#f3f1f7', '#f3f1f7', + '#f2f0f7', '#f2f0f7', '#f1f0f6', '#f1eff6', '#f1eff6', '#f0eef6', '#f0eef5', '#efedf5', + '#efedf5', '#eeecf5', '#eeecf4', '#edebf4', '#ecebf4', '#eceaf3', '#ebe9f3', '#eae9f3', + '#eae8f2', '#e9e8f2', '#e8e7f2', '#e8e6f2', '#e7e6f1', '#e6e5f1', '#e6e5f1', '#e5e4f0', + '#e4e3f0', '#e4e3f0', '#e3e2ef', '#e2e2ef', '#e2e1ef', '#e1e0ee', '#e0e0ee', '#e0dfee', + '#dfdfed', '#dedeed', '#dedded', '#ddddec', '#dcdcec', '#dcdcec', '#dbdbec', '#dadaeb', + '#dadaeb', '#d9d9ea', '#d8d8ea', '#d7d7e9', '#d6d6e9', '#d5d5e9', '#d4d4e8', '#d3d3e8', + '#d2d2e7', '#d1d2e7', '#d0d1e6', '#cfd0e6', '#cecfe5', '#cecee5', '#cdcde4', '#cccce4', + '#cbcbe3', '#cacae3', '#c9c9e2', '#c8c8e2', '#c7c8e1', '#c6c7e1', '#c5c6e1', '#c4c5e0', + '#c3c4e0', '#c2c3df', '#c1c2df', '#c0c1de', '#bfc0de', '#bebfdd', '#bebedd', '#bdbedc', + '#bcbddc', '#bbbbdb', '#babadb', '#b9b9da', '#b8b8d9', '#b7b7d9', '#b6b6d8', '#b5b5d7', + '#b4b4d7', '#b3b3d6', '#b2b2d5', '#b1b1d5', '#b0afd4', '#afaed4', '#aeadd3', '#aeacd2', + '#adabd2', '#acaad1', '#aba9d0', '#aaa8d0', '#a9a7cf', '#a8a6cf', '#a7a4ce', '#a6a3cd', + '#a5a2cd', '#a4a1cc', '#a3a0cb', '#a29fcb', '#a19eca', '#a09dca', '#9f9cc9', '#9e9bc8', + '#9e9ac8', '#9d99c7', '#9c98c7', '#9b97c6', '#9a96c6', '#9995c6', '#9894c5', '#9793c5', + '#9692c4', '#9591c4', '#9490c3', '#9390c3', '#928fc3', '#918ec2', '#908dc2', '#8f8cc1', + '#8e8bc1', '#8e8ac0', '#8d89c0', '#8c88bf', '#8b87bf', '#8a86bf', '#8986be', '#8885be', + '#8784bd', '#8683bd', '#8582bc', '#8481bc', '#8380bb', '#827fbb', '#817ebb', '#807dba', + '#807cba', '#7f7bb9', '#7e79b8', '#7d78b7', '#7d77b7', '#7c75b6', '#7b74b5', '#7b72b4', + '#7a71b4', '#7970b3', '#796eb2', '#786db2', '#776cb1', '#776ab0', '#7669af', '#7567af', + '#7566ae', '#7465ad', '#7363ad', '#7262ac', '#7261ab', '#715faa', '#705eaa', '#705ca9', + '#6f5ba8', '#6e5aa8', '#6e58a7', '#6d57a6', '#6c55a5', '#6c54a5', '#6b53a4', '#6a51a3', + '#6950a3', '#694fa2', '#684da1', '#674ca1', '#674ba0', '#66499f', '#65489f', '#65479e', + '#64459e', '#63449d', '#63439c', '#62429c', '#61409b', '#613f9a', '#603e9a', '#5f3c99', + '#5e3b98', '#5e3a98', '#5d3897', '#5c3797', '#5c3696', '#5b3495', '#5a3395', '#5a3294', + '#593093', '#582f93', '#582e92', '#572c92', '#562b91', '#552a90', '#552890', '#54278f', + '#53268f', '#53258e', '#52238d', '#51228d', '#51218c', '#50208c', '#4f1f8b', '#4f1d8b', + '#4e1c8a', '#4d1b89', '#4d1a89', '#4c1888', '#4c1788', '#4b1687', '#4a1587', '#4a1486', + '#491285', '#481185', '#481084', '#470f84', '#460d83', '#460c83', '#450b82', '#440a82', + '#440981', '#430780', '#420680', '#42057f', '#41047f', '#40027e', '#40017e', '#3f007d' +]); + +ColorMapContainer.blues = ColorMapContainer.fromStringList([ + '#f7fbff', '#f6faff', '#f5fafe', '#f5f9fe', '#f4f9fe', '#f3f8fe', '#f2f8fd', '#f2f7fd', + '#f1f7fd', '#f0f6fd', '#eff6fc', '#eef5fc', '#eef5fc', '#edf4fc', '#ecf4fb', '#ebf3fb', + '#eaf3fb', '#eaf2fb', '#e9f2fa', '#e8f1fa', '#e7f1fa', '#e7f0fa', '#e6f0f9', '#e5eff9', + '#e4eff9', '#e3eef9', '#e3eef8', '#e2edf8', '#e1edf8', '#e0ecf8', '#dfecf7', '#dfebf7', + '#deebf7', '#ddeaf7', '#dceaf6', '#dce9f6', '#dbe9f6', '#dae8f6', '#d9e8f5', '#d9e7f5', + '#d8e7f5', '#d7e6f5', '#d6e6f4', '#d6e5f4', '#d5e5f4', '#d4e4f4', '#d3e4f3', '#d3e3f3', + '#d2e3f3', '#d1e2f3', '#d0e2f2', '#d0e1f2', '#cfe1f2', '#cee0f2', '#cde0f1', '#cddff1', + '#ccdff1', '#cbdef1', '#cadef0', '#caddf0', '#c9ddf0', '#c8dcf0', '#c7dcef', '#c7dbef', + '#c6dbef', '#c4daee', '#c3daee', '#c2d9ee', '#c1d9ed', '#bfd8ed', '#bed8ec', '#bdd7ec', + '#bcd7eb', '#bad6eb', '#b9d6ea', '#b8d5ea', '#b7d4ea', '#b5d4e9', '#b4d3e9', '#b3d3e8', + '#b2d2e8', '#b0d2e7', '#afd1e7', '#aed1e7', '#add0e6', '#abd0e6', '#aacfe5', '#a9cfe5', + '#a8cee4', '#a6cee4', '#a5cde3', '#a4cce3', '#a3cce3', '#a1cbe2', '#a0cbe2', '#9fcae1', + '#9dcae1', '#9cc9e1', '#9ac8e0', '#99c7e0', '#97c6df', '#95c5df', '#94c4df', '#92c4de', + '#91c3de', '#8fc2de', '#8dc1dd', '#8cc0dd', '#8abfdd', '#89bedc', '#87bddc', '#85bcdc', + '#84bcdb', '#82bbdb', '#81badb', '#7fb9da', '#7db8da', '#7cb7da', '#7ab6d9', '#79b5d9', + '#77b5d9', '#75b4d8', '#74b3d8', '#72b2d8', '#71b1d7', '#6fb0d7', '#6dafd7', '#6caed6', + '#6aaed6', '#69add5', '#68acd5', '#66abd4', '#65aad4', '#64a9d3', '#63a8d3', '#61a7d2', + '#60a7d2', '#5fa6d1', '#5da5d1', '#5ca4d0', '#5ba3d0', '#5aa2cf', '#58a1cf', '#57a0ce', + '#56a0ce', '#549fcd', '#539ecd', '#529dcc', '#519ccc', '#4f9bcb', '#4e9acb', '#4d99ca', + '#4b98ca', '#4a98c9', '#4997c9', '#4896c8', '#4695c8', '#4594c7', '#4493c7', '#4292c6', + '#4191c6', '#4090c5', '#3f8fc5', '#3e8ec4', '#3d8dc4', '#3c8cc3', '#3b8bc2', '#3a8ac2', + '#3989c1', '#3888c1', '#3787c0', '#3686c0', '#3585bf', '#3484bf', '#3383be', '#3282be', + '#3181bd', '#3080bd', '#2f7fbc', '#2e7ebc', '#2d7dbb', '#2c7cba', '#2b7bba', '#2a7ab9', + '#2979b9', '#2777b8', '#2676b8', '#2575b7', '#2474b7', '#2373b6', '#2272b6', '#2171b5', + '#2070b4', '#206fb4', '#1f6eb3', '#1e6db2', '#1d6cb1', '#1c6bb0', '#1c6ab0', '#1b69af', + '#1a68ae', '#1967ad', '#1966ad', '#1865ac', '#1764ab', '#1663aa', '#1562a9', '#1561a9', + '#1460a8', '#135fa7', '#125ea6', '#125da6', '#115ca5', '#105ba4', '#0f5aa3', '#0e59a2', + '#0e58a2', '#0d57a1', '#0c56a0', '#0b559f', '#0a549e', '#0a539e', '#09529d', '#08519c', + '#08509b', '#084f99', '#084e98', '#084d96', '#084c95', '#084b93', '#084a91', '#084990', + '#08488e', '#08478d', '#08468b', '#08458a', '#084488', '#084387', '#084285', '#084184', + '#084082', '#083e81', '#083d7f', '#083c7d', '#083b7c', '#083a7a', '#083979', '#083877', + '#083776', '#083674', '#083573', '#083471', '#083370', '#08326e', '#08316d', '#08306b' +]); + +ColorMapContainer.greens = ColorMapContainer.fromStringList([ + '#f7fcf5', '#f6fcf4', '#f6fcf4', '#f5fbf3', '#f5fbf2', '#f4fbf2', '#f4fbf1', '#f3faf0', + '#f2faf0', '#f2faef', '#f1faee', '#f1faee', '#f0f9ed', '#f0f9ec', '#eff9ec', '#eff9eb', + '#eef8ea', '#edf8ea', '#edf8e9', '#ecf8e8', '#ecf8e8', '#ebf7e7', '#ebf7e7', '#eaf7e6', + '#e9f7e5', '#e9f7e5', '#e8f6e4', '#e8f6e3', '#e7f6e3', '#e7f6e2', '#e6f5e1', '#e5f5e1', + '#e5f5e0', '#e4f5df', '#e3f4de', '#e2f4dd', '#e1f3dc', '#e0f3db', '#dff3da', '#def2d9', + '#ddf2d8', '#dcf2d7', '#dbf1d6', '#dbf1d5', '#daf0d4', '#d9f0d3', '#d8f0d2', '#d7efd1', + '#d6efd0', '#d5efcf', '#d4eece', '#d3eecd', '#d2edcc', '#d1edcb', '#d0edca', '#cfecc9', + '#ceecc8', '#cdecc7', '#ccebc6', '#cbebc5', '#cbeac4', '#caeac3', '#c9eac2', '#c8e9c1', + '#c7e9c0', '#c6e8bf', '#c4e8bd', '#c3e7bc', '#c2e7bb', '#c1e6ba', '#c0e6b9', '#bee5b8', + '#bde5b6', '#bce4b5', '#bbe4b4', '#bae3b3', '#b8e3b2', '#b7e2b1', '#b6e2af', '#b5e1ae', + '#b4e1ad', '#b2e0ac', '#b1e0ab', '#b0dfaa', '#afdfa8', '#aedea7', '#acdea6', '#abdda5', + '#aadda4', '#a9dca3', '#a8dca2', '#a7dba0', '#a5db9f', '#a4da9e', '#a3da9d', '#a2d99c', + '#a0d99b', '#9fd899', '#9ed798', '#9cd797', '#9bd696', '#99d595', '#98d594', '#97d492', + '#95d391', '#94d390', '#92d28f', '#91d28e', '#90d18d', '#8ed08b', '#8dd08a', '#8bcf89', + '#8ace88', '#88ce87', '#87cd86', '#86cc85', '#84cc83', '#83cb82', '#81ca81', '#80ca80', + '#7fc97f', '#7dc87e', '#7cc87c', '#7ac77b', '#79c67a', '#78c679', '#76c578', '#75c477', + '#73c476', '#72c375', '#70c274', '#6ec173', '#6dc072', '#6bc072', '#6abf71', '#68be70', + '#66bd6f', '#65bd6f', '#63bc6e', '#62bb6d', '#60ba6c', '#5eb96b', '#5db96b', '#5bb86a', + '#5ab769', '#58b668', '#56b567', '#55b567', '#53b466', '#52b365', '#50b264', '#4eb264', + '#4db163', '#4bb062', '#4aaf61', '#48ae60', '#46ae60', '#45ad5f', '#43ac5e', '#42ab5d', + '#40aa5d', '#3fa95c', '#3fa85b', '#3ea75a', '#3da65a', '#3ca559', '#3ba458', '#3aa357', + '#39a257', '#38a156', '#37a055', '#369f54', '#359e53', '#349d53', '#339c52', '#329b51', + '#319a50', '#309950', '#2f984f', '#2f974e', '#2e964d', '#2d954d', '#2c944c', '#2b934b', + '#2a924a', '#29914a', '#289049', '#278f48', '#268e47', '#258d47', '#248c46', '#238b45', + '#228a44', '#218944', '#208843', '#1f8742', '#1e8741', '#1d8640', '#1c8540', '#1a843f', + '#19833e', '#18823d', '#17813d', '#16803c', '#157f3b', '#147e3a', '#137d39', '#127c39', + '#117b38', '#107a37', '#0e7936', '#0d7836', '#0c7735', '#0b7734', '#0a7633', '#097532', + '#087432', '#077331', '#067230', '#05712f', '#03702e', '#026f2e', '#016e2d', '#006d2c', + '#006c2c', '#006b2b', '#00692a', '#00682a', '#006729', '#006529', '#006428', '#006328', + '#006227', '#006027', '#005f26', '#005e26', '#005c25', '#005b25', '#005a24', '#005924', + '#005723', '#005622', '#005522', '#005321', '#005221', '#005120', '#005020', '#004e1f', + '#004d1f', '#004c1e', '#004a1e', '#00491d', '#00481d', '#00471c', '#00451c', '#00441b' +]); + +ColorMapContainer.oranges = ColorMapContainer.fromStringList([ + '#fff5eb', '#fff5ea', '#fff4e9', '#fff4e8', '#fff3e7', '#fff3e6', '#fff2e6', '#fff2e5', + '#fff1e4', '#fff1e3', '#fff0e2', '#fff0e1', '#ffefe0', '#ffefdf', '#ffeede', '#ffeedd', + '#feeddc', '#feeddc', '#feeddb', '#feecda', '#feecd9', '#feebd8', '#feebd7', '#feead6', + '#feead5', '#fee9d4', '#fee9d3', '#fee8d2', '#fee8d2', '#fee7d1', '#fee7d0', '#fee6cf', + '#fee6ce', '#fee5cc', '#fee5cb', '#fee4ca', '#fee3c8', '#fee2c7', '#fee2c6', '#fee1c4', + '#fee0c3', '#fee0c1', '#fedfc0', '#fedebf', '#fedebd', '#feddbc', '#fedcbb', '#fedcb9', + '#fddbb8', '#fddab6', '#fdd9b5', '#fdd9b4', '#fdd8b2', '#fdd7b1', '#fdd7af', '#fdd6ae', + '#fdd5ad', '#fdd5ab', '#fdd4aa', '#fdd3a9', '#fdd3a7', '#fdd2a6', '#fdd1a4', '#fdd1a3', + '#fdd0a2', '#fdcfa0', '#fdce9e', '#fdcd9c', '#fdcb9b', '#fdca99', '#fdc997', '#fdc895', + '#fdc794', '#fdc692', '#fdc590', '#fdc48f', '#fdc38d', '#fdc28b', '#fdc189', '#fdc088', + '#fdbf86', '#fdbe84', '#fdbd83', '#fdbb81', '#fdba7f', '#fdb97d', '#fdb87c', '#fdb77a', + '#fdb678', '#fdb576', '#fdb475', '#fdb373', '#fdb271', '#fdb170', '#fdb06e', '#fdaf6c', + '#fdae6a', '#fdad69', '#fdac67', '#fdab66', '#fda965', '#fda863', '#fda762', '#fda660', + '#fda55f', '#fda45d', '#fda35c', '#fda25a', '#fda159', '#fda057', '#fd9f56', '#fd9e54', + '#fd9d53', '#fd9c51', '#fd9b50', '#fd9a4e', '#fd994d', '#fd984b', '#fd974a', '#fd9649', + '#fd9547', '#fd9446', '#fd9344', '#fd9243', '#fd9141', '#fd9040', '#fd8f3e', '#fd8e3d', + '#fd8c3b', '#fc8b3a', '#fc8a39', '#fc8937', '#fb8836', '#fb8735', '#fb8634', '#fa8532', + '#fa8331', '#f98230', '#f9812e', '#f9802d', '#f87f2c', '#f87e2b', '#f87d29', '#f77b28', + '#f77a27', '#f67925', '#f67824', '#f67723', '#f57622', '#f57520', '#f5741f', '#f4721e', + '#f4711c', '#f3701b', '#f36f1a', '#f36e19', '#f26d17', '#f26c16', '#f26b15', '#f16913', + '#f16813', '#f06712', '#ef6612', '#ee6511', '#ee6410', '#ed6310', '#ec620f', '#eb610f', + '#eb600e', '#ea5f0e', '#e95e0d', '#e85d0c', '#e75c0c', '#e75b0b', '#e65a0b', '#e5590a', + '#e4580a', '#e45709', '#e35608', '#e25508', '#e15407', '#e15307', '#e05206', '#df5106', + '#de5005', '#de4e05', '#dd4d04', '#dc4c03', '#db4b03', '#db4a02', '#da4902', '#d94801', + '#d84801', '#d64701', '#d54601', '#d34601', '#d14501', '#d04501', '#ce4401', '#cd4401', + '#cb4302', '#c94202', '#c84202', '#c64102', '#c54102', '#c34002', '#c14002', '#c03f02', + '#be3f02', '#bd3e02', '#bb3d02', '#b93d02', '#b83c02', '#b63c02', '#b53b02', '#b33b02', + '#b13a03', '#b03903', '#ae3903', '#ad3803', '#ab3803', '#a93703', '#a83703', '#a63603', + '#a53603', '#a43503', '#a23503', '#a13403', '#a03403', '#9f3303', '#9e3303', '#9c3203', + '#9b3203', '#9a3103', '#993103', '#973003', '#963003', '#952f03', '#942f03', '#932f03', + '#912e04', '#902e04', '#8f2d04', '#8e2d04', '#8c2c04', '#8b2c04', '#8a2b04', '#892b04', + '#882a04', '#862a04', '#852904', '#842904', '#832804', '#812804', '#802704', '#7f2704' +]); + +ColorMapContainer.reds = ColorMapContainer.fromStringList([ + '#fff5f0', '#fff4ef', '#fff4ee', '#fff3ed', '#fff2ec', '#fff2eb', '#fff1ea', '#fff0e9', + '#fff0e8', '#ffefe8', '#ffeee7', '#ffeee6', '#ffede5', '#ffece4', '#ffece3', '#ffebe2', + '#feeae1', '#feeae0', '#fee9df', '#fee8de', '#fee8dd', '#fee7dc', '#fee7db', '#fee6da', + '#fee5d9', '#fee5d8', '#fee4d8', '#fee3d7', '#fee3d6', '#fee2d5', '#fee1d4', '#fee1d3', + '#fee0d2', '#fedfd0', '#fedecf', '#fedccd', '#fedbcc', '#fedaca', '#fed9c9', '#fed8c7', + '#fdd7c6', '#fdd5c4', '#fdd4c2', '#fdd3c1', '#fdd2bf', '#fdd1be', '#fdd0bc', '#fdcebb', + '#fdcdb9', '#fdccb8', '#fdcbb6', '#fdcab5', '#fdc9b3', '#fdc7b2', '#fdc6b0', '#fdc5ae', + '#fcc4ad', '#fcc3ab', '#fcc2aa', '#fcc1a8', '#fcbfa7', '#fcbea5', '#fcbda4', '#fcbca2', + '#fcbba1', '#fcb99f', '#fcb89e', '#fcb79c', '#fcb69b', '#fcb499', '#fcb398', '#fcb296', + '#fcb095', '#fcaf93', '#fcae92', '#fcad90', '#fcab8f', '#fcaa8d', '#fca98c', '#fca78b', + '#fca689', '#fca588', '#fca486', '#fca285', '#fca183', '#fca082', '#fc9e80', '#fc9d7f', + '#fc9c7d', '#fc9b7c', '#fc997a', '#fc9879', '#fc9777', '#fc9576', '#fc9474', '#fc9373', + '#fc9272', '#fc9070', '#fc8f6f', '#fc8e6e', '#fc8d6d', '#fc8b6b', '#fc8a6a', '#fc8969', + '#fc8767', '#fc8666', '#fc8565', '#fc8464', '#fc8262', '#fc8161', '#fc8060', '#fc7f5f', + '#fb7d5d', '#fb7c5c', '#fb7b5b', '#fb7a5a', '#fb7858', '#fb7757', '#fb7656', '#fb7555', + '#fb7353', '#fb7252', '#fb7151', '#fb7050', '#fb6e4e', '#fb6d4d', '#fb6c4c', '#fb6b4b', + '#fb694a', '#fa6849', '#fa6648', '#fa6547', '#f96346', '#f96245', '#f96044', '#f85f43', + '#f85d42', '#f75c41', '#f75b40', '#f7593f', '#f6583e', '#f6563d', '#f6553c', '#f5533b', + '#f5523a', '#f4503a', '#f44f39', '#f44d38', '#f34c37', '#f34a36', '#f34935', '#f24734', + '#f24633', '#f14432', '#f14331', '#f14130', '#f0402f', '#f03f2e', '#f03d2d', '#ef3c2c', + '#ee3a2c', '#ed392b', '#ec382b', '#eb372a', '#ea362a', '#e93529', '#e83429', '#e63328', + '#e53228', '#e43027', '#e32f27', '#e22e27', '#e12d26', '#e02c26', '#de2b25', '#dd2a25', + '#dc2924', '#db2824', '#da2723', '#d92523', '#d82422', '#d72322', '#d52221', '#d42121', + '#d32020', '#d21f20', '#d11e1f', '#d01d1f', '#cf1c1f', '#ce1a1e', '#cc191e', '#cb181d', + '#ca181d', '#c9181d', '#c8171c', '#c7171c', '#c5171c', '#c4161c', '#c3161b', '#c2161b', + '#c1161b', '#bf151b', '#be151a', '#bd151a', '#bc141a', '#bb141a', '#b91419', '#b81419', + '#b71319', '#b61319', '#b51318', '#b31218', '#b21218', '#b11218', '#b01217', '#af1117', + '#ad1117', '#ac1117', '#ab1016', '#aa1016', '#a91016', '#a81016', '#a60f15', '#a50f15', + '#a30f15', '#a10e15', '#9f0e14', '#9d0d14', '#9c0d14', '#9a0c14', '#980c13', '#960b13', + '#940b13', '#920a13', '#900a12', '#8e0912', '#8c0912', '#8a0812', '#880811', '#860811', + '#840711', '#820711', '#800610', '#7e0610', '#7c0510', '#7a0510', '#79040f', '#77040f', + '#75030f', '#73030f', '#71020e', '#6f020e', '#6d010e', '#6b010e', '#69000d', '#67000d' +]); + +ColorMapContainer.rdYlBu = ColorMapContainer.fromStringList([ + '#a50026', '#a70226', '#a90426', '#ab0626', '#ad0826', '#af0926', '#b10b26', '#b30d26', + '#b50f26', '#b71126', '#b91326', '#bb1526', '#bd1726', '#be1827', '#c01a27', '#c21c27', + '#c41e27', '#c62027', '#c82227', '#ca2427', '#cc2627', '#ce2827', '#d02927', '#d22b27', + '#d42d27', '#d62f27', '#d83128', '#d93429', '#da362a', '#db382b', '#dc3b2c', '#dd3d2d', + '#de402e', '#e0422f', '#e14430', '#e24731', '#e34933', '#e44c34', '#e54e35', '#e65036', + '#e75337', '#e95538', '#ea5739', '#eb5a3a', '#ec5c3b', '#ed5f3c', '#ee613e', '#ef633f', + '#f16640', '#f26841', '#f36b42', '#f46d43', '#f47044', '#f57245', '#f57547', '#f57748', + '#f67a49', '#f67c4a', '#f67f4b', '#f7814c', '#f7844e', '#f8864f', '#f88950', '#f88c51', + '#f98e52', '#f99153', '#f99355', '#fa9656', '#fa9857', '#fa9b58', '#fb9d59', '#fba05b', + '#fba35c', '#fca55d', '#fca85e', '#fcaa5f', '#fdad60', '#fdaf62', '#fdb164', '#fdb366', + '#fdb567', '#fdb769', '#fdb96b', '#fdbb6d', '#fdbd6f', '#fdbf71', '#fdc173', '#fdc374', + '#fdc576', '#fdc778', '#fec87a', '#feca7c', '#fecc7e', '#fece7f', '#fed081', '#fed283', + '#fed485', '#fed687', '#fed889', '#feda8a', '#fedc8c', '#fede8e', '#fee090', '#fee192', + '#fee294', '#fee496', '#fee597', '#fee699', '#fee79b', '#fee99d', '#feea9f', '#feeba1', + '#feeca2', '#feeda4', '#feefa6', '#fff0a8', '#fff1aa', '#fff2ac', '#fff3ad', '#fff5af', + '#fff6b1', '#fff7b3', '#fff8b5', '#fffab7', '#fffbb9', '#fffcba', '#fffdbc', '#fffebe', + '#feffc0', '#fdfec2', '#fcfec5', '#fbfdc7', '#fafdc9', '#f8fccb', '#f7fcce', '#f6fbd0', + '#f5fbd2', '#f3fbd4', '#f2fad6', '#f1fad9', '#f0f9db', '#eff9dd', '#edf8df', '#ecf8e2', + '#ebf7e4', '#eaf7e6', '#e9f6e8', '#e7f6eb', '#e6f5ed', '#e5f5ef', '#e4f4f1', '#e2f4f4', + '#e1f3f6', '#e0f3f8', '#def2f7', '#dcf1f7', '#daf0f6', '#d8eff6', '#d6eef5', '#d4edf4', + '#d1ecf4', '#cfebf3', '#cdeaf3', '#cbe9f2', '#c9e8f2', '#c7e7f1', '#c5e6f0', '#c3e5f0', + '#c1e4ef', '#bfe3ef', '#bde2ee', '#bbe1ed', '#b9e0ed', '#b6dfec', '#b4deec', '#b2ddeb', + '#b0dcea', '#aedbea', '#acdae9', '#aad8e9', '#a8d6e8', '#a6d5e7', '#a3d3e6', '#a1d1e5', + '#9fd0e4', '#9dcee3', '#9bcce2', '#99cae1', '#97c9e0', '#94c7df', '#92c5de', '#90c3dd', + '#8ec2dc', '#8cc0db', '#8abeda', '#87bdd9', '#85bbd9', '#83b9d8', '#81b7d7', '#7fb6d6', + '#7db4d5', '#7ab2d4', '#78b0d3', '#76afd2', '#74add1', '#72abd0', '#70a9cf', '#6ea6ce', + '#6da4cc', '#6ba2cb', '#69a0ca', '#679ec9', '#659bc8', '#6399c7', '#6297c6', '#6095c4', + '#5e93c3', '#5c90c2', '#5a8ec1', '#588cc0', '#578abf', '#5588be', '#5385bd', '#5183bb', + '#4f81ba', '#4d7fb9', '#4b7db8', '#4a7ab7', '#4878b6', '#4676b5', '#4574b3', '#4471b2', + '#436fb1', '#426cb0', '#416aaf', '#4167ad', '#4065ac', '#3f62ab', '#3e60aa', '#3e5ea8', + '#3d5ba7', '#3c59a6', '#3b56a5', '#3a54a4', '#3a51a2', '#394fa1', '#384ca0', '#374a9f', + '#36479e', '#36459c', '#35429b', '#34409a', '#333d99', '#333b97', '#323896', '#313695' +]); diff --git a/engine/esm/layers/fits_image.js b/engine/esm/layers/fits_image.js new file mode 100644 index 00000000..66676e7a --- /dev/null +++ b/engine/esm/layers/fits_image.js @@ -0,0 +1,430 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A FITS image. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { WebFile } from "../web_file.js"; +import { Coordinates } from "../coordinates.js"; +import { WcsImage } from "./wcs_image.js"; + + +// wwtlib.FitsImage + +export function FitsImage(dataset, file, blob, callMeBack) { + this.errored = false; + this.numAxis = 0; + this.histogramMaxCount = 0; + this.sourceBlob = null; + this.header = {}; + this.position = 0; + this.bufferSize = 1; + this._parseSuccessful$1 = false; + WcsImage.call(this); + this.dataset = dataset; + this.fitsProperties = dataset.get_fitsProperties(); + this._callBack$1 = callMeBack; + this.filename = file; + if (blob != null) { + this._readFromBlob$1(blob); + } + else { + this.getFile(file); + } +} + +FitsImage.naN = 0 / 0; + +var FitsImage$ = { + getFile: function (url) { + this._webFile$1 = new WebFile(url); + this._webFile$1.responseType = 'blob'; + this._webFile$1.onStateChange = ss.bind('fileStateChange', this); + this._webFile$1.send(); + }, + + fileStateChange: function () { + if (this._webFile$1.get_state() === 2) { + this.errored = true; + if (this._callBack$1 != null) { + this._callBack$1(this); + } + } else if (this._webFile$1.get_state() === 1) { + var mainBlob = this._webFile$1.getBlob(); + this._readFromBlob$1(mainBlob); + } + }, + _readFromBlob$1: function (blob) { + var $this = this; + + this.sourceBlob = blob; + var chunck = new FileReader(); + chunck.onloadend = function (e) { + $this.readFromBin(new DataView(chunck.result)); + $this.errored = !$this._parseSuccessful$1; + if ($this._callBack$1 != null) { + $this._callBack$1($this); + } + }; + chunck.readAsArrayBuffer(blob); + }, + _readByteString$1: function (dataView, count) { + var data = ''; + for (var i = 0; i < count; i++) { + data += String.fromCharCode(dataView.getUint8(this.position)); + this.position++; + } + return data; + }, + _validateFitsSimple$1: function (dataView) { + var data = this._readByteString$1(dataView, 8); + var keyword = ss.trimEnd(data); + this.position -= 8; + return keyword.toUpperCase() === 'SIMPLE'; + }, + + readFromBin: function (dataView) { + if (!this._validateFitsSimple$1(dataView)) { + console.log('The requested file is not a valid FITS file.'); + return; + } + var foundEnd = false; + while (!foundEnd) { + for (var i = 0; i < 36; i++) { + var data = this._readByteString$1(dataView, 80); + if (!foundEnd) { + var keyword = ss.trimEnd(data.substring(0, 8)); + var values = data.substring(10).split('/'); + if (keyword.toUpperCase() === 'END') { + foundEnd = true; + // Check for XTENSION + i++; + data = this._readByteString$1(dataView, 80); + while (ss.whitespace(data)) { + i++; + data = this._readByteString$1(dataView, 80); + } + keyword = ss.trimEnd(data.substring(0, 8)); + if (keyword.toUpperCase() === 'XTENSION') { + // We have additional headers + foundEnd = false; + } + else { + // Rewind these 80 bytes which could be data + this.position -= 80; + } + } + else { + this._addKeyword$1(keyword, values); + } + } + } + } + if (!foundEnd) { + console.log('Unable to parse requested FITS file.'); + return; + } + this.numAxis = parseInt(this.header['NAXIS']); + if (ss.keyExists(this.header, 'BLANK')) { + this.fitsProperties.blankValue = parseFloat(this.header['BLANK']); + this.fitsProperties.containsBlanks = true; + } + if (ss.keyExists(this.header, 'BZERO')) { + this.fitsProperties.bZero = parseFloat(this.header['BZERO']); + } + if (ss.keyExists(this.header, 'BSCALE')) { + this.fitsProperties.bScale = parseFloat(this.header['BSCALE']); + } + this.axisSize = new Array(this.numAxis); + for (var axis = 0; axis < this.numAxis; axis++) { + this.axisSize[axis] = parseInt(this.header[ss.format('NAXIS{0}', axis + 1)]); + this.bufferSize *= this.axisSize[axis]; + } + var bitpix = parseInt(this.header['BITPIX']); + this.readDataUnit(dataView, bitpix); + if (this.numAxis > 1) { + this.sizeX = this.axisSize[0]; + this.sizeY = this.axisSize[1]; + this.histogram = this.computeHistogram(256); + this.histogramMaxCount = this.histogram[256]; + } + this.computeWcs(); + this._parseSuccessful$1 = true; + }, + _addKeyword$1: function (keyword, values) { + if (keyword !== 'CONTINUE' && keyword !== 'COMMENT' && keyword !== 'HISTORY' && !ss.emptyString(keyword)) { + try { + if (ss.keyExists(this.header, keyword)) { + this.header[keyword] = ss.trim(values[0]); + } + else { + this.header[keyword.toUpperCase()] = ss.trim(values[0]); + } + } + catch ($e1) { + } + } + }, + + readDataUnit: function (dataView, bitpix) { + this.dataUnit = new Float32Array(this.bufferSize); + switch (bitpix) { + case -64: + this.readDataUnitFloat64(dataView); + break; + case -32: + this.readDataUnitFloat32(dataView); + break; + case 8: + this.readDataUnitUint8(dataView); + break; + case 16: + this.readDataUnitInt16(dataView); + break; + case 32: + this.readDataUnitInt32(dataView); + break; + case 64: + // 64 bit integers not supported by Safari + console.log('64 bit integer FITS are not yet supported'); + break; + } + }, + + readDataUnitFloat64: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getFloat64(this.position, false); + var physicalValue = this.dataUnit[i] * this.fitsProperties.bScale + this.fitsProperties.bZero; + if (this.fitsProperties.minVal > physicalValue) { + this.fitsProperties.minVal = physicalValue; + } + if (this.fitsProperties.maxVal < physicalValue) { + this.fitsProperties.maxVal = physicalValue; + } + i++; + this.position += 8; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + + readDataUnitFloat32: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getFloat32(this.position, false); + var physicalValue = this.dataUnit[i] * this.fitsProperties.bScale + this.fitsProperties.bZero; + if (this.fitsProperties.minVal > physicalValue) { + this.fitsProperties.minVal = physicalValue; + } + if (this.fitsProperties.maxVal < physicalValue) { + this.fitsProperties.maxVal = physicalValue; + } + i++; + this.position += 4; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + + readDataUnitUint8: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getUint8(this.position); + if (this.fitsProperties.minVal > this.dataUnit[i]) { + this.fitsProperties.minVal = this.dataUnit[i]; + } + if (this.fitsProperties.maxVal < this.dataUnit[i]) { + this.fitsProperties.maxVal = this.dataUnit[i]; + } + i++; + this.position += 1; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + + readDataUnitInt16: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getInt16(this.position, false); + if (this.fitsProperties.minVal > this.dataUnit[i]) { + this.fitsProperties.minVal = this.dataUnit[i]; + } + if (this.fitsProperties.maxVal < this.dataUnit[i]) { + this.fitsProperties.maxVal = this.dataUnit[i]; + } + i++; + this.position += 2; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + + readDataUnitInt32: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getInt32(this.position, false); + if (this.fitsProperties.minVal > this.dataUnit[i]) { + this.fitsProperties.minVal = this.dataUnit[i]; + } + if (this.fitsProperties.maxVal < this.dataUnit[i]) { + this.fitsProperties.maxVal = this.dataUnit[i]; + } + i++; + this.position += 4; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + + computeWcs: function () { + if (ss.keyExists(this.header, 'CROTA2')) { + this.rotation = parseFloat(ss.trim(this.header['CROTA2'])); + this.hasRotation = true; + } + if (ss.keyExists(this.header, 'CDELT1')) { + this.scaleX = parseFloat(ss.trim(this.header['CDELT1'])); + if (ss.keyExists(this.header, 'CDELT2')) { + this.scaleY = parseFloat(ss.trim(this.header['CDELT2'])); + this.hasScale = true; + } + } + if (ss.keyExists(this.header, 'CRPIX1')) { + // In FITS/ WCS, pixel coordinates are 1 - based and integer pixel + // coordinates land on pixel centers. Therefore in standard FITS + // orientation, where the "first" pixel is at the lower-left, the + // lower-left corner of the image has pixel coordinate (0.5, 0.5). For + // the WWT offset parameters, the lower-left corner of the image has + // coordinate (0, 0). + this.referenceX = parseFloat(ss.trim(this.header['CRPIX1'])) - 0.5; + if (ss.keyExists(this.header, 'CRPIX2')) { + this.referenceY = parseFloat(ss.trim(this.header['CRPIX2'])) - 0.5; + this.hasPixel = true; + } + } + var galactic = false; + var tan = false; + if (ss.keyExists(this.header, 'CTYPE1')) { + if (this.header['CTYPE1'].indexOf('GLON-') > -1) { + galactic = true; + tan = true; + } + if (this.header['CTYPE2'].indexOf('GLAT-') > -1) { + galactic = true; + tan = true; + } + if (this.header['CTYPE1'].indexOf('-TAN') > -1) { + tan = true; + } + if (this.header['CTYPE1'].indexOf('-SIN') > -1) { + tan = true; + } + } + if (!tan) { + throw new Error('Only TAN projected images are supported: '); + } + this.hasSize = true; + if (ss.keyExists(this.header, 'CRVAL1')) { + this.centerX = parseFloat(ss.trim(this.header['CRVAL1'])); + if (ss.keyExists(this.header, 'CRVAL2')) { + this.centerY = parseFloat(ss.trim(this.header['CRVAL2'])); + this.hasLocation = true; + } + } + if (galactic) { + var result = Coordinates.galactictoJ2000(this.centerX, this.centerY); + this.centerX = result[0]; + this.centerY = result[1]; + } + if (ss.keyExists(this.header, 'CD1_1') && ss.keyExists(this.header, 'CD1_2') && ss.keyExists(this.header, 'CD2_1') && ss.keyExists(this.header, 'CD2_2')) { + this.cd1_1 = parseFloat(ss.trim(this.header['CD1_1'])); + this.cd1_2 = parseFloat(ss.trim(this.header['CD1_2'])); + this.cd2_1 = parseFloat(ss.trim(this.header['CD2_1'])); + this.cd2_2 = parseFloat(ss.trim(this.header['CD2_2'])); + if (!this.hasRotation) { + this.calculateRotationFromCD(); + } + if (!this.hasScale) { + this.calculateScaleFromCD(); + } + this.hasScale = true; + this.hasRotation = true; + } + this.set_validWcs(this.hasScale && this.hasRotation && this.hasPixel && this.hasLocation); + }, + + // Modify the FitsProperties object to apply any settings stored in this + // FITS image's header keywords. This mechanism gives us a way to set up + // the rendering of a tiled FITS image through keywords set on its + // level-0 tile file. + // + // I'm not aware of any standard, or even standard-ish, headers to + // define these settings, so we'll roll our own here. + applyDisplaySettings: function () { + // TODO for tiled FITS: distinguish between datamin in this one tile, + // and datamin across the full, un-downsampled original imagery. + + if (ss.keyExists(this.header, 'DATAMIN')) { + this.fitsProperties.lowerCut = parseFloat(ss.trim(this.header['DATAMIN'])); + this.fitsProperties.minVal = this.fitsProperties.lowerCut; + } + if (ss.keyExists(this.header, 'DATAMAX')) { + this.fitsProperties.upperCut = parseFloat(ss.trim(this.header['DATAMAX'])); + this.fitsProperties.maxVal = this.fitsProperties.upperCut; + } + if (ss.keyExists(this.header, 'PXCUTMIN')) { + this.fitsProperties.lowerCut = parseFloat(ss.trim(this.header['PXCUTMIN'])); + } + if (ss.keyExists(this.header, 'PXCUTMAX')) { + this.fitsProperties.upperCut = parseFloat(ss.trim(this.header['PXCUTMAX'])); + } + }, + + computeHistogram: function (count) { + var histogram = new Array(count + 1); + for (var i = 0; i < count + 1; i++) { + histogram[i] = 0; + } + this.populateHistogram(histogram); + var maxCounter = 1; + var $enum1 = ss.enumerate(histogram); + while ($enum1.moveNext()) { + var val = $enum1.current; + if (val > maxCounter) { + maxCounter = val; + } + } + histogram[count] = maxCounter; + return histogram; + }, + + populateHistogram: function (histogram) { + var buckets = histogram.length; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + for (var i = 0; i < this.dataUnit.length; i++) { + if (!(this.dataUnit[i] === FitsImage.naN)) { + histogram[Math.min(buckets - 1, ss.truncate(((this.fitsProperties.bZero + this.fitsProperties.bScale * this.dataUnit[i] - this.fitsProperties.minVal) / factor)))]++; + } + } + }, + + drawHistogram: function (ctx) { + ctx.clearRect(0, 0, 255, 150); + ctx.beginPath(); + ctx.strokeStyle = 'rgba(255,255,255,255)'; + var logMax = Math.log(this.histogramMaxCount); + for (var i = 0; i < this.histogram.length; i++) { + var height = Math.log(this.histogram[i]) / logMax; + if (height < 0) { + height = 0; + } + ctx.moveTo(i, 150); + ctx.lineTo(i, 150 - (height * 150)); + ctx.stroke(); + } + } +}; + +registerType("FitsImage", [FitsImage, FitsImage$, WcsImage]); diff --git a/engine/esm/layers/fits_image_js.js b/engine/esm/layers/fits_image_js.js new file mode 100644 index 00000000..b5aba6f7 --- /dev/null +++ b/engine/esm/layers/fits_image_js.js @@ -0,0 +1,632 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A FITS image with a pure JavaScript implementation. +// +// This class is used when WebGL 2 is not available, as in Safari. + +import { ss } from "../ss.js"; +import { registerType, registerEnum } from "../typesystem.js"; +import { BinaryReader } from "../utilities/binary_reader.js"; +import { Bitmap } from "../utilities/bitmap.js"; +import { ColorMapContainer } from "./color_map_container.js"; +import { FitsImage } from "./fits_image.js"; + + +// wwtlib.DataTypes + +export var DataTypes = { + byteT: 0, + int16T: 1, + int32T: 2, + floatT: 3, + doubleT: 4, + none: 5 +}; + +registerType("DataTypes", DataTypes); +registerEnum("DataTypes", DataTypes); + + +// wwtlib.ScaleMap + +export function ScaleMap() { } + +var ScaleMap$ = {}; + +registerType("ScaleMap", [ScaleMap, ScaleMap$, null]); + + +// wwtlib.ScaleLinear + +export function ScaleLinear(min, max) { + this._min$1 = 0; + this._max$1 = 0; + this._factor$1 = 0; + this._logFactor$1 = 0; + ScaleMap.call(this); + this._min$1 = min; + this._max$1 = max; + this._factor$1 = max - min; +} + +var ScaleLinear$ = { + map: function (val) { + return Math.min(255, Math.max(0, ss.truncate(((val - this._min$1) / this._factor$1 * 255)))); + } +}; + +registerType("ScaleLinear", [ScaleLinear, ScaleLinear$, ScaleMap]); + + +// wwtlib.ScaleLog + +export function ScaleLog(min, max) { + this._min$1 = 0; + this._max$1 = 0; + this._factor$1 = 0; + this._logFactor$1 = 0; + ScaleMap.call(this); + this._min$1 = min; + this._max$1 = max; + this._factor$1 = max - min; + this._logFactor$1 = 255 / Math.log(255); +} + +var ScaleLog$ = { + map: function (val) { + return Math.min(255, Math.max(0, ss.truncate((Math.log((val - this._min$1) / this._factor$1 * 255) * this._logFactor$1)))); + } +}; + +registerType("ScaleLog", [ScaleLog, ScaleLog$, ScaleMap]); + + +// wwtlib.ScalePow + +export function ScalePow(min, max) { + this._min$1 = 0; + this._max$1 = 0; + this._factor$1 = 0; + this._powFactor$1 = 0; + ScaleMap.call(this); + this._min$1 = min; + this._max$1 = max; + this._factor$1 = max - min; + this._powFactor$1 = 255 / Math.pow(255, 2); +} + +var ScalePow$ = { + map: function (val) { + return Math.min(255, Math.max(0, ss.truncate((Math.pow((val - this._min$1) / this._factor$1 * 255, 2) * this._powFactor$1)))); + } +}; + +registerType("ScalePow", [ScalePow, ScalePow$, ScaleMap]); + + +// wwtlib.ScaleSqrt + +export function ScaleSqrt(min, max) { + this._min$1 = 0; + this._max$1 = 0; + this._factor$1 = 0; + this._sqrtFactor$1 = 0; + ScaleMap.call(this); + this._min$1 = min; + this._max$1 = max; + this._factor$1 = max - min; + this._sqrtFactor$1 = 255 / Math.sqrt(255); +} + +var ScaleSqrt$ = { + map: function (val) { + return Math.min(255, Math.max(0, ss.truncate((Math.sqrt((val - this._min$1) / this._factor$1 * 255) * this._sqrtFactor$1)))); + } +}; + +registerType("ScaleSqrt", [ScaleSqrt, ScaleSqrt$, ScaleMap]); + + +// wwtlib.HistogramEqualization + +export function HistogramEqualization(image, min, max) { + this._min$1 = 0; + this._max$1 = 0; + this._factor$1 = 0; + this._maxHistogramValue$1 = 1; + ScaleMap.call(this); + this._min$1 = min; + this._max$1 = max; + this._factor$1 = max - min; + this._histogram$1 = image.computeHistogram(10000); + this._maxHistogramValue$1 = this._histogram$1[10000]; + this._lookup$1 = new Array(10000); + var totalCounts = ss.truncate((image.get_sizeX() * image.get_sizeY())); + var sum = 0; + for (var i = 0; i < 10000; i++) { + sum += this._histogram$1[i]; + this._lookup$1[i] = (Math.min(255, (sum * 255) / totalCounts) + 0.5); + } +} + +var HistogramEqualization$ = { + map: function (val) { + return this._lookup$1[Math.min(10000 - 1, Math.max(0, ss.truncate(((val - this._min$1) / this._factor$1 * (10000 - 1)))))]; + } +}; + +registerType("HistogramEqualization", [HistogramEqualization, HistogramEqualization$, ScaleMap]); + + +// wwtlib.FitsImageJs + +export function FitsImageJs(dataset, file, blob, callMeBack) { + this.dataType = DataTypes.none; + this._color$2 = false; + this.isTiledFits = false; + FitsImage.call(this, dataset, file, blob, callMeBack); +} + +FitsImageJs.createTiledFits = function (dataset, file, callMeBack) { + var fits = new FitsImageJs(dataset, file, null, callMeBack); + fits.isTiledFits = true; + return fits; +}; + +var FitsImageJs$ = { + readFromBin: function (dataView) { + FitsImage.prototype.readFromBin.call(this, dataView); + if (this.numAxis === 3) { + if (this.axisSize[2] === 3) { + this._color$2 = true; + } + } + }, + + readDataUnit: function (dataView, bitpix) { + var br = new BinaryReader(new Uint8Array(dataView.buffer)); + br.position = this.position; + switch (bitpix) { + case -64: + this.dataType = DataTypes.doubleT; + this._readDataUnitFloat64$2(br); + break; + case -32: + this.dataType = DataTypes.floatT; + this._readDataUnitFloat32$2(br); + break; + case 8: + this.dataType = DataTypes.byteT; + this._readDataUnitUint8$2(br); + break; + case 16: + this.dataType = DataTypes.int16T; + this._readDataUnitInt16$2(br); + break; + case 32: + this.dataType = DataTypes.int32T; + this._readDataUnitInt32$2(br); + break; + } + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + }, + _readDataUnitUint8$2: function (br) { + var buffer = new Array(this.bufferSize); + this._dataBuffer$2 = buffer; + for (var i = 0; i < this.bufferSize; i++) { + buffer[i] = br.readByte(); + if (this.fitsProperties.minVal > buffer[i]) { + this.fitsProperties.minVal = buffer[i]; + } + if (this.fitsProperties.maxVal < buffer[i]) { + this.fitsProperties.maxVal = buffer[i]; + } + } + }, + _readDataUnitInt16$2: function (br) { + var buffer = new Array(this.bufferSize); + this._dataBuffer$2 = buffer; + for (var i = 0; i < this.bufferSize; i++) { + buffer[i] = ((br.readSByte() * 256) + br.readByte()); + if (this.fitsProperties.minVal > buffer[i]) { + this.fitsProperties.minVal = buffer[i]; + } + if (this.fitsProperties.maxVal < buffer[i]) { + this.fitsProperties.maxVal = buffer[i]; + } + } + }, + _readDataUnitInt32$2: function (br) { + var buffer = new Array(this.bufferSize); + this._dataBuffer$2 = buffer; + for (var i = 0; i < this.bufferSize; i++) { + buffer[i] = (br.readSByte() << 24) + (br.readSByte() << 16) + (br.readSByte() << 8) + br.readByte(); + if (this.fitsProperties.minVal > buffer[i]) { + this.fitsProperties.minVal = buffer[i]; + } + if (this.fitsProperties.maxVal < buffer[i]) { + this.fitsProperties.maxVal = buffer[i]; + } + } + }, + _readDataUnitFloat32$2: function (br) { + var buffer = new Array(this.bufferSize); + this._dataBuffer$2 = buffer; + var part = new Uint8Array(4); + for (var i = 0; i < this.bufferSize; i++) { + part[3] = br.readByte(); + part[2] = br.readByte(); + part[1] = br.readByte(); + part[0] = br.readByte(); + buffer[i] = new Float32Array(part.buffer, 0, 1)[0]; + if (this.fitsProperties.minVal > buffer[i]) { + this.fitsProperties.minVal = buffer[i]; + } + if (this.fitsProperties.maxVal < buffer[i]) { + this.fitsProperties.maxVal = buffer[i]; + } + } + }, + _readDataUnitFloat64$2: function (br) { + var buffer = new Array(this.bufferSize); + var part = new Uint8Array(8); + this._dataBuffer$2 = buffer; + for (var i = 0; i < this.bufferSize; i++) { + part[7] = br.readByte(); + part[6] = br.readByte(); + part[5] = br.readByte(); + part[4] = br.readByte(); + part[3] = br.readByte(); + part[2] = br.readByte(); + part[1] = br.readByte(); + part[0] = br.readByte(); + buffer[i] = new Float64Array(part.buffer, 0, 1)[0]; + if (this.fitsProperties.minVal > buffer[i]) { + this.fitsProperties.minVal = buffer[i]; + } + if (this.fitsProperties.maxVal < buffer[i]) { + this.fitsProperties.maxVal = buffer[i]; + } + } + }, + + getBitmap: function () { + if (!this.fitsProperties.upperCut && !this.fitsProperties.lowerCut) { + this.fitsProperties.lowerCut = this.fitsProperties.minVal; + this.fitsProperties.upperCut = this.fitsProperties.maxVal; + } + return this.getScaledBitmap(this.fitsProperties.lowerCut, this.fitsProperties.upperCut, this.fitsProperties.scaleType, 0, this.fitsProperties.colorMapName); + }, + + getScaledBitmap: function (min, max, scaleType, z, colorMapperName) { + var scale; + this.fitsProperties.scaleType = scaleType; + this.fitsProperties.lowerCut = min; + this.fitsProperties.upperCut = max; + this.fitsProperties.colorMapName = colorMapperName; + var colorMapper = ColorMapContainer.fromNamedColormap(colorMapperName); + switch (scaleType) { + case 0: + default: + scale = new ScaleLinear(min, max); + break; + case 1: + scale = new ScaleLog(min, max); + break; + case 2: + scale = new ScalePow(min, max); + break; + case 3: + scale = new ScaleSqrt(min, max); + break; + case 4: + scale = new HistogramEqualization(this, min, max); + break; + } + try { + switch (this.dataType) { + case DataTypes.byteT: + return this._getBitmapByte$2(min, max, scale, 0, colorMapper); + case DataTypes.int16T: + return this.getBitmapShort(min, max, scale, 0, colorMapper); + case DataTypes.int32T: + return this._getBitmapInt$2(min, max, scale, 0, colorMapper); + case DataTypes.floatT: + return this._getBitmapFloat$2(min, max, scale, 0, colorMapper); + case DataTypes.doubleT: + return this._getBitmapDouble$2(min, max, scale, 0, colorMapper); + case DataTypes.none: + default: + return Bitmap.create(100, 100); + } + } + catch ($e1) { + return Bitmap.create(10, 10); + } + }, + _setPixelWithColorMap$2: function (bmp, x, y, val, colorMapper) { + if (colorMapper == null) { + bmp.setPixel(x, y, val, val, val, (this.fitsProperties.transparentBlack && !val) ? 0 : 255); + return; + } + var pixel_value = val / 255; + if (Number.isNaN(pixel_value)) { + // This case "can't happen" in C#, but due to JavaScript's numerical + // model, it can happen here. + bmp.setPixel(x, y, 0, 0, 0, 0); + return; + } + var pixel_color = colorMapper.findClosestColor(pixel_value); + bmp.setPixel(x, y, ss.truncate(pixel_color.r), ss.truncate(pixel_color.g), ss.truncate(pixel_color.b), (this.fitsProperties.transparentBlack && !val) ? 0 : 255); + }, + _getBitmapByte$2: function (min, max, scale, z, colorMapper) { + var buf = this._dataBuffer$2; + var factor = max - min; + var stride = this.axisSize[0]; + var page = this.axisSize[0] * this.axisSize[1] * z; + var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); + for (var y = 0; y < this.axisSize[1]; y++) { + var indexY = ((this.axisSize[1] - 1) - y); + for (var x = 0; x < this.axisSize[0]; x++) { + if (this._color$2) { + var datR = buf[(x + indexY * stride)]; + var datG = buf[(x + indexY * stride) + page]; + var datB = buf[(x + indexY * stride) + page * 2]; + if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var r = scale.map(datR); + var g = scale.map(datG); + var b = scale.map(datB); + bmp.setPixel(x, y, r, g, b, 255); + } + } + else { + var dataValue = buf[x + indexY * stride + page]; + if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var val = scale.map(dataValue); + this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); + } + } + } + } + return bmp; + }, + _getBitmapDouble$2: function (min, max, scale, z, colorMapper) { + var buf = this._dataBuffer$2; + var factor = max - min; + var stride = this.axisSize[0]; + var page = this.axisSize[0] * this.axisSize[1] * z; + var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); + for (var y = 0; y < this.axisSize[1]; y++) { + var indexY = ((this.axisSize[1] - 1) - y); + for (var x = 0; x < this.axisSize[0]; x++) { + if (this._color$2) { + var datR = buf[(x + indexY * stride)]; + var datG = buf[(x + indexY * stride) + page]; + var datB = buf[(x + indexY * stride) + page * 2]; + if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var r = scale.map(datR); + var g = scale.map(datG); + var b = scale.map(datB); + bmp.setPixel(x, y, r, g, b, 255); + } + } + else { + var dataValue = buf[x + indexY * stride + page]; + if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var val = scale.map(dataValue); + this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); + } + } + } + } + return bmp; + }, + _getBitmapFloat$2: function (min, max, scale, z, colorMapper) { + var buf = this._dataBuffer$2; + var factor = max - min; + var stride = this.axisSize[0]; + var page = this.axisSize[0] * this.axisSize[1] * z; + var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); + for (var y = 0; y < this.axisSize[1]; y++) { + var indexY = ((this.axisSize[1] - 1) - y); + for (var x = 0; x < this.axisSize[0]; x++) { + if (this._color$2) { + var datR = buf[(x + indexY * stride)]; + var datG = buf[(x + indexY * stride) + page]; + var datB = buf[(x + indexY * stride) + page * 2]; + if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var r = scale.map(datR); + var g = scale.map(datG); + var b = scale.map(datB); + bmp.setPixel(x, y, r, g, b, 255); + } + } + else { + var dataValue = buf[x + indexY * stride + page]; + if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var val = scale.map(dataValue); + this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); + } + } + } + } + return bmp; + }, + _getBitmapInt$2: function (min, max, scale, z, colorMapper) { + var buf = this._dataBuffer$2; + var factor = max - min; + var stride = this.axisSize[0]; + var page = this.axisSize[0] * this.axisSize[1] * z; + var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); + for (var y = 0; y < this.axisSize[1]; y++) { + var indexY = ((this.axisSize[1] - 1) - y); + for (var x = 0; x < this.axisSize[0]; x++) { + if (this._color$2) { + var datR = buf[(x + indexY * stride)]; + var datG = buf[(x + indexY * stride) + page]; + var datB = buf[(x + indexY * stride) + page * 2]; + if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var r = scale.map(datR); + var g = scale.map(datG); + var b = scale.map(datB); + bmp.setPixel(x, y, r, g, b, 255); + } + } + else { + var dataValue = buf[x + indexY * stride + page]; + if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var val = scale.map(dataValue); + this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); + } + } + } + } + return bmp; + }, + + getBitmapShort: function (min, max, scale, z, colorMapper) { + var buf = this._dataBuffer$2; + var factor = max - min; + var stride = this.axisSize[0]; + var page = this.axisSize[0] * this.axisSize[1] * z; + var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); + for (var y = 0; y < this.axisSize[1]; y++) { + var indexY = ((this.axisSize[1] - 1) - y); + for (var x = 0; x < this.axisSize[0]; x++) { + if (this._color$2) { + var datR = buf[(x + indexY * stride)]; + var datG = buf[(x + indexY * stride) + page]; + var datB = buf[(x + indexY * stride) + page * 2]; + if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var r = scale.map(datR); + var g = scale.map(datG); + var b = scale.map(datB); + bmp.setPixel(x, y, r, g, b, 255); + } + } + else { + var dataValue = buf[x + indexY * stride + page]; + if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { + bmp.setPixel(x, y, 0, 0, 0, 0); + } + else { + var val = scale.map(dataValue); + this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); + } + } + } + } + return bmp; + }, + + computeWcs: function () { + if (!this.isTiledFits) { + FitsImage.prototype.computeWcs.call(this); + } + }, + + populateHistogram: function (histogram) { + switch (this.dataType) { + case DataTypes.byteT: + this._populateHistogramByte$2(histogram); + break; + case DataTypes.int16T: + this._populateHistogramInt16$2(histogram); + break; + case DataTypes.int32T: + this._populateHistogramInt32$2(histogram); + break; + case DataTypes.floatT: + this._populateHistogramFloat$2(histogram); + break; + case DataTypes.doubleT: + this._populateHistogramDouble$2(histogram); + break; + } + }, + _populateHistogramDouble$2: function (histogram) { + var buckets = histogram.length; + var buf = this._dataBuffer$2; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + var $enum1 = ss.enumerate(buf); + while ($enum1.moveNext()) { + var val = $enum1.current; + if (!Number.isNaN(val)) { + histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; + } + } + }, + _populateHistogramFloat$2: function (histogram) { + var buckets = histogram.length; + var buf = this._dataBuffer$2; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + var $enum1 = ss.enumerate(buf); + while ($enum1.moveNext()) { + var val = $enum1.current; + if (!(val === FitsImage.naN)) { + histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; + } + } + }, + _populateHistogramInt32$2: function (histogram) { + var buckets = histogram.length; + var buf = this._dataBuffer$2; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + var $enum1 = ss.enumerate(buf); + while ($enum1.moveNext()) { + var val = $enum1.current; + histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; + } + }, + _populateHistogramInt16$2: function (histogram) { + var buckets = histogram.length; + var buf = this._dataBuffer$2; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + var $enum1 = ss.enumerate(buf); + while ($enum1.moveNext()) { + var val = $enum1.current; + histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; + } + }, + _populateHistogramByte$2: function (histogram) { + var buckets = histogram.length; + var buf = this._dataBuffer$2; + var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; + var $enum1 = ss.enumerate(buf); + while ($enum1.moveNext()) { + var val = $enum1.current; + histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; + } + } +}; + +registerType("FitsImageJs", [FitsImageJs, FitsImageJs$, FitsImage]); diff --git a/engine/esm/layers/fits_image_tile.js b/engine/esm/layers/fits_image_tile.js new file mode 100644 index 00000000..020b4753 --- /dev/null +++ b/engine/esm/layers/fits_image_tile.js @@ -0,0 +1,68 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A FITS image used as a tile in a pyramid. + +import { registerType } from "../typesystem.js"; +import { FitsImage } from "./fits_image.js"; + + +// wwtlib.FitsImageTile +// +// Min & Max are already known for pyramid FITS. +// To improve performance, the below per pixel methods are overriden + +export function FitsImageTile(dataset, file, callMeBack) { + FitsImage.call(this, dataset, file, null, callMeBack); +} + +var FitsImageTile$ = { + readDataUnitFloat64: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getFloat64(this.position, false); + i++; + this.position += 8; + } + }, + + readDataUnitFloat32: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getFloat32(this.position, false); + i++; + this.position += 4; + } + }, + + readDataUnitUint8: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getUint8(this.position); + i++; + this.position += 1; + } + }, + + readDataUnitInt16: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getInt16(this.position, false); + i++; + this.position += 2; + } + }, + + readDataUnitInt32: function (dataView) { + var i = 0; + while (this.position < dataView.byteLength) { + this.dataUnit[i] = dataView.getInt32(this.position, false); + i++; + this.position += 4; + } + }, + + computeWcs: function () { } +}; + +registerType("FitsImageTile", [FitsImageTile, FitsImageTile$, FitsImage]); diff --git a/engine/esm/layers/from_xml.js b/engine/esm/layers/from_xml.js new file mode 100644 index 00000000..9d3d99c3 --- /dev/null +++ b/engine/esm/layers/from_xml.js @@ -0,0 +1,63 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Set up the `Layer.fromXml()` function, which depends on a bunch of Layer +// subclasses. +// +// There are a variety of ways that we could set this up, possibly including +// just implementing this function in `layer.js`. This is a more conservating +// approach that tries to avoid circular module imports. + +import { ss } from "../ss.js"; +import { Layer } from "./layer.js"; +import { GreatCirlceRouteLayer } from "./great_circle_route_layer.js"; +import { GridLayer } from "./grid_layer.js"; +import { ImageSetLayer } from "./imageset_layer.js"; +import { Object3dLayer } from "./object3d.js"; +import { OrbitLayer } from "./orbit_layer.js"; +import { SpreadSheetLayer } from "./spreadsheet_layer.js"; +import { VoTableLayer } from "./vo_table_layer.js"; + + +// The `layerFromXml` function, which we also install as `Layer.fromXml()`. It +// needs to be aware of a bunch of layer subclasses. +export function layerFromXml(layerNode, someFlag) { + var layerClassName = layerNode.attributes.getNamedItem('Type').nodeValue; + + var overLayType = ss.replaceString(layerClassName, 'TerraViewer.', ''); + if (overLayType == null) { + return null; + } + + var newLayer = null; + switch (overLayType) { + case 'SpreadSheetLayer': + newLayer = new SpreadSheetLayer(); + break; + case 'GreatCirlceRouteLayer': + newLayer = new GreatCirlceRouteLayer(); + break; + case 'GridLayer': + newLayer = new GridLayer(); + break; + case 'ImageSetLayer': + newLayer = new ImageSetLayer(); + break; + case 'Object3dLayer': + newLayer = new Object3dLayer(); + break; + case 'OrbitLayer': + newLayer = new OrbitLayer(); + break; + case 'VoTableLayer': + newLayer = new VoTableLayer(); + break; + default: + return null; + } + + newLayer.initFromXml(layerNode); + return newLayer; +} + +Layer.fromXml = layerFromXml; diff --git a/engine/esm/layers/great_circle_route_layer.js b/engine/esm/layers/great_circle_route_layer.js new file mode 100644 index 00000000..17e6ab9f --- /dev/null +++ b/engine/esm/layers/great_circle_route_layer.js @@ -0,0 +1,199 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders progress along a great circle. +// +// Yes, there is an egregious typo in the name of this class. But to maintain +// API compatibility, we're not fixing it. + +import { registerType } from "../typesystem.js"; +import { Vector3d } from "../double3d.js"; +import { Dates, TriangleList } from "../graphics/primitives3d.js"; +import { Coordinates } from "../coordinates.js"; +import { Layer } from "./layer.js"; + + +// wwtlib.GreatCirlceRouteLayer + +export function GreatCirlceRouteLayer() { + this._triangleList$1 = null; + this._latStart$1 = 0; + this._lngStart$1 = 0; + this._latEnd$1 = 0; + this._lngEnd$1 = 0; + this._width$1 = 4; + this._percentComplete$1 = 100; + Layer.call(this); +} + +var GreatCirlceRouteLayer$ = { + // Even if we fix the typo in this class's name in an API break, we need to + // maintain it here to maintain compatibility with existing data files and + // older WWT clients. + getTypeName: function () { + return 'TerraViewer.GreatCirlceRouteLayer'; + }, + + cleanUp: function () { + if (this._triangleList$1 != null) { + this._triangleList$1.clear(); + } + this._triangleList$1 = null; + Layer.prototype.cleanUp.call(this); + }, + + draw: function (renderContext, opacity, flat) { + if (this._triangleList$1 == null) { + this._initializeRoute$1(renderContext); + } + this._triangleList$1.jNow = this._percentComplete$1 / 100; + this._triangleList$1.draw(renderContext, opacity * this.get_opacity(), 2); + return true; + }, + _initializeRoute$1: function (renderContext) { + this._triangleList$1 = new TriangleList(); + this._triangleList$1.decay = 1000; + this._triangleList$1.sky = this.get_astronomical(); + this._triangleList$1.timeSeries = true; + this._triangleList$1.depthBuffered = false; + this._triangleList$1.autoTime = false; + var steps = 500; + var start = Coordinates.geoTo3dDouble(this._latStart$1, this._lngStart$1); + var end = Coordinates.geoTo3dDouble(this._latEnd$1, this._lngEnd$1); + var dir = Vector3d.subtractVectors(end, start); + dir.normalize(); + var startNormal = start; + startNormal.normalize(); + var left = Vector3d.cross(startNormal, dir); + var right = Vector3d.cross(dir, startNormal); + left.normalize(); + right.normalize(); + left.multiply(0.001 * this._width$1); + right.multiply(0.001 * this._width$1); + var lastLeft = new Vector3d(); + var lastRight = new Vector3d(); + var firstTime = true; + for (var i = 0; i <= steps; i++) { + var v = Vector3d.lerp(start, end, i / steps); + v.normalize(); + var cl = v; + var cr = v; + cl.add(left); + cr.add(right); + if (!firstTime) { + this._triangleList$1.addQuad(lastRight, lastLeft, cr, cl, this.get_color(), new Dates(i / steps, 2)); + } + else { + firstTime = false; + } + lastLeft = cl; + lastRight = cr; + } + }, + + getParams: function () { + return [this._percentComplete$1]; + }, + + getParamNames: function () { + return ['Percentage']; + }, + + setParams: function (paramList) { + if (paramList.length > 0) { + this._percentComplete$1 = paramList[0]; + } + }, + + get_latStart: function () { + return this._latStart$1; + }, + + set_latStart: function (value) { + if (this._latStart$1 !== value) { + this._latStart$1 = value; + this.version++; + } + return value; + }, + + get_lngStart: function () { + return this._lngStart$1; + }, + + set_lngStart: function (value) { + if (this._lngStart$1 !== value) { + this._lngStart$1 = value; + this.version++; + } + return value; + }, + + get_latEnd: function () { + return this._latEnd$1; + }, + + set_latEnd: function (value) { + if (this._latEnd$1 !== value) { + this._latEnd$1 = value; + this.version++; + } + return value; + }, + + get_lngEnd: function () { + return this._lngEnd$1; + }, + + set_lngEnd: function (value) { + if (this._lngEnd$1 !== value) { + this._lngEnd$1 = value; + this.version++; + } + return value; + }, + + get_width: function () { + return this._width$1; + }, + + set_width: function (value) { + if (this._width$1 !== value) { + this._width$1 = value; + this.version++; + } + return value; + }, + + get_percentComplete: function () { + return this._percentComplete$1; + }, + + set_percentComplete: function (value) { + if (this._percentComplete$1 !== value) { + this._percentComplete$1 = value; + this.version++; + } + return value; + }, + + writeLayerProperties: function (xmlWriter) { + xmlWriter._writeAttributeString('LatStart', this.get_latStart().toString()); + xmlWriter._writeAttributeString('LngStart', this.get_lngStart().toString()); + xmlWriter._writeAttributeString('LatEnd', this.get_latEnd().toString()); + xmlWriter._writeAttributeString('LngEnd', this.get_lngEnd().toString()); + xmlWriter._writeAttributeString('Width', this.get_width().toString()); + xmlWriter._writeAttributeString('PercentComplete', this.get_percentComplete().toString()); + }, + + initializeFromXml: function (node) { + this._latStart$1 = parseFloat(node.attributes.getNamedItem('LatStart').nodeValue); + this._lngStart$1 = parseFloat(node.attributes.getNamedItem('LngStart').nodeValue); + this._latEnd$1 = parseFloat(node.attributes.getNamedItem('LatEnd').nodeValue); + this._lngEnd$1 = parseFloat(node.attributes.getNamedItem('LngEnd').nodeValue); + this._width$1 = parseFloat(node.attributes.getNamedItem('Width').nodeValue); + this._percentComplete$1 = parseFloat(node.attributes.getNamedItem('PercentComplete').nodeValue); + } +}; + +registerType("GreatCirlceRouteLayer", [GreatCirlceRouteLayer, GreatCirlceRouteLayer$, Layer]); diff --git a/engine/esm/layers/grid_layer.js b/engine/esm/layers/grid_layer.js new file mode 100644 index 00000000..1d358572 --- /dev/null +++ b/engine/esm/layers/grid_layer.js @@ -0,0 +1,25 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders a coordinate grid on a planet. + +import { registerType } from "../typesystem.js"; +import { Grids } from "../grids.js"; +import { Layer } from "./layer.js"; + + +// wwtlib.GridLayer + +export function GridLayer() { + Layer.call(this); +} + +var GridLayer$ = { + draw: function (renderContext, opacity, flat) { + Grids.drawPlanetGrid(renderContext, opacity * this.get_opacity(), this.get_color()); + Grids.drawPlanetGridText(renderContext, opacity * this.get_opacity(), this.get_color()); + return true; + } +}; + +registerType("GridLayer", [GridLayer, GridLayer$, Layer]); diff --git a/engine/esm/layers/imageset_layer.js b/engine/esm/layers/imageset_layer.js new file mode 100644 index 00000000..91b14766 --- /dev/null +++ b/engine/esm/layers/imageset_layer.js @@ -0,0 +1,236 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders an arbitrary imageset + +import { ss } from "../ss.js"; +import { registerType, Enums } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { useGlVersion2 } from "../render_globals.js"; +import { Histogram } from "../utilities/histogram.js"; +import { ColorMapContainer } from "./color_map_container.js"; +import { FitsImage } from "./fits_image.js"; +import { FitsImageJs } from "./fits_image_js.js"; +import { Imageset } from "../imageset.js"; +import { Layer } from "./layer.js"; + + +// wwtlib.ImageSetLayer + +export function ImageSetLayer() { + this._imageSet$1 = null; + this._extension$1 = '.txt'; + this._overrideDefaultLayer$1 = false; + this._loaded$1 = false; + Layer.call(this); +} + +ImageSetLayer.create = function (set) { + var isl = new ImageSetLayer(); + isl._imageSet$1 = set; + return isl; +}; + +var ImageSetLayer$ = { + get_imageSet: function () { + return this._imageSet$1; + }, + + set_imageSet: function (value) { + this._imageSet$1 = value; + return value; + }, + + get_overrideDefaultLayer: function () { + return this._overrideDefaultLayer$1; + }, + + set_overrideDefaultLayer: function (value) { + this._overrideDefaultLayer$1 = value; + return value; + }, + + getFitsImage: function () { + return ss.safeCast(this._imageSet$1.get_wcsImage(), FitsImage); + }, + + // Test whether our underlying imagery is FITS based. + // + // This can come in two flavors: a single FITS image, or tiled FITS. + // Note that even though the FileType/Extension field can currently + // specify multiple file formats, the rendering code requires that the + // extension is exactly ".fits" for FITS rendering to kick in. + _isFitsImageset$1: function () { + var hasFitsExt = this._imageSet$1.get_extension() === '.fits'; + return ss.canCast(this._imageSet$1.get_wcsImage(), FitsImage) || (this._imageSet$1.get_wcsImage() == null && hasFitsExt); + }, + + initializeFromXml: function (node) { + var imageSetNode = Util.selectSingleNode(node, 'ImageSet'); + this._imageSet$1 = Imageset.fromXMLNode(imageSetNode); + if (node.attributes.getNamedItem('Extension') != null) { + this._extension$1 = node.attributes.getNamedItem('Extension').nodeValue; + } + if (node.attributes.getNamedItem('ScaleType') != null) { + this.get_imageSet().get_fitsProperties().scaleType = Enums.parse('ScaleTypes', node.attributes.getNamedItem('ScaleType').nodeValue); + } + if (node.attributes.getNamedItem('MinValue') != null) { + this.get_imageSet().get_fitsProperties().minVal = parseFloat(node.attributes.getNamedItem('MinValue').nodeValue); + this.get_imageSet().get_fitsProperties().lowerCut = (node.attributes.getNamedItem('LowerCut') != null) ? parseFloat(node.attributes.getNamedItem('LowerCut').nodeValue) : this.get_imageSet().get_fitsProperties().minVal; + } + if (node.attributes.getNamedItem('MaxValue') != null) { + this.get_imageSet().get_fitsProperties().maxVal = parseFloat(node.attributes.getNamedItem('MaxValue').nodeValue); + this.get_imageSet().get_fitsProperties().upperCut = (node.attributes.getNamedItem('UpperCut') != null) ? parseFloat(node.attributes.getNamedItem('UpperCut').nodeValue) : this.get_imageSet().get_fitsProperties().maxVal; + } + if (node.attributes.getNamedItem('ColorMapperName') != null) { + this.get_imageSet().get_fitsProperties().colorMapName = node.attributes.getNamedItem('ColorMapperName').nodeValue; + } + if (node.attributes.getNamedItem('OverrideDefault') != null) { + this._overrideDefaultLayer$1 = ss.boolean(node.attributes.getNamedItem('OverrideDefault').nodeValue); + } + }, + + draw: function (renderContext, opacity, flat) { + if (!this._loaded$1) { + return false; + } + renderContext.set_worldBase(renderContext.get_world()); + renderContext.set_viewBase(renderContext.get_view()); + renderContext.makeFrustum(); + renderContext.drawImageSet(this._imageSet$1, this.get_opacity() * opacity * 100); + return true; + }, + + writeLayerProperties: function (xmlWriter) { + if (this._imageSet$1.get_wcsImage() != null) { + if (this._isFitsImageset$1()) { + this._extension$1 = '.fit'; + } + else { + this._extension$1 = '.png'; + } + xmlWriter._writeAttributeString('Extension', this._extension$1); + } + if (this._isFitsImageset$1()) { + xmlWriter._writeAttributeString('ScaleType', Enums.toXml('ScaleTypes', this._imageSet$1.get_fitsProperties().scaleType)); + xmlWriter._writeAttributeString('MinValue', this._imageSet$1.get_fitsProperties().minVal.toString()); + xmlWriter._writeAttributeString('MaxValue', this._imageSet$1.get_fitsProperties().maxVal.toString()); + xmlWriter._writeAttributeString('LowerCut', this._imageSet$1.get_fitsProperties().lowerCut.toString()); + xmlWriter._writeAttributeString('UpperCut', this._imageSet$1.get_fitsProperties().upperCut.toString()); + if (this._imageSet$1.get_fitsProperties().colorMapName != null) { + xmlWriter._writeAttributeString('ColorMapperName', this._imageSet$1.get_fitsProperties().colorMapName); + } + } + xmlWriter._writeAttributeString('OverrideDefault', this._overrideDefaultLayer$1.toString()); + Imageset.saveToXml(xmlWriter, this._imageSet$1, ''); + Layer.prototype.writeLayerProperties.call(this, xmlWriter); + }, + + getTypeName: function () { + return 'TerraViewer.ImageSetLayer'; + }, + + cleanUp: function () { + Layer.prototype.cleanUp.call(this); + }, + + addFilesToCabinet: function (fc) { + if (ss.canCast(this._imageSet$1.get_wcsImage(), FitsImage)) { + var fName = (this._imageSet$1.get_wcsImage()).get_filename(); + var fileName = fc.tempDirectory + ss.format('{0}\\{1}{2}', fc.get_packageID(), this.id.toString(), this._extension$1); + fc.addFile(fileName, (this._imageSet$1.get_wcsImage()).sourceBlob); + } + }, + + getParamNames: function () { + return Layer.prototype.getParamNames.call(this); + }, + + getParams: function () { + return Layer.prototype.getParams.call(this); + }, + + setParams: function (paramList) { + Layer.prototype.setParams.call(this, paramList); + }, + + setImageScale: function (scaleType, min, max) { + console.warn('SetImageScale is considered deprecated. Use setImageScaleRaw or setImageScalePhysical instead.'); + this.setImageScaleRaw(scaleType, min, max); + }, + + setImageScaleRaw: function (scaleType, min, max) { + this.get_imageSet().get_fitsProperties().lowerCut = min; + this.get_imageSet().get_fitsProperties().upperCut = max; + this.get_imageSet().get_fitsProperties().scaleType = scaleType; + if (ss.canCast(this._imageSet$1.get_wcsImage(), FitsImageJs)) { + Histogram.updateScale(this, scaleType, min, max); + } + }, + + setImageScalePhysical: function (scaleType, min, max) { + var newMin = min; + var newMax = max; + if (this._isFitsImageset$1()) { + newMin = (newMin - this._imageSet$1.get_fitsProperties().bZero) / this._imageSet$1.get_fitsProperties().bScale; + newMax = (newMax - this._imageSet$1.get_fitsProperties().bZero) / this._imageSet$1.get_fitsProperties().bScale; + } + this.setImageScaleRaw(scaleType, newMin, newMax); + }, + + setImageZ: function (z) { + if (this._isFitsImageset$1()) { + Histogram.updateImage(this, z); + } + }, + + get_colorMapperName: function () { + return this.get_imageSet().get_fitsProperties().colorMapName; + }, + + set_colorMapperName: function (value) { + if (ColorMapContainer.fromNamedColormap(value) == null) { + throw new Error('Invalid colormap name'); + } + this.version++; + if (this._isFitsImageset$1()) { + if (useGlVersion2) { + this._imageSet$1.get_fitsProperties().colorMapName = value; + } + else { + Histogram.updateColorMapper(this, value); + } + } + return value; + }, + + get_colorMapper: function () { + if (this.get_imageSet().get_fitsProperties().colorMapName == null) { + return null; + } else { + return ColorMapContainer.fromNamedColormap(this.get_imageSet().get_fitsProperties().colorMapName); + } + }, + + loadData: function (tourDoc, filename) { + if (ss.startsWith(this._extension$1.toLowerCase(), '.fit')) { + var blob = tourDoc.getFileBlob(ss.replaceString(filename, '.txt', this._extension$1)); + var fi; + if (useGlVersion2) { + fi = new FitsImage(this._imageSet$1, 'image.fit', blob, ss.bind('doneLoading', this)); + } + else { + fi = new FitsImageJs(this._imageSet$1, 'image.fit', blob, ss.bind('doneLoading', this)); + } + this._imageSet$1.set_wcsImage(fi); + } else { + this._loaded$1 = true; + } + }, + + doneLoading: function (wcsImage) { + this._loaded$1 = true; + } +}; + +registerType("ImageSetLayer", [ImageSetLayer, ImageSetLayer$, Layer]); diff --git a/engine/esm/layers/iss_layer.js b/engine/esm/layers/iss_layer.js new file mode 100644 index 00000000..ac2e5ab8 --- /dev/null +++ b/engine/esm/layers/iss_layer.js @@ -0,0 +1,97 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that adds the International Space Station (ISS) with an up-to-date orbit. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Guid } from "../util.js"; +import { Matrix3d, Vector3d } from "../double3d.js"; +import { freestandingMode, tourDocumentFromUrlRaw } from "../data_globals.js"; +import { Colors } from "../color.js"; +import { URLHelpers } from "../url_helpers.js"; +import { Object3dLayer, Object3d } from "./object3d.js"; + + +// wwtlib.ISSLayer + +export function ISSLayer() { + Object3dLayer.call(this); + this.id = ISSLayer.issGuid; +} + +ISSLayer.issGuid = Guid.fromString('00000001-0002-0003-0405-060708090a0b'); +ISSLayer._loading$2 = false; +ISSLayer._issmodel$2 = null; +ISSLayer._doc$2 = null; + +ISSLayer.loadBackground = function () { + // The ISS frame cannot be created in freestanding mode, so I'm not + // sure if this function will even get called, but just in case, we + // make sure to noop if we're in freestanding mode. + if (ISSLayer._loading$2 || freestandingMode) { + return; + } + ISSLayer._loading$2 = true; + var url = URLHelpers.singleton.coreStaticUrl('data/iss.wtt'); + ISSLayer._doc$2 = tourDocumentFromUrlRaw(url, function () { + ISSLayer.createSpaceStation(); + }); +}; + +ISSLayer.createSpaceStation = function () { + ISSLayer._doc$2.set_id('28016047-97a9-4b33-a226-cd820262a151'); + var filename = '0c10ae54-b6da-4282-bfda-f34562d403bc.3ds'; + var o3d = new Object3d(ISSLayer._doc$2, filename, true, false, true, Colors.get_white()); + if (o3d != null) { + o3d.issLayer = true; + ISSLayer._issmodel$2 = o3d; + } +}; + +var ISSLayer$ = { + draw: function (renderContext, opacity, flat) { + if (this.object3d == null && ISSLayer._issmodel$2 == null) { + if (!ISSLayer._loading$2) { + var worldView = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + var v = worldView.transform(Vector3d.get_empty()); + var scaleFactor = Math.sqrt(worldView.get_m11() * worldView.get_m11() + worldView.get_m22() * worldView.get_m22() + worldView.get_m33() * worldView.get_m33()); + var dist = v.length(); + var radius = scaleFactor; + + // Calculate pixelsPerUnit which is the number of pixels covered + // by an object 1 AU at the distance of the planet center from + // the camera. This calculation works regardless of the projection + // type. + var viewportHeight = ss.truncate(renderContext.height); + var p11 = renderContext.get_projection().get_m11(); + var p34 = renderContext.get_projection().get_m34(); + var p44 = renderContext.get_projection().get_m44(); + var w = Math.abs(p34) * dist + p44; + var pixelsPerUnit = (p11 / w) * viewportHeight; + var radiusInPixels = (radius * pixelsPerUnit); + if (radiusInPixels > 0.5) { + ISSLayer.loadBackground(); + } + } + } + this.object3d = ISSLayer._issmodel$2; + return Object3dLayer.prototype.draw.call(this, renderContext, opacity, flat); + }, + + getPrimaryUI: function () { + return null; + }, + + addFilesToCabinet: function (fc) { + return; + }, + + loadData: function (doc, filename) { + return; + }, + + cleanUp: function () { } +}; + +registerType("ISSLayer", [ISSLayer, ISSLayer$, Object3dLayer]); diff --git a/engine/esm/layers/layer.js b/engine/esm/layers/layer.js new file mode 100644 index 00000000..486c1637 --- /dev/null +++ b/engine/esm/layers/layer.js @@ -0,0 +1,423 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Top-level information about a tour. + +import pako from "pako"; + +import { ss } from "../ss.js"; +import { registerType, registerEnum } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { Color, Colors } from "../color.js"; +import { IUiController } from "../interfaces.js"; +import { Guid } from "../util.js"; + + +// wwtlib.AltUnits + +export var AltUnits = { + meters: 1, + feet: 2, + inches: 3, + miles: 4, + kilometers: 5, + astronomicalUnits: 6, + lightYears: 7, + parsecs: 8, + megaParsecs: 9, + custom: 10 +}; + +registerType("AltUnits", AltUnits); +registerEnum("AltUnits", AltUnits); + + +// wwtlib.FadeType + +export var FadeType = { + fadeIn: 1, + fadeOut: 2, + both: 3, + none: 4 +}; + +registerType("FadeType", FadeType); +registerEnum("FadeType", FadeType); + + +// wwtlib.DomainValue + +export function DomainValue(text, markerIndex) { + this.markerIndex = 4; + this.customMarker = null; + this.text = text; + this.markerIndex = markerIndex; +} + +var DomainValue$ = {}; + +registerType("DomainValue", [DomainValue, DomainValue$, null]); + + +// wwtlib.Layer + +export function Layer() { + this.id = Guid.newGuid(); + this.loadedFromTour = false; + this.tourDocument = null; + this.opacity = 1; + this.opened = false; + this._startTime = ss.date('01/01/1900'); + this._endTime = ss.date('01/01/2100'); + this._fadeSpan = 0; + this._fadeType = 4; + this.version = 0; + this.color = Colors.get_white(); + this.enabled = true; + this.astronomical = false; +} + +var Layer$ = { + getPrimaryUI: function () { + return null; + }, + + getFileStreamUrl: function (filename) { + if (this.tourDocument != null) { + return this.tourDocument.getFileStream(filename); + } + return null; + }, + + get_opacity: function () { + return this.opacity; + }, + + set_opacity: function (value) { + if (this.opacity !== value) { + this.version++; + this.opacity = value; + } + return value; + }, + + get_opened: function () { + return this.opened; + }, + + set_opened: function (value) { + if (this.opened !== value) { + this.version++; + this.opened = value; + } + return value; + }, + + get_startTime: function () { + return this._startTime; + }, + + set_startTime: function (value) { + if (!ss.compareDates(this._startTime, value)) { + this.version++; + this._startTime = value; + } + return value; + }, + + get_endTime: function () { + return this._endTime; + }, + + set_endTime: function (value) { + if (!ss.compareDates(this._endTime, value)) { + this.version++; + this._endTime = value; + } + return value; + }, + + get_fadeSpan: function () { + return this._fadeSpan; + }, + + set_fadeSpan: function (value) { + this.version++; + this._fadeSpan = value; + return value; + }, + + get_fadeType: function () { + return this._fadeType; + }, + + set_fadeType: function (value) { + if (this._fadeType !== value) { + this.set_version(this.get_version() + 1) - 1; + this._fadeType = value; + } + return value; + }, + + get_version: function () { + return this.version; + }, + + set_version: function (value) { + this.version = value; + return value; + }, + + findClosest: function (target, distance, closestPlace, astronomical) { + return closestPlace; + }, + + hoverCheckScreenSpace: function (cursor) { + return false; + }, + + clickCheckScreenSpace: function (cursor) { + return false; + }, + + draw: function (renderContext, opacity, flat) { + return true; + }, + + preDraw: function (renderContext, opacity) { + return true; + }, + + updateData: function (data, purgeOld, purgeAll, hasHeader) { + return true; + }, + + // "updateData" used to be named this. We add this function as a + // compatibility shim just in case there's some JavaScript out there + // still using the old name. + upadteData: function (data, purgeOld, purgeAll, hasHeader) { + return this.updateData(data, purgeOld, purgeAll, hasHeader); + }, + + canCopyToClipboard: function () { + return false; + }, + + copyToClipboard: function () { + return; + }, + + getParams: function () { + var paramList = new Array(5); + paramList[0] = this.color.r / 255; + paramList[1] = this.color.g / 255; + paramList[2] = this.color.b / 255; + paramList[3] = this.color.a / 255; + paramList[4] = this.opacity; + return paramList; + }, + + setParams: function (paramList) { + if (paramList.length === 5) { + this.opacity = paramList[4]; + this.color = Color.fromArgb((paramList[3] * 255), (paramList[0] * 255), (paramList[1] * 255), (paramList[2] * 255)); + } + }, + + getParamNames: function () { + return ['Color.Red', 'Color.Green', 'Color.Blue', 'Color.Alpha', 'Opacity']; + }, + + getEditUI: function () { + return ss.safeCast(this, IUiController); + }, + + cleanUp: function () { }, + + get_name: function () { + return this._name; + }, + + set_name: function (value) { + if (this._name !== value) { + this.version++; + this._name = value; + } + return value; + }, + + toString: function () { + return this._name; + }, + + get_referenceFrame: function () { + return this.referenceFrame; + }, + + set_referenceFrame: function (value) { + this.referenceFrame = value; + return value; + }, + + getProps: function () { + return ''; + }, + + get_color: function () { + return this.color; + }, + + set_color: function (value) { + if (this.color !== value) { + this.color = value; + this.version++; + } + return value; + }, + + colorChanged: function () { }, + + get_colorValue: function () { + return this.get_color().toString(); + }, + + set_colorValue: function (value) { + this.set_color(Color.fromName(value)); + return value; + }, + + // These named accessor functions were added so that we can support + // `enabled` as a "setting" in our TypeScript framework, without breaking + // anything that might rely on `this.enabled` being a genuine bool. + get_enabled: function () { + return this.enabled; + }, + + set_enabled: function (value) { + this.enabled = value; + return value; + }, + + get_astronomical: function () { + return this.astronomical; + }, + + set_astronomical: function (value) { + if (this.astronomical !== value) { + this.version++; + this.astronomical = value; + } + return value; + }, + + getTypeName: function () { + return 'TerraViewer.Layer'; + }, + + saveToXml: function (xmlWriter) { + xmlWriter._writeStartElement('Layer'); + xmlWriter._writeAttributeString('Id', this.id.toString()); + xmlWriter._writeAttributeString('Type', this.getTypeName()); + xmlWriter._writeAttributeString('Name', this.get_name()); + xmlWriter._writeAttributeString('ReferenceFrame', this.referenceFrame); + xmlWriter._writeAttributeString('Color', this.color.save()); + xmlWriter._writeAttributeString('Opacity', this.opacity.toString()); + xmlWriter._writeAttributeString('StartTime', Util.xmlDate(this.get_startTime())); + xmlWriter._writeAttributeString('EndTime', Util.xmlDate(this.get_endTime())); + xmlWriter._writeAttributeString('FadeSpan', this.get_fadeSpan().toString()); + xmlWriter._writeAttributeString('FadeType', this.get_fadeType().toString()); + this.writeLayerProperties(xmlWriter); + xmlWriter._writeEndElement(); + }, + + writeLayerProperties: function (xmlWriter) { + return; + }, + + initializeFromXml: function (node) { }, + + initFromXml: function (node) { + this.id = Guid.fromString(node.attributes.getNamedItem('Id').nodeValue); + this.set_name(node.attributes.getNamedItem('Name').nodeValue); + this.referenceFrame = node.attributes.getNamedItem('ReferenceFrame').nodeValue; + this.color = Color.load(node.attributes.getNamedItem('Color').nodeValue); + this.opacity = parseFloat(node.attributes.getNamedItem('Opacity').nodeValue); + if (node.attributes.getNamedItem('StartTime') != null) { + this.set_startTime(new Date(node.attributes.getNamedItem('StartTime').nodeValue)); + } + if (node.attributes.getNamedItem('EndTime') != null) { + this.set_endTime(new Date(node.attributes.getNamedItem('EndTime').nodeValue)); + } + if (node.attributes.getNamedItem('FadeSpan') != null) { + this.set_fadeSpan(Util.parseTimeSpan(node.attributes.getNamedItem('FadeSpan').nodeValue)); + } + if (node.attributes.getNamedItem('FadeType') != null) { + switch (node.attributes.getNamedItem('FadeType').nodeValue) { + case 'In': + this.set_fadeType(1); + break; + case 'Out': + this.set_fadeType(2); + break; + case 'Both': + this.set_fadeType(3); + break; + case 'None': + this.set_fadeType(4); + break; + default: + break; + } + } + this.initializeFromXml(node); + }, + + loadData: function (doc, filename) { + return; + }, + + addFilesToCabinet: function (fc) { + return; + }, + + // This method decompresses a blob into a string, and if the string cannot be decompressed + // due to an invalid header, we assume the blob is not compressed and return the string + // as-is. + getStringFromGzipBlob: function (blob, dataReady) { + var reader = new FileReader(); + reader.onloadend = function (e) { + var result = ''; + try { + result = pako.inflate(e.target.result, { to: 'string' }); + } + catch (err) { + var errString = err.toString(); + if (errString === 'incorrect header check' || errString === 'unknown compression method') { + result = String.fromCharCode.apply(null, new Uint8Array(e.target.result)); + } + else { + throw err; + } + } + dataReady(result); + }; + reader.readAsArrayBuffer(blob); + } +}; + +registerType("Layer", [Layer, Layer$, null]); + + +// wwtlib.LayerCollection + +export function LayerCollection() { + Layer.call(this); +} + +var LayerCollection$ = { + draw: function (renderContext, opacity, flat) { + return Layer.prototype.draw.call(this, renderContext, opacity, false); + } +}; + +registerType("LayerCollection", [LayerCollection, LayerCollection$, Layer]); diff --git a/engine/esm/layers/layer_manager.js b/engine/esm/layers/layer_manager.js new file mode 100644 index 00000000..380153f5 --- /dev/null +++ b/engine/esm/layers/layer_manager.js @@ -0,0 +1,1747 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Managing the tree of renderer layers. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { + freestandingMode, + globalScriptInterface, + globalWWTControl, + set_layerManagerGetAllMaps, + set_setManagerVisibleLayerList, +} from "../data_globals.js"; +import { globalRenderContext } from "../render_globals.js"; +import { Vector2d, Vector3d, Matrix3d } from "../double3d.js"; +import { ELL } from "../astrocalc/elliptical.js"; +import { Histogram } from "../utilities/histogram.js"; +import { SimpleInput } from "../utilities/simple_input.js"; +import { ColorPicker } from "../utilities/color_picker.js"; +import { ContextMenuStrip, ToolStripMenuItem, ToolStripSeparator } from "../utilities/context_menu_strip.js"; +import { Color } from "../color.js"; +import { FitsImage } from "./fits_image.js"; +import { ProjectionType } from "../imageset.js"; +import { Planets } from "../planets.js"; +import { Settings } from "../settings.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { URLHelpers } from "../url_helpers.js"; +import { Cursor, Language } from "../util.js"; +import { WebFile } from "../web_file.js"; +import { Layer } from "./layer.js"; +import { ReferenceFrame } from "./reference_frame.js"; +import { GreatCirlceRouteLayer } from "./great_circle_route_layer.js"; +import { GridLayer } from "./grid_layer.js"; +import { ImageSetLayer } from "./imageset_layer.js"; +import { ISSLayer } from "./iss_layer.js"; +import { Orbit } from "./orbit.js"; +import { OrbitLayer } from "./orbit_layer.js"; +import { SpreadSheetLayer, PushPin } from "./spreadsheet_layer.js"; +import { VoTableLayer } from "./vo_table_layer.js"; +import { LayerInfo } from "../tours/tour_stop.js"; +import { TourPlayer } from "../tours/tour_player.js"; + + +// wwtlib.ReferenceFrames + +export var ReferenceFrames = { + sky: 0, + ecliptic: 1, + galactic: 2, + sun: 3, + mercury: 4, + venus: 5, + earth: 6, + mars: 7, + jupiter: 8, + saturn: 9, + uranus: 10, + neptune: 11, + pluto: 12, + moon: 13, + io: 14, + europa: 15, + ganymede: 16, + callisto: 17, + custom: 18, + identity: 19, + sandbox: 20 +}; + +registerType("ReferenceFrames", ReferenceFrames); +registerEnum("ReferenceFrames", ReferenceFrames); + + +// wwtlib.LayerManager + +export function LayerManager() { } + +LayerManager._version = 0; +LayerManager._tourLayers = false; +LayerManager._layerMaps = {}; +LayerManager._layerMapsTours = {}; +LayerManager._allMaps = {}; +LayerManager._allMapsTours = {}; +LayerManager._currentMap = 'Earth'; +LayerManager._layerList = {}; +LayerManager._layerListTours = {}; +LayerManager._moonfile = ''; +LayerManager._selectedLayer = null; +LayerManager._lastMenuClick = new Vector2d(); + +LayerManager.get_version = function () { + return LayerManager._version; +}; + +LayerManager.set_version = function (value) { + LayerManager._version = value; + return value; +}; + +LayerManager.get_frameWizardDialog = function () { + return LayerManager._frameWizardDialog; +}; + +LayerManager.get_dataVizWizardDialog = function () { + return LayerManager._dataVizWizardDialog; +}; + +LayerManager.get_referenceFramePropsDialog = function () { + return LayerManager._referenceFramePropsDialog; +}; + +LayerManager.get_greatCircleDlg = function () { + return LayerManager._greatCircleDialog; +}; + +LayerManager.get_tourLayers = function () { + return LayerManager._tourLayers; +}; + +LayerManager.set_tourLayers = function (value) { + if (LayerManager._tourLayers !== value && !value) { + LayerManager._clearLayers(); + LayerManager._tourLayers = value; + LayerManager.loadTree(); + } + else if (LayerManager._tourLayers !== value && !!value) { + LayerManager._tourLayers = value; + LayerManager.initLayers(); + } + return value; +}; + +LayerManager.loadTree = function () { + if (globalScriptInterface != null) { + globalScriptInterface.refreshLayerManagerNow(); + } +}; + +LayerManager.get_layerMaps = function () { + if (LayerManager.get_tourLayers()) { + return LayerManager._layerMapsTours; + } + else { + return LayerManager._layerMaps; + } +}; + +LayerManager.set_layerMaps = function (value) { + if (LayerManager.get_tourLayers()) { + LayerManager._layerMapsTours = value; + } + else { + LayerManager._layerMaps = value; + } + return value; +}; + +LayerManager.get_allMaps = function () { + if (LayerManager.get_tourLayers()) { + return LayerManager._allMapsTours; + } + else { + return LayerManager._allMaps; + } +}; + +set_layerManagerGetAllMaps(LayerManager.get_allMaps); + +LayerManager.set_allMaps = function (value) { + if (LayerManager.get_tourLayers()) { + LayerManager._allMapsTours = value; + } + else { + LayerManager._allMaps = value; + } + return value; +}; + +LayerManager.get_currentMap = function () { + return LayerManager._currentMap; +}; + +LayerManager.set_currentMap = function (value) { + LayerManager._currentMap = value; + return value; +}; + +LayerManager.get_layerList = function () { + if (LayerManager.get_tourLayers()) { + return LayerManager._layerListTours; + } + else { + return LayerManager._layerList; + } +}; + +LayerManager.set_layerList = function (value) { + if (LayerManager.get_tourLayers()) { + LayerManager._layerListTours = value; + } + else { + LayerManager._layerList = value; + } + return value; +}; + +// This function *can* be called multiple times safely, but it only +// needs to be called once upon app startup. The `InitLayers` function +// can be called more than once, if/when the `TourLayers` setting is +// toggled. +LayerManager.oneTimeInitialization = function () { + if (LayerManager._webFileMoons == null) { + LayerManager.getMoonFile(URLHelpers.singleton.engineAssetUrl('moons.txt')); + } + PushPin.triggerLoadSprite(); +}; + +LayerManager.initLayers = function () { + LayerManager._clearLayers(); + var iss = null; + var doISS = !LayerManager.get_tourLayers() && !freestandingMode; + if (doISS) { + iss = new LayerMap('ISS', 18); + iss.frame.epoch = SpaceTimeController._twoLineDateToJulian('10184.51609218'); + iss.frame.semiMajorAxis = 6728829.41; + iss.frame.referenceFrameType = 1; + iss.frame.inclination = 51.6442; + iss.frame.longitudeOfAscendingNode = 147.0262; + iss.frame.eccentricity = 0.0009909; + iss.frame.meanAnomolyAtEpoch = 325.5563; + iss.frame.meanDailyMotion = 360 * 15.72172655; + iss.frame.argumentOfPeriapsis = 286.4623; + iss.frame.scale = 1; + iss.frame.semiMajorAxisUnits = 1; + iss.frame.meanRadius = 130; + iss.frame.oblateness = 0; + iss.frame.showOrbitPath = true; + var isstle = new Array(0); + + //This is downloaded now on startup + var url = URLHelpers.singleton.coreDynamicUrl('wwtweb/isstle.aspx'); + var webFile; + webFile = new WebFile(url); + webFile.onStateChange = function () { + if (webFile.get_state() === 1) { + var data = webFile.getText(); + isstle = data.split('\n'); + if (isstle.length > 1) { + iss.frame.fromTLE(isstle[0], isstle[1], 398600441800000); + } + } + }; + webFile.send(); + iss.enabled = true; + } + LayerManager.get_layerMaps()['Sun'] = new LayerMap('Sun', 3); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Mercury', 4)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Venus', 5)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Earth', 6)); + LayerManager.get_layerMaps()['Sun'].childMaps['Earth'].addChild(new LayerMap('Moon', 13)); + if (doISS) { + LayerManager.get_layerMaps()['Sun'].childMaps['Earth'].addChild(iss); + } + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Mars', 7)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Jupiter', 8)); + LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Io', 14)); + LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Europa', 15)); + LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Ganymede', 16)); + LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Callisto', 17)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Saturn', 9)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Uranus', 10)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Neptune', 11)); + LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Pluto', 12)); + LayerManager._addMoons(LayerManager._moonfile); + LayerManager.get_layerMaps()['Sky'] = new LayerMap('Sky', 0); + LayerManager.get_layerMaps()['Sun'].open = true; + LayerManager._allMaps = {}; + LayerManager._addAllMaps(LayerManager.get_layerMaps(), null); + if (doISS) { + LayerManager._addIss(); + } + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._addIss = function () { + var layer = new ISSLayer(); + layer.set_name(Language.getLocalizedText(1314, 'ISS Model (Toshiyuki Takahei)')); + layer.enabled = Settings.get_active().get_showISSModel(); + LayerManager.get_layerList()[layer.id] = layer; + layer.set_referenceFrame('ISS'); + LayerManager.get_allMaps()['ISS'].layers.push(layer); + LayerManager.get_allMaps()['ISS'].open = true; +}; + +LayerManager._addAllMaps = function (maps, parent) { + var $enum1 = ss.enumerate(ss.keys(maps)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var map = maps[key]; + map.frame.parent = parent; + LayerManager.get_allMaps()[map.get_name()] = map; + LayerManager._addAllMaps(map.childMaps, map.get_name()); + } +}; + +LayerManager._clearLayers = function () { + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var layer = LayerManager.get_layerList()[key]; + layer.cleanUp(); + } + ss.clearKeys(LayerManager.get_layerList()); + ss.clearKeys(LayerManager.get_layerMaps()); +}; + +LayerManager.getMoonFile = function (url) { + LayerManager._webFileMoons = new WebFile(url); + LayerManager._webFileMoons.onStateChange = LayerManager.moonFileStateChange; + LayerManager._webFileMoons.send(); +}; + +LayerManager.moonFileStateChange = function () { + if (LayerManager._webFileMoons.get_state() === 2) { + alert(LayerManager._webFileMoons.get_message()); + } + else if (LayerManager._webFileMoons.get_state() === 1) { + LayerManager._moonfile = LayerManager._webFileMoons.getText(); + LayerManager.initLayers(); + } +}; + +LayerManager._addMoons = function (file) { + var data = file.split('\r\n'); + var first = true; + var $enum1 = ss.enumerate(data); + while ($enum1.moveNext()) { + var line = $enum1.current; + if (first) { + first = false; + continue; + } + var parts = line.split('\t'); + if (parts.length > 16) { + var planet = parts[0]; + var frame = new LayerMap(parts[2], 18); + frame.frame._systemGenerated = true; + frame.frame.epoch = parseFloat(parts[1]); + frame.frame.semiMajorAxis = parseFloat(parts[3]) * 1000; + frame.frame.referenceFrameType = 1; + frame.frame.inclination = parseFloat(parts[7]); + frame.frame.longitudeOfAscendingNode = parseFloat(parts[8]); + frame.frame.eccentricity = parseFloat(parts[4]); + frame.frame.meanAnomolyAtEpoch = parseFloat(parts[6]); + frame.frame.meanDailyMotion = parseFloat(parts[9]); + frame.frame.argumentOfPeriapsis = parseFloat(parts[5]); + frame.frame.scale = 1; + frame.frame.semiMajorAxisUnits = 1; + frame.frame.meanRadius = parseFloat(parts[16]) * 1000; + frame.frame.rotationalPeriod = parseFloat(parts[17]); + frame.frame.showAsPoint = false; + frame.frame.showOrbitPath = true; + frame.frame.set_representativeColor(Color.fromArgb(255, 175, 216, 230)); + frame.frame.oblateness = 0; + LayerManager.get_layerMaps()['Sun'].childMaps[planet].addChild(frame); + } + } +}; + +LayerManager.addVoTableLayer = function (table, title) { + return LayerManager.addVoTableLayerWithPlotType(table, title, 2); +}; + +LayerManager.addVoTableLayerWithPlotType = function (table, title, plotType) { + var layer = VoTableLayer.create(table, plotType); + layer.set_name(title); + layer.set_astronomical(true); + layer.set_referenceFrame('Sky'); + LayerManager.get_layerList()[layer.id] = layer; + LayerManager.get_allMaps()['Sky'].layers.push(layer); + LayerManager.get_allMaps()['Sky'].open = true; + layer.enabled = true; + LayerManager._version++; + LayerManager.loadTree(); + return layer; +}; + +LayerManager.addImageSetLayer = function (imageset, title) { + var layer = ImageSetLayer.create(imageset); + return LayerManager.addFitsImageSetLayer(layer, title); +}; + +LayerManager.addImageSetLayerCallback = function (imageset, title, callback) { + var layer = ImageSetLayer.create(imageset); + + // The tile rendering codepaths require that "Extension" is exactly + // .fits -- multiple extensions are not currently supported. + var isNonHipsTiledFits = + imageset.get_extension() === '.fits' && + layer.getFitsImage() == null && + imageset.get_projection() !== ProjectionType.healpix; + + // The goal here is to fire the callback once the initial imageset + // data have loaded. In particular, for FITS-type imagesets, we + // inevitably need to download some data in order to figure out + // parameters like FitsProperties.LowerCut. + // + // At the moment, this is only wired up correctly for non-HiPS tiled + // FITS. In a pretty egregious hack, the OnMainImageLoaded callback + // below will be fired once the level-0 FITS tile is loaded. We + // basically needed to add this new callback hook because there + // wasn't any other way to get something to fire when the level-0 + // tile data actually arrive. + // + // HiPS FITS datasets will *eventually* get the right FitsProperties + // because the fetch of the HipsProperties data sets this up. (This + // is triggered by the HipsProperties constructor, used in + // Imageset.GetNewTile.) But the timing of the callback here is + // uncorrelated with that process. The same is broadly true for + // untiled FITS. This function should be improved to make sure that + // the callback argument gets fired at the right time for such + // datasets. + + if (isNonHipsTiledFits) { + imageset.get_fitsProperties().onMainImageLoaded = function (image) { + image.applyDisplaySettings(); + if (callback != null) { + callback(layer); + } + }; + } + LayerManager.addFitsImageSetLayer(layer, title); + + // For everything not yet handled, just trigger the callback now, if + // needed. + if (callback != null && (!isNonHipsTiledFits || imageset.get_fitsProperties().mainImageLoadedEventHasFired)) { + callback(layer); + } + + return layer; +}; + +// This method is somewhat misnamed - there's nothing FITS-specific about it. +LayerManager.addFitsImageSetLayer = function (layer, title) { + layer.doneLoading(null); + layer.set_name(title); + layer.set_astronomical(true); + layer.set_referenceFrame('Sky'); + LayerManager.get_layerList()[layer.id] = layer; + LayerManager.get_allMaps()['Sky'].layers.push(layer); + LayerManager.get_allMaps()['Sky'].open = true; + layer.enabled = true; + LayerManager._version++; + LayerManager.loadTree(); + return layer; +}; + +LayerManager.getNextFitsName = function () { + return LayerManager._getNextName('Fits Image'); +}; + +LayerManager.getNextImageSetName = function () { + return LayerManager._getNextName('Image Set'); +}; + +LayerManager._getNextName = function (type) { + var currentNumber = 0; + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var $enum2 = ss.enumerate(LayerManager.get_allMaps()[key].layers); + while ($enum2.moveNext()) { + var layer = $enum2.current; + if (ss.startsWith(layer.get_name(), type + ' ')) { + var number = ss.replaceString(layer.get_name(), type + ' ', ''); + try { + var num = parseInt(number); + if (num > currentNumber) { + currentNumber = num; + } + } + catch ($e3) { + } + } + } + } + return ss.format('{0} {1}', type, currentNumber + 1); +}; + +LayerManager._closeAllTourLoadedLayers = function () { + var purgeTargets = []; + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var layer = LayerManager.get_layerList()[key]; + if (layer.loadedFromTour) { + purgeTargets.push(layer.id); + } + } + var $enum2 = ss.enumerate(purgeTargets); + while ($enum2.moveNext()) { + var guid = $enum2.current; + LayerManager.deleteLayerByID(guid, true, false); + } + var purgeMapsNames = []; + var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); + while ($enum3.moveNext()) { + var key = $enum3.current; + var map = LayerManager.get_allMaps()[key]; + if (map.loadedFromTour && !map.layers.length) { + purgeMapsNames.push(map.get_name()); + } + } + var $enum4 = ss.enumerate(purgeMapsNames); + while ($enum4.moveNext()) { + var name = $enum4.current; + LayerManager.purgeLayerMapDeep(LayerManager.get_allMaps()[name], true); + } + LayerManager.set_version(LayerManager.get_version() + 1) - 1; + LayerManager.loadTree(); +}; + +LayerManager.purgeLayerMapDeep = function (target, topLevel) { + var $enum1 = ss.enumerate(target.layers); + while ($enum1.moveNext()) { + var layer = $enum1.current; + LayerManager.deleteLayerByID(layer.id, false, false); + } + target.layers.length = 0; + var $enum2 = ss.enumerate(ss.keys(target.childMaps)); + while ($enum2.moveNext()) { + var key = $enum2.current; + var map = target.childMaps[key]; + LayerManager.purgeLayerMapDeep(map, false); + } + ss.clearKeys(target.childMaps); + if (topLevel) { + if (!ss.emptyString(target.frame.parent)) { + if (ss.keyExists(LayerManager.get_allMaps(), target.frame.parent)) { + delete LayerManager.get_allMaps()[target.frame.parent].childMaps[target.get_name()]; + } + } else { + if (ss.keyExists(LayerManager.get_layerMaps(), target.get_name())) { + delete LayerManager.get_layerMaps()[target.get_name()]; + } + } + } + delete LayerManager.get_allMaps()[target.get_name()]; + LayerManager._version++; +}; + +LayerManager._cleanAllTourLoadedLayers = function () { + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var layer = LayerManager.get_layerList()[key]; + if (layer.loadedFromTour) { + layer.loadedFromTour = false; + } + } +}; + +// Merge layers from Tour Player Alternate universe into the real layer manager layers list +LayerManager.mergeToursLayers = function () { + LayerManager._tourLayers = false; + var OverWrite = false; + var CollisionChecked = false; + var $enum1 = ss.enumerate(ss.keys(LayerManager._allMapsTours)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var map = LayerManager._allMapsTours[key]; + if (!ss.keyExists(LayerManager._allMaps, map.get_name())) { + var newMap = new LayerMap(map.get_name(), 18); + newMap.frame = map.frame; + newMap.loadedFromTour = true; + LayerManager.get_allMaps()[newMap.get_name()] = newMap; + } + } + LayerManager.connectAllChildren(); + var $enum2 = ss.enumerate(ss.keys(LayerManager._layerListTours)); + while ($enum2.moveNext()) { + var key = $enum2.current; + var layer = LayerManager._layerListTours[key]; + if (ss.keyExists(LayerManager.get_layerList(), layer.id)) { + if (!CollisionChecked) { + OverWrite = true; + CollisionChecked = true; + } + if (OverWrite) { + LayerManager.deleteLayerByID(layer.id, true, false); + } + } + if (!ss.keyExists(LayerManager.get_layerList(), layer.id)) { + if (ss.keyExists(LayerManager.get_allMaps(), layer.get_referenceFrame())) { + LayerManager.get_layerList()[layer.id] = layer; + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); + } + } else { + layer.cleanUp(); + } + } + ss.clearKeys(LayerManager._layerListTours); + ss.clearKeys(LayerManager._allMapsTours); + ss.clearKeys(LayerManager._layerMapsTours); + LayerManager.loadTree(); +}; + +LayerManager.connectAllChildren = function () { + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var map = LayerManager.get_allMaps()[key]; + if (ss.emptyString(map.frame.parent) && !ss.keyExists(LayerManager.get_layerMaps(), map.frame.name)) { + LayerManager.get_layerMaps()[map.get_name()] = map; + } else if (!ss.emptyString(map.frame.parent) && ss.keyExists(LayerManager.get_allMaps(), map.frame.parent)) { + if (!ss.keyExists(LayerManager.get_allMaps()[map.frame.parent].childMaps, map.frame.name)) { + LayerManager.get_allMaps()[map.frame.parent].childMaps[map.frame.name] = map; + map.parent = LayerManager.get_allMaps()[map.frame.parent]; + } + } + } +}; + +LayerManager.deleteLayerByID = function (ID, removeFromParent, updateTree) { + if (ss.keyExists(LayerManager.get_layerList(), ID)) { + var layer = LayerManager.get_layerList()[ID]; + layer.cleanUp(); + if (removeFromParent) { + ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); + } + delete LayerManager.get_layerList()[ID]; + LayerManager._version++; + if (updateTree) { + LayerManager.loadTree(); + } + return true; + } + else { + return false; + } +}; + +LayerManager._getFrameTarget = function (renderContext, TrackingFrame) { + var target = new FrameTarget(); + var targetPoint = Vector3d.get_empty(); + target.target = Vector3d.get_empty(); + target.matrix = Matrix3d.get_identity(); + if (!ss.keyExists(LayerManager.get_allMaps(), TrackingFrame)) { + return target; + } + var mapList = []; + var current = LayerManager.get_allMaps()[TrackingFrame]; + mapList.push(current); + while (current.frame.reference === 18) { + current = current.parent; + mapList.splice(0, 0, current); + } + var matOld = renderContext.get_world().clone(); + var matOldNonRotating = renderContext.get_worldBaseNonRotating(); + var matOldBase = renderContext.get_worldBase(); + var oldNominalRadius = renderContext.get_nominalRadius(); + var $enum1 = ss.enumerate(mapList); + while ($enum1.moveNext()) { + var map = $enum1.current; + if (map.frame.reference !== 18 && map.frame.reference !== 20) { + Planets.setupPlanetMatrix(renderContext, Enums.parse('SolarSystemObjects', map.frame.name), Vector3d.get_empty(), false); + } else { + map.computeFrame(renderContext); + if (map.frame.useRotatingParentFrame()) { + renderContext.set_world(Matrix3d.multiplyMatrix(map.frame.worldMatrix, renderContext.get_world())); + } + else { + renderContext.set_world(Matrix3d.multiplyMatrix(map.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); + } + if (map.frame.referenceFrameType === 3) { + renderContext.set_worldBaseNonRotating(renderContext.get_world().clone()); + } + renderContext.set_nominalRadius(map.frame.meanRadius); + } + } + targetPoint = renderContext.get_world().transform(targetPoint); + var lookAt = renderContext.get_world().transform(Vector3d.create(0, 0, 1)); + var lookUp = Vector3d.subtractVectors(renderContext.get_world().transform(Vector3d.create(0, 1, 0)), targetPoint); + lookUp.normalize(); + target.matrix = Matrix3d.lookAtLH(new Vector3d(), Vector3d.subtractVectors(lookAt, targetPoint), lookUp); + renderContext.set_nominalRadius(oldNominalRadius); + renderContext.set_world(matOld); + renderContext.set_worldBaseNonRotating(matOldNonRotating); + renderContext.set_worldBase(matOldBase); + target.target = targetPoint; + return target; +}; + +LayerManager._prepTourLayers = function () { + if (TourPlayer.get_playing()) { + var player = globalWWTControl.uiController; + if (player != null) { + var tour = player.get_tour(); + if (tour.get_currentTourStop() != null) { + player.updateTweenPosition(-1); + if (!tour.get_currentTourStop().get_keyFramed()) { + tour.get_currentTourStop()._updateLayerOpacity(); + var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var info = tour.get_currentTourStop().layers[key]; + if (ss.keyExists(LayerManager.get_layerList(), info.id)) { + LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); + LayerManager.get_layerList()[info.id].setParams(info.frameParams); + } + } + } + } + } + } +}; + +LayerManager._draw = function (renderContext, opacity, astronomical, referenceFrame, nested, cosmos) { + if (!ss.keyExists(LayerManager.get_allMaps(), referenceFrame)) { + return; + } + var thisMap = LayerManager.get_allMaps()[referenceFrame]; + if (!thisMap.enabled || (!ss.keyCount(thisMap.childMaps) && !thisMap.layers.length && !(thisMap.frame.showAsPoint || thisMap.frame.showOrbitPath))) { + return; + } + if (TourPlayer.get_playing()) { + var player = globalWWTControl.uiController; + if (player != null) { + var tour = player.get_tour(); + if (tour.get_currentTourStop() != null) { + player.updateTweenPosition(-1); + tour.get_currentTourStop()._updateLayerOpacity(); + var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var info = tour.get_currentTourStop().layers[key]; + if (ss.keyExists(LayerManager.get_layerList(), info.id)) { + LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); + LayerManager.get_layerList()[info.id].setParams(info.frameParams); + } + } + } + } + } + var matOld = renderContext.get_world(); + var matOldNonRotating = renderContext.get_worldBaseNonRotating(); + var oldNominalRadius = renderContext.get_nominalRadius(); + if ((thisMap.frame.reference === 18 | thisMap.frame.reference === 18) === 1) { + thisMap.computeFrame(renderContext); + if (thisMap.frame.referenceFrameType !== 1 && thisMap.frame.referenceFrameType !== 2) { + renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_world())); + } else { + renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); + } + renderContext.set_nominalRadius(thisMap.frame.meanRadius); + } + if (thisMap.frame.showAsPoint) { + // todo Draw point planet... + // Planets.DrawPointPlanet(renderContext.Device, new Vector3d(0, 0, 0), (float).2, thisMap.Frame.RepresentativeColor, true); + } + for (var pass = 0; pass < 2; pass++) { + var $enum2 = ss.enumerate(LayerManager.get_allMaps()[referenceFrame].layers); + while ($enum2.moveNext()) { + var layer = $enum2.current; + if ((!pass && ss.canCast(layer, ImageSetLayer)) || (pass === 1 && !(ss.canCast(layer, ImageSetLayer)))) { + var skipLayer = false; + if (!pass) { + // Skip default image set layer so that it's not drawn twice + skipLayer = !astronomical && (layer).get_overrideDefaultLayer(); + } + if (layer.enabled && !skipLayer) { + var layerStart = SpaceTimeController.utcToJulian(layer.get_startTime()); + var layerEnd = SpaceTimeController.utcToJulian(layer.get_endTime()); + var fadeIn = SpaceTimeController.utcToJulian(layer.get_startTime()) - ((layer.get_fadeType() === 1 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); + var fadeOut = SpaceTimeController.utcToJulian(layer.get_endTime()) + ((layer.get_fadeType() === 2 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); + if (SpaceTimeController.get_jNow() > fadeIn && SpaceTimeController.get_jNow() < fadeOut) { + var fadeOpacity = 1; + if (SpaceTimeController.get_jNow() < layerStart) { + fadeOpacity = ((SpaceTimeController.get_jNow() - fadeIn) / (layer.get_fadeSpan() / 864000000)); + } + if (SpaceTimeController.get_jNow() > layerEnd) { + fadeOpacity = ((fadeOut - SpaceTimeController.get_jNow()) / (layer.get_fadeSpan() / 864000000)); + } + layer.set_astronomical(astronomical); + if (ss.canCast(layer, SpreadSheetLayer)) { + var tsl = ss.safeCast(layer, SpreadSheetLayer); + tsl.draw(renderContext, opacity * fadeOpacity, cosmos); + } + else { + layer.draw(renderContext, opacity * fadeOpacity, cosmos); + } + } + } + } + } + } + if (nested) { + var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps()[referenceFrame].childMaps)); + while ($enum3.moveNext()) { + var key = $enum3.current; + var map = LayerManager.get_allMaps()[referenceFrame].childMaps[key]; + if (!(ss.canCast(map, LayerMap))) { + continue; + } + if (map.enabled && map.frame.showOrbitPath && Settings.get_active().get_solarSystemOrbits() && Settings.get_active().get_solarSystemMinorOrbits()) { + if (map.frame.referenceFrameType === 1) { + if (map.frame.get_orbit() == null) { + map.frame.set_orbit(new Orbit(map.frame.get_elements(), 360, map.frame.get_representativeColor(), 1, map.parent.frame.meanRadius)); + } + var matSaved = renderContext.get_world(); + renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); + map.frame.get_orbit().draw3D(renderContext, 1 * 0.5, Vector3d.create(0, 0, 0)); + renderContext.set_world(matSaved); + } + else if (map.frame.referenceFrameType === 2) { + } + } + if ((map.frame.reference === 18 || map.frame.reference === 19)) { + LayerManager._draw(renderContext, opacity, astronomical, map.get_name(), nested, cosmos); + } + } + } + renderContext.set_nominalRadius(oldNominalRadius); + renderContext.set_world(matOld); + renderContext.set_worldBaseNonRotating(matOldNonRotating); +}; + +LayerManager._getVisibleLayerList = function (previous) { + var list = {}; + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var layer = LayerManager.get_layerList()[key]; + if (layer.enabled) { + var info = new LayerInfo(); + info.startOpacity = info.endOpacity = layer.get_opacity(); + info.id = layer.id; + info.startParams = layer.getParams(); + if (ss.keyExists(previous, info.id)) { + info.endOpacity = previous[info.id].endOpacity; + info.endParams = previous[info.id].endParams; + } + else { + info.endParams = layer.getParams(); + } + list[layer.id] = info; + } + } + return list; +}; + +LayerManager.setVisibleLayerList = function (list) { + var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var layer = LayerManager.get_layerList()[key]; + layer.enabled = ss.keyExists(list, layer.id); + try { + if (layer.enabled) { + layer.set_opacity(list[layer.id].frameOpacity); + layer.setParams(list[layer.id].frameParams); + } + } + catch ($e2) { + } + } +}; + +set_setManagerVisibleLayerList(LayerManager.setVisibleLayerList); + +LayerManager._preDraw = function (renderContext, opacity, astronomical, referenceFrame, nested) { + if (!ss.keyExists(LayerManager.get_allMaps(), referenceFrame)) { + return; + } + var thisMap = LayerManager.get_allMaps()[referenceFrame]; + if (!ss.keyCount(thisMap.childMaps) && !thisMap.layers.length) { + return; + } + if (TourPlayer.get_playing()) { + var player = ss.safeCast(globalWWTControl.uiController, TourPlayer); + if (player != null) { + var tour = player.get_tour(); + if (tour.get_currentTourStop() != null) { + player.updateTweenPosition(-1); + tour.get_currentTourStop()._updateLayerOpacity(); + var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var info = tour.get_currentTourStop().layers[key]; + if (ss.keyExists(LayerManager.get_layerList(), info.id)) { + LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); + LayerManager.get_layerList()[info.id].setParams(info.frameParams); + } + } + } + } + } + var matOld = renderContext.get_world(); + var matOldNonRotating = renderContext.get_worldBaseNonRotating(); + var oldNominalRadius = renderContext.get_nominalRadius(); + if (thisMap.frame.reference === 18) { + thisMap.computeFrame(renderContext); + if (thisMap.frame.referenceFrameType !== 1) { + renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_world())); + } else { + renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); + } + renderContext.set_nominalRadius(thisMap.frame.meanRadius); + } + for (var pass = 0; pass < 2; pass++) { + var $enum2 = ss.enumerate(LayerManager.get_allMaps()[referenceFrame].layers); + while ($enum2.moveNext()) { + var layer = $enum2.current; + if ((!pass && ss.canCast(layer, ImageSetLayer)) || (pass === 1 && !(ss.canCast(layer, ImageSetLayer)))) { + if (layer.enabled) { + var layerStart = SpaceTimeController.utcToJulian(layer.get_startTime()); + var layerEnd = SpaceTimeController.utcToJulian(layer.get_endTime()); + var fadeIn = SpaceTimeController.utcToJulian(layer.get_startTime()) - ((layer.get_fadeType() === 1 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); + var fadeOut = SpaceTimeController.utcToJulian(layer.get_endTime()) + ((layer.get_fadeType() === 2 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); + if (SpaceTimeController.get_jNow() > fadeIn && SpaceTimeController.get_jNow() < fadeOut) { + var fadeOpacity = 1; + if (SpaceTimeController.get_jNow() < layerStart) { + fadeOpacity = ((SpaceTimeController.get_jNow() - fadeIn) / (layer.get_fadeSpan() / 864000000)); + } + if (SpaceTimeController.get_jNow() > layerEnd) { + fadeOpacity = ((fadeOut - SpaceTimeController.get_jNow()) / (layer.get_fadeSpan() / 864000000)); + } + if (!thisMap.frame.reference) { + layer.set_astronomical(true); + } + layer.preDraw(renderContext, opacity * fadeOpacity); + } + } + } + } + } + if (nested) { + var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps()[referenceFrame].childMaps)); + while ($enum3.moveNext()) { + var key = $enum3.current; + var map = LayerManager.get_allMaps()[referenceFrame].childMaps[key]; + if ((map.frame.reference === 18 || map.frame.reference === 19)) { + LayerManager._preDraw(renderContext, opacity, astronomical, map.get_name(), nested); + } + } + } + renderContext.set_nominalRadius(oldNominalRadius); + renderContext.set_world(matOld); + renderContext.set_worldBaseNonRotating(matOldNonRotating); +}; + +LayerManager.add = function (layer, updateTree) { + if (!ss.keyExists(LayerManager.get_layerList(), layer.id)) { + if (ss.keyExists(LayerManager.get_allMaps(), layer.get_referenceFrame())) { + LayerManager.get_layerList()[layer.id] = layer; + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); + LayerManager._version++; + if (updateTree) { + LayerManager.loadTree(); + } + } + } +}; + +LayerManager.layerSelectionChanged = function (selected) { + LayerManager._selectedLayer = selected; + if (LayerManager._selectedLayer != null) { + if (ss.canCast(LayerManager._selectedLayer, LayerMap)) { + var map = ss.safeCast(LayerManager._selectedLayer, LayerMap); + if (map != null) { + LayerManager.set_currentMap(map.get_name()); + } + } else { + var layer = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); + if (layer != null && ss.canCast(layer.get_imageSet().get_wcsImage(), FitsImage)) { + return; + } + } + } + globalScriptInterface.setTimeSlider('left', ''); + globalScriptInterface.setTimeSlider('right', ''); + globalScriptInterface.setTimeSlider('title', Language.getLocalizedText(667, 'Time Scrubber')); +}; + +//Fits time slider not implemented for webgl engine (only Windows version) +LayerManager.setTimeSliderValue = function (pos) { + var layer = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); + if (layer != null && ss.canCast(layer.get_imageSet().get_wcsImage(), FitsImage)) { } +}; + +LayerManager.showLayerMenu = function (selected, x, y) { + LayerManager._lastMenuClick = Vector2d.create(x, y); + LayerManager._selectedLayer = selected; + if (ss.canCast(selected, LayerMap)) { + LayerManager.set_currentMap((selected).get_name()); + } + else if (ss.canCast(selected, Layer)) { + LayerManager.set_currentMap((selected).get_referenceFrame()); + } + if (((ss.canCast(selected, Layer)) && !(ss.canCast(selected, SkyOverlays)))) { + var selectedLayer = selected; + LayerManager._contextMenu = new ContextMenuStrip(); + var renameMenu = ToolStripMenuItem.create(Language.getLocalizedText(225, 'Rename')); + var Expand = ToolStripMenuItem.create(Language.getLocalizedText(981, 'Expand')); + var Collapse = ToolStripMenuItem.create(Language.getLocalizedText(982, 'Collapse')); + var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); + var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); + var saveMenu = ToolStripMenuItem.create(Language.getLocalizedText(960, 'Save...')); + var publishMenu = ToolStripMenuItem.create(Language.getLocalizedText(983, 'Publish to Community...')); + var colorMenu = ToolStripMenuItem.create(Language.getLocalizedText(458, 'Color/Opacity')); + var opacityMenu = ToolStripMenuItem.create(Language.getLocalizedText(305, 'Opacity')); + var propertiesMenu = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); + var scaleMenu = ToolStripMenuItem.create(Language.getLocalizedText(1291, 'Scale/Histogram')); + var lifeTimeMenu = ToolStripMenuItem.create(Language.getLocalizedText(683, 'Lifetime')); + var spacer1 = new ToolStripSeparator(); + var top = ToolStripMenuItem.create(Language.getLocalizedText(684, 'Move to Top')); + var up = ToolStripMenuItem.create(Language.getLocalizedText(685, 'Move Up')); + var down = ToolStripMenuItem.create(Language.getLocalizedText(686, 'Move Down')); + var bottom = ToolStripMenuItem.create(Language.getLocalizedText(687, 'Move to Bottom')); + var showViewer = ToolStripMenuItem.create(Language.getLocalizedText(957, 'VO Table Viewer')); + var spacer2 = new ToolStripSeparator(); + var defaultImageset = ToolStripMenuItem.create(Language.getLocalizedText(1294, 'Background Image Set')); + top.click = LayerManager._top_Click; + up.click = LayerManager._up_Click; + down.click = LayerManager._down_Click; + bottom.click = LayerManager._bottom_Click; + saveMenu.click = LayerManager._saveMenu_Click; + publishMenu.click = LayerManager._publishMenu_Click; + Expand.click = LayerManager._expand_Click; + Collapse.click = LayerManager._collapse_Click; + copyMenu.click = LayerManager._copyMenu_Click; + colorMenu.click = LayerManager._colorMenu_Click; + deleteMenu.click = LayerManager._deleteMenu_Click; + renameMenu.click = LayerManager._renameMenu_Click; + propertiesMenu.click = LayerManager._propertiesMenu_Click; + scaleMenu.click = LayerManager.scaleMenu_click; + defaultImageset.click = LayerManager._defaultImageset_Click; + opacityMenu.click = LayerManager._opacityMenu_Click; + lifeTimeMenu.click = LayerManager._lifeTimeMenu_Click; + showViewer.click = LayerManager._showViewer_Click; + LayerManager._contextMenu.items.push(renameMenu); + if (!selectedLayer.get_opened() && selectedLayer.getPrimaryUI() != null && selectedLayer.getPrimaryUI().get_hasTreeViewNodes()) { + LayerManager._contextMenu.items.push(Expand); + } + if (selectedLayer.get_opened()) { + LayerManager._contextMenu.items.push(Collapse); + } + if (selectedLayer.canCopyToClipboard()) { + } + LayerManager._contextMenu.items.push(deleteMenu); + LayerManager._contextMenu.items.push(spacer2); + LayerManager._contextMenu.items.push(colorMenu); + if (ss.canCast(selected, ImageSetLayer)) { + LayerManager._contextMenu.items.push(defaultImageset); + var isl = ss.safeCast(selected, ImageSetLayer); + defaultImageset.checked = isl.get_overrideDefaultLayer(); + } + if (ss.canCast(selected, SpreadSheetLayer) || ss.canCast(selected, GreatCirlceRouteLayer)) { + LayerManager._contextMenu.items.push(propertiesMenu); + } + if (ss.canCast(selected, VoTableLayer)) { + LayerManager._contextMenu.items.push(showViewer); + } + if (ss.canCast(selected, ImageSetLayer)) { + var isl = ss.safeCast(selected, ImageSetLayer); + LayerManager._contextMenu.items.push(scaleMenu); + } + if (LayerManager.get_allMaps()[selectedLayer.get_referenceFrame()].layers.length > 1) { + LayerManager._contextMenu.items.push(spacer1); + LayerManager._contextMenu.items.push(top); + LayerManager._contextMenu.items.push(up); + LayerManager._contextMenu.items.push(down); + LayerManager._contextMenu.items.push(bottom); + } + LayerManager._contextMenu._show(Vector2d.create(x, y)); + } + else if (ss.canCast(selected, LayerMap)) { + var map = ss.safeCast(selected, LayerMap); + var sandbox = map.frame.reference.toString() === 'Sandbox'; + var Dome = map.frame.name === 'Dome'; + var Sky = map.frame.name === 'Sky'; + if (Dome) { + return; + } + LayerManager._contextMenu = new ContextMenuStrip(); + var trackFrame = ToolStripMenuItem.create(Language.getLocalizedText(1298, 'Track this frame')); + var goTo = ToolStripMenuItem.create(Language.getLocalizedText(1299, 'Fly Here')); + var showOrbit = ToolStripMenuItem.create('Show Orbit'); + var newMenu = ToolStripMenuItem.create(Language.getLocalizedText(674, 'New Reference Frame')); + var newLayerGroupMenu = ToolStripMenuItem.create(Language.getLocalizedText(675, 'New Layer Group')); + var addMenu = ToolStripMenuItem.create(Language.getLocalizedText(166, 'Add')); + var newLight = ToolStripMenuItem.create('Add Light'); + var addFeedMenu = ToolStripMenuItem.create(Language.getLocalizedText(956, 'Add OData/table feed as Layer')); + var addWmsLayer = ToolStripMenuItem.create(Language.getLocalizedText(987, 'New WMS Layer')); + var addGridLayer = ToolStripMenuItem.create(Language.getLocalizedText(1300, 'New Lat/Lng Grid')); + var addGreatCircle = ToolStripMenuItem.create(Language.getLocalizedText(988, 'New Great Circle')); + var importTLE = ToolStripMenuItem.create(Language.getLocalizedText(989, 'Import Orbital Elements')); + var addMpc = ToolStripMenuItem.create(Language.getLocalizedText(1301, 'Add Minor Planet')); + var deleteFrameMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); + var addToTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1290, 'Add to Timeline')); + var addKeyframe = ToolStripMenuItem.create(Language.getLocalizedText(1280, 'Add Keyframe')); + var popertiesMenu = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); + var saveMenu = ToolStripMenuItem.create(Language.getLocalizedText(990, 'Save Layers')); + var publishLayers = ToolStripMenuItem.create(Language.getLocalizedText(991, 'Publish Layers to Community')); + var spacer1 = new ToolStripSeparator(); + var spacer0 = new ToolStripSeparator(); + var spacer2 = new ToolStripSeparator(); + var asReferenceFrame = ToolStripMenuItem.create('As Reference Frame'); + var asOrbitalLines = ToolStripMenuItem.create('As Orbital Line'); + trackFrame.click = LayerManager._trackFrame_Click; + goTo.click = LayerManager._goTo_Click; + asReferenceFrame.click = LayerManager._addMpc_Click; + asOrbitalLines.click = LayerManager._asOrbitalLines_Click; + + // Add Sub Menus + addMpc.dropDownItems.push(asReferenceFrame); + addMpc.dropDownItems.push(asOrbitalLines); + addMenu.click = LayerManager._addMenu_Click; + newLayerGroupMenu.click = LayerManager._newLayerGroupMenu_Click; + pasteMenu.click = LayerManager._pasteLayer_Click; + newMenu.click = LayerManager._newMenu_Click; + deleteFrameMenu.click = LayerManager._deleteFrameMenu_Click; + popertiesMenu.click = LayerManager._framePropertiesMenu_Click; + addGreatCircle.click = LayerManager._addGreatCircle_Click; + addGridLayer.click = LayerManager._addGirdLayer_Click; + var convertToOrbit = ToolStripMenuItem.create('Extract Orbit Layer'); + if (map.frame.reference !== 19) { + if ((globalWWTControl.get_solarSystemMode() | globalWWTControl.sandboxMode) === 1) { + var spacerNeeded = false; + if (map.frame.reference !== 18 && !globalWWTControl.sandboxMode) { + // fly to + if (!Sky) { + } + try { + var name = map.frame.reference.toString(); + if (name !== 'Sandbox') { + var ssObj = Enums.parse('SolarSystemObjects', name); + var id = ssObj; + var bit = Math.pow(2, id); + showOrbit.checked = !!(Settings.get_active().get_planetOrbitsFilter() & bit); + showOrbit.click = LayerManager._showOrbitPlanet_Click; + showOrbit.tag = bit.toString(); + } + } + catch ($e1) { + } + } + else { + // track + if (!sandbox && !Sky) { + LayerManager._contextMenu.items.push(trackFrame); + spacerNeeded = true; + } + showOrbit.checked = map.frame.showOrbitPath; + showOrbit.click = LayerManager._showOrbit_Click; + } + if (spacerNeeded) { + LayerManager._contextMenu.items.push(spacer2); + } + if (!Sky && !sandbox) { + LayerManager._contextMenu.items.push(showOrbit); + LayerManager._contextMenu.items.push(spacer0); + } + if (map.frame.reference.toString() === 'Sandbox') { + LayerManager._contextMenu.items.push(newLight); + } + } + if (!Sky) { + LayerManager._contextMenu.items.push(newMenu); + } + } + if (!Sky) { + LayerManager._contextMenu.items.push(addGreatCircle); + LayerManager._contextMenu.items.push(addGridLayer); + } + if ((map.frame.reference !== 19 && map.frame.name === 'Sun') || (map.frame.reference === 19 && map.parent != null && map.parent.frame.name === 'Sun')) { + LayerManager._contextMenu.items.push(addMpc); + } + if (map.frame.reference === 18 && map.frame.referenceFrameType === 1 && map.parent != null && map.parent.frame.name === 'Sun') { + } + if (!Sky) { + } + LayerManager._contextMenu.items.push(pasteMenu); + if (map.frame.reference === 19) { + LayerManager._contextMenu.items.push(deleteFrameMenu); + } + if (map.frame.reference === 18) { + LayerManager._contextMenu.items.push(deleteFrameMenu); + LayerManager._contextMenu.items.push(popertiesMenu); + } + LayerManager._contextMenu.items.push(spacer1); + LayerManager._contextMenu._show(Vector2d.create(x, y)); + } +}; + +LayerManager._publishMenu_Click = function (sender, e) { }; + +LayerManager._addGirdLayer_Click = function (sender, e) { + var layer = new GridLayer(); + layer.enabled = true; + layer.set_name('Lat-Lng Grid'); + LayerManager.get_layerList()[layer.id] = layer; + layer.set_referenceFrame(LayerManager._currentMap); + LayerManager.get_allMaps()[LayerManager._currentMap].layers.push(layer); + LayerManager.get_allMaps()[LayerManager._currentMap].open = true; + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._trackFrame_Click = function (sender, e) { + var target = LayerManager._selectedLayer; + globalRenderContext.set_solarSystemTrack(20); + globalRenderContext.set_trackingFrame(target.get_name()); + globalRenderContext.viewCamera.zoom = globalRenderContext.targetCamera.zoom = 1E-09; +}; + +LayerManager._goTo_Click = function (sender, e) { }; + +LayerManager._saveMenu_Click = function (sender, e) { }; + +LayerManager._expand_Click = function (sender, e) { }; + +LayerManager._collapse_Click = function (sender, e) { }; + +LayerManager._copyMenu_Click = function (sender, e) { + if (LayerManager._selectedLayer != null && ss.canCast(LayerManager._selectedLayer, Layer)) { + var node = LayerManager._selectedLayer; + node.copyToClipboard(); + } +}; + +LayerManager._newLayerGroupMenu_Click = function (sender, e) { }; + +LayerManager._importTLEFile = function (filename) { }; + +LayerManager._makeLayerGroupNow = function (name) { + var target = LayerManager._selectedLayer; + LayerManager._makeLayerGroup(name, target); +}; + +LayerManager._makeLayerGroup = function (name, target) { + var frame = new ReferenceFrame(); + frame.name = name; + frame.reference = 19; + var newMap = new LayerMap(frame.name, 19); + newMap.frame = frame; + newMap.frame._systemGenerated = false; + target.addChild(newMap); + newMap.frame.parent = target.get_name(); + LayerManager.get_allMaps()[frame.name] = newMap; + LayerManager._version++; +}; + +LayerManager._lifeTimeMenu_Click = function (sender, e) { }; + +LayerManager._deleteFrameMenu_Click = function (sender, e) { }; + +LayerManager._framePropertiesMenu_Click = function (sender, e) { + var target = LayerManager._selectedLayer; + LayerManager.get_referenceFramePropsDialog().show(target.frame, e); +}; + +LayerManager._newMenu_Click = function (sender, e) { + var frame = new ReferenceFrame(); + LayerManager.get_frameWizardDialog().show(frame, e); +}; + +LayerManager.referenceFrameWizardFinished = function (frame) { + var target = LayerManager._selectedLayer; + var newMap = new LayerMap(frame.name, 18); + if (!ss.keyExists(LayerManager.get_allMaps(), frame.name)) { + newMap.frame = frame; + target.addChild(newMap); + newMap.frame.parent = target.get_name(); + LayerManager.get_allMaps()[frame.name] = newMap; + LayerManager._version++; + LayerManager.loadTree(); + } +}; + +LayerManager.pasteFromTle = function (lines, frame) { + var line1 = ''; + var line2 = ''; + for (var i = 0; i < lines.length; i++) { + lines[i] = ss.trim(lines[i]); + if (lines[i].length === 69 && ReferenceFrame.isTLECheckSumGood(lines[i])) { + if (!line1.length && lines[i].substring(0, 1) === '1') { + line1 = lines[i]; + } + if (!line2.length && lines[i].substring(0, 1) === '2') { + line2 = lines[i]; + } + } + } + if (line1.length === 69 && line2.length === 69) { + frame.fromTLE(line1, line2, 398600441800000); + return true; + } + return false; +}; + +LayerManager._opacityMenu_Click = function (sender, e) { }; + +LayerManager._defaultImageset_Click = function (sender, e) { + var isl = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); + isl.set_overrideDefaultLayer(!isl.get_overrideDefaultLayer()); +}; + +LayerManager._propertiesMenu_Click = function (sender, e) { + if (ss.canCast(LayerManager._selectedLayer, SpreadSheetLayer)) { + var target = LayerManager._selectedLayer; + LayerManager.get_dataVizWizardDialog().show(target, e); + } + if (ss.canCast(LayerManager._selectedLayer, GreatCirlceRouteLayer)) { + LayerManager.get_greatCircleDlg().show(LayerManager._selectedLayer, new ss.EventArgs()); + } +}; + +LayerManager._renameMenu_Click = function (sender, e) { + var layer = LayerManager._selectedLayer; + var input = new SimpleInput(Language.getLocalizedText(225, 'Rename'), Language.getLocalizedText(228, 'New Name'), layer.get_name(), 32); + input.show(LayerManager._lastMenuClick, function () { + if (!ss.emptyString(input.text)) { + layer.set_name(input.text); + LayerManager._version++; + LayerManager.loadTree(); + } + }); +}; + +LayerManager._colorMenu_Click = function (sender, e) { + var layer = LayerManager._selectedLayer; + var picker = new ColorPicker(); + if (layer.get_color() != null) { + picker.color = layer.get_color(); + } + picker.callBack = function () { + layer.set_color(picker.color); + }; + picker.show(e); +}; + +LayerManager._addMenu_Click = function (sender, e) { }; + +LayerManager._deleteMenu_Click = function (sender, e) { + LayerManager._deleteSelectedLayer(); +}; + +LayerManager._deleteSelectedLayer = function () { + if (LayerManager._selectedLayer != null && ss.canCast(LayerManager._selectedLayer, Layer)) { + var node = LayerManager._selectedLayer; + delete LayerManager.get_layerList()[node.id]; + ss.remove(LayerManager.get_allMaps()[LayerManager.get_currentMap()].layers, node); + node.cleanUp(); + node.set_version(node.get_version() + 1) - 1; + LayerManager.loadTree(); + LayerManager._version++; + } +}; + +LayerManager.scaleMenu_click = function (sender, e) { + var isl = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); + if (isl != null) { + var hist = new Histogram(); + hist.image = isl.getFitsImage(); + hist.layer = isl; + hist.show(Vector2d.create(200, 200)); + } +}; + +LayerManager._showViewer_Click = function (sender, e) { + if (ss.canCast(LayerManager._selectedLayer, VoTableLayer)) { + var layer = ss.safeCast(LayerManager._selectedLayer, VoTableLayer); + globalScriptInterface.displayVoTableLayer(layer); + } +}; + +LayerManager._bottom_Click = function (sender, e) { + var layer = ss.safeCast(LayerManager._selectedLayer, Layer); + if (layer != null) { + ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); + } + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._down_Click = function (sender, e) { + var layer = ss.safeCast(LayerManager._selectedLayer, Layer); + if (layer != null) { + var index = LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.lastIndexOf(layer); + if (index < (LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.length - 1)) { + ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(index + 1, 0, layer); + } + } + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._up_Click = function (sender, e) { + var layer = ss.safeCast(LayerManager._selectedLayer, Layer); + if (layer != null) { + var index = LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.lastIndexOf(layer); + if (index > 0) { + ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(index - 1, 0, layer); + } + } + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._top_Click = function (sender, e) { + var layer = ss.safeCast(LayerManager._selectedLayer, Layer); + if (layer != null) { + ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); + LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(0, 0, layer); + } + LayerManager._version++; + LayerManager.loadTree(); +}; + +LayerManager._pasteLayer_Click = function (sender, e) { + LayerManager.get_dataVizWizardDialog().show(LayerManager.get_currentMap(), e); +}; + +LayerManager.createSpreadsheetLayer = function (frame, name, data) { + var layer = new SpreadSheetLayer(); + layer.loadFromString(data, false, false, false, true); + layer.set_name(name); + LayerManager.addSpreadsheetLayer(layer, frame); + return layer; +}; + +LayerManager.addSpreadsheetLayer = function (layer, frame) { + layer.enabled = true; + layer.set_referenceFrame(frame); + LayerManager.add(layer, true); +}; + +LayerManager._showOrbitPlanet_Click = function (sender, e) { + try { + var bit = parseInt((sender).tag.toString()); + // Flip the state + if (!(Settings.get_globalSettings().get_planetOrbitsFilter() & bit)) { + Settings.get_globalSettings().set_planetOrbitsFilter(Settings.get_globalSettings().get_planetOrbitsFilter() | bit); + } else { + Settings.get_globalSettings().set_planetOrbitsFilter(Settings.get_globalSettings().get_planetOrbitsFilter() & ~bit); + } + } + catch ($e1) { } +}; + +LayerManager._showOrbit_Click = function (sender, e) { + // Flip the state + var map = ss.safeCast(LayerManager._selectedLayer, LayerMap); + map.frame.showOrbitPath = !map.frame.showOrbitPath; +}; + +LayerManager._addGreatCircle_Click = function (sender, e) { + LayerManager._addGreatCircleLayer(); +}; + +LayerManager._addMpc_Click = function (sender, e) { + var target = LayerManager._selectedLayer; + var input = new SimpleInput(Language.getLocalizedText(1302, 'Minor planet name or designation'), Language.getLocalizedText(238, 'Name'), '', 32); + var retry = false; + do { + if (input.showDialog() === 1) { + if (ss.keyExists(target.childMaps, input.text)) { + retry = true; + } + else { + try { + LayerManager._getMpc(input.text, target); + retry = false; + } + catch ($e1) { + retry = true; + } + } + } else { + retry = false; + } + } while (retry); + return; +}; + +LayerManager._asOrbitalLines_Click = function (sender, e) { + var target = LayerManager._selectedLayer; + var input = new SimpleInput(Language.getLocalizedText(1302, 'Minor planet name or designation'), Language.getLocalizedText(238, 'Name'), '', 32); + input.show(Cursor.get_position(), function () { + if (ss.keyExists(target.childMaps, input.text)) { + } else { + LayerManager._getMpcAsTLE(input.text, target); + } + }); +}; + +LayerManager._getMpcAsTLE = function (id, target) { + var file = new WebFile('https://www.minorplanetcenter.net/db_search/show_object?object_id=' + id); + file.onStateChange = function () { + if (file.get_state() !== 1) { + return; + } + var data = file.getText(); + var startform = data.indexOf('show-orbit-button'); + var lastForm = data.indexOf('/form', startform); + var formpart = data.substring(startform, lastForm); + var name = id; + var frame = new ReferenceFrame(); + frame.oblateness = 0; + frame.showOrbitPath = true; + frame.showAsPoint = true; + frame.epoch = SpaceTimeController.utcToJulian(ss.date(LayerManager._getValueByID(formpart, 'epoch').substring(0, 10))); + frame.semiMajorAxis = parseFloat(LayerManager._getValueByID(formpart, 'a')) * 149598000 * 1000; + frame.referenceFrameType = 1; + frame.inclination = parseFloat(LayerManager._getValueByID(formpart, 'incl')); + frame.longitudeOfAscendingNode = parseFloat(LayerManager._getValueByID(formpart, 'node')); + frame.eccentricity = parseFloat(LayerManager._getValueByID(formpart, 'e')); + frame.meanAnomolyAtEpoch = parseFloat(LayerManager._getValueByID(formpart, 'm')); + frame.meanDailyMotion = ELL.meanMotionFromSemiMajorAxis(parseFloat(LayerManager._getValueByID(formpart, 'a'))); + frame.argumentOfPeriapsis = parseFloat(LayerManager._getValueByID(formpart, 'peri')); + frame.scale = 1; + frame.semiMajorAxisUnits = 1; + frame.meanRadius = 10; + frame.oblateness = 0; + var TLE = name + '\n' + frame.toTLE(); + LayerManager._loadOrbitsFile(id, TLE, target.get_name()); + LayerManager.loadTree(); + }; + file.send(); +}; + +LayerManager._getMpc = function (id, target) { + var file = new WebFile('https://www.minorplanetcenter.net/db_search/show_object?object_id=' + id); + file.onStateChange = function () { + var data = file.getText(); + var startform = data.indexOf('show-orbit-button'); + var lastForm = data.indexOf('/form', startform); + var formpart = data.substring(startform, lastForm); + var name = id; + var orbit = new LayerMap(ss.trim(name), 18); + orbit.frame.oblateness = 0; + orbit.frame.showOrbitPath = true; + orbit.frame.showAsPoint = true; + orbit.frame.epoch = SpaceTimeController.utcToJulian(ss.date(LayerManager._getValueByID(formpart, 'epoch').substring(0, 10))); + orbit.frame.semiMajorAxis = parseFloat(LayerManager._getValueByID(formpart, 'a')) * 149598000 * 1000; + orbit.frame.referenceFrameType = 1; + orbit.frame.inclination = parseFloat(LayerManager._getValueByID(formpart, 'incl')); + orbit.frame.longitudeOfAscendingNode = parseFloat(LayerManager._getValueByID(formpart, 'node')); + orbit.frame.eccentricity = parseFloat(LayerManager._getValueByID(formpart, 'e')); + orbit.frame.meanAnomolyAtEpoch = parseFloat(LayerManager._getValueByID(formpart, 'm')); + orbit.frame.meanDailyMotion = ELL.meanMotionFromSemiMajorAxis(parseFloat(LayerManager._getValueByID(formpart, 'a'))); + orbit.frame.argumentOfPeriapsis = parseFloat(LayerManager._getValueByID(formpart, 'peri')); + orbit.frame.scale = 1; + orbit.frame.semiMajorAxisUnits = 1; + orbit.frame.meanRadius = 10; + orbit.frame.oblateness = 0; + if (!ss.keyExists(LayerManager.get_allMaps()[target.get_name()].childMaps, ss.trim(name))) { + LayerManager.get_allMaps()[target.get_name()].addChild(orbit); + } + LayerManager.get_allMaps()[orbit.get_name()] = orbit; + orbit.frame.parent = target.get_name(); + LayerManager._makeLayerGroup('Minor Planet', orbit); + LayerManager.loadTree(); + }; +}; + +LayerManager._getValueByID = function (data, id) { + var valStart = data.indexOf('id="' + id + '"'); + valStart = data.indexOf('value=', valStart) + 7; + var valEnd = data.indexOf('"', valStart); + return data.substr(valStart, valEnd - valStart); +}; + +LayerManager._addGreatCircleLayer = function () { + var layer = new GreatCirlceRouteLayer(); + var camera = globalRenderContext.viewCamera; + layer.set_latStart(camera.lat); + layer.set_latEnd(camera.lat - 5); + layer.set_lngStart(camera.lng); + layer.set_lngEnd(camera.lng + 5); + layer.set_width(4); + layer.enabled = true; + layer.set_name(Language.getLocalizedText(1144, 'Great Circle Route')); + LayerManager.get_layerList()[layer.id] = layer; + layer.set_referenceFrame(LayerManager._currentMap); + LayerManager.get_allMaps()[LayerManager._currentMap].layers.push(layer); + LayerManager.get_allMaps()[LayerManager._currentMap].open = true; + LayerManager._version++; + LayerManager.loadTree(); + LayerManager.get_greatCircleDlg().show(layer, new ss.EventArgs()); +}; + +LayerManager._loadOrbitsFile = function (name, data, currentMap) { + var layer = new OrbitLayer(); + layer.loadString(data); + layer.enabled = true; + layer.set_name(name); + LayerManager.get_layerList()[layer.id] = layer; + layer.set_referenceFrame(currentMap); + LayerManager.get_allMaps()[currentMap].layers.push(layer); + LayerManager.get_allMaps()[currentMap].open = true; + LayerManager._version++; + LayerManager.loadTree(); + return layer; +}; + +var LayerManager$ = {}; + +registerType("LayerManager", [LayerManager, LayerManager$, null]); + + +// wwtlib.LayerMap + +export function LayerMap(name, reference) { + this.childMaps = {}; + this.parent = null; + this.layers = []; + this.open = false; + this.enabled = true; + this.loadedFromTour = false; + this.frame = new ReferenceFrame(); + this.set_name(name); + this.frame.reference = reference; + var radius = 6371000; + switch (reference) { + case 0: + break; + case 1: + break; + case 2: + break; + case 3: + radius = 696000000; + break; + case 4: + radius = 2439700; + break; + case 5: + radius = 6051800; + break; + case 6: + radius = 6371000; + break; + case 7: + radius = 3390000; + break; + case 8: + radius = 69911000; + break; + case 9: + radius = 58232000; + break; + case 10: + radius = 25362000; + break; + case 11: + radius = 24622000; + break; + case 12: + radius = 1161000; + break; + case 13: + radius = 1737100; + break; + case 14: + radius = 1821500; + break; + case 15: + radius = 1561000; + break; + case 16: + radius = 2631200; + break; + case 17: + radius = 2410300; + break; + case 18: + break; + case 19: + break; + default: + break; + } + this.frame.meanRadius = radius; +} + +var LayerMap$ = { + addChild: function (child) { + child.parent = this; + this.childMaps[child.get_name()] = child; + }, + + get_name: function () { + return this.frame.name; + }, + + set_name: function (value) { + this.frame.name = value; + return value; + }, + + computeFrame: function (renderContext) { + if (this.frame.reference === 18) { + this.frame.computeFrame(renderContext); + } + }, + + toString: function () { + return this.get_name(); + } +}; + +registerType("LayerMap", [LayerMap, LayerMap$, null]); + + +// wwtlib.SkyOverlays + +export function SkyOverlays() { } + +var SkyOverlays$ = {}; + +registerType("SkyOverlays", [SkyOverlays, SkyOverlays$, null]); + + +// wwtlib.GroundOverlayLayer + +export function GroundOverlayLayer() { } + +var GroundOverlayLayer$ = {}; + +registerType("GroundOverlayLayer", [GroundOverlayLayer, GroundOverlayLayer$, null]); + + +// wwtlib.FrameTarget + +export function FrameTarget() { } + +var FrameTarget$ = {}; + +registerType("FrameTarget", [FrameTarget, FrameTarget$, null]); diff --git a/engine/esm/layers/layer_ui.js b/engine/esm/layers/layer_ui.js new file mode 100644 index 00000000..a3605f3b --- /dev/null +++ b/engine/esm/layers/layer_ui.js @@ -0,0 +1,290 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A framework for constructing UIs associated with specific layers. Largely +// unused in the web engine context. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Colors } from "../color.js"; + + +// wwtlib.LayerUI + +export function LayerUI() { } + +LayerUI._type = null; + +var LayerUI$ = { + get_hasTreeViewNodes: function () { + return false; + }, + + getTreeNodes: function () { + return null; + }, + + getNodeContextMenu: function (node) { + return null; + }, + + setUICallbacks: function (callbacks) { } +}; + +registerType("LayerUI", [LayerUI, LayerUI$, null]); + + +// wwtlib.LayerUIMenuItem + +export function LayerUIMenuItem() { + this._tag = null; + this._isChecked = false; + this._isEnabled = true; + this._subMenus = null; +} + +var LayerUIMenuItem$ = { + get_name: function () { + return this._name; + }, + + set_name: function (value) { + this._name = value; + return value; + }, + + get_tag: function () { + return this._tag; + }, + + set_tag: function (value) { + this._tag = value; + return value; + }, + + get_checked: function () { + return this._isChecked; + }, + + set_checked: function (value) { + this._isChecked = value; + return value; + }, + + get_enabled: function () { + return this._isEnabled; + }, + + set_enabled: function (value) { + this._isEnabled = value; + return value; + }, + + add_menuItemSelected: function (value) { + this.__menuItemSelected = ss.bindAdd(this.__menuItemSelected, value); + }, + + remove_menuItemSelected: function (value) { + this.__menuItemSelected = ss.bindSub(this.__menuItemSelected, value); + }, + + fireMenuItemSelected: function () { + if (this.__menuItemSelected != null) { + this.__menuItemSelected(this); + } + }, + + get_subMenus: function () { + if (this._subMenus == null) { + this._subMenus = []; + } + return this._subMenus; + } +}; + +registerType("LayerUIMenuItem", [LayerUIMenuItem, LayerUIMenuItem$, null]); + + +// wwtlib.LayerUITreeNode + +export function LayerUITreeNode() { + this._parent = null; + this._level = 0; + this._open = false; + this._isChecked = false; + this._bold = false; + this._color = Colors.get_white(); + this._nodes = null; +} + +var LayerUITreeNode$ = { + add_nodeChecked: function (value) { + this.__nodeChecked = ss.bindAdd(this.__nodeChecked, value); + }, + + remove_nodeChecked: function (value) { + this.__nodeChecked = ss.bindSub(this.__nodeChecked, value); + }, + + fireNodeChecked: function (newState) { + if (this.__nodeChecked != null) { + this.__nodeChecked(this, newState); + } + }, + + add_nodeUpdated: function (value) { + this.__nodeUpdated = ss.bindAdd(this.__nodeUpdated, value); + }, + + remove_nodeUpdated: function (value) { + this.__nodeUpdated = ss.bindSub(this.__nodeUpdated, value); + }, + + fireNodeUpdated: function () { + if (this.__nodeUpdated != null) { + this.__nodeUpdated(this); + } + }, + + add_nodeSelected: function (value) { + this.__nodeSelected = ss.bindAdd(this.__nodeSelected, value); + }, + + remove_nodeSelected: function (value) { + this.__nodeSelected = ss.bindSub(this.__nodeSelected, value); + }, + + fireNodeSelected: function () { + if (this.__nodeSelected != null) { + this.__nodeSelected(this); + } + }, + + add_nodeActivated: function (value) { + this.__nodeActivated = ss.bindAdd(this.__nodeActivated, value); + }, + + remove_nodeActivated: function (value) { + this.__nodeActivated = ss.bindSub(this.__nodeActivated, value); + }, + + fireNodeActivated: function () { + if (this.__nodeActivated != null) { + this.__nodeActivated(this); + } + }, + + get_name: function () { + return this._name; + }, + + set_name: function (value) { + if (this._name !== value) { + this._name = value; + this.fireNodeUpdated(); + } + return value; + }, + + get_parent: function () { + return this._parent; + }, + + set_parent: function (value) { + this._parent = value; + return value; + }, + + get_level: function () { + return this._level; + }, + + set_level: function (value) { + this._level = value; + return value; + }, + + get_tag: function () { + return this._tag; + }, + + set_tag: function (value) { + this._tag = value; + return value; + }, + + get_referenceTag: function () { + return this._referenceTag; + }, + + set_referenceTag: function (value) { + this._referenceTag = value; + return value; + }, + + get_opened: function () { + return this._open; + }, + + set_opened: function (value) { + if (this._open !== value) { + this._open = value; + this.fireNodeUpdated(); + } + return value; + }, + + get_checked: function () { + return this._isChecked; + }, + + set_checked: function (value) { + if (this._isChecked !== value) { + this._isChecked = value; + this.fireNodeUpdated(); + } + return value; + }, + + get_bold: function () { + return this._bold; + }, + + set_bold: function (value) { + if (this._bold !== value) { + this._bold = value; + this.fireNodeUpdated(); + } + return value; + }, + + get_color: function () { + return this._color; + }, + + set_color: function (value) { + if (this._color !== value) { + this._color = value; + this.fireNodeUpdated(); + } + return value; + }, + + add: function (name) { + var node = new LayerUITreeNode(); + node.set_name(name); + node.set_parent(this); + node.set_level(this.get_level() + 1); + this.get_nodes().push(node); + return node; + }, + + get_nodes: function () { + if (this._nodes == null) { + this._nodes = []; + } + return this._nodes; + } +}; + +registerType("LayerUITreeNode", [LayerUITreeNode, LayerUITreeNode$, null]); diff --git a/engine/esm/layers/manager_dialogs.js b/engine/esm/layers/manager_dialogs.js new file mode 100644 index 00000000..d3db8fd3 --- /dev/null +++ b/engine/esm/layers/manager_dialogs.js @@ -0,0 +1,83 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Types defining UI elements associated with the layer manager. +// +// These don't do anything in the web client, but to preserve API compatibility, +// we keep them hanging around. + +import { registerType } from "../typesystem.js"; +import { Dialog } from "../utilities/dialog.js"; +import { LayerManager } from "./layer_manager.js"; + + +// wwtlib.FrameWizard +// +// This was originally defined in `Utilities/Dialog.cs`. + +export function FrameWizard() { + Dialog.call(this); +} + +var FrameWizard$ = { + OK: function (frame) { + LayerManager.referenceFrameWizardFinished(frame); + } +}; + +registerType("FrameWizard", [FrameWizard, FrameWizard$, Dialog]); + + +// wwtlib.ReferenceFrameProps +// +// This was originally defined in `Utilities/Dialog.cs`. + +export function ReferenceFrameProps() { + Dialog.call(this); +} + +var ReferenceFrameProps$ = { + OK: function (frame) { + LayerManager.loadTree(); + } +}; + +registerType("ReferenceFrameProps", [ReferenceFrameProps, ReferenceFrameProps$, Dialog]); + + +// wwtlib.GreatCircleDialog +// +// This was originally defined in `Utilities/Dialog.cs`. + +export function GreatCircleDialog() { + Dialog.call(this); +} + +var GreatCircleDialog$ = { + OK: function (frame) { } +}; + +registerType("GreatCircleDialog", [GreatCircleDialog, GreatCircleDialog$, Dialog]); + + +// wwtlib.DataVizWizard +// +// This was originally defined in `Utilities/Dialog.cs`. + +export function DataVizWizard() { + Dialog.call(this); +} + +var DataVizWizard$ = { + OK: function () { } +}; + +registerType("DataVizWizard", [DataVizWizard, DataVizWizard$, Dialog]); + + +// Initialize: + +LayerManager._frameWizardDialog = new FrameWizard(); +LayerManager._dataVizWizardDialog = new DataVizWizard(); +LayerManager._referenceFramePropsDialog = new ReferenceFrameProps(); +LayerManager._greatCircleDialog = new GreatCircleDialog(); diff --git a/engine/esm/layers/object3d.js b/engine/esm/layers/object3d.js new file mode 100644 index 00000000..73b21c90 --- /dev/null +++ b/engine/esm/layers/object3d.js @@ -0,0 +1,2583 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer adding a 3D object model, and supporting code. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Color, Colors } from "../color.js"; +import { + Vector2d, + Vector3d, + Matrix3d, + PositionNormalTextured, + PositionNormalTexturedTangent, + SphereHull, + ConvexHull, +} from "../double3d.js"; +import { globalRenderContext } from "../render_globals.js"; +import { WEBGL } from "../graphics/webgl_constants.js"; +import { Dates, LineList, TriangleList } from "../graphics/primitives3d.js"; +import { IndexBuffer, PositionNormalTexturedVertexBuffer, PositionNormalTexturedTangentVertexBuffer } from "../graphics/gl_buffers.js"; +import { ModelShader } from "../graphics/shaders.js"; +import { BinaryReader } from "../utilities/binary_reader.js"; +import { BasePlanets } from "../baseplanets.js"; +import { IUiController } from "../interfaces.js"; +import { Settings } from "../settings.js"; +import { Cursor, Cursors } from "../util.js"; +import { Layer } from "./layer.js"; +import { LayerUI, LayerUITreeNode } from "./layer_ui.js"; + + +// wwtlib.Material +// +// This was defined in `RenderContext.cs` in the C# code, but that really didn't +// make any sense, so we've moved it here. + +export function Material() { + this.specularSharpness = 0; + this.opacity = 0; + this.isDefault = false; +} + +var Material$ = {}; + +registerType("Material", [Material, Material$, null]); + + +// wwtlib.Object3dLayer + +export function Object3dLayer() { + this._primaryUI$1 = null; + this._heading$1 = 0; + this._flipV$1 = true; + this._flipHandedness$1 = false; + this._smooth$1 = true; + this._twoSidedGeometry$1 = false; + this._pitch$1 = 0; + this._roll$1 = 0; + this._scale$1 = Vector3d.create(1, 1, 1); + this._translate$1 = Vector3d.create(0, 0, 0); + this._lightID$1 = 0; + this._dirty$1 = false; + this.objType = false; + this._xHandle$1 = new Vector2d(); + this._yHandle$1 = new Vector2d(); + this._zHandle$1 = new Vector2d(); + this._hprHandles$1 = new Array(6); + this._uiScale$1 = 1; + this._showEditUi$1 = false; + this._dragMode$1 = 0; + this._pntDown$1 = new Vector2d(); + this._valueOnDown$1 = 0; + this._valueOnDown2$1 = 0; + this._hitDist$1 = 20; + this._lockPreferedAxis$1 = false; + this._preferY$1 = false; + Layer.call(this); +} + +Object3dLayer._translateUI$1 = null; +Object3dLayer._translateUILines$1 = null; +Object3dLayer._scaleUI$1 = null; +Object3dLayer._rotateUi$1 = null; + +Object3dLayer._initTranslateUI$1 = function () { + Object3dLayer._translateUILines$1 = new LineList(); + Object3dLayer._translateUILines$1.timeSeries = false; + Object3dLayer._translateUILines$1.set_depthBuffered(false); + Object3dLayer._translateUILines$1.showFarSide = true; + Object3dLayer._translateUI$1 = new TriangleList(); + Object3dLayer._translateUI$1.depthBuffered = false; + Object3dLayer._translateUI$1.timeSeries = false; + Object3dLayer._translateUI$1.writeZbuffer = false; + var twoPi = Math.PI * 2; + var step = twoPi / 45; + var rad = 0.05; + + // X + + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(1 - rad * 4, 0, 0); + var pnt2 = Vector3d.create(1 - rad * 4, Math.cos(a) * rad, Math.sin(a) * rad); + var pnt3 = Vector3d.create(1 - rad * 4, Math.cos(a + step) * rad, Math.sin(a + step) * rad); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_red(), Dates.empty()); + } + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(1, 0, 0); + var pnt3 = Vector3d.create(1 - rad * 4, Math.cos(a) * rad, Math.sin(a) * rad); + var pnt2 = Vector3d.create(1 - rad * 4, Math.cos(a + step) * rad, Math.sin(a + step) * rad); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, 255, Math.max(0, (Math.sin(a) * 128)), Math.max(0, (Math.sin(a) * 128))), Dates.empty()); + } + Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(1, 0, 0), Colors.get_red(), Dates.empty()); + + // Y + + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(0, 1 - rad * 4, 0); + var pnt3 = Vector3d.create(Math.cos(a) * rad, 1 - rad * 4, Math.sin(a) * rad); + var pnt2 = Vector3d.create(Math.cos(a + step) * rad, 1 - rad * 4, Math.sin(a + step) * rad); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_green(), Dates.empty()); + } + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(0, 1, 0); + var pnt2 = Vector3d.create(Math.cos(a) * rad, 1 - rad * 4, Math.sin(a) * rad); + var pnt3 = Vector3d.create(Math.cos(a + step) * rad, 1 - rad * 4, Math.sin(a + step) * rad); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, Math.max(0, (Math.sin(a) * 128)), 255, Math.max(0, (Math.sin(a) * 128))), Dates.empty()); + } + Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(0, 1, 0), Colors.get_green(), Dates.empty()); + + // Z + + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(0, 0, 1 - rad * 4); + var pnt2 = Vector3d.create(Math.cos(a) * rad, Math.sin(a) * rad, 1 - rad * 4); + var pnt3 = Vector3d.create(Math.cos(a + step) * rad, Math.sin(a + step) * rad, 1 - rad * 4); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_blue(), Dates.empty()); + } + for (var a = 0; a < twoPi; a += step) { + var pnt1 = Vector3d.create(0, 0, 1); + var pnt3 = Vector3d.create(Math.cos(a) * rad, Math.sin(a) * rad, 1 - rad * 4); + var pnt2 = Vector3d.create(Math.cos(a + step) * rad, Math.sin(a + step) * rad, 1 - rad * 4); + Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, Math.max(0, (Math.sin(a) * 128)), Math.max(0, (Math.sin(a) * 128)), 255), Dates.empty()); + } + Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(0, 0, 1), Colors.get_blue(), Dates.empty()); + Object3dLayer._initRotateUI$1(); + Object3dLayer._initScaleUI$1(); +}; + +Object3dLayer._initScaleUI$1 = function () { + Object3dLayer._scaleUI$1 = new TriangleList(); + Object3dLayer._scaleUI$1.depthBuffered = false; + Object3dLayer._scaleUI$1.timeSeries = false; + Object3dLayer._scaleUI$1.writeZbuffer = false; + var twoPi = Math.PI * 2; + var step = twoPi / 45; + var rad = 0.05; + Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(1 - rad * 2, 0, 0), rad * 2, Colors.get_red()); + Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(0, 1 - rad * 2, 0), rad * 2, Colors.get_green()); + Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(0, 0, 1 - rad * 2), rad * 2, Colors.get_blue()); +}; + +Object3dLayer._makeCube$1 = function (tl, center, size, color) { + var dark = Color.fromArgb(255, ss.truncate((color.r * 0.6)), color.g, ss.truncate((color.b * 0.6))); + var med = Color.fromArgb(255, ss.truncate((color.r * 0.8)), ss.truncate((color.g * 0.8)), ss.truncate((color.b * 0.8))); + tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z - size), color, Dates.empty()); + tl.addQuad(Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z - size), color, Dates.empty()); + tl.addQuad(Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z - size), dark, Dates.empty()); + tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x + size, center.y - size, center.z - size), dark, Dates.empty()); + tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z + size), med, Dates.empty()); + tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x + size, center.y - size, center.z - size), Vector3d.create(center.x - size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z - size), med, Dates.empty()); +}; + +Object3dLayer._initRotateUI$1 = function () { + Object3dLayer._rotateUi$1 = new TriangleList(); + Object3dLayer._rotateUi$1.depthBuffered = false; + Object3dLayer._rotateUi$1.timeSeries = false; + Object3dLayer._rotateUi$1.writeZbuffer = false; + var twoPi = Math.PI * 2; + var step = twoPi / 40; + var rad = 0.05; + var index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); + var pnt2 = Vector3d.create(-rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); + var pnt3 = Vector3d.create(rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); + var pnt4 = Vector3d.create(-rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Color._fromArgbColor(192, Colors.get_red()), Dates.empty()); + index++; + } + index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(Math.cos(a), Math.sin(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1))); + var pnt2 = Vector3d.create(Math.cos(a), Math.sin(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1))); + var pnt3 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1))); + var pnt4 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1))); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Color._fromArgbColor(192, Colors.get_blue()), Dates.empty()); + index++; + } + index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(Math.cos(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); + var pnt2 = Vector3d.create(Math.cos(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); + var pnt3 = Vector3d.create(Math.cos(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); + var pnt4 = Vector3d.create(Math.cos(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt2, pnt3, pnt4, Color._fromArgbColor(192, Colors.get_green()), Dates.empty()); + index++; + } + + // X + + index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(-rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); + var pnt2 = Vector3d.create(rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); + var pnt3 = Vector3d.create(-rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); + var pnt4 = Vector3d.create(rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Colors.get_red(), Dates.empty()); + index++; + } + + // Y + + index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(Math.cos(a), Math.sin(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1))); + var pnt2 = Vector3d.create(Math.cos(a), Math.sin(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1))); + var pnt3 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1))); + var pnt4 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1))); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Colors.get_blue(), Dates.empty()); + index++; + } + + // Z + + index = 0; + for (var a = 0; a < twoPi; a += step) { + var start = !(index % 10); + var end = !((index + 1) % 10); + var pnt1 = Vector3d.create(Math.cos(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); + var pnt2 = Vector3d.create(Math.cos(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); + var pnt3 = Vector3d.create(Math.cos(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); + var pnt4 = Vector3d.create(Math.cos(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); + Object3dLayer._rotateUi$1.addQuad(pnt1, pnt2, pnt3, pnt4, Colors.get_green(), Dates.empty()); + index++; + } +}; + +var Object3dLayer$ = { + getPrimaryUI: function () { + if (this._primaryUI$1 == null) { + this._primaryUI$1 = new Object3dLayerUI(this); + } + return this._primaryUI$1; + }, + + get_flipV: function () { + return this._flipV$1; + }, + + set_flipV: function (value) { + if (this._flipV$1 !== value) { + this._flipV$1 = value; + if (this.object3d != null) { + this.object3d.flipV = this._flipV$1; + this.object3d._reload(); + } + this.version++; + } + return value; + }, + + get_flipHandedness: function () { + return this._flipHandedness$1; + }, + + set_flipHandedness: function (value) { + if (this._flipHandedness$1 !== value) { + this._flipHandedness$1 = value; + if (this.object3d != null) { + this.object3d.flipHandedness = this._flipHandedness$1; + this.object3d._reload(); + } + this.version++; + } + return value; + }, + + get_smooth: function () { + return this._smooth$1; + }, + + set_smooth: function (value) { + if (this._smooth$1 !== value) { + this._smooth$1 = value; + if (this.object3d != null) { + this.object3d.smooth = this._smooth$1; + this.object3d._reload(); + } + this.version++; + } + return value; + }, + + get_twoSidedGeometry: function () { + return this._twoSidedGeometry$1; + }, + + set_twoSidedGeometry: function (value) { + if (this._twoSidedGeometry$1 !== value) { + this._twoSidedGeometry$1 = value; + this.version++; + } + return value; + }, + + get_heading: function () { + return this._heading$1; + }, + + set_heading: function (value) { + if (this._heading$1 !== value) { + this.version++; + this._heading$1 = value; + } + return value; + }, + + get_pitch: function () { + return this._pitch$1; + }, + + set_pitch: function (value) { + if (this._pitch$1 !== value) { + this.version++; + this._pitch$1 = value; + } + return value; + }, + + get_roll: function () { + return this._roll$1; + }, + + set_roll: function (value) { + if (this._roll$1 !== value) { + this.version++; + this._roll$1 = value; + } + return value; + }, + + get_scale: function () { + return this._scale$1; + }, + + set_scale: function (value) { + if (this._scale$1 !== value) { + this.version++; + this._scale$1 = value; + } + return value; + }, + + get_translate: function () { + return this._translate$1; + }, + + set_translate: function (value) { + if (this._translate$1 !== value) { + this.version++; + this._translate$1 = value; + } + return value; + }, + + get_lightID: function () { + return this._lightID$1; + }, + + set_lightID: function (value) { + this._lightID$1 = value; + return value; + }, + + cleanUp: function () { + this._dirty$1 = true; + }, + + colorChanged: function () { + if (this.object3d != null) { + this.object3d.color = this.get_color(); + } + }, + + writeLayerProperties: function (xmlWriter) { + xmlWriter._writeAttributeString('FlipV', this.get_flipV().toString()); + xmlWriter._writeAttributeString('FlipHandedness', this.get_flipHandedness().toString()); + xmlWriter._writeAttributeString('Smooth', this.get_smooth().toString()); + xmlWriter._writeAttributeString('TwoSidedGeometry', this.get_twoSidedGeometry().toString()); + xmlWriter._writeAttributeString('Heading', this.get_heading().toString()); + xmlWriter._writeAttributeString('Pitch', this.get_pitch().toString()); + xmlWriter._writeAttributeString('Roll', this.get_roll().toString()); + xmlWriter._writeAttributeString('Scale', this.get_scale().toString()); + xmlWriter._writeAttributeString('Translate', this.get_translate().toString()); + xmlWriter._writeAttributeString('LightID', this.get_lightID().toString()); + xmlWriter._writeAttributeString('Obj', this.objType.toString()); + }, + + getParams: function () { + var paramList = new Array(14); + paramList[0] = this._heading$1; + paramList[1] = this._pitch$1; + paramList[2] = this._roll$1; + paramList[3] = this._scale$1.x; + paramList[4] = this._scale$1.y; + paramList[5] = this._scale$1.z; + paramList[6] = this._translate$1.x; + paramList[7] = this._translate$1.y; + paramList[8] = this._translate$1.z; + paramList[9] = this.get_color().r / 255; + paramList[10] = this.get_color().g / 255; + paramList[11] = this.get_color().b / 255; + paramList[12] = this.get_color().a / 255; + paramList[13] = this.get_opacity(); + return paramList; + }, + + getParamNames: function () { + return ['Heading', 'Pitch', 'Roll', 'Scale.X', 'Scale.Y', 'Scale.Z', 'Translate.X', 'Translate.Y', 'Translate.Z', 'Colors.Red', 'Colors.Green', 'Colors.Blue', 'Colors.Alpha', 'Opacity']; + }, + + setParams: function (paramList) { + if (paramList.length === 14) { + this._heading$1 = paramList[0]; + this._pitch$1 = paramList[1]; + this._roll$1 = paramList[2]; + this._scale$1.x = paramList[3]; + this._scale$1.y = paramList[4]; + this._scale$1.z = paramList[5]; + this._translate$1.x = paramList[6]; + this._translate$1.y = paramList[7]; + this._translate$1.z = paramList[8]; + this.set_opacity(paramList[13]); + var color = Color.fromArgb(ss.truncate((paramList[12] * 255)), ss.truncate((paramList[9] * 255)), ss.truncate((paramList[10] * 255)), ss.truncate((paramList[11] * 255))); + this.set_color(color); + } + }, + + add_propertiesChanged: function (value) { + this.__propertiesChanged$1 = ss.bindAdd(this.__propertiesChanged$1, value); + }, + + remove_propertiesChanged: function (value) { + this.__propertiesChanged$1 = ss.bindSub(this.__propertiesChanged$1, value); + }, + + fireChanged: function () { + if (this.__propertiesChanged$1 != null) { + this.__propertiesChanged$1(this, new ss.EventArgs()); + } + }, + + getEditUI: function () { + return ss.safeCast(this, IUiController); + }, + + initializeFromXml: function (node) { + this.set_flipV(ss.boolean(node.attributes.getNamedItem('FlipV').nodeValue)); + if (node.attributes.getNamedItem('FlipHandedness') != null) { + this.set_flipHandedness(ss.boolean(node.attributes.getNamedItem('FlipHandedness').nodeValue)); + } else { + this.set_flipHandedness(false); + } + if (node.attributes.getNamedItem('Smooth') != null) { + this.set_smooth(ss.boolean(node.attributes.getNamedItem('Smooth').nodeValue)); + } else { + this.set_smooth(true); + } + if (node.attributes.getNamedItem('TwoSidedGeometry') != null) { + this.set_twoSidedGeometry(ss.boolean(node.attributes.getNamedItem('TwoSidedGeometry').nodeValue)); + } else { + this.set_twoSidedGeometry(false); + } + if (node.attributes.getNamedItem('Obj') != null) { + this.objType = ss.boolean(node.attributes.getNamedItem('Obj').nodeValue); + } else { + this.objType = false; + } + this.set_heading(parseFloat(node.attributes.getNamedItem('Heading').nodeValue)); + this.set_pitch(parseFloat(node.attributes.getNamedItem('Pitch').nodeValue)); + this.set_roll(parseFloat(node.attributes.getNamedItem('Roll').nodeValue)); + this.set_scale(Vector3d.parse(node.attributes.getNamedItem('Scale').nodeValue)); + this.set_translate(Vector3d.parse(node.attributes.getNamedItem('Translate').nodeValue)); + if (node.attributes.getNamedItem('LightID') != null) { + this.set_lightID(parseInt(node.attributes.getNamedItem('LightID').nodeValue)); + } + }, + + draw: function (renderContext, opacity, flat) { + var oldWorld = renderContext.get_world(); + var rotation = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d._rotationZ(-this._roll$1 / 180 * Math.PI), Matrix3d._rotationX(-this._pitch$1 / 180 * Math.PI)), Matrix3d._rotationY(this._heading$1 / 180 * Math.PI)); + renderContext.set_world(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(rotation, Matrix3d._scaling(this._scale$1.x, this._scale$1.y, this._scale$1.z)), Matrix3d.translation(this._translate$1)), oldWorld)); + renderContext.set_twoSidedLighting(this.get_twoSidedGeometry()); + BasePlanets.drawPointPlanet(renderContext, new Vector3d(), 1, Colors.get_red(), false); + if (this._lightID$1 > 0) { + // draw light + } else { + if (this.object3d != null) { + this.object3d.color = this.get_color(); + this.object3d.render(renderContext, opacity * this.get_opacity()); + } + } + + // todo enable edit UI + + renderContext.set_twoSidedLighting(false); + renderContext.set_world(oldWorld); + return true; + }, + + addFilesToCabinet: function (fc) { + // todo: implement + }, + + loadData: function (doc, filename) { + if (ss.endsWith(filename.toLowerCase(), '.obj')) { + this.objType = true; + } + if (!this._lightID$1) { + if (this.objType) { + this.object3d = new Object3d(doc, ss.replaceString(filename, '.txt', '.obj'), this.get_flipV(), this._flipHandedness$1, true, this.get_color()); + } + else { + this.object3d = new Object3d(doc, ss.replaceString(filename, '.txt', '.3ds'), this.get_flipV(), this._flipHandedness$1, true, this.get_color()); + } + } + }, + + pointToView: function (pnt) { + var clientHeight = globalRenderContext.height; + var clientWidth = globalRenderContext.width; + var viewWidth = (globalRenderContext.width / globalRenderContext.height) * 1116; + var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); + var y = (pnt.y) / clientHeight * 1116; + return Vector2d.create(x, y); + }, + + render: function (renderEngine) { + this._showEditUi$1 = true; + return; + }, + + preRender: function (renderEngine) { + this._showEditUi$1 = true; + return; + }, + + mouseDown: function (sender, e) { + var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + this._pntDown$1 = location; + var pnt = location; + if (e.shiftKey) { + if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 10; + this._valueOnDown$1 = this._scale$1.x; + return true; + } + if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 10; + this._valueOnDown$1 = this._scale$1.y; + return true; + } + if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 10; + this._valueOnDown$1 = this._scale$1.z; + return true; + } + } else { + if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 1; + this._valueOnDown$1 = this._translate$1.x; + return true; + } + if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 2; + this._valueOnDown$1 = this._translate$1.y; + return true; + } + if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { + this._dragMode$1 = 3; + this._valueOnDown$1 = this._translate$1.z; + return true; + } + } + for (var i = 0; i < this._hprHandles$1.length; i++) { + if (Vector2d.subtract(pnt, this._hprHandles$1[i]).get_length() < this._hitDist$1) { + switch (i) { + case 0: + this._dragMode$1 = 4; + this._valueOnDown$1 = this._heading$1; + this._valueOnDown2$1 = this._pitch$1; + return true; + case 1: + this._dragMode$1 = 7; + this._valueOnDown$1 = this._heading$1; + this._valueOnDown2$1 = this._pitch$1; + return true; + case 2: + this._dragMode$1 = 5; + this._valueOnDown$1 = this._pitch$1; + this._valueOnDown2$1 = this._roll$1; + return true; + case 3: + this._dragMode$1 = 8; + this._valueOnDown$1 = this._pitch$1; + this._valueOnDown2$1 = this._roll$1; + return true; + case 4: + this._dragMode$1 = 6; + this._valueOnDown$1 = this._roll$1; + this._valueOnDown2$1 = this._heading$1; + return true; + case 5: + this._dragMode$1 = 9; + this._valueOnDown$1 = this._roll$1; + this._valueOnDown2$1 = this._heading$1; + return true; + default: + break; + } + } + } + return false; + }, + + mouseUp: function (sender, e) { + if (!!this._dragMode$1) { + this._dragMode$1 = 0; + this._lockPreferedAxis$1 = false; + return true; + } + return false; + }, + + mouseMove: function (sender, e) { + var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + if (!!this._dragMode$1) { + var dist = 0; + var distX = location.x - this._pntDown$1.x; + var distY = -(location.y - this._pntDown$1.y); + if (this._lockPreferedAxis$1) { + if (this._preferY$1) { + dist = distY; + this._preferY$1 = true; + Cursor.set_current(Cursors.get_sizeNS()); + } + else { + dist = distX; + this._preferY$1 = false; + Cursor.set_current(Cursors.get_sizeWE()); + } + } + else { + if (Math.abs(distX) > Math.abs(distY)) { + dist = distX; + this._preferY$1 = false; + } + else { + dist = distY; + this._preferY$1 = true; + } + if (dist > 5) { + this._lockPreferedAxis$1 = true; + } + } + switch (this._dragMode$1) { + case 0: + break; + case 1: + this._translate$1.x = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / globalRenderContext.width)); + break; + case 2: + this._translate$1.y = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / globalRenderContext.width)); + break; + case 3: + this._translate$1.z = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / globalRenderContext.width)); + break; + case 4: + this._heading$1 = this._valueOnDown$1 - distX / 4; + this._pitch$1 = this._valueOnDown2$1 + distY / 4; + break; + case 5: + this._pitch$1 = this._valueOnDown$1 + distY / 4; + this._roll$1 = this._valueOnDown2$1 - distX / 4; + break; + case 6: + this._roll$1 = this._valueOnDown$1 + distY / 4; + this._heading$1 = this._valueOnDown2$1 - distX / 4; + break; + case 7: + this._heading$1 = this._valueOnDown$1 - distX / 4; + this._pitch$1 = this._valueOnDown2$1 - distY / 4; + break; + case 8: + this._pitch$1 = this._valueOnDown$1 + distY / 4; + this._roll$1 = this._valueOnDown2$1 + distX / 4; + break; + case 9: + this._roll$1 = this._valueOnDown$1 - distY / 4; + this._heading$1 = this._valueOnDown2$1 - distX / 4; + break; + case 10: + this._scale$1.x = this._scale$1.y = this._scale$1.z = this._valueOnDown$1 * Math.pow(2, (dist / 100)); + break; + default: + break; + } + this.fireChanged(); + return true; + } else { + var pnt = location; + if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { + Cursor.set_current(Cursors.get_sizeAll()); + return true; + } + if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { + Cursor.set_current(Cursors.get_sizeAll()); + return true; + } + if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { + Cursor.set_current(Cursors.get_sizeAll()); + return true; + } + for (var i = 0; i < this._hprHandles$1.length; i++) { + if (Vector2d.subtract(pnt, this._hprHandles$1[i]).get_length() < this._hitDist$1) { + Cursor.set_current(Cursors.get_sizeAll()); + return true; + } + } + } + return false; + }, + + mouseClick: function (sender, e) { + return false; + }, + + click: function (sender, e) { + return false; + }, + + mouseDoubleClick: function (sender, e) { + return false; + }, + + keyDown: function (sender, e) { + return false; + }, + + keyUp: function (sender, e) { + return false; + }, + + hover: function (pnt) { + return false; + } +}; + +registerType("Object3dLayer", [Object3dLayer, Object3dLayer$, Layer, IUiController]); + + +// wwtlib.Group + +export function Group() { + this.startIndex = 0; + this.indexCount = 0; + this.materialIndex = 0; +} + +var Group$ = {}; + +registerType("Group", [Group, Group$, null]); + +// wwtlib.Mesh + +export function Mesh() { + this.boundingSphere = new SphereHull(); +} + +Mesh.create = function (vertices, indices) { + var mesh = new Mesh(); + mesh.vertices = vertices; + mesh.indices = indices; + var points = new Array(vertices.length); + for (var i = 0; i < vertices.length; ++i) { + points[i] = vertices[i].get_position(); + } + mesh.boundingSphere = ConvexHull.findEnclosingSphereFast(points); + return mesh; +}; + +Mesh.createTangent = function (vertices, indices) { + var mesh = new Mesh(); + mesh.tangentVertices = vertices; + mesh.indices = indices; + var points = new Array(mesh.tangentVertices.length); + for (var i = 0; i < mesh.tangentVertices.length; ++i) { + points[i] = mesh.tangentVertices[i].get_position(); + } + mesh.boundingSphere = ConvexHull.findEnclosingSphereFast(points); + return mesh; +}; + +var Mesh$ = { + dispose: function () { + if (this.vertexBuffer != null) { + this.vertexBuffer.dispose(); + this.vertexBuffer = null; + } + if (this.tangentVertexBuffer != null) { + this.tangentVertexBuffer.dispose(); + this.tangentVertexBuffer = null; + } + if (this.indexBuffer != null) { + this.indexBuffer.dispose(); + this.indexBuffer = null; + } + }, + + setObjects: function (objects) { + this._objects = objects; + }, + + // Convert the vertex data to a GPU vertex buffer + commitToDevice: function () { + if (this.vertices != null) { + this.vertexBuffer = PositionNormalTexturedVertexBuffer.create(this.vertices); + } else if (this.tangentVertices != null) { + this.tangentVertexBuffer = PositionNormalTexturedTangentVertexBuffer.create(this.tangentVertices); + } + this.indexBuffer = new IndexBuffer(new Uint32Array(this.indices)); + }, + + beginDrawing: function (renderContext) { + if (this.vertexBuffer != null) { + renderContext._setVertexBuffer(this.vertexBuffer); + } else if (this.tangentVertexBuffer != null) { + renderContext._setVertexBuffer(this.tangentVertexBuffer); + } + if (this.indexBuffer != null) { + renderContext._setIndexBuffer(this.indexBuffer); + } + }, + + drawSubset: function (renderContext, materialIndex) { + if (this.indexBuffer == null || this._objects == null) { + return; + } + this.drawHierarchy(this._objects, materialIndex, renderContext, 0); + }, + + drawHierarchy: function (nodes, materialIndex, renderContext, depth) { + if (depth > 1212) { + return; + } + var $enum1 = ss.enumerate(nodes); + while ($enum1.moveNext()) { + var node = $enum1.current; + if (node.drawGroup != null && node.enabled) { + var $enum2 = ss.enumerate(node.drawGroup); + while ($enum2.moveNext()) { + var group = $enum2.current; + if (group.materialIndex === materialIndex) { + renderContext.gl.drawElements(WEBGL.TRIANGLES, group.indexCount, WEBGL.UNSIGNED_INT, group.startIndex * 4); + } + } + } + this.drawHierarchy(node.children, materialIndex, renderContext, depth + 1); + } + }, + + get_objects: function () { + return this._objects; + }, + + set_objects: function (value) { + this._objects = value; + return value; + } +}; + +registerType("Mesh", [Mesh, Mesh$, null, ss.IDisposable]); + + +// wwtlib.VertexPosition + +export function VertexPosition() { + this.index = 0; +} + +var VertexPosition$ = {}; + +registerType("VertexPosition", [VertexPosition, VertexPosition$, null]); + + +// wwtlib.Object3d + +export function Object3d(tourDoc, filename, flipV, flipHandedness, smooth, color) { + this.flipHandedness = false; + this.flipV = true; + this.smooth = true; + this._mesh = null; // Our mesh object in sysmem + this._meshMaterials = []; + this._meshTextures = []; + this._meshSpecularTextures = []; + this._meshNormalMaps = []; + this.meshFilenames = []; + this.color = Colors.get_white(); + this._textureCache = {}; + this._matFiles = new Array(0); + this._matFileIndex = 0; + this.objects = []; + this._matLib = {}; + this._textureLib = {}; + this._tourDocument = null; + this.issLayer = false; + this._readyToRender = false; + this.useCurrentAmbient = false; + this._dirty = true; + this.color = color; + this.smooth = smooth; + this.flipV = flipV; + this.flipHandedness = flipHandedness; + this.filename = filename; + if (ss.endsWith(this.filename.toLowerCase(), '.obj')) { + this._loadMeshFromObj(tourDoc, this.filename); + } + else { + this._loadMeshFrom3ds(tourDoc, this.filename, 1); + } +} + +Object3d._compareVector3 = function (v0, v1) { + if (v0.x < v1.x) { + return -1; + } + else if (v0.x > v1.x) { + return 1; + } + else if (v0.y < v1.y) { + return -1; + } + else if (v0.y > v1.y) { + return 1; + } + else if (v0.z < v1.z) { + return -1; + } + else if (v0.z > v1.z) { + return 1; + } + else { + return 0; + } +}; + +Object3d._compareVector = function (v0, v1) { + if (v0.x < v1.x) { + return -1; + } + else if (v0.x > v1.x) { + return 1; + } + else if (v0.y < v1.y) { + return -1; + } + else if (v0.y > v1.y) { + return 1; + } + else { + return 0; + } +}; + +Object3d._getMaterialID = function (material, materialNames) { + var index = 0; + var $enum1 = ss.enumerate(materialNames); + while ($enum1.moveNext()) { + var mat = $enum1.current; + if (mat === material) { + return index; + } + index++; + } + return -1; +}; + +Object3d._disposeTextureList = function (textures) { + if (textures != null) { + for (var i = 0; i < textures.length; ++i) { + if (textures[i] != null) { + textures[i].dispose(); + textures[i] = null; + } + } + textures.length = 0; + } +}; + +var Object3d$ = { + _reload: function () { + if (!this.issLayer) { + this.dispose(); + if (ss.endsWith(this.filename.toLowerCase(), '.obj')) { + this._loadMeshFromObj(this._tourDocument, this.filename); + } + else { + this._loadMeshFrom3ds(this._tourDocument, this.filename, 1); + } + } + }, + + // Calculate per-vertex normals by averaging face normals. Normals of adjacent faces with an + // angle of greater than crease angle are not included in the average. CalculateVertexNormalsMerged + // is slower than the other normal generation method, CalculateVertexNormals, but it produces better + // results. Vertices with identical positions (bot possibly different texture coordinates) are treated + // as the same vertex for purposes of normal calculation. This allows smooth normals across texture + // wrap seams. + // + // This method returns an array of vertex normals, one for each index in the index list + _calculateVertexNormalsMerged: function (vertexList, indexList, creaseAngleRad) { + if (!vertexList.length) { + return null; + } + var vertexCount = vertexList.length; + var triangleCount = Math.floor(indexList.length / 3); + + // Create a list of vertices sorted by their positions. This will be used to + // produce a list of vertices with unique positions. + var vertexPositions = []; + for (var vertexIndex = 0; vertexIndex < vertexList.length; ++vertexIndex) { + var vp = new VertexPosition(); + vp.position = vertexList[vertexIndex].get_position(); + vp.index = vertexIndex; + vertexPositions.push(vp); + } + vertexPositions.sort(function (v0, v1) { + return Object3d._compareVector3(v0.position, v1.position); + }); + + // vertexMap will map a vertex index to the index of a vertex with a unique position + var vertexMap = new Array(vertexPositions.length); + var uniqueVertexCount = 0; + for (var vertexIndex = 0; vertexIndex < vertexPositions.length; vertexIndex++) { + if (!vertexIndex || !!Object3d._compareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position)) { + ++uniqueVertexCount; + } + vertexMap[vertexPositions[vertexIndex].index] = uniqueVertexCount - 1; + } + var vertexInstanceCounts = new Array(uniqueVertexCount); + for (var i = 0; i < uniqueVertexCount; i++) { + vertexInstanceCounts[i] = 0; + } + var $enum1 = ss.enumerate(indexList); + while ($enum1.moveNext()) { + var vertexIndex = $enum1.current; + var uniqueIndex = vertexMap[vertexIndex]; + vertexInstanceCounts[uniqueIndex]++; + } + + // vertexInstances contains the list of faces each vertex is referenced in + var vertexInstances = new Array(uniqueVertexCount); + for (var i = 0; i < uniqueVertexCount; ++i) { + var count = vertexInstanceCounts[i]; + if (count > 0) { + vertexInstances[i] = new Array(count); + for (var j = 0; j < count; j++) { + vertexInstances[i][j] = 0; + } + } + } + + // For each vertex, record all faces which include it + for (var i = 0; i < indexList.length; ++i) { + var faceIndex = Math.floor(i / 3); + var uniqueIndex = vertexMap[indexList[i]]; + vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; + } + + // At this point, vertexInstanceCounts should contain nothing but zeroes + + // Compute normals for all faces + var faceNormals = new Array(triangleCount); + for (var i = 0; i < triangleCount; ++i) { + // The face normal is just the cross product of the two edge vectors + var i0 = indexList[i * 3 + 0]; + var i1 = indexList[i * 3 + 1]; + var i2 = indexList[i * 3 + 2]; + var edge0 = Vector3d.subtractVectors(vertexList[i1].get_position(), vertexList[i0].get_position()); + var edge1 = Vector3d.subtractVectors(vertexList[i2].get_position(), vertexList[i1].get_position()); + faceNormals[i] = Vector3d.cross(edge0, edge1); + faceNormals[i].normalize(); + } + + // Finally, average the face normals + var newVertexCount = triangleCount * 3; + var vertexNormals = new Array(newVertexCount); + var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); + for (var i = 0; i < newVertexCount; ++i) { + var vertexIndex = indexList[i]; + var uniqueIndex = vertexMap[vertexIndex]; + var faceNormal = faceNormals[Math.floor(i / 3)]; + var sum = new Vector3d(); + var $enum2 = ss.enumerate(vertexInstances[uniqueIndex]); + while ($enum2.moveNext()) { + var faceIndex = $enum2.current; + var n = faceNormals[faceIndex]; + if (Vector3d.dot(faceNormal, n) > cosCreaseAngle) { + sum.add(n); + } + } + vertexNormals[i] = sum; + vertexNormals[i].normalize(); + } + return vertexNormals; + }, + + // Calculate tangent vectors at each vertex. The 'face tangent' is a direction in the plane of the + // triangle and parallel to the direction of increasing tex coord u, i.e. the partial derivative + // with respect to u of the triangle's plane equation expressed in terms of the texture coordinate + // (u, v). Partial derivatives of the triangles containing a vertex are averaged to compute the + // vertex tangent. Faces are not included in the when the angle formed with the test face is + // greater than the crease angle, or when the texture texture coordinates are not continuous. + // + // This method returns an array of vertex normals, one for each index in the index list + _calculateVertexTangents: function (vertexList, indexList, creaseAngleRad) { + if (!vertexList.length) { + return null; + } + var vertexCount = vertexList.length; + var triangleCount = Math.floor(indexList.length / 3); + + // Create a list of vertices sorted by their positions. This will be used to + // produce a list of vertices with unique positions. + var vertexPositions = []; + for (var vertexIndex = 0; vertexIndex < vertexList.length; ++vertexIndex) { + var vp = new VertexPosition(); + vp.position = vertexList[vertexIndex].get_position(); + vp.index = vertexIndex; + vertexPositions.push(vp); + } + vertexPositions.sort(function (v0, v1) { + return Object3d._compareVector3(v0.position, v1.position); + }); + + // vertexMap will map a vertex index to the index of a vertex with a unique position + var vertexMap = new Array(vertexPositions.length); + var uniqueVertexCount = 0; + for (var vertexIndex = 0; vertexIndex < vertexPositions.length; vertexIndex++) { + if (!vertexIndex || !!Object3d._compareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position)) { + ++uniqueVertexCount; + } + vertexMap[vertexPositions[vertexIndex].index] = (uniqueVertexCount - 1); + } + var vertexInstanceCounts = new Array(uniqueVertexCount); + for (var i = 0; i < uniqueVertexCount; i++) { + vertexInstanceCounts[i] = 0; + } + var $enum1 = ss.enumerate(indexList); + while ($enum1.moveNext()) { + var vertexIndex = $enum1.current; + var uniqueIndex = vertexMap[vertexIndex]; + vertexInstanceCounts[uniqueIndex]++; + } + + // vertexInstances contains the list of faces each vertex is referenced in + var vertexInstances = new Array(uniqueVertexCount); + for (var i = 0; i < uniqueVertexCount; ++i) { + var count = vertexInstanceCounts[i]; + if (count > 0) { + vertexInstances[i] = new Array(count); + for (var j = 0; j < count; j++) { + vertexInstances[i][j] = 0; + } + } + } + + // For each vertex, record all faces which include it + for (var i = 0; i < indexList.length; ++i) { + var faceIndex = Math.floor(i / 3); + var uniqueIndex = vertexMap[indexList[i]]; + vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; + } + + // At this point, vertexInstanceCounts should contain nothing but zeroes + + // Compute partial derivatives for all faces + var partials = new Array(triangleCount); + for (var i = 0; i < triangleCount; ++i) { + var v0 = vertexList[indexList[i * 3 + 0]]; + var v1 = vertexList[indexList[i * 3 + 1]]; + var v2 = vertexList[indexList[i * 3 + 2]]; + var edge0 = Vector3d.subtractVectors(v1.get_position(), v0.get_position()); + var edge1 = Vector3d.subtractVectors(v2.get_position(), v0.get_position()); + var m00 = v1.tu - v0.tu; + var m01 = v1.tv - v0.tv; + var m10 = v2.tu - v0.tu; + var m11 = v2.tv - v0.tv; + var determinant = m00 * m11 - m01 * m10; + if (Math.abs(determinant) < 1E-06) { + if (edge0.lengthSq() > 0) { + // No unique vector; just select one of the edges + partials[i] = edge0; + partials[i].normalize(); + } + else { + // Degenerate edge; just use the unit x vector + partials[i] = Vector3d.create(1, 0, 0); + } + } + else { + // Matrix n is the inverse of m + var invDeterminant = 1 / determinant; + var n00 = m11 * invDeterminant; + var n01 = -m01 * invDeterminant; + var n10 = -m10 * invDeterminant; + var n11 = m00 * invDeterminant; + partials[i] = Vector3d.addVectors(Vector3d.multiplyScalar(edge0, n00), Vector3d.multiplyScalar(edge1, n01)); + partials[i].normalize(); + } + } + + // Finally, average the partial derivatives + var newVertexCount = triangleCount * 3; + var tangents = new Array(newVertexCount); + var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); + for (var i = 0; i < newVertexCount; ++i) { + var vertexIndex = indexList[i]; + var uniqueIndex = vertexMap[vertexIndex]; + var du = partials[Math.floor(i / 3)]; + var sum = new Vector3d(); + var $enum2 = ss.enumerate(vertexInstances[uniqueIndex]); + while ($enum2.moveNext()) { + var faceIndex = $enum2.current; + var T = partials[faceIndex]; + if (Vector3d.dot(du, T) > cosCreaseAngle) { + sum.add(T); + } + } + var N = vertexList[vertexIndex].get_normal(); + + // Make the tangent orthogonal to the vertex normal + tangents[i] = Vector3d.subtractVectors(sum, Vector3d.multiplyScalar(N, Vector3d.dot(N, sum))); + tangents[i].normalize(); + } + return tangents; + }, + + // Calculate per-vertex normals by averaging face normals. Normals of adjacent faces with an + // angle of greater than crease angle are not included in the average. + // + // This method returns an array of vertex normals, one for each index in the index list + _calculateVertexNormals: function (vertexList, indexList, creaseAngleRad) { + var vertexCount = vertexList.length; + var triangleCount = Math.floor(indexList.length / 3); + + // vertexInstanceCounts contains the number of times each vertex is referenced in the mesh + var vertexInstanceCounts = new Array(vertexCount); + var $enum1 = ss.enumerate(indexList); + while ($enum1.moveNext()) { + var vertexIndex = $enum1.current; + vertexInstanceCounts[vertexIndex]++; + } + + // vertexInstances contains the list of faces each vertex is referenced in + var vertexInstances = new Array(vertexCount); + for (var i = 0; i < vertexCount; ++i) { + var count = vertexInstanceCounts[i]; + if (count > 0) { + vertexInstances[i] = new Array(count); + } + } + + // For each vertex, record all faces which include it + for (var i = 0; i < indexList.length; ++i) { + var faceIndex = Math.floor(i / 3); + var vertexIndex = indexList[i]; + vertexInstances[vertexIndex][--vertexInstanceCounts[vertexIndex]] = faceIndex; + } + + // At this point, vertexInstanceCounts should contain nothing but zeroes + + // Compute normals for all faces + var faceNormals = new Array(triangleCount); + for (var i = 0; i < triangleCount; ++i) { + // The face normal is just the cross product of the two edge vectors + var i0 = indexList[i * 3 + 0]; + var i1 = indexList[i * 3 + 1]; + var i2 = indexList[i * 3 + 2]; + var edge0 = Vector3d.subtractVectors(vertexList[i1].get_position(), vertexList[i0].get_position()); + var edge1 = Vector3d.subtractVectors(vertexList[i2].get_position(), vertexList[i1].get_position()); + faceNormals[i] = Vector3d.cross(edge0, edge1); + faceNormals[i].normalize(); + } + + // Finally, average the face normals + var newVertexCount = triangleCount * 3; + var vertexNormals = new Array(newVertexCount); + var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); + for (var i = 0; i < newVertexCount; ++i) { + var vertexIndex = indexList[i]; + var faceNormal = faceNormals[Math.floor(i / 3)]; + var sum = new Vector3d(); + var $enum2 = ss.enumerate(vertexInstances[vertexIndex]); + while ($enum2.moveNext()) { + var faceIndex = $enum2.current; + var n = faceNormals[faceIndex]; + if (Vector3d.dot(faceNormal, n) > cosCreaseAngle) { + sum.add(n); + } + } + vertexNormals[i] = sum; + vertexNormals[i].normalize(); + } + return vertexNormals; + }, + + // Add textures to ensure that we have as many textures as [...] + _addMaterial: function (material) { + this._meshMaterials.push(material); + while (this._meshTextures.length < this._meshMaterials.length) { + this._meshTextures.push(null); + } + while (this._meshSpecularTextures.length < this._meshMaterials.length) { + this._meshSpecularTextures.push(null); + } + while (this._meshNormalMaps.length < this._meshMaterials.length) { + this._meshNormalMaps.push(null); + } + }, + + // Load a color chunk from a 3ds file` + // Colors may be stored in a 3ds file either as 3 floats or 3 bytes + _loadColorChunk: function (br) { + var chunkID = br.readUInt16(); + var chunkLength = br.readUInt32(); + var color = Colors.get_black(); + if ((chunkID === 16 || chunkID === 19) && chunkLength === 18) { + // Need to guard against values outside of [0, 1], otherwise Colors.FromArgb + // will throw an exception. + var r = Math.max(0, Math.min(1, br.readSingle())); + var g = Math.max(0, Math.min(1, br.readSingle())); + var b = Math.max(0, Math.min(1, br.readSingle())); + color = Color.fromArgb(255, ss.truncate((255 * r)), ss.truncate((255 * g)), ss.truncate((255 * b))); + } else if ((chunkID === 17 || chunkID === 18) && chunkLength === 9) { + color = Color.fromArgb(255, br.readByte(), br.readByte(), br.readByte()); + } else { + // Unknown color block; ignore it + br.readBytes(chunkLength - 6); + } + return color; + }, + + // Load a percentage chunk from a 3ds file + // A percentage may be stored as either a float or a 16-bit integer + _loadPercentageChunk: function (br) { + var chunkID = br.readUInt16(); + var chunkLength = br.readUInt32(); + var percentage = 0; + if (chunkID === 48 && chunkLength === 8) { + percentage = br.readUInt16(); + } else if (chunkID === 49 && chunkLength === 10) { + percentage = br.readSingle(); + } else { + // Unknown percentage block; ignore it + br.readBytes(chunkLength - 6); + } + return percentage; + }, + + _loadMeshFromObj: function (doc, filename) { + var $this = this; + + this.filename = filename; + this._tourDocument = doc; + var blob = doc.getFileBlob(filename); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + $this._matFiles = $this._readObjMaterialsFromBin(ss.safeCast(chunck.result, String)); + $this._matFileIndex = 0; + + // pass data to LoadMatLib. It will chain load all the material + // files, then load the obj from this data - hack for having no + // synchronous blob reading in javascript + $this._loadMatLib(ss.safeCast(chunck.result, String)); + }; + chunck.readAsText(blob); + }, + + _readObjMaterialsFromBin: function (data) { + var matFiles = []; + var lines = data.split('\n'); + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var lineraw = $enum1.current; + var line = ss.replaceString(lineraw, ' ', ' '); + var parts = ss.trim(line).split(' '); + if (parts.length > 0) { + switch (parts[0]) { + case 'mtllib': + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + var matFile = path + parts[1]; + matFiles.push(matFile); + break; + } + } + } + return matFiles; + }, + + _readObjFromBin: function (data) { + var objectFound = false; + var objects = []; + var currentObject = new ObjectNode(); + currentObject.name = 'Default'; + var triangleCount = 0; + var vertexCount = 0; + var vertexList = []; + var vertList = []; + var normList = []; + var uvList = []; + vertList.push(new Vector3d()); + normList.push(new Vector3d()); + uvList.push(new Vector2d()); + var indexList = []; + var attribList = []; + var applyLists = []; + var applyListsIndex = []; + var materialNames = []; + var currentMaterialIndex = -1; + var currentMaterial = new Material(); + var currentGroup = new Group(); + var currentIndex = 0; + + // initialize the default material + currentMaterial = new Material(); + currentMaterial.diffuse = this.color; + currentMaterial.ambient = this.color; + currentMaterial.specular = Colors.get_white(); + currentMaterial.specularSharpness = 30; + currentMaterial.opacity = 1; + currentMaterial.isDefault = true; + + // initialize the group + currentGroup.startIndex = 0; + currentGroup.indexCount = 0; + currentGroup.materialIndex = 0; + var lines = data.split('\n'); + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var lineraw = $enum1.current; + var line = ss.replaceString(lineraw, ' ', ' '); + var parts = ss.trim(line).split(' '); + if (parts.length > 0) { + switch (parts[0]) { + case 'mtllib': + // We have to pre-load these now in JavaScript, since we + // can't synchronously load the file and we need file + // contents to interpret the rest of this file + break; + case 'usemtl': + var materialName = parts[1]; + if (ss.keyExists(this._matLib, materialName)) { + if (currentMaterialIndex === -1 && currentIndex > 0) { + this._addMaterial(currentMaterial); + currentMaterialIndex++; + } + if (currentMaterialIndex > -1) { + currentGroup.indexCount = currentIndex - currentGroup.startIndex; + currentObject.drawGroup.push(currentGroup); + } + currentMaterialIndex++; + if (ss.keyExists(this._matLib, materialName)) { + currentMaterial = this._matLib[materialName]; + if (ss.keyExists(this._textureLib, materialName)) { + try { + if (!ss.keyExists(this._textureCache, this._textureLib[materialName])) { + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + var tex = this._tourDocument.getCachedTexture2d(path + this._textureLib[materialName]); + if (tex != null) { + this.meshFilenames.push(this._textureLib[materialName]); + this._textureCache[this._textureLib[materialName]] = tex; + } + } + this._meshTextures.push(this._textureCache[this._textureLib[materialName]]); + } + catch ($e2) { + } + } + this._addMaterial(currentMaterial); + currentGroup = new Group(); + currentGroup.startIndex = currentIndex; + currentGroup.indexCount = 0; + currentGroup.materialIndex = currentMaterialIndex; + } + } + break; + case 'v': + vertexCount++; + if (this.flipHandedness) { + vertList.push(Vector3d.create(-parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); + } + else { + vertList.push(Vector3d.create(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); + } + break; + case 'vn': + if (this.flipHandedness) { + normList.push(Vector3d.create(-parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); + } + else { + normList.push(Vector3d.create(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); + } + break; + case 'vt': + uvList.push(Vector2d.create(parseFloat(parts[1]), (this.flipV) ? (1 - parseFloat(parts[2])) : parseFloat(parts[2]))); + break; + case 'g': + case 'o': + if (objectFound) { + if (currentMaterialIndex > -1) { + currentGroup.indexCount = currentIndex - currentGroup.startIndex; + currentObject.drawGroup.push(currentGroup); + currentGroup = new Group(); + currentGroup.startIndex = currentIndex; + currentGroup.indexCount = 0; + currentGroup.materialIndex = currentMaterialIndex; + } + currentObject = new ObjectNode(); + } + objectFound = true; + if (parts.length > 1) { + currentObject.name = parts[1]; + } + else { + currentObject.name = 'Unnamed'; + } + objects.push(currentObject); + break; + case 'f': + var indexiesA = this._getIndexies(parts[1]); + var indexiesB = this._getIndexies(parts[2]); + var indexiesC = this._getIndexies(parts[3]); + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); + if (this.flipHandedness) { + indexList.push(currentIndex); + indexList.push(currentIndex + 2); + indexList.push(currentIndex + 1); + } + else { + indexList.push(currentIndex); + indexList.push(currentIndex + 1); + indexList.push(currentIndex + 2); + } + triangleCount++; + currentIndex += 3; + if (parts.length > 4) { + var partIndex = 4; + while (partIndex < parts.length) { + if (this.flipHandedness) { + indexiesA = this._getIndexies(parts[1]); + indexiesC = this._getIndexies(parts[partIndex]); + indexiesB = this._getIndexies(parts[partIndex - 1]); + } + else { + indexiesA = this._getIndexies(parts[1]); + indexiesB = this._getIndexies(parts[partIndex - 1]); + indexiesC = this._getIndexies(parts[partIndex]); + } + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); + vertexList.push(PositionNormalTextured.createUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); + indexList.push(currentIndex); + indexList.push(currentIndex + 1); + indexList.push(currentIndex + 2); + triangleCount++; + currentIndex += 3; + partIndex++; + } + } + break; + } + } + } + + if (!objectFound) { + // add the default object + objects.push(currentObject); + } + + if (currentMaterialIndex === -1 && currentIndex > 0) { + this._addMaterial(currentMaterial); + currentMaterialIndex++; + } + + if (currentMaterialIndex > -1) { + currentGroup.indexCount = (currentIndex - currentGroup.startIndex); + currentObject.drawGroup.push(currentGroup); + } + + if (normList.length < 2) { + var degtorag = Math.PI / 180; + var creaseAngleRad = ((this.smooth) ? 170 * degtorag : 45 * degtorag); + var vertexNormals = this._calculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); + var newVertexList = []; + var newVertexCount = indexList.length; + for (var vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) { + var v = vertexList[indexList[vertexIndex]]; + v.set_normal(vertexNormals[vertexIndex]); + newVertexList.push(v); + } + vertexList = newVertexList; + } + this._mesh = Mesh.create(vertexList, indexList); + var rootDummy = new ObjectNode(); + rootDummy.name = 'Root'; + rootDummy.parent = null; + rootDummy.level = -1; + rootDummy.drawGroup = null; + rootDummy.children = objects; + this.objects = []; + this.objects.push(rootDummy); + this._mesh.setObjects(this.objects); + this._mesh.commitToDevice(); + this._dirty = false; + this._readyToRender = true; + }, + + _loadMatLib: function (data) { + var $this = this; + + if (this._matFileIndex < this._matFiles.length) { + var filename = this._matFiles[this._matFileIndex++]; + var blob = this._tourDocument.getFileBlob(filename); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + $this._readMatLibFromBin(ss.safeCast(chunck.result, String)); + $this._loadMatLib(data); + }; + chunck.readAsText(blob); + } else { + this._readObjFromBin(data); + } + }, + + _readMatLibFromBin: function (data) { + try { + var currentMaterial = new Material(); + var materialName = ''; + this._matLib = {}; + this._textureLib = {}; + var lines = data.split('\n'); + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var lineraw = $enum1.current; + var line = lineraw; + var parts = ss.trim(line).split(' '); + if (parts.length > 0) { + switch (parts[0]) { + case 'newmtl': + if (!ss.emptyString(materialName)) { + this._matLib[materialName] = currentMaterial; + } + currentMaterial = new Material(); + currentMaterial.diffuse = Colors.get_white(); + currentMaterial.ambient = Colors.get_white(); + currentMaterial.specular = Colors.get_black(); + currentMaterial.specularSharpness = 30; + currentMaterial.opacity = 1; + materialName = parts[1]; + break; + case 'Ka': + currentMaterial.ambient = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); + break; + case 'map_Kd': + //ENDURE TEXTURES ARE NOT BLACK! + currentMaterial.diffuse = Colors.get_white(); + var textureFilename = parts[1]; + for (var i = 2; i < parts.length; i++) { + textureFilename += ' ' + parts[i]; + } + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + textureFilename = ss.replaceString(textureFilename, '/', '\\'); + if (textureFilename.indexOf('\\') !== -1) { + textureFilename = textureFilename.substring(textureFilename.lastIndexOf('\\') + 1); + } + this._textureLib[materialName] = textureFilename; + break; + case 'Kd': + currentMaterial.diffuse = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); + break; + case 'Ks': + currentMaterial.specular = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); + break; + case 'd': + // Where does this map? + currentMaterial.opacity = parseFloat(parts[1]); + break; + case 'Tr': + // Where does this map? + currentMaterial.opacity = 1 - parseFloat(parts[1]); + break; + case 'illum': + // Where does this map? + var illuminationMode = parseInt(parts[1]); + break; + case 'sharpness': + currentMaterial.specularSharpness = parseFloat(parts[1]); + break; + case 'Ns': + currentMaterial.specularSharpness = 1 + 2 * parseFloat(parts[1]); + currentMaterial.specularSharpness = Math.max(10, currentMaterial.specularSharpness); + break; + } + } + } + if (!ss.emptyString(materialName)) { + this._matLib[materialName] = currentMaterial; + } + } + catch ($e2) { + } + }, + + _getIndexies: function (data) { + var parts = ss.trim(data).split('/'); + var indecies = new Array(3); + if (ss.emptyString(data)) { + return indecies; + } + if (parts.length > 0) { + indecies[0] = parseInt(parts[0]); + } + if (parts.length > 1) { + if (ss.emptyString(parts[1])) { + indecies[1] = 0; + } + else { + indecies[1] = parseInt(parts[1]); + } + } + if (parts.length > 2) { + indecies[2] = parseInt(parts[2]); + } + return indecies; + }, + + _loadMeshFrom3ds: function (doc, filename, scale) { + var $this = this; + + this._tourDocument = doc; + var blob = doc.getFileBlob(filename); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + $this._read3dsFromBin(new BinaryReader(new Uint8Array(chunck.result)), scale); + }; + chunck.readAsArrayBuffer(blob); + }, + + _read3dsFromBin: function (br, scale) { + var i; + var sectionID; + var sectionLength; + var name = ''; + var material = ''; + var triangleCount = 0; + var vertexCount = 0; + var vertexList = []; + var indexList = []; + var attribList = []; + var materialNames = []; + var currentMaterialIndex = -1; + var currentMaterial = new Material(); + var attributeID = 0; + var count = 0; + var lastID = 0; + var exit = false; + var normalMapFound = false; + var offsetX = 0; + var offsetY = 0; + var offsetZ = 0; + var objects = []; + var currentObject = null; + var objHierarchy = []; + var objNames = []; + var objectTable = {}; + var dummyCount = 0; + var length = br.get_length() - 1; + var startMapIndex = 0; + var startTriangleIndex = 0; + + // Loop to scan the whole file + while (br.get_position() < length && !exit) { + sectionID = br.readUInt16(); + sectionLength = br.readUInt32(); + switch (sectionID) { + //This section the begining of the file + case 0x4D4D: + break; + + // This section marks the edit section containing the 3d models (3d3d get it? very punny!) + case 0x3D3D: + break; + + // Object section contains meshes, etc. + case 0x4000: + name = ''; + var b; + do { + b = br.readByte(); + if (b > 0) { + name += String.fromCharCode(b); + } + } while (!!b); + currentObject = new ObjectNode(); + currentObject.name = name; + objects.push(currentObject); + if (!ss.keyExists(objectTable, currentObject.name)) { + objectTable[currentObject.name] = currentObject; + } + break; + + // Marks the start of a mesh section + case 0x4100: + startMapIndex = vertexList.length; + startTriangleIndex = Math.floor(indexList.length / 3); + break; + + // This section has the vertex list.. Maps to Vertext buffer in Direct3d + case 0x4110: + vertexCount = br.readUInt16(); + for (i = 0; i < vertexCount; i++) { + var x = br.readSingle() - offsetX; + var y = br.readSingle() - offsetY; + var z = br.readSingle() - offsetZ; + var vert = PositionNormalTextured._create(x * scale, z * scale, y * scale, 0, 0, 0, 0, 0); + vertexList.push(vert); + } + break; + + // This section is a triangle index list. Maps to Index Buffer in Direct3d + case 0x4120: + var triCount = br.readUInt16(); + triangleCount += triCount; + for (i = 0; i < triCount; i++) { + var aa = br.readUInt16() + startMapIndex; + var bb = br.readUInt16() + startMapIndex; + var cc = br.readUInt16() + startMapIndex; + indexList.push(cc); + indexList.push(bb); + indexList.push(aa); + var flags = br.readUInt16(); + } + break; + + // Material for face from start face to triCount + case 0x4130: + material = ''; + i = 0; + var b1; + do { + b1 = br.readByte(); + if (b1 > 0) { + material += String.fromCharCode(b1); + } + i++; + } while (!!b1); + var triCount = br.readUInt16(); + var applyList = new Array(triCount); + attributeID = Object3d._getMaterialID(material, materialNames); + for (i = 0; i < triCount; i++) { + applyList[i] = br.readUInt16() + startTriangleIndex; + } + currentObject.applyLists.push(applyList); + currentObject.applyListsIndex.push(attributeID); + break; + + // Section for UV texture maps + case 0x4140: + count = br.readUInt16(); + for (i = 0; i < count; i++) { + var vert = vertexList[startMapIndex + i]; + var texCoord = Vector2d.create(br.readSingle(), (this.flipV) ? (1 - br.readSingle()) : br.readSingle()); + vertexList[startMapIndex + i] = PositionNormalTextured.createUV(vert.get_position(), new Vector3d(), texCoord); + } + break; + + // Section for Smoothing Groups ?? + case 0x4160: + var mat = new Array(12); + for (i = 0; i < 12; i++) { + mat[i] = br.readSingle(); + } + if (ss.keyExists(objectTable, name)) { + objectTable[name].localMat = Matrix3d.create(mat[0], mat[1], mat[2], 0, mat[3], mat[4], mat[5], 0, mat[6], mat[7], mat[8], 0, mat[9], mat[10], mat[11], 1); + objectTable[name].localMat.invert(); + } + break; + + // Materials library section + case 0xAFFF: + break; + + // Material Name + case 0xA000: + var matName = ''; + i = 0; + var b2; + do { + b2 = br.readByte(); + if (b2 > 0) { + matName += String.fromCharCode(b2); + } + i++; + } while (!!b2); + materialNames.push(matName); + if (currentMaterialIndex > -1) { + this._addMaterial(currentMaterial); + } + currentMaterialIndex++; + currentMaterial = new Material(); + currentMaterial.diffuse = Colors.get_white(); + currentMaterial.ambient = Colors.get_white(); + currentMaterial.specular = Colors.get_black(); + currentMaterial.specularSharpness = 30; + currentMaterial.opacity = 1; + break; + + // Ambient color + case 0xA010: + currentMaterial.ambient = this._loadColorChunk(br); + break; + + // Diffuse color + case 0xA020: + currentMaterial.diffuse = this._loadColorChunk(br); + break; + + // Specular color + case 0xA030: + currentMaterial.specular = this._loadColorChunk(br); + break; + + // Specular power + case 0xA040: + // This is just a reasonable guess at the mapping from percentage to + // specular exponent used by 3D Studio. + currentMaterial.specularSharpness = 1 + 2 * this._loadPercentageChunk(br); + + // Minimum sharpness of 10 enforced here because of bad specular exponents + // in ISS model. + // TODO: Fix ISS and permit lower specular exponents here + currentMaterial.specularSharpness = Math.max(10, currentMaterial.specularSharpness); + break; + + //Texture map file + case 0xA200: + break; + + // Texture file name + case 0xA300: + var textureFilename = ''; + i = 0; + var b2; + do { + b2 = br.readByte(); + if (b2 > 0) { + textureFilename += String.fromCharCode(b2); + } + i++; + } while (!!b2); + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + try { + var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); + if (tex != null) { + this._meshTextures.push(tex); + this.meshFilenames.push(textureFilename); + // The ISS model has black for the diffuse color; to work around this + // we'll set the diffuse color to white when there's a texture present. + // The correct fix is to modify the 3ds model of ISS. + currentMaterial.diffuse = Colors.get_white(); + } + else { + this._meshTextures.push(null); + } + } + catch ($e1) { + this._meshTextures.push(null); + } + break; + + // Bump map + case 0xA230: + var percentage = this._loadPercentageChunk(br); + var nameId = br.readUInt16(); + var nameBlockLength = br.readUInt32(); + var textureFilename = ''; + i = 0; + var b2; + do { + b2 = br.readByte(); + if (b2 > 0) { + textureFilename += String.fromCharCode(b2); + } + i++; + } while (!!b2); + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + try { + var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); + if (tex != null) { + this._meshNormalMaps.push(tex); + this.meshFilenames.push(textureFilename); + // Indicate that we have a normal map so that we know to generate tangent vectors for the mesh + normalMapFound = true; + } + else { + this._meshNormalMaps.push(null); + } + } + catch ($e2) { + this._meshNormalMaps.push(null); + } + break; + + // Specular map + case 0xA204: + var strength = this._loadPercentageChunk(br); + var nameId = br.readUInt16(); + var nameBlockLength = br.readUInt32(); + var textureFilename = ''; + i = 0; + var b2; + do { + b2 = br.readByte(); + if (b2 > 0) { + textureFilename += String.fromCharCode(b2); + } + i++; + } while (!!b2); + var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); + try { + var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); + if (tex != null) { + this._meshSpecularTextures.push(tex); + this.meshFilenames.push(textureFilename); + // Set the current specular color from the specular texture strength + var gray = ss.truncate((255.99 * strength / 100)); + currentMaterial.specular = Color.fromArgb(255, gray, gray, gray); + } + else { + this._meshSpecularTextures.push(null); + } + } + catch ($e3) { + this._meshSpecularTextures.push(null); + } + break; + + case 0xB000: + break; + case 0xB002: + break; + case 0xB010: + name = ''; + i = 0; + var b1; + do { + b1 = br.readByte(); + if (b1 > 0) { + name += String.fromCharCode(b1); + } + i++; + } while (!!b1); + var dum1 = br.readUInt16(); + var dum2 = br.readUInt16(); + var level = br.readUInt16(); + if (level === 65535) { + level = -1; + } + if (ss.startsWith(name, '$')) { + dummyCount++; + } + else { + objNames.push(name); + } + objHierarchy.push(level); + if (ss.keyExists(objectTable, name)) { + objectTable[name].level = level; + } + break; + + case 0xB011: + name = ''; + i = 0; + var b1; + do { + b1 = br.readByte(); + if (b1 > 0) { + name += String.fromCharCode(b1); + } + i++; + } while (!!b1); + objNames.push('$$$' + name); + break; + + case 0xB013: + // pivot point + var points = new Array(3); + for (i = 0; i < 3; i++) { + points[i] = br.readSingle(); + } + if (ss.keyExists(objectTable, name)) { + objectTable[name].pivotPoint = Vector3d.create(-points[0], -points[1], -points[2]); + } + break; + + case 0xB020: + var pos = new Array(8); + for (i = 0; i < 8; i++) { + pos[i] = br.readSingle(); + } + break; + + // If we don't recognize a section then jump over it. Subract the header from the section length + default: + br.seekRelative((sectionLength - 6)); + break; + } + + lastID = sectionID; + } + + br.close(); + if (currentMaterialIndex > -1) { + this._addMaterial(currentMaterial); + } + + // Generate vertex normals + + // Vertex normals are computed by averaging the normals of all faces + // with an angle between them less than the crease angle. By setting + // the crease angle to 0 degrees, the model will have a faceted appearance. + // Right now, the smooth flag selects between one of two crease angles, + // but some smoothing is always applied. + + var degtorag = Math.PI / 180; + var creaseAngleRad = ((this.smooth) ? 70 * degtorag : 45 * degtorag); + var vertexNormals = this._calculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); + var newVertexList = []; + var newVertexCount = triangleCount * 3; + for (var vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) { + var v = vertexList[indexList[vertexIndex]]; + v.set_normal(vertexNormals[vertexIndex]); + newVertexList.push(v); + } + + // Use the triangle mesh and material assignments to create a single + // index list for the mesh. + var newIndexList = []; + var $enum4 = ss.enumerate(objects); + while ($enum4.moveNext()) { + var node = $enum4.current; + var materialGroups = []; + for (i = 0; i < node.applyLists.length; i++) { + var matId = node.applyListsIndex[i]; + var startIndex = newIndexList.length; + var $enum5 = ss.enumerate(node.applyLists[i]); + while ($enum5.moveNext()) { + var triangleIndex = $enum5.current; + newIndexList.push((triangleIndex * 3)); + newIndexList.push((triangleIndex * 3 + 1)); + newIndexList.push((triangleIndex * 3 + 2)); + } + var group = new Group(); + group.startIndex = startIndex; + group.indexCount = node.applyLists[i].length * 3; + group.materialIndex = matId; + materialGroups.push(group); + } + node.drawGroup = materialGroups; + } + + // Turn objects into tree + var nodeStack = new ss.Stack(); + var nodeTreeRoot = []; + var rootDummy = new ObjectNode(); + rootDummy.name = 'Root'; + rootDummy.parent = null; + rootDummy.level = -1; + rootDummy.drawGroup = null; + var currentLevel = -1; + nodeStack.push(rootDummy); + nodeTreeRoot.push(rootDummy); + for (i = 0; i < objHierarchy.length; i++) { + var level = objHierarchy[i]; + if (level <= currentLevel) { + // pop out all the nodes to intended parent + while (level <= nodeStack.peek().level && nodeStack.count > 1) { + nodeStack.pop(); + } + currentLevel = level; + } + if (ss.startsWith(objNames[i], '$$$')) { + var dummy = new ObjectNode(); + dummy.name = ss.replaceString(objNames[i], '$$$', ''); + dummy.parent = nodeStack.peek(); + dummy.parent.children.push(dummy); + dummy.level = currentLevel = level; + dummy.drawGroup = null; + nodeStack.push(dummy); + } + else { + objectTable[objNames[i]].level = currentLevel = level; + objectTable[objNames[i]].parent = nodeStack.peek(); + objectTable[objNames[i]].parent.children.push(objectTable[objNames[i]]); + nodeStack.push(objectTable[objNames[i]]); + } + } + if (!objHierarchy.length) { + var $enum6 = ss.enumerate(objects); + while ($enum6.moveNext()) { + var node = $enum6.current; + rootDummy.children.push(node); + node.parent = rootDummy; + } + } + if (normalMapFound) { + // If we've got a normal map, we want to generate tangent vectors for the mesh + + // Mapping of vertices to geometry is extremely straightforward now, but this could + // change when a mesh optimization step is introduced. + var tangentIndexList = []; + for (var tangentIndex = 0; tangentIndex < newVertexCount; ++tangentIndex) { + tangentIndexList.push(tangentIndex); + } + var tangents = this._calculateVertexTangents(newVertexList, tangentIndexList, creaseAngleRad); + + // Copy the tangents in the vertex data list + var vertices = new Array(newVertexList.length); + var vertexIndex = 0; + var $enum7 = ss.enumerate(newVertexList); + while ($enum7.moveNext()) { + var v = $enum7.current; + var tvertex = new PositionNormalTexturedTangent(v.get_position(), v.get_normal(), Vector2d.create(v.tu, v.tv), tangents[vertexIndex]); + vertices[vertexIndex] = tvertex; + ++vertexIndex; + } + this._mesh = Mesh.createTangent(vertices, newIndexList); + } else { + this._mesh = Mesh.create(newVertexList, newIndexList); + } + this.objects = nodeTreeRoot; + this._mesh.setObjects(nodeTreeRoot); + this._mesh.commitToDevice(); + this._dirty = false; + this._readyToRender = true; + }, + + _offsetObjects: function (vertList, objects, offsetMat, offsetPoint) { + var $enum1 = ss.enumerate(objects); + while ($enum1.moveNext()) { + var node = $enum1.current; + var matLoc = node.localMat; + this._offsetObjects(vertList, node.children, matLoc, Vector3d.addVectors(node.pivotPoint, offsetPoint)); + var $enum2 = ss.enumerate(node.drawGroup); + while ($enum2.moveNext()) { + var group = $enum2.current; + var end = group.startIndex + group.indexCount; + for (var i = group.startIndex; i < end; i++) { + var vert = vertList[i]; + vert.set_position(Vector3d.addVectors(vert.get_position(), Vector3d.addVectors(node.pivotPoint, offsetPoint))); + vertList[i] = vert; + } + } + } + }, + + // Set up lighting state to account for: + // - Light reflected from a nearby planet + // - Shadows cast by nearby planets + setupLighting: function (renderContext) { + var objPosition = Vector3d.create(renderContext.get_world().get_offsetX(), renderContext.get_world().get_offsetY(), renderContext.get_world().get_offsetZ()); + var objToLight = Vector3d.subtractVectors(objPosition, renderContext.get_reflectedLightPosition()); + var sunPosition = Vector3d.subtractVectors(renderContext.get_sunPosition(), renderContext.get_reflectedLightPosition()); + var cosPhaseAngle = (sunPosition.length() <= 0) ? 1 : Vector3d.dot(objToLight, sunPosition) / (objToLight.length() * sunPosition.length()); + var reflectedLightFactor = Math.max(0, cosPhaseAngle); + reflectedLightFactor = Math.sqrt(reflectedLightFactor); // Tweak falloff of reflected light + var hemiLightFactor = 0; + + // 1. Reduce the amount of sunlight when the object is in the shadow of a planet + // 2. Introduce some lighting due to scattering by the planet's atmosphere if it's + // close to the surface. + var sunlightFactor = 1; + if (renderContext.get_occludingPlanetRadius() > 0) { + var objAltitude = Vector3d.subtractVectors(objPosition, renderContext.get_occludingPlanetPosition()).length() - renderContext.get_occludingPlanetRadius(); + hemiLightFactor = Math.max(0, Math.min(1, 1 - (objAltitude / renderContext.get_occludingPlanetRadius()) * 300)); + reflectedLightFactor *= (1 - hemiLightFactor); + + // Compute the distance from the center of the object to the line between the sun and occluding planet + // We're assuming that the radius of the object is very small relative to Earth; + // for large objects the amount of shadow will vary, and we should use circular + // eclipse shadows. + var sunToPlanet = Vector3d.subtractVectors(renderContext.get_occludingPlanetPosition(), renderContext.get_sunPosition()); + var objToPlanet = Vector3d.subtractVectors(renderContext.get_occludingPlanetPosition(), objPosition); + var hemiLightDirection = Vector3d.create(-objToPlanet.x, -objToPlanet.y, -objToPlanet.z); + hemiLightDirection.normalize(); + renderContext.set_hemisphereLightUp(hemiLightDirection); + var objToSun = Vector3d.subtractVectors(renderContext.get_sunPosition(), objPosition); + var sunPlanetDistance = sunToPlanet.length(); + var t = -Vector3d.dot(objToSun, sunToPlanet) / (sunPlanetDistance * sunPlanetDistance); + if (t > 1) { + // Object is on the side of the planet opposite the sun, so a shadow is possible + + // Compute the position of the object projected onto the shadow axis + var shadowAxisPoint = Vector3d.addVectors(renderContext.get_sunPosition(), Vector3d.multiplyScalar(sunToPlanet, t)); + + // d is the distance to the shadow axis + var d = Vector3d.subtractVectors(shadowAxisPoint, objPosition).length(); + + // s is the distance from the sun along the shadow axis + var s = Vector3d.subtractVectors(shadowAxisPoint, renderContext.get_sunPosition()).length(); + + // Use the sun's radius to accurately compute the penumbra and umbra cones + var solarRadius = 0.004645784; + var penumbraRadius = renderContext.get_occludingPlanetRadius() + (t - 1) * (renderContext.get_occludingPlanetRadius() + solarRadius); + var umbraRadius = renderContext.get_occludingPlanetRadius() + (t - 1) * (renderContext.get_occludingPlanetRadius() - solarRadius); + if (d < penumbraRadius) { + // The object is inside the penumbra, so it is at least partly shadowed + var minimumShadow = 0; + if (umbraRadius < 0) { + // No umbra at this point; degree of shadowing is limited because the + // planet doesn't completely cover the sun even when the object is positioned + // exactly on the shadow axis. + var occlusion = Math.pow(1 / (1 - umbraRadius), 2); + umbraRadius = 0; + minimumShadow = 1 - occlusion; + } + + // Approximate the amount of shadow with linear interpolation. The accurate + // calculation involves computing the area of the intersection of two circles. + var u = Math.max(0, umbraRadius); + sunlightFactor = Math.max(minimumShadow, (d - u) / (penumbraRadius - u)); + var gray = ss.truncate((255.99 * sunlightFactor)); + renderContext.set_sunlightColor(Color.fromArgb(255, gray, gray, gray)); + + // Reduce sky-scattered light as well + hemiLightFactor *= sunlightFactor; + } + } + } + renderContext.set_reflectedLightColor(Color.fromArgb(255, ss.truncate((renderContext.get_reflectedLightColor().r * reflectedLightFactor)), ss.truncate((renderContext.get_reflectedLightColor().g * reflectedLightFactor)), ss.truncate((renderContext.get_reflectedLightColor().b * reflectedLightFactor)))); + renderContext.set_hemisphereLightColor(Color.fromArgb(255, ss.truncate((renderContext.get_hemisphereLightColor().r * hemiLightFactor)), ss.truncate((renderContext.get_hemisphereLightColor().g * hemiLightFactor)), ss.truncate((renderContext.get_hemisphereLightColor().b * hemiLightFactor)))); + }, + + render: function (renderContext, opacity) { + if (!this._readyToRender) { + return; + } + if (this._dirty && !this.issLayer) { + this._reload(); + } + var oldWorld = renderContext.get_world(); + var offset = this._mesh.boundingSphere.center; + var unitScale = 1; + if (this._mesh.boundingSphere.radius > 0) { + unitScale = 1 / this._mesh.boundingSphere.radius; + } + renderContext.set_world(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.translation(Vector3d.create(-offset.x, -offset.y, -offset.z)), Matrix3d._scaling(unitScale, unitScale, unitScale)), oldWorld)); + var worldView = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); + var v = worldView.transform(Vector3d.get_empty()); + var scaleFactor = Math.sqrt(worldView.get_m11() * worldView.get_m11() + worldView.get_m22() * worldView.get_m22() + worldView.get_m33() * worldView.get_m33()) / unitScale; + var dist = v.length(); + var radius = scaleFactor; + + // Calculate pixelsPerUnit which is the number of pixels covered + // by an object 1 AU at the distance of the planet center from + // the camera. This calculation works regardless of the projection + // type. + var viewportHeight = ss.truncate(renderContext.height); + var p11 = renderContext.get_projection().get_m11(); + var p34 = renderContext.get_projection().get_m34(); + var p44 = renderContext.get_projection().get_m44(); + var w = Math.abs(p34) * dist + p44; + var pixelsPerUnit = (p11 / w) * viewportHeight; + var radiusInPixels = (radius * pixelsPerUnit); + if (radiusInPixels < 0.5) { + // Too small to be visible; skip rendering + return; + } + + // These colors can be modified by shadows, distance from planet, etc. Restore + // the original values after rendering. + var savedSunlightColor = renderContext.get_sunlightColor(); + var savedReflectedColor = renderContext.get_reflectedLightColor(); + var savedHemiColor = renderContext.get_hemisphereLightColor(); + if (Settings.get_current().get_solarSystemLighting()) { + this.setupLighting(renderContext); + if (!this.useCurrentAmbient) { + renderContext.set_ambientLightColor(Color.fromArgb(255, 11, 11, 11)); + } + } else { + // No lighting: set ambient light to white and turn off all other light sources + renderContext.set_sunlightColor(Colors.get_black()); + renderContext.set_reflectedLightColor(Colors.get_black()); + renderContext.set_hemisphereLightColor(Colors.get_black()); + renderContext.set_ambientLightColor(Colors.get_white()); + } + if (this._mesh == null) { + return; + } + ModelShader.minLightingBrightness = 0.1; + var count = this._meshMaterials.length; + this._mesh.beginDrawing(renderContext); + if (count > 0) { + for (var i = 0; i < this._meshMaterials.length; i++) { + if (this._meshMaterials[i].isDefault) { + var mat = this._meshMaterials[i]; + mat.diffuse = this.color; + mat.ambient = this.color; + this._meshMaterials[i] = mat; + } + + // Set the material and texture for this subset + renderContext.setMaterial(this._meshMaterials[i], this._meshTextures[i], this._meshSpecularTextures[i], this._meshNormalMaps[i], opacity); + if (this._mesh.vertexBuffer != null) { + ModelShader.use(renderContext, this._mesh.vertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 32); + } + else { + ModelShader.use(renderContext, this._mesh.tangentVertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 44); + } + renderContext.preDraw(); + this._mesh.drawSubset(renderContext, i); + } + } else { + renderContext.preDraw(); + for (var i = 0; i < this._meshTextures.length; i++) { + if (this._meshTextures[i] != null) { + renderContext.set_mainTexture(this._meshTextures[i]); + if (this._mesh.vertexBuffer != null) { + ModelShader.use(renderContext, this._mesh.vertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 32); + } + else { + ModelShader.use(renderContext, this._mesh.tangentVertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 44); + } + } + renderContext.preDraw(); + this._mesh.drawSubset(renderContext, i); + } + } + renderContext.set_world(oldWorld); + renderContext.set_sunlightColor(savedSunlightColor); + renderContext.set_reflectedLightColor(savedReflectedColor); + renderContext.set_hemisphereLightColor(savedHemiColor); + renderContext.set_ambientLightColor(Colors.get_black()); + }, + + dispose: function () { + if (this._mesh != null) { + this._mesh.dispose(); + this._mesh = null; + } + var $enum1 = ss.enumerate(ss.keys(this._textureCache)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var tex = this._textureCache[key]; + if (tex != null) { + tex.dispose(); + } + } + ss.clearKeys(this._textureCache); + Object3d._disposeTextureList(this._meshTextures); + Object3d._disposeTextureList(this._meshSpecularTextures); + Object3d._disposeTextureList(this._meshNormalMaps); + this._meshMaterials.length = 0; + this._dirty = true; + } +}; + +registerType("Object3d", [Object3d, Object3d$, null]); + + +// wwtlib.ObjectNode + +export function ObjectNode() { + this.level = -1; + this.children = []; + this.enabled = true; + this.drawGroup = []; + this.applyLists = []; + this.applyListsIndex = []; +} + +var ObjectNode$ = {}; + +registerType("ObjectNode", [ObjectNode, ObjectNode$, null]); + + +// wwtlib.Object3dLayerUI + +export function Object3dLayerUI(layer) { + this._layer$1 = null; + this._opened$1 = true; + this._callbacks$1 = null; + LayerUI.call(this); + this._layer$1 = layer; +} + +var Object3dLayerUI$ = { + setUICallbacks: function (callbacks) { + this._callbacks$1 = callbacks; + }, + + get_hasTreeViewNodes: function () { + return true; + }, + + getTreeNodes: function () { + var nodes = []; + if (this._layer$1.object3d.objects.length > 0 && this._layer$1.object3d.objects[0].children != null) { + this._loadTree$1(nodes, this._layer$1.object3d.objects[0].children); + } + return nodes; + }, + _loadTree$1: function (nodes, children) { + var $enum1 = ss.enumerate(children); + while ($enum1.moveNext()) { + var child = $enum1.current; + var node = new LayerUITreeNode(); + node.set_name(child.name); + node.set_tag(child); + node.set_checked(child.enabled); + node.add_nodeSelected(ss.bind('_node_NodeSelected$1', this)); + node.add_nodeChecked(ss.bind('_node_NodeChecked$1', this)); + nodes.push(node); + this._loadTree$1(node.get_nodes(), child.children); + } + }, + _node_NodeChecked$1: function (node, newState) { + var child = node.get_tag(); + if (child != null) { + child.enabled = newState; + } + }, + _node_NodeSelected$1: function (node) { + if (this._callbacks$1 != null) { + var child = node.get_tag(); + var rowData = {}; + rowData['Name'] = child.name; + rowData['Pivot.X'] = child.pivotPoint.x.toString(); + rowData['Pivot.Y'] = child.pivotPoint.y.toString(); + rowData['Pivot.Z'] = child.pivotPoint.z.toString(); + this._callbacks$1.showRowData(rowData); + } + }, + + getNodeContextMenu: function (node) { + return LayerUI.prototype.getNodeContextMenu.call(this, node); + } +}; + +registerType("Object3dLayerUI", [Object3dLayerUI, Object3dLayerUI$, LayerUI]); diff --git a/engine/esm/layers/orbit.js b/engine/esm/layers/orbit.js new file mode 100644 index 00000000..46bef442 --- /dev/null +++ b/engine/esm/layers/orbit.js @@ -0,0 +1,157 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Arbitrary orbits and how we render them. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Vector3d, Matrix3d } from "../double3d.js"; +import { WEBGL } from "../graphics/webgl_constants.js"; +import { EllipseShader } from "../graphics/shaders.js"; +import { PositionVertexBuffer } from "../graphics/gl_buffers.js"; +import { Color, Colors } from "../color.js"; +import { Coordinates } from "../coordinates.js"; +import { SpaceTimeController } from "../space_time_controller.js"; + + +// wwtlib.Orbit + +export function Orbit(elements, segments, color, thickness, scale) { + this._elements = null; + this._orbitColor = Colors.get_white(); + this._scale = 0; + this._segmentCount = 0; + this._elements = elements; + this._segmentCount = segments; + this._orbitColor = color; + this._scale = scale; +} + +// Convert from standard coordinate system with z normal to the orbital plane +// to WWT's system where y is the normal. Note that this transformation is not +// a pure rotation: it incorporates a reflection, because the two systems have +// different handedness. +Orbit._orbitalToWwt = Matrix3d.create(1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1); +Orbit._initBegun = false; + +var Orbit$ = { + cleanUp: function () { }, + + // Get the radius of a sphere (centered at a focus of the ellipse) that is + // large enough to contain the orbit. The value returned has units of the orbit scale. + get_boundingRadius: function () { + if (this._elements != null) { + return (this._elements.a * (1 + this._elements.e)) / this._scale; + } else { + return 0; + } + }, + + draw3D: function (renderContext, opacity, centerPoint) { + // Extra transformation required because the ellipse shader uses the xy-plane, but WWT uses the + // xz-plane as the reference. + var orbitalPlaneOrientation = Matrix3d.multiplyMatrix(Matrix3d._rotationZ(Coordinates.degreesToRadians(this._elements.w)), Matrix3d.multiplyMatrix(Matrix3d._rotationX(Coordinates.degreesToRadians(this._elements.i)), Matrix3d._rotationZ(Coordinates.degreesToRadians(this._elements.omega)))); + orbitalPlaneOrientation = Matrix3d.multiplyMatrix(orbitalPlaneOrientation, Orbit._orbitalToWwt); + + var worldMatrix = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(orbitalPlaneOrientation, Matrix3d.translation(centerPoint)), renderContext.get_world()); + var M = this._elements.n * (SpaceTimeController.get_jNow() - this._elements.t); + var F = 1; + if (M < 0) { + F = -1; + } + M = Math.abs(M) / 360; + M = (M - ss.truncate(M)) * 360 * F; + var color = Color._fromArgbColor(ss.truncate((opacity * 255)), this._orbitColor); + + // Newton-Raphson iteration to solve Kepler's equation. + // This is faster than calling CAAKepler.Calculate(), and 5 steps + // is more than adequate for draw the orbit paths of small satellites + // (which are ultimately rendered using single-precision floating point.) + M = Coordinates.degreesToRadians(M); + var E = M; + for (var i = 0; i < 5; i++) { + E += (M - E + this._elements.e * Math.sin(E)) / (1 - this._elements.e * Math.cos(E)); + } + EllipseRenderer.drawEllipse(renderContext, this._elements.a / this._scale, this._elements.e, E, color, worldMatrix); + } +}; + +registerType("Orbit", [Orbit, Orbit$, null]); + + +// wwtlib.EllipseRenderer + +export function EllipseRenderer() { } + +// Draw an ellipse with the specified semi-major axis and eccentricity. The orbit is drawn over a single period, +// fading from full brightness at the given eccentric anomaly. +// +// In order to match exactly the position at which a planet is drawn, the planet's position at the current time +// must be passed as a parameter. positionNow is in the current coordinate system of the render context, not the +// translated and rotated system of the orbital plane. +EllipseRenderer.drawEllipseWithPosition = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, worldMatrix, positionNow) { + if (EllipseRenderer._ellipseShader == null) { + EllipseRenderer._ellipseShader = new EllipseShader(); + } + if (EllipseRenderer._ellipseVertexBuffer == null) { + EllipseRenderer._ellipseVertexBuffer = EllipseRenderer.createEllipseVertexBuffer(500); + } + var savedWorld = renderContext.get_world(); + renderContext.set_world(worldMatrix); + renderContext.gl.bindBuffer(WEBGL.ARRAY_BUFFER, EllipseRenderer._ellipseVertexBuffer.vertexBuffer); + renderContext.gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + EllipseShader.use(renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, 1, savedWorld, positionNow); + renderContext.gl.drawArrays(WEBGL.LINE_STRIP, 0, EllipseRenderer._ellipseVertexBuffer.count); + renderContext.set_world(savedWorld); +}; + +// This version of DrawEllipse works without a 'head' point +EllipseRenderer.drawEllipse = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, worldMatrix) { + if (EllipseRenderer._ellipseShader == null) { + EllipseRenderer._ellipseShader = new EllipseShader(); + } + if (EllipseRenderer._ellipseWithoutStartPointVertexBuffer == null) { + EllipseRenderer._ellipseWithoutStartPointVertexBuffer = EllipseRenderer.createEllipseVertexBufferWithoutStartPoint(360); + } + var savedWorld = renderContext.get_world(); + renderContext.set_world(worldMatrix); + renderContext.gl.bindBuffer(WEBGL.ARRAY_BUFFER, EllipseRenderer._ellipseWithoutStartPointVertexBuffer.vertexBuffer); + renderContext.gl.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, null); + EllipseShader.use(renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, 1, savedWorld, Vector3d.create(0, 0, 0)); + renderContext.gl.drawArrays(WEBGL.LINE_STRIP, 0, EllipseRenderer._ellipseWithoutStartPointVertexBuffer.count - 1); + renderContext.set_world(savedWorld); +}; + +EllipseRenderer.createEllipseVertexBuffer = function (vertexCount) { + var vb = new PositionVertexBuffer(vertexCount); + var verts = vb.lock(); + var index = 0; + + // Pack extra samples into the front of the orbit to avoid obvious segmentation + // when viewed from near the planet or moon. + for (var i = 0; i < vertexCount / 2; ++i) { + verts[index++] = Vector3d.create(2 * i / vertexCount * 0.05, 0, 0); + } + for (var i = 0; i < vertexCount / 2; ++i) { + verts[index++] = Vector3d.create(2 * i / vertexCount * 0.95 + 0.05, 0, 0); + } + vb.unlock(); + return vb; +}; + +EllipseRenderer.createEllipseVertexBufferWithoutStartPoint = function (vertexCount) { + var vb = new PositionVertexBuffer(vertexCount); + var verts = vb.lock(); + + // Setting a non-zero value will prevent the ellipse shader from using the 'head' point + verts[0] = Vector3d.create(1E-06, 0, 0); + for (var i = 1; i < vertexCount; ++i) { + verts[i] = Vector3d.create(2 * i / vertexCount, 0, 0); + } + vb.unlock(); + return vb; +}; + +var EllipseRenderer$ = {}; + +registerType("EllipseRenderer", [EllipseRenderer, EllipseRenderer$, null]); diff --git a/engine/esm/layers/orbit_layer.js b/engine/esm/layers/orbit_layer.js new file mode 100644 index 00000000..dff864b6 --- /dev/null +++ b/engine/esm/layers/orbit_layer.js @@ -0,0 +1,257 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders an orbit. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Vector3d } from "../double3d.js"; +import { Color, Colors } from "../color.js"; +import { Layer } from "./layer.js"; +import { LayerUI, LayerUITreeNode } from "./layer_ui.js"; +import { Orbit } from "./orbit.js"; +import { ReferenceFrame } from "./reference_frame.js"; + + +// wwtlib.OrbitLayer + +export function OrbitLayer() { + this._frames$1 = []; + this._primaryUI$1 = null; + this._pointOpacity$1 = 1; + this._pointColor$1 = Colors.get_yellow(); + this._filename$1 = ''; + this._dataFile$1 = ''; + Layer.call(this); +} + +var OrbitLayer$ = { + get_frames: function () { + return this._frames$1; + }, + + set_frames: function (value) { + this._frames$1 = value; + return value; + }, + + getPrimaryUI: function () { + if (this._primaryUI$1 == null) { + this._primaryUI$1 = new OrbitLayerUI(this); + } + return this._primaryUI$1; + }, + + cleanUp: function () { + var $enum1 = ss.enumerate(this._frames$1); + while ($enum1.moveNext()) { + var frame = $enum1.current; + if (frame.get_orbit() != null) { + frame.get_orbit().cleanUp(); + frame.set_orbit(null); + } + } + }, + + writeLayerProperties: function (xmlWriter) { + xmlWriter._writeAttributeString('PointOpacity', this.get_pointOpacity().toString()); + xmlWriter._writeAttributeString('PointColor', this._pointColor$1.save()); + }, + + get_pointOpacity: function () { + return this._pointOpacity$1; + }, + + set_pointOpacity: function (value) { + if (this._pointOpacity$1 !== value) { + this.version++; + this._pointOpacity$1 = value; + } + return value; + }, + + get_pointColor: function () { + return this._pointColor$1; + }, + + set_pointColor: function (value) { + if (this._pointColor$1 !== value) { + this.version++; + this._pointColor$1 = value; + } + return value; + }, + + getParams: function () { + var paramList = new Array(6); + paramList[0] = this._pointOpacity$1; + paramList[1] = this.get_color().r / 255; + paramList[2] = this.get_color().g / 255; + paramList[3] = this.get_color().b / 255; + paramList[4] = this.get_color().a / 255; + paramList[5] = this.get_opacity(); + return paramList; + }, + + getParamNames: function () { + return ['PointOpacity', 'Color.Red', 'Color.Green', 'Color.Blue', 'Color.Alpha', 'Opacity']; + }, + + setParams: function (paramList) { + if (paramList.length === 6) { + this._pointOpacity$1 = paramList[0]; + this.set_opacity(paramList[5]); + var color = Color.fromArgb(ss.truncate((paramList[4] * 255)), ss.truncate((paramList[1] * 255)), ss.truncate((paramList[2] * 255)), ss.truncate((paramList[3] * 255))); + this.set_color(color); + } + }, + + initializeFromXml: function (node) { + this.set_pointOpacity(parseFloat(node.attributes.getNamedItem('PointOpacity').nodeValue)); + this.set_pointColor(Color.load(node.attributes.getNamedItem('PointColor').nodeValue)); + }, + + draw: function (renderContext, opacity, flat) { + var matSaved = renderContext.get_world(); + renderContext.set_world(renderContext.get_worldBaseNonRotating()); + var $enum1 = ss.enumerate(this._frames$1); + while ($enum1.moveNext()) { + var frame = $enum1.current; + if (frame.showOrbitPath) { + if (frame.get_orbit() == null) { + frame.set_orbit(new Orbit(frame.get_elements(), 360, this.get_color(), 1, renderContext.get_nominalRadius())); + } + frame.get_orbit().draw3D(renderContext, opacity * this.get_opacity(), new Vector3d()); + } + } + renderContext.set_world(matSaved); + return true; + }, + + addFilesToCabinet: function (fc) { + this._filename$1 = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); + var dir = this._filename$1.substring(0, this._filename$1.lastIndexOf('\\')); + var blob = new Blob([this._dataFile$1]); + fc.addFile(this._filename$1, blob); + Layer.prototype.addFilesToCabinet.call(this, fc); + }, + + loadData: function (tourDoc, filename) { + var $this = this; + + var blob = tourDoc.getFileBlob(filename); + var doc = new FileReader(); + doc.onloadend = function (ee) { + $this._dataFile$1 = ss.safeCast(doc.result, String); + $this.loadString($this._dataFile$1); + }; + doc.readAsText(blob); + }, + + loadString: function (dataFile) { + var data = dataFile.split('\n'); + this._frames$1.length = 0; + for (var i = 0; i < data.length; i += 2) { + var line1 = i; + var line2 = i + 1; + if (data[i].length > 0) { + var frame = new ReferenceFrame(); + if (data[i].substring(0, 1) !== '1') { + line1++; + line2++; + frame.name = ss.trim(data[i]); + i++; + } + else if (data[i].substring(0, 1) === '1') { + frame.name = data[i].substring(2, 5); + } + else { + i -= 2; + continue; + } + frame.reference = 18; + frame.oblateness = 0; + frame.showOrbitPath = true; + frame.showAsPoint = true; + frame.referenceFrameType = 1; + frame.scale = 1; + frame.semiMajorAxisUnits = 1; + frame.meanRadius = 10; + frame.oblateness = 0; + frame.fromTLE(data[line1], data[line2], 398600441800000); + this._frames$1.push(frame); + } + else { + i -= 1; + } + } + } +}; + +registerType("OrbitLayer", [OrbitLayer, OrbitLayer$, Layer]); + + +// wwtlib.OrbitLayerUI + +export function OrbitLayerUI(layer) { + this._layer$1 = null; + this._opened$1 = true; + this._callbacks$1 = null; + LayerUI.call(this); + this._layer$1 = layer; +} + +var OrbitLayerUI$ = { + setUICallbacks: function (callbacks) { + this._callbacks$1 = callbacks; + }, + + get_hasTreeViewNodes: function () { + return true; + }, + + getTreeNodes: function () { + var nodes = []; + var $enum1 = ss.enumerate(this._layer$1.get_frames()); + while ($enum1.moveNext()) { + var frame = $enum1.current; + var node = new LayerUITreeNode(); + node.set_name(frame.name); + node.set_tag(frame); + node.set_checked(frame.showOrbitPath); + node.add_nodeSelected(ss.bind('_node_NodeSelected$1', this)); + node.add_nodeChecked(ss.bind('_node_NodeChecked$1', this)); + nodes.push(node); + } + return nodes; + }, + _node_NodeChecked$1: function (node, newState) { + var frame = node.get_tag(); + if (frame != null) { + frame.showOrbitPath = newState; + } + }, + _node_NodeSelected$1: function (node) { + if (this._callbacks$1 != null) { + var frame = node.get_tag(); + var rowData = {}; + rowData['Name'] = frame.name; + rowData['SemiMajor Axis'] = frame.semiMajorAxis.toString(); + rowData['SMA Units'] = frame.semiMajorAxisUnits.toString(); + rowData['Inclination'] = frame.inclination.toString(); + rowData['Eccentricity'] = frame.eccentricity.toString(); + rowData['Long of Asc. Node'] = frame.longitudeOfAscendingNode.toString(); + rowData['Argument Of Periapsis'] = frame.argumentOfPeriapsis.toString(); + rowData['Epoch'] = frame.epoch.toString(); + rowData['Mean Daily Motion'] = frame.meanDailyMotion.toString(); + rowData['Mean Anomoly at Epoch'] = frame.meanAnomolyAtEpoch.toString(); + this._callbacks$1.showRowData(rowData); + } + }, + + getNodeContextMenu: function (node) { + return LayerUI.prototype.getNodeContextMenu.call(this, node); + } +}; + +registerType("OrbitLayerUI", [OrbitLayerUI, OrbitLayerUI$, LayerUI]); diff --git a/engine/esm/layers/reference_frame.js b/engine/esm/layers/reference_frame.js new file mode 100644 index 00000000..db14d446 --- /dev/null +++ b/engine/esm/layers/reference_frame.js @@ -0,0 +1,480 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A reference frame for the 3D mode. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { EOE, ELL } from "../astrocalc/elliptical.js"; +import { Vector3d, Matrix3d } from "../double3d.js"; +import { Color, Colors } from "../color.js"; +import { SpaceTimeController } from "../space_time_controller.js"; + + +// wwtlib.ReferenceFrameTypes + +export var ReferenceFrameTypes = { + fixedSherical: 0, + orbital: 1, + trajectory: 2, + synodic: 3 +}; + +registerType("ReferenceFrameTypes", ReferenceFrameTypes); +registerEnum("ReferenceFrameTypes", ReferenceFrameTypes); + + +// wwtlib.ReferenceFrame + +export function ReferenceFrame() { + this._systemGenerated = false; + + // Calclulated + this.meanAnomoly = 0; + this.orbitalYears = 0; + + // Serialized + this.observingLocation = false; + this.reference = 18; + this.parentsRoationalBase = false; + this.referenceFrameType = 0; + this.meanRadius = 6371000; + this.oblateness = 0.0033528; + this.heading = 0; + this.pitch = 0; + this.roll = 0; + this.scale = 1; + this.tilt = 0; + this.translation = new Vector3d(); + + // For Spherical Offset + this.lat = 0; + this.lng = 0; + this.altitude = 0; + + // For Rotating frames + this.rotationalPeriod = 0; // days + this.zeroRotationDate = 0; // julian decimal + + // For representing orbits & distant point location + this.representativeColor = Colors.get_white(); // Used for orbits and points + this.showAsPoint = false; + this.showOrbitPath = false; + this.stationKeeping = true; + + this.semiMajorAxis = 0; // a Au's + this.semiMajorAxisUnits = 1; // AltUnits + this.eccentricity = 0; // e + this.inclination = 0; // i + this.argumentOfPeriapsis = 0; // w + this.longitudeOfAscendingNode = 0; // Omega + this.meanAnomolyAtEpoch = 0; // M + this.meanDailyMotion = 0; // n .degrees day + this.epoch = 0; // standard equinox + + this._orbit = null; + this._elements = new EOE(); + this.worldMatrix = new Matrix3d(); + this.worldMatrix = Matrix3d.get_identity(); +} + +ReferenceFrame.isTLECheckSumGood = function (line) { + if (line.length !== 69) { + return false; + } + var checksum = 0; + for (var i = 0; i < 68; i++) { + switch (line.substr(i, 1)) { + case '1': + checksum += 1; + break; + case '2': + checksum += 2; + break; + case '3': + checksum += 3; + break; + case '4': + checksum += 4; + break; + case '5': + checksum += 5; + break; + case '6': + checksum += 6; + break; + case '7': + checksum += 7; + break; + case '8': + checksum += 8; + break; + case '9': + checksum += 9; + break; + case '-': + checksum += 1; + break; + } + } + return (checksum % 10).toString() === line.charAt(68).toString(); +}; + +ReferenceFrame.toTLEExponential = function (num, size) { + var exp = num.toExponential(size); + if (exp.length < size + 6) { + exp = exp.substring(0, size + 4) + '0' + exp.substr(size + 4, 1); + } + return exp; +}; + +ReferenceFrame.tleNumberString = function (num, left, right) { + var formated = num.toFixed(right); + var point = formated.indexOf('.'); + if (point === -1) { + point = formated.length; + formated += '.0'; + } + var len = formated.length - point - 1; + var fill = '00000000'; + formated = fill.substr(0, left - point) + formated + fill.substr(0, right - len); + return formated; +}; + +ReferenceFrame.computeTLECheckSum = function (line) { + if (line.length !== 68) { + return '0'; + } + var checksum = 0; + for (var i = 0; i < 68; i++) { + switch (line[i]) { + case '1': + checksum += 1; + break; + case '2': + checksum += 2; + break; + case '3': + checksum += 3; + break; + case '4': + checksum += 4; + break; + case '5': + checksum += 5; + break; + case '6': + checksum += 6; + break; + case '7': + checksum += 7; + break; + case '8': + checksum += 8; + break; + case '9': + checksum += 9; + break; + case '-': + checksum += 1; + break; + } + } + return ((checksum % 10)); +}; + +var ReferenceFrame$ = { + get_representativeColor: function () { + return this.representativeColor; + }, + + set_representativeColor: function (value) { + if (value !== this.representativeColor) { + this.representativeColor = value; + this._orbit = null; + } + return value; + }, + + get_orbit: function () { + return this._orbit; + }, + + set_orbit: function (value) { + this._orbit = value; + return value; + }, + + getIndentifier: function () { + return this.name; + }, + + importTrajectory: function (filename) { }, + + saveToXml: function (xmlWriter) { + xmlWriter._writeStartElement('ReferenceFrame'); + xmlWriter._writeAttributeString('Name', this.name); + xmlWriter._writeAttributeString('Parent', this.parent); + xmlWriter._writeAttributeString('ReferenceFrameType', Enums.toXml('ReferenceFrameTypes', this.referenceFrameType)); + xmlWriter._writeAttributeString('Reference', Enums.toXml('ReferenceFrames', this.reference)); + xmlWriter._writeAttributeString('ParentsRoationalBase', this.parentsRoationalBase.toString()); + xmlWriter._writeAttributeString('MeanRadius', this.meanRadius.toString()); + xmlWriter._writeAttributeString('Oblateness', this.oblateness.toString()); + xmlWriter._writeAttributeString('Heading', this.heading.toString()); + xmlWriter._writeAttributeString('Pitch', this.pitch.toString()); + xmlWriter._writeAttributeString('Roll', this.roll.toString()); + xmlWriter._writeAttributeString('Scale', this.scale.toString()); + xmlWriter._writeAttributeString('Tilt', this.tilt.toString()); + xmlWriter._writeAttributeString('Translation', this.translation.toString()); + if (!this.referenceFrameType) { + xmlWriter._writeAttributeString('Lat', this.lat.toString()); + xmlWriter._writeAttributeString('Lng', this.lng.toString()); + xmlWriter._writeAttributeString('Altitude', this.altitude.toString()); + } + xmlWriter._writeAttributeString('RotationalPeriod', this.rotationalPeriod.toString()); + xmlWriter._writeAttributeString('ZeroRotationDate', this.zeroRotationDate.toString()); + xmlWriter._writeAttributeString('RepresentativeColor', this.get_representativeColor().save()); + xmlWriter._writeAttributeString('ShowAsPoint', this.showAsPoint.toString()); + xmlWriter._writeAttributeString('ShowOrbitPath', this.showOrbitPath.toString()); + xmlWriter._writeAttributeString('StationKeeping', this.stationKeeping.toString()); + if (this.referenceFrameType === 1) { + xmlWriter._writeAttributeString('SemiMajorAxis', this.semiMajorAxis.toString()); + xmlWriter._writeAttributeString('SemiMajorAxisScale', Enums.toXml('AltUnits', this.semiMajorAxisUnits)); + xmlWriter._writeAttributeString('Eccentricity', this.eccentricity.toString()); + xmlWriter._writeAttributeString('Inclination', this.inclination.toString()); + xmlWriter._writeAttributeString('ArgumentOfPeriapsis', this.argumentOfPeriapsis.toString()); + xmlWriter._writeAttributeString('LongitudeOfAscendingNode', this.longitudeOfAscendingNode.toString()); + xmlWriter._writeAttributeString('MeanAnomolyAtEpoch', this.meanAnomolyAtEpoch.toString()); + xmlWriter._writeAttributeString('MeanDailyMotion', this.meanDailyMotion.toString()); + xmlWriter._writeAttributeString('Epoch', this.epoch.toString()); + } + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + this.name = node.attributes.getNamedItem('Name').nodeValue; + this.parent = node.attributes.getNamedItem('Parent').nodeValue; + this.referenceFrameType = Enums.parse('ReferenceFrameTypes', node.attributes.getNamedItem('ReferenceFrameType').nodeValue); + this.reference = Enums.parse('ReferenceFrames', node.attributes.getNamedItem('Reference').nodeValue); + this.parentsRoationalBase = ss.boolean(node.attributes.getNamedItem('ParentsRoationalBase').nodeValue); + this.meanRadius = parseFloat(node.attributes.getNamedItem('MeanRadius').nodeValue); + this.oblateness = parseFloat(node.attributes.getNamedItem('Oblateness').nodeValue); + this.heading = parseFloat(node.attributes.getNamedItem('Heading').nodeValue); + this.pitch = parseFloat(node.attributes.getNamedItem('Pitch').nodeValue); + this.roll = parseFloat(node.attributes.getNamedItem('Roll').nodeValue); + this.scale = parseFloat(node.attributes.getNamedItem('Scale').nodeValue); + this.tilt = parseFloat(node.attributes.getNamedItem('Tilt').nodeValue); + this.translation = Vector3d.parse(node.attributes.getNamedItem('Translation').nodeValue); + if (!this.referenceFrameType) { + this.lat = parseFloat(node.attributes.getNamedItem('Lat').nodeValue); + this.lng = parseFloat(node.attributes.getNamedItem('Lng').nodeValue); + this.altitude = parseFloat(node.attributes.getNamedItem('Altitude').nodeValue); + } + this.rotationalPeriod = parseFloat(node.attributes.getNamedItem('RotationalPeriod').nodeValue); + this.zeroRotationDate = parseFloat(node.attributes.getNamedItem('ZeroRotationDate').nodeValue); + this.set_representativeColor(Color.load(node.attributes.getNamedItem('RepresentativeColor').nodeValue)); + this.showAsPoint = ss.boolean(node.attributes.getNamedItem('ShowAsPoint').nodeValue); + if (node.attributes.getNamedItem('StationKeeping') != null) { + this.stationKeeping = ss.boolean(node.attributes.getNamedItem('StationKeeping').nodeValue); + } + if (this.referenceFrameType === 1) { + this.showOrbitPath = ss.boolean(node.attributes.getNamedItem('ShowOrbitPath').nodeValue); + this.semiMajorAxis = parseFloat(node.attributes.getNamedItem('SemiMajorAxis').nodeValue); + this.semiMajorAxisUnits = Enums.parse('AltUnits', node.attributes.getNamedItem('SemiMajorAxisScale').nodeValue); + this.eccentricity = parseFloat(node.attributes.getNamedItem('Eccentricity').nodeValue); + this.inclination = parseFloat(node.attributes.getNamedItem('Inclination').nodeValue); + this.argumentOfPeriapsis = parseFloat(node.attributes.getNamedItem('ArgumentOfPeriapsis').nodeValue); + this.longitudeOfAscendingNode = parseFloat(node.attributes.getNamedItem('LongitudeOfAscendingNode').nodeValue); + this.meanAnomolyAtEpoch = parseFloat(node.attributes.getNamedItem('MeanAnomolyAtEpoch').nodeValue); + this.meanDailyMotion = parseFloat(node.attributes.getNamedItem('MeanDailyMotion').nodeValue); + this.epoch = parseFloat(node.attributes.getNamedItem('Epoch').nodeValue); + } + }, + + fromTLE: function (line1, line2, gravity) { + this.epoch = SpaceTimeController._twoLineDateToJulian(line1.substr(18, 14)); + this.eccentricity = parseFloat('0.' + line2.substr(26, 7)); + this.inclination = parseFloat(line2.substr(8, 8)); + this.longitudeOfAscendingNode = parseFloat(line2.substr(17, 8)); + this.argumentOfPeriapsis = parseFloat(line2.substr(34, 8)); + var revs = parseFloat(line2.substr(52, 11)); + this.meanAnomolyAtEpoch = parseFloat(line2.substr(43, 8)); + this.meanDailyMotion = revs * 360; + var part = (86400 / revs) / (Math.PI * 2); + this.semiMajorAxis = Math.pow((part * part) * gravity, 1 / 3); + this.semiMajorAxisUnits = 1; + }, + + toTLE: function () { + // Epoch need to convert to TLE time string. + // Ecentricity remove "0." from the begin and trim to 7 digits + // Inclination decimal degrees 8 digits max + // LOAN decimal degrees 8 digits + // AOP + // mean anomoly at epoch 8 digits + // Mean motion (revs per day) Compute + // Convert Semi-major-axis to meters from storage unit + // Compute revs + var line1 = new ss.StringBuilder(); + line1.append('1 99999U 00111AAA '); + line1.append(SpaceTimeController.julianToTwoLineDate(this.epoch)); + line1.append(' '); + line1.append(this.semiMajorAxis.toExponential(4)); + line1.append(' 00000-0 '); + line1.append(ReferenceFrame.toTLEExponential(this.meanDailyMotion, 5)); + line1.append(' 001'); + line1.append(ReferenceFrame.computeTLECheckSum(line1.toString())); + line1.appendLine(''); + var line2 = new ss.StringBuilder(); + line2.append('2 99999 '); + line2.append(ReferenceFrame.tleNumberString(this.inclination, 3, 4) + ' '); + line2.append(ReferenceFrame.tleNumberString(this.longitudeOfAscendingNode, 3, 4) + ' '); + line2.append((ReferenceFrame.tleNumberString(this.eccentricity, 1, 7) + ' ').substring(2)); + line2.append(ReferenceFrame.tleNumberString(this.argumentOfPeriapsis, 3, 4) + ' '); + line2.append(ReferenceFrame.tleNumberString(this.meanAnomolyAtEpoch, 3, 4) + ' '); + line2.append(ReferenceFrame.toTLEExponential(this.meanDailyMotion / 207732, 5)); + line2.append('00001'); + line2.append(ReferenceFrame.computeTLECheckSum(line2.toString())); + line2.appendLine(''); + return line1.toString() + line2.toString(); + }, + + get_elements: function () { + this._elements.a = this.semiMajorAxis; + this._elements.e = this.eccentricity; + this._elements.i = this.inclination; + this._elements.w = this.argumentOfPeriapsis; + this._elements.omega = this.longitudeOfAscendingNode; + this._elements.jdEquinox = this.epoch; + if (!this.meanDailyMotion) { + this._elements.n = ELL.meanMotionFromSemiMajorAxis(this._elements.a); + } else { + this._elements.n = this.meanDailyMotion; + } + this._elements.t = this.epoch - (this.meanAnomolyAtEpoch / this._elements.n); + return this._elements; + }, + + set_elements: function (value) { + this._elements = value; + return value; + }, + + computeFrame: function (renderContext) { + switch (this.referenceFrameType) { + case 1: + this._computeOrbital(renderContext); + break; + case 0: + this._computeFixedSherical(renderContext); + break; + case 2: + this._computeFrameTrajectory(renderContext); + break; + default: + break; + } + }, + + useRotatingParentFrame: function () { + switch (this.referenceFrameType) { + case 1: + case 2: + case 3: + return false; + default: + return true; + } + }, + + _computeFixedRectangular: function (renderContext) { }, + + _computeFixedSherical: function (renderContext) { + if (this.observingLocation) { + this.lat = SpaceTimeController.get_location().get_lat(); + this.lng = SpaceTimeController.get_location().get_lng(); + this.altitude = SpaceTimeController.get_altitude(); + } + this.worldMatrix = Matrix3d.get_identity(); + this.worldMatrix.translate(this.translation); + var localScale = (1 / renderContext.get_nominalRadius()) * this.scale * this.meanRadius; + this.worldMatrix.scale(Vector3d.create(localScale, localScale, localScale)); + this.worldMatrix._multiply(Matrix3d.rotationYawPitchRoll((this.heading / 180 * Math.PI), (this.pitch / 180 * Math.PI), (this.roll / 180 * Math.PI))); + this.worldMatrix._multiply(Matrix3d._rotationZ(-90 / 180 * Math.PI)); + if (!!this.rotationalPeriod) { + var rotationCurrent = (((SpaceTimeController.get_jNow() - this.zeroRotationDate) / this.rotationalPeriod) * Math.PI * 2) % (Math.PI * 2); + this.worldMatrix._multiply(Matrix3d._rotationX(-rotationCurrent)); + } + this.worldMatrix.translate(Vector3d.create(1 + (this.altitude / renderContext.get_nominalRadius()), 0, 0)); + this.worldMatrix._multiply(Matrix3d._rotationZ(this.lat / 180 * Math.PI)); + this.worldMatrix._multiply(Matrix3d._rotationY(-(this.lng + 180) / 180 * Math.PI)); + }, + + _computeFrameTrajectory: function (renderContext) { }, + + _computeOrbital: function (renderContext) { + var ee = this.get_elements(); + var point = ELL.calculateRectangularJD(SpaceTimeController.get_jNow(), ee); + this.meanAnomoly = ee.meanAnnomolyOut; + var pointInstantLater = ELL.calculateRectangular(ee, this.meanAnomoly + 0.001); + var direction = Vector3d.subtractVectors(point, pointInstantLater); + var up = point.copy(); + up.normalize(); + direction.normalize(); + var dist = point.length(); + var scaleFactor = 1; + switch (this.semiMajorAxisUnits) { + case 1: + scaleFactor = 1; + break; + case 2: + scaleFactor = 1 / 3.2808399; + break; + case 3: + scaleFactor = (1 / 3.2808399) / 12; + break; + case 4: + scaleFactor = 1609.344; + break; + case 5: + scaleFactor = 1000; + break; + case 6: + scaleFactor = 149598000 * 1000; + break; + case 7: + scaleFactor = 63239.6717 * 149598000 * 1000; + break; + case 8: + scaleFactor = 206264.806 * 149598000 * 1000; + break; + case 9: + scaleFactor = 206264.806 * 149598000 * 1000 * 1000000; + break; + case 10: + scaleFactor = 1; + break; + default: + break; + } + scaleFactor *= 1 / renderContext.get_nominalRadius(); + var look = Matrix3d.lookAtLH(Vector3d.create(0, 0, 0), direction, up); + look.invert(); + this.worldMatrix = Matrix3d.get_identity(); + this.worldMatrix.translate(this.translation); + var localScale = (1 / renderContext.get_nominalRadius()) * this.scale * this.meanRadius; + this.worldMatrix.scale(Vector3d.create(localScale, localScale, localScale)); + this.worldMatrix._multiply(Matrix3d.rotationYawPitchRoll((this.heading / 180 * Math.PI), (this.pitch / 180 * Math.PI), (this.roll / 180 * Math.PI))); + if (!!this.rotationalPeriod) { + var rotationCurrent = (((SpaceTimeController.get_jNow() - this.zeroRotationDate) / this.rotationalPeriod) * Math.PI * 2) % (Math.PI * 2); + this.worldMatrix._multiply(Matrix3d._rotationX(-rotationCurrent)); + } + point = Vector3d.scale(point, scaleFactor); + this.worldMatrix.translate(point); + if (this.stationKeeping) { + this.worldMatrix = Matrix3d.multiplyMatrix(look, this.worldMatrix); + } + } +}; + +registerType("ReferenceFrame", [ReferenceFrame, ReferenceFrame$, null]); diff --git a/engine/esm/layers/spreadsheet_layer.js b/engine/esm/layers/spreadsheet_layer.js new file mode 100644 index 00000000..cb9508ef --- /dev/null +++ b/engine/esm/layers/spreadsheet_layer.js @@ -0,0 +1,2071 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders tabular data. + +import { ss } from "../ss.js"; +import { registerType, Enums } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { Vector3d, Vector4d } from "../double3d.js"; +import { layerManagerGetAllMaps } from "../data_globals.js"; +import { globalRenderContext, tilePrepDevice } from "../render_globals.js"; +import { WEBGL } from "../graphics/webgl_constants.js"; +import { Dates, LineList, TriangleList, PointList } from "../graphics/primitives3d.js"; +import { Texture } from "../graphics/texture.js"; +import { Tessellator } from "../graphics/tessellator.js"; +import { Color, Colors } from "../color.js"; +import { Coordinates } from "../coordinates.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { UiTools } from "../ui_tools.js"; +import { URLHelpers } from "../url_helpers.js"; +import { ColorMapContainer } from "./color_map_container.js"; +import { Layer } from "./layer.js"; +import { Table } from "./table.js"; + + +// wwtlib.KmlCoordinate + +export function KmlCoordinate() { + this.lat = 0; + this.lng = 0; + this.alt = 0; +} + +var KmlCoordinate$ = {}; + +registerType("KmlCoordinate", [KmlCoordinate, KmlCoordinate$, null]); + + +// wwtlib.KmlLineList + +export function KmlLineList() { + this.extrude = false; + this.astronomical = false; + this.meanRadius = 6371000; + this.pointList = []; +} + +var KmlLineList$ = { + parseWkt: function (geoText, option, alt, date) { + var parts = UiTools.split(geoText, '(,)'); + var $enum1 = ss.enumerate(parts); + while ($enum1.moveNext()) { + var part = $enum1.current; + var coordinates = ss.trim(part).split(' '); + if (coordinates.length > 1) { + var pnt = new KmlCoordinate(); + pnt.lng = parseFloat(coordinates[0]); + if (this.astronomical) { + pnt.lng -= 180; + } + pnt.lat = parseFloat(coordinates[1]); + if (coordinates.length > 2 && !alt) { + pnt.alt = parseFloat(coordinates[2]); + } + else { + pnt.alt = alt; + } + pnt.date = date; + this.pointList.push(pnt); + } + } + }, + + getCenterPoint: function () { + var point = new KmlCoordinate(); + point.lat = 0; + point.lng = 0; + point.alt = 0; + var $enum1 = ss.enumerate(this.pointList); + while ($enum1.moveNext()) { + var pnt = $enum1.current; + point.lat += pnt.lat; + point.lng += pnt.lng; + point.alt += pnt.alt; + } + point.lat /= this.pointList.length; + point.lng /= this.pointList.length; + point.alt /= this.pointList.length; + return point; + } +}; + +registerType("KmlLineList", [KmlLineList, KmlLineList$, null]); + + +// wwtlib.PushPin + +export function PushPin() { } + +PushPin._pinTextureCache = {}; +PushPin._pins = null; + +PushPin.triggerLoadSprite = function () { + if (PushPin._pins == null) { + PushPin._pins = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('pins.png')); + } +}; + +PushPin.getPushPinTexture = function (pinId) { + var texture = null; + if (ss.keyExists(PushPin._pinTextureCache, pinId)) { + return PushPin._pinTextureCache[pinId]; + } + try { + texture = tilePrepDevice.createTexture(); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, texture); + var row = Math.floor(pinId / 16); + var col = pinId % 16; + var temp = document.createElement('canvas'); + temp.height = 32; + temp.width = 32; + var ctx = temp.getContext('2d'); + //Substitute the resized image + ctx.drawImage(PushPin._pins.imageElement, (col * 32), (row * 32), 32, 32, 0, 0, 32, 32); + var image = temp; + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_S, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_T, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGBA, WEBGL.RGBA, WEBGL.UNSIGNED_BYTE, image); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.LINEAR_MIPMAP_NEAREST); + tilePrepDevice.generateMipmap(WEBGL.TEXTURE_2D); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, null); + PushPin._pinTextureCache[pinId] = texture; + } + catch ($e1) { } + return texture; +}; + +var PushPin$ = {}; + +registerType("PushPin", [PushPin, PushPin$, null]); + + +// wwtlib.SpreadSheetLayer + +export function SpreadSheetLayer() { + this._dataDirty$1 = false; + this._lastNormalizeSizeColumnIndex$1 = -1; + this._lastDynamicColorColumnIndex$1 = -1; + this._table_backcompat$1 = null; + this._barChartBitmask$1 = 0; + this._barScaleFactor$1 = 20; + this._meanRadius$1 = 6371000; + this._table$1 = new Table(); + this.isLongIndex = false; + this.shapeVertexCount = 0; + this.lines = false; + this.latColumn = -1; + this.fixedSize = 1; + this.decay = 16; + this.timeSeries = false; + this._dynamicData$1 = false; + this._autoUpdate$1 = false; + this._dataSourceUrl$1 = ''; + this._beginRange$1 = new Date('1/1/2100'); + this._endRange$1 = new Date('01/01/1800'); + this.markerDomainValues = {}; + this.colorDomainValues = {}; + this._coordinatesType$1 = 0; + this.lngColumn = -1; + this.geometryColumn = -1; + this._xAxisColumn$1 = -1; + this._yAxisColumn$1 = -1; + this._zAxisColumn$1 = -1; + this._xAxisReverse$1 = false; + this._yAxisReverse$1 = false; + this._zAxisReverse$1 = false; + this._altType$1 = 3; + this._markerMix$1 = 0; + this._raUnits$1 = 0; + this.colorMap = 3; + this.colorMapperName = 'Greys'; + + // The following attributes control whether and how to map values from + // the ColorMapColumn to colors. The overall option DynamicColor + // determines whether colors should be determined on-the-fly from column + // values. In this case, first, if NormalizeColorMap is true, the values + // are normalized to the range [0:1] using: + // + // new_value = (value - NormalizeColorMapMin) / (NormalizeColorMapMax - NormalizeColorMapMin) + // + // Whether or not the values are normalized, they are then mapped to colors using + // the color map with the name given by ColorMapName. + + // Note that we use a hard-coded UUID since we need it to always be the same across + // all WWT sessions so that we can remove it when it isn't needed. + + this._dynamicColorColumnName$1 = '2efc32e3-b9d9-47ff-8036-8cc344c585bd'; + this.dynamicColor = false; + this.normalizeColorMap = false; + this.normalizeColorMapMin = 0; + this.normalizeColorMapMax = 1; + this._markerColumn$1 = -1; + this.colorMapColumn = -1; + this._plotType$1 = 0; + this._markerIndex$1 = 0; + this._showFarSide$1 = false; + this._markerScale$1 = 1; + this._altUnit$1 = 1; + this._cartesianScale$1 = 1; + this._cartesianCustomScale$1 = 1; + this.altColumn = -1; + this.startDateColumn = -1; + this.endDateColumn = -1; + this.sizeColumn = -1; + + // The following attributes control whether the point sizes should be normalized before + // being used. When NormalizeSize is true, the point sizes are scaled using + // + // new_size = (size - NormalizeSizeMin) / (NormalizeSizeMax - NormalizeSizeMin) + // + // The NormalizeSizeClip attribute can be used to determine whether the sizes should + // be clipped to the range [0:1]. At this time, normalization is only applied if + // PointScaleTypes is Linear or Power. + + // Note that we use a hard-coded UUID since we need it to always be the same across + // all WWT sessions so that we can remove it when it isn't needed. + + this._normalizeSizeColumnName$1 = 'dfe78b4c-f972-4796-b04f-68c5efd4ecb0'; + this.normalizeSize = false; + this.normalizeSizeClip = false; + this.normalizeSizeMin = 0; + this.normalizeSizeMax = 1; + this.nameColumn = 0; + this._hyperlinkFormat$1 = ''; + this._hyperlinkColumn$1 = -1; + this.scaleFactor = 1; + this.pointScaleType = 1; + this.positions = []; + this.bufferIsFlat = false; + this.baseDate = new Date(2010, 0, 1, 12, 0, 0); + this.dirty = true; + this.lastVersion = 0; + Layer.call(this); +} + +SpreadSheetLayer._circleTexture$1 = null; + +SpreadSheetLayer._getDatafromFeed$1 = function (url) { + return ''; +}; + +SpreadSheetLayer._executeQuery$1 = function (url) { + return ''; +}; + +SpreadSheetLayer.parseDate = function (date) { + var dt = ss.now(); + try { + dt = new Date(date); + } + catch ($e1) { + try { + return SpreadSheetLayer.execlToDateTime(parseFloat(date)); + } + catch ($e2) { + } + } + return dt; +}; + +SpreadSheetLayer.execlToDateTime = function (excelDate) { + if (excelDate > 59) { + excelDate -= 1; + } + if (excelDate > 730000) { + excelDate = 730000; + } + var es = new Date(1899, 12, 31); + return new Date(es.getDate() + ss.truncate((excelDate * 24 * 60 * 60 * 1000))); +}; + +SpreadSheetLayer.get__circleTexture$1 = function () { + if (SpreadSheetLayer._circleTexture$1 == null) { + var url = URLHelpers.singleton.engineAssetUrl('circle.png'); + SpreadSheetLayer._circleTexture$1 = Texture.fromUrl(url); + } + return SpreadSheetLayer._circleTexture$1; +}; + +var SpreadSheetLayer$ = { + getTypeName: function () { + return 'TerraViewer.SpreadSheetLayer'; + }, + + get_header: function () { + return this._table$1.header; + }, + + canCopyToClipboard: function () { + return true; + }, + + copyToClipboard: function () { }, + + dynamicUpdate: function () { + var data = SpreadSheetLayer._getDatafromFeed$1(this.get_dataSourceUrl()); + if (data != null) { + this.updateData(data, false, true, true); + this.guessHeaderAssignments(); + return true; + } + return false; + }, + + updateData: function (data, purgeOld, purgeAll, hasHeader) { + this.loadFromString(ss.safeCast(data, String), true, purgeOld, purgeAll, hasHeader); + this.computeDateDomainRange(-1, -1); + this._dataDirty$1 = true; + this.dirty = true; + return true; + }, + + loadData: function (tourDoc, filename) { + var $this = this; + + this._table$1 = new Table(); + var blob = tourDoc.getFileBlob(filename); + this.getStringFromGzipBlob(blob, function (data) { + $this._table$1.loadFromString(data, false, true, true); + + // The NormalizeSizeColumnName column is only present for backward-compatibility + // and should be removed in this version of SpreadSheetLayer, otherwise we might + // keep adding it several times if exporting to XML again. + if ($this._table$1.header.indexOf($this._normalizeSizeColumnName$1) > -1) { + $this._table$1.removeColumn($this._normalizeSizeColumnName$1); + } + $this.computeDateDomainRange(-1, -1); + if ($this.get_dynamicData() && $this.get_autoUpdate()) { + $this.dynamicUpdate(); + } + $this._dataDirty$1 = true; + $this.dirty = true; + }); + }, + + addFilesToCabinet: function (fc) { + this._fileName$1 = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); + var dir = this._fileName$1.substring(0, this._fileName$1.lastIndexOf('\\')); + var data = ''; + + // See PrepareBackCompatTable for an explanation of the + // circumstances under which table_backcompat is used. + if (this._table_backcompat$1 == null) { + data = this._table$1.save(); + } else { + data = this._table_backcompat$1.save(); + } + var blob = new Blob([data]); + fc.addFile(this._fileName$1, blob); + Layer.prototype.addFilesToCabinet.call(this, fc); + }, + _prepareBackCompatTable$1: function () { + // In this this layer class we implement dynamic normalization of the + // points based on one of the existing numerical columns. However, we + // need to produce XML files that are backward-compatible with older + // versions of WWT, so the approach we take is to add a column with + // the computed sizes for versions of WWT that can't do the dynamic + // scaling - while in newer versions we ignore this additional column + // and use the dynamic scaling. + + // Take a shortcut to avoid copying the table if possible + if ((this.sizeColumn === -1 || !this.get_normalizeSize()) && (this.colorMapColumn === -1 || !this.get_dynamicColor())) { + this._lastNormalizeSizeColumnIndex$1 = -1; + this._lastDynamicColorColumnIndex$1 = -1; + return; + } + this._table_backcompat$1 = this._table$1.clone(); + if (this.sizeColumn > -1 && this.get_normalizeSize()) { + var normalizedPointSize = []; + var $enum1 = ss.enumerate(this._table_backcompat$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + normalizedPointSize.push(this.normalizePointSize(parseFloat(row[this.sizeColumn])).toString()); + } + this._table_backcompat$1.addColumn(this._normalizeSizeColumnName$1, normalizedPointSize); + this._lastNormalizeSizeColumnIndex$1 = this._table_backcompat$1.header.length - 1; + } else { + this._lastNormalizeSizeColumnIndex$1 = -1; + } + if (this.colorMapColumn > -1 && this.get_dynamicColor()) { + var pointColors = []; + var $enum2 = ss.enumerate(this._table_backcompat$1.rows); + while ($enum2.moveNext()) { + var row = $enum2.current; + pointColors.push(this.get_colorMapper().findClosestColor(this.normalizeColorMapValue(parseFloat(row[this.get_colorMapColumn()]))).toSimpleHex()); + } + this._table_backcompat$1.addColumn(this._dynamicColorColumnName$1, pointColors); + this._lastDynamicColorColumnIndex$1 = this._table_backcompat$1.header.length - 1; + } else { + this._lastDynamicColorColumnIndex$1 = -1; + } + }, + + guessHeaderAssignments: function () { + var index = 0; + var $enum1 = ss.enumerate(this._table$1.header); + while ($enum1.moveNext()) { + var headerName = $enum1.current; + this._guessHeaderAssignment$1(headerName, index++); + } + if (this._table$1.header.length > 0) { + this.nameColumn = 0; + } + }, + + guessHeaderAssignmentsFromVoTable: function (votable) { + var decColumn = votable.getDecColumn(); + if (decColumn != null) { + this.latColumn = decColumn.index; + this.astronomical = true; + } + var raColumn = votable.getRAColumn(); + if (raColumn != null) { + this.lngColumn = raColumn.index; + this.astronomical = true; + this.pointScaleType = 4; + } + var magColumn = votable.getMagColumn(); + if (magColumn != null) { + this.sizeColumn = magColumn.index; + } + var index = 0; + var $enum1 = ss.enumerate(votable.column); + while ($enum1.moveNext()) { + var column = $enum1.current; + this._guessHeaderAssignment$1(column.name, index++); + } + if (this._table$1.header.length > 0) { + this.nameColumn = 0; + } + }, + _guessHeaderAssignment$1: function (name, index) { + name = name.toLowerCase(); + if (name.indexOf('lat') > -1 && this.latColumn === -1) { + this.latColumn = index; + } + if ((name.indexOf('lon') > -1 || name.indexOf('lng') > -1) && this.lngColumn === -1) { + this.lngColumn = index; + } + if (name.indexOf('dec') > -1 && this.latColumn === -1) { + this.latColumn = index; + this.astronomical = true; + } + if ((name.indexOf('ra') > -1 || name.indexOf('ascen') > -1) && this.lngColumn === -1) { + this.lngColumn = index; + this.astronomical = true; + this.pointScaleType = 4; + } + if ((name.indexOf('mag') > -1 || name.indexOf('size') > -1) && this.sizeColumn === -1) { + this.sizeColumn = index; + } + if ((name.indexOf('date') > -1 || name.indexOf('time') > -1 || name.indexOf('dt') > -1 || name.indexOf('tm') > -1)) { + if (name.indexOf('end') > -1 && this.endDateColumn === -1) { + this.endDateColumn = index; + } + else if (this.startDateColumn === -1) { + this.startDateColumn = index; + } + } + if ((name.indexOf('altitude') > -1 || name.indexOf('alt') > -1) && this.altColumn === -1) { + this.altColumn = index; + this.set_altType(1); + this.set_altUnit(1); + } + if (name.indexOf('depth') > -1 && this.altColumn === -1) { + this.altColumn = index; + this.set_altType(0); + this.set_altUnit(5); + } + if (ss.startsWith(name, 'x') && this.get_xAxisColumn() === -1) { + this.set_xAxisColumn(index); + } + if (ss.startsWith(name, 'y') && this.get_yAxisColumn() === -1) { + this.set_yAxisColumn(index); + } + if (ss.startsWith(name, 'z') && this.get_zAxisColumn() === -1) { + this.set_zAxisColumn(index); + } + if (name.indexOf('color') > -1 && this.get_colorMapColumn() === -1) { + this.set_colorMapColumn(index); + } + if ((name.indexOf('geometry') > -1 || name.indexOf('geography') > -1) && this.geometryColumn === -1) { + this.geometryColumn = index; + } + }, + + computeDateDomainRange: function (columnStart, columnEnd) { + if (columnStart === -1) { + columnStart = this.startDateColumn; + } + if (columnEnd === -1) { + columnEnd = this.endDateColumn; + } + if (columnEnd === -1) { + columnEnd = columnStart; + } + this.set_beginRange(new Date('12/31/2100')); + this.set_endRange(new Date('12/31/1890')); + var $enum1 = ss.enumerate(this._table$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + try { + if (columnStart > -1) { + var sucsess = true; + var dateTimeStart = new Date('12/31/2100'); + try { + dateTimeStart = new Date(row[columnStart]); + if (dateTimeStart < this.get_beginRange()) { + this.set_beginRange(dateTimeStart); + } + } + catch ($e2) { + } + try { + var dateTimeEnd = new Date('12/31/1890'); + if (columnEnd > -1) { + dateTimeEnd = new Date(row[columnEnd]); + if (sucsess && dateTimeEnd > this.get_endRange()) { + this.set_endRange(dateTimeEnd); + } + } + } + catch ($e3) { + } + } + } + catch ($e4) { + } + } + }, + + checkState: function () { }, + + getMaxValue: function (column) { + var max = 0; + this._table$1.lock(); + var $enum1 = ss.enumerate(this._table$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + try { + if (column > -1) { + var sucsess = true; + try { + var val = parseFloat(row[column]); + if (sucsess && val > max) { + max = val; + } + } + catch ($e2) { + } + } + } + catch ($e3) { + } + } + this._table$1.unlock(); + return max; + }, + + getDomainValues: function (column) { + var domainValues = []; + this._table$1.lock(); + var $enum1 = ss.enumerate(this._table$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + try { + if (column > -1) { + if (!(domainValues.indexOf(row[column]) >= 0)) { + domainValues.push(row[column]); + } + } + } + catch ($e2) { + } + } + domainValues.sort(); + this._table$1.unlock(); + return domainValues; + }, + + get_barChartBitmask: function () { + return this._barChartBitmask$1; + }, + + set_barChartBitmask: function (value) { + this._barChartBitmask$1 = value; + return value; + }, + _isPointInFrustum$1: function (position, frustum) { + var centerV4 = new Vector4d(position.x, position.y, position.z, 1); + for (var i = 0; i < 6; i++) { + if (frustum[i].dot(centerV4) < 0) { + return false; + } + } + return true; + }, + + getTableDataInView: function () { + var data = ''; + var first = true; + var $enum1 = ss.enumerate(this.get_header()); + while ($enum1.moveNext()) { + var col = $enum1.current; + if (!first) { + data += '\t'; + } + else { + first = false; + } + data += col; + } + data += '\r\n'; + var $enum2 = ss.enumerate(this.get__table().rows); + while ($enum2.moveNext()) { + var row = $enum2.current; + var ra = parseFloat(row[this.get_lngColumn()]); + var dec = parseFloat(row[this.get_latColumn()]); + var position = Coordinates.geoTo3dDouble(dec, ra); + if (!this._isPointInFrustum$1(position, globalRenderContext.get_frustum())) { + continue; + } + first = true; + var $enum3 = ss.enumerate(row); + while ($enum3.moveNext()) { + var col = $enum3.current; + if (!first) { + data += '\t'; + } + else { + first = false; + } + data += col; + } + data += '\r\n'; + } + return data; + }, + + prepVertexBuffer: function (renderContext, opacity) { + this._table$1.lock(); + if (this.lineList != null) { + this.lineList.clear(); + } + if (this.lineList2d != null) { + this.lineList2d.clear(); + } + if (this.triangleList != null) { + this.triangleList.clear(); + } + if (this.pointList != null) { + this.pointList.clear(); + } + if (this.triangleList2d != null) { + this.triangleList2d.clear(); + } + if (this.lineList == null) { + this.lineList = new LineList(); + } + if (this.pointList == null) { + this.pointList = new PointList(renderContext); + } + this.lineList.timeSeries = this.timeSeries; + if (this.lineList2d == null) { + this.lineList2d = new LineList(); + this.lineList2d.set_depthBuffered(false); + } + this.lineList.timeSeries = this.timeSeries; + if (this.triangleList == null) { + this.triangleList = new TriangleList(); + } + if (this.triangleList2d == null) { + this.triangleList2d = new TriangleList(); + this.triangleList2d.depthBuffered = false; + } + this.positions.length = 0; + var currentIndex = 0; + var colorLocal = this.get_color(); + + // for space 3d + var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; + var selectDomain = {}; + var mr = layerManagerGetAllMaps()[this.get_referenceFrame()].frame.meanRadius; + if (!!mr) { + this._meanRadius$1 = mr; + } + var position = new Vector3d(); + var pointSize = 0.0002; + var pointColor = Colors.get_white(); + var pointStartTime = 0; + var pointEndTime = 0; + var $enum1 = ss.enumerate(this._table$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + try { + if (this.geometryColumn > -1 || (!this.get_coordinatesType() && (this.lngColumn > -1 && this.latColumn > -1)) || ((this.get_coordinatesType() === 1) && (this.get_xAxisColumn() > -1 && this.get_yAxisColumn() > -1))) { + var Xcoord = 0; + var Ycoord = 0; + var Zcoord = 0; + var alt = 1; + var altitude = 0; + var distParces = 0; + var factor = this.getScaleFactor(this.get_altUnit(), 1); + if (this.altColumn === -1 || this.get_altType() === 3 || this.bufferIsFlat) { + alt = 1; + if ((this.astronomical & !this.bufferIsFlat) === 1) { + alt = 63239.6717 * 100; + } + } + else { + if (!this.get_altType()) { + factor = -factor; + } + alt = 0; + try { + alt = parseFloat(row[this.altColumn]); + } + catch ($e2) { + } + if (this.astronomical) { + factor = factor / (1000 * 149598000); + distParces = (alt * factor) / 206264.806; + altitude = (factor * alt); + alt = (factor * alt); + } + else if (this.get_altType() === 2) { + altitude = (factor * alt); + alt = (factor * alt / this._meanRadius$1); + } + else { + altitude = (factor * alt); + alt = 1 + (factor * alt / this._meanRadius$1); + } + } + if (!this.get_coordinatesType() && this.lngColumn > -1 && this.latColumn > -1) { + Xcoord = parseFloat(row[this.lngColumn]); + Ycoord = parseFloat(row[this.latColumn]); + if (this.astronomical) { + if (!this.get_raUnits()) { + Xcoord *= 15; + } + if (this.bufferIsFlat) { + } + } + else { + Xcoord += 180; + } + var pos = Coordinates.geoTo3dRad(Ycoord, Xcoord, alt); + if (this.astronomical && !this.bufferIsFlat) { + pos.rotateX(ecliptic); + } + position = pos; + this.positions.push(position); + } + else if (this.get_coordinatesType() === 1) { + var xyzScale = this.getScaleFactor(this.get_cartesianScale(), this.get_cartesianCustomScale()); + if (this.astronomical) { + xyzScale /= (1000 * 149598000); + } + else { + xyzScale /= this._meanRadius$1; + } + if (this.get_zAxisColumn() > -1) { + Zcoord = parseFloat(row[this.get_zAxisColumn()]); + } + Xcoord = parseFloat(row[this.get_xAxisColumn()]); + Ycoord = parseFloat(row[this.get_yAxisColumn()]); + if (this.get_xAxisReverse()) { + Xcoord = -Xcoord; + } + if (this.get_yAxisReverse()) { + Ycoord = -Ycoord; + } + if (this.get_zAxisReverse()) { + Zcoord = -Zcoord; + } + position = Vector3d.create((Xcoord * xyzScale), (Zcoord * xyzScale), (Ycoord * xyzScale)); + this.positions.push(position); + } + switch (this.get_colorMap()) { + case 0: + pointColor = colorLocal; + break; + case 3: + if (this.get_colorMapColumn() > -1) { + if (this.get_dynamicColor()) { + pointColor = this.get_colorMapper().findClosestColor(this.normalizeColorMapValue(parseFloat(row[this.get_colorMapColumn()]))); + } + else { + pointColor = this._parseColor$1(row[this.get_colorMapColumn()], colorLocal); + } + } + else { + pointColor = colorLocal; + } + break; + default: + break; + } + if (pointColor == null) { + pointColor = Colors.get_transparent(); + } + if (this.sizeColumn > -1) { + switch (this.pointScaleType) { + case 0: + pointSize = parseFloat(row[this.sizeColumn]); + pointSize = this.normalizePointSize(pointSize); + break; + case 2: + pointSize = parseFloat(row[this.sizeColumn]); + pointSize = Math.log(pointSize); + break; + case 1: + try { + pointSize = parseFloat(row[this.sizeColumn]); + pointSize = this.normalizePointSize(pointSize); + pointSize = Math.pow(2, pointSize); + } + catch ($e3) { + pointSize = 0; + } + break; + case 4: + var size = 0; + try { + size = parseFloat(row[this.sizeColumn]); + if (!this.bufferIsFlat) { + size = size - 5 * (Util.logN(distParces, 10) - 1); + pointSize = (120000000 / Math.pow(1.6, size)); + } + else { + pointSize = (40 / Math.pow(1.6, size)); + } + } + catch ($e4) { + pointSize = 0; + } + break; + case 3: + pointSize = 1; + break; + default: + break; + } + } + else { + pointSize = 0.2; + } + if (this.get_plotType() === 1) { + pointSize = 1; + } + if ((this.astronomical & !this.bufferIsFlat) === 1) { + } + if (this.startDateColumn > -1) { + var dateTime = new Date(row[this.startDateColumn]); + pointStartTime = (SpaceTimeController.utcToJulian(dateTime) - SpaceTimeController.utcToJulian(this.baseDate)); + if (this.endDateColumn > -1) { + dateTime = new Date(row[this.endDateColumn]); + pointEndTime = (SpaceTimeController.utcToJulian(dateTime) - SpaceTimeController.utcToJulian(this.baseDate)); + } + else { + pointEndTime = pointStartTime; + } + } + this.pointList.addPoint(position, pointColor, new Dates(pointStartTime, pointEndTime), pointSize); + if (this.geometryColumn > -1) { + this._parseGeometry$1(row[this.geometryColumn], pointColor, pointColor, altitude, new Dates(pointStartTime, pointEndTime)); + } + currentIndex++; + } + } + catch ($e5) { + } + this.lines = false; + } + this._table$1.unlock(); + this._dataDirty$1 = false; + this.dirty = false; + return false; + }, + _parseGeometry$1: function (gs, lineColor, polyColor, alt, date) { + gs = ss.trim(gs).toLowerCase(); + var index = gs.indexOf('('); + if (index < 0) { + return; + } + if (!ss.endsWith(gs, ')')) { + return; + } + var commandPart = ss.trim(gs.substring(0, index)); + var parens = gs.substr(index); + var parts = commandPart.split(' '); + var command = null; + var mods = null; + if (parts.length > 0) { + var $enum1 = ss.enumerate(parts); + while ($enum1.moveNext()) { + var item = $enum1.current; + if (ss.emptyString(command)) { + command = item; + } + else if (ss.emptyString(mods)) { + mods = item; + } + } + } + switch (command) { + case 'multipolygon': + case 'polygon': + this._parsePolygon$1(parens, mods, lineColor, polyColor, alt, date); + break; + case 'multilinestring': + this._parseLineString$1(parens, mods, lineColor, alt, false, date); + break; + case 'linestring': + this._parseLineString$1(parens, mods, lineColor, alt, true, date); + break; + case 'geometrycollection': + parens = parens.substring(1, parens.length - 2); + var shapes = UiTools.splitString(parens, ','); + var $enum2 = ss.enumerate(shapes); + while ($enum2.moveNext()) { + var shape = $enum2.current; + this._parseGeometry$1(shape, lineColor, polyColor, alt, date); + } + break; + default: + break; + } + }, + _parsePolygon$1: function (parens, mods, lineColor, polyColor, alt, date) { + if (!ss.startsWith(parens, '(') && ss.endsWith(parens, ')')) { + return; + } + + // string the top level of parens + parens = parens.substring(1, parens.length - 2); + var shapes = UiTools.splitString(parens, ','); + var $enum1 = ss.enumerate(shapes); + while ($enum1.moveNext()) { + var shape = $enum1.current; + var lineList = new KmlLineList(); + lineList.astronomical = this.astronomical; + lineList.meanRadius = this._meanRadius$1; + lineList.parseWkt(shape, mods, alt, date); + if (!alt) { + this._addPolygonFlat$1(false, lineList, 1, polyColor, lineColor, true, true, date); + } + else { + this._addPolygon$1(false, lineList, 1, polyColor, lineColor, true, true, date); + } + } + }, + _parseLineString$1: function (parens, mods, lineColor, alt, single, date) { + if (!ss.startsWith(parens, '(') && ss.endsWith(parens, ')')) { + return; + } + if (!single) { + // string the top level of parens + parens = parens.substring(1, parens.length - 2); + } + var shapes = UiTools.splitString(parens, ','); + var $enum1 = ss.enumerate(shapes); + while ($enum1.moveNext()) { + var shape = $enum1.current; + var lineList = new KmlLineList(); + lineList.astronomical = this.astronomical; + lineList.meanRadius = this._meanRadius$1; + lineList.parseWkt(shape, mods, alt, date); + this._addPolygon$1(false, lineList, 1, Colors.get_white(), lineColor, false, false, date); + } + }, + _splitShapes$1: function (shapes) { + var shapeList = []; + var nesting = 0; + var current = 0; + while (current < shapes.length) { + if (shapes.substr(current, 1) === '(') { + nesting++; + } + } + return shapeList; + }, + _addPolygon$1: function (sky, geo, lineWidth, polyColor, lineColor, extrude, fill, date) { + //todo can we save this work for later? + var vertexList = []; + var vertexListGround = []; + for (var i = 0; i < geo.pointList.length; i++) { + vertexList.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1 + (geo.pointList[i].alt / this._meanRadius$1))); + vertexListGround.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1)); + } + for (var i = 0; i < (geo.pointList.length - 1); i++) { + if (sky) { + // todo reenable this + } + else { + if (extrude) { + this.triangleList.addQuad(vertexList[i], vertexList[i + 1], vertexListGround[i], vertexListGround[i + 1], polyColor, date); + } + if (lineWidth > 0) { + if (extrude) { + this.lineList.addLine(vertexList[i], vertexList[i + 1], lineColor, date); + } + else { + this.lineList2d.addLine(vertexList[i], vertexList[i + 1], lineColor, date); + } + if (extrude) { + this.lineList.addLine(vertexListGround[i], vertexListGround[i + 1], lineColor, date); + this.lineList.addLine(vertexList[i], vertexListGround[i], lineColor, date); + this.lineList.addLine(vertexList[i + 1], vertexListGround[i + 1], lineColor, date); + } + } + } + } + if (fill) { + var indexes = Tessellator.tesselateSimplePoly(vertexList); + for (var i = 0; i < indexes.length; i += 3) { + this.triangleList.addTriangle(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date); + } + } + }, + _addPolygonFlat$1: function (sky, geo, lineWidth, polyColor, lineColor, extrude, fill, date) { + var vertexList = []; + for (var i = 0; i < geo.pointList.length; i++) { + vertexList.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1 + (geo.pointList[i].alt / this._meanRadius$1))); + } + for (var i = 0; i < (geo.pointList.length - 1); i++) { + if (sky) { + } + else { + if (lineWidth > 0) { + this.lineList2d.addLine(vertexList[i], vertexList[i + 1], lineColor, date); + } + } + } + if (fill) { + var indexes = Tessellator.tesselateSimplePoly(vertexList); + for (var i = 0; i < indexes.length; i += 3) { + this.triangleList2d.addSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date, 2); + } + } + }, + _parseColor$1: function (colorText, defaultColor) { + return Color.load(colorText); + }, + + getScaleFactor: function (AltUnit, custom) { + var factor = 1; + switch (AltUnit) { + case 1: + factor = 1; + break; + case 2: + factor = 1 * 0.3048; + break; + case 3: + factor = (1 / 12) * 0.3048; + break; + case 4: + factor = 5280 * 0.3048; + break; + case 5: + factor = 1000; + break; + case 6: + factor = 1000 * 149598000; + break; + case 7: + factor = 1000 * 149598000 * 63239.6717; + break; + case 8: + factor = 1000 * 149598000 * 206264.806; + break; + case 9: + factor = 1000 * 149598000 * 206264.806 * 1000000; + break; + case 10: + factor = custom; + break; + default: + break; + } + return factor; + }, + + get__table: function () { + return this._table$1; + }, + + set__table: function (value) { + this._table$1 = value; + return value; + }, + + useHeadersFromVoTable: function (voTable) { + var $enum1 = ss.enumerate(voTable.column); + while ($enum1.moveNext()) { + var column = $enum1.current; + this.get_header().push(column.name); + } + this.guessHeaderAssignmentsFromVoTable(voTable); + if (voTable.getRAColumn() != null && voTable.getRAColumn().unit.toLowerCase() === 'deg') { + this.set_raUnits(1); + } + }, + + loadFromString: function (data, isUpdate, purgeOld, purgeAll, hasHeader) { + if (!isUpdate) { + this._table$1 = new Table(); + } + this._table$1.lock(); + this._table$1.loadFromString(data, isUpdate, purgeAll, hasHeader); + if (!isUpdate) { + this.guessHeaderAssignments(); + if (this.astronomical && this.lngColumn > -1) { + var max = this.getMaxValue(this.lngColumn); + if (max > 24) { + this.set_raUnits(1); + } + } + } + if (purgeOld) { + this.purgeByTime(); + } + this._table$1.unlock(); + }, + + purgeByTime: function () { + if (this.startDateColumn < 0) { + return; + } + var columnToUse = this.startDateColumn; + if (this.endDateColumn > -1) { + columnToUse = this.endDateColumn; + } + var threasholdTime = SpaceTimeController.get_now(); + var ts = ss.truncate(this.decay) * 24 * 60 * 60 * 1000; + threasholdTime = new Date(threasholdTime.getDate() - ts); + var count = this._table$1.rows.length; + for (var i = 0; i < count; i++) { + try { + var row = this._table$1.rows[i]; + var colDate = new Date(row[columnToUse]); + if (colDate < threasholdTime) { + this._table$1.rows.splice(i, 1); + count--; + i--; + } + } + catch ($e1) { + } + } + }, + + cleanUp: function () { + this.cleanUpBase(); + this._table$1.lock(); + Layer.prototype.cleanUp.call(this); + this._table$1.unlock(); + this.dirty = true; + }, + + writeLayerProperties: function (xmlWriter) { + xmlWriter._writeAttributeString('TimeSeries', this.get_timeSeries().toString()); + xmlWriter._writeAttributeString('BeginRange', Util.xmlDate(this.get_beginRange())); + xmlWriter._writeAttributeString('EndRange', Util.xmlDate(this.get_endRange())); + xmlWriter._writeAttributeString('Decay', this.get_decay().toString()); + xmlWriter._writeAttributeString('CoordinatesType', Enums.toXml('CoordinatesTypes', this.get_coordinatesType())); + xmlWriter._writeAttributeString('LatColumn', this.get_latColumn().toString()); + xmlWriter._writeAttributeString('LngColumn', this.get_lngColumn().toString()); + xmlWriter._writeAttributeString('GeometryColumn', this.get_geometryColumn().toString()); + xmlWriter._writeAttributeString('AltType', Enums.toXml('AltTypes', this.get_altType())); + xmlWriter._writeAttributeString('MarkerMix', Enums.toXml('MarkerMixes', this.get_markerMix())); + xmlWriter._writeAttributeString('ColorMap', Enums.toXml('ColorMaps', this.get_colorMap())); + xmlWriter._writeAttributeString('MarkerColumn', this.get_markerColumn().toString()); + xmlWriter._writeAttributeString('PlotType', Enums.toXml('PlotTypes', this.get_plotType())); + xmlWriter._writeAttributeString('MarkerIndex', this.get_markerIndex().toString()); + xmlWriter._writeAttributeString('MarkerScale', Enums.toXml('MarkerScales', this.get_markerScale())); + xmlWriter._writeAttributeString('AltUnit', Enums.toXml('AltUnits', this.get_altUnit())); + xmlWriter._writeAttributeString('AltColumn', this.get_altColumn().toString()); + xmlWriter._writeAttributeString('StartDateColumn', this.get_startDateColumn().toString()); + xmlWriter._writeAttributeString('EndDateColumn', this.get_endDateColumn().toString()); + + // In this layer class we implement dynamic scaling and coloring of the points + // based on one of the existing numerical columns. However, we need to produce + // XML files that are backward-compatible with older versions of WWT. If + // dynamic scaling/coloring is used, we therefore point sizeColumn and/or + // colorMapColumn to the hard-coded sizes/colors, and then if we detect + // normalization arguments when reading in the XML, we switch sizeColumn + // and/or colorMapColumn to the original one. + + // Note that we need to call this here since WriteLayerProperties + // gets called before AddFilesToCabinet. + this._prepareBackCompatTable$1(); + if (this._lastNormalizeSizeColumnIndex$1 > -1) { + xmlWriter._writeAttributeString('SizeColumn', this._lastNormalizeSizeColumnIndex$1); + xmlWriter._writeAttributeString('NormalizeSizeColumn', this.sizeColumn.toString()); + } else { + xmlWriter._writeAttributeString('SizeColumn', this.get_sizeColumn().toString()); + } + xmlWriter._writeAttributeString('NormalizeSize', this.get_normalizeSize().toString()); + xmlWriter._writeAttributeString('NormalizeSizeClip', this.get_normalizeSizeClip().toString()); + xmlWriter._writeAttributeString('NormalizeSizeMin', this.get_normalizeSizeMin().toString()); + xmlWriter._writeAttributeString('NormalizeSizeMax', this.get_normalizeSizeMax().toString()); + if (this._lastDynamicColorColumnIndex$1 > -1) { + xmlWriter._writeAttributeString('ColorMapColumn', this._lastDynamicColorColumnIndex$1); + xmlWriter._writeAttributeString('DynamicColorColumn', this.get_colorMapColumn().toString()); + } else { + xmlWriter._writeAttributeString('ColorMapColumn', this.get_colorMapColumn().toString()); + } + xmlWriter._writeAttributeString('DynamicColor', this.get_dynamicColor().toString()); + xmlWriter._writeAttributeString('ColorMapperName', this.get_colorMapperName()); + xmlWriter._writeAttributeString('NormalizeColorMap', this.get_normalizeColorMap().toString()); + xmlWriter._writeAttributeString('NormalizeColorMapMin', this.get_normalizeColorMapMin().toString()); + xmlWriter._writeAttributeString('NormalizeColorMapMax', this.get_normalizeColorMapMax().toString()); + xmlWriter._writeAttributeString('HyperlinkFormat', this.get_hyperlinkFormat()); + xmlWriter._writeAttributeString('HyperlinkColumn', this.get_hyperlinkColumn().toString()); + xmlWriter._writeAttributeString('ScaleFactor', this.get_scaleFactor().toString()); + xmlWriter._writeAttributeString('PointScaleType', Enums.toXml('PointScaleTypes', this.get_pointScaleType())); + xmlWriter._writeAttributeString('ShowFarSide', this.get_showFarSide().toString()); + xmlWriter._writeAttributeString('RaUnits', Enums.toXml('RAUnits', this.get_raUnits())); + xmlWriter._writeAttributeString('HoverTextColumn', this.get_nameColumn().toString()); + xmlWriter._writeAttributeString('XAxisColumn', this.get_xAxisColumn().toString()); + xmlWriter._writeAttributeString('XAxisReverse', this.get_xAxisReverse().toString()); + xmlWriter._writeAttributeString('YAxisColumn', this.get_yAxisColumn().toString()); + xmlWriter._writeAttributeString('YAxisReverse', this.get_yAxisReverse().toString()); + xmlWriter._writeAttributeString('ZAxisColumn', this.get_zAxisColumn().toString()); + xmlWriter._writeAttributeString('ZAxisReverse', this.get_zAxisReverse().toString()); + xmlWriter._writeAttributeString('CartesianScale', Enums.toXml('AltUnits', this.get_cartesianScale())); + xmlWriter._writeAttributeString('CartesianCustomScale', this.get_cartesianCustomScale().toString()); + xmlWriter._writeAttributeString('DynamicData', this.get_dynamicData().toString()); + xmlWriter._writeAttributeString('AutoUpdate', this.get_autoUpdate().toString()); + xmlWriter._writeAttributeString('DataSourceUrl', this.get_dataSourceUrl()); + }, + + get_dynamicData: function () { + return this._dynamicData$1; + }, + + set_dynamicData: function (value) { + this._dynamicData$1 = value; + return value; + }, + + get_autoUpdate: function () { + return this._autoUpdate$1; + }, + + set_autoUpdate: function (value) { + this._autoUpdate$1 = value; + return value; + }, + + get_dataSourceUrl: function () { + return this._dataSourceUrl$1; + }, + + set_dataSourceUrl: function (value) { + this._dataSourceUrl$1 = value; + return value; + }, + + get_timeSeries: function () { + return this.timeSeries; + }, + + set_timeSeries: function (value) { + if (this.timeSeries !== value) { + this.version++; + this.timeSeries = value; + } + return value; + }, + + get_beginRange: function () { + return this._beginRange$1; + }, + + set_beginRange: function (value) { + if (!ss.compareDates(this._beginRange$1, value)) { + this.version++; + this._beginRange$1 = value; + } + return value; + }, + + get_endRange: function () { + return this._endRange$1; + }, + + set_endRange: function (value) { + if (!ss.compareDates(this._endRange$1, value)) { + this.version++; + this._endRange$1 = value; + } + return value; + }, + + initializeFromXml: function (node) { + this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); + this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); + this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); + this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); + this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); + if (this.get_coordinatesType() < 0) { + this.set_coordinatesType(0); + } + this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); + this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); + if (node.attributes.getNamedItem('GeometryColumn') != null) { + this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); + } + this.set_altType(Enums.parse('AltTypes', node.attributes.getNamedItem('AltType').nodeValue)); + this.set_markerMix(0); + this.set_colorMap(Enums.parse('ColorMaps', node.attributes.getNamedItem('ColorMap').nodeValue)); + this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); + this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); + this.set_plotType(Enums.parse('PlotTypes', node.attributes.getNamedItem('PlotType').nodeValue)); + this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); + this.set_markerScale(Enums.parse('MarkerScales', node.attributes.getNamedItem('MarkerScale').nodeValue)); + this.set_altUnit(Enums.parse('AltUnits', node.attributes.getNamedItem('AltUnit').nodeValue)); + this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); + this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); + this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); + + // In this layer class we implement dynamic scaling and coloring of the points + // based on one of the existing numerical columns. However, we need to produce + // XML files that are backward-compatible with older versions of WWT. Since we + // can deal with size/color scaling here, we ignore SizeColumn and ColorMapColumn + // and use NormalizeSizeColumn and DynamicColorColumn instead, if present. + + if (node.attributes.getNamedItem('NormalizeSizeColumn') != null) { + this.set_sizeColumn(parseInt(node.attributes.getNamedItem('NormalizeSizeColumn').nodeValue)); + } else { + this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); + } + + // Only recent files have normalization parameters + + if (node.attributes.getNamedItem('NormalizeSize') != null) { + this.set_normalizeSize(ss.boolean(node.attributes.getNamedItem('NormalizeSize').nodeValue)); + this.set_normalizeSizeClip(ss.boolean(node.attributes.getNamedItem('NormalizeSizeClip').nodeValue)); + this.set_normalizeSizeMin(parseFloat(node.attributes.getNamedItem('NormalizeSizeMin').nodeValue)); + this.set_normalizeSizeMax(parseFloat(node.attributes.getNamedItem('NormalizeSizeMax').nodeValue)); + } + if (node.attributes.getNamedItem('DynamicColorColumn') != null) { + this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('DynamicColorColumn').nodeValue)); + } else { + this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); + } + + // Only recent files have normalization parameters + + if (node.attributes.getNamedItem('DynamicColor') != null) { + this.set_dynamicColor(ss.boolean(node.attributes.getNamedItem('DynamicColor').nodeValue)); + this.set_colorMapperName(node.attributes.getNamedItem('ColorMapperName').nodeValue); + this.set_normalizeColorMap(ss.boolean(node.attributes.getNamedItem('NormalizeColorMap').nodeValue)); + this.set_normalizeColorMapMin(parseFloat(node.attributes.getNamedItem('NormalizeColorMapMin').nodeValue)); + this.set_normalizeColorMapMax(parseFloat(node.attributes.getNamedItem('NormalizeColorMapMax').nodeValue)); + } + this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); + this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); + this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); + this.set_pointScaleType(Enums.parse('PointScaleTypes', node.attributes.getNamedItem('PointScaleType').nodeValue)); + if (node.attributes.getNamedItem('ShowFarSide') != null) { + this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); + } + if (node.attributes.getNamedItem('RaUnits') != null) { + this.set_raUnits(Enums.parse('RAUnits', node.attributes.getNamedItem('RaUnits').nodeValue)); + } + if (node.attributes.getNamedItem('HoverTextColumn') != null) { + this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); + } + if (node.attributes.getNamedItem('XAxisColumn') != null) { + this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); + this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); + this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); + this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); + this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); + this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); + this.set_cartesianScale(Enums.parse('AltUnits', node.attributes.getNamedItem('CartesianScale').nodeValue)); + this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); + } + if (node.attributes.getNamedItem('DynamicData') != null) { + this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); + this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); + this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); + } + }, + + get_decay: function () { + return this.decay; + }, + + set_decay: function (value) { + if (this.decay !== value) { + this.version++; + this.decay = value; + } + return value; + }, + + get_coordinatesType: function () { + return this._coordinatesType$1; + }, + + set_coordinatesType: function (value) { + if (this._coordinatesType$1 !== value) { + this.version++; + this._coordinatesType$1 = value; + } + return value; + }, + + get_latColumn: function () { + return this.latColumn; + }, + + set_latColumn: function (value) { + if (this.latColumn !== value) { + this.version++; + this.latColumn = value; + } + return value; + }, + + get_lngColumn: function () { + return this.lngColumn; + }, + + set_lngColumn: function (value) { + if (this.lngColumn !== value) { + this.version++; + this.lngColumn = value; + } + return value; + }, + + get_geometryColumn: function () { + return this.geometryColumn; + }, + + set_geometryColumn: function (value) { + if (this.geometryColumn !== value) { + this.version++; + this.geometryColumn = value; + } + return value; + }, + + get_xAxisColumn: function () { + return this._xAxisColumn$1; + }, + + set_xAxisColumn: function (value) { + if (this._xAxisColumn$1 !== value) { + this.version++; + this._xAxisColumn$1 = value; + } + return value; + }, + + get_yAxisColumn: function () { + return this._yAxisColumn$1; + }, + + set_yAxisColumn: function (value) { + if (this._yAxisColumn$1 !== value) { + this.version++; + this._yAxisColumn$1 = value; + } + return value; + }, + + get_zAxisColumn: function () { + return this._zAxisColumn$1; + }, + + set_zAxisColumn: function (value) { + if (this._zAxisColumn$1 !== value) { + this.version++; + this._zAxisColumn$1 = value; + } + return value; + }, + + get_xAxisReverse: function () { + return this._xAxisReverse$1; + }, + + set_xAxisReverse: function (value) { + if (this._xAxisReverse$1 !== value) { + this.version++; + this._xAxisReverse$1 = value; + } + return value; + }, + + get_yAxisReverse: function () { + return this._yAxisReverse$1; + }, + + set_yAxisReverse: function (value) { + if (this._yAxisReverse$1 !== value) { + this.version++; + this._yAxisReverse$1 = value; + } + return value; + }, + + get_zAxisReverse: function () { + return this._zAxisReverse$1; + }, + + set_zAxisReverse: function (value) { + if (this._zAxisReverse$1 !== value) { + this.version++; + this._zAxisReverse$1 = value; + } + return value; + }, + + get_altType: function () { + return this._altType$1; + }, + + set_altType: function (value) { + if (this._altType$1 !== value) { + this.version++; + this._altType$1 = value; + } + return value; + }, + + get_markerMix: function () { + return this._markerMix$1; + }, + + set_markerMix: function (value) { + if (this._markerMix$1 !== value) { + this.version++; + this._markerMix$1 = value; + } + return value; + }, + + get_raUnits: function () { + return this._raUnits$1; + }, + + set_raUnits: function (value) { + if (this._raUnits$1 !== value) { + this.version++; + this._raUnits$1 = value; + } + return value; + }, + + get_colorMap: function () { + return this.colorMap; + }, + + set_colorMap: function (value) { + if (this.colorMap !== value) { + this.version++; + this.colorMap = value; + } + return value; + }, + + get_colorMapperName: function () { + return this.colorMapperName; + }, + + set_colorMapperName: function (value) { + if (ColorMapContainer.fromNamedColormap(value) == null) { + throw new Error('Invalid colormap name'); + } + this.version++; + this.colorMapperName = value; + return value; + }, + + get_colorMapper: function () { + return ColorMapContainer.fromNamedColormap(this.colorMapperName); + }, + + get_dynamicColor: function () { + return this.dynamicColor; + }, + + set_dynamicColor: function (value) { + this.version++; + this.dynamicColor = value; + return value; + }, + + get_normalizeColorMap: function () { + return this.normalizeColorMap; + }, + + set_normalizeColorMap: function (value) { + this.version++; + this.normalizeColorMap = value; + return value; + }, + + get_normalizeColorMapMin: function () { + return this.normalizeColorMapMin; + }, + + set_normalizeColorMapMin: function (value) { + this.version++; + this.normalizeColorMapMin = value; + return value; + }, + + get_normalizeColorMapMax: function () { + return this.normalizeColorMapMax; + }, + + set_normalizeColorMapMax: function (value) { + this.version++; + this.normalizeColorMapMax = value; + return value; + }, + + normalizeColorMapValue: function (value) { + if (!this.get_normalizeColorMap()) { + return value; + } + var new_value = (value - this.get_normalizeColorMapMin()) / (this.get_normalizeColorMapMax() - this.get_normalizeColorMapMin()); + if (new_value < 0) { + new_value = 0; + } else if (new_value > 1) { + new_value = 1; + } + return new_value; + }, + + get_markerColumn: function () { + return this._markerColumn$1; + }, + + set_markerColumn: function (value) { + if (this._markerColumn$1 !== value) { + this.version++; + this._markerColumn$1 = value; + } + return value; + }, + + get_colorMapColumn: function () { + return this.colorMapColumn; + }, + + set_colorMapColumn: function (value) { + if (this.colorMapColumn !== value) { + this.version++; + this.colorMapColumn = value; + } + return value; + }, + + get_plotType: function () { + return this._plotType$1; + }, + + set_plotType: function (value) { + if (this._plotType$1 !== value) { + this.version++; + this._plotType$1 = value; + } + return value; + }, + + get_markerIndex: function () { + return this._markerIndex$1; + }, + + set_markerIndex: function (value) { + if (this._markerIndex$1 !== value) { + this.version++; + this._markerIndex$1 = value; + } + return value; + }, + + get_showFarSide: function () { + return this._showFarSide$1; + }, + + set_showFarSide: function (value) { + if (this._showFarSide$1 !== value) { + this.version++; + this._showFarSide$1 = value; + } + return value; + }, + + get_markerScale: function () { + return this._markerScale$1; + }, + + set_markerScale: function (value) { + if (this._markerScale$1 !== value) { + this.version++; + this._markerScale$1 = value; + } + return value; + }, + + get_altUnit: function () { + return this._altUnit$1; + }, + + set_altUnit: function (value) { + if (this._altUnit$1 !== value) { + this.version++; + this._altUnit$1 = value; + } + return value; + }, + + get_cartesianScale: function () { + return this._cartesianScale$1; + }, + + set_cartesianScale: function (value) { + if (this._cartesianScale$1 !== value) { + this.version++; + this._cartesianScale$1 = value; + } + return value; + }, + + get_cartesianCustomScale: function () { + return this._cartesianCustomScale$1; + }, + + set_cartesianCustomScale: function (value) { + if (this._cartesianCustomScale$1 !== value) { + this.version++; + this._cartesianCustomScale$1 = value; + } + return value; + }, + + get_altColumn: function () { + return this.altColumn; + }, + + set_altColumn: function (value) { + if (this.altColumn !== value) { + this.version++; + this.altColumn = value; + } + return value; + }, + + get_startDateColumn: function () { + return this.startDateColumn; + }, + + set_startDateColumn: function (value) { + if (this.startDateColumn !== value) { + this.version++; + this.startDateColumn = value; + } + return value; + }, + + get_endDateColumn: function () { + return this.endDateColumn; + }, + + set_endDateColumn: function (value) { + if (this.endDateColumn !== value) { + this.version++; + this.endDateColumn = value; + } + return value; + }, + + get_sizeColumn: function () { + return this.sizeColumn; + }, + + set_sizeColumn: function (value) { + if (this.sizeColumn !== value) { + this.version++; + this.sizeColumn = value; + } + return value; + }, + + get_normalizeSize: function () { + return this.normalizeSize; + }, + + set_normalizeSize: function (value) { + if (this.normalizeSize !== value) { + this.version++; + this.normalizeSize = value; + } + return value; + }, + + get_normalizeSizeClip: function () { + return this.normalizeSizeClip; + }, + + set_normalizeSizeClip: function (value) { + if (this.normalizeSizeClip !== value) { + this.version++; + this.normalizeSizeClip = value; + } + return value; + }, + + get_normalizeSizeMin: function () { + return this.normalizeSizeMin; + }, + + set_normalizeSizeMin: function (value) { + if (this.normalizeSizeMin !== value) { + this.version++; + this.normalizeSizeMin = value; + } + return value; + }, + + get_normalizeSizeMax: function () { + return this.normalizeSizeMax; + }, + + set_normalizeSizeMax: function (value) { + if (this.normalizeSizeMax !== value) { + this.version++; + this.normalizeSizeMax = value; + } + return value; + }, + + normalizePointSize: function (value) { + if (!this.get_normalizeSize()) { + return value; + } + var new_value = (value - this.get_normalizeSizeMin()) / (this.get_normalizeSizeMax() - this.get_normalizeSizeMin()); + if (this.get_normalizeSizeClip()) { + if (new_value < 0) { + new_value = 0; + } + else if (new_value > 1) { + new_value = 1; + } + } + return new_value; + }, + + get_nameColumn: function () { + return this.nameColumn; + }, + + set_nameColumn: function (value) { + if (this.nameColumn !== value) { + this.version++; + this.nameColumn = value; + } + return value; + }, + + get_hyperlinkFormat: function () { + return this._hyperlinkFormat$1; + }, + + set_hyperlinkFormat: function (value) { + if (this._hyperlinkFormat$1 !== value) { + this.version++; + this._hyperlinkFormat$1 = value; + } + return value; + }, + + get_hyperlinkColumn: function () { + return this._hyperlinkColumn$1; + }, + + set_hyperlinkColumn: function (value) { + if (this._hyperlinkColumn$1 !== value) { + this.version++; + this._hyperlinkColumn$1 = value; + } + return value; + }, + + get_scaleFactor: function () { + return this.scaleFactor; + }, + + set_scaleFactor: function (value) { + if (this.scaleFactor !== value) { + this.version++; + this.scaleFactor = value; + } + return value; + }, + + get_pointScaleType: function () { + return this.pointScaleType; + }, + + set_pointScaleType: function (value) { + if (this.pointScaleType !== value) { + this.version++; + this.pointScaleType = value; + } + return value; + }, + + draw: function (renderContext, opacity, flat) { + var device = renderContext; + if (this.version !== this.lastVersion) { + this.cleanUp(); + } + this.lastVersion = this.version; + if (this.bufferIsFlat !== flat) { + this.cleanUp(); + this.bufferIsFlat = flat; + } + if (this.dirty) { + this.prepVertexBuffer(device, opacity); + } + var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); + var adjustedScale = this.scaleFactor * 3; + if (flat && this.astronomical && (this._markerScale$1 === 1)) { + adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); + } + if (this.triangleList2d != null) { + this.triangleList2d.decay = this.decay; + this.triangleList2d.sky = this.get_astronomical(); + this.triangleList2d.timeSeries = this.timeSeries; + this.triangleList2d.jNow = jNow; + this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.triangleList != null) { + this.triangleList.decay = this.decay; + this.triangleList.sky = this.get_astronomical(); + this.triangleList.timeSeries = this.timeSeries; + this.triangleList.jNow = jNow; + this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.pointList != null) { + this.pointList.depthBuffered = false; + this.pointList.showFarSide = this.get_showFarSide(); + this.pointList.decay = (this.timeSeries) ? this.decay : 0; + this.pointList.sky = this.get_astronomical(); + this.pointList.timeSeries = this.timeSeries; + this.pointList.jNow = jNow; + this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; + switch (this._plotType$1) { + case 0: + this.pointList.draw(renderContext, opacity * this.get_opacity(), false); + break; + case 2: + this.pointList.drawTextured(renderContext, SpreadSheetLayer.get__circleTexture$1().texture2d, opacity * this.get_opacity()); + break; + case 1: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(19), opacity * this.get_opacity()); + break; + case 3: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(35), opacity * this.get_opacity()); + break; + case 5: + case 4: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(this._markerIndex$1), opacity * this.get_opacity()); + break; + default: + break; + } + } + if (this.lineList != null) { + this.lineList.sky = this.get_astronomical(); + this.lineList.decay = this.decay; + this.lineList.timeSeries = this.timeSeries; + this.lineList.jNow = jNow; + this.lineList.drawLines(renderContext, opacity * this.get_opacity()); + } + if (this.lineList2d != null) { + this.lineList2d.sky = this.get_astronomical(); + this.lineList2d.decay = this.decay; + this.lineList2d.timeSeries = this.timeSeries; + this.lineList2d.showFarSide = this.get_showFarSide(); + this.lineList2d.jNow = jNow; + this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); + } + return true; + }, + + cleanUpBase: function () { + if (this.lineList != null) { + this.lineList.clear(); + } + if (this.lineList2d != null) { + this.lineList2d.clear(); + } + if (this.triangleList2d != null) { + this.triangleList2d.clear(); + } + if (this.pointList != null) { + this.pointList.clear(); + } + if (this.triangleList != null) { + this.triangleList.clear(); + } + } +}; + +registerType("SpreadSheetLayer", [SpreadSheetLayer, SpreadSheetLayer$, Layer]); + + +// wwtlib.CatalogSpreadSheetLayer + +export function CatalogSpreadSheetLayer() { + this._addedTiles$2 = {}; + SpreadSheetLayer.call(this); +} + +var CatalogSpreadSheetLayer$ = { + addTileRows: function (tileKey, catalogRows) { + if (!ss.keyExists(this._addedTiles$2, tileKey)) { + var $enum1 = ss.enumerate(catalogRows); + while ($enum1.moveNext()) { + var row = $enum1.current; + this.get__table().rows.push(row); + } + this.dirty = true; + this._addedTiles$2[tileKey] = true; + } + }, + + removeTileRows: function (tileKey, catalogRows) { + if (ss.keyExists(this._addedTiles$2, tileKey)) { + var $enum1 = ss.enumerate(catalogRows); + while ($enum1.moveNext()) { + var row = $enum1.current; + ss.remove(this.get__table().rows, row); + } + this.dirty = true; + delete this._addedTiles$2[tileKey]; + } + }, + + cleanUp: function () { + SpreadSheetLayer.prototype.cleanUp.call(this); + ss.clearKeys(this._addedTiles$2); + this.get__table().rows.length = 0; + } +}; + +registerType("CatalogSpreadSheetLayer", [CatalogSpreadSheetLayer, CatalogSpreadSheetLayer$, SpreadSheetLayer]); diff --git a/engine/esm/layers/table.js b/engine/esm/layers/table.js new file mode 100644 index 00000000..11adc2c0 --- /dev/null +++ b/engine/esm/layers/table.js @@ -0,0 +1,135 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Tabular data. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Guid } from "../util.js"; +import { UiTools } from "../ui_tools.js"; + + +// wwtlib.Table + +export function Table() { + this.guid = new Guid(); + this.header = []; + this.rows = []; + this.delimiter = '\t'; + this.locked = false; +} + +var Table$ = { + lock: function () { + this.locked = true; + }, + + unlock: function () { + this.locked = false; + }, + + save: function () { + var data = ''; + var first = true; + var $enum1 = ss.enumerate(this.header); + while ($enum1.moveNext()) { + var col = $enum1.current; + if (!first) { + data += '\t'; + } + else { + first = false; + } + data += col; + } + data += '\r\n'; + var $enum2 = ss.enumerate(this.rows); + while ($enum2.moveNext()) { + var row = $enum2.current; + first = true; + var $enum3 = ss.enumerate(row); + while ($enum3.moveNext()) { + var col = $enum3.current; + if (!first) { + data += '\t'; + } + else { + first = false; + } + data += col; + } + data += '\r\n'; + } + return data; + }, + + loadFromString: function (data, isUpdate, purge, hasHeader) { + var count = 0; + var lines = data.split('\r\n'); + if (!isUpdate || hasHeader) { + if (lines.length > 0) { + var headerLine = lines[0]; + count++; + if (headerLine.indexOf('\t') === -1 && headerLine.indexOf(',') > -1) { + this.delimiter = ','; + } + if (!isUpdate) { + this.rows.length = 0; + } + this.header = UiTools.splitString(headerLine, this.delimiter); + } + else { + this.header = []; + } + } + var temp = []; + if (!purge) { + temp = this.rows; + } + while (count < lines.length) { + var line = lines[count]; + var rowData = UiTools.splitString(line, this.delimiter); + if (rowData.length < 1) { + break; + } + temp.push(rowData); + count++; + } + if (purge) { + this.rows = temp; + } + }, + + clone: function () { + var cloned_table = new Table(); + for (var i = 0; i < this.header.length; i++) { + cloned_table.header.push(this.header[i]); + } + for (var j = 0; j < this.rows.length; j++) { + cloned_table.rows.push([]); + for (var i = 0; i < this.rows[j].length; i++) { + cloned_table.rows[j].push(this.rows[j][i]); + } + } + return cloned_table; + }, + + addColumn: function (name, data) { + this.header.push(name); + for (var i = 0; i < data.length; i++) { + this.rows[i].push(data[i]); + } + }, + + removeColumn: function (name) { + var remove_index = this.header.indexOf(name); + if (remove_index > -1) { + this.header.splice(remove_index, 1); + for (var i = 0; i < this.rows.length; i++) { + this.rows[i].splice(remove_index, 1); + } + } + } +}; + +registerType("Table", [Table, Table$, null]); diff --git a/engine/esm/layers/time_series_layer.js b/engine/esm/layers/time_series_layer.js new file mode 100644 index 00000000..8e413e33 --- /dev/null +++ b/engine/esm/layers/time_series_layer.js @@ -0,0 +1,924 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer for rendering time-series data. +// +// This layer is essentially unimplemented in the WWT WebGL engine. See +// "spreadsheetlayer" and "votablelayer" for functionality that is actually +// available. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { Layer } from "./layer.js"; + + +// wwtlib.CoordinatesTypes + +export var CoordinatesTypes = { + spherical: 0, + rectangular: 1, + orbital: 2 +}; + +registerType("CoordinatesTypes", CoordinatesTypes); +registerEnum("CoordinatesTypes", CoordinatesTypes); + + +// wwtlib.AltTypes + +export var AltTypes = { + depth: 0, + altitude: 1, + distance: 2, + seaLevel: 3, + terrain: 4 +}; + +registerType("AltTypes", AltTypes); +registerEnum("AltTypes", AltTypes); + + +// wwtlib.MarkerMixes + +export var MarkerMixes = { + same_For_All: 0 +}; + +registerType("MarkerMixes", MarkerMixes); +registerEnum("MarkerMixes", MarkerMixes); + + +// wwtlib.ColorMaps + +export var ColorMaps = { + same_For_All: 0, + group_by_Values: 2, + per_Column_Literal: 3 +}; + +registerType("ColorMaps", ColorMaps); +registerEnum("ColorMaps", ColorMaps); + + +// wwtlib.PlotTypes + +export var PlotTypes = { + gaussian: 0, + point: 1, + circle: 2, + square: 3, + pushPin: 4, + custom: 5 +}; + +registerType("PlotTypes", PlotTypes); +registerEnum("PlotTypes", PlotTypes); + + +// wwtlib.MarkerScales + +export var MarkerScales = { + screen: 0, + world: 1 +}; + +registerType("MarkerScales", MarkerScales); +registerEnum("MarkerScales", MarkerScales); + + +// wwtlib.RAUnits + +export var RAUnits = { + hours: 0, + degrees: 1 +}; + +registerType("RAUnits", RAUnits); +registerEnum("RAUnits", RAUnits); + + +// wwtlib.TimeSeriesLayer + +export function TimeSeriesLayer() { + this.isLongIndex = false; + this.shapeVertexCount = 0; + this.lines = false; + this.latColumn = -1; + this.fixedSize = 1; + this.decay = 16; + this.timeSeries = false; + this._dynamicData$1 = false; + this._autoUpdate$1 = false; + this._dataSourceUrl$1 = ''; + this._beginRange$1 = new Date('1/1/2100'); + this._endRange$1 = new Date('01/01/1800'); + this.markerDomainValues = {}; + this.colorDomainValues = {}; + this._coordinatesType$1 = 0; + this.lngColumn = -1; + this.geometryColumn = -1; + this._xAxisColumn$1 = -1; + this._yAxisColumn$1 = -1; + this._zAxisColumn$1 = -1; + this._xAxisReverse$1 = false; + this._yAxisReverse$1 = false; + this._zAxisReverse$1 = false; + this._altType$1 = 3; + this._markerMix$1 = 0; + this._raUnits$1 = 0; + this._colorMap$1 = 3; + this._markerColumn$1 = -1; + this._colorMapColumn$1 = -1; + this._plotType$1 = 0; + this._markerIndex$1 = 0; + this._showFarSide$1 = false; + this._markerScale$1 = 1; + this._altUnit$1 = 1; + this._cartesianScale$1 = 1; + this._cartesianCustomScale$1 = 1; + this.altColumn = -1; + this.startDateColumn = -1; + this.endDateColumn = -1; + this.sizeColumn = -1; + this.nameColumn = 0; + this._hyperlinkFormat$1 = ''; + this._hyperlinkColumn$1 = -1; + this.scaleFactor = 1; + this.pointScaleType = 1; + this.positions = []; + this.bufferIsFlat = false; + this.baseDate = new Date(2010, 0, 1, 12, 0, 0); + this.dirty = true; + this.lastVersion = 0; + Layer.call(this); +} + +TimeSeriesLayer._circleTexture$1 = null; + +TimeSeriesLayer.get__circleTexture$1 = function () { + return TimeSeriesLayer._circleTexture$1; +}; + +var TimeSeriesLayer$ = { + get_dynamicData: function () { + return this._dynamicData$1; + }, + + set_dynamicData: function (value) { + this._dynamicData$1 = value; + return value; + }, + + get_autoUpdate: function () { + return this._autoUpdate$1; + }, + + set_autoUpdate: function (value) { + this._autoUpdate$1 = value; + return value; + }, + + get_dataSourceUrl: function () { + return this._dataSourceUrl$1; + }, + + set_dataSourceUrl: function (value) { + this._dataSourceUrl$1 = value; + return value; + }, + + get_timeSeries: function () { + return this.timeSeries; + }, + + set_timeSeries: function (value) { + if (this.timeSeries !== value) { + this.version++; + this.timeSeries = value; + } + return value; + }, + + get_header: function () { + return null; + }, + + get_beginRange: function () { + return this._beginRange$1; + }, + + set_beginRange: function (value) { + if (!ss.compareDates(this._beginRange$1, value)) { + this.version++; + this._beginRange$1 = value; + } + return value; + }, + + get_endRange: function () { + return this._endRange$1; + }, + + set_endRange: function (value) { + if (!ss.compareDates(this._endRange$1, value)) { + this.version++; + this._endRange$1 = value; + } + return value; + }, + + initializeFromXml: function (node) { + this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); + this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); + this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); + this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); + this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); + if (this.get_coordinatesType() < 0) { + this.set_coordinatesType(0); + } + this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); + this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); + if (node.attributes.getNamedItem('GeometryColumn') != null) { + this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); + } + switch (node.attributes.getNamedItem('AltType').nodeValue) { + case 'Depth': + this.set_altType(0); + break; + case 'Altitude': + this.set_altType(1); + break; + case 'Distance': + this.set_altType(2); + break; + case 'SeaLevel': + this.set_altType(3); + break; + case 'Terrain': + this.set_altType(4); + break; + default: + break; + } + this.set_markerMix(0); + switch (node.attributes.getNamedItem('ColorMap').nodeValue) { + case 'Same_For_All': + this.set__colorMap(0); + break; + case 'Group_by_Values': + this.set__colorMap(2); + break; + case 'Per_Column_Literal': + this.set__colorMap(3); + break; + default: + break; + } + this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); + this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); + switch (node.attributes.getNamedItem('PlotType').nodeValue) { + case 'Gaussian': + this.set_plotType(0); + break; + case 'Point': + this.set_plotType(1); + break; + case 'Circle': + this.set_plotType(2); + break; + case 'PushPin': + this.set_plotType(4); + break; + default: + break; + } + this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); + switch (node.attributes.getNamedItem('MarkerScale').nodeValue) { + case 'Screen': + this.set_markerScale(0); + break; + case 'World': + this.set_markerScale(1); + break; + default: + break; + } + switch (node.attributes.getNamedItem('AltUnit').nodeValue) { + case 'Meters': + this.set_altUnit(1); + break; + case 'Feet': + this.set_altUnit(2); + break; + case 'Inches': + this.set_altUnit(3); + break; + case 'Miles': + this.set_altUnit(4); + break; + case 'Kilometers': + this.set_altUnit(5); + break; + case 'AstronomicalUnits': + this.set_altUnit(6); + break; + case 'LightYears': + this.set_altUnit(7); + break; + case 'Parsecs': + this.set_altUnit(8); + break; + case 'MegaParsecs': + this.set_altUnit(9); + break; + case 'Custom': + this.set_altUnit(10); + break; + default: + break; + } + this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); + this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); + this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); + this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); + this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); + this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); + this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); + switch (node.attributes.getNamedItem('PointScaleType').nodeValue) { + case 'Linear': + this.set_pointScaleType(0); + break; + case 'Power': + this.set_pointScaleType(1); + break; + case 'Log': + this.set_pointScaleType(2); + break; + case 'Constant': + this.set_pointScaleType(3); + break; + case 'StellarMagnitude': + this.set_pointScaleType(4); + break; + default: + break; + } + if (node.attributes.getNamedItem('ShowFarSide') != null) { + this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); + } + if (node.attributes.getNamedItem('RaUnits') != null) { + switch (node.attributes.getNamedItem('RaUnits').nodeValue) { + case 'Hours': + this.set_raUnits(0); + break; + case 'Degrees': + this.set_raUnits(1); + break; + } + } + if (node.attributes.getNamedItem('HoverTextColumn') != null) { + this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); + } + if (node.attributes.getNamedItem('XAxisColumn') != null) { + this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); + this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); + this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); + this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); + this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); + this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); + switch (node.attributes.getNamedItem('CartesianScale').nodeValue) { + case 'Meters': + this.set_cartesianScale(1); + break; + case 'Feet': + this.set_cartesianScale(2); + break; + case 'Inches': + this.set_cartesianScale(3); + break; + case 'Miles': + this.set_cartesianScale(4); + break; + case 'Kilometers': + this.set_cartesianScale(5); + break; + case 'AstronomicalUnits': + this.set_cartesianScale(6); + break; + case 'LightYears': + this.set_cartesianScale(7); + break; + case 'Parsecs': + this.set_cartesianScale(8); + break; + case 'MegaParsecs': + this.set_cartesianScale(9); + break; + case 'Custom': + this.set_cartesianScale(10); + break; + default: + break; + } + this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); + } + if (node.attributes.getNamedItem('DynamicData') != null) { + this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); + this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); + this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); + } + }, + + computeDateDomainRange: function (columnStart, columnEnd) { }, + + getDomainValues: function (column) { + return []; + }, + + get_decay: function () { + return this.decay; + }, + + set_decay: function (value) { + if (this.decay !== value) { + this.version++; + this.decay = value; + } + return value; + }, + + get_coordinatesType: function () { + return this._coordinatesType$1; + }, + + set_coordinatesType: function (value) { + if (this._coordinatesType$1 !== value) { + this.version++; + this._coordinatesType$1 = value; + } + return value; + }, + + get_latColumn: function () { + return this.latColumn; + }, + + set_latColumn: function (value) { + if (this.latColumn !== value) { + this.version++; + this.latColumn = value; + } + return value; + }, + + get_lngColumn: function () { + return this.lngColumn; + }, + + set_lngColumn: function (value) { + if (this.lngColumn !== value) { + this.version++; + this.lngColumn = value; + } + return value; + }, + + get_geometryColumn: function () { + return this.geometryColumn; + }, + + set_geometryColumn: function (value) { + if (this.geometryColumn !== value) { + this.version++; + this.geometryColumn = value; + } + return value; + }, + + get_xAxisColumn: function () { + return this._xAxisColumn$1; + }, + + set_xAxisColumn: function (value) { + if (this._xAxisColumn$1 !== value) { + this.version++; + this._xAxisColumn$1 = value; + } + return value; + }, + + get_yAxisColumn: function () { + return this._yAxisColumn$1; + }, + + set_yAxisColumn: function (value) { + if (this._yAxisColumn$1 !== value) { + this.version++; + this._yAxisColumn$1 = value; + } + return value; + }, + + get_zAxisColumn: function () { + return this._zAxisColumn$1; + }, + + set_zAxisColumn: function (value) { + if (this._zAxisColumn$1 !== value) { + this.version++; + this._zAxisColumn$1 = value; + } + return value; + }, + + get_xAxisReverse: function () { + return this._xAxisReverse$1; + }, + + set_xAxisReverse: function (value) { + if (this._xAxisReverse$1 !== value) { + this.version++; + this._xAxisReverse$1 = value; + } + return value; + }, + + get_yAxisReverse: function () { + return this._yAxisReverse$1; + }, + + set_yAxisReverse: function (value) { + if (this._yAxisReverse$1 !== value) { + this.version++; + this._yAxisReverse$1 = value; + } + return value; + }, + + get_zAxisReverse: function () { + return this._zAxisReverse$1; + }, + + set_zAxisReverse: function (value) { + if (this._zAxisReverse$1 !== value) { + this.version++; + this._zAxisReverse$1 = value; + } + return value; + }, + + get_altType: function () { + return this._altType$1; + }, + + set_altType: function (value) { + if (this._altType$1 !== value) { + this.version++; + this._altType$1 = value; + } + return value; + }, + + get_markerMix: function () { + return this._markerMix$1; + }, + + set_markerMix: function (value) { + if (this._markerMix$1 !== value) { + this.version++; + this._markerMix$1 = value; + } + return value; + }, + + get_raUnits: function () { + return this._raUnits$1; + }, + + set_raUnits: function (value) { + if (this._raUnits$1 !== value) { + this.version++; + this._raUnits$1 = value; + } + return value; + }, + + get__colorMap: function () { + return this._colorMap$1; + }, + + set__colorMap: function (value) { + if (this._colorMap$1 !== value) { + this.version++; + this._colorMap$1 = value; + } + return value; + }, + + get_markerColumn: function () { + return this._markerColumn$1; + }, + + set_markerColumn: function (value) { + if (this._markerColumn$1 !== value) { + this.version++; + this._markerColumn$1 = value; + } + return value; + }, + + get_colorMapColumn: function () { + return this._colorMapColumn$1; + }, + + set_colorMapColumn: function (value) { + if (this._colorMapColumn$1 !== value) { + this.version++; + this._colorMapColumn$1 = value; + } + return value; + }, + + get_plotType: function () { + return this._plotType$1; + }, + + set_plotType: function (value) { + if (this._plotType$1 !== value) { + this.version++; + this._plotType$1 = value; + } + return value; + }, + + get_markerIndex: function () { + return this._markerIndex$1; + }, + + set_markerIndex: function (value) { + if (this._markerIndex$1 !== value) { + this.version++; + this._markerIndex$1 = value; + } + return value; + }, + + get_showFarSide: function () { + return this._showFarSide$1; + }, + + set_showFarSide: function (value) { + if (this._showFarSide$1 !== value) { + this.version++; + this._showFarSide$1 = value; + } + return value; + }, + + get_markerScale: function () { + return this._markerScale$1; + }, + + set_markerScale: function (value) { + if (this._markerScale$1 !== value) { + this.version++; + this._markerScale$1 = value; + } + return value; + }, + + get_altUnit: function () { + return this._altUnit$1; + }, + + set_altUnit: function (value) { + if (this._altUnit$1 !== value) { + this.version++; + this._altUnit$1 = value; + } + return value; + }, + + get_cartesianScale: function () { + return this._cartesianScale$1; + }, + + set_cartesianScale: function (value) { + if (this._cartesianScale$1 !== value) { + this.version++; + this._cartesianScale$1 = value; + } + return value; + }, + + get_cartesianCustomScale: function () { + return this._cartesianCustomScale$1; + }, + + set_cartesianCustomScale: function (value) { + if (this._cartesianCustomScale$1 !== value) { + this.version++; + this._cartesianCustomScale$1 = value; + } + return value; + }, + + get_altColumn: function () { + return this.altColumn; + }, + + set_altColumn: function (value) { + if (this.altColumn !== value) { + this.version++; + this.altColumn = value; + } + return value; + }, + + get_startDateColumn: function () { + return this.startDateColumn; + }, + + set_startDateColumn: function (value) { + if (this.startDateColumn !== value) { + this.version++; + this.startDateColumn = value; + } + return value; + }, + + get_endDateColumn: function () { + return this.endDateColumn; + }, + + set_endDateColumn: function (value) { + if (this.endDateColumn !== value) { + this.version++; + this.endDateColumn = value; + } + return value; + }, + + get_sizeColumn: function () { + return this.sizeColumn; + }, + + set_sizeColumn: function (value) { + if (this.sizeColumn !== value) { + this.version++; + this.sizeColumn = value; + } + return value; + }, + + get_nameColumn: function () { + return this.nameColumn; + }, + + set_nameColumn: function (value) { + if (this.nameColumn !== value) { + this.version++; + this.nameColumn = value; + } + return value; + }, + + get_hyperlinkFormat: function () { + return this._hyperlinkFormat$1; + }, + + set_hyperlinkFormat: function (value) { + if (this._hyperlinkFormat$1 !== value) { + this.version++; + this._hyperlinkFormat$1 = value; + } + return value; + }, + + get_hyperlinkColumn: function () { + return this._hyperlinkColumn$1; + }, + + set_hyperlinkColumn: function (value) { + if (this._hyperlinkColumn$1 !== value) { + this.version++; + this._hyperlinkColumn$1 = value; + } + return value; + }, + + get_scaleFactor: function () { + return this.scaleFactor; + }, + + set_scaleFactor: function (value) { + if (this.scaleFactor !== value) { + this.version++; + this.scaleFactor = value; + } + return value; + }, + + get_pointScaleType: function () { + return this.pointScaleType; + }, + + set_pointScaleType: function (value) { + if (this.pointScaleType !== value) { + this.version++; + this.pointScaleType = value; + } + return value; + }, + + prepVertexBuffer: function (renderContext, opacity) { + return true; + }, + + draw: function (renderContext, opacity, flat) { + var device = renderContext; + if (this.version !== this.lastVersion) { + this.cleanUp(); + } + if (this.bufferIsFlat !== flat) { + this.cleanUp(); + this.bufferIsFlat = flat; + } + if (this.dirty) { + this.prepVertexBuffer(device, opacity); + } + var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); + var adjustedScale = this.scaleFactor; + if (flat && this.astronomical && (this._markerScale$1 === 1)) { + adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); + } + if (this.triangleList2d != null) { + this.triangleList2d.decay = this.decay; + this.triangleList2d.sky = this.get_astronomical(); + this.triangleList2d.timeSeries = this.timeSeries; + this.triangleList2d.jNow = jNow; + this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.triangleList != null) { + this.triangleList.decay = this.decay; + this.triangleList.sky = this.get_astronomical(); + this.triangleList.timeSeries = this.timeSeries; + this.triangleList.jNow = jNow; + this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.pointList != null) { + this.pointList.depthBuffered = false; + this.pointList.decay = this.decay; + this.pointList.sky = this.get_astronomical(); + this.pointList.timeSeries = this.timeSeries; + this.pointList.jNow = jNow; + this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; + this.pointList.draw(renderContext, opacity * this.get_opacity(), false); + } + if (this.lineList != null) { + this.lineList.sky = this.get_astronomical(); + this.lineList.decay = this.decay; + this.lineList.timeSeries = this.timeSeries; + this.lineList.jNow = jNow; + this.lineList.drawLines(renderContext, opacity * this.get_opacity()); + } + if (this.lineList2d != null) { + this.lineList2d.sky = this.get_astronomical(); + this.lineList2d.decay = this.decay; + this.lineList2d.timeSeries = this.timeSeries; + this.lineList2d.showFarSide = this.get_showFarSide(); + this.lineList2d.jNow = jNow; + this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); + } + return true; + }, + + initFromXml: function (node) { + Layer.prototype.initFromXml.call(this, node); + }, + + cleanUp: function () { + if (this.lineList != null) { + this.lineList.clear(); + } + if (this.lineList2d != null) { + this.lineList2d.clear(); + } + if (this.triangleList2d != null) { + this.triangleList2d.clear(); + } + if (this.pointList != null) { + this.pointList.clear(); + } + if (this.triangleList != null) { + this.triangleList.clear(); + } + }, + + dynamicUpdate: function () { + return false; + } +}; + +registerType("TimeSeriesLayer", [TimeSeriesLayer, TimeSeriesLayer$, Layer]); diff --git a/engine/esm/layers/vo_table.js b/engine/esm/layers/vo_table.js new file mode 100644 index 00000000..c1fd0448 --- /dev/null +++ b/engine/esm/layers/vo_table.js @@ -0,0 +1,393 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The Virtual Observatory table (VOTable) format. + +import { ss } from "../ss.js"; +import { registerType, registerEnum } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { URLHelpers } from "../url_helpers.js"; +import { WebFile } from "../web_file.js"; + + +// wwtlib.Primitives + +export var Primitives = { + voBoolean: 1, + voBit: 2, + voUnsignedByte: 3, + voShort: 4, + voInt: 5, + voLong: 6, + voChar: 7, + voUnicodeChar: 8, + voFloat: 9, + voDouble: 10, + voFloatComplex: 11, + voDoubleComplex: 12, + voUndefined: 13 +}; + +registerType("Primitives", Primitives); +registerEnum("Primitives", Primitives); + + +// wwtlib.VoTable + +export function VoTable() { + this.columns = {}; + this.column = []; + this.rows = []; + this.loadFilename = ''; + this.sampId = ''; + this.selectedRow = null; + this.error = false; + this.errorText = ''; +} + +VoTable.loadFromUrl = function (url, complete) { + var temp = new VoTable(); + temp._onComplete = complete; + temp._webFile = new WebFile(URLHelpers.singleton.rewrite(url, 1)); + temp._webFile.onStateChange = ss.bind('_loadData', temp); + temp._webFile.send(); + return temp; +}; + +VoTable.loadFromString = function (data) { + var xParser = new DOMParser(); + var doc = xParser.parseFromString(data, 'text/xml'); + var table = new VoTable(); + table.loadFromXML(doc); + return table; +}; + +var VoTable$ = { + _loadData: function () { + if (this._webFile.get_state() === 2) { + alert(this._webFile.get_message()); + } else if (this._webFile.get_state() === 1) { + this.loadFromXML(this._webFile.getXml()); + if (this._onComplete != null) { + this._onComplete(); + } + } + }, + + loadFromXML: function (xml) { + var voTable = Util.selectSingleNode(xml, 'VOTABLE'); + if (voTable == null) { + return; + } + var index = 0; + try { + var table = Util.selectSingleNode(Util.selectSingleNode(voTable, 'RESOURCE'), 'TABLE'); + if (table != null) { + var $enum1 = ss.enumerate(table.childNodes); + while ($enum1.moveNext()) { + var node = $enum1.current; + if (node.nodeName === 'FIELD') { + var col = new VoColumn(node, index++); + this.columns[col.name] = col; + this.column.push(col); + } + } + } + } + catch ($e2) { + this.error = true; + this.errorText = Util.selectSingleNode(voTable, 'DESCRIPTION').text; + } + try { + var tableData = Util.selectSingleNode(Util.selectSingleNode(Util.selectSingleNode(Util.selectSingleNode(voTable, 'RESOURCE'), 'TABLE'), 'DATA'), 'TABLEDATA'); + if (tableData != null) { + var $enum3 = ss.enumerate(tableData.childNodes); + while ($enum3.moveNext()) { + var node = $enum3.current; + if (node.nodeName === 'TR') { + var row = new VoRow(this); + row.columnData = new Array(ss.keyCount(this.columns)); + index = 0; + var $enum4 = ss.enumerate(node.childNodes); + while ($enum4.moveNext()) { + var child = $enum4.current; + if (child.nodeName === 'TD') { + row.columnData[index++] = ss.trim(Util.getInnerText(child)); + } + } + this.rows.push(row); + } + } + } + } + catch ($e5) { + } + }, + + save: function (filename) { + return true; + }, + + getColumnByUcd: function (ucd) { + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (ss.replaceString(col.ucd, '_', '.').toLocaleLowerCase().indexOf(ucd.toLocaleLowerCase()) > -1) { + return col; + } + } + return null; + }, + + getRAColumn: function () { + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (col.ucd.toLocaleLowerCase().indexOf('pos.eq.ra') > -1 || col.ucd.toLocaleLowerCase().indexOf('pos_eq_ra') > -1) { + return col; + } + } + var $enum2 = ss.enumerate(ss.keys(this.columns)); + while ($enum2.moveNext()) { + var key = $enum2.current; + var col = this.columns[key]; + if (col.name.toLocaleLowerCase().indexOf('ra') > -1) { + return col; + } + } + return null; + }, + + getDecColumn: function () { + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (col.ucd.toLowerCase().indexOf('pos.eq.dec') > -1 || col.ucd.toLowerCase().indexOf('pos_eq_dec') > -1) { + return col; + } + } + var $enum2 = ss.enumerate(ss.keys(this.columns)); + while ($enum2.moveNext()) { + var key = $enum2.current; + var col = this.columns[key]; + if (col.name.toLowerCase().indexOf('dec') > -1) { + return col; + } + } + return null; + }, + + getMagColumn: function () { + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (col.ucd.toLowerCase().indexOf('phot.mag') > -1 || col.ucd.toLowerCase().indexOf('phot_mag') > -1) { + return col; + } + } + return null; + }, + + getDistanceColumn: function () { + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (col.ucd.toLowerCase().indexOf('pos.distance') > -1 || col.ucd.toLowerCase().indexOf('pos_distance') > -1) { + return col; + } + } + return null; + }, + + toString: function () { + var sb = new ss.StringBuilder(); + var first = true; + + // Copy header + + var $enum1 = ss.enumerate(ss.keys(this.columns)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var col = this.columns[key]; + if (first) { + first = false; + } + else { + sb.append('\t'); + } + sb.append(col.name); + } + sb.appendLine(''); + + // copy rows + + var $enum2 = ss.enumerate(this.rows); + while ($enum2.moveNext()) { + var row = $enum2.current; + first = true; + var $enum3 = ss.enumerate(row.columnData); + while ($enum3.moveNext()) { + var col = $enum3.current; + if (first) { + first = false; + } + else { + sb.append('\t'); + } + sb.append(col.toString()); + } + sb.appendLine(''); + } + return sb.toString(); + } +}; + +registerType("VoTable", [VoTable, VoTable$, null]); + + +// wwtlib.VoRow + +export function VoRow(owner) { + this.selected = false; + this.owner = owner; +} + +var VoRow$ = { + getColumnData: function (key) { + if (this.owner.columns[key] != null) { + return this.columnData[this.owner.columns[key].index]; + } + return null; + }, + + get_item: function (index) { + if (index < 0 || index >= this.columnData.length) { + return null; + } + return this.columnData[index]; + } +}; + +registerType("VoRow", [VoRow, VoRow$, null]); + + +// wwtlib.VoColumn + +export function VoColumn(node, index) { + this.id = ''; + this.type = 0; + this.precision = 0; + this.dimentions = 0; + this.sizes = null; + this.ucd = ''; + this.unit = ''; + this.name = ''; + this.index = 0; + this.index = index; + if (node.attributes.getNamedItem('datatype') != null) { + this.type = VoColumn.getType(node.attributes.getNamedItem('datatype').nodeValue); + } + if (node.attributes.getNamedItem('ucd') != null) { + this.ucd = node.attributes.getNamedItem('ucd').nodeValue; + } + if (node.attributes.getNamedItem('precision') != null) { + try { + this.precision = parseInt(node.attributes.getNamedItem('precision').nodeValue); + } + catch ($e1) { + } + } + if (node.attributes.getNamedItem('ID') != null) { + this.id = node.attributes.getNamedItem('ID').nodeValue; + } + if (node.attributes.getNamedItem('name') != null) { + this.name = node.attributes.getNamedItem('name').nodeValue; + } + else { + this.name = this.id; + } + if (node.attributes.getNamedItem('unit') != null) { + this.unit = node.attributes.getNamedItem('unit').nodeValue; + } + if (node.attributes.getNamedItem('arraysize') != null) { + var split = node.attributes.getNamedItem('arraysize').nodeValue.split('x'); + this.dimentions = split.length; + this.sizes = new Array(split.length); + var indexer = 0; + var $enum2 = ss.enumerate(split); + while ($enum2.moveNext()) { + var dim = $enum2.current; + if (!(dim.indexOf('*') > -1)) { + this.sizes[indexer++] = parseInt(dim); + } + else { + var len = 9999; + var lenString = ss.replaceString(dim, '*', ''); + if (lenString.length > 0) { + len = parseInt(lenString); + } + this.sizes[indexer++] = len; + } + } + } +} + +VoColumn.getType = function (type) { + var Type = 13; + switch (type) { + case 'boolean': + Type = 1; + break; + case 'bit': + Type = 2; + break; + case 'unsignedByte': + Type = 3; + break; + case 'short': + Type = 4; + break; + case 'int': + Type = 5; + break; + case 'long': + Type = 6; + break; + case 'char': + Type = 7; + break; + case 'unicodeChar': + Type = 8; + break; + case 'float': + Type = 9; + break; + case 'double': + Type = 10; + break; + case 'floatComplex': + Type = 11; + break; + case 'doubleComplex': + Type = 12; + break; + default: + Type = 13; + break; + } + return Type; +}; + +var VoColumn$ = { + toString: function () { + return this.name; + } +}; + +registerType("VoColumn", [VoColumn, VoColumn$, null]); + diff --git a/engine/esm/layers/vo_table_layer.js b/engine/esm/layers/vo_table_layer.js new file mode 100644 index 00000000..bdcfce45 --- /dev/null +++ b/engine/esm/layers/vo_table_layer.js @@ -0,0 +1,1117 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer that renders a VO data table. +// +// This has massive redundancy with SpreadSheetLayer, which I think was +// necessitated by limitations in ScriptSharp. It would be nice to streamline +// things. + +import { ss } from "../ss.js"; +import { registerType, Enums } from "../typesystem.js"; +import { Vector3d } from "../double3d.js"; +import { Dates, LineList, PointList, TimeSeriesPointVertex } from "../graphics/primitives3d.js"; +import { Texture } from "../graphics/texture.js"; +import { Color, Colors } from "../color.js"; +import { Coordinates } from "../coordinates.js"; +import { Place } from "../place.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { URLHelpers } from "../url_helpers.js"; +import { Layer } from "./layer.js"; +import { VoTable } from "./vo_table.js"; +import { SpreadSheetLayer, PushPin } from "./spreadsheet_layer.js"; + + +// wwtlib.VoTableLayer + +export function VoTableLayer() { + this.isLongIndex = false; + this.shapeVertexCount = 0; + this.lines = false; + this.latColumn = -1; + this.fixedSize = 1; + this.decay = 0; + this.timeSeries = false; + this._dynamicData$1 = false; + this._autoUpdate$1 = false; + this._dataSourceUrl$1 = ''; + this._beginRange$1 = new Date('1/1/2100'); + this._endRange$1 = new Date('01/01/1800'); + this.markerDomainValues = {}; + this.colorDomainValues = {}; + this._coordinatesType$1 = 0; + this.lngColumn = -1; + this.geometryColumn = -1; + this._xAxisColumn$1 = -1; + this._yAxisColumn$1 = -1; + this._zAxisColumn$1 = -1; + this._xAxisReverse$1 = false; + this._yAxisReverse$1 = false; + this._zAxisReverse$1 = false; + this._altType$1 = 3; + this._markerMix$1 = 0; + this._raUnits$1 = 0; + this._colorMap$1 = 3; + this._markerColumn$1 = -1; + this._colorMapColumn$1 = -1; + this._plotType$1 = 0; + this._markerIndex$1 = 0; + this._showFarSide$1 = false; + this._markerScale$1 = 1; + this._altUnit$1 = 1; + this._cartesianScale$1 = 1; + this._cartesianCustomScale$1 = 1; + this.altColumn = -1; + this.startDateColumn = -1; + this.endDateColumn = -1; + this.sizeColumn = -1; + this.nameColumn = 0; + this._hyperlinkFormat$1 = ''; + this._hyperlinkColumn$1 = -1; + this.scaleFactor = 1; + this.pointScaleType = 1; + this.positions = []; + this.bufferIsFlat = false; + this.baseDate = new Date(2010, 0, 1, 12, 0, 0); + this.dirty = true; + this._filename$1 = ''; + Layer.call(this); + this._table$1 = null; + this._filename$1 = ''; + this.set_plotType(2); +} + +VoTableLayer._circleTexture$1 = null; + +VoTableLayer.get__circleTexture$1 = function () { + if (VoTableLayer._circleTexture$1 == null) { + var url = URLHelpers.singleton.engineAssetUrl('circle.png'); + VoTableLayer._circleTexture$1 = Texture.fromUrl(url); + } + return VoTableLayer._circleTexture$1; +}; + +VoTableLayer.create = function (table, plotType) { + var layer = new VoTableLayer(); + layer._table$1 = table; + layer._filename$1 = table.loadFilename; + layer.set_lngColumn(table.getRAColumn().index); + layer.set_latColumn(table.getDecColumn().index); + layer.sizeColumn = table.getColumnByUcd('phot.mag').index; + layer.set_plotType(plotType); + return layer; +}; + +var VoTableLayer$ = { + get_dynamicData: function () { + return this._dynamicData$1; + }, + + set_dynamicData: function (value) { + this._dynamicData$1 = value; + return value; + }, + + get_autoUpdate: function () { + return this._autoUpdate$1; + }, + + set_autoUpdate: function (value) { + this._autoUpdate$1 = value; + return value; + }, + + get_dataSourceUrl: function () { + return this._dataSourceUrl$1; + }, + + set_dataSourceUrl: function (value) { + this._dataSourceUrl$1 = value; + return value; + }, + + get_timeSeries: function () { + return this.timeSeries; + }, + + set_timeSeries: function (value) { + if (this.timeSeries !== value) { + this.version++; + this.timeSeries = value; + } + return value; + }, + + get_beginRange: function () { + return this._beginRange$1; + }, + + set_beginRange: function (value) { + if (!ss.compareDates(this._beginRange$1, value)) { + this.version++; + this._beginRange$1 = value; + } + return value; + }, + + get_endRange: function () { + return this._endRange$1; + }, + + set_endRange: function (value) { + if (!ss.compareDates(this._endRange$1, value)) { + this.version++; + this._endRange$1 = value; + } + return value; + }, + + initializeFromXml: function (node) { + this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); + this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); + this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); + this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); + this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); + if (this.get_coordinatesType() < 0) { + this.set_coordinatesType(0); + } + this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); + this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); + if (node.attributes.getNamedItem('GeometryColumn') != null) { + this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); + } + switch (node.attributes.getNamedItem('AltType').nodeValue) { + case 'Depth': + this.set_altType(0); + break; + case 'Altitude': + this.set_altType(1); + break; + case 'Distance': + this.set_altType(2); + break; + case 'SeaLevel': + this.set_altType(3); + break; + case 'Terrain': + this.set_altType(4); + break; + default: + break; + } + this.set_markerMix(0); + switch (node.attributes.getNamedItem('ColorMap').nodeValue) { + case 'Same_For_All': + this.set__colorMap(0); + break; + case 'Group_by_Values': + this.set__colorMap(2); + break; + case 'Per_Column_Literal': + this.set__colorMap(3); + break; + default: + break; + } + this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); + this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); + switch (node.attributes.getNamedItem('PlotType').nodeValue) { + case 'Gaussian': + this.set_plotType(0); + break; + case 'Point': + this.set_plotType(1); + break; + case 'Circle': + this.set_plotType(2); + break; + case 'PushPin': + this.set_plotType(4); + break; + default: + break; + } + this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); + switch (node.attributes.getNamedItem('MarkerScale').nodeValue) { + case 'Screen': + this.set_markerScale(0); + break; + case 'World': + this.set_markerScale(1); + break; + default: + break; + } + switch (node.attributes.getNamedItem('AltUnit').nodeValue) { + case 'Meters': + this.set_altUnit(1); + break; + case 'Feet': + this.set_altUnit(2); + break; + case 'Inches': + this.set_altUnit(3); + break; + case 'Miles': + this.set_altUnit(4); + break; + case 'Kilometers': + this.set_altUnit(5); + break; + case 'AstronomicalUnits': + this.set_altUnit(6); + break; + case 'LightYears': + this.set_altUnit(7); + break; + case 'Parsecs': + this.set_altUnit(8); + break; + case 'MegaParsecs': + this.set_altUnit(9); + break; + case 'Custom': + this.set_altUnit(10); + break; + default: + break; + } + this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); + this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); + this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); + this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); + this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); + this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); + this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); + switch (node.attributes.getNamedItem('PointScaleType').nodeValue) { + case 'Linear': + this.set_pointScaleType(0); + break; + case 'Power': + this.set_pointScaleType(1); + break; + case 'Log': + this.set_pointScaleType(2); + break; + case 'Constant': + this.set_pointScaleType(3); + break; + case 'StellarMagnitude': + this.set_pointScaleType(4); + break; + default: + break; + } + if (node.attributes.getNamedItem('ShowFarSide') != null) { + this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); + } + if (node.attributes.getNamedItem('RaUnits') != null) { + switch (node.attributes.getNamedItem('RaUnits').nodeValue) { + case 'Hours': + this.set_raUnits(0); + break; + case 'Degrees': + this.set_raUnits(1); + break; + } + } + if (node.attributes.getNamedItem('HoverTextColumn') != null) { + this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); + } + if (node.attributes.getNamedItem('XAxisColumn') != null) { + this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); + this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); + this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); + this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); + this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); + this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); + switch (node.attributes.getNamedItem('CartesianScale').nodeValue) { + case 'Meters': + this.set_cartesianScale(1); + break; + case 'Feet': + this.set_cartesianScale(2); + break; + case 'Inches': + this.set_cartesianScale(3); + break; + case 'Miles': + this.set_cartesianScale(4); + break; + case 'Kilometers': + this.set_cartesianScale(5); + break; + case 'AstronomicalUnits': + this.set_cartesianScale(6); + break; + case 'LightYears': + this.set_cartesianScale(7); + break; + case 'Parsecs': + this.set_cartesianScale(8); + break; + case 'MegaParsecs': + this.set_cartesianScale(9); + break; + case 'Custom': + this.set_cartesianScale(10); + break; + default: + break; + } + this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); + } + if (node.attributes.getNamedItem('DynamicData') != null) { + this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); + this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); + this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); + } + }, + + get_decay: function () { + return this.decay; + }, + + set_decay: function (value) { + if (this.decay !== value) { + this.version++; + this.decay = value; + } + return value; + }, + + get_coordinatesType: function () { + return this._coordinatesType$1; + }, + + set_coordinatesType: function (value) { + if (this._coordinatesType$1 !== value) { + this.version++; + this._coordinatesType$1 = value; + } + return value; + }, + + get_latColumn: function () { + return this.latColumn; + }, + + set_latColumn: function (value) { + if (this.latColumn !== value) { + this.version++; + this.latColumn = value; + } + return value; + }, + + get_lngColumn: function () { + return this.lngColumn; + }, + + set_lngColumn: function (value) { + if (this.lngColumn !== value) { + this.version++; + this.lngColumn = value; + } + return value; + }, + + get_geometryColumn: function () { + return this.geometryColumn; + }, + + set_geometryColumn: function (value) { + if (this.geometryColumn !== value) { + this.version++; + this.geometryColumn = value; + } + return value; + }, + + get_xAxisColumn: function () { + return this._xAxisColumn$1; + }, + + set_xAxisColumn: function (value) { + if (this._xAxisColumn$1 !== value) { + this.version++; + this._xAxisColumn$1 = value; + } + return value; + }, + + get_yAxisColumn: function () { + return this._yAxisColumn$1; + }, + + set_yAxisColumn: function (value) { + if (this._yAxisColumn$1 !== value) { + this.version++; + this._yAxisColumn$1 = value; + } + return value; + }, + + get_zAxisColumn: function () { + return this._zAxisColumn$1; + }, + + set_zAxisColumn: function (value) { + if (this._zAxisColumn$1 !== value) { + this.version++; + this._zAxisColumn$1 = value; + } + return value; + }, + + get_xAxisReverse: function () { + return this._xAxisReverse$1; + }, + + set_xAxisReverse: function (value) { + if (this._xAxisReverse$1 !== value) { + this.version++; + this._xAxisReverse$1 = value; + } + return value; + }, + + get_yAxisReverse: function () { + return this._yAxisReverse$1; + }, + + set_yAxisReverse: function (value) { + if (this._yAxisReverse$1 !== value) { + this.version++; + this._yAxisReverse$1 = value; + } + return value; + }, + + get_zAxisReverse: function () { + return this._zAxisReverse$1; + }, + + set_zAxisReverse: function (value) { + if (this._zAxisReverse$1 !== value) { + this.version++; + this._zAxisReverse$1 = value; + } + return value; + }, + + get_altType: function () { + return this._altType$1; + }, + + set_altType: function (value) { + if (this._altType$1 !== value) { + this.version++; + this._altType$1 = value; + } + return value; + }, + + get_markerMix: function () { + return this._markerMix$1; + }, + + set_markerMix: function (value) { + if (this._markerMix$1 !== value) { + this.version++; + this._markerMix$1 = value; + } + return value; + }, + + get_raUnits: function () { + return this._raUnits$1; + }, + + set_raUnits: function (value) { + if (this._raUnits$1 !== value) { + this.version++; + this._raUnits$1 = value; + } + return value; + }, + + get__colorMap: function () { + return this._colorMap$1; + }, + + set__colorMap: function (value) { + if (this._colorMap$1 !== value) { + this.version++; + this._colorMap$1 = value; + } + return value; + }, + + get_markerColumn: function () { + return this._markerColumn$1; + }, + + set_markerColumn: function (value) { + if (this._markerColumn$1 !== value) { + this.version++; + this._markerColumn$1 = value; + } + return value; + }, + + get_colorMapColumn: function () { + return this._colorMapColumn$1; + }, + + set_colorMapColumn: function (value) { + if (this._colorMapColumn$1 !== value) { + this.version++; + this._colorMapColumn$1 = value; + } + return value; + }, + + get_plotType: function () { + return this._plotType$1; + }, + + set_plotType: function (value) { + if (this._plotType$1 !== value) { + this.version++; + this._plotType$1 = value; + } + return value; + }, + + get_markerIndex: function () { + return this._markerIndex$1; + }, + + set_markerIndex: function (value) { + if (this._markerIndex$1 !== value) { + this.version++; + this._markerIndex$1 = value; + } + return value; + }, + + get_showFarSide: function () { + return this._showFarSide$1; + }, + + set_showFarSide: function (value) { + if (this._showFarSide$1 !== value) { + this.version++; + this._showFarSide$1 = value; + } + return value; + }, + + get_markerScale: function () { + return this._markerScale$1; + }, + + set_markerScale: function (value) { + if (this._markerScale$1 !== value) { + this.version++; + this._markerScale$1 = value; + } + return value; + }, + + get_altUnit: function () { + return this._altUnit$1; + }, + + set_altUnit: function (value) { + if (this._altUnit$1 !== value) { + this.version++; + this._altUnit$1 = value; + } + return value; + }, + + get_cartesianScale: function () { + return this._cartesianScale$1; + }, + + set_cartesianScale: function (value) { + if (this._cartesianScale$1 !== value) { + this.version++; + this._cartesianScale$1 = value; + } + return value; + }, + + get_cartesianCustomScale: function () { + return this._cartesianCustomScale$1; + }, + + set_cartesianCustomScale: function (value) { + if (this._cartesianCustomScale$1 !== value) { + this.version++; + this._cartesianCustomScale$1 = value; + } + return value; + }, + + get_altColumn: function () { + return this.altColumn; + }, + + set_altColumn: function (value) { + if (this.altColumn !== value) { + this.version++; + this.altColumn = value; + } + return value; + }, + + get_startDateColumn: function () { + return this.startDateColumn; + }, + + set_startDateColumn: function (value) { + if (this.startDateColumn !== value) { + this.version++; + this.startDateColumn = value; + } + return value; + }, + + get_endDateColumn: function () { + return this.endDateColumn; + }, + + set_endDateColumn: function (value) { + if (this.endDateColumn !== value) { + this.version++; + this.endDateColumn = value; + } + return value; + }, + + get_sizeColumn: function () { + return this.sizeColumn; + }, + + set_sizeColumn: function (value) { + if (this.sizeColumn !== value) { + this.version++; + this.sizeColumn = value; + } + return value; + }, + + get_nameColumn: function () { + return this.nameColumn; + }, + + set_nameColumn: function (value) { + if (this.nameColumn !== value) { + this.version++; + this.nameColumn = value; + } + return value; + }, + + get_hyperlinkFormat: function () { + return this._hyperlinkFormat$1; + }, + + set_hyperlinkFormat: function (value) { + if (this._hyperlinkFormat$1 !== value) { + this.version++; + this._hyperlinkFormat$1 = value; + } + return value; + }, + + get_hyperlinkColumn: function () { + return this._hyperlinkColumn$1; + }, + + set_hyperlinkColumn: function (value) { + if (this._hyperlinkColumn$1 !== value) { + this.version++; + this._hyperlinkColumn$1 = value; + } + return value; + }, + + get_scaleFactor: function () { + return this.scaleFactor; + }, + + set_scaleFactor: function (value) { + if (this.scaleFactor !== value) { + this.version++; + this.scaleFactor = value; + } + return value; + }, + + get_pointScaleType: function () { + return this.pointScaleType; + }, + + set_pointScaleType: function (value) { + if (this.pointScaleType !== value) { + this.version++; + this.pointScaleType = value; + } + return value; + }, + + draw: function (renderContext, opacity, flat) { + var device = renderContext; + if (this.bufferIsFlat !== flat) { + this.cleanUp(); + this.bufferIsFlat = flat; + } + if (this.dirty) { + this.prepVertexBuffer(renderContext, opacity); + this.dirty = false; + } + var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); + var adjustedScale = this.scaleFactor; + if (flat && this.astronomical && (this._markerScale$1 === 1)) { + adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); + } + if (this.triangleList2d != null) { + this.triangleList2d.decay = this.decay; + this.triangleList2d.sky = this.get_astronomical(); + this.triangleList2d.timeSeries = this.timeSeries; + this.triangleList2d.jNow = jNow; + this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.triangleList != null) { + this.triangleList.decay = this.decay; + this.triangleList.sky = this.get_astronomical(); + this.triangleList.timeSeries = this.timeSeries; + this.triangleList.jNow = jNow; + this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); + } + if (this.pointList != null) { + this.pointList.depthBuffered = false; + this.pointList.showFarSide = this.get_showFarSide(); + this.pointList.decay = (this.timeSeries) ? this.decay : 0; + this.pointList.sky = this.get_astronomical(); + this.pointList.timeSeries = this.timeSeries; + this.pointList.jNow = jNow; + this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; + switch (this._plotType$1) { + case 0: + this.pointList.draw(renderContext, opacity * this.get_opacity(), false); + break; + case 2: + this.pointList.drawTextured(renderContext, VoTableLayer.get__circleTexture$1().texture2d, opacity * this.get_opacity()); + break; + case 1: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(19), opacity * this.get_opacity()); + break; + case 3: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(35), opacity * this.get_opacity()); + break; + case 5: + case 4: + this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(this._markerIndex$1), opacity * this.get_opacity()); + break; + default: + break; + } + } + if (this.lineList != null) { + this.lineList.sky = this.get_astronomical(); + this.lineList.decay = this.decay; + this.lineList.timeSeries = this.timeSeries; + this.lineList.jNow = jNow; + this.lineList.drawLines(renderContext, opacity * this.get_opacity()); + } + if (this.lineList2d != null) { + this.lineList2d.sky = this.get_astronomical(); + this.lineList2d.decay = this.decay; + this.lineList2d.timeSeries = this.timeSeries; + this.lineList2d.showFarSide = this.get_showFarSide(); + this.lineList2d.jNow = jNow; + this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); + } + return true; + }, + + initFromXml: function (node) { + Layer.prototype.initFromXml.call(this, node); + }, + + cleanUp: function () { + this.dirty = true; + if (this.lineList != null) { + this.lineList.clear(); + } + if (this.lineList2d != null) { + this.lineList2d.clear(); + } + if (this.triangleList2d != null) { + this.triangleList2d.clear(); + } + if (this.pointList != null) { + this.pointList.clear(); + } + if (this.triangleList != null) { + this.triangleList.clear(); + } + }, + + dynamicUpdate: function () { + return false; + }, + + addFilesToCabinet: function (fc) { + var fName = this._filename$1; + var fileName = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); + var path = fName.substring(0, fName.lastIndexOf('\\') + 1); + var path2 = fileName.substring(0, fileName.lastIndexOf('\\') + 1); + }, + + loadData: function (tourDoc, filename) { + var $this = this; + + var blob = tourDoc.getFileBlob(filename); + var doc = new FileReader(); + doc.onloadend = function (ee) { + var data = ss.safeCast(doc.result, String); + $this._table$1 = VoTable.loadFromString(data); + $this.set_lngColumn($this._table$1.getRAColumn().index); + $this.set_latColumn($this._table$1.getDecColumn().index); + }; + doc.readAsText(blob); + }, + + canCopyToClipboard: function () { + return true; + }, + + copyToClipboard: function () { }, + + findClosest: function (target, distance, defaultPlace, astronomical) { + var searchPoint = Coordinates.geoTo3dDouble(target.get_lat(), target.get_lng()); + var dist; + if (defaultPlace != null) { + var testPoint = Coordinates.raDecTo3dAu(defaultPlace.get_RA(), -defaultPlace.get_dec(), -1); + dist = Vector3d.subtractVectors(searchPoint, testPoint); + distance = dist.length(); + } + var closestItem = -1; + var index = 0; + var $enum1 = ss.enumerate(this.positions); + while ($enum1.moveNext()) { + var point = $enum1.current; + dist = Vector3d.subtractVectors(searchPoint, point); + if (dist.length() < distance) { + distance = dist.length(); + closestItem = index; + } + index++; + } + if (closestItem === -1) { + return defaultPlace; + } + var pnt = Coordinates.cartesianToSpherical2(this.positions[closestItem]); + var name = this._table$1.rows[closestItem].columnData[this.nameColumn].toString(); + if (this.nameColumn === this.startDateColumn || this.nameColumn === this.endDateColumn) { + name = SpreadSheetLayer.parseDate(name).toString(); + } + if (ss.emptyString(name)) { + name = ss.format('RA={0}, Dec={1}', Coordinates.formatHMS(pnt.get_RA()), Coordinates.formatDMS(pnt.get_dec())); + } + var place = Place.create(name, pnt.get_lat(), pnt.get_RA(), 268435456, '', 2, -1); + var rowData = {}; + for (var i = 0; i < ss.keyCount(this._table$1.columns); i++) { + var colValue = this._table$1.rows[closestItem].get_item(i).toString(); + if (i === this.startDateColumn || i === this.endDateColumn) { + colValue = SpreadSheetLayer.parseDate(colValue).toString(); + } + if (!ss.keyExists(rowData, this._table$1.column[i].name) && !ss.emptyString(this._table$1.column[i].name)) { + rowData[this._table$1.column[i].name] = colValue; + } + else { + rowData['Column' + i.toString()] = colValue; + } + } + place.set_tag(rowData); + return place; + }, + + prepVertexBuffer: function (renderContext, opacity) { + var col = this._table$1.getColumnByUcd('meta.id'); + if (col == null) { + col = this._table$1.column[0]; + } + var siapSet = this.isSiapResultSet(); + if (this.pointList == null) { + this.pointList = new PointList(renderContext); + } + if (this.lineList2d == null) { + this.lineList2d = new LineList(); + } + this.lineList2d.clear(); + var stcsCol = this._table$1.getColumnByUcd('phys.area;obs.field'); + if (stcsCol == null && ss.keyExists(this._table$1.columns, 'regionSTCS')) { + stcsCol = this._table$1.columns['regionSTCS']; + } + if (!this.get_plotType()) { + this.set_markerScale(1); + } else { + this.set_markerScale(0); + } + var vertList = []; + var indexList = []; + var lastItem = new TimeSeriesPointVertex(); + this.positions.length = 0; + var currentIndex = 0; + var color = Color.fromArgb(ss.truncate((opacity * this.get_color().a)), this.get_color().r, this.get_color().g, this.get_color().b); + this.pointScaleType = 4; + var $enum1 = ss.enumerate(this._table$1.rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + try { + if (this.lngColumn > -1 && this.latColumn > -1) { + var ra = parseFloat(row.get_item(this.get_lngColumn()).toString()); + var dec = parseFloat(row.get_item(this.get_latColumn()).toString()); + var position = Coordinates.geoTo3dDouble(dec, ra); + lastItem.position = position; + this.positions.push(lastItem.position); + lastItem.set_color(color); + if (this.sizeColumn > -1) { + try { + if (!this.get_markerScale()) { + lastItem.pointSize = 20; + } + else { + switch (this.pointScaleType) { + case 0: + lastItem.pointSize = parseFloat(row.get_item(this.sizeColumn).toString()); + break; + case 2: + lastItem.pointSize = Math.log(parseFloat(row.get_item(this.sizeColumn).toString())); + break; + case 1: + lastItem.pointSize = Math.pow(2, parseFloat(row.get_item(this.sizeColumn).toString())); + break; + case 4: + var size = parseFloat(row.get_item(this.sizeColumn).toString()); + lastItem.pointSize = (40 / Math.pow(1.6, size)) * 10; + break; + case 3: + lastItem.pointSize = 1; + break; + default: + break; + } + } + } + catch ($e2) { + lastItem.pointSize = 0.01; + } + } + else { + if (!this.get_markerScale()) { + lastItem.pointSize = 20; + } + else { + lastItem.pointSize = Math.pow(2, 1) * 100; + } + } + if (this.startDateColumn > -1) { + var dateTime = ss.date(row.get_item(this.startDateColumn).toString()); + lastItem.tu = SpaceTimeController.utcToJulian(dateTime); + lastItem.tv = 0; + } + vertList.push(lastItem); + this.pointList.addPoint(lastItem.position, lastItem.color, new Dates(lastItem.tu, lastItem.tv), lastItem.pointSize); + currentIndex++; + } + if (siapSet && stcsCol != null) { + this._addSiapStcRow$1(stcsCol.name, row, row === this._table$1.selectedRow); + } + } + catch ($e3) { + } + this.lines = false; + } + if (siapSet && stcsCol != null) { + this._addSiapStcRow$1(stcsCol.name, this._table$1.selectedRow, true); + } + return true; + }, + _addSiapStcRow$1: function (stcsColName, row, selected) { + var stcs = ss.replaceString(row.getColumnData(stcsColName).toString(), ' ', ' '); + var col = Color.fromArgb(120, 255, 255, 255); + if (selected) { + col = Colors.get_yellow(); + } + if (ss.startsWith(stcs, 'Polygon J2000')) { + var parts = stcs.split(' '); + var len = parts.length; + var index = 0; + while (index < len) { + if (parts[index] === 'Polygon') { + index += 2; + var lastPoint = new Vector3d(); + var firstPoint = new Vector3d(); + var start = true; + for (var i = index; i < len; i += 2) { + if (parts[i] === 'Polygon') { + start = true; + break; + } + else { + var Xcoord = Coordinates.parseRA(parts[i], true) * 15 + 180; + var Ycoord = Coordinates.parseDec(parts[i + 1]); + var pnt = Coordinates.geoTo3dDouble(Ycoord, Xcoord); + if (!start) { + this.lineList2d.addLine(lastPoint, pnt, col, new Dates(0, 0)); + } + else { + firstPoint = pnt; + start = false; + } + lastPoint = pnt; + } + index += 2; + } + if (len > 4) { + this.lineList2d.addLine(firstPoint, lastPoint, col, new Dates(0, 0)); + } + } + } + } + }, + + isSiapResultSet: function () { + return this._table$1.getColumnByUcd('vox:image.title') != null && this._table$1.getColumnByUcd('VOX:Image.AccessReference') != null; + }, + + get_header: function () { + var header = new Array(ss.keyCount(this._table$1.columns)); + var index = 0; + var $enum1 = ss.enumerate(this._table$1.column); + while ($enum1.moveNext()) { + var col = $enum1.current; + header[index++] = col.name; + } + return header; + }, + + get_table: function () { + return this._table$1; + }, + + set_table: function (value) { + this._table$1 = value; + return value; + } +}; + +registerType("VoTableLayer", [VoTableLayer, VoTableLayer$, Layer]); diff --git a/engine/esm/layers/wcs_image.js b/engine/esm/layers/wcs_image.js new file mode 100644 index 00000000..64a94f43 --- /dev/null +++ b/engine/esm/layers/wcs_image.js @@ -0,0 +1,261 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Information about an image with a World Coordinate System registration. + +import { registerType } from "../typesystem.js"; + + +// wwtlib.WcsImage + +export function WcsImage() { + this.copyright = ''; + this.creditsUrl = ''; + this._validWcs = false; + this.keywords = []; + this.description = ''; + this.scaleX = 0; + this.scaleY = 0; + this.centerX = 0; + this.centerY = 0; + this.rotation = 0; + this.referenceX = 0; + this.referenceY = 0; + this.sizeX = 0; + this.sizeY = 0; + this.cd1_1 = 0; + this.cd1_2 = 0; + this.cd2_1 = 0; + this.cd2_2 = 0; + this.hasRotation = false; + this.hasSize = false; + this.hasScale = false; + this.hasLocation = false; + this.hasPixel = false; + this.filename = ''; + this._colorCombine = false; +} + +var WcsImage$ = { + get_copyright: function () { + return this.copyright; + }, + + set_copyright: function (value) { + this.copyright = value; + return value; + }, + + get_creditsUrl: function () { + return this.creditsUrl; + }, + + set_creditsUrl: function (value) { + this.creditsUrl = value; + return value; + }, + + get_validWcs: function () { + return this._validWcs; + }, + + set_validWcs: function (value) { + this._validWcs = value; + return value; + }, + + get_keywords: function () { + if (!this.keywords.length) { + this.keywords.push('Image File'); + } + return this.keywords; + }, + + set_keywords: function (value) { + this.keywords = value; + return value; + }, + + get_description: function () { + return this.description; + }, + + set_description: function (value) { + this.description = value; + return value; + }, + + get_scaleX: function () { + return this.scaleX; + }, + + set_scaleX: function (value) { + this.scaleX = value; + return value; + }, + + get_scaleY: function () { + return this.scaleY; + }, + + set_scaleY: function (value) { + this.scaleY = value; + return value; + }, + + get_centerX: function () { + return this.centerX; + }, + + set_centerX: function (value) { + this.centerX = value; + return value; + }, + + get_viewCenterX: function () { + return this.centerX + (this.get_sizeX() / 2 - this.get_referenceX()) * this.get_scaleX(); + }, + + get_centerY: function () { + return this.centerY; + }, + + set_centerY: function (value) { + this.centerY = value; + return value; + }, + + get_viewCenterY: function () { + return this.centerY + (this.get_sizeY() / 2 - this.get_referenceY()) * this.get_scaleY(); + }, + + get_rotation: function () { + return this.rotation; + }, + + set_rotation: function (value) { + this.rotation = value; + return value; + }, + + get_referenceX: function () { + return this.referenceX; + }, + + set_referenceX: function (value) { + this.referenceX = value; + return value; + }, + + get_referenceY: function () { + return this.referenceY; + }, + + set_referenceY: function (value) { + this.referenceY = value; + return value; + }, + + get_sizeX: function () { + return this.sizeX; + }, + + set_sizeX: function (value) { + this.sizeX = value; + return value; + }, + + get_sizeY: function () { + return this.sizeY; + }, + + set_sizeY: function (value) { + this.sizeY = value; + return value; + }, + + get_cd1_1: function () { + return this.cd1_1; + }, + + set_cd1_1: function (value) { + this.cd1_1 = value; + return value; + }, + + get_cd1_2: function () { + return this.cd1_2; + }, + + set_cd1_2: function (value) { + this.cd1_2 = value; + return value; + }, + + get_cd2_1: function () { + return this.cd2_1; + }, + + set_cd2_1: function (value) { + this.cd2_1 = value; + return value; + }, + + get_cd2_2: function () { + return this.cd2_2; + }, + + set_cd2_2: function (value) { + this.cd2_2 = value; + return value; + }, + + adjustScale: function (width, height) { + //adjusts the actual height vs the reported height. + if (width !== this.sizeX) { + this.scaleX *= (this.sizeX / width); + this.referenceX /= (this.sizeX / width); + this.sizeX = width; + } + if (height !== this.sizeY) { + this.scaleY *= (this.sizeY / height); + this.referenceY /= (this.sizeY / height); + this.sizeY = height; + } + }, + + calculateScaleFromCD: function () { + this.scaleX = (Math.sqrt(this.cd1_1 * this.cd1_1 + this.cd2_1 * this.cd2_1) * (this.cd1_1 * this.cd2_2 - this.cd1_2 * this.cd2_1) < 0) ? -1 : 1; + this.scaleY = Math.sqrt(this.cd1_2 * this.cd1_2 + this.cd2_2 * this.cd2_2); + }, + + calculateRotationFromCD: function () { + var sign = ((this.cd1_1 * this.cd2_2 - this.cd1_2 * this.cd2_1) < 0) ? -1 : 1; + var rot2 = Math.atan2((-sign * this.cd1_2), this.cd2_2); + this.rotation = rot2 / Math.PI * 180; + }, + + get_filename: function () { + return this.filename; + }, + + set_filename: function (value) { + this.filename = value; + return value; + }, + + get_colorCombine: function () { + return this._colorCombine; + }, + + set_colorCombine: function (value) { + this._colorCombine = value; + return value; + }, + + getBitmap: function () { + return null; + } +}; + +registerType("WcsImage", [WcsImage, WcsImage$, null]); diff --git a/engine/esm/mercator_tile.js b/engine/esm/mercator_tile.js new file mode 100644 index 00000000..20748d8e --- /dev/null +++ b/engine/esm/mercator_tile.js @@ -0,0 +1,404 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses a Mercator projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { tilePrepDevice, tileUvMultiple } from "./render_globals.js"; +import { Vector2d, Vector3d, PositionTexture } from "./double3d.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Tile } from "./tile.js"; + + +// wwtlib.MercatorTile + +export function MercatorTile() { + this._tileDegrees$1 = 0; + this._latMin$1 = 0; + this._latMax$1 = 0; + this._lngMin$1 = 0; + this._lngMax$1 = 0; + this._subDivisionLevel$1 = 32; + Tile.call(this); +} + +MercatorTile.create = function (level, X, Y, dataset, parent) { + var temp = new MercatorTile(); + temp.parent = parent; + temp.level = level; + temp.tileX = X; + temp.tileY = Y; + temp.dataset = dataset; + temp.computeBoundingSphere(); + return temp; +}; + +MercatorTile.getCentrePointOffsetAsTileRatio = function (lat, lon, zoom) { + var metersX = MercatorTile.absoluteLonToMetersAtZoom(lon, zoom); + var relativeXIntoCell = (metersX / 256) - Math.floor(metersX / 256); + var metersY = MercatorTile.absoluteLatToMetersAtZoom(lat, zoom); + var relativeYIntoCell = (metersY / 256) - Math.floor(metersY / 256); + return Vector2d.create(relativeXIntoCell, relativeYIntoCell); +}; + +MercatorTile.relativeMetersToLatAtZoom = function (Y, zoom) { + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + var metersY = Y * metersPerPixel; + return MercatorTile._radToDeg$1(Math.PI / 2 - 2 * Math.atan(Math.exp(0 - metersY / 6378137))); +}; + +MercatorTile.relativeMetersToLonAtZoom = function (X, zoom) { + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + var metersX = X * metersPerPixel; + return MercatorTile._radToDeg$1(metersX / 6378137); +}; + +MercatorTile.absoluteLatToMetersAtZoom = function (latitude, zoom) { + var sinLat = Math.sin(MercatorTile._degToRad$1(latitude)); + var metersY = 6378137 / 2 * Math.log((1 + sinLat) / (1 - sinLat)); + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + return ss.truncate((Math.round(20037508 - metersY) / metersPerPixel)); +}; + +MercatorTile.absoluteMetersToLatAtZoom = function (Y, zoom) { + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + var metersY = 20037508 - Y * metersPerPixel; + return MercatorTile._radToDeg$1(Math.PI / 2 - 2 * Math.atan(Math.exp(0 - metersY / 6378137))); +}; + +MercatorTile.absoluteLonToMetersAtZoom = function (longitude, zoom) { + var metersX = 6378137 * MercatorTile._degToRad$1(longitude); + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + return ss.truncate(((metersX + 20037508) / metersPerPixel)); +}; + +MercatorTile.absoluteMetersToLonAtZoom = function (X, zoom) { + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + var metersX = X * metersPerPixel - 20037508; + return MercatorTile._radToDeg$1(metersX / 6378137); +}; + +MercatorTile.absoluteLonToMetersAtZoomTile = function (longitude, zoom, tileX) { + var metersX = 6378137 * MercatorTile._degToRad$1(longitude); + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + return ss.truncate(((metersX + 20037508) / metersPerPixel)); +}; + +MercatorTile.absoluteLatToMetersAtZoomTile = function (latitude, zoom, tileX) { + var sinLat = Math.sin(MercatorTile._degToRad$1(latitude)); + var metersY = 6378137 / 2 * Math.log((1 + sinLat) / (1 - sinLat)); + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + return ss.truncate((Math.round(20037508 - metersY) / metersPerPixel)); +}; + +MercatorTile.absoluteMetersToLonAtZoomByTileY = function (X, zoom, tileY) { + var metersPerPixel = MercatorTile.metersPerPixel2(zoom); + var metersX = X * metersPerPixel - 20037508; + return MercatorTile._radToDeg$1(metersX / 6378137); +}; + +MercatorTile._degToRad$1 = function (deg) { + return (deg * Math.PI / 180); +}; + +MercatorTile.metersPerPixel2 = function (zoom) { + return (156543 / (1 << zoom)); +}; + +MercatorTile._radToDeg$1 = function (rad) { + return (rad * 180 / Math.PI); +}; + +var MercatorTile$ = { + computeBoundingSphere: function () { + this._tileDegrees$1 = 360 / Math.pow(2, this.level); + this._latMin$1 = MercatorTile.absoluteMetersToLatAtZoom(this.tileY * 256, this.level); + this._latMax$1 = MercatorTile.absoluteMetersToLatAtZoom((this.tileY + 1) * 256, this.level); + this._lngMin$1 = ((this.tileX * this._tileDegrees$1) - 180); + this._lngMax$1 = ((((this.tileX + 1)) * this._tileDegrees$1) - 180); + var latCenter = (this._latMin$1 + this._latMax$1) / 2; + var lngCenter = (this._lngMin$1 + this._lngMax$1) / 2; + this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); + this.topLeft = this.geoTo3d(this._latMin$1, this._lngMin$1, false); + this.bottomRight = this.geoTo3d(this._latMax$1, this._lngMax$1, false); + this.topRight = this.geoTo3d(this._latMin$1, this._lngMax$1, false); + this.bottomLeft = this.geoTo3d(this._latMax$1, this._lngMin$1, false); + if (!this.tileY) { + this.topLeft = Vector3d.create(0, 1, 0); + this.topRight = Vector3d.create(0, 1, 0); + } + if (this.tileY === Math.pow(2, this.level) - 1) { + this.bottomRight = Vector3d.create(0, -1, 0); + this.bottomLeft = Vector3d.create(0, -1, 0); + } + var distVect = this.topLeft; + distVect.subtract(this.sphereCenter); + this.sphereRadius = distVect.length(); + distVect = this.bottomRight; + distVect.subtract(this.sphereCenter); + var len = distVect.length(); + if (this.sphereRadius < len) { + this.sphereRadius = len; + } + this._tileDegrees$1 = Math.abs(this._latMax$1 - this._latMin$1); + }, + + isPointInTile: function (lat, lng) { + if (!this.demReady || this.demData == null || lat < Math.min(this._latMin$1, this._latMax$1) || lat > Math.max(this._latMax$1, this._latMin$1) || lng < Math.min(this._lngMin$1, this._lngMax$1) || lng > Math.max(this._lngMin$1, this._lngMax$1)) { + return false; + } + return true; + }, + + getSurfacePointAltitude: function (lat, lng, meters) { + if (this.level < Tile.lastDeepestLevel) { + var $enum1 = ss.enumerate(this.children); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child != null) { + if (child.isPointInTile(lat, lng)) { + var retVal = child.getSurfacePointAltitude(lat, lng, meters); + if (!!retVal) { + return retVal; + } + else { + break; + } + } + } + } + } + var alt = this._getAltitudeAtLatLng$1(lat, lng, (meters) ? 1 : this.get__demScaleFactor()); + return alt; + }, + + _getAltitudeAtLatLng$1: function (lat, lng, scaleFactor) { + var height = Math.abs(this._latMax$1 - this._latMin$1); + var width = Math.abs(this._lngMax$1 - this._lngMin$1); + var yy = ((lat - Math.min(this._latMax$1, this._latMin$1)) / height * 32); + var xx = ((lng - Math.min(this._lngMax$1, this._lngMin$1)) / width * 32); + var indexY = Math.min(31, ss.truncate(yy)); + var indexX = Math.min(31, ss.truncate(xx)); + var ha = xx - indexX; + var va = yy - indexY; + var ul = this.demData[indexY * 33 + indexX]; + var ur = this.demData[indexY * 33 + (indexX + 1)]; + var ll = this.demData[(indexY + 1) * 33 + indexX]; + var lr = this.demData[(indexY + 1) * 33 + (indexX + 1)]; + var top = ul * (1 - ha) + ha * ur; + var bottom = ll * (1 - ha) + ha * lr; + var val = top * (1 - va) + va * bottom; + return val / scaleFactor; + }, + + createGeometry: function (renderContext) { + Tile.prototype.createGeometry.call(this, renderContext); + if (this.geometryCreated) { + return true; + } + this.geometryCreated = true; + if (tileUvMultiple == 256) { + if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { + this._subDivisionLevel$1 = Math.max(2, (6 - this.level) * 2); + } + } + for (var i = 0; i < 4; i++) { + this._renderTriangleLists[i] = []; + } + var lat, lng; + var index = 0; + var tileDegrees = 360 / Math.pow(2, this.level); + this._latMin$1 = MercatorTile.absoluteMetersToLatAtZoom(this.tileY * 256, this.level); + this._latMax$1 = MercatorTile.absoluteMetersToLatAtZoom((this.tileY + 1) * 256, this.level); + this._lngMin$1 = ((this.tileX * tileDegrees) - 180); + this._lngMax$1 = ((((this.tileX + 1)) * tileDegrees) - 180); + var latCenter = MercatorTile.absoluteMetersToLatAtZoom(((this.tileY * 2) + 1) * 256, this.level + 1); + this.topLeft = this.geoTo3d(this._latMin$1, this._lngMin$1, false); + this.bottomRight = this.geoTo3d(this._latMax$1, this._lngMax$1, false); + this.topRight = this.geoTo3d(this._latMin$1, this._lngMax$1, false); + this.bottomLeft = this.geoTo3d(this._latMax$1, this._lngMin$1, false); + var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); + tileDegrees = this._lngMax$1 - this._lngMin$1; + var dGrid = (tileDegrees / this._subDivisionLevel$1); + var x1, y1; + var textureStep = 1 / this._subDivisionLevel$1; + var latDegrees = this._latMax$1 - latCenter; + for (y1 = 0; y1 < this._subDivisionLevel$1 / 2; y1++) { + if (y1 !== this._subDivisionLevel$1 / 2) { + lat = this._latMax$1 - (2 * textureStep * latDegrees * y1); + } + else { + lat = latCenter; + } + for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { + if (x1 !== this._subDivisionLevel$1) { + lng = this._lngMin$1 + (textureStep * tileDegrees * x1); + } + else { + lng = this._lngMax$1; + } + index = y1 * (this._subDivisionLevel$1 + 1) + x1; + verts[index] = new PositionTexture(); + verts[index].position = this.geoTo3dWithAlt(lat, lng, false, true); + verts[index].tu = (x1 * textureStep) * tileUvMultiple; + verts[index].tv = ((MercatorTile.absoluteLatToMetersAtZoom(lat, this.level) - (this.tileY * 256)) / 256) * tileUvMultiple; + this.demIndex++; + } + } + latDegrees = this._latMin$1 - latCenter; + for (y1 = this._subDivisionLevel$1 / 2; y1 <= this._subDivisionLevel$1; y1++) { + if (y1 !== this._subDivisionLevel$1) { + lat = latCenter + (2 * textureStep * latDegrees * (y1 - (this._subDivisionLevel$1 / 2))); + } + else { + lat = this._latMin$1; + } + for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { + if (x1 !== this._subDivisionLevel$1) { + lng = this._lngMin$1 + (textureStep * tileDegrees * x1); + } + else { + lng = this._lngMax$1; + } + index = y1 * (this._subDivisionLevel$1 + 1) + x1; + verts[index] = new PositionTexture(); + verts[index].position = this.geoTo3dWithAlt(lat, lng, false, true); + verts[index].tu = (x1 * textureStep) * tileUvMultiple; + verts[index].tv = ((MercatorTile.absoluteLatToMetersAtZoom(lat, this.level) - (this.tileY * 256)) / 256) * tileUvMultiple; + this.demIndex++; + } + } + if (!this.tileY) { + // Send the tops to the pole to fill in the Bing Hole + y1 = this._subDivisionLevel$1; + for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { + index = y1 * (this._subDivisionLevel$1 + 1) + x1; + verts[index].position = Vector3d.create(0, 1, 0); + } + } + if (this.tileY === Math.pow(2, this.level) - 1) { + // Send the tops to the pole to fill in the Bing Hole + y1 = 0; + for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { + index = y1 * (this._subDivisionLevel$1 + 1) + x1; + verts[index].position = Vector3d.create(0, -1, 0); + } + } + this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; + var quarterDivisions = this._subDivisionLevel$1 / 2; + var part = 0; + if (renderContext.gl == null) { + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + index = 0; + for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + var p1; + var p2; + var p3; + + // First triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + var tri = RenderTriangle.create(p1, p2, p3, this.texture, this.level); + this._renderTriangleLists[part].push(tri); + + // Second triangle in quad + p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; + p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; + tri = RenderTriangle.create(p1, p2, p3, this.texture, this.level); + this._renderTriangleLists[part].push(tri); + } + } + part++; + } + } + } else { + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(verts.length * 5); + var buffer = f32array; + index = 0; + var $enum1 = ss.enumerate(verts); + while ($enum1.moveNext()) { + var pt = $enum1.current; + index = this.addVertex(buffer, index, pt); + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + for (var y2 = 0; y2 < 2; y2++) { + for (var x2 = 0; x2 < 2; x2++) { + var ui16array = new Uint16Array(this.triangleCount * 3); + var indexArray = ui16array; + index = 0; + for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { + for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { + // First triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + + // Second triangle in quad + indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); + indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); + } + } + this._indexBuffers[part] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this._indexBuffers[part]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, ui16array, WEBGL.STATIC_DRAW); + part++; + } + } + } + return true; + }, + + _getDemSample$1: function (x, y) { + return this.demData[(32 - y) * 33 + x]; + }, + + createDemFromParent: function () { + var parent = ss.safeCast(this.parent, MercatorTile); + if (parent == null || parent.demData == null) { + return false; + } + var offsetX = (((this.tileX % 2) === 1) ? 16 : 0); + var offsetY = (((this.tileY % 2) === 1) ? 16 : 0); + this.demData = new Array(this.demSize); + + // Interpolate across + for (var y = 0; y < 33; y += 2) { + var copy = true; + for (var x = 0; x < 33; x++) { + if (copy) { + this.demData[(32 - y) * 33 + x] = parent._getDemSample$1((x / 2) + offsetX, (y / 2) + offsetY); + } + else { + this.demData[(32 - y) * 33 + x] = ((parent._getDemSample$1((x / 2) + offsetX, (y / 2) + offsetY) + parent._getDemSample$1(((x / 2) + offsetX) + 1, (y / 2) + offsetY)) / 2); + } + copy = !copy; + } + } + + // Interpolate down + for (var y = 1; y < 33; y += 2) { + for (var x = 0; x < 33; x++) { + this.demData[(32 - y) * 33 + x] = ((this._getDemSample$1(x, y - 1) + this._getDemSample$1(x, y + 1)) / 2); + } + } + var $enum1 = ss.enumerate(this.demData); + while ($enum1.moveNext()) { + var sample = $enum1.current; + this.demAverage += sample; + } + this.demAverage /= this.demData.length; + this.demReady = true; + return true; + } +}; + +registerType("MercatorTile", [MercatorTile, MercatorTile$, Tile]); diff --git a/engine/esm/minor_planets.js b/engine/esm/minor_planets.js new file mode 100644 index 00000000..135d36ad --- /dev/null +++ b/engine/esm/minor_planets.js @@ -0,0 +1,162 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Rendering the minor planet database + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d, Matrix3d } from "./double3d.js"; +import { EOE } from "./astrocalc/elliptical.js"; +import { Texture } from "./graphics/texture.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { KeplerVertexBuffer } from "./graphics/gl_buffers.js" +import { KeplerPointSpriteShader } from "./graphics/shaders.js"; +import { BlendState } from "./blend_state.js"; +import { Colors } from "./color.js"; +import { freestandingMode } from "./data_globals.js"; +import { KeplerVertex } from "./kepler_vertex.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { URLHelpers } from "./url_helpers.js"; +import { BinaryReader } from "./utilities/binary_reader.js"; +import { WebFile } from "./web_file.js"; + + +// wwtlib.MinorPlanets + +export function MinorPlanets() { } + +MinorPlanets.mpcList = []; +MinorPlanets._initBegun = false; +MinorPlanets._mpcBlendStates = new Array(7); +MinorPlanets.starTexture = null; +MinorPlanets._mpcVertexBuffer = null; +MinorPlanets._mpcCount = 0; + +MinorPlanets.getMpcFile = function (url) { + MinorPlanets._webMpcFile = new WebFile(url); + MinorPlanets._webMpcFile.responseType = 'blob'; + MinorPlanets._webMpcFile.onStateChange = MinorPlanets.starFileStateChange; + MinorPlanets._webMpcFile.send(); +}; + +MinorPlanets.starFileStateChange = function () { + if (MinorPlanets._webMpcFile.get_state() === 2) { + alert(MinorPlanets._webMpcFile.get_message()); + } + else if (MinorPlanets._webMpcFile.get_state() === 1) { + var mainBlob = MinorPlanets._webMpcFile.getBlob(); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + MinorPlanets._readFromBin(new BinaryReader(new Uint8Array(chunck.result))); + MinorPlanets.initMPCVertexBuffer(); + }; + chunck.readAsArrayBuffer(mainBlob); + } +}; + +MinorPlanets._readFromBin = function (br) { + MinorPlanets.mpcList = []; + var len = br.get_length(); + var ee; + try { + while (br.get_position() < len) { + ee = EOE._create(br); + MinorPlanets.mpcList.push(ee); + } + } + catch ($e1) { } + br.close(); +}; + +MinorPlanets.drawMPC3D = function (renderContext, opacity, centerPoint) { + var zoom = renderContext.viewCamera.zoom; + var distAlpha = ((Math.log(Math.max(1, zoom)) / Math.log(4)) - 15.5) * 90; + var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); + if (alpha > 254) { + return; + } + if (MinorPlanets._mpcVertexBuffer == null) { + if (MinorPlanets.starTexture == null) { + MinorPlanets.starTexture = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png')); + } + for (var i = 0; i < 7; i++) { + MinorPlanets._mpcBlendStates[i] = BlendState.create(false, 1000); + } + if (!MinorPlanets._initBegun) { + MinorPlanets._startInit(); + MinorPlanets._initBegun = true; + } + return; + } + var offset = Matrix3d.translation(Vector3d.negate(centerPoint)); + var world = Matrix3d.multiplyMatrix(renderContext.get_world(), offset); + var matrixWV = Matrix3d.multiplyMatrix(world, renderContext.get_view()); + var cam = Vector3d._transformCoordinate(renderContext.cameraPosition, Matrix3d.invertMatrix(renderContext.get_world())); + if (MinorPlanets._mpcVertexBuffer != null) { + for (var i = 0; i < 7; i++) { + MinorPlanets._mpcBlendStates[i].set_targetState(true); + if (MinorPlanets._mpcBlendStates[i].get_state()) { + KeplerPointSpriteShader.use(renderContext, matrixWV, MinorPlanets._mpcVertexBuffer[i].vertexBuffer, MinorPlanets.starTexture.texture2d, Colors.get_white(), opacity * MinorPlanets._mpcBlendStates[i].get_opacity(), false, (SpaceTimeController.get_jNow() - KeplerVertex.baseDate), 0, renderContext.cameraPosition, 200, 0.1); + renderContext.gl.drawArrays(WEBGL.POINTS, 0, MinorPlanets._mpcVertexBuffer[i].count); + } + } + } +}; + +MinorPlanets._startInit = function () { + if (!freestandingMode) { + MinorPlanets.getMpcFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=mpcbin')); + } +}; + +MinorPlanets.initMPCVertexBuffer = function () { + try { + if (MinorPlanets._mpcVertexBuffer == null) { + var mpcVertexBufferTemp = new Array(7); + MinorPlanets._mpcCount = MinorPlanets.mpcList.length; + var lists = new Array(7); + for (var i = 0; i < 7; i++) { + lists[i] = []; + } + var $enum1 = ss.enumerate(MinorPlanets.mpcList); + while ($enum1.moveNext()) { + var ee = $enum1.current; + var listID = 0; + if (ee.a < 2.5) { + listID = 0; + } + else if (ee.a < 2.83) { + listID = 1; + } + else if (ee.a < 2.96) { + listID = 2; + } + else if (ee.a < 3.3) { + listID = 3; + } + else if (ee.a < 5) { + listID = 4; + } + else if (ee.a < 10) { + listID = 5; + } + else { + listID = 6; + } + var vert = new KeplerVertex(); + vert.fill(ee); + lists[listID].push(vert); + } + for (var i = 0; i < 7; i++) { + mpcVertexBufferTemp[i] = KeplerVertexBuffer.create(lists[i]); + mpcVertexBufferTemp[i].unlock(); + } + MinorPlanets._mpcVertexBuffer = mpcVertexBufferTemp; + } + } + finally { } +}; + +var MinorPlanets$ = {}; + +registerType("MinorPlanets", [MinorPlanets, MinorPlanets$, null]); diff --git a/engine/esm/place.js b/engine/esm/place.js new file mode 100644 index 00000000..59e3fe0a --- /dev/null +++ b/engine/esm/place.js @@ -0,0 +1,538 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A place to look at, potentially with associated imagesets. + +import { ss } from "./ss.js"; +import { registerType, registerEnum, Enums } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { freestandingMode, set_createPlace } from "./data_globals.js"; +import { Util } from "./baseutil.js"; +import { CameraParameters } from "./camera_parameters.js"; +import { IPlace, IThumbnail } from "./interfaces.js"; +import { UiTools } from "./ui_tools.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Coordinates } from "./coordinates.js"; +import { Imageset } from "./imageset.js"; +import { Planets } from "./planets.js"; + + +// wwtlib.Classification +// +// This was defined in `IPlace.cs`, which we've folded into `interfaces.js`. + +export var Classification = { + star: 1, + supernova: 2, + blackHole: 4, + neutronStar: 8, + doubleStar: 16, + multipleStars: 32, + asterism: 64, + constellation: 128, + openCluster: 256, + globularCluster: 512, + nebulousCluster: 1024, + nebula: 2048, + emissionNebula: 4096, + planetaryNebula: 8192, + reflectionNebula: 16384, + darkNebula: 32768, + giantMolecularCloud: 65536, + supernovaRemnant: 131072, + interstellarDust: 262144, + quasar: 524288, + galaxy: 1048576, + spiralGalaxy: 2097152, + irregularGalaxy: 4194304, + ellipticalGalaxy: 8388608, + knot: 16777216, + plateDefect: 33554432, + clusterOfGalaxies: 67108864, + otherNGC: 134217728, + unidentified: 268435456, + solarSystem: 536870912, + unfiltered: 1073741823, + stellar: 63, + stellarGroupings: 2032, + nebulae: 523264, + galactic: 133693440, + other: 436207616 +}; + +registerType("Classification", Classification); +registerEnum("Classification", Classification); + + +// wwtlib.Place + +export function Place() { + this._camParams = CameraParameters.create(0, 0, -1, 0, 0, 100); + this._location3d = Vector3d.create(0, 0, 0); + this.htmlDescription = ''; + this._constellation = ''; + this._classification = 1048576; + this._type = 2; + this._magnitude = 0; + this._distnace = 0; + this.angularSize = 60; // Angular size in arcseconds + this.annotation = ''; + this._thumbNail = null; + this._studyImageset = null; + this._backgroundImageSet = null; + this._searchDistance = 0; + this._elevation = 50; +} + +Place.create = function (name, lat, lng, classification, constellation, type, zoomFactor) { + var temp = new Place(); + temp.set_zoomLevel(zoomFactor); + temp._constellation = constellation; + temp._name = name; + if (type === 2 || type === 4) { + temp._camParams.set_RA(lng); + } + else { + temp.set_lng(lng); + } + temp.set_lat(lat); + temp.set_classification(classification); + temp.set_type(type); + return temp; +}; + +Place.createCameraParams = function (name, camParams, classification, constellation, type, target) { + var temp = new Place(); + temp._constellation = constellation; + temp._name = name; + temp.set_classification(classification); + temp._camParams = camParams; + temp.set_type(type); + temp.set_target(target); + return temp; +}; + +Place._fromXml = function (place) { + var newPlace = new Place(); + newPlace._name = place.attributes.getNamedItem('Name').nodeValue; + if (place.attributes.getNamedItem('MSRComponentId') != null && place.attributes.getNamedItem('Permission') != null && place.attributes.getNamedItem('Url') != null) { + //communities item + newPlace.set_url(place.attributes.getNamedItem('Url').nodeValue); + newPlace.set_thumbnailUrl(place.attributes.getNamedItem('Thumbnail').nodeValue); + return newPlace; + } + if (place.attributes.getNamedItem('DataSetType') != null) { + newPlace._type = Enums.parse('ImageSetType', place.attributes.getNamedItem('DataSetType').nodeValue); + } + if (newPlace.get_type() === 2) { + newPlace._camParams.set_RA(parseFloat(place.attributes.getNamedItem('RA').nodeValue)); + newPlace._camParams.set_dec(parseFloat(place.attributes.getNamedItem('Dec').nodeValue)); + } + else { + newPlace.set_lat(parseFloat(place.attributes.getNamedItem('Lat').nodeValue)); + newPlace.set_lng(parseFloat(place.attributes.getNamedItem('Lng').nodeValue)); + } + if (place.attributes.getNamedItem('Constellation') != null) { + newPlace._constellation = place.attributes.getNamedItem('Constellation').nodeValue; + } + if (place.attributes.getNamedItem('Classification') != null) { + newPlace._classification = Enums.parse('Classification', place.attributes.getNamedItem('Classification').nodeValue); + } + if (place.attributes.getNamedItem('Magnitude') != null) { + newPlace._magnitude = parseFloat(place.attributes.getNamedItem('Magnitude').nodeValue); + } + if (place.attributes.getNamedItem('AngularSize') != null) { + newPlace.angularSize = parseFloat(place.attributes.getNamedItem('AngularSize').nodeValue); + } + if (place.attributes.getNamedItem('ZoomLevel') != null) { + newPlace.set_zoomLevel(parseFloat(place.attributes.getNamedItem('ZoomLevel').nodeValue)); + } + if (place.attributes.getNamedItem('Rotation') != null) { + newPlace._camParams.rotation = parseFloat(place.attributes.getNamedItem('Rotation').nodeValue); + } + if (place.attributes.getNamedItem('Annotation') != null) { + newPlace.annotation = place.attributes.getNamedItem('Annotation').nodeValue; + } + if (place.attributes.getNamedItem('Angle') != null) { + newPlace._camParams.angle = parseFloat(place.attributes.getNamedItem('Angle').nodeValue); + } + if (place.attributes.getNamedItem('Opacity') != null) { + newPlace._camParams.opacity = parseFloat(place.attributes.getNamedItem('Opacity').nodeValue); + } + else { + newPlace._camParams.opacity = 100; + } + newPlace.set_target(65536); + if (place.attributes.getNamedItem('Target') != null) { + newPlace.set_target(Enums.parse('SolarSystemObjects', place.attributes.getNamedItem('Target').nodeValue)); + } + if (place.attributes.getNamedItem('ViewTarget') != null) { + newPlace._camParams.viewTarget = Vector3d.parse(place.attributes.getNamedItem('ViewTarget').nodeValue); + } + if (place.attributes.getNamedItem('TargetReferenceFrame') != null) { + newPlace._camParams.targetReferenceFrame = place.attributes.getNamedItem('TargetReferenceFrame').nodeValue; + } + var descriptionNode = Util.selectSingleNode(place, 'Description'); + if (descriptionNode != null) { + newPlace.htmlDescription = Util.getInnerText(descriptionNode); + } + var backgroundImageSet = Util.selectSingleNode(place, 'BackgroundImageSet'); + if (backgroundImageSet != null) { + var imageSet = Util.selectSingleNode(backgroundImageSet, 'ImageSet'); + newPlace._backgroundImageSet = Imageset.fromXMLNode(imageSet); + } + var study = Util.selectSingleNode(place, 'ForegroundImageSet'); + if (study != null) { + var imageSet = Util.selectSingleNode(study, 'ImageSet'); + newPlace._studyImageset = Imageset.fromXMLNode(imageSet); + } + study = Util.selectSingleNode(place, 'ImageSet'); + if (study != null) { + newPlace._studyImageset = Imageset.fromXMLNode(study); + } + return newPlace; +}; + +Place._properCaps = function (name) { + var list = name.split(' '); + var ProperName = ''; + var $enum1 = ss.enumerate(list); + while ($enum1.moveNext()) { + var part = $enum1.current; + ProperName = ProperName + part.substr(0, 1).toUpperCase() + ((part.length > 1) ? part.substr(1).toLowerCase() : '') + ' '; + } + return ss.trim(ProperName); +}; + +var Place$ = { + get_tag: function () { + return this._tag; + }, + + set_tag: function (value) { + this._tag = value; + return value; + }, + + get_url: function () { + return this._url; + }, + + set_url: function (value) { + this._url = value; + return value; + }, + + get_thumbnail: function () { + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + return value; + }, + + get_name: function () { + return this.get_names()[0]; + }, + + get_names: function () { + if (ss.emptyString(this._name)) { + return ''.split(';'); + } + return this._name.split(';'); + }, + + set_names: function (value) { + this._name = UiTools.getNamesStringFromArray(value); + return value; + }, + + get_camParams: function () { + if (this.get_classification() === 536870912 && this._camParams.target !== 20) { + var raDec = Planets.getPlanetLocation(this.get_name()); + this._camParams.set_RA(raDec.RA); + this._camParams.set_dec(raDec.dec); + this._distnace = raDec.distance; + } + return this._camParams; + }, + + set_camParams: function (value) { + this._camParams = value; + return value; + }, + + updatePlanetLocation: function (jNow) { + this._camParams.viewTarget = Planets.getPlanet3dLocationJD(this.get_target(), jNow); + if (this.get_target() !== 65536 && this.get_target() !== 20) { + this._camParams.viewTarget = Planets.getPlanetTargetPoint(this.get_target(), this.get_lat(), this.get_lng(), jNow); + } + }, + + get_location3d: function () { + if (this.get_classification() === 536870912 || (!this._location3d.x && !this._location3d.y && !this._location3d.z)) { + this._location3d = Coordinates.raDecTo3d(this.get_RA(), this.get_dec()); + } + return this._location3d; + }, + + get_lat: function () { + return this.get_camParams().lat; + }, + + set_lat: function (value) { + this._camParams.lat = value; + return value; + }, + + get_lng: function () { + return this.get_camParams().lng; + }, + + set_lng: function (value) { + this._camParams.lng = value; + return value; + }, + + get_opacity: function () { + return this.get_camParams().opacity; + }, + + set_opacity: function (value) { + this._camParams.opacity = value; + return value; + }, + + get_constellation: function () { + return this._constellation; + }, + + set_constellation: function (value) { + this._constellation = value; + return value; + }, + + get_classification: function () { + return this._classification; + }, + + set_classification: function (value) { + this._classification = value; + return value; + }, + + get_type: function () { + return this._type; + }, + + set_type: function (value) { + this._type = value; + return value; + }, + + get_magnitude: function () { + return this._magnitude; + }, + + set_magnitude: function (value) { + this._magnitude = value; + return value; + }, + + get_distance: function () { + return this._distnace; + }, + + set_distance: function (value) { + this._distnace = value; + return value; + }, + + get_zoomLevel: function () { + return this.get_camParams().zoom; + }, + + set_zoomLevel: function (value) { + this._camParams.zoom = value; + return value; + }, + + get_annotation: function () { + return this.annotation; + }, + + set_annotation: function (value) { + this.annotation = value; + return value; + }, + + get_studyImageset: function () { + return this._studyImageset; + }, + + set_studyImageset: function (value) { + this._studyImageset = value; + return value; + }, + + get_backgroundImageset: function () { + return this._backgroundImageSet; + }, + + set_backgroundImageset: function (value) { + if (value != null) { + this.set_type(value.get_dataSetType()); + } + this._backgroundImageSet = value; + return value; + }, + + get_searchDistance: function () { + return this._searchDistance; + }, + + set_searchDistance: function (value) { + this._searchDistance = value; + return value; + }, + + get_elevation: function () { + return this._elevation; + }, + + set_elevation: function (value) { + this._elevation = value; + return value; + }, + + get_thumbnailUrl: function () { + if (ss.emptyString(this._thumbnailField)) { + if (this._studyImageset != null && !ss.emptyString(this._studyImageset.get_thumbnailUrl())) { + return this._studyImageset.get_thumbnailUrl(); + } + if (this._backgroundImageSet != null && !ss.emptyString(this._backgroundImageSet.get_thumbnailUrl())) { + return this._backgroundImageSet.get_thumbnailUrl(); + } + var name = this.get_name(); + if (name.indexOf(';') > -1) { + name = name.substr(0, name.indexOf(';')); + } + if (this.get_classification() === 1 || freestandingMode) { + return URLHelpers.singleton.engineAssetUrl('thumb_star.jpg'); + } + return URLHelpers.singleton.coreStaticUrl('wwtweb/thumbnail.aspx?name=' + name.toLowerCase()); + } + return this._thumbnailField; + }, + + set_thumbnailUrl: function (value) { + this._thumbnailField = value; + return value; + }, + + get_RA: function () { + return this.get_camParams().get_RA(); + }, + + set_RA: function (value) { + this._camParams.set_RA(value); + return value; + }, + + get_dec: function () { + return this.get_camParams().get_dec(); + }, + + set_dec: function (value) { + this._camParams.set_dec(value); + return value; + }, + + toString: function () { + return this._name; + }, + + _saveToXml: function (xmlWriter, elementName) { + xmlWriter._writeStartElement(elementName); + xmlWriter._writeAttributeString('Name', this._name); + xmlWriter._writeAttributeString('DataSetType', Enums.toXml('ImageSetType', this._type)); + if (this.get_type() === 2) { + xmlWriter._writeAttributeString('RA', this._camParams.get_RA().toString()); + xmlWriter._writeAttributeString('Dec', this._camParams.get_dec().toString()); + } else { + xmlWriter._writeAttributeString('Lat', this.get_lat().toString()); + xmlWriter._writeAttributeString('Lng', this.get_lng().toString()); + } + xmlWriter._writeAttributeString('Constellation', this._constellation); + xmlWriter._writeAttributeString('Classification', Enums.toXml('Classification', this._classification)); + xmlWriter._writeAttributeString('Magnitude', this._magnitude.toString()); + xmlWriter._writeAttributeString('Distance', this._distnace.toString()); + xmlWriter._writeAttributeString('AngularSize', this.angularSize.toString()); + xmlWriter._writeAttributeString('ZoomLevel', this.get_zoomLevel().toString()); + xmlWriter._writeAttributeString('Rotation', this._camParams.rotation.toString()); + xmlWriter._writeAttributeString('Angle', this._camParams.angle.toString()); + xmlWriter._writeAttributeString('Opacity', this._camParams.opacity.toString()); + xmlWriter._writeAttributeString('Target', Enums.toXml('SolarSystemObjects', this.get_target())); + xmlWriter._writeAttributeString('ViewTarget', this._camParams.viewTarget.toString()); + xmlWriter._writeAttributeString('TargetReferenceFrame', this._camParams.targetReferenceFrame); + xmlWriter._writeStartElement('Description'); + xmlWriter._writeCData(this.htmlDescription); + xmlWriter._writeEndElement(); + if (this._backgroundImageSet != null) { + xmlWriter._writeStartElement('BackgroundImageSet'); + Imageset.saveToXml(xmlWriter, this._backgroundImageSet, ''); + xmlWriter._writeEndElement(); + } + if (this._studyImageset != null) { + Imageset.saveToXml(xmlWriter, this._studyImageset, ''); + } + xmlWriter._writeEndElement(); + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_isImage: function () { + return this._studyImageset != null || this._backgroundImageSet != null; + }, + + get_isTour: function () { + return false; + }, + + get_isFolder: function () { + return false; + }, + + get_children: function () { + return []; + }, + + get_readOnly: function () { + return true; + }, + + get_target: function () { + return this._camParams.target; + }, + + set_target: function (value) { + this._camParams.target = value; + return value; + }, + + get_isCloudCommunityItem: function () { + return false; + } +}; + +registerType("Place", [Place, Place$, null, IThumbnail, IPlace]); + +set_createPlace(Place.create); diff --git a/engine/esm/planets.js b/engine/esm/planets.js new file mode 100644 index 00000000..099b08b2 --- /dev/null +++ b/engine/esm/planets.js @@ -0,0 +1,1033 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The main planet-related code. +// +// This does not include the 3D planet-rendering code, which has been separated +// into `planets_3d.js`. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d, Matrix3d, PositionColoredTextured } from "./double3d.js"; +import { CAAEarth } from "./astrocalc/earth.js"; +import { CAAMercury } from "./astrocalc/mercury.js"; +import { CAAVenus } from "./astrocalc/venus.js"; +import { CAAMars } from "./astrocalc/mars.js"; +import { CAAJupiter } from "./astrocalc/jupiter.js"; +import { CAASaturn } from "./astrocalc/saturn.js"; +import { CAAUranus } from "./astrocalc/uranus.js"; +import { CAANeptune } from "./astrocalc/neptune.js"; +import { CAAPluto } from "./astrocalc/pluto.js"; +import { GM } from "./astrocalc/galilean_moons.js"; +import { CAAMoon } from "./astrocalc/moon.js"; +import { AstroCalc } from "./astrocalc.js"; +import { Texture } from "./graphics/texture.js"; +import { Sprite2d } from "./graphics/sprite2d.js"; +import { BasePlanets } from "./baseplanets.js"; +import { SolarSystemObjects } from "./camera_parameters.js"; +import { Color, Colors } from "./color.js"; +import { Coordinates } from "./coordinates.js"; +import { Settings } from "./settings.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { URLHelpers } from "./url_helpers.js"; + + +// wwtlib.KeplerianElements +// +// Keplerian elements defined here use eccentric anomaly instead of mean anomaly +// and have all orbital plane angles converted to a rotation matrix. +export function KeplerianElements() { + this.a = 0; + this.e = 0; + this.ea = 0; +} + +var KeplerianElements$ = {}; + +registerType("KeplerianElements", [KeplerianElements, KeplerianElements$, null]); + + +// wwtlib.BodyAngles + +export function BodyAngles(poleRa, poleDec, primeMeridian, rotationRate) { + this.poleDec = 0; + this.poleRa = 0; + this.primeMeridian = 0; + this.rotationRate = 0; + this.poleDec = poleDec; + this.poleRa = poleRa; + this.primeMeridian = primeMeridian; + this.rotationRate = rotationRate; +} + +var BodyAngles$ = {}; + +registerType("BodyAngles", [BodyAngles, BodyAngles$, null]); + + +// wwtlib.Planets + +export function Planets() { } + +Planets.RC = (Math.PI / 180); +Planets._jNow = 0; + +// Values taken from version 10 of the SPICE planetary constants file, updated +// October 21, 2011: ftp://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00010.tpc +// +// Precession rates for rotation angles are currently not stored. +// +// All angles are in degrees. +Planets._planetAngles = [ + new BodyAngles(286.13, 63.87, 84.176, 14.1844), + new BodyAngles(281.0097, 61.4143, 329.548, 6.1385025), + new BodyAngles(272.76, 67.16, 160.2, -1.4813688), + new BodyAngles(317.68143, 52.8865, 176.63, 350.89198226), + new BodyAngles(268.056595, 64.495303, 284.95, 870.536), + new BodyAngles(40.589, 83.537, 38.9, 810.7939024), + new BodyAngles(257.311, -15.175, 203.81, 501.1600928), + new BodyAngles(299.36, 43.46, 253.18, 536.3128492), + new BodyAngles(132.993, -6.163, 302.695, 56.3625225), + new BodyAngles(269.9949, 66.5392, 38.3213, 13.17635815), + new BodyAngles(268.05, 64.5, 200.39, 203.4889538), + new BodyAngles(268.08, 64.51, 36.022, 101.3747235), + new BodyAngles(268.2, 64.57, 44.064, 50.3176081), + new BodyAngles(268.72, 64.83, 259.51, 21.5710715), + new BodyAngles(0, 0, 0, 0), + new BodyAngles(0, 0, 0, 0), + new BodyAngles(0, 0, 0, 0), + new BodyAngles(0, 0, 0, 0), + new BodyAngles(0, 0, 0, 0), + new BodyAngles(0, 90, 190.147, 360.9856235) +]; +Planets._lastPlanetCenterID = -2; +Planets._orbitalSampleRate = 256; +Planets._obliquity = 23.5 * Planets.RC; +Planets._drawOrder = {}; +Planets.earthMatrix = new Matrix3d(); +Planets.earthMatrixInv = new Matrix3d(); +Planets._lastUpdate = new Date(); +Planets._planetSprite = new Sprite2d(); +Planets._planetPoints = null; +Planets._planet3dLocations = null; + +// This function is equivalent to `Texture.from_url` and not specific to the +// Planets infrastructure at all. It should go away. But at the moment, we +// preserve it so as not to break API. +Planets.loadPlanetTexture = function (url) { + var texture = new Texture(); + texture.load(url); + return texture; +}; + +Planets.getPlanet3dLocation = function (target) { + try { + if (target < 21) { + return Planets._planet3dLocations[target].copy(); + } + } + catch ($e1) { } + return Vector3d.create(0, 0, 0); +}; + +Planets.getPlanet3dSufaceAltitude = function (target) { + try { + if (target < 21) { + return Planets.getAdjustedPlanetRadius(target); + } + } + catch ($e1) { } + return 0; +}; + +Planets.getPlanetTargetPoint = function (target, lat, lng, jNow) { + var temp; + if (!jNow) { + temp = Planets.getPlanet3dLocation(target); + } + else { + temp = Planets.getPlanet3dLocationJD(target, jNow); + } + temp.add(Coordinates.raDecTo3dAu((lng / 15) + 6, lat, Planets.getPlanet3dSufaceAltitude(target))); + return temp; +}; + +Planets.getPlanet3dLocationJD = function (target, jNow) { + try { + var result = new Vector3d(); + var centerRaDec = AstroCalc.getPlanet(jNow, 0, 0, 0, -6378149); + var center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); + if (target === SolarSystemObjects.earth) { + result = Vector3d.create(-center.x, -center.y, -center.z); + } else { + var planet = AstroCalc.getPlanet(jNow, target, 0, 0, -6378149); + result = Coordinates.raDecTo3dAu(planet.RA, planet.dec, planet.distance); + result.subtract(center); + } + result.rotateX(Coordinates.meanObliquityOfEcliptic(jNow) * Planets.RC); + if (Settings.get_active().get_solarSystemScale() !== 1) { + switch (target) { + case SolarSystemObjects.moon: + var parent = Planets.getPlanet3dLocationJD(SolarSystemObjects.earth, jNow); + result.subtract(parent); + result.multiply(Settings.get_active().get_solarSystemScale() / 2); + result.add(parent); + break; + case SolarSystemObjects.io: + case SolarSystemObjects.europa: + case SolarSystemObjects.ganymede: + case SolarSystemObjects.callisto: + var parent = Planets.getPlanet3dLocationJD(SolarSystemObjects.jupiter, jNow); + result.subtract(parent); + result.multiply(Settings.get_active().get_solarSystemScale()); + result.add(parent); + break; + default: + break; + } + } + return result; + } + catch ($e1) { + return Vector3d.create(0, 0, 0); + } +}; + +Planets.getPlanetLocation = function (name) { + var id = Planets.getPlanetIDFromName(name); + if (Planets._planetLocations != null) { + return Planets._planetLocations[id]; + } + else { + return AstroCalc.getPlanet(SpaceTimeController.get_jNow(), id, SpaceTimeController.get_location().get_lat(), SpaceTimeController.get_location().get_lng(), SpaceTimeController.get_altitude()); + } +}; + +Planets.getPlanetLocationJD = function (name, jNow) { + var id = Planets.getPlanetIDFromName(name); + return AstroCalc.getPlanet(jNow, id, SpaceTimeController.get_location().get_lat(), SpaceTimeController.get_location().get_lng(), SpaceTimeController.get_altitude()); +}; + +Planets.getPlanetIDFromName = function (planetName) { + switch (planetName) { + case 'Sun': + return SolarSystemObjects.sun; + case 'Mercury': + return SolarSystemObjects.mercury; + case 'Venus': + return SolarSystemObjects.venus; + case 'Mars': + return SolarSystemObjects.mars; + case 'Jupiter': + return SolarSystemObjects.jupiter; + case 'Saturn': + return SolarSystemObjects.saturn; + case 'Uranus': + return SolarSystemObjects.uranus; + case 'Neptune': + return SolarSystemObjects.neptune; + case 'Pluto': + return SolarSystemObjects.pluto; + case 'Moon': + return SolarSystemObjects.moon; + case 'Io': + return SolarSystemObjects.io; + case 'Europa': + return SolarSystemObjects.europa; + case 'Ganymede': + return SolarSystemObjects.ganymede; + case 'Callisto': + return SolarSystemObjects.callisto; + case 'Earth': + return SolarSystemObjects.earth; + case 'IoShadow': + return SolarSystemObjects.ioShadow; + case 'EuropaShadow': + return SolarSystemObjects.europaShadow; + case 'GanymedeShadow': + return SolarSystemObjects.ganymedeShadow; + case 'CallistoShadow': + return SolarSystemObjects.callistoShadow; + case 'SunEclipsed': + return SolarSystemObjects.sunEclipsed; + case 'Custom': + return SolarSystemObjects.custom; + case 'Undefined': + return SolarSystemObjects.undefined; + default: + return -1; + } +}; + +Planets.getNameFrom3dId = function (id) { + switch (id) { + case SolarSystemObjects.sun: + return 'Sun'; + case SolarSystemObjects.mercury: + return 'Mercury'; + case SolarSystemObjects.venus: + return 'Venus'; + case SolarSystemObjects.mars: + return 'Mars'; + case SolarSystemObjects.jupiter: + return 'Jupiter'; + case SolarSystemObjects.saturn: + return 'Saturn'; + case SolarSystemObjects.uranus: + return 'Uranus'; + case SolarSystemObjects.neptune: + return 'Neptune'; + case SolarSystemObjects.pluto: + return 'Pluto'; + case SolarSystemObjects.moon: + return 'Moon'; + case SolarSystemObjects.io: + return 'Io'; + case SolarSystemObjects.europa: + return 'Europa'; + case SolarSystemObjects.ganymede: + return 'Ganymede'; + case SolarSystemObjects.callisto: + return 'Callisto'; + case SolarSystemObjects.earth: + return 'Earth'; + default: + return ''; + } +}; + +Planets.updatePlanetLocations = function (threeDee) { + Planets._jNow = SpaceTimeController.get_jNow(); + if (threeDee) { + Planets.updateOrbits(0); + } + if (Planets._planetDiameters == null) { + Planets._planetDiameters = new Array(20); + Planets._planetDiameters[0] = 0.009291568; + Planets._planetDiameters[1] = 3.25794793734425E-05; + Planets._planetDiameters[2] = 8.08669220531394E-05; + Planets._planetDiameters[3] = 4.53785605596396E-05; + Planets._planetDiameters[4] = 0.000954501; + Planets._planetDiameters[5] = 0.000802173; + Planets._planetDiameters[6] = 0.000339564; + Planets._planetDiameters[7] = 0.000324825; + Planets._planetDiameters[8] = 1.52007379777805E-05; + Planets._planetDiameters[9] = 2.32084653538149E-05; + Planets._planetDiameters[10] = 2.43519298386342E-05; + Planets._planetDiameters[11] = 2.08692629580609E-05; + Planets._planetDiameters[12] = 3.51742670356556E-05; + Planets._planetDiameters[13] = 3.22263666626559E-05; + Planets._planetDiameters[14] = 2.43519298386342E-05; + Planets._planetDiameters[15] = 2.08692629580609E-05; + Planets._planetDiameters[16] = 3.51742670356556E-05; + Planets._planetDiameters[17] = 3.22263666626559E-05; + Planets._planetDiameters[18] = 0.009291568 * 2; + Planets._planetDiameters[SolarSystemObjects.earth] = 8.55626412117809E-05; + } + if (Planets.planetColors == null) { + var lightYellow = Color.fromArgb(255, 255, 255, 221); + var orangeRed = Color.fromArgb(255, 255, 68, 0); + Planets.planetColors = new Array(20); + Planets.planetColors[0] = Colors.get_yellow(); + Planets.planetColors[1] = Colors.get_white(); + Planets.planetColors[2] = lightYellow; + Planets.planetColors[3] = orangeRed; + Planets.planetColors[4] = Color.fromArgb(255, 255, 165, 0); + Planets.planetColors[5] = Color.fromArgb(255, 184, 134, 11); + Planets.planetColors[6] = Color.fromArgb(255, 173, 216, 230); + Planets.planetColors[7] = Colors.get_blue(); + Planets.planetColors[8] = Colors.get_white(); + Planets.planetColors[9] = Colors.get_white(); + Planets.planetColors[10] = Colors.get_white(); + Planets.planetColors[11] = Colors.get_white(); + Planets.planetColors[12] = Colors.get_white(); + Planets.planetColors[13] = Colors.get_white(); + Planets.planetColors[14] = Colors.get_black(); + Planets.planetColors[15] = Colors.get_black(); + Planets.planetColors[16] = Colors.get_black(); + Planets.planetColors[17] = Colors.get_black(); + Planets.planetColors[18] = Colors.get_white(); + Planets.planetColors[SolarSystemObjects.earth] = Color.fromArgb(255, 173, 216, 230); + } + if (Planets._planetTilts == null) { + Planets._planetTilts = new Array(20); + Planets._planetTilts[0] = 0; + Planets._planetTilts[1] = 0.01; + Planets._planetTilts[2] = 177.4; + Planets._planetTilts[3] = 25.19; + Planets._planetTilts[4] = 3.13; + Planets._planetTilts[5] = 26.73; + Planets._planetTilts[6] = 97.77; + Planets._planetTilts[7] = 28.32; + Planets._planetTilts[8] = 119.61; + Planets._planetTilts[9] = 23.439; + Planets._planetTilts[10] = 2.21; + Planets._planetTilts[11] = 0; + Planets._planetTilts[12] = -0.33; + Planets._planetTilts[13] = 0; + Planets._planetTilts[14] = 0; + Planets._planetTilts[15] = 0; + Planets._planetTilts[16] = 0; + Planets._planetTilts[17] = 0; + Planets._planetTilts[18] = 0; + Planets._planetTilts[SolarSystemObjects.earth] = 23.5; + } + Planets._planetTilts[SolarSystemObjects.earth] = Planets._obliquity / Planets.RC; + if (Planets.planetRotationPeriod == null) { + Planets.planetRotationPeriod = new Array(20); + Planets.planetRotationPeriod[0] = 25.37995; + Planets.planetRotationPeriod[1] = 58.6462; + Planets.planetRotationPeriod[2] = -243.0187; + Planets.planetRotationPeriod[3] = 1.02595675; + Planets.planetRotationPeriod[4] = 0.41007; + Planets.planetRotationPeriod[5] = 0.426; + Planets.planetRotationPeriod[6] = -0.71833; + Planets.planetRotationPeriod[7] = 0.67125; + Planets.planetRotationPeriod[8] = -6.38718; + Planets.planetRotationPeriod[9] = 27.3; + Planets.planetRotationPeriod[10] = 1.769137786; + Planets.planetRotationPeriod[11] = 3.551; + Planets.planetRotationPeriod[12] = 7.155; + Planets.planetRotationPeriod[13] = 16.69; + Planets.planetRotationPeriod[14] = 0; + Planets.planetRotationPeriod[15] = 0; + Planets.planetRotationPeriod[16] = 0; + Planets.planetRotationPeriod[17] = 0; + Planets.planetRotationPeriod[18] = 0; + Planets.planetRotationPeriod[SolarSystemObjects.earth] = 0.99726968; + } + if (Planets._planetScales == null) { + Planets._planetScales = new Array(20); + } + if (Planets._planet3dLocations == null) { + Planets._planet3dLocations = new Array(20); + } + if (Settings.get_active().get_actualPlanetScale()) { + Planets._planetScales[0] = 0.5; + Planets._planetScales[1] = 0.25; + Planets._planetScales[2] = 0.25; + Planets._planetScales[3] = 0.25; + Planets._planetScales[4] = 0.25; + Planets._planetScales[5] = 0.5; + Planets._planetScales[6] = 0.25; + Planets._planetScales[7] = 0.25; + Planets._planetScales[8] = 0.25; + Planets._planetScales[9] = 0.25; + Planets._planetScales[10] = 0.25; + Planets._planetScales[11] = 0.25; + Planets._planetScales[12] = 0.25; + Planets._planetScales[13] = 0.25; + Planets._planetScales[14] = 0.25; + Planets._planetScales[15] = 0.25; + Planets._planetScales[16] = 0.25; + Planets._planetScales[17] = 0.25; + Planets._planetScales[18] = 0.5; + Planets._planetScales[SolarSystemObjects.earth] = 0.25; + } + else { + for (var i = 0; i < 20; i++) { + if (i < 10) { + Planets._planetScales[i] = 0.25; + } + else { + Planets._planetScales[i] = 0.1; + } + } + + // Make Sun and Saturn bigger + Planets._planetScales[SolarSystemObjects.sun] = 0.5; + Planets._planetScales[SolarSystemObjects.saturn] = 0.5; + Planets._planetScales[SolarSystemObjects.sunEclipsed] = 0.5; + } + Planets._planetDrawOrder = {}; + Planets._planetLocations = new Array(20); + var center = new Vector3d(); + var planetCenter = 0; + if (planetCenter > -1) { + var centerRaDec = AstroCalc.getPlanet(Planets._jNow, planetCenter, (threeDee) ? 0 : SpaceTimeController.get_location().get_lat(), (threeDee) ? 0 : SpaceTimeController.get_location().get_lng(), (threeDee) ? -6378149 : SpaceTimeController.get_altitude()); + center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); + } + Planets._planet3dLocations[SolarSystemObjects.earth] = Vector3d.create(-center.x, -center.y, -center.z); + Planets._planet3dLocations[SolarSystemObjects.earth].rotateX(Planets._obliquity); + for (var i = 0; i < 18; i++) { + Planets._planetLocations[i] = AstroCalc.getPlanet(Planets._jNow, i, (threeDee) ? 0 : SpaceTimeController.get_location().get_lat(), (threeDee) ? 0 : SpaceTimeController.get_location().get_lng(), (threeDee) ? -6378149 : SpaceTimeController.get_altitude()); + Planets._planet3dLocations[i] = Coordinates.raDecTo3dAu(Planets._planetLocations[i].RA, Planets._planetLocations[i].dec, Planets._planetLocations[i].distance); + Planets._planet3dLocations[i].subtract(center); + Planets._planet3dLocations[i].rotateX(Planets._obliquity); + if (Settings.get_active().get_actualPlanetScale()) { + Planets._planetScales[i] = (2 * Math.atan(0.5 * (Planets._planetDiameters[i] / Planets._planetLocations[i].distance))) / Math.PI * 180; + } + if (Settings.get_active().get_solarSystemScale() !== 1) { + var id = i; + switch (id) { + case SolarSystemObjects.moon: + var parent = Planets._planet3dLocations[SolarSystemObjects.earth]; + Planets._planet3dLocations[i].subtract(parent); + Planets._planet3dLocations[i].multiply(Settings.get_active().get_solarSystemScale() / 2); + Planets._planet3dLocations[i].add(parent); + break; + case SolarSystemObjects.io: + case SolarSystemObjects.europa: + case SolarSystemObjects.ganymede: + case SolarSystemObjects.callisto: + var parent = Planets._planet3dLocations[SolarSystemObjects.jupiter]; + Planets._planet3dLocations[i].subtract(parent); + Planets._planet3dLocations[i].multiply(Settings.get_active().get_solarSystemScale()); + Planets._planet3dLocations[i].add(parent); + break; + default: + break; + } + } + var finalDistance = -Planets._planetLocations[i].distance; + while (ss.keyExists(Planets._planetDrawOrder, finalDistance)) { + finalDistance += 1E-10; + } + Planets._planetDrawOrder[finalDistance] = i; + } + Planets._planetLocations[SolarSystemObjects.sunEclipsed] = Planets._planetLocations[SolarSystemObjects.sun]; + Planets._planetScales[SolarSystemObjects.sun] *= 2; + Planets._planetScales[SolarSystemObjects.sunEclipsed] = Planets._planetScales[SolarSystemObjects.sun]; + Planets._planetScales[SolarSystemObjects.saturn] = Planets._planetScales[SolarSystemObjects.saturn] * 2; + Planets._lastUpdate = SpaceTimeController.get_now(); +}; + +Planets.planetsReady = function () { }; + +Planets.updateOrbits = function (planetCenter) { + try { + Planets._obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) * Planets.RC; + if (planetCenter !== Planets._lastPlanetCenterID) { + Planets._orbits = null; + } + Planets._lastPlanetCenterID = planetCenter; + if (Planets._orbits == null) { + if (planetCenter < 0) { + Planets._eclipticTilt = Matrix3d.get_identity(); + } + else { + Planets._eclipticTilt = Matrix3d.get_identity(); + Planets._eclipticTilt = Matrix3d._rotationX(Planets._obliquity); + } + if (Planets.planetOrbitalYears == null) { + Planets.planetOrbitalYears = new Array(20); + Planets.planetOrbitalYears[0] = 1; + Planets.planetOrbitalYears[1] = 0.241; + Planets.planetOrbitalYears[2] = 0.615; + Planets.planetOrbitalYears[3] = 1.881; + Planets.planetOrbitalYears[4] = 11.87; + Planets.planetOrbitalYears[5] = 29.45; + Planets.planetOrbitalYears[6] = 84.07; + Planets.planetOrbitalYears[7] = 164.9; + Planets.planetOrbitalYears[8] = 248.1; + Planets.planetOrbitalYears[9] = 27.3 / 365.25; + Planets.planetOrbitalYears[10] = 16.6890184 / 365.25; + Planets.planetOrbitalYears[11] = 3.551181 / 365.25; + Planets.planetOrbitalYears[12] = 7.15455296 / 365.25; + Planets.planetOrbitalYears[13] = 16.6890184 / 365.25; + Planets.planetOrbitalYears[SolarSystemObjects.earth] = 1; + } + if (!Planets.readOrbits()) { + Planets._orbits = new Array(20); + for (var i = 1; i < 20; i++) { + Planets._orbits[i] = new Array(Planets._orbitalSampleRate); + if (i < 9 || i === SolarSystemObjects.earth) { + for (var j = 0; j < Planets._orbitalSampleRate; j++) { + var centerId = planetCenter; + var now = Planets._jNow + ((Planets.planetOrbitalYears[i] * 365.25 / Planets._orbitalSampleRate) * (j - (Planets._orbitalSampleRate / 2))); + var center = new Vector3d(); + if (i === SolarSystemObjects.moone) { + centerId = -1; + } + else if (i > 9 && i < 14) { + centerId = 4; + } + if (centerId > -1) { + var centerRaDec = AstroCalc.getPlanet(now, centerId, 0, 0, -6378149); + center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); + } + if (i !== SolarSystemObjects.earth) { + var planetRaDec = AstroCalc.getPlanet(now, i, 0, 0, -6378149); + Planets._orbits[i][j] = Coordinates.raDecTo3dAu(planetRaDec.RA, planetRaDec.dec, planetRaDec.distance); + Planets._orbits[i][j].subtract(center); + } + else { + Planets._orbits[i][j] = Vector3d.create(-center.x, -center.y, -center.z); + } + Planets._orbits[i][j].rotateX(Planets._obliquity); + } + Planets._orbits[i][Planets._orbitalSampleRate - 1] = Planets._orbits[i][0]; + } + } + Planets.dumpOrbitsFile(); + } + } + } + finally { } +}; + +Planets.readOrbits = function () { + // This function ought to fetch wwtweb/catalog.aspx?Q=orbitsbin and set + // `orbits`, see Windows client code. + return false; +}; + +Planets.dumpOrbitsFile = function () { }; + +Planets.drawPlanets = function (renderContext, opacity) { + if (Planets._planetTextures == null) { + Planets._loadPlanetTextures(); + } + + // Get Moon Phase + + var elong = Planets._geocentricElongation(Planets._planetLocations[9].RA, Planets._planetLocations[9].dec, Planets._planetLocations[0].RA, Planets._planetLocations[0].dec); + var raDif = Planets._planetLocations[9].RA - Planets._planetLocations[0].RA; + if (Planets._planetLocations[9].RA < Planets._planetLocations[0].RA) { + raDif += 24; + } + var phaseAngle = Planets._phaseAngle(elong, Planets._planetLocations[9].distance, Planets._planetLocations[0].distance); + var limbAngle = Planets._positionAngle(Planets._planetLocations[9].RA, Planets._planetLocations[9].dec, Planets._planetLocations[0].RA, Planets._planetLocations[0].dec); + if (raDif < 12) { + phaseAngle += 180; + } + + // Check for solar eclipse + + var dista = (Math.abs(Planets._planetLocations[9].RA - Planets._planetLocations[0].RA) * 15) * Math.cos(Coordinates.degreesToRadians(Planets._planetLocations[0].dec)); + var distb = Math.abs(Planets._planetLocations[9].dec - Planets._planetLocations[0].dec); + var sunMoonDist = Math.sqrt(dista * dista + distb * distb); + var eclipse = false; + var coronaOpacity = 0; + var moonEffect = (Planets._planetScales[9] / 2 - sunMoonDist); + var darkLimb = Math.min(32, ss.truncate((sunMoonDist * 32))); + if (moonEffect > (Planets._planetScales[0] / 4)) { + eclipse = true; + coronaOpacity = Math.min(1, (moonEffect - (Planets._planetScales[0] / 2)) / 0.001); + Planets._drawPlanet(renderContext, 18, coronaOpacity); + } + var $enum1 = ss.enumerate(ss.keys(Planets._planetDrawOrder)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var planetId = Planets._planetDrawOrder[key]; + Planets._drawPlanet(renderContext, planetId, 1); + } + return true; +}; + +Planets._loadPlanetTextures = function () { + // Note: these PNG files are fairly large and are loaded at + // startup of the web client, adding nontrivially to the needed + // network traffic. JPGs are a lot smaller, but unfortunately the + // transparency support is important here since we don't want + // black boxes surrounding all of our planets when they're viewed + // in the sky. + + var baseUrl = URLHelpers.singleton.engineAssetUrl(''); + + Planets._planetTextures = new Array(20); + Planets._planetTextures[0] = Texture.fromUrl(baseUrl + 'sun.png'); + Planets._planetTextures[1] = Texture.fromUrl(baseUrl + 'mercury.png'); + Planets._planetTextures[2] = Texture.fromUrl(baseUrl + 'venus.png'); + Planets._planetTextures[3] = Texture.fromUrl(baseUrl + 'mars.png'); + Planets._planetTextures[4] = Texture.fromUrl(baseUrl + 'jupiter.png'); + Planets._planetTextures[5] = Texture.fromUrl(baseUrl + 'saturn.png'); + Planets._planetTextures[6] = Texture.fromUrl(baseUrl + 'uranus.png'); + Planets._planetTextures[7] = Texture.fromUrl(baseUrl + 'neptune.png'); + Planets._planetTextures[8] = Texture.fromUrl(baseUrl + 'pluto.png'); + Planets._planetTextures[9] = Texture.fromUrl(baseUrl + 'moon.png'); + Planets._planetTextures[10] = Texture.fromUrl(baseUrl + 'io.png'); + Planets._planetTextures[11] = Texture.fromUrl(baseUrl + 'europa.png'); + Planets._planetTextures[12] = Texture.fromUrl(baseUrl + 'ganymede.png'); + Planets._planetTextures[13] = Texture.fromUrl(baseUrl + 'callisto.png'); + Planets._planetTextures[14] = Texture.fromUrl(baseUrl + 'moonshadow.png'); + Planets._planetTextures[15] = Texture.fromUrl(baseUrl + 'moonshadow.png'); + Planets._planetTextures[16] = Texture.fromUrl(baseUrl + 'moonshadow.png'); + Planets._planetTextures[17] = Texture.fromUrl(baseUrl + 'moonshadow.png'); + Planets._planetTextures[18] = Texture.fromUrl(baseUrl + 'sunCorona.png'); + Planets._planetTextures[SolarSystemObjects.earth] = Texture.fromUrl(baseUrl + 'earth.png'); +}; + +// Compute the rotation of a planet at the J2000 epoch. +// +// The rotation at some instant in can be computed by multiplying the +// the returned matrix by Y(W * t) +Planets.getPlanetOrientationAtEpoch = function (planetID) { + var m = Matrix3d.get_identity(); + + // Rotational elements for the planets are in the form used by the + // IAU Working Group on Cartographic Coordinates and Rotational Elements: + // + // a : Right ascension of north pole + // d : Declination of north pole + // W0 : Prime meridian angle at epoch J2000.0 + // + // The canonical Euler angle sequence is: Z(a - 90) * X(90 - d) * Z(W0) + // + // The following transformations are required to convert it to a rotation for WWT: + // * WWT uses a coordinate system with +Y = ecliptic north, +X = equinox of J2000 + // This system is rotated 90 degrees about the X axis from the standard ecliptic + // system based on the Earth Mean Equinox of J2000 (EMEJ2000) + // * WWT uses row vectors instead of column vectors, so the order of transformations + // is reversed + // * WWT has planet maps with longitude 0 at the edge rather than the middle. This + // requires an extra 180 degrees to be added to W0 + var obliquityOfEcliptic = 23.4392794; + + if (planetID === SolarSystemObjects.earth) { + // Different calculation for Earth, since the meridian offset + // is already included in the Mean Sidereal Time function. + // + // equatorial to ecliptic transformation + m._multiply(Matrix3d._rotationX(obliquityOfEcliptic * Planets.RC)); + } else { + // 90 degree rotation from WWT coord sys + m._multiply(Matrix3d._rotationX(-90 * Planets.RC)); + + m._multiply(Matrix3d._rotationZ((180 + Planets._planetAngles[planetID].primeMeridian) * Planets.RC)); + m._multiply(Matrix3d._rotationX((90 - Planets._planetAngles[planetID].poleDec) * Planets.RC)); + m._multiply(Matrix3d._rotationZ((Planets._planetAngles[planetID].poleRa - 90) * Planets.RC)); + m._multiply(Matrix3d._rotationX(obliquityOfEcliptic * Planets.RC)); // equatorial to ecliptic transformation + + // 90 degree rotation back to WWT coord sys + m._multiply(Matrix3d._rotationX(90 * Planets.RC)); + } + return m; +}; + +Planets.setupPlanetMatrix = function (renderContext, planetID, centerPoint, makeFrustum) { + var matNonRotating = renderContext.get_world().clone(); + Planets._setupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, makeFrustum); + + if (planetID === SolarSystemObjects.sun) { + // Don't apply the Sun's orientation to its non-rotating frame; this means that + // the Sun's reference frame will be the ecliptic frame. + var radius = Planets.getAdjustedPlanetRadius(planetID); + matNonRotating.scale(Vector3d.create(radius, radius, radius)); + var translation = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); + matNonRotating._multiply(Matrix3d.translation(translation)); + renderContext.set_worldBaseNonRotating(matNonRotating); + } +}; + +Planets._setupMatrixForPlanetGeometry = function (renderContext, planetID, centerPoint, makeFrustum) { + var radius = Planets.getAdjustedPlanetRadius(planetID); + var rotationCurrent = 0; + if (planetID === SolarSystemObjects.earth) { + rotationCurrent = Math.PI + Coordinates.mstFromUTC2(SpaceTimeController.get_now(), 0) / 180 * Math.PI; + } + else { + rotationCurrent = Math.PI + (((Planets._jNow - 2451545) / Planets.planetRotationPeriod[planetID]) * Math.PI * 2) % (Math.PI * 2); + } + if (planetID === 9) { + rotationCurrent -= Math.PI / 2; + } + var matLocal = renderContext.get_world().clone(); + var matNonRotating = renderContext.get_world().clone(); + var translation = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); + var orientationAtEpoch = Planets.getPlanetOrientationAtEpoch(planetID); + matLocal.scale(Vector3d.create(radius, radius, radius)); + matLocal._multiply(Matrix3d._rotationY(-rotationCurrent)); + matLocal._multiply(orientationAtEpoch); + if (planetID === renderContext.viewCamera.target) { + Planets.earthMatrix = Matrix3d.get_identity(); + Planets.earthMatrix._multiply(Matrix3d._rotationY(-rotationCurrent)); + Planets.earthMatrix._multiply(orientationAtEpoch); + Planets.earthMatrixInv = Planets.earthMatrix.clone(); + Planets.earthMatrixInv.invert(); + } + matLocal._multiply(Matrix3d.translation(translation)); + renderContext.set_world(matLocal); + renderContext.set_worldBase(renderContext.get_world().clone()); + renderContext.set_nominalRadius(Planets.getPlanetRadiusInMeters(planetID)); + if (makeFrustum) { + renderContext.makeFrustum(); + } + matNonRotating.scale(Vector3d.create(radius, radius, radius)); + matNonRotating._multiply(orientationAtEpoch); + matNonRotating._multiply(Matrix3d.translation(translation)); + renderContext.set_worldBaseNonRotating(matNonRotating); + return rotationCurrent; +}; + +// Get the position of a Solar System object using a 'direct' calculation that +// avoids including an aberration correction. +// +// The returned position is in ecliptic coordinate system with the origin at the center +// of the parent body (i.e. the Sun for planets, a planet for moons). The position of moons +// is _not_ modified by the SolarSystemScale, making it possible to use function to +// a calculate valid Keplerian elements. +Planets.getPlanetPositionDirect = function (id, jd) { + var L = 0; + var B = 0; + var R = 0; + switch (id) { + case 1: + L = CAAMercury.eclipticLongitude(jd); + B = CAAMercury.eclipticLatitude(jd); + R = CAAMercury.radiusVector(jd); + break; + case 2: + L = CAAVenus.eclipticLongitude(jd); + B = CAAVenus.eclipticLatitude(jd); + R = CAAVenus.radiusVector(jd); + break; + case SolarSystemObjects.earth: + L = CAAEarth.eclipticLongitude(jd); + B = CAAEarth.eclipticLatitude(jd); + R = CAAEarth.radiusVector(jd); + break; + case 3: + L = CAAMars.eclipticLongitude(jd); + B = CAAMars.eclipticLatitude(jd); + R = CAAMars.radiusVector(jd); + break; + case 4: + L = CAAJupiter.eclipticLongitude(jd); + B = CAAJupiter.eclipticLatitude(jd); + R = CAAJupiter.radiusVector(jd); + break; + case 5: + L = CAASaturn.eclipticLongitude(jd); + B = CAASaturn.eclipticLatitude(jd); + R = CAASaturn.radiusVector(jd); + break; + case 6: + L = CAAUranus.eclipticLongitude(jd); + B = CAAUranus.eclipticLatitude(jd); + R = CAAUranus.radiusVector(jd); + break; + case 7: + L = CAANeptune.eclipticLongitude(jd); + B = CAANeptune.eclipticLatitude(jd); + R = CAANeptune.radiusVector(jd); + break; + case 8: + L = CAAPluto.eclipticLongitude(jd); + B = CAAPluto.eclipticLatitude(jd); + R = CAAPluto.radiusVector(jd); + break; + case 9: + L = CAAMoon.eclipticLongitude(jd); + B = CAAMoon.eclipticLatitude(jd); + R = CAAMoon.radiusVector(jd) / 149598000; + break; + case 10: + var galileanInfo = GM.calculate(jd); + var position = galileanInfo.satellite1.eclipticRectangularCoordinates; + return Vector3d.create(position.x, position.z, position.y); + case 11: + var galileanInfo = GM.calculate(jd); + var position = galileanInfo.satellite2.eclipticRectangularCoordinates; + return Vector3d.create(position.x, position.z, position.y); + case 12: + var galileanInfo = GM.calculate(jd); + var position = galileanInfo.satellite3.eclipticRectangularCoordinates; + return Vector3d.create(position.x, position.z, position.y); + case 13: + var galileanInfo = GM.calculate(jd); + var position = galileanInfo.satellite4.eclipticRectangularCoordinates; + return Vector3d.create(position.x, position.z, position.y); + } + + // Enabling this code transforms planet positions from the mean ecliptic/equinox of + // date to the J2000 ecliptic. It is necessary because the VSOP87D series used + // for planet positions is in the mean-of-date frame. The transformation is currently + // disabled in order to better match planet positions calculated elsewhere in the code. + //CAA2DCoordinate prec = CAAPrecession.PrecessEcliptic(L, B, jd, 2451545.0); + //L = prec.X; + //B = prec.Y; + + L = Coordinates.degreesToRadians(L); + B = Coordinates.degreesToRadians(B); + var eclPos = Vector3d.create(Math.cos(L) * Math.cos(B) * R, Math.sin(L) * Math.cos(B) * R, Math.sin(B) * R); + + + // Transform from the ecliptic of date to the J2000 ecliptic; this transformation should be deleted + // once the precession is turned on. + var eclipticOfDateRotation = (Coordinates.meanObliquityOfEcliptic(jd) - Coordinates.meanObliquityOfEcliptic(2451545)) * Planets.RC; + eclPos.rotateX(eclipticOfDateRotation); + return Vector3d.create(eclPos.x, eclPos.z, eclPos.y); +}; + +Planets._stateVectorToKeplerian = function (position, velocity, mu) { + // Work in units of km and seconds + var r = Vector3d.scale(position, 149598000); + var v = Vector3d.scale(Vector3d.scale(velocity, 1 / 86400), 149598000); + var rmag = r.length(); + var vmag = v.length(); + var sma = 1 / (2 / rmag - vmag * vmag / mu); + + // h is the orbital angular momentum vector + var h = Vector3d.cross(r, v); + + // ecc is the eccentricity vector, which points from the + // planet at periapsis to the center point. + var ecc = Vector3d.subtractVectors(Vector3d.scale(Vector3d.cross(v, h), 1 / mu), Vector3d.scale(r, 1 / rmag)); + var e = ecc.length(); + + h.normalize(); + ecc.normalize(); + + // h, s, and ecc are orthogonal vectors that define a coordinate + // system. h is normal to the orbital plane. + var s = Vector3d.cross(h, ecc); + + // Calculate the sine and cosine of the true anomaly + r.normalize(); + var cosNu = Vector3d.dot(ecc, r); + var sinNu = Vector3d.dot(s, r); + + // Compute the eccentric anomaly + var E = Math.atan2(Math.sqrt(1 - e * e) * sinNu, e + cosNu); + var elements = new KeplerianElements(); + + // Create a rotation matrix given the three orthogonal vectors: + // ecc - eccentricity vector + // s - in the orbital plane, perpendicular to ecc + // h - angular momentum vector, normal to orbital plane + elements.orientation = Matrix3d.create(ecc.x, ecc.y, ecc.z, 0, s.x, s.y, s.z, 0, h.x, h.y, h.z, 0, 0, 0, 0, 1); + elements.a = sma; + elements.e = e; + elements.ea = E; + return elements; +}; + +Planets.getAdjustedPlanetRadius = function (planetID) { + if (planetID > Planets._planetDiameters.length - 1) { + planetID = SolarSystemObjects.earth; + } + var diameter = Planets._planetDiameters[planetID]; + var radius = (diameter / 2); + if (!!planetID) { + radius = radius * (1 + (3 * (Settings.get_active().get_solarSystemScale() - 1))); + } + else { + radius = radius * (1 + (0.3 * (Settings.get_active().get_solarSystemScale() - 1))); + } + return radius; +}; + +Planets.getPlanetRadiusInMeters = function (planetID) { + if (planetID > Planets._planetDiameters.length - 1) { + planetID = SolarSystemObjects.earth; + } + var diameter = Planets._planetDiameters[planetID]; + return (diameter / 2) * 149598000 * 1000; +}; + +Planets._drawPlanet = function (renderContext, planetID, opacity) { + var planetPosition = Planets._planetLocations[planetID]; + if (((planetID < 14) && Planets._planetScales[planetID] < (renderContext.viewCamera.zoom / 6) / 400)) { + if (planetID < 10 || ((planetID < 14) && Planets._planetScales[planetID] > (renderContext.viewCamera.zoom / 6) / 6400)) { + var point = Coordinates.raDecTo3d(planetPosition.RA, planetPosition.dec); + BasePlanets.drawPointPlanet(renderContext, point, 3, Planets.planetColors[planetID], false); + } + return; + } + var brush = null; + if (planetID < 10 || planetID === 18) { + brush = Planets._planetTextures[planetID]; + } + else if (planetID < 14) { + if (Planets._planetLocations[planetID].eclipsed) { + brush = Planets._planetTextures[15]; + } else { + if (Settings.get_active().get_showMoonsAsPointSource()) { + brush = Planets._planetTextures[14]; + } + else { + brush = Planets._planetTextures[planetID]; + } + } + } + else { + if (!Planets._planetLocations[planetID].shadow) { + return; + } + + //Shadows of moons + brush = Planets._planetTextures[15]; + } + if (renderContext.gl != null) { + if (Planets._planetPoints == null) { + Planets._planetPoints = new Array(4); + for (var i = 0; i < 4; i++) { + Planets._planetPoints[i] = new PositionColoredTextured(); + } + } + var radius = (Planets._planetScales[planetID] / 2); + var raRadius = (radius / Math.cos(planetPosition.dec / 180 * Math.PI)); + Planets._planetPoints[0].position = Coordinates.raDecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.dec + radius, 1); + Planets._planetPoints[0].tu = 0; + Planets._planetPoints[0].tv = 1; + Planets._planetPoints[0].color = Colors.get_white(); + Planets._planetPoints[1].position = Coordinates.raDecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.dec - radius, 1); + Planets._planetPoints[1].tu = 0; + Planets._planetPoints[1].tv = 0; + Planets._planetPoints[1].color = Colors.get_white(); + Planets._planetPoints[2].position = Coordinates.raDecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.dec + radius, 1); + Planets._planetPoints[2].tu = 1; + Planets._planetPoints[2].tv = 1; + Planets._planetPoints[2].color = Colors.get_white(); + Planets._planetPoints[3].position = Coordinates.raDecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.dec - radius, 1); + Planets._planetPoints[3].tu = 1; + Planets._planetPoints[3].tv = 0; + Planets._planetPoints[3].color = Colors.get_white(); + Planets._planetSprite.draw(renderContext, Planets._planetPoints, 4, brush, true, 1); + } + else { + var center = Coordinates.raDecTo3d(planetPosition.RA, planetPosition.dec); + var rad = Planets._planetScales[planetID] / (renderContext.get_fovScale() / 3600) / 2; + var screenSpacePnt = renderContext.WVP.transform(center); + if (screenSpacePnt.z < 0) { + return; + } + if (Vector3d.dot(renderContext.get_viewPoint(), center) < 0.55) { + return; + } + var ctx = renderContext.device; + ctx.save(); + ctx.globalAlpha = opacity; + ctx.beginPath(); + ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); + ctx.lineWidth = 0; + ctx.closePath(); + ctx.clip(); + ctx.drawImage(brush.imageElement, screenSpacePnt.x - rad, screenSpacePnt.y - rad, rad * 2, rad * 2); + ctx.globalAlpha = 1; + ctx.restore(); + } +}; + +Planets._drawPlanetPhase = function (renderContext, planetID, phase, angle, dark) { }; + +Planets._geocentricElongation = function (ObjectAlpha, ObjectDelta, SunAlpha, SunDelta) { + //Convert the RA's to radians + ObjectAlpha = Coordinates.degreesToRadians(ObjectAlpha * 15); + SunAlpha = Coordinates.degreesToRadians(SunAlpha * 15); + + //Convert the declinations to radians + ObjectDelta = Coordinates.degreesToRadians(ObjectDelta); + SunDelta = Coordinates.degreesToRadians(SunDelta); + return Coordinates.radiansToDegrees(Math.acos(Math.sin(SunDelta) * Math.sin(ObjectDelta) + Math.cos(SunDelta) * Math.cos(ObjectDelta) * Math.cos(SunAlpha - ObjectAlpha))); +}; + +Planets._phaseAngle = function (GeocentricElongation, EarthObjectDistance, EarthSunDistance) { + //Convert from degrees to radians + GeocentricElongation = Coordinates.degreesToRadians(GeocentricElongation); + + return Coordinates.mapTo0To360Range(Coordinates.radiansToDegrees(Math.atan2(EarthSunDistance * Math.sin(GeocentricElongation), EarthObjectDistance - EarthSunDistance * Math.cos(GeocentricElongation)))); +}; + +Planets._positionAngle = function (Alpha0, Delta0, Alpha, Delta) { + Alpha0 = Coordinates.hoursToRadians(Alpha0); + Alpha = Coordinates.hoursToRadians(Alpha); + Delta0 = Coordinates.degreesToRadians(Delta0); + Delta = Coordinates.degreesToRadians(Delta); + return Coordinates.mapTo0To360Range(Coordinates.radiansToDegrees(Math.atan2(Math.cos(Delta0) * Math.sin(Alpha0 - Alpha), Math.sin(Delta0) * Math.cos(Delta) - Math.cos(Delta0) * Math.sin(Delta) * Math.cos(Alpha0 - Alpha)))); +}; + +var Planets$ = {}; + +registerType("Planets", [Planets, Planets$, null]); diff --git a/engine/esm/planets_3d.js b/engine/esm/planets_3d.js new file mode 100644 index 00000000..891602b9 --- /dev/null +++ b/engine/esm/planets_3d.js @@ -0,0 +1,540 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The 3D planet-related code. +// +// This does not include the 3D planet-rendering code, which has been separated +// into `planets_3d.js`. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d, Vector4d, Matrix3d, PositionTexture } from "./double3d.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { PositionTextureVertexBuffer } from "./graphics/gl_buffers.js"; +import { OrbitLineList } from "./graphics/primitives3d.js"; +import { Texture } from "./graphics/texture.js"; +import { TileShader } from "./graphics/shaders.js"; +import { Util } from "./baseutil.js"; +import { BasePlanets } from "./baseplanets.js"; +import { globalWWTControl } from "./data_globals.js"; +import { Color, Colors } from "./color.js"; +import { Planets } from "./planets.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Settings } from "./settings.js"; +import { Triangle } from "./triangle.js"; +import { UiTools } from "./ui_tools.js"; +import { URLHelpers } from "./url_helpers.js"; +import { EllipseRenderer } from "./layers/orbit.js"; +import { LayerManager } from "./layers/layer_manager.js"; + + +// 3D planet code. This used to live in `Planets.cs` with the 2D planet. + +export function Planets3d() { } + +Planets3d._ringsTriangleLists = new Array(2); +Planets3d._ringImage = null; +Planets3d._triangleCountRings = 192 + 1 * 2; +Planets3d._ringsVertexBuffer = null; + +Planets3d.getImageSetNameNameFrom3dId = function (id) { + switch (id) { + case 0: + return 'Sun'; + case 1: + return 'Mercury'; + case 2: + return 'Venus'; + case 3: + return 'Visible Imagery'; + case 4: + return 'Jupiter'; + case 5: + return 'Saturn'; + case 6: + return 'Uranus'; + case 7: + return 'Neptune'; + case 8: + return 'Pluto'; + case 9: + return 'Moon'; + case 10: + return 'Io (Jupiter)'; + case 11: + return 'Europa (Jupiter)'; + case 12: + return 'Ganymede (Jupiter)'; + case 13: + return 'Callisto (Jupiter)'; + case 19: + return 'Bing Maps Aerial'; + default: + return ''; + } +}; + +Planets3d.initPlanetResources = function (renderContext) { }; + +Planets3d.drawPlanets3D = function (renderContext, opacity, centerPoint) { + Planets3d.initPlanetResources(renderContext); + var distss = UiTools.solarSystemToMeters(renderContext.get_solarSystemCameraDistance()); + var moonFade = Math.min(1, Math.max(Util.log10(distss) - 7.3, 0)); + var fade = Math.min(1, Math.max(Util.log10(distss) - 8.6, 0)); + if (Settings.get_active().get_solarSystemOrbits() && fade > 0) { + for (var ii = 1; ii < 10; ii++) { + var id = ii; + if (ii === 9) { + id = 19; + } + var angle = Math.atan2(Planets._planet3dLocations[id].z, Planets._planet3dLocations[id].x); + Planets3d._drawSingleOrbit(renderContext, Planets.planetColors[id], id, centerPoint, angle, Planets._planet3dLocations[id], fade); + } + var mid = 9; + Planets3d._drawSingleOrbit(renderContext, Planets.planetColors[mid], mid, centerPoint, 0, Planets._planet3dLocations[mid], fade); + } + ss.clearKeys(Planets._drawOrder); + var camera = renderContext.cameraPosition.copy(); + for (var planetId = 0; planetId < 14; planetId++) { + // If we're using realistic lighting and this is an eclipsed + // moon, don't draw it at all. This is slightly suboptimal + // since, if you're looking at the moon, you'll suddenly be able + // to see the stars through it. In principle we should do + // something like keep on drawing it, but as an all-black + // sphere. + if (!(Settings.get_active().get_solarSystemLighting() && Planets._planetLocations[planetId].eclipsed)) { + var distVector = Vector3d.subtractVectors(camera, Vector3d.subtractVectors(Planets._planet3dLocations[planetId], centerPoint)); + if (!ss.keyExists(Planets._drawOrder, distVector.length())) { + Planets._drawOrder[distVector.length()] = planetId; + } + } + } + var distVectorEarth = Vector3d.subtractVectors(camera, Vector3d.subtractVectors(Planets._planet3dLocations[19], centerPoint)); + if (!ss.keyExists(Planets._drawOrder, distVectorEarth.length())) { + Planets._drawOrder[distVectorEarth.length()] = 19; + } + var $enum1 = ss.enumerate(ss.keys(Planets._drawOrder)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var planetId = Planets._drawOrder[key]; + Planets3d._drawPlanet3d(renderContext, planetId, centerPoint); + } + return true; +}; + +Planets3d._drawSingleOrbit = function (renderContext, eclipticColor, id, centerPoint, startAngle, planetNow, opacity) { + // mu is the standard gravitational parameter GM, where G + // is the gravitational constant and M is the mass of the + // central body. + const muSun = 1.327124400188e11; // km^3/s^2 + const muEarth = 3.9860044189e5; + const muMoon = 4.9027779e3; + const muJupiter = 1.26686534e8; + + if (opacity < 0.01) { + return; + } + if (renderContext.gl == null) { + var count = Planets._orbitalSampleRate; + var planetDropped = false; + var viewPoint = renderContext.get_viewPoint(); + var ctx = renderContext.device; + ctx.save(); + ctx.strokeStyle = eclipticColor.toString(); + ctx.lineWidth = 2; + ctx.globalAlpha = 1; + var point = new Vector3d(); + var pointTest = new Vector3d(); + var lastPoint = new Vector3d(); + var firstPoint = true; + var translate = Matrix3d.translation(Vector3d.negate(centerPoint)); + var mat = Matrix3d.multiplyMatrix(translate, renderContext.WVP); + var matWV = Matrix3d.multiplyMatrix(translate, renderContext.WV); + for (var i = 0; i < count; i++) { + var pnt = Planets._orbits[id][i]; + var angle = (Math.atan2(Planets._orbits[id][i].z, Planets._orbits[id][i].x) + Math.PI * 2 - startAngle) % (Math.PI * 2); + var alpha = ss.truncate((angle / (Math.PI * 2) * 255)); + var alphaD = alpha / 255; + if (alpha < 2 && !planetDropped) { + pnt = planetNow; + alphaD = 1; + } + pointTest = matWV.transform(pnt); + point = mat.transform(pnt); + if (pointTest.z > 0) { + if (firstPoint) { + firstPoint = false; + } + else { + ctx.beginPath(); + ctx.globalAlpha = alphaD * opacity; + ctx.moveTo(lastPoint.x, lastPoint.y); + ctx.lineTo(point.x, point.y); + ctx.stroke(); + } + } + lastPoint = point; + } + ctx.restore(); + } + else { + if (id !== 9) { + var count = Planets._orbitalSampleRate; + var planetDropped = false; + var viewPoint = renderContext.get_viewPoint(); + var point = new Vector3d(); + var pointTest = new Vector3d(); + var lastPoint = new Vector3d(); + var lastColor = new Color(); + var firstPoint = true; + var list = new OrbitLineList(); + for (var i = 0; i < count; i++) { + var pnt = Planets._orbits[id][i].copy(); + var angle = (Math.atan2(pnt.z, pnt.x) + Math.PI * 2 - startAngle) % (Math.PI * 2); + var alpha = ss.truncate((angle / (Math.PI * 2) * 255)); + var alphaD = alpha / 255; + var color = Color.fromArgb(alpha, eclipticColor.r, eclipticColor.g, eclipticColor.b); + if (alpha < 2 && !planetDropped && !firstPoint) { + pnt = Vector3d.subtractVectors(planetNow, centerPoint); + alphaD = 1; + alpha = 255; + color.a = 255; + lastColor.a = 255; + list.addLine(lastPoint, pnt.copy(), lastColor._clone(), color._clone()); + lastColor.a = 0; + color.a = 0; + pnt = Planets._orbits[id][i].copy(); + planetDropped = true; + } + pnt = Vector3d.subtractVectors(pnt, centerPoint); + if (firstPoint) { + firstPoint = false; + } + else { + list.addLine(lastPoint, pnt, lastColor, color); + } + lastPoint = pnt; + lastColor = color._clone(); + } + list.drawLines(renderContext, 1, Colors.get_white()); + list.clear(); + } else { + var mu = 0; + switch (id) { + case 9: + mu = muEarth + muMoon; + break; + case 10: + case 11: + case 12: + case 13: + mu = muJupiter; + break; + default: + mu = muSun; + break; + } + var deltaT = 1 / 1440 * 0.1; + var r0 = Planets.getPlanetPositionDirect(id, Planets._jNow); + var r1 = Planets.getPlanetPositionDirect(id, Planets._jNow - deltaT); + var v = Vector3d.scale(Vector3d.subtractVectors(r0, r1), 1 / deltaT); + var elements = Planets._stateVectorToKeplerian(r0, v, mu); + Planets3d._drawSingleOrbitElements(renderContext, eclipticColor, id, centerPoint, startAngle, planetNow, elements); + } + } +}; + +Planets3d._drawSingleOrbitElements = function (renderContext, eclipticColor, id, centerPoint, xstartAngle, planetNow, el) { + var scaleFactor; + switch (id) { + case 9: + if (Settings.get_active().get_solarSystemScale() > 1) { + scaleFactor = Settings.get_active().get_solarSystemScale() / 2; + } + else { + scaleFactor = 1; + } + break; + case 10: + case 11: + case 12: + case 13: + scaleFactor = Settings.get_active().get_solarSystemScale(); + break; + default: + scaleFactor = 1; + break; + } + var translation = Vector3d.negate(centerPoint); + if (id === 9) { + translation.add(Planets._planet3dLocations[19]); + } + else if (id === 10 || id === 11 || id === 12 || id === 13) { + translation.add(Planets._planet3dLocations[4]); + } + var currentPosition = Vector3d.subtractVectors(planetNow, centerPoint); + var worldMatrix = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(el.orientation, Matrix3d.translation(translation)), renderContext.get_world()); + EllipseRenderer.drawEllipseWithPosition(renderContext, el.a / 149598000 * scaleFactor, el.e, el.ea, eclipticColor, worldMatrix, currentPosition); +}; + +Planets3d.isPlanetInFrustum = function (renderContext, rad) { + var frustum = renderContext.get_frustum(); + var center = Vector3d.create(0, 0, 0); + var centerV4 = new Vector4d(0, 0, 0, 1); + for (var i = 0; i < 6; i++) { + if (frustum[i].dot(centerV4) + rad < 0) { + return false; + } + } + return true; +}; + +Planets3d._drawPlanet3d = function (renderContext, planetID, centerPoint) { + if (planetID === 0) { + TileShader.minLightingBrightness = 1; + } + else { + TileShader.minLightingBrightness = 0.025; + if (planetID === 19) { + TileShader.atmosphereColor = Color.fromArgb(255, 65, 157, 217); + } else { + TileShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); + } + } + var matOld = renderContext.get_world(); + var matOldBase = renderContext.get_worldBase(); + var matOldNonRotating = renderContext.get_worldBaseNonRotating(); + var radius = Planets.getAdjustedPlanetRadius(planetID); + Planets.setupPlanetMatrix(renderContext, planetID, centerPoint, true); + var planetWidth = 1; + if (planetID === 5) { + planetWidth = 3; + } + if (Planets3d.isPlanetInFrustum(renderContext, planetWidth)) { + // Save all matrices modified by SetupMatrix... + var matOld2 = renderContext.get_world(); + var matOldBase2 = renderContext.get_worldBase(); + var matOldNonRotating2 = renderContext.get_worldBaseNonRotating(); + var sun = Planets._planet3dLocations[0].copy(); + var planet = Planets._planet3dLocations[planetID].copy(); + sun = matOld.transform(sun); + planet = matOld.transform(planet); + renderContext.set_world(matOld); + renderContext.set_worldBase(matOldBase); + renderContext.set_worldBaseNonRotating(matOldNonRotating); + Planets._setupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, true); + var sunPosition = Vector3d.subtractVectors(sun, planet); + sunPosition.normalize(); + renderContext.set_sunPosition(sunPosition); + TileShader.sunPosition = Vector3d.subtractVectors(Planets._planet3dLocations[0], planet); + var loc = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); + loc.subtract(renderContext.cameraPosition); + var dist = loc.length(); + var sizeIndexParam = (2 * Math.atan(0.5 * (radius / dist))) / Math.PI * 180; + var sizeIndex = 0; + if (sizeIndexParam > 10.5) { + sizeIndex = 0; + } else if (sizeIndexParam > 3.9) { + sizeIndex = 1; + } else if (sizeIndexParam > 0.72) { + sizeIndex = 2; + } else if (sizeIndexParam > 0.05) { + sizeIndex = 3; + } else { + sizeIndex = 4; + } + if (planetID === 19 && sizeIndex < 2) { + var width = Settings.get_active().get_solarSystemScale() * 1E-05; + } + if (sizeIndex < 4) { + var oldLighting = renderContext.lighting; + if (planetID === 5) { + if (renderContext.gl == null) { + renderContext.lighting = false; + // DRAW BACK HALF OF RINGS + Planets3d.drawSaturnsRings(renderContext, false, dist); + renderContext.lighting = oldLighting; + } + } + if (!planetID) { + renderContext.lighting = false; + } + Planets3d._drawSphere(renderContext, planetID); + if (planetID === 5) { + if (renderContext.gl == null) { + renderContext.lighting = false; + // DRAW FRONT HALF OF RINGS + Planets3d.drawSaturnsRings(renderContext, true, dist); + } + else { + renderContext.lighting = false; + Planets3d._drawRings(renderContext); + renderContext.lighting = oldLighting; + } + } + renderContext.lighting = oldLighting; + } else { + if (!planetID) { + BasePlanets.drawPointPlanet(renderContext, new Vector3d(), (10 * Planets._planetDiameters[planetID]), Planets.planetColors[planetID], true); + } + else if (planetID < 9 || planetID === 19) { + var size = (800 * Planets._planetDiameters[planetID]); + BasePlanets.drawPointPlanet(renderContext, new Vector3d(), Math.max(0.05, Math.min(0.1, size)), Planets.planetColors[planetID], true); + } + else if (sizeIndexParam > 0.002) { + var size = (800 * Planets._planetDiameters[planetID]); + BasePlanets.drawPointPlanet(renderContext, new Vector3d(), Math.max(0.05, Math.min(0.1, size)), Planets.planetColors[planetID], true); + } + } + } + LayerManager._draw(renderContext, 1, false, Planets.getNameFrom3dId(planetID), true, false); + renderContext.set_world(matOld); + renderContext.set_worldBase(matOldBase); + renderContext.set_worldBaseNonRotating(matOldNonRotating); +}; + +Planets3d.drawSaturnsRings = function (renderContext, front, distance) { + if (Planets3d._ringsTriangleLists[0] == null) { + Planets3d._ringImage = document.createElement('img'); + var xdomimg = Planets3d._ringImage; + xdomimg.crossOrigin = 'anonymous'; + Planets3d._ringImage.src = URLHelpers.singleton.engineAssetUrl('saturnringsshadow.png'); + Planets3d._ringsTriangleLists[0] = []; + Planets3d._ringsTriangleLists[1] = []; + var ringSize = 2.25; + var TopLeft = Vector3d.create(-ringSize, 0, -ringSize); + var TopRight = Vector3d.create(ringSize, 0, -ringSize); + var BottomLeft = Vector3d.create(-ringSize, 0, ringSize); + var BottomRight = Vector3d.create(ringSize, 0, ringSize); + var center = Vector3d.create(0, 0, 0); + var leftCenter = Vector3d.create(-ringSize, 0, 0); + var topCenter = Vector3d.create(0, 0, -ringSize); + var bottomCenter = Vector3d.create(0, 0, ringSize); + var rightCenter = Vector3d.create(ringSize, 0, 0); + var level = 6; + var vertexList; + vertexList = []; + var Width = 1024; + var Height = 1024; + vertexList.push(PositionTexture.createPosSize(TopLeft, 0, 0, Width, Height)); + vertexList.push(PositionTexture.createPosSize(TopRight, 1, 0, Width, Height)); + vertexList.push(PositionTexture.createPosSize(BottomLeft, 0, 1, Width, Height)); + vertexList.push(PositionTexture.createPosSize(BottomRight, 1, 1, Width, Height)); + var childTriangleList = []; + childTriangleList.push(Triangle.create(0, 2, 1)); + childTriangleList.push(Triangle.create(2, 3, 1)); + var count = 5; + while (count-- > 1) { + var newList = []; + var $enum1 = ss.enumerate(childTriangleList); + while ($enum1.moveNext()) { + var tri = $enum1.current; + tri.subDivideNoNormalize(newList, vertexList); + } + childTriangleList = newList; + } + var miter = 0.6 / (Width / 256); + var $enum2 = ss.enumerate(childTriangleList); + while ($enum2.moveNext()) { + var tri = $enum2.current; + var p1 = vertexList[tri.a]; + var p2 = vertexList[tri.b]; + var p3 = vertexList[tri.c]; + Planets3d._ringsTriangleLists[0].push(RenderTriangle.createWithMiter(p1, p2, p3, Planets3d._ringImage, level, miter)); + } + } + if (renderContext.gl == null) { + var cam = renderContext.cameraPosition; + var test = new Vector3d(); + var worldLocal = Matrix3d.multiplyMatrix(Matrix3d._rotationY(Math.atan2(renderContext.get_sunPosition().x, renderContext.get_sunPosition().z)), renderContext.get_worldBaseNonRotating()); + var wv = Matrix3d.multiplyMatrix(worldLocal, renderContext.get_view()); + var wvp = Matrix3d.multiplyMatrix(wv, renderContext.get_projection()); + var Width = renderContext.width; + var Height = renderContext.height; + wvp.scale(Vector3d.create(Width / 2, -Height / 2, 1)); + wvp.translate(Vector3d.create(Width / 2, Height / 2, 0)); + var td = 0; + for (var i = 0; i < 2; i++) { + var $enum3 = ss.enumerate(Planets3d._ringsTriangleLists[0]); + while ($enum3.moveNext()) { + var tri = $enum3.current; + test = wv.transform(tri.a.position); + td = test.length(); + var draw = td > distance; + if (front) { + draw = !draw; + } + if (draw) { + tri.opacity = 1; + tri.draw(renderContext.device, wvp); + } + } + RenderTriangle.cullInside = !RenderTriangle.cullInside; + } + } + else { } +}; + +// Various input layouts used in 3D solar system mode +// TODO Replace with an input layout cache + +Planets3d._drawRings = function (renderContext) { + Planets3d._initRings(); + TileShader.use(renderContext, Planets3d._ringsVertexBuffer.vertexBuffer, null, Planets._ringsTexture.texture2d, 1, false, Vector3d.zero); + renderContext.gl.drawArrays(WEBGL.TRIANGLE_STRIP, 0, Planets3d._triangleCountRings); +}; + +Planets3d._initRings = function () { + if (Planets3d._ringsVertexBuffer != null) { + return; + } + Planets._ringsTexture = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('saturnringsstrip.png')); + var inner = 1.113; + var outer = 2.25; + Planets3d._ringsVertexBuffer = new PositionTextureVertexBuffer(((192 + 1) * 2)); + Planets3d._triangleCountRings = (192 + 1) * 2; + var verts = Planets3d._ringsVertexBuffer.lock(); + var radStep = Math.PI * 2 / 192; + var index = 0; + for (var x = 0; x <= 192; x += 2) { + var rads1 = x * radStep; + var rads2 = (x + 1) * radStep; + verts[index] = new PositionTexture(); + verts[index].position = Vector3d.create((Math.cos(rads1) * inner), 0, (Math.sin(rads1) * inner)); + verts[index].tu = 1; + verts[index].tv = 0; + index++; + verts[index] = new PositionTexture(); + verts[index].position = Vector3d.create((Math.cos(rads1) * outer), 0, (Math.sin(rads1) * outer)); + verts[index].tu = 0; + verts[index].tv = 0; + index++; + verts[index] = new PositionTexture(); + verts[index].position = Vector3d.create((Math.cos(rads2) * inner), 0, (Math.sin(rads2) * inner)); + verts[index].tu = 1; + verts[index].tv = 1; + index++; + verts[index] = new PositionTexture(); + verts[index].position = Vector3d.create((Math.cos(rads2) * outer), 0, (Math.sin(rads2) * outer)); + verts[index].tu = 0; + verts[index].tv = 1; + index++; + } + Planets3d._ringsVertexBuffer.unlock(); +}; + +Planets3d._drawSphere = function (renderContext, planetID) { + var planetName = Planets3d.getImageSetNameNameFrom3dId(planetID); + var planet = globalWWTControl.getImagesetByName(planetName); + if (planet == null) { + planet = globalWWTControl.getImagesetByName('Bing Maps Aerial'); + } + if (planet != null) { + renderContext.drawImageSet(planet, 100); + if (planetID === 19) { + } + return; + } +}; + +registerType("Planets3d", [Planets3d, {}, null]); diff --git a/engine/esm/plot_tile.js b/engine/esm/plot_tile.js new file mode 100644 index 00000000..c8aecf09 --- /dev/null +++ b/engine/esm/plot_tile.js @@ -0,0 +1,266 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile that plots tabular data. +// +// This tile class is not implemented for the WebGL rendering backend! + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { tileCacheRemoveFromQueue, tileCacheGetTile, tileUvMultiple } from "./render_globals.js"; +import { Vector2d, Vector3d, PositionTexture } from "./double3d.js"; +import { BasePlanets } from "./baseplanets.js"; +import { Coordinates } from "./coordinates.js"; +import { Star } from "./star.js"; +import { URLHelpers } from "./url_helpers.js"; +import { WebFile } from "./web_file.js"; +import { Tile } from "./tile.js"; + + +// wwtlib.PlotTile + +export function PlotTile() { + this._topDown$1 = true; + this.backslash = false; + this._vertexList$1 = null; + this._childTriangleList$1 = null; + this._stars$1 = []; + this._subDivisionLevel$1 = 4; + this._subDivided$1 = false; + Tile.call(this); +} + +PlotTile.create = function (level, xc, yc, dataset, parent) { + var temp = new PlotTile(); + temp.parent = parent; + temp.level = level; + temp.tileX = xc; + temp.tileY = yc; + temp.dataset = dataset; + temp._topDown$1 = !dataset.get_bottomsUp(); + if (temp.tileX !== xc) { + alert('bad'); + } + if (!!dataset.get_meanRadius()) { + temp.set__demScaleFactor(dataset.get_meanRadius()); + } + else { + if (!dataset.get_dataSetType()) { + temp.set__demScaleFactor(6371000); + } else { + temp.set__demScaleFactor(3396010); + } + } + temp.computeBoundingSphere(); + return temp; +}; + +var PlotTile$ = { + computeBoundingSphere: function () { + this._initializeGrids$1(); + this.topLeft = this.bounds[0 + 3 * 0].position.copy(); + this.bottomRight = this.bounds[2 + 3 * 2].position.copy(); + this.topRight = this.bounds[2 + 3 * 0].position.copy(); + this.bottomLeft = this.bounds[0 + 3 * 2].position.copy(); + this.calcSphere(); + }, + + renderPart: function (renderContext, part, opacity, combine) { + if (renderContext.gl != null) { + //todo draw in WebGL + } else { + if (!part) { + var $enum1 = ss.enumerate(this._stars$1); + while ($enum1.moveNext()) { + var star = $enum1.current; + var radDec = 25 / Math.pow(1.6, star.magnitude); + BasePlanets.drawPointPlanet(renderContext, star.position, radDec, star.col, false); + } + } + } + }, + + requestImage: function () { + if (!this.downloading && !this.readyToRender) { + this.downloading = true; + this._webFile$1 = new WebFile(URLHelpers.singleton.rewrite(this.get_URL(), 0)); + this._webFile$1.onStateChange = ss.bind('fileStateChange', this); + this._webFile$1.send(); + } + }, + + fileStateChange: function () { + if (this._webFile$1.get_state() === 2) { + this.downloading = false; + this.readyToRender = false; + this.errored = true; + this.requestPending = false; + tileCacheRemoveFromQueue(this.get_key(), true); + } else if (this._webFile$1.get_state() === 1) { + this.texReady = true; + this.downloading = false; + this.errored = false; + this.readyToRender = this.texReady && (this.demReady || !this.demTile); + this.requestPending = false; + tileCacheRemoveFromQueue(this.get_key(), true); + this._loadData$1(this._webFile$1.getText()); + } + }, + + _loadData$1: function (data) { + var rows = ss.replaceString(data, '\r\n', '\n').split('\n'); + var firstRow = true; + var type = 0; + var star = null; + var $enum1 = ss.enumerate(rows); + while ($enum1.moveNext()) { + var row = $enum1.current; + if (firstRow) { + firstRow = false; + continue; + } + if (ss.trim(row).length > 5) { + star = new Star(row); + star.position = Coordinates.raDecTo3dAu(star.RA, star.dec, 1); + this._stars$1.push(star); + } + } + }, + + isPointInTile: function (lat, lng) { + if (!this.level) { + return true; + } + if (this.level === 1) { + if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { + return true; + } + if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { + return true; + } + if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { + return true; + } + if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { + return true; + } + return false; + } + if (!this.demReady || this.demData == null) { + return false; + } + var testPoint = Coordinates.geoTo3dDouble(-lat, lng); + var top = this._isLeftOfHalfSpace$1(this.topLeft.copy(), this.topRight.copy(), testPoint); + var right = this._isLeftOfHalfSpace$1(this.topRight.copy(), this.bottomRight.copy(), testPoint); + var bottom = this._isLeftOfHalfSpace$1(this.bottomRight.copy(), this.bottomLeft.copy(), testPoint); + var left = this._isLeftOfHalfSpace$1(this.bottomLeft.copy(), this.topLeft.copy(), testPoint); + if (top && right && bottom && left) { + return true; + } + return false; + }, + + _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { + pntA.normalize(); + pntB.normalize(); + var cross = Vector3d.cross(pntA, pntB); + var dot = Vector3d.dot(cross, pntTest); + return dot < 0; + }, + + _initializeGrids$1: function () { + this._vertexList$1 = []; + this._childTriangleList$1 = new Array(4); + this._childTriangleList$1[0] = []; + this._childTriangleList$1[1] = []; + this._childTriangleList$1[2] = []; + this._childTriangleList$1[3] = []; + this.bounds = new Array(9); + if (this.level > 0) { + if (this.parent == null) { + this.parent = tileCacheGetTile(this.level - 1, this.tileX / 2, this.tileY / 2, this.dataset, null); + } + var parent = this.parent; + var xIndex = this.tileX % 2; + var yIndex = this.tileY % 2; + if (this.level > 1) { + this.backslash = parent.backslash; + } + else { + this.backslash = (xIndex === 1 ^ yIndex === 1) === 1; + } + this.bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].copy(); + this.bounds[1 + 3 * 0] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); + this.bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].copy(); + this.bounds[0 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); + if (this.backslash) { + this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + } + else { + this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); + } + this.bounds[2 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + this.bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].copy(); + this.bounds[1 + 3 * 2] = this._midpoint$1(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + this.bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].copy(); + this.bounds[0 + 3 * 0].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[1 + 3 * 0].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[2 + 3 * 0].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[0 + 3 * 1].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 1].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[2 + 3 * 1].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[0 + 3 * 2].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 2].tv = 1 * tileUvMultiple; + this.bounds[1 + 3 * 2].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 2].tv = 1 * tileUvMultiple; + this.bounds[2 + 3 * 2].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 2].tv = 1 * tileUvMultiple; + } else { + this.bounds[0 + 3 * 0] = PositionTexture.create(0, -1, 0, 0, 0); + this.bounds[1 + 3 * 0] = PositionTexture.create(0, 0, 1, 0.5, 0); + this.bounds[2 + 3 * 0] = PositionTexture.create(0, -1, 0, 1, 0); + this.bounds[0 + 3 * 1] = PositionTexture.create(-1, 0, 0, 0, 0.5); + this.bounds[1 + 3 * 1] = PositionTexture.create(0, 1, 0, 0.5, 0.5); + this.bounds[2 + 3 * 1] = PositionTexture.create(1, 0, 0, 1, 0.5); + this.bounds[0 + 3 * 2] = PositionTexture.create(0, -1, 0, 0, 1); + this.bounds[1 + 3 * 2] = PositionTexture.create(0, 0, -1, 0.5, 1); + this.bounds[2 + 3 * 2] = PositionTexture.create(0, -1, 0, 1, 1); + } + }, + + _midpoint$1: function (positionNormalTextured, positionNormalTextured_2) { + var a1 = Vector3d.lerp(positionNormalTextured.position, positionNormalTextured_2.position, 0.5); + var a1uv = Vector2d.lerp(Vector2d.create(positionNormalTextured.tu, positionNormalTextured.tv), Vector2d.create(positionNormalTextured_2.tu, positionNormalTextured_2.tv), 0.5); + a1.normalize(); + return PositionTexture.createPos(a1, a1uv.x, a1uv.y); + }, + + createGeometry: function (renderContext) { + if (this.geometryCreated) { + return true; + } + this.geometryCreated = true; + Tile.prototype.createGeometry.call(this, renderContext); + return true; + }, + + cleanUp: function (removeFromParent) { + Tile.prototype.cleanUp.call(this, removeFromParent); + if (this._vertexList$1 != null) { + this._vertexList$1 = null; + } + if (this._childTriangleList$1 != null) { + this._childTriangleList$1 = null; + } + this._subDivided$1 = false; + this.demArray = null; + } +}; + +registerType("PlotTile", [PlotTile, PlotTile$, Tile]); diff --git a/engine/esm/pointing.js b/engine/esm/pointing.js new file mode 100644 index 00000000..29900896 --- /dev/null +++ b/engine/esm/pointing.js @@ -0,0 +1,54 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A lat/lon datatype. This is unused in the engine, but preserved for API +// compatibility. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { HealpixUtils } from "./healpix_utils.js"; + + +// wwtlib.Pointing + +export function Pointing() { + // Colatitude in radians (0 is North Pole; Pi is South Pole) + this.theta = 0; + + // Longitude in radians + this.phi = 0; +} + +Pointing.create = function (theta, phi) { + var temp = new Pointing(); + temp.theta = theta; + temp.phi = phi; + return temp; +}; + +var Pointing$ = { + normalizeTheta: function () { + this.theta = HealpixUtils.fmodulo(this.theta, 2 * Math.PI); + if (this.theta > Math.PI) { + this.phi += Math.PI; + this.theta = 2 * Math.PI - this.theta; + } + }, + + normalize: function () { + this.normalizeTheta(); + this.phi = HealpixUtils.fmodulo(this.phi, 2 * Math.PI); + }, + + toString: function () { + var s = new ss.StringBuilder(); + s.append('ptg('); + s.append(this.theta); + s.append(','); + s.append(this.phi); + s.append(')'); + return s.toString(); + } +}; + +registerType("Pointing", [Pointing, Pointing$, null]); diff --git a/engine/esm/render_context.js b/engine/esm/render_context.js new file mode 100644 index 00000000..f8cdedaa --- /dev/null +++ b/engine/esm/render_context.js @@ -0,0 +1,978 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The main engine renderer implementation. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d, Matrix3d, PlaneD } from "./double3d.js"; +import { globalWWTControl, makeNewHipsProperties } from "./data_globals.js"; +import { set_tileDemEnabled, set_tileUvMultiple, tileCacheGetTile } from "./render_globals.js"; +import { Util } from "./baseutil.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { TileShader } from "./graphics/shaders.js"; +import { CameraParameters } from "./camera_parameters.js"; +import { Colors } from "./color.js"; +import { Coordinates } from "./coordinates.js"; +import { ProjectionType, ImageSetType } from "./imageset.js"; +import { Planets } from "./planets.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Settings } from "./settings.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { CatalogSpreadSheetLayer } from "./layers/spreadsheet_layer.js"; +import { LayerManager } from "./layers/layer_manager.js"; + + +// wwtlib.InViewReturnMessage + +export function InViewReturnMessage() { + this.aborted = false; +} + +var InViewReturnMessage$ = {}; + +registerType("InViewReturnMessage", [InViewReturnMessage, InViewReturnMessage$, null]); + + +// wwtlib.RenderContext + +export function RenderContext() { + this.height = 0; + this.width = 0; + this.lighting = false; + this._viewPoint = new Vector3d(); + this.space = false; + this._fovAngle = 0; + this._fovScale = 0; + this._nominalRadius = 6378137; + this._mainTexture = null; + this.viewMover = null; + this.viewCamera = new CameraParameters(); + this.targetCamera = new CameraParameters(); + this.alt = 0; + this.az = 0; + this.targetAlt = 0; + this.targetAz = 0; + this._backgroundImageset = null; + this._foregroundImageset = null; + this._activeCatalogHipsImagesets = []; + this._targetHeight = 1; + this.targetAltitude = 0; + this._galactic = true; + this._galacticMatrix = Matrix3d.create(-0.4838350155, -0.0548755604, -0.8734370902, 0, 0.7469822445, 0.4941094279, -0.44482963, 0, 0.4559837762, -0.867666149, -0.1980763734, 0, 0, 0, 0, 1); + this._firstTimeInit = false; + this._useSolarSystemTilt = true; + this.customTrackingParams = new CameraParameters(); + this._cameraOffset = new Vector3d(); + this._fovLocal = (Math.PI / 4); + this.perspectiveFov = Math.PI / 4; + this.nearPlane = 0; + this._frustumDirty = true; + this._frustum = new Array(6); + this._ambientLightColor = Colors.get_black(); + this._hemiLightColor = Colors.get_black(); + this._hemiLightUp = new Vector3d(); + this._sunlightColor = Colors.get_white(); + this._sunPosition = new Vector3d(); + this._reflectedLightColor = Colors.get_black(); + this._reflectedLightPosition = new Vector3d(); + this._occludingPlanetRadius = 0; + this._occludingPlanetPosition = new Vector3d(); + this._lightingStateDirty = true; + this._twoSidedLighting = false; + this.cameraPosition = new Vector3d(); + this._skyColor = 'Blue'; + for (var i = 0; i < 6; i++) { + this._frustum[i] = new PlaneD(0, 0, 0, 0); + } +} + +RenderContext.back = 0; + +RenderContext.create = function (device) { + var temp = new RenderContext(); + temp.device = device; + temp.viewCamera.zoom = 700; + temp.viewCamera.target = 65536; + return temp; +}; + +RenderContext.getTilesYForLevel = function (layer, level) { + var maxY = 1; + switch (layer.get_projection()) { + case ProjectionType.mercator: + maxY = Math.pow(2, level); + break; + case ProjectionType.equirectangular: + maxY = (Math.pow(2, level) * (180 / layer.get_baseTileDegrees())); + break; + case ProjectionType.tangent: + maxY = Math.pow(2, level); + break; + case ProjectionType.spherical: + maxY = 1; + break; + case ProjectionType.healpix: + maxY = 4 * Math.pow(2, level); + break; + default: + maxY = Math.pow(2, level); + break; + } + if (maxY === Number.POSITIVE_INFINITY) { + maxY = 1; + } + return maxY; +}; + +RenderContext.getTilesXForLevel = function (layer, level) { + var maxX = 1; + switch (layer.get_projection()) { + case ProjectionType.plotted: + case ProjectionType.toast: + maxX = Math.pow(2, level); + break; + case ProjectionType.mercator: + maxX = Math.pow(2, level) * ss.truncate((layer.get_baseTileDegrees() / 360)); + break; + case ProjectionType.equirectangular: + maxX = Math.pow(2, level) * ss.truncate((360 / layer.get_baseTileDegrees())); + break; + case ProjectionType.tangent: + if (layer.get_widthFactor() === 1) { + maxX = Math.pow(2, level) * 2; + } + else { + maxX = Math.pow(2, level); + } + break; + case ProjectionType.skyImage: + maxX = 1; + break; + case ProjectionType.spherical: + maxX = 1; + break; + case ProjectionType.healpix: + maxX = Math.pow(2, level) * 3; + break; + default: + maxX = Math.pow(2, level) * 2; + break; + } + return maxX; +}; + +var RenderContext$ = { + save: function () { + if (this.gl != null) { + } else { + this.device.save(); + } + }, + + restore: function () { + if (this.gl != null) { + } else { + this.device.restore(); + } + }, + + clear: function () { + if (this.gl != null) { + this.gl.viewport(0, 0, ss.truncate(this.width), ss.truncate(this.height)); + this.gl.clear(WEBGL.COLOR_BUFFER_BIT | WEBGL.DEPTH_BUFFER_BIT); + } else { + this.device.save(); + this.device.fillStyle = 'black'; + this.device.fillRect(0, 0, this.width, this.height); + this.device.restore(); + } + }, + + get_viewPoint: function () { + return this._viewPoint; + }, + + get_RA: function () { + return ((((180 - (this.viewCamera.lng - 180)) / 15) % 24) + 48) % 24; + }, + + rAtoViewLng: function (ra) { + return 180 - (ra / 24 * 360) - 180; + }, + + get_dec: function () { + return this.viewCamera.lat; + }, + + get_fovAngle: function () { + return this._fovAngle; + }, + + get_fovScale: function () { + return this._fovScale; + }, + + set_fovScale: function (value) { + this._fovScale = value; + return value; + }, + + get_view: function () { + return this._view; + }, + + set_view: function (value) { + this._view = value; + this._frustumDirty = true; + return value; + }, + + get_viewBase: function () { + return this._viewBase; + }, + + set_viewBase: function (value) { + this._viewBase = value; + return value; + }, + + get_projection: function () { + return this._projection; + }, + + set_projection: function (value) { + this._projection = value; + this._frustumDirty = true; + return value; + }, + + get_world: function () { + return this._world; + }, + + set_world: function (value) { + this._world = value; + this._frustumDirty = true; + return value; + }, + + _getScreenTexture: function () { + //todo add code to capture screen + var tex = null; + return tex; + }, + + get_worldBase: function () { + return this._worldBase; + }, + + set_worldBase: function (value) { + this._worldBase = value; + return value; + }, + + get_worldBaseNonRotating: function () { + return this._worldBaseNonRotating; + }, + + set_worldBaseNonRotating: function (value) { + this._worldBaseNonRotating = value; + return value; + }, + + get_nominalRadius: function () { + return this._nominalRadius; + }, + + set_nominalRadius: function (value) { + this._nominalRadius = value; + return value; + }, + + get_mainTexture: function () { + return this._mainTexture; + }, + + set_mainTexture: function (value) { + if (value != null) { + this._mainTexture = value; + this.gl.bindTexture(WEBGL.TEXTURE_2D, this._mainTexture.texture2d); + } + return value; + }, + + onTarget: function (place) { + return ((Math.abs(this.viewCamera.lat - this.targetCamera.lat) < 1E-12 && Math.abs(this.viewCamera.lng - this.targetCamera.lng) < 1E-12 && Math.abs(this.viewCamera.zoom - this.targetCamera.zoom) < 1E-12) && this.viewMover == null); + }, + + setTexture: function (texture) { }, + + get_backgroundImageset: function () { + return this._backgroundImageset; + }, + + set_backgroundImageset: function (value) { + var viewModeChanged = this._backgroundImageset != null && value != null && (this._backgroundImageset.get_dataSetType() !== value.get_dataSetType()); + this._backgroundImageset = value; + + if (viewModeChanged) { + //Prevent potential artifacts when going from 3D to Sky/Pan + globalWWTControl._freezeView(); + globalWWTControl.clampZooms(this); + } + return value; + }, + + get_foregroundImageset: function () { + return this._foregroundImageset; + }, + + set_foregroundImageset: function (value) { + this._foregroundImageset = value; + return value; + }, + + get_catalogHipsImagesets: function () { + return this._activeCatalogHipsImagesets; + }, + + getCatalogHipsDataInView: function (imageset, limit, onComplete) { + var $this = this; + + var layer = new CatalogSpreadSheetLayer(); + var onHeaderInfoLoad = function () { + layer.useHeadersFromVoTable(imageset.get_hipsProperties().get_catalogColumnInfo()); + $this._tryGetAllDataInView(imageset, limit, layer, onComplete, 0); + }; + if (imageset.get_hipsProperties() == null) { + imageset.set_hipsProperties(makeNewHipsProperties(imageset)); + imageset.get_hipsProperties().setDownloadCompleteListener(onHeaderInfoLoad); + } else if (imageset.get_hipsProperties() != null && imageset.get_hipsProperties().get_downloadComplete()) { + onHeaderInfoLoad(); + } else { + imageset.get_hipsProperties().setDownloadCompleteListener(onHeaderInfoLoad); + } + }, + + _tryGetAllDataInView: function (imageset, limit, catalogSpreadSheetLayer, onComplete, i) { + var $this = this; + + var maxX = RenderContext.getTilesXForLevel(imageset, imageset.get_baseLevel()); + var maxY = RenderContext.getTilesYForLevel(imageset, imageset.get_baseLevel()); + var anyTileStillDownloading = false; + for (var x = 0; x < maxX; x++) { + for (var y = 0; y < maxY; y++) { + var tile = tileCacheGetTile(imageset.get_baseLevel(), x, y, imageset, null); + if (tile != null) { + var tileAndChildrenReady = (tile).getDataInView(this, limit, catalogSpreadSheetLayer); + anyTileStillDownloading = anyTileStillDownloading || !tileAndChildrenReady; + } + else { + anyTileStillDownloading = true; + } + } + } + if (anyTileStillDownloading) { + var count = catalogSpreadSheetLayer.get__table().rows.length; + if ((count > 10000 || i > 100 * 60 * 5) && limit) { + console.log('Too Many results - Aborting'); + console.log(count); + var returnMessage = new InViewReturnMessage(); + returnMessage.aborted = true; + returnMessage.table = catalogSpreadSheetLayer.getTableDataInView(); + onComplete(returnMessage); + catalogSpreadSheetLayer.cleanUp(); + } + else { + setTimeout(function () { + $this._tryGetAllDataInView(imageset, limit, catalogSpreadSheetLayer, onComplete, i); + }, 10); + if (!(i % 200)) { + console.log('Waiting for more tiles to load'); + console.log(count); + } + i++; + } + } else { + var count = catalogSpreadSheetLayer.get__table().rows.length; + console.log('Done!'); + console.log(count); + var returnMessage = new InViewReturnMessage(); + returnMessage.aborted = false; + returnMessage.table = catalogSpreadSheetLayer.getTableDataInView(); + onComplete(returnMessage); + catalogSpreadSheetLayer.cleanUp(); + } + }, + + addCatalogHips: function (imageset, onLoad) { + if (!(this._activeCatalogHipsImagesets.indexOf(imageset) >= 0)) { + this._activeCatalogHipsImagesets.push(imageset); + } + if (imageset.get_hipsProperties() == null) { + imageset.set_hipsProperties(makeNewHipsProperties(imageset)); + imageset.get_hipsProperties().setDownloadCompleteListener(onLoad); + } else if (imageset.get_hipsProperties() != null && imageset.get_hipsProperties().get_downloadComplete()) { + LayerManager.addSpreadsheetLayer(imageset.get_hipsProperties().get_catalogSpreadSheetLayer(), 'Sky'); + if (onLoad != null) { + onLoad(); + } + } + }, + + removeCatalogHips: function (imageset) { + ss.remove(this._activeCatalogHipsImagesets, imageset); + if (imageset.get_hipsProperties() != null) { + LayerManager.deleteLayerByID(imageset.get_hipsProperties().get_catalogSpreadSheetLayer().id, true, true); + } + }, + + getCatalogHipsByName: function (name) { + var $enum1 = ss.enumerate(this._activeCatalogHipsImagesets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_name() === name) { + return imageset; + } + } + return null; + }, + + getAltitudeForLatLongForPlanet: function (planetID, viewLat, viewLong) { + var layer = globalWWTControl.getImagesetByName(Planets.getNameFrom3dId(planetID)); + if (layer == null) { + return 0; + } + var maxX = RenderContext.getTilesXForLevel(layer, layer.get_baseLevel()); + var maxY = RenderContext.getTilesYForLevel(layer, layer.get_baseLevel()); + for (var x = 0; x < maxX; x++) { + for (var y = 0; y < maxY; y++) { + var tile = tileCacheGetTile(layer.get_baseLevel(), x, y, layer, null); + if (tile != null) { + if (tile.isPointInTile(viewLat, viewLong)) { + return tile.getSurfacePointAltitude(viewLat, viewLong, true); + } + } + } + } + return 0; + }, + + getEarthAltitude: function (ViewLat, ViewLong, meters) { + if (globalWWTControl.get_solarSystemMode()) { + var pnt = Coordinates.geoTo3dDouble(ViewLat, ViewLong + 90); + var EarthMat = Planets.earthMatrixInv; + pnt = Vector3d._transformCoordinate(pnt, EarthMat); + pnt.normalize(); + var point = Coordinates.cartesianToLatLng(pnt); + return this.getAltitudeForLatLongForPlanet(this.viewCamera.target, point.y, point.x); + } else if (this.get_backgroundImageset().get_dataSetType() != ImageSetType.earth) { + return (meters) ? this.getMetersAltitudeForLatLong(ViewLat, ViewLong) : this.getScaledAltitudeForLatLong(ViewLat, ViewLong); + } else { + return 0; + } + }, + + drawImageSet: function (imageset, opacity) { + var maxX = RenderContext.getTilesXForLevel(imageset, imageset.get_baseLevel()); + var maxY = RenderContext.getTilesYForLevel(imageset, imageset.get_baseLevel()); + for (var x = 0; x < maxX; x++) { + for (var y = 0; y < maxY; y++) { + var tile = tileCacheGetTile(imageset.get_baseLevel(), x, y, imageset, null); + if (tile != null) { + tile.draw3D(this, opacity); + } + } + } + }, + + _getTileAtLatLong: function (viewLat, viewLong) { + var layer = this.get_backgroundImageset(); + if (layer == null) { + return null; + } + var maxX = RenderContext.getTilesXForLevel(layer, layer.get_baseLevel()); + var maxY = RenderContext.getTilesYForLevel(layer, layer.get_baseLevel()); + for (var x = 0; x < maxX; x++) { + for (var y = 0; y < maxY; y++) { + var tile = tileCacheGetTile(layer.get_baseLevel(), x, y, layer, null); + if (tile != null) { + if (tile.isPointInTile(viewLat, viewLong)) { + return tile; + } + } + } + } + return null; + }, + + getScaledAltitudeForLatLong: function (viewLat, viewLong) { + var tile = this._getTileAtLatLong(viewLat, viewLong); + if (tile != null) { + return tile.getSurfacePointAltitude(viewLat, viewLong, false); + } + return 0; + }, + + getMetersAltitudeForLatLong: function (viewLat, viewLong) { + var tile = this._getTileAtLatLong(viewLat, viewLong); + if (tile != null) { + return tile.getSurfacePointAltitude(viewLat, viewLong, true); + } + return 0; + }, + + _setupMatricesLand3d: function () { + this.lighting = false; + this.space = false; + RenderTriangle.cullInside = false; + + // For our world matrix, we will just rotate the Earth and Clouds about the y-axis. + var WorldMatrix = Matrix3d._rotationY(((this.viewCamera.lng - 90) / 180 * Math.PI)); + WorldMatrix._multiply(Matrix3d._rotationX(((-this.viewCamera.lat) / 180 * Math.PI))); + this.set_world(WorldMatrix); + this.set_worldBase(WorldMatrix.clone()); + this._viewPoint = Coordinates.geoTo3d(this.viewCamera.lat, this.viewCamera.lng); + var distance = 0; + if (this._backgroundImageset.get_isMandelbrot()) { + distance = (4 * (this.viewCamera.zoom / 180)) + 1E-41; + } else { + distance = (4 * (this.viewCamera.zoom / 180)) + 1E-06; + } + this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; + this._fovScale = (this._fovAngle / this.height) * 3600; + if (this.gl != null) { + this.targetAltitude = this.getScaledAltitudeForLatLong(this.viewCamera.lat, this.viewCamera.lng); + var heightNow = 1 + this.targetAltitude; + this.targetAltitude *= this.get_nominalRadius(); + if (this._targetHeight < heightNow) { + this._targetHeight = (((this._targetHeight * 2) + heightNow) / 3); + } + else { + this._targetHeight = (((this._targetHeight * 9) + heightNow) / 10); + } + } else { + this.targetAltitude = 0; + this._targetHeight = 1; + } + var rotLocal = this.viewCamera.rotation; + this.cameraPosition = Vector3d.create((Math.sin(rotLocal) * Math.sin(this.viewCamera.angle) * distance), (Math.cos(rotLocal) * Math.sin(this.viewCamera.angle) * distance), (-this._targetHeight - (Math.cos(this.viewCamera.angle) * distance))); + var cameraTarget = Vector3d.create(0, 0, -this._targetHeight); + var camHeight = this.cameraPosition.length(); + var lookUp = Vector3d.create(Math.sin(rotLocal) * Math.cos(this.viewCamera.angle), Math.cos(rotLocal) * Math.cos(this.viewCamera.angle), Math.sin(this.viewCamera.angle)); + this.set_view(Matrix3d.lookAtLH(this.cameraPosition, cameraTarget, lookUp)); + this.set_viewBase(this.get_view()); + var back = Math.sqrt((distance + 1) * (distance + 1) - 1); + back = Math.max(0.5, back); + var m_nearPlane = distance * 0.05; + m_nearPlane = distance * 0.05; + this.set_projection(Matrix3d.perspectiveFovLH((Math.PI / 4), this.width / this.height, m_nearPlane, back)); + this._setMatrixes(); + this.makeFrustum(); + }, + + setupMatricesSpace3d: function (canvasWidth, canvasHeight) { + this.lighting = false; + if (!this._firstTimeInit) { + this._galacticMatrix = Matrix3d.get_identity(); + this._galacticMatrix._multiply(Matrix3d._rotationY(-(270 - (17.7603329867975 * 15)) / 180 * Math.PI)); + this._galacticMatrix._multiply(Matrix3d._rotationX(-(-28.9361739586894) / 180 * Math.PI)); + this._galacticMatrix._multiply(Matrix3d._rotationZ(((31.422052860102) - 90) / 180 * Math.PI)); + this._firstTimeInit = true; + } + this.space = true; + RenderTriangle.cullInside = true; + var WorldMatrix = Matrix3d.get_identity(); + if (Settings.get_active().get_galacticMode()) { + WorldMatrix._multiply(this._galacticMatrix); + WorldMatrix._multiply(Matrix3d._rotationY(this.az / 180 * Math.PI)); + WorldMatrix._multiply(Matrix3d._rotationX(-this.alt / 180 * Math.PI)); + var gPoint = Coordinates.galactictoJ2000(this.az, this.alt); + this._viewPoint = Coordinates.raDecTo3dAu(gPoint[0] / 15, gPoint[1], 1); + this.targetCamera.lng = this.rAtoViewLng(gPoint[0] / 15); + this.targetCamera.lat = gPoint[1]; + this.viewCamera.lat = this.targetCamera.lat; + this.viewCamera.lng = this.targetCamera.lng; + } else { + WorldMatrix._multiply(Matrix3d._rotationY(-(this.viewCamera.lng - 90) / 180 * Math.PI)); + WorldMatrix._multiply(Matrix3d._rotationX(-this.viewCamera.lat / 180 * Math.PI)); + this._viewPoint = Coordinates.raDecTo3dAu(this.get_RA(), this.get_dec(), 1); + } + var camLocal = this.viewCamera.rotation; + this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; + this._fovScale = (this._fovAngle / canvasHeight) * 3600; + + // altaz + if (Settings.get_active().get_localHorizonMode() && this._backgroundImageset.get_dataSetType() == ImageSetType.sky) { + var zenithAltAz = new Coordinates(0, 0); + zenithAltAz.set_az(0); + zenithAltAz.set_alt(0); + var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); + var raPart = -((zenith.get_RA() - 6) / 24 * (Math.PI * 2)); + var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); + var raText = Coordinates.formatDMS(zenith.get_RA()); + WorldMatrix = Matrix3d._rotationY(-raPart - Math.PI); + WorldMatrix._multiply(Matrix3d._rotationX(decPart)); + if (SpaceTimeController.get_location().get_lat() < 0) { + WorldMatrix._multiply(Matrix3d._rotationY((this.az / 180 * Math.PI))); + WorldMatrix._multiply(Matrix3d._rotationX((this.alt / 180 * Math.PI))); + camLocal += Math.PI; + } + else { + WorldMatrix._multiply(Matrix3d._rotationY(((-this.az) / 180 * Math.PI))); + WorldMatrix._multiply(Matrix3d._rotationX(((-this.alt) / 180 * Math.PI))); + } + var currentRaDec = Coordinates.horizonToEquitorial(Coordinates.fromLatLng(this.alt, this.az), SpaceTimeController.get_location(), SpaceTimeController.get_now()); + this.viewCamera.lat = this.targetCamera.lat = currentRaDec.get_dec(); + this.viewCamera.lng = this.targetCamera.lng = this.rAtoViewLng(currentRaDec.get_RA()); + } + this.set_world(WorldMatrix); + this.set_worldBase(WorldMatrix.clone()); + var localZoomFactor = this.viewCamera.zoom; + var FovAngle = (localZoomFactor / 343.774) / Math.PI * 180; + this.cameraPosition = Vector3d.create(0, 0, 0); + + // This is for distance Calculation. For space everything is the same distance, so camera target is key. + this.set_view(Matrix3d.lookAtLH(this.cameraPosition, Vector3d.create(0, 0, -1), Vector3d.create(Math.sin(camLocal), Math.cos(camLocal), 0))); + this.set_viewBase(this.get_view().clone()); + var m_nearPlane = 0.1; + this.nearPlane = 0.1; + this.set_projection(Matrix3d.perspectiveFovLH(localZoomFactor / 343.774, canvasWidth / canvasHeight, 0.1, -2)); + this._setMatrixes(); + this.makeFrustum(); + }, + + get_solarSystemTrack: function () { + return this.viewCamera.target; + }, + + set_solarSystemTrack: function (value) { + this.viewCamera.target = value; + return value; + }, + + get_solarSystemCameraDistance: function () { + return (4 * (this.viewCamera.zoom / 9)) + 1E-06; + }, + + get_sandboxMode: function () { + if (this._backgroundImageset == null) { + return false; + } + return this._backgroundImageset.get_dataSetType() === ImageSetType.sandbox; + }, + + get_trackingFrame: function () { + return this.viewCamera.targetReferenceFrame; + }, + + set_trackingFrame: function (value) { + this.viewCamera.targetReferenceFrame = value; + return value; + }, + + get_fovLocal: function () { + return this._fovLocal; + }, + + set_fovLocal: function (value) { + this._fovLocal = value; + return value; + }, + + setupMatricesOverlays: function () { + this.set_world(Matrix3d.get_identity()); + var lookAtAdjust = Matrix3d.get_identity(); + var lookFrom = Vector3d.create(0, 0, 0); + var lookAt = Vector3d.create(0, 0, 1); + var lookUp = Vector3d.create(0, 1, 0); + var view; + view = Matrix3d.lookAtLH(lookFrom, lookAt, lookUp); + view._multiply(Matrix3d._scaling(1, -1, 1)); + this.set_view(view); + var back = 10000; + this.nearPlane = 0.1; + this.set_projection(Matrix3d.perspectiveFovLH(this._fovLocal, this.width / this.height, this.nearPlane, back)); + }, + + setupMatricesSolarSystem: function (forStars) { + this.lighting = Settings.get_active().get_solarSystemLighting(); + this.space = false; + if (this.get_solarSystemTrack() !== 20 && this.get_solarSystemTrack() !== 65536) { + this.viewCamera.viewTarget = Planets.getPlanetTargetPoint(this.get_solarSystemTrack(), this.viewCamera.lat, this.viewCamera.lng, 0); + } + RenderTriangle.cullInside = false; + var cameraDistance = this.get_solarSystemCameraDistance(); + var trackingMatrix = Matrix3d.get_identity(); + cameraDistance -= 1E-06; + var activeTrackingFrame = false; + if (this.get_solarSystemTrack() === 20 && !ss.emptyString(this.get_trackingFrame())) { + activeTrackingFrame = true; + var target = LayerManager._getFrameTarget(this, this.get_trackingFrame()); + this.viewCamera.viewTarget = target.target; + trackingMatrix = target.matrix; + } else if (!ss.emptyString(this.get_trackingFrame())) { + this.set_trackingFrame(''); + } + var center = this.viewCamera.viewTarget; + var localZoom = this.viewCamera.zoom * 20; + var lookAt = new Vector3d(); + var viewAdjust = Matrix3d.get_identity(); + viewAdjust._multiply(Matrix3d._rotationX(((-this.viewCamera.lat) / 180 * Math.PI))); + viewAdjust._multiply(Matrix3d._rotationY(((-this.viewCamera.lng) / 180 * Math.PI))); + var lookAtAdjust = Matrix3d.get_identity(); + var dome = false; + var lookUp; + if (this._useSolarSystemTilt && !this.get_sandboxMode()) { + var angle = this.viewCamera.angle; + if (cameraDistance > 0.0008) { + angle = 0; + } + else if (cameraDistance > 1E-05) { + var val = Math.min(1.903089987, Util.log10(cameraDistance) + 5) / 1.903089987; + angle = angle * Math.max(0, 1 - val); + } + this.cameraPosition = Vector3d.create((Math.sin(-this.viewCamera.rotation) * Math.sin(angle) * cameraDistance), (Math.cos(-this.viewCamera.rotation) * Math.sin(angle) * cameraDistance), (Math.cos(angle) * cameraDistance)); + lookUp = Vector3d.create(Math.sin(-this.viewCamera.rotation), Math.cos(-this.viewCamera.rotation), 1E-05); + } else { + this.cameraPosition = Vector3d.create(0, 0, cameraDistance); + lookUp = Vector3d.create(Math.sin(-this.viewCamera.rotation), Math.cos(-this.viewCamera.rotation), 0.0001); + } + this.cameraPosition = viewAdjust.transform(this.cameraPosition); + this._cameraOffset = this.cameraPosition.copy(); + var tmp = trackingMatrix.clone(); + tmp.invert(); + this._cameraOffset = Vector3d._transformCoordinate(this._cameraOffset, tmp); + lookUp = viewAdjust.transform(lookUp); + this.set_world(Matrix3d.get_identity()); + this.set_worldBase(Matrix3d.get_identity()); + this.set_worldBaseNonRotating(Matrix3d.get_identity()); + this.set_view(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(trackingMatrix, Matrix3d.lookAtLH(this.cameraPosition, lookAt, lookUp)), lookAtAdjust)); + this.set_viewBase(this.get_view().clone()); + var temp = Vector3d.subtractVectors(lookAt, this.cameraPosition); + temp.normalize(); + temp = Vector3d._transformCoordinate(temp, trackingMatrix); + temp.normalize(); + this._viewPoint = temp; + var radius = Planets.getAdjustedPlanetRadius(this.get_solarSystemTrack()); + if (cameraDistance < radius * 2 && !forStars) { + this.nearPlane = cameraDistance * 0.03; + this.nearPlane = Math.max(this.nearPlane, 1E-11); + RenderContext.back = 1900; + } else { + if (forStars) { + RenderContext.back = 900056; + RenderContext.back = (cameraDistance > 900056) ? cameraDistance * 3 : 900056; + this.nearPlane = 3E-05; + } + else { + RenderContext.back = (cameraDistance > 1900) ? cameraDistance + 200 : 1900; + if (Settings.get_active().get_solarSystemScale() < 13) { + this.nearPlane = Math.min(cameraDistance * 0.03, 0.01); + } + else { + this.nearPlane = 0.001; + } + } + } + this.set_projection(Matrix3d.perspectiveFovLH(this._fovLocal, this.width / this.height, this.nearPlane, RenderContext.back)); + this.perspectiveFov = this._fovLocal; + this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; + this._fovScale = (this._fovAngle / this.height) * 3600; + this._setMatrixes(); + this.makeFrustum(); + }, + + _setMatrixes: function () { }, + + get_frustum: function () { + return this._frustum; + }, + + get_ambientLightColor: function () { + return this._ambientLightColor; + }, + + set_ambientLightColor: function (value) { + this._ambientLightColor = value; + this._lightingStateDirty = true; + return value; + }, + + get_hemisphereLightColor: function () { + return this._hemiLightColor; + }, + + set_hemisphereLightColor: function (value) { + this._hemiLightColor = value; + this._lightingStateDirty = true; + return value; + }, + + get_hemisphereLightUp: function () { + return this._hemiLightUp; + }, + + set_hemisphereLightUp: function (value) { + this._hemiLightUp = value; + this._lightingStateDirty = true; + return value; + }, + + get_sunlightColor: function () { + return this._sunlightColor; + }, + + set_sunlightColor: function (value) { + this._sunlightColor = value; + this._lightingStateDirty = true; + return value; + }, + + get_sunPosition: function () { + return this._sunPosition; + }, + + set_sunPosition: function (value) { + this._sunPosition = value; + this._lightingStateDirty = true; + return value; + }, + + get_reflectedLightColor: function () { + return this._reflectedLightColor; + }, + + set_reflectedLightColor: function (value) { + if (this._reflectedLightColor !== value) { + this._reflectedLightColor = value; + this._lightingStateDirty = true; + } + return value; + }, + + get_reflectedLightPosition: function () { + return this._reflectedLightPosition; + }, + + set_reflectedLightPosition: function (value) { + this._reflectedLightPosition = value; + this._lightingStateDirty = true; + return value; + }, + + // Radius of a planet casting a shadow; zero when there's no shadow + get_occludingPlanetRadius: function () { + return this._occludingPlanetRadius; + }, + + set_occludingPlanetRadius: function (value) { + this._occludingPlanetRadius = value; + return value; + }, + + get_occludingPlanetPosition: function () { + return this._occludingPlanetPosition; + }, + + set_occludingPlanetPosition: function (value) { + this._occludingPlanetPosition = value; + return value; + }, + + get_twoSidedLighting: function () { + return this._twoSidedLighting; + }, + + set_twoSidedLighting: function (value) { + if (value !== this._twoSidedLighting) { + this._twoSidedLighting = value; + this._lightingStateDirty = true; + } + return value; + }, + + makeFrustum: function () { + this.WV = Matrix3d.multiplyMatrix(this.get_world(), this.get_view()); + var viewProjection = Matrix3d.multiplyMatrix(this.WV, this.get_projection()); + this.WVP = viewProjection.clone(); + var inverseWorld = this.get_world().clone(); + inverseWorld.invert(); + + // Left plane + this._frustum[0].a = viewProjection.get_m14() + viewProjection.get_m11(); + this._frustum[0].b = viewProjection.get_m24() + viewProjection.get_m21(); + this._frustum[0].c = viewProjection.get_m34() + viewProjection.get_m31(); + this._frustum[0].d = viewProjection.get_m44() + viewProjection.get_m41(); + + // Right plane + this._frustum[1].a = viewProjection.get_m14() - viewProjection.get_m11(); + this._frustum[1].b = viewProjection.get_m24() - viewProjection.get_m21(); + this._frustum[1].c = viewProjection.get_m34() - viewProjection.get_m31(); + this._frustum[1].d = viewProjection.get_m44() - viewProjection.get_m41(); + + // Top plane + this._frustum[2].a = viewProjection.get_m14() - viewProjection.get_m12(); + this._frustum[2].b = viewProjection.get_m24() - viewProjection.get_m22(); + this._frustum[2].c = viewProjection.get_m34() - viewProjection.get_m32(); + this._frustum[2].d = viewProjection.get_m44() - viewProjection.get_m42(); + + // Bottom plane + this._frustum[3].a = viewProjection.get_m14() + viewProjection.get_m12(); + this._frustum[3].b = viewProjection.get_m24() + viewProjection.get_m22(); + this._frustum[3].c = viewProjection.get_m34() + viewProjection.get_m32(); + this._frustum[3].d = viewProjection.get_m44() + viewProjection.get_m42(); + + // Near plane + this._frustum[4].a = viewProjection.get_m13(); + this._frustum[4].b = viewProjection.get_m23(); + this._frustum[4].c = viewProjection.get_m33(); + this._frustum[4].d = viewProjection.get_m43(); + + // Far plane + this._frustum[5].a = viewProjection.get_m14() - viewProjection.get_m13(); + this._frustum[5].b = viewProjection.get_m24() - viewProjection.get_m23(); + this._frustum[5].c = viewProjection.get_m34() - viewProjection.get_m33(); + this._frustum[5].d = viewProjection.get_m44() - viewProjection.get_m43(); + + // Normalize planes + for (var i = 0; i < 6; i++) { + this._frustum[i].normalize(); + } + this._frustumDirty = false; + this.WVP.scale(Vector3d.create(this.width / 2, -this.height / 2, 1)); + this.WVP.translate(Vector3d.create(this.width / 2, this.height / 2, 0)); + this._setMatrixes(); + }, + + _initGL: function () { + if (this.gl == null) { + return; + } + var uints_for_indices = this.gl.getExtension('OES_element_index_uint'); + set_tileUvMultiple(1); + set_tileDemEnabled(true); + TileShader.init(this); + }, + + freezeView: function () { + this.targetAlt = this.alt; + this.targetAz = this.az; + this.targetCamera = this.viewCamera.copy(); + }, + + _setVertexBuffer: function (vertexBuffer) { }, + + _setIndexBuffer: function (indexBuffer) { }, + + // Set up a shader for the specified material properties and the + // current lighting environment. + setMaterial: function (material, diffuseTex, specularTex, normalMap, opacity) { + this.set_mainTexture(diffuseTex); + }, + + preDraw: function () { } +}; + +registerType("RenderContext", [RenderContext, RenderContext$, null]); diff --git a/engine/esm/render_globals.js b/engine/esm/render_globals.js new file mode 100644 index 00000000..dfae59a2 --- /dev/null +++ b/engine/esm/render_globals.js @@ -0,0 +1,95 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Various global variables associated with the rendering engine. +// +// In the original C# code these were generally static values associated with +// various classes, but since we want to avoid circular dependencies in our +// module structure, we gather some of those values in modules that contain +// minimal amounts of code (like this one) so that they can go early in the +// dependency graph. + +// This used to be Tile.prepDevice. It's the global WebGL rendering context. +export var tilePrepDevice = null; + +export function set_tilePrepDevice(value) { + tilePrepDevice = value; +} + +// This used to be Tile.uvMultiple. It's some GL rendering state variable. +export var tileUvMultiple = 256; + +export function set_tileUvMultiple(value) { + tileUvMultiple = value; +} + +// This used to be Tile.demEnabled. It controls whether DEM rendering is +// enabled, hopefully? +export var tileDemEnabled = false; + +export function set_tileDemEnabled(value) { + tileDemEnabled = !!value; +} + +// This used to be `RenderContext.useGl`. It sets whether we're using WebGL. +// +// Older versions of the engine used to support HTML Canvas rendering, but that +// mode is now deprecated. Uses where `useGl` is false may break at any time. +export var useGl = false; + +export function set_useGl(value) { + useGl = !!value; +} + +// This used to be `RenderContext.useGlVersion2`. It sets whether we're +// using WebGL >= 2. +export var useGlVersion2 = false; + +export function set_useGlVersion2(value) { + useGlVersion2 = !!value; +} + +// This used to be `TileCache.addTileToQueue()`. It's a function that +// adds a tile to the fetch queue. +export var tileCacheAddTileToQueue = null; + +export function set_tileCacheAddTileToQueue(value) { + tileCacheAddTileToQueue = value; +} + +// This used to be `TileCache.removeFromQueue()`. It's a function that +// removes a tile from the fetch queue. +export var tileCacheRemoveFromQueue = null; + +export function set_tileCacheRemoveFromQueue(value) { + tileCacheRemoveFromQueue = value; +} + +// This used to be `TileCache.accessID`. +var tileCacheAccessID = 0; + +export function inc_tileCacheAccessID() { + return tileCacheAccessID++; +} + +// This used to be `TileCache.getTile()`. It gets a tile from the cache, unconditionally. +export var tileCacheGetTile = null; + +export function set_tileCacheGetTile(value) { + tileCacheGetTile = value; +} + +// This used to be `TileCache.getCachedTile()`. It gets a tile from the cache. +export var tileCacheGetCachedTile = null; + +export function set_tileCacheGetCachedTile(value) { + tileCacheGetCachedTile = value; +} + +// This is another way to access `WWTControl.singleton.renderContext`. It's the +// global singleton RenderContext instance. +export var globalRenderContext = null; + +export function set_globalRenderContext(value) { + globalRenderContext = value; +} diff --git a/engine/esm/render_triangle.js b/engine/esm/render_triangle.js new file mode 100644 index 00000000..536592c5 --- /dev/null +++ b/engine/esm/render_triangle.js @@ -0,0 +1,296 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A triangle that is part of a tile pyramid render. + +import { registerType } from "./typesystem.js"; +import { Vector2d, Vector3d, PositionTexture } from "./double3d.js"; + + +// wwtlib.RenderTriangle + +export function RenderTriangle() { + this.a = new PositionTexture(); + this.b = new PositionTexture(); + this.c = new PositionTexture(); + this.normal = new Vector3d(); + this.opacity = 1; + this.expansionInPixels = 0.6; + this.tileLevel = 0; + this._ta = new Vector3d(); + this._tb = new Vector3d(); + this._tc = new Vector3d(); + this._expandedS0 = new Vector2d(); + this._expandedS1 = new Vector2d(); + this._expandedS2 = new Vector2d(); + this.lighting = 1; +} + +RenderTriangle.width = 1024; +RenderTriangle.height = 768; +RenderTriangle._contractionInPixels = -0.5; +RenderTriangle.trianglesRendered = 0; +RenderTriangle.trianglesCulled = 0; +RenderTriangle.renderingOn = true; +RenderTriangle._factor = 1; +RenderTriangle.cullInside = true; +RenderTriangle._hw = 0; +RenderTriangle._qw = 0; +RenderTriangle._hh = 0; +RenderTriangle._qh = 0; + +RenderTriangle.create = function (a, b, c, img, level) { + var temp = new RenderTriangle(); + temp.a = a.copy(); + temp.b = b.copy(); + temp.c = c.copy(); + temp._texture = img; + temp.tileLevel = level; + temp.makeNormal(); + return temp; +}; + +RenderTriangle.createWithMiter = function (a, b, c, img, level, expansion) { + var temp = new RenderTriangle(); + temp.expansionInPixels = expansion; + temp.a = a.copy(); + temp.b = b.copy(); + temp.c = c.copy(); + temp._texture = img; + temp.tileLevel = level; + temp.makeNormal(); + return temp; +}; + +RenderTriangle._getMiterPoint = function (p1, p2, p3, edgeOffset) { + var edge1 = Vector2d.subtract(p2, p1); + var edge2 = Vector2d.subtract(p3, p1); + edge1.normalize(); + edge2.normalize(); + var dir = Vector2d.create(edge1.x + edge2.x, edge1.y + edge2.y); + dir.normalize(); + var delta = Vector2d.create(edge1.x - edge2.x, edge1.y - edge2.y); + var sineHalfAngle = delta.get_length() / 2; + var net = Math.min(2, edgeOffset / sineHalfAngle); + dir.extend(net); + return Vector2d.create(p1.x - dir.x, p1.y - dir.y); +}; + +RenderTriangle._miterPoint = function (p1x, p1y, p2x, p2y, p3x, p3y, ExpansionInPixels) { + var e1x = p2x - p1x; + var e1y = p2y - p1y; + var e2x = p3x - p1x; + var e2y = p3y - p1y; + var length = Math.sqrt(e1x * e1x + e1y * e1y); + if (!!length) { + e1x /= length; + e1y /= length; + } + length = Math.sqrt(e2x * e2x + e2y * e2y); + if (!!length) { + e2x /= length; + e2y /= length; + } + var dx = e1x + e2x; + var dy = e1y + e2y; + length = Math.sqrt(dx * dx + dy * dy); + if (!!length) { + dx /= length; + dy /= length; + } + var deltax = e1x - e2x; + var deltay = e1y - e2y; + length = Math.sqrt(deltax * deltax + deltay * deltay); + var sineHalfAngle = length / 2; + var net = Math.min(2, ExpansionInPixels / sineHalfAngle); + dx *= net; + dy *= net; + return Vector2d.create(p1x - dx, p1y - dy); +}; + +RenderTriangle._miterPointOut = function (pntOut, p1x, p1y, p2x, p2y, p3x, p3y, ExpansionInPixels) { + var e1x = p2x - p1x; + var e1y = p2y - p1y; + var e2x = p3x - p1x; + var e2y = p3y - p1y; + var length = Math.sqrt(e1x * e1x + e1y * e1y); + if (!!length) { + e1x /= length; + e1y /= length; + } + length = Math.sqrt(e2x * e2x + e2y * e2y); + if (!!length) { + e2x /= length; + e2y /= length; + } + var dx = e1x + e2x; + var dy = e1y + e2y; + length = Math.sqrt(dx * dx + dy * dy); + if (!!length) { + dx /= length; + dy /= length; + } + var deltax = e1x - e2x; + var deltay = e1y - e2y; + length = Math.sqrt(deltax * deltax + deltay * deltay); + var sineHalfAngle = length / 2; + var net = Math.min(2, ExpansionInPixels / sineHalfAngle); + dx *= net; + dy *= net; + pntOut.x = p1x - dx; + pntOut.y = p1y - dy; +}; + +var RenderTriangle$ = { + makeNormal: function () { + var a = this.a.position.copy(); + var b = this.b.position.copy(); + var c = this.c.position.copy(); + a.normalize(); + b.normalize(); + c.normalize(); + var x = a.x + b.x + c.x; + var y = a.y + b.y + c.y; + var z = a.z + b.z + c.z; + this.normal = Vector3d.create(x / 3, y / 3, z / 3); + this.normal.normalize(); + }, + + _checkBackface: function () { + var ab = Vector3d.subtractVectors(this._ta, this._tb); + var ac = Vector3d.subtractVectors(this._ta, this._tc); + var cp = Vector3d.cross(ab, ac); + cp.normalize(); + return cp.z >= 0; + }, + + draw: function (ctx, wvp) { + if (ctx == null) { + return; + } + wvp._transformTo(this.a.position, this._ta); + wvp._transformTo(this.b.position, this._tb); + wvp._transformTo(this.c.position, this._tc); + if (this._checkBackface() === RenderTriangle.cullInside) { + RenderTriangle.trianglesCulled++; + return; + } + this._drawTriangle(ctx, this._texture, this._ta.x, this._ta.y, this._tb.x, this._tb.y, this._tc.x, this._tc.y, this.a.tu, this.a.tv, this.b.tu, this.b.tv, this.c.tu, this.c.tv); + }, + + _drawTriangle: function (ctx, im, x0, y0, x1, y1, x2, y2, sx0, sy0, sx1, sy1, sx2, sy2) { + if (!this.intersects(0, RenderTriangle.width, 0, RenderTriangle.height, x0, y0, x1, y1, x2, y2)) { + return false; + } + RenderTriangle._miterPointOut(this._expandedS0, x0, y0, x1, y1, x2, y2, this.expansionInPixels); + RenderTriangle._miterPointOut(this._expandedS1, x1, y1, x0, y0, x2, y2, this.expansionInPixels); + RenderTriangle._miterPointOut(this._expandedS2, x2, y2, x1, y1, x0, y0, this.expansionInPixels); + x0 = this._expandedS0.x; + y0 = this._expandedS0.y; + x1 = this._expandedS1.x; + y1 = this._expandedS1.y; + x2 = this._expandedS2.x; + y2 = this._expandedS2.y; + ctx.save(); + if (RenderTriangle.renderingOn) { + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.closePath(); + ctx.clip(); + } + var denom = sx0 * (sy2 - sy1) - sx1 * sy2 + sx2 * sy1 + (sx1 - sx2) * sy0; + //if (denom == 0) + //{ + // ctx.Restore(); + // return false; + //} + + var m11 = -(sy0 * (x2 - x1) - sy1 * x2 + sy2 * x1 + (sy1 - sy2) * x0) / denom; + var m12 = (sy1 * y2 + sy0 * (y1 - y2) - sy2 * y1 + (sy2 - sy1) * y0) / denom; + var m21 = (sx0 * (x2 - x1) - sx1 * x2 + sx2 * x1 + (sx1 - sx2) * x0) / denom; + var m22 = -(sx1 * y2 + sx0 * (y1 - y2) - sx2 * y1 + (sx2 - sx1) * y0) / denom; + var dx = (sx0 * (sy2 * x1 - sy1 * x2) + sy0 * (sx1 * x2 - sx2 * x1) + (sx2 * sy1 - sx1 * sy2) * x0) / denom; + var dy = (sx0 * (sy2 * y1 - sy1 * y2) + sy0 * (sx1 * y2 - sx2 * y1) + (sx2 * sy1 - sx1 * sy2) * y0) / denom; + ctx.transform(m11, m12, m21, m22, dx, dy); + if (RenderTriangle.renderingOn) { + ctx.globalAlpha = this.opacity; + if (this.lighting < 1) { + ctx.globalAlpha = 1; + ctx.fillStyle = 'Black'; + ctx.fillRect(0, 0, RenderTriangle.width, RenderTriangle.height); + ctx.globalAlpha = this.lighting * this.opacity; + } + ctx.drawImage(im, 0, 0); + } + ctx.restore(); + return true; + }, + + intersects: function (l, r, t, b, x0, y0, x1, y1, x2, y2) { + if (x0 > l && x0 < r && y0 > t && y0 < b) { + return true; + } + if (x1 > l && x1 < r && y1 > t && y1 < b) { + return true; + } + if (x2 > l && x2 < r && y2 > t && y2 < b) { + return true; + } + var h4 = RenderTriangle.height * 4; + if (this.tileLevel < 4 && ((Math.abs(x0 - x1) > h4) || (Math.abs(y0 - y1) > h4) || (Math.abs(x2 - x1) > h4) || (Math.abs(y2 - y1) > h4) || (Math.abs(x0 - x2) > h4) || (Math.abs(y0 - y2) > h4))) { + return false; + } + return this.lineRectangleIntersect(l, r, t, b, x0, y0, x1, y1) || this.lineRectangleIntersect(l, r, t, b, x1, y1, x2, y2) || this.lineRectangleIntersect(l, r, t, b, x2, y2, x0, y0); + }, + + lineRectangleIntersect: function (l, r, t, b, x0, y0, x1, y1) { + var top_intersection; + var bottom_intersection; + var toptrianglepoint; + var bottomtrianglepoint; + var m; + var c; + + // Calculate m and c for the equation for the line (y = mx+c) + m = (y1 - y0) / (x1 - x0); + c = y0 - (m * x0); + + // if the line is going up from right to left then the top intersect point is on the left + if (m > 0) { + top_intersection = (m * l + c); + bottom_intersection = (m * r + c); + } else { + // otherwise it's on the right + top_intersection = (m * r + c); + bottom_intersection = (m * l + c); + } + + // work out the top and bottom extents for the triangle + if (y0 < y1) { + toptrianglepoint = y0; + bottomtrianglepoint = y1; + } else { + toptrianglepoint = y1; + bottomtrianglepoint = y0; + } + + // and calculate the overlap between those two bounds + var topoverlap; + var botoverlap; + topoverlap = (top_intersection > toptrianglepoint) ? top_intersection : toptrianglepoint; + botoverlap = (bottom_intersection < bottomtrianglepoint) ? bottom_intersection : bottomtrianglepoint; + + // (topoverlapb)) : + // If the bottom overlap is higher than the top of the rectangle or the top overlap is + // lower than the bottom of the rectangle we don't have intersection. So return the negative + // of that. Much faster than checking each of the points is within the bounds of the rectangle. + return (topoverlap < botoverlap) && (!((botoverlap < t) || (topoverlap > b))); + } +}; + +registerType("RenderTriangle", [RenderTriangle, RenderTriangle$, null]); diff --git a/engine/esm/script_interface.js b/engine/esm/script_interface.js new file mode 100644 index 00000000..3a093be5 --- /dev/null +++ b/engine/esm/script_interface.js @@ -0,0 +1,716 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The quasi-legacy ScriptInterface control interface. +// +// I believe that this new class was created in the very early days of the WWT +// web control and was used as the interface point with the browser. In the +// modern WebGL engine, there's not need to put all this functionality in this +// separate module. But, as always, to preserve API compatibility, we maintain +// all of the interfaces that were added here. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Util } from "./util.js"; +import { globalRenderContext, useGlVersion2 } from "./render_globals.js"; +import { globalWWTControl, layerManagerGetAllMaps, loadWtmlFile } from "./data_globals.js"; +import { Annotation, Circle, Poly, PolyLine } from "./annotation.js"; +import { FitsImage } from "./layers/fits_image.js"; +import { FitsImageJs } from "./layers/fits_image_js.js"; +import { Imageset } from "./imageset.js"; +import { ImageSetLayer } from "./layers/imageset_layer.js"; +import { LayerManager } from "./layers/layer_manager.js"; +import { Folder } from "./folder.js"; + + +// wwtlib.SlideChangedEventArgs + +export function SlideChangedEventArgs(caption) { + ss.EventArgs.call(this); + this.set_caption(caption); +} + +var SlideChangedEventArgs$ = { + get_caption: function () { + return this._caption$2; + }, + + set_caption: function (value) { + this._caption$2 = value; + return value; + } +}; + +registerType("SlideChangedEventArgs", [SlideChangedEventArgs, SlideChangedEventArgs$, ss.EventArgs]); + + +// wwtlib.ArrivedEventArgs + +export function ArrivedEventArgs(ra, dec, zoom) { + this._ra$2 = 0; + this._dec$2 = 0; + this._zoom$2 = 0; + ss.EventArgs.call(this); + this.set_RA(ra * 15); + this.set_dec(dec); + this.set_zoom(zoom / 6); +} + +var ArrivedEventArgs$ = { + get_RA: function () { + return this._ra$2; + }, + + set_RA: function (value) { + this._ra$2 = value; + return value; + }, + + get_dec: function () { + return this._dec$2; + }, + + set_dec: function (value) { + this._dec$2 = value; + return value; + }, + + get_zoom: function () { + return this._zoom$2; + }, + + set_zoom: function (value) { + this._zoom$2 = value; + return value; + } +}; + +registerType("ArrivedEventArgs", [ArrivedEventArgs, ArrivedEventArgs$, ss.EventArgs]); + + +// wwtlib.AnnotationClickEventArgs + +export function AnnotationClickEventArgs(ra, dec, id) { + this._ra$2 = 0; + this._dec$2 = 0; + ss.EventArgs.call(this); + this.set_RA(ra * 15); + this.set_dec(dec); + this.set_id(id); +} + +var AnnotationClickEventArgs$ = { + get_RA: function () { + return this._ra$2; + }, + + set_RA: function (value) { + this._ra$2 = value; + return value; + }, + + get_dec: function () { + return this._dec$2; + }, + + set_dec: function (value) { + this._dec$2 = value; + return value; + }, + + get_id: function () { + return this._id$2; + }, + + set_id: function (value) { + this._id$2 = value; + return value; + } +}; + +registerType("AnnotationClickEventArgs", [AnnotationClickEventArgs, AnnotationClickEventArgs$, ss.EventArgs]); + + +// wwtlib.CollectionLoadedEventArgs + +export function CollectionLoadedEventArgs(url) { + ss.EventArgs.call(this); + this._url$2 = url; +} + +var CollectionLoadedEventArgs$ = { + get_url: function () { + return this._url$2; + }, + + set_url: function (value) { + this._url$2 = value; + return value; + } +}; + +registerType("CollectionLoadedEventArgs", [CollectionLoadedEventArgs, CollectionLoadedEventArgs$, ss.EventArgs]); + + +// wwtlib.ScriptInterface + +export function ScriptInterface() { + this._missedReady = false; + this.hideTourFeedback = false; + this._smoothAnimation = false; + this._showCaptions = true; +} + +ScriptInterface._containsFitsLikeExtentsion = function (url) { + var lowerCaseUrl = url.toLowerCase(); + return (ss.endsWith(lowerCaseUrl, 'fits') || ss.endsWith(lowerCaseUrl, 'ftz') || ss.endsWith(lowerCaseUrl, 'fit') || ss.endsWith(lowerCaseUrl, 'fts')); +}; + +ScriptInterface._addImageSet = function (name, gotoTarget, loaded, imageset) { + if (ss.whitespace(name)) { + name = LayerManager.getNextImageSetName(); + } + var imagesetLayer = LayerManager.addImageSetLayerCallback(imageset, name, loaded); + if (gotoTarget) { + var zoom = imageset._guessZoomSetting(globalRenderContext.viewCamera.zoom); + globalWWTControl.gotoRADecZoom(imageset.get_viewCenterX() / 15, imageset.get_viewCenterY(), zoom, false, null); + } + return imagesetLayer; +}; + +ScriptInterface._addFitsLayer = function (url, name, gotoTarget, loaded) { + if (ss.whitespace(name)) { + name = LayerManager.getNextFitsName(); + } + var imagesetLayer = new ImageSetLayer(); + var imageset = new Imageset(); + var wcsLoaded = function (wcsImage) { + if ((wcsImage).errored) { + return; + } + var width = ss.truncate(wcsImage.get_sizeX()); + var height = ss.truncate(wcsImage.get_sizeY()); + imageset.setInitialParameters(wcsImage.get_description(), wcsImage.get_filename(), 2, 3, 5, Util.getHashCode(wcsImage.get_filename()), 0, 0, wcsImage.get_scaleY(), '.fits', wcsImage.get_scaleX() > 0, '', wcsImage.get_centerX(), wcsImage.get_centerY(), wcsImage.get_rotation(), false, '', false, false, 1, wcsImage.get_referenceX(), wcsImage.get_referenceY(), wcsImage.get_copyright(), wcsImage.get_creditsUrl(), '', '', 0, ''); + imageset.set_wcsImage(wcsImage); + imagesetLayer.set_imageSet(imageset); + LayerManager.addFitsImageSetLayer(imagesetLayer, name); + if (gotoTarget) { + var zoom = imageset._guessZoomSetting(globalRenderContext.viewCamera.zoom); + globalWWTControl.gotoRADecZoom(wcsImage.get_viewCenterX() / 15, wcsImage.get_viewCenterY(), zoom, false, null); + } + if (loaded != null) { + loaded(imagesetLayer); + } + }; + if (ss.whitespace(name)) { + name = LayerManager.getNextFitsName(); + } + if (useGlVersion2) { + new FitsImage(imageset, url, null, wcsLoaded); + } + else { + new FitsImageJs(imageset, url, null, wcsLoaded); + } + return imagesetLayer; +}; + +var ScriptInterface$ = { + add_ready: function (value) { + this.__ready = ss.bindAdd(this.__ready, value); + }, + + remove_ready: function (value) { + this.__ready = ss.bindSub(this.__ready, value); + }, + + _fireReady: function () { + if (this.__ready != null) { + this.__ready(this, new ss.EventArgs()); + } else { + this._missedReady = true; + } + }, + + add_collectionLoaded: function (value) { + this.__collectionLoaded = ss.bindAdd(this.__collectionLoaded, value); + }, + + remove_collectionLoaded: function (value) { + this.__collectionLoaded = ss.bindSub(this.__collectionLoaded, value); + }, + + _fireCollectionLoaded: function (url) { + if (this.__collectionLoaded != null) { + this.__collectionLoaded(this, new CollectionLoadedEventArgs(url)); + } + }, + + add_colorPickerDisplay: function (value) { + this.__colorPickerDisplay = ss.bindAdd(this.__colorPickerDisplay, value); + }, + + remove_colorPickerDisplay: function (value) { + this.__colorPickerDisplay = ss.bindSub(this.__colorPickerDisplay, value); + }, + + add_voTableDisplay: function (value) { + this.__voTableDisplay = ss.bindAdd(this.__voTableDisplay, value); + }, + + remove_voTableDisplay: function (value) { + this.__voTableDisplay = ss.bindSub(this.__voTableDisplay, value); + }, + + add_refreshLayerManager: function (value) { + this.__refreshLayerManager = ss.bindAdd(this.__refreshLayerManager, value); + }, + + remove_refreshLayerManager: function (value) { + this.__refreshLayerManager = ss.bindSub(this.__refreshLayerManager, value); + }, + + add_arrived: function (value) { + this.__arrived = ss.bindAdd(this.__arrived, value); + }, + + remove_arrived: function (value) { + this.__arrived = ss.bindSub(this.__arrived, value); + }, + + add_clicked: function (value) { + this.__clicked = ss.bindAdd(this.__clicked, value); + }, + + remove_clicked: function (value) { + this.__clicked = ss.bindSub(this.__clicked, value); + }, + + add_annotationClicked: function (value) { + this.__annotationClicked = ss.bindAdd(this.__annotationClicked, value); + }, + + remove_annotationClicked: function (value) { + this.__annotationClicked = ss.bindSub(this.__annotationClicked, value); + }, + + add_imageryLoaded: function (value) { + this.__imageryLoaded = ss.bindAdd(this.__imageryLoaded, value); + }, + + remove_imageryLoaded: function (value) { + this.__imageryLoaded = ss.bindSub(this.__imageryLoaded, value); + }, + + add_tourReady: function (value) { + this.__tourReady = ss.bindAdd(this.__tourReady, value); + }, + + remove_tourReady: function (value) { + this.__tourReady = ss.bindSub(this.__tourReady, value); + }, + + add_tourError: function (value) { + this.__tourError = ss.bindAdd(this.__tourError, value); + }, + + remove_tourError: function (value) { + this.__tourError = ss.bindSub(this.__tourError, value); + }, + + add_tourPaused: function (value) { + this.__tourPaused = ss.bindAdd(this.__tourPaused, value); + }, + + remove_tourPaused: function (value) { + this.__tourPaused = ss.bindSub(this.__tourPaused, value); + }, + + add_tourResumed: function (value) { + this.__tourResumed = ss.bindAdd(this.__tourResumed, value); + }, + + remove_tourResumed: function (value) { + this.__tourResumed = ss.bindSub(this.__tourResumed, value); + }, + + add_tourEnded: function (value) { + this.__tourEnded = ss.bindAdd(this.__tourEnded, value); + }, + + remove_tourEnded: function (value) { + this.__tourEnded = ss.bindSub(this.__tourEnded, value); + }, + + add_slideChanged: function (value) { + this.__slideChanged = ss.bindAdd(this.__slideChanged, value); + }, + + remove_slideChanged: function (value) { + this.__slideChanged = ss.bindSub(this.__slideChanged, value); + }, + + //UI will set this to a function that takes 2 string properties (prop,val) + //("title", "left", or "right" for the labels, "pos" for the slider pos) + //Pass a 0-1 float to set the slider position (stringify it if you need to for strong typing) + + add_timeScrubberHook: function (value) { + this.__timeScrubberHook = ss.bindAdd(this.__timeScrubberHook, value); + }, + + remove_timeScrubberHook: function (value) { + this.__timeScrubberHook = ss.bindSub(this.__timeScrubberHook, value); + }, + + setTimeScrubberPosition: function (posLeft) { + LayerManager.setTimeSliderValue(posLeft); + }, + + setTimeSlider: function (name, value) { + this.__timeScrubberHook(name, value); + }, + + showColorPicker: function (pickerInstance, e) { + if (this.__colorPickerDisplay != null) { + this.__colorPickerDisplay(pickerInstance, e); + } + }, + + displayVoTableLayer: function (layer) { + if (this.__voTableDisplay != null) { + this.__voTableDisplay(layer, new ss.EventArgs()); + } + }, + + refreshLayerManagerNow: function () { + if (this.__refreshLayerManager != null) { + this.__refreshLayerManager(null, new ss.EventArgs()); + } + }, + + _fireTourReady: function () { + if (this.__tourReady != null) { + this.__tourReady(this, new ss.EventArgs()); + } + }, + + _fireTourError: function (ex) { + if (this.__tourError != null) { + this.__tourError(ex, new ss.EventArgs()); + } + }, + + _fireTourPaused: function () { + if (this.__tourPaused != null) { + this.__tourPaused(this, new ss.EventArgs()); + } + }, + + _fireTourResume: function () { + if (this.__tourResumed != null) { + this.__tourResumed(this, new ss.EventArgs()); + } + }, + + _fireTourEnded: function () { + if (this.__tourEnded != null) { + this.__tourEnded(this, new ss.EventArgs()); + } + }, + + _fireImageryLoaded: function () { + if (this.__imageryLoaded != null) { + this.__imageryLoaded(this, new ss.EventArgs()); + } + }, + + _fireClick: function (ra, dec) { + if (this.__clicked != null) { + this.__clicked(this, new ArrivedEventArgs(ra, dec, globalRenderContext.viewCamera.zoom)); + } + }, + + _fireArrived: function (ra, dec, zoom) { + if (this.__arrived != null) { + this.__arrived(this, new ArrivedEventArgs(ra, dec, zoom)); + } + }, + + _fireAnnotationclicked: function (RA, Dec, id) { + try { + if (this.__annotationClicked != null) { + this.__annotationClicked(this, new AnnotationClickEventArgs(RA, Dec, id)); + } + } + catch ($e1) { + } + }, + + _fireSlideChanged: function (caption) { + try { + if (this.__slideChanged != null) { + this.__slideChanged(this, new SlideChangedEventArgs(caption)); + } + } + catch ($e1) { + } + }, + + endInit: function () { + if (this._missedReady) { + this._fireReady(); + } + }, + + gotoRaDecZoom: function (ra, dec, zoom, instant, roll) { + if (globalWWTControl != null) { + globalWWTControl.gotoRADecZoom(ra / 15, dec, zoom * 6, instant, roll); + } + }, + + setBackgroundImageByName: function (name) { + if (globalWWTControl != null) { + globalWWTControl.setBackgroundImageByName(name); + } + }, + + // Call this to add a VOTable to layers + addVoTableLayer: function (table) { + return LayerManager.addVoTableLayer(table, 'Vo Table'); + }, + + getLayers: function () { + return LayerManager.get_layerList(); + }, + + setForegroundImageByName: function (name) { + if (globalWWTControl != null) { + globalWWTControl.setForegroundImageByName(name); + globalRenderContext.viewCamera.opacity = 100; + } + }, + + setForegroundOpacity: function (opacity) { + if (globalWWTControl != null) { + globalRenderContext.viewCamera.opacity = opacity; + } + }, + + addCatalogHipsByName: function (name) { + if (globalWWTControl != null) { + globalWWTControl.addCatalogHipsByName(name); + } + }, + + addCatalogHipsByNameWithCallback: function (name, onLoad) { + if (globalWWTControl != null) { + globalWWTControl.addCatalogHipsByNameWithCallback(name, onLoad); + } + }, + + removeCatalogHipsByName: function (name) { + if (globalWWTControl != null) { + globalWWTControl.removeCatalogHipsByName(name); + } + }, + + getCatalogHipsDataInView: function (name, limit, onComplete) { + if (globalWWTControl != null) { + globalWWTControl.getCatalogHipsDataInView(name, limit, onComplete); + } + }, + + setCutsForFits: function (imagesetName, min, max) { + if (globalWWTControl != null) { + globalWWTControl.setCutsForFits(imagesetName, min, max); + } + }, + + setColorMapForFits: function (imagesetName, colorMapName) { + if (globalWWTControl != null) { + globalWWTControl.setColorMapForFits(imagesetName, colorMapName); + } + }, + + setScaleTypeForFits: function (imagesetName, scaleType) { + if (globalWWTControl != null) { + globalWWTControl.setScaleTypeForFits(imagesetName, scaleType); + } + }, + + hideUI: function (hide) { }, + + loadTour: function (url) { + if (globalWWTControl != null) { + globalWWTControl.playTour(url); + } + }, + + loadFits: function (url) { + return this.loadFitsLayer(url, '', true, null); + }, + + loadFitsLayer: function (url, name, gotoTarget, loaded) { + return this.addImageSetLayer(url, 'fits', name, gotoTarget, loaded); + }, + + addImageSetLayer: function (url, mode, name, gotoTarget, loaded) { + if (mode != null && mode.toLowerCase() === 'fits') { + return ScriptInterface._addFitsLayer(url, name, gotoTarget, loaded); + } else if (mode != null && mode.toLowerCase() === 'preloaded') { + var imageset = globalWWTControl.getImageSetByUrl(url); + if (imageset != null) { + return ScriptInterface._addImageSet(name, gotoTarget, loaded, imageset); + } + } else { + var imageset = globalWWTControl.getImageSetByUrl(url); + if (imageset != null) { + return ScriptInterface._addImageSet(name, gotoTarget, loaded, imageset); + } + else if (ScriptInterface._containsFitsLikeExtentsion(url)) { + return ScriptInterface._addFitsLayer(url, name, gotoTarget, loaded); + } + } + return null; + }, + + setImageSetLayerOrder: function (id, order) { + var layer = LayerManager.get_layerList()[id]; + if (ss.canCast(layer, ImageSetLayer) && order >= 0) { + ss.remove(layerManagerGetAllMaps()[layer.get_referenceFrame()].layers, layer); + + //In case of order > Layers.length, the layer is properly put at the end of the list + layerManagerGetAllMaps()[layer.get_referenceFrame()].layers.splice(order, 0, layer); + } + }, + + isUsingWebGl2: function () { + return useGlVersion2; + }, + + get_hideTourFeedback: function () { + return this.hideTourFeedback; + }, + + set_hideTourFeedback: function (value) { + this.hideTourFeedback = value; + return value; + }, + + playTour: function () { + if (globalWWTControl != null) { + globalWWTControl.playCurrentTour(); + } + }, + + stopTour: function () { + if (globalWWTControl != null) { + globalWWTControl.stopCurrentTour(); + } + }, + + loadImageCollection: function (url, loadChildFolders) { + var $this = this; + + this._imageUrl = url; + loadWtmlFile(url, function () { + $this._fireCollectionLoaded(url); + }, loadChildFolders); + }, + + _imageFileLoaded: function () { + this._fireCollectionLoaded(this._imageUrl); + }, + + zoom: function (factor) { + if (globalWWTControl != null) { + globalWWTControl.zoom(factor); + } + return; + }, + + getRA: function () { + if (globalWWTControl != null) { + return globalRenderContext.get_RA(); + } + return 0; + }, + + getDec: function () { + if (globalWWTControl != null) { + return globalRenderContext.get_dec(); + } + return 0; + }, + + createFolder: function () { + var folder = new Folder(); + return folder; + }, + + createPolygon: function (fill) { + var p = new Poly(); + p.set_fill(fill); + return p; + }, + + createPolyLine: function (fill) { + return new PolyLine(); + }, + + createCircle: function (fill) { + var c = new Circle(); + c.set_fill(fill); + return c; + }, + + addAnnotation: function (annotation) { + if (annotation != null && ss.canCast(annotation, Annotation)) { + if (globalWWTControl != null) { + globalWWTControl._addAnnotation(annotation); + } + } + }, + + removeAnnotation: function (annotation) { + if (annotation != null) { + if (globalWWTControl != null) { + globalWWTControl._removeAnnotation(annotation); + } + } + }, + + clearAnnotations: function () { + if (globalWWTControl != null) { + globalWWTControl._clearAnnotations(); + } + }, + + get_smoothAnimation: function () { + return this._smoothAnimation; + }, + + set_smoothAnimation: function (value) { + this._smoothAnimation = value; + return value; + }, + + get_showCaptions: function () { + return this._showCaptions; + }, + + set_showCaptions: function (value) { + this._showCaptions = value; + return value; + }, + + loadVOTable: function (url, useCurrentView) { }, + + get_fov: function () { + if (globalWWTControl != null) { + return globalRenderContext.viewCamera.zoom / 6; + } + return 60; + } +}; + +registerType("ScriptInterface", [ScriptInterface, ScriptInterface$, null]); diff --git a/engine/esm/settings.js b/engine/esm/settings.js new file mode 100644 index 00000000..96e298ae --- /dev/null +++ b/engine/esm/settings.js @@ -0,0 +1,840 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Planet-related code that can come lower in the dependency graph. + +import { registerType, registerEnum } from "./typesystem.js"; +import { Colors } from "./color.js"; +import { ConstellationFilter } from "./constellation_filter.js"; +import { ISettings } from "./interfaces.js"; + + +// wwtlib.StockSkyOverlayTypes +// +// This was defined in `Tours/ISettings.cs`, which we've folded into `interfaces.js`. + +export var StockSkyOverlayTypes = { + empty: 0, + equatorialGrid: 1, + equatorialGridText: 2, + galacticGrid: 3, + galacticGridText: 4, + eclipticGrid: 5, + eclipticGridText: 6, + eclipticOverview: 7, + eclipticOverviewText: 8, + precessionChart: 9, + altAzGrid: 10, + altAzGridText: 11, + constellationFigures: 12, + constellationBoundaries: 13, + constellationFocusedOnly: 14, + constellationNames: 15, + constellationPictures: 16, + fadeToBlack: 17, + fadeToLogo: 18, + fadeToGradient: 19, + screenBroadcast: 20, + fadeRemoteOnly: 21, + skyGrids: 22, + constellations: 23, + solarSystemStars: 24, + solarSystemMilkyWay: 25, + solarSystemCosmos: 26, + solarSystemOrbits: 27, + solarSystemPlanets: 28, + solarSystemAsteroids: 29, + solarSystemLighting: 30, + solarSystemMinorOrbits: 31, + showEarthCloudLayer: 32, + showElevationModel: 33, + showAtmosphere: 34, + multiResSolarSystemBodies: 35, + auroraBorialis: 36, + earthCutAway: 37, + showSolarSystem: 38, + clouds8k: 39, + filedOfView: 40, + showISSModel: 41, + solarSystemCMB: 42, + mpcZone1: 43, + mpcZone2: 44, + mpcZone3: 45, + mpcZone4: 46, + mpcZone5: 47, + mpcZone6: 48, + mpcZone7: 49, + orbitFilters: 50 +}; + +registerType("StockSkyOverlayTypes", StockSkyOverlayTypes); +registerEnum("StockSkyOverlayTypes", StockSkyOverlayTypes); + + +// wwtlib.SettingParameter +// +// This was defined in `Tours/ISettings.cs`, which we've folded into `interfaces.js`. + +export function SettingParameter(edgeTrigger, opacity, targetState, filter) { + this.targetState = false; + this.edgeTrigger = false; + this.opacity = 0; + this.edgeTrigger = edgeTrigger; + this.opacity = opacity; + this.targetState = targetState; + this.filter = filter; +} + +var SettingParameter$ = {}; + +registerType("SettingParameter", [SettingParameter, SettingParameter$, null]); + + +// wwtlib.Settings + +export function Settings() { + this.autoRepeatTour = false; + this._localHorizonMode = false; + this._galacticMode = false; + this._constellationBoundryColor = 'blue'; + this._constellationSelectionColor = 'yellow'; + this._constellationFigureColor = 'red'; + this._showConstellationFigures = true; + this._showConstellationBoundries = true; + this._showConstellationSelection = true; + this._showCrosshairs = true; + this._crosshairsColor = 'white'; + this._showEcliptic = false; + this._locationLat = 47.717; + this._locationLng = -122.0858; + this._locationAltitude = 100; + this._showFiledOfView = false; + this._actualPlanetScale = true; + this._fovCamera = 0; + this._fovEyepiece = 0; + this._fovTelescope = 0; + this._showClouds = false; + this._showGrid = false; + this._showHorizon = true; + this._showHorizonPanorama = false; + this._showMoonsAsPointSource = true; + this._showSolarSystem = true; + this._solarSystemStars = true; + this._solarSystemMilkyWay = true; + this._solarSystemCosmos = true; + this._solarSystemOrbits = true; + this._solarSystemOverlays = true; + this._solarSystemLighting = true; + this._solarSystemMultiRes = true; + this._solarSystemScale = 1; + this._smoothPan = true; + this._showElevationModel = true; + this._showEquatorialGridText = false; + this._showGalacticGrid = false; + this._showGalacticGridText = false; + this._showEclipticGrid = false; + this._showEclipticGridText = false; + this._showEclipticOverviewText = false; + this._showAltAzGrid = false; + this._eclipticGridColor = Colors.get_green(); + this._galacticGridColor = Colors.get_cyan(); + this._altAzGridColor = Colors.get_magenta(); + this._precessionChartColor = Colors.get_orange(); + this._eclipticColor = Colors.get_blue(); + this._equatorialGridColor = Colors.get_white(); + this._showAltAzGridText = false; + this._showPrecessionChart = false; + this._showConstellationPictures = false; + this._showConstellationLabels = false; + this._constellationLabelsHeight = 80; + this._solarSystemCMB = true; + this._solarSystemMinorPlanets = false; + this._solarSystemPlanets = true; + this._showEarthSky = true; + this._solarSystemMinorOrbits = false; + this._constellationsEnabled = ''; + this._constellationFiguresFilter = new ConstellationFilter(); + this._constellationBoundariesFilter = new ConstellationFilter(); + this._constellationNamesFilter = new ConstellationFilter(); + this._constellationArtFilter = new ConstellationFilter(); + this._showSkyOverlays = true; + this._showConstellations = true; + this._showSkyNode = true; + this._showSkyGrids = true; + this._showSkyOverlaysIn3d = true; + this._earthCutawayView = false; + this._showISSModel = false; + this._milkyWayModel = false; + this._minorPlanetsFilter = 255; + this._planetOrbitsFilter = 2147483647; + this._constellations = true; +} + +Settings._active = null; +Settings.tourSettings = null; + +Settings.get_current = function () { + if (Settings._active == null) { + Settings._active = new Settings(); + } + return Settings._active; +}; + +Settings.get_globalSettings = function () { + if (Settings._active == null) { + Settings._active = new Settings(); + } + return Settings._active; +}; + +Settings.get_active = function () { + if (Settings._active == null) { + Settings._active = new Settings(); + } + if (Settings.tourSettings != null) { + return Settings.tourSettings; + } + return Settings._active; +}; + +var Settings$ = { + get_constellationFigureColor: function () { + return this._constellationFigureColor; + }, + + set_constellationFigureColor: function (value) { + this._constellationFigureColor = value; + return value; + }, + + get_constellationBoundryColor: function () { + return this._constellationBoundryColor; + }, + + set_constellationBoundryColor: function (value) { + this._constellationBoundryColor = value; + return value; + }, + + get_constellationSelectionColor: function () { + return this._constellationSelectionColor; + }, + + set_constellationSelectionColor: function (value) { + this._constellationSelectionColor = value; + return value; + }, + + get_showCrosshairs: function () { + return this._showCrosshairs; + }, + + set_showCrosshairs: function (value) { + this._showCrosshairs = value; + return value; + }, + + get_smoothPan: function () { + return this._smoothPan; + }, + + set_smoothPan: function (value) { + this._smoothPan = value; + return value; + }, + + get_crosshairsColor: function () { + return this._crosshairsColor; + }, + + set_crosshairsColor: function (value) { + this._crosshairsColor = value; + return value; + }, + + get_actualPlanetScale: function () { + return this._actualPlanetScale; + }, + + set_actualPlanetScale: function (value) { + this._actualPlanetScale = value; + return value; + }, + + get_fovCamera: function () { + return this._fovCamera; + }, + + get_fovEyepiece: function () { + return this._fovEyepiece; + }, + + get_fovTelescope: function () { + return this._fovTelescope; + }, + + get_locationAltitude: function () { + return this._locationAltitude; + }, + + set_locationAltitude: function (value) { + this._locationAltitude = value; + return value; + }, + + get_locationLat: function () { + return this._locationLat; + }, + + set_locationLat: function (value) { + this._locationLat = value; + return value; + }, + + get_locationLng: function () { + return this._locationLng; + }, + + set_locationLng: function (value) { + this._locationLng = value; + return value; + }, + + get_showClouds: function () { + return this._showClouds; + }, + + get_showConstellationBoundries: function () { + return this._showConstellationBoundries; + }, + + set_showConstellationBoundries: function (value) { + this._showConstellationBoundries = value; + return value; + }, + + get_showConstellationFigures: function () { + return this._showConstellationFigures; + }, + + set_showConstellationFigures: function (value) { + this._showConstellationFigures = value; + return value; + }, + + get_showConstellationSelection: function () { + return this._showConstellationSelection; + }, + + set_showConstellationSelection: function (value) { + this._showConstellationSelection = value; + return value; + }, + + get_showEcliptic: function () { + return this._showEcliptic; + }, + + set_showEcliptic: function (value) { + this._showEcliptic = value; + return value; + }, + + get_showElevationModel: function () { + return this._showElevationModel; + }, + + set_showElevationModel: function (value) { + this._showElevationModel = value; + return value; + }, + + get_showFieldOfView: function () { + return this._showFiledOfView; + }, + + get_showGrid: function () { + return this._showGrid; + }, + + set_showGrid: function (value) { + this._showGrid = value; + return value; + }, + + get_showHorizon: function () { + return this._showHorizon; + }, + + set_showHorizon: function (value) { + this._showHorizon = value; + return value; + }, + + get_showHorizonPanorama: function () { + return this._showHorizonPanorama; + }, + + get_showMoonsAsPointSource: function () { + return this._showMoonsAsPointSource; + }, + + get_showSolarSystem: function () { + return this._showSolarSystem; + }, + + set_showSolarSystem: function (value) { + this._showSolarSystem = value; + return value; + }, + + get_localHorizonMode: function () { + return this._localHorizonMode; + }, + + set_localHorizonMode: function (value) { + this._localHorizonMode = value; + return value; + }, + + get_galacticMode: function () { + return this._galacticMode; + }, + + set_galacticMode: function (value) { + this._galacticMode = value; + return value; + }, + + get_solarSystemStars: function () { + return this._solarSystemStars; + }, + + set_solarSystemStars: function (value) { + this._solarSystemStars = value; + return value; + }, + + get_solarSystemMilkyWay: function () { + return this._solarSystemMilkyWay; + }, + + set_solarSystemMilkyWay: function (value) { + this._solarSystemMilkyWay = value; + return value; + }, + + get_solarSystemCosmos: function () { + return this._solarSystemCosmos; + }, + + set_solarSystemCosmos: function (value) { + this._solarSystemCosmos = value; + return value; + }, + + get_solarSystemOrbits: function () { + return this._solarSystemOrbits; + }, + + set_solarSystemOrbits: function (value) { + this._solarSystemOrbits = value; + return value; + }, + + get_solarSystemOverlays: function () { + return this._solarSystemOverlays; + }, + + set_solarSystemOverlays: function (value) { + this._solarSystemOverlays = value; + return value; + }, + + get_solarSystemLighting: function () { + return this._solarSystemLighting; + }, + + set_solarSystemLighting: function (value) { + this._solarSystemLighting = value; + return value; + }, + + get_solarSystemMultiRes: function () { + return true; + }, + + set_solarSystemMultiRes: function (value) { + this._solarSystemMultiRes = value; + return value; + }, + + get_solarSystemScale: function () { + return this._solarSystemScale; + }, + + set_solarSystemScale: function (value) { + this._solarSystemScale = value; + return value; + }, + + get_showEquatorialGridText: function () { + return this._showEquatorialGridText; + }, + + set_showEquatorialGridText: function (value) { + this._showEquatorialGridText = value; + return value; + }, + + get_showGalacticGrid: function () { + return this._showGalacticGrid; + }, + + set_showGalacticGrid: function (value) { + this._showGalacticGrid = value; + return value; + }, + + get_showGalacticGridText: function () { + return this._showGalacticGridText; + }, + + set_showGalacticGridText: function (value) { + this._showGalacticGridText = value; + return value; + }, + + get_showEclipticGrid: function () { + return this._showEclipticGrid; + }, + + set_showEclipticGrid: function (value) { + this._showEclipticGrid = value; + return value; + }, + + get_showEclipticGridText: function () { + return this._showEclipticGridText; + }, + + set_showEclipticGridText: function (value) { + this._showEclipticGridText = value; + return value; + }, + + get_showEclipticOverviewText: function () { + return this._showEclipticOverviewText; + }, + + set_showEclipticOverviewText: function (value) { + this._showEclipticOverviewText = value; + return value; + }, + + get_showAltAzGrid: function () { + return this._showAltAzGrid; + }, + + set_showAltAzGrid: function (value) { + this._showAltAzGrid = value; + return value; + }, + + get_eclipticGridColor: function () { + return this._eclipticGridColor; + }, + + set_eclipticGridColor: function (value) { + this._eclipticGridColor = value; + return value; + }, + + get_galacticGridColor: function () { + return this._galacticGridColor; + }, + + set_galacticGridColor: function (value) { + this._galacticGridColor = value; + return value; + }, + + get_altAzGridColor: function () { + return this._altAzGridColor; + }, + + set_altAzGridColor: function (value) { + this._altAzGridColor = value; + return value; + }, + + get_precessionChartColor: function () { + return this._precessionChartColor; + }, + + set_precessionChartColor: function (value) { + this._precessionChartColor = value; + return value; + }, + + get_eclipticColor: function () { + return this._eclipticColor; + }, + + set_eclipticColor: function (value) { + this._eclipticColor = value; + return value; + }, + + get_equatorialGridColor: function () { + return this._equatorialGridColor; + }, + + set_equatorialGridColor: function (value) { + this._equatorialGridColor = value; + return value; + }, + + get_showAltAzGridText: function () { + return this._showAltAzGridText; + }, + + set_showAltAzGridText: function (value) { + this._showAltAzGridText = value; + return value; + }, + + get_showPrecessionChart: function () { + return this._showPrecessionChart; + }, + + set_showPrecessionChart: function (value) { + this._showPrecessionChart = value; + return value; + }, + + get_showConstellationPictures: function () { + return this._showConstellationPictures; + }, + + set_showConstellationPictures: function (value) { + this._showConstellationPictures = value; + return value; + }, + + get_showConstellationLabels: function () { + return this._showConstellationLabels; + }, + + set_showConstellationLabels: function (value) { + this._showConstellationLabels = value; + return value; + }, + + get_constellationLabelsHeight: function () { + return this._constellationLabelsHeight; + }, + + set_constellationLabelsHeight: function (value) { + this._constellationLabelsHeight = value; + return value; + }, + + get_solarSystemCMB: function () { + return this._solarSystemCMB; + }, + + set_solarSystemCMB: function (value) { + this._solarSystemCMB = value; + return value; + }, + + get_solarSystemMinorPlanets: function () { + return this._solarSystemMinorPlanets; + }, + + set_solarSystemMinorPlanets: function (value) { + this._solarSystemMinorPlanets = value; + return value; + }, + + get_solarSystemPlanets: function () { + return this._solarSystemPlanets; + }, + + set_solarSystemPlanets: function (value) { + this._solarSystemPlanets = value; + return value; + }, + + get_showEarthSky: function () { + return this._showEarthSky; + }, + + set_showEarthSky: function (value) { + this._showEarthSky = value; + return value; + }, + + get_solarSystemMinorOrbits: function () { + return this._solarSystemMinorOrbits; + }, + + set_solarSystemMinorOrbits: function (value) { + this._solarSystemMinorOrbits = value; + return value; + }, + + get_constellationsEnabled: function () { + return this._constellationsEnabled; + }, + + set_constellationsEnabled: function (value) { + this._constellationsEnabled = value; + return value; + }, + + get_constellationFiguresFilter: function () { + return this._constellationFiguresFilter; + }, + + set_constellationFiguresFilter: function (value) { + this._constellationFiguresFilter = value; + return value; + }, + + get_constellationBoundariesFilter: function () { + return this._constellationBoundariesFilter; + }, + + set_constellationBoundariesFilter: function (value) { + this._constellationBoundariesFilter = value; + return value; + }, + + get_constellationNamesFilter: function () { + return this._constellationNamesFilter; + }, + + set_constellationNamesFilter: function (value) { + this._constellationNamesFilter = value; + return value; + }, + + get_constellationArtFilter: function () { + return this._constellationArtFilter; + }, + + set_constellationArtFilter: function (value) { + this._constellationArtFilter = value; + return value; + }, + + get_showSkyOverlays: function () { + return this._showSkyOverlays; + }, + + set_showSkyOverlays: function (value) { + this._showSkyOverlays = value; + return value; + }, + + get_showConstellations: function () { + return this._showConstellations; + }, + + set_showConstellations: function (value) { + this._showConstellations = value; + return value; + }, + + get_showSkyNode: function () { + return this._showSkyNode; + }, + + set_showSkyNode: function (value) { + this._showSkyNode = value; + return value; + }, + + get_showSkyGrids: function () { + return this._showSkyGrids; + }, + + set_showSkyGrids: function (value) { + this._showSkyGrids = value; + return value; + }, + + get_showSkyOverlaysIn3d: function () { + return this._showSkyOverlaysIn3d; + }, + + set_showSkyOverlaysIn3d: function (value) { + this._showSkyOverlaysIn3d = value; + return value; + }, + + get_earthCutawayView: function () { + return this._earthCutawayView; + }, + + set_earthCutawayView: function (value) { + this._earthCutawayView = value; + return value; + }, + + get_showISSModel: function () { + return this._showISSModel; + }, + + set_showISSModel: function (value) { + this._showISSModel = value; + return value; + }, + + get_milkyWayModel: function () { + return this._milkyWayModel; + }, + + set_milkyWayModel: function (value) { + this._milkyWayModel = value; + return value; + }, + + get_minorPlanetsFilter: function () { + return this._minorPlanetsFilter; + }, + + set_minorPlanetsFilter: function (value) { + this._minorPlanetsFilter = value; + return value; + }, + + get_planetOrbitsFilter: function () { + return this._planetOrbitsFilter; + }, + + set_planetOrbitsFilter: function (value) { + this._planetOrbitsFilter = value; + return value; + }, + + get_constellations: function () { + return this._constellations; + }, + + set_constellations: function (value) { + this._constellations = value; + return value; + }, + + getSetting: function (type) { + if (type === 17) { + return new SettingParameter(true, 0, !!0, null); + } + return new SettingParameter(false, 1, false, null); + } +}; + +registerType("Settings", [Settings, Settings$, null, ISettings]); diff --git a/engine/esm/sky_image_tile.js b/engine/esm/sky_image_tile.js new file mode 100644 index 00000000..06a35646 --- /dev/null +++ b/engine/esm/sky_image_tile.js @@ -0,0 +1,66 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A "tile" that is really a single image displayed using a tangential +// projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { useGl, useGlVersion2 } from "./render_globals.js"; +import { WcsImage } from "./layers/wcs_image.js"; +import { TangentTile, LatLngEdges } from "./tangent_tile.js"; + + +// wwtlib.SkyImageTile + +export function SkyImageTile(level, x, y, dataset, parent) { + this.pixelCenterX = 0; + this.pixelCenterY = 0; + this.scaleX = 0.01; + this.scaleY = 0.01; + this.height = 0; + this.width = 0; + TangentTile.call(this, level, x, y, dataset, parent); + this.pixelCenterX = dataset.get_offsetX(); + this.pixelCenterY = dataset.get_offsetY(); + this.scaleX = -(this.scaleY = dataset.get_baseTileDegrees()); + if (dataset.get_bottomsUp()) { + this.scaleX = -this.scaleX; + } + this.sphereCenter = this.geoTo3dTan(0, 0); + this.radius = 1.25; + this.computeBoundingSphere(); +} + +var SkyImageTile$ = { + getLatLngEdges: function () { + var edges = new LatLngEdges(); + var wcsImage = ss.safeCast(this.dataset.get_wcsImage(), WcsImage); + if (wcsImage != null && useGl) { + if (useGlVersion2) { + this.width = wcsImage.get_sizeX(); + this.height = wcsImage.get_sizeY(); + } + else { + this.height = this.bmp.height; + this.width = this.bmp.width; + if (this.bmp.height !== wcsImage.get_sizeY()) { + this.pixelCenterY += this.bmp.height - wcsImage.get_sizeY(); + } + } + } else if (this.texture != null) { + this.height = this.texture.naturalHeight; + this.width = this.texture.naturalWidth; + } else { + this.height = 256; + this.width = 256; + } + edges.latMin = 0 + (this.scaleY * (this.height - this.pixelCenterY)); + edges.latMax = 0 - (this.scaleY * this.pixelCenterY); + edges.lngMin = 0 + (this.scaleX * this.pixelCenterX); + edges.lngMax = 0 - (this.scaleX * (this.width - this.pixelCenterX)); + return edges; + } +}; + +registerType("SkyImageTile", [SkyImageTile, SkyImageTile$, TangentTile]); diff --git a/engine/esm/sky_text.js b/engine/esm/sky_text.js new file mode 100644 index 00000000..afe41244 --- /dev/null +++ b/engine/esm/sky_text.js @@ -0,0 +1,429 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Text rendered on the sky. + +import { ss } from "./ss.js"; +import { registerType, registerEnum } from "./typesystem.js"; +import { Vector2d, Vector3d, Matrix3d, PositionTexture } from "./double3d.js"; +import { Util } from "./baseutil.js"; +import { Colors } from "./color.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { PositionTextureVertexBuffer } from "./graphics/gl_buffers.js"; +import { Texture } from "./graphics/texture.js"; +import { TextShader } from "./graphics/shaders.js"; +import { TextObject } from "./tours/text_object.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Rectangle } from "./util.js"; +import { WebFile } from "./web_file.js"; + + +// wwtlib.Alignment + +export var Alignment = { + center: 0, + left: 1 +}; + +registerType("Alignment", Alignment); +registerEnum("Alignment", Alignment); + + +// wwtlib.Text3dBatch + +export function Text3dBatch(height) { + this.height = 128; + this.items = []; + this._glyphVersion = -1; + this.viewTransform = Matrix3d.get_identity(); + this._textObject = new TextObject(); + this._vertCount = 0; + this.height = (height * 3); +} + +var Text3dBatch$ = { + add: function (newItem) { + this.items.push(newItem); + }, + + draw: function (renderContext, opacity, color) { + if (renderContext.gl == null) { + var viewPoint = Vector3d._transformCoordinate(renderContext.get_viewPoint(), this.viewTransform); + var drawHeight = (this.height / renderContext.get_fovAngle()) * renderContext.height / 180; + var $enum1 = ss.enumerate(this.items); + while ($enum1.moveNext()) { + var t3d = $enum1.current; + var screenSpacePnt = renderContext.WVP.transform(t3d.center); + if (screenSpacePnt.z < 0) { + continue; + } + if (Vector3d.dot(viewPoint, t3d.center) < 0.55) { + continue; + } + var screenSpaceTop = renderContext.WVP.transform(t3d.top); + var rotation = Math.atan2(screenSpacePnt.x - screenSpaceTop.x, screenSpacePnt.y - screenSpaceTop.y); + var ctx = renderContext.device; + ctx.save(); + ctx.translate(screenSpacePnt.x, screenSpacePnt.y); + ctx.rotate(-rotation); // todo update with up vector + ctx.globalAlpha = opacity; + ctx.fillStyle = color.toString(); + ctx.font = 'normal' + ' ' + ((false) ? 'bold' : 'normal') + ' ' + Math.round(drawHeight * 1.2).toString() + 'px ' + 'Arial'; + ctx.textBaseline = 'top'; + var tm = ctx.measureText(t3d.text); + ctx.fillText(t3d.text, -tm.width / 2, -drawHeight / 2); + ctx.restore(); + } + } else { + if (this._glyphCache == null || this._glyphCache.get_version() > this._glyphVersion) { + this.prepareBatch(); + } + if (!this._glyphCache.ready) { + return; + } + TextShader.use(renderContext, this._vertexBuffer.vertexBuffer, this._glyphCache.get_texture().texture2d); + renderContext.gl.drawArrays(WEBGL.TRIANGLES, 0, this._vertexBuffer.count); + } + }, + + prepareBatch: function () { + if (this._glyphCache == null) { + this._glyphCache = GlyphCache.getCache(this.height); + } + if (!this._glyphCache.ready) { + return; + } + this._textObject.text = ''; + this._textObject.fontSize = this.height * 0.5; + var verts = []; + var $enum1 = ss.enumerate(this.items); + while ($enum1.moveNext()) { + var t3d = $enum1.current; + var text = t3d.text; + var left = 0; + var top = 0; + var fntAdjust = this._textObject.fontSize / 128; + var factor = 0.6666; + var width = 0; + var height = 0; + for (var i = 0; i < text.length; i++) { + var item = this._glyphCache.getGlyphItem(text.substr(i, 1)); + if (item != null) { + width += item.extents.x; + height = Math.max(item.extents.y, height); + } + } + var size = Vector2d.create(width, height); + t3d.width = size.x * t3d.scale * factor * fntAdjust; + t3d.height = size.y * t3d.scale * factor * fntAdjust; + var charsLeft = text.length; + for (var i = 0; i < charsLeft; i++) { + var item = this._glyphCache.getGlyphItem(text.substr(i, 1)); + if (item != null) { + var position = Rectangle.create(left * t3d.scale * factor, 0 * t3d.scale * factor, item.extents.x * fntAdjust * t3d.scale * factor, item.extents.y * fntAdjust * t3d.scale * factor); + left += (item.extents.x * fntAdjust); + t3d.addGlyphPoints(verts, item.size, position, item.uvRect); + } + } + } + this._vertCount = verts.length; + this._vertexBuffer = new PositionTextureVertexBuffer(this._vertCount); + var vertBuf = this._vertexBuffer.lock(); + for (var i = 0; i < this._vertCount; i++) { + vertBuf[i] = verts[i]; + } + this._vertexBuffer.unlock(); + this._glyphVersion = this._glyphCache.get_version(); + }, + + cleanUp: function () { + if (this._vertexBuffer != null) { + this._vertexBuffer = null; + } + this.items.length = 0; + } +}; + +registerType("Text3dBatch", [Text3dBatch, Text3dBatch$, null]); + +// wwtlib.GlyphItem + +export function GlyphItem(glyph) { + this.referenceCount = 0; + this.glyph = glyph; + this.uvRect = new Rectangle(); + this.size = new Vector2d(); + this.referenceCount = 1; +} + +GlyphItem.create = function (glyph, uv, size, extents) { + var temp = new GlyphItem(glyph); + temp.glyph = glyph; + temp.uvRect = uv; + temp.size = size; + temp.extents = extents; + temp.referenceCount = 1; + return temp; +}; + +GlyphItem._fromXML = function (node) { + var glyph = node.attributes.getNamedItem('Glyph').nodeValue; + var item = new GlyphItem(glyph); + item.uvRect = Rectangle.create(parseFloat(node.attributes.getNamedItem('UVLeft').nodeValue), parseFloat(node.attributes.getNamedItem('UVTop').nodeValue), parseFloat(node.attributes.getNamedItem('UVWidth').nodeValue), parseFloat(node.attributes.getNamedItem('UVHeight').nodeValue)); + item.size = Vector2d.create(parseFloat(node.attributes.getNamedItem('SizeWidth').nodeValue), parseFloat(node.attributes.getNamedItem('SizeHeight').nodeValue)); + item.extents = Vector2d.create(parseFloat(node.attributes.getNamedItem('ExtentsWidth').nodeValue), parseFloat(node.attributes.getNamedItem('ExtentsHeight').nodeValue)); + return item; +}; + +var GlyphItem$ = { + addRef: function () { + this.referenceCount++; + }, + + release: function () { + this.referenceCount--; + } +}; + +registerType("GlyphItem", [GlyphItem, GlyphItem$, null]); + +// wwtlib.GlyphCache + +export function GlyphCache(height) { + this._cellHeight = 128; + this._gridSize = 8; + this.ready = false; + this._glyphItems = {}; + this.textObject = new TextObject(); + this._dirty = true; + this._textureDirty = true; + this._version = 0; + this._cellHeight = height; + this._texture = Texture.fromUrl(URLHelpers.singleton.engineAssetUrl('glyphs1.png')); + this._webFile = new WebFile(URLHelpers.singleton.engineAssetUrl('glyphs1.xml')); + this._webFile.onStateChange = ss.bind('_glyphXmlReady', this); + this._webFile.send(); +} + +GlyphCache._caches = {}; +GlyphCache._allGlyphs = ''; + +GlyphCache.getCache = function (height) { + if (!ss.keyExists(GlyphCache._caches, height)) { + GlyphCache._caches[height] = new GlyphCache(height); + } + return GlyphCache._caches[height]; +}; + +GlyphCache.cleanUpAll = function () { + ss.clearKeys(GlyphCache._caches); +}; + +var GlyphCache$ = { + get_height: function () { + return this._cellHeight; + }, + + _glyphXmlReady: function () { + if (this._webFile.get_state() === 2) { + alert(this._webFile.get_message()); + } else if (this._webFile.get_state() === 1) { + this._loadXmlGlyph(this._webFile.getXml()); + } + }, + + _loadXmlGlyph: function (xml) { + var nodes = Util.selectSingleNode(xml, 'GlyphItems'); + var $enum1 = ss.enumerate(nodes.childNodes); + while ($enum1.moveNext()) { + var glyphItem = $enum1.current; + if (glyphItem.nodeName === 'GlyphItem') { + var item = GlyphItem._fromXML(glyphItem); + this._glyphItems[item.glyph] = item; + GlyphCache._allGlyphs = GlyphCache._allGlyphs + item.glyph; + } + } + this.ready = true; + }, + + get_texture: function () { + return this._texture; + }, + + _makeTexture: function () { + this._calcOrMake(true); + }, + + getGlyphItem: function (glyph) { + if (this._dirty) { + this._calculateGlyphDetails(); + } + return this._glyphItems[glyph]; + }, + + _calculateGlyphDetails: function () { + this._calcOrMake(false); + }, + + _calcOrMake: function (makeTexture) { }, + + get_version: function () { + return this._version; + }, + + set_version: function (value) { + this._version = value; + return value; + }, + + addGlyph: function (glyph) { + if (!ss.keyExists(this._glyphItems, glyph)) { + var item = new GlyphItem(glyph); + this._glyphItems[glyph] = item; + this._dirty = true; + this._textureDirty = true; + this._version++; + GlyphCache._allGlyphs = GlyphCache._allGlyphs + glyph; + } else { + this._glyphItems[glyph].addRef(); + } + }, + + cleanUp: function () { + this._dirty = true; + this._texture = null; + }, + + dispose: function () { + this.cleanUp(); + }, + + get_dirty: function () { + return this._dirty; + }, + + set_dirty: function (value) { + this._dirty = value; + return value; + } +}; + +registerType("GlyphCache", [GlyphCache, GlyphCache$, null, ss.IDisposable]); + +// wwtlib.Text3d + +export function Text3d(center, up, text, fontsize, scale) { + this.rotation = 0; + this.tilt = 0; + this.bank = 0; + this._matInit = false; + this.color = Colors.get_white(); + this.sky = true; + this.scale = 0; + this.opacity = 1; + this.text = ''; + this.width = 1; + this.height = 1; + this.alignment = 0; + this.text = text; + this.up = up; + this.center = center; + this.scale = scale; + this.top = Vector3d.addVectors(center, Vector3d.scale(up, scale)); + if (fontsize < 0) { + this.sky = false; + } +} + +var Text3d$ = { + addGlyphPoints: function (pointList, size, position, uv) { + var points = new Array(6); + for (var i = 0; i < 6; i++) { + points[i] = new PositionTexture(); + } + var left = Vector3d.cross(this.center, this.up); + var right = Vector3d.cross(this.up, this.center); + left.normalize(); + right.normalize(); + this.up.normalize(); + var upTan = Vector3d.cross(this.center, right); + upTan.normalize(); + if (!this.alignment) { + left.multiply(this.width - position.get_left() * 2); + right.multiply(this.width - ((this.width * 2) - position.get_right() * 2)); + } else if (this.alignment === 1) { + left.multiply(-position.get_left() * 2); + right.multiply(position.get_right() * 2); + } + var top = upTan.copy(); + var bottom = Vector3d.subtractVectors(Vector3d.get_empty(), upTan); + top.multiply(this.height - position.get_top() * 2); + bottom.multiply(this.height - ((this.height * 2) - position.get_bottom() * 2)); + var ul = this.center.copy(); + ul.add(top); + if (this.sky) { + ul.add(left); + } else { + ul.subtract(left); + } + var ur = this.center.copy(); + ur.add(top); + if (this.sky) { + ur.add(right); + } else { + ur.subtract(right); + } + var ll = this.center.copy(); + if (this.sky) { + ll.add(left); + } else { + ll.subtract(left); + } + ll.add(bottom); + var lr = this.center.copy(); + if (this.sky) { + lr.add(right); + } else { + lr.subtract(right); + } + lr.add(bottom); + points[0].position = ul.copy(); + points[0].tu = uv.get_left(); + points[0].tv = uv.get_top(); + points[2].tu = uv.get_left(); + points[2].tv = uv.get_bottom(); + points[2].position = ll.copy(); + points[1].tu = uv.get_right(); + points[1].tv = uv.get_top(); + points[1].position = ur.copy(); + points[3].tu = uv.get_right(); + points[3].tv = uv.get_bottom(); + points[3].position = lr.copy(); + points[5].tu = uv.get_right(); + points[5].tv = uv.get_top(); + points[5].position = ur.copy(); + points[4].tu = uv.get_left(); + points[4].tv = uv.get_bottom(); + points[4].position = ll.copy(); + if (!!this.rotation || !!this.tilt || !!this.bank) { + if (!this._matInit) { + var lookAt = Matrix3d.lookAtLH(this.center, new Vector3d(), this.up); + var lookAtInv = lookAt.clone(); + lookAtInv.invert(); + this._rtbMat = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(lookAt, Matrix3d._rotationZ(-this.rotation / 180 * Math.PI)), Matrix3d._rotationX(-this.tilt / 180 * Math.PI)), Matrix3d._rotationY(-this.bank / 180 * Math.PI)), lookAtInv); + // "todo make this true after debug" + this._matInit = true; + } + for (var i = 0; i < 6; i++) { + points[i].position = Vector3d._transformCoordinate(points[i].position, this._rtbMat); + } + } + var $enum1 = ss.enumerate(points); + while ($enum1.moveNext()) { + var pnt = $enum1.current; + pointList.push(pnt); + } + } +}; + +registerType("Text3d", [Text3d, Text3d$, null]); diff --git a/engine/esm/space_time_controller.js b/engine/esm/space_time_controller.js new file mode 100644 index 00000000..7451214e --- /dev/null +++ b/engine/esm/space_time_controller.js @@ -0,0 +1,249 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The WWT clock and related calculations. + +import { registerType } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { DT } from "./astrocalc/date.js"; +import { AstroCalc } from "./astrocalc.js"; +import { Coordinates } from "./coordinates.js"; +import { Settings } from "./settings.js"; + + +// wwtlib.SpaceTimeController + +export function SpaceTimeController() { } + +SpaceTimeController.framesPerSecond = 30; +SpaceTimeController.frameDumping = false; +SpaceTimeController.cancelFrameDump = false; +SpaceTimeController.currentFrameNumber = 0; +SpaceTimeController.totalFrames = 0; +SpaceTimeController._offset = 0; +SpaceTimeController._syncToClock = true; +SpaceTimeController._timeRate = 1; +SpaceTimeController._altitude = 0; + +SpaceTimeController.updateClock = function () { + if (SpaceTimeController._syncToClock) { + var justNow = SpaceTimeController.get_metaNow(); + if (SpaceTimeController._timeRate !== 1) { + var ts = justNow.getTime() - SpaceTimeController.last.getTime(); + var ticks = (ts * SpaceTimeController._timeRate); + SpaceTimeController._offset += ticks; + } + SpaceTimeController.last = justNow; + try { + SpaceTimeController._now = new Date(justNow.getTime() + SpaceTimeController._offset); + } + catch ($e1) { + SpaceTimeController._now = new Date(1, 12, 25, 23, 59, 59); + SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); + } + if (SpaceTimeController._now.getFullYear() > 4000) { + SpaceTimeController._now = new Date(4000, 12, 31, 23, 59, 59); + SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); + } + if (SpaceTimeController._now.getFullYear() < 1) { + SpaceTimeController._now = new Date(0, 12, 25, 23, 59, 59); + SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); + } + } +}; + +SpaceTimeController.getTimeForFutureTime = function (delta) { + try { + if (SpaceTimeController._syncToClock) { + var future = new Date((SpaceTimeController.get_now().getTime() + (delta * 1000) * SpaceTimeController._timeRate)); + return future; + } else { + return SpaceTimeController.get_now(); + } + } + catch ($e1) { + return SpaceTimeController.get_now(); + } +}; + +SpaceTimeController.getJNowForFutureTime = function (delta) { + try { + if (SpaceTimeController._syncToClock) { + var future = new Date(SpaceTimeController.get_now().getTime() + ss.truncate((delta * 1000 * SpaceTimeController._timeRate))); + return SpaceTimeController.utcToJulian(future); + } else { + return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); + } + } + catch ($e1) { + return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); + } +}; + +SpaceTimeController.get_now = function () { + return SpaceTimeController._now; +}; + +SpaceTimeController.set_now = function (value) { + SpaceTimeController._now = value; + SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); + SpaceTimeController.last = SpaceTimeController.get_metaNow(); + return value; +}; + +SpaceTimeController.get_metaNow = function () { + return SpaceTimeController._metaNow; +}; + +SpaceTimeController.set_metaNow = function (value) { + if (!SpaceTimeController.frameDumping) { + SpaceTimeController._metaNow = value; + } + return value; +}; + +SpaceTimeController.nextFrame = function () { + SpaceTimeController._metaNow.setMilliseconds(SpaceTimeController._metaNow.getMilliseconds() + Math.round(1000 / SpaceTimeController.framesPerSecond)); + SpaceTimeController.currentFrameNumber += 1; +}; + +SpaceTimeController.get_doneDumping = function () { + return !SpaceTimeController.frameDumping || SpaceTimeController.cancelFrameDump || (SpaceTimeController.currentFrameNumber >= SpaceTimeController.totalFrames); +}; + +SpaceTimeController.syncTime = function () { + SpaceTimeController._offset = 0; + SpaceTimeController._now = ss.now(); + SpaceTimeController._syncToClock = true; +}; + +SpaceTimeController.get_jNow = function () { + return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); +}; + +SpaceTimeController.get_syncToClock = function () { + return SpaceTimeController._syncToClock; +}; + +SpaceTimeController.set_syncToClock = function (value) { + if (SpaceTimeController._syncToClock !== value) { + SpaceTimeController._syncToClock = value; + if (value) { + SpaceTimeController.last = ss.now(); + SpaceTimeController._offset = SpaceTimeController._now - ss.now(); + } else { + SpaceTimeController._now = new Date(ss.now().getTime() + SpaceTimeController._offset); + } + } + return value; +}; + +SpaceTimeController.get_timeRate = function () { + return SpaceTimeController._timeRate; +}; + +SpaceTimeController.set_timeRate = function (value) { + SpaceTimeController._timeRate = value; + return value; +}; + +SpaceTimeController.get_altitude = function () { + return SpaceTimeController._altitude; +}; + +SpaceTimeController.set_altitude = function (value) { + SpaceTimeController._altitude = value; + return value; +}; + +SpaceTimeController.get_location = function () { + SpaceTimeController._location = Coordinates.fromLatLng(Settings.get_active().get_locationLat(), Settings.get_active().get_locationLng()); + SpaceTimeController._altitude = Settings.get_active().get_locationAltitude(); + return SpaceTimeController._location; +}; + +SpaceTimeController.set_location = function (value) { + if (Settings.get_globalSettings().get_locationLat() !== value.get_lat()) { + Settings.get_globalSettings().set_locationLat(value.get_lat()); + } + if (Settings.get_globalSettings().get_locationLng() !== value.get_lng()) { + Settings.get_globalSettings().set_locationLng(value.get_lng()); + } + SpaceTimeController._location = value; + return value; +}; + +SpaceTimeController.julianToUtc = function (jDate) { + var date = new DT(); + date.setJD(jDate, true); + var ms = (date.second() - ss.truncate(date.second())) * 1000; + return new Date(date.year(), date.month() - 1, date.day(), date.hour(), date.minute(), ss.truncate(date.second()), ss.truncate(ms)); +}; + +SpaceTimeController._twoLineDateToJulian = function (p) { + var pre1950 = parseInt(p.substring(0, 1)) < 6; + var year = parseInt(((pre1950) ? ' 20' : '19') + p.substring(0, 2)); + var days = parseFloat(p.substring(2, 3)); + var fraction = parseFloat(p.substr(5)); + var date = new Date(year, 0, 1, 0, 0); + return SpaceTimeController.utcToJulian(date) + (days - 1 + fraction); +}; + +SpaceTimeController.julianToTwoLineDate = function (jDate) { + return SpaceTimeController.dateToTwoLineDate(SpaceTimeController.julianToUtc(jDate)); +}; + +SpaceTimeController.dateToTwoLineDate = function (date) { + var sb = new ss.StringBuilder(); + sb.append(date.getFullYear() % 100); + var fullYear = new Date(date.getFullYear(), 0, 1, 0, 0); + var dayofyear = Math.floor((date - fullYear) / (60 * 60 * 24 * 1000)) + 2; + var day = dayofyear + date.getHours() / 24 + date.getMinutes() / 60 / 24 + date.getSeconds() / 60 / 60 / 24 + date.getMilliseconds() / 1000 / 60 / 60 / 24; + var sDay = SpaceTimeController.tleDayString(day); + sb.append(sDay); + return sb.toString(); +}; + +SpaceTimeController.tleDayString = function (day) { + var formated = day.toString(); + var point = formated.indexOf('.'); + if (point === -1) { + point = formated.length; + formated += '.0'; + } + var len = formated.length - point - 1; + var fill = '00000000'; + formated = fill.substr(0, 3 - point) + formated + fill.substr(0, 8 - len); + return formated; +}; + +SpaceTimeController.utcToJulian = function (utc) { + var year = utc.getUTCFullYear(); + var month = utc.getUTCMonth() + 1; + var day = utc.getUTCDate(); + var hour = utc.getUTCHours(); + var minute = utc.getUTCMinutes(); + var second = utc.getUTCSeconds() + utc.getUTCMilliseconds() / 1000; + var dblDay = day + (hour / 24) + (minute / 1440) + (second / 86400); + return AstroCalc.getJulianDay(year, month, dblDay); +}; + +SpaceTimeController.dateToJD = function (Year, Month, Day, bGregorianCalendar) { + var Y = Year; + var M = Month; + if (M < 3) { + Y = Y - 1; + M = M + 12; + } + var A = 0; + var B = 0; + if (bGregorianCalendar) { + A = ss.truncate((Y / 100)); + B = 2 - A + ss.truncate((A / 4)); + } + return ss.truncate((365.25 * (Y + 4716))) + ss.truncate((30.6001 * (M + 1))) + Day + B - 1524.5; +}; + +var SpaceTimeController$ = {}; + +registerType("SpaceTimeController", [SpaceTimeController, SpaceTimeController$, null]); diff --git a/engine/js/ss.js b/engine/esm/ss.js similarity index 98% rename from engine/js/ss.js rename to engine/esm/ss.js index 9309cfe7..947b3919 100644 --- a/engine/js/ss.js +++ b/engine/esm/ss.js @@ -1,9 +1,14 @@ +// This file is part of WorldWide Telescope and derived from: + /*! Script# Runtime * Designed and licensed for use and distribution with Script#-generated scripts. * Copyright (c) 2012, Nikhil Kothari, and the Script# Project. * More information at http://scriptsharp.com */ +// It has been customized to adapt to the particulars of the WWT JavaScript +// build system. + function _ss() { "use strict"; @@ -134,7 +139,7 @@ function _ss() { function fail(message) { console.assert(false, message); - if (global.navigator) { + if (globalThis.navigator) { eval('debugger;'); } } @@ -323,7 +328,7 @@ function _ss() { return (s1 === s2) ? 0 : (s1 < s2) ? -1 : 1; } - var _formatPlaceHolderRE = /(\{[^\}^\{]+\})/g; + var _formatPlaceHolderRE = /(\{[^}^{]+\})/g; var _formatters = {}; function format(cultureOrFormat) { @@ -507,7 +512,7 @@ function _ss() { // If unspecified, exported bindings go on the global object // (so they are callable using a simple identifier). - root = root || global; + root = root || globalThis; var exp = { name: name, @@ -1329,7 +1334,7 @@ function _ss() { function type(s) { var nsIndex = s.indexOf('.'); - var ns = nsIndex > 0 ? _modules[s.substr(0, nsIndex)] : global; + var ns = nsIndex > 0 ? _modules[s.substr(0, nsIndex)] : globalThis; var name = nsIndex > 0 ? s.substr(nsIndex + 1) : s; return ns ? ns[name] : null; @@ -1434,6 +1439,11 @@ function _ss() { return api; } + function createRegistry(name) { + var registry = _modules[name] = { $name: name }; + return registry; + } + return extend(ss_module('ss', null, { IDisposable: [IDisposable], IEnumerable: [IEnumerable], @@ -1497,6 +1507,8 @@ function _ss() { module: ss_module, modules: _modules, + createRegistry: createRegistry, + createType: createType, isClass: isClass, isInterface: isInterface, @@ -1517,4 +1529,4 @@ function _ss() { }); } -var ss = _ss(); \ No newline at end of file +export var ss = _ss(); \ No newline at end of file diff --git a/engine/esm/star.js b/engine/esm/star.js new file mode 100644 index 00000000..762d13ba --- /dev/null +++ b/engine/esm/star.js @@ -0,0 +1,215 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Information about catalogued objects. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Util } from "./baseutil.js"; +import { Color } from "./color.js"; +import { Coordinates } from "./coordinates.js"; + + +// wwtlib.Star + +export function Star(input) { + this.magnitude = 0; + this.RA = 0; + this.dec = 0; + this.BMV = 0; + this.id = 0; + this.absoluteMagnitude = 0; + this.par = 0; + this.distance = 0; + var sa = input.split('\t'); + this.id = parseInt(ss.replaceString(sa[0], 'HIP', '')); + this.dec = parseFloat(sa[3]); + this.RA = parseFloat(sa[2]) / 15; + if (sa.length > 4) { + try { + if (sa[4].toUpperCase() !== 'NULL' && !!sa[4]) { + this.magnitude = parseFloat(sa[4]); + } + } + catch ($e1) { + } + } + if (sa.length > 5) { + try { + this.BMV = parseFloat(sa[5]); + this._makeColor(this.BMV); + } + catch ($e2) { + } + } + if (sa.length > 6) { + this.par = parseFloat(sa[6]); + this._makeDistanceAndMagnitude(); + } +} + +var Star$ = { + get_name: function () { + return 'HIP' + this.id.toString(); + }, + + get_coordinates: function () { + return Coordinates.fromRaDec(this.RA, this.dec); + }, + + stars: function (input, newish) { + var sa = input.split('\t'); + this.id = parseInt(sa[0]); + this.RA = parseFloat(sa[1]) / 15; + this.dec = parseFloat(sa[2]); + if (sa.length > 3) { + try { + this.magnitude = parseFloat(sa[3]); + } + catch ($e1) { + } + } + if (sa.length > 4) { + try { + this.col = Color.load(sa[4]); + } + catch ($e2) { + } + } + }, + + _makeDistanceAndMagnitude: function () { + this.distance = 1 / (this.par / 1000); + this.absoluteMagnitude = this.magnitude - 5 * (Util.logN(this.distance, 10) - 1); + //Convert to AU + this.distance *= 206264.806; + }, + + _makeColor: function (bmv) { + var c = 0xFFFFFFFF; + + if (bmv <= -0.32) { + c = 0xFFA2B8FF; + } else if (bmv <= -0.31) { + c = 0xFFA3B8FF; + } else if (bmv <= -0.3) { + c = 0xFFA4BAFF; + } + // mistake in original source. Should this be "<= -0.29" or something? + // else if (bmv <= -0.3) { + // c = 0xFFA5BAFF; + // } + else if (bmv <= -0.28) { + c = 0xFFA7BCFF; + } else if (bmv <= -0.26) { + c = 0xFFA9BDFF; + } else if (bmv <= -0.24) { + c = 0xFFABBFFF; + } else if (bmv <= -0.2) { + c = 0xFFAFC2FF; + } else if (bmv <= -0.16) { + c = 0xFFB4C6FF; + } else if (bmv <= -0.14) { + c = 0xFFB6C8FF; + } else if (bmv <= -0.12) { + c = 0xFFB9CAFF; + } else if (bmv <= -0.09) { + c = 0xFFBCCDFF; + } else if (bmv <= -0.06) { + c = 0xFFC1D0FF; + } else if (bmv <= 0) { + c = 0xFFCAD6FF; + } else if (bmv <= 0.06) { + c = 0xFFD2DCFF; + } else if (bmv <= 0.14) { + c = 0xFFDDE4FF; + } else if (bmv <= 0.19) { + c = 0xFFE3E8FF; + } else if (bmv <= 0.31) { + c = 0xFFF2F2FF; + } else if (bmv <= 0.36) { + c = 0xFFF9F6FF; + } else if (bmv <= 0.43) { + c = 0xFFFFF9FC; + } else if (bmv <= 0.54) { + c = 0xFFFFF6F3; + } else if (bmv <= 0.59) { + c = 0xFFFFF3EB; + } else if (bmv <= 0.63) { + c = 0xFFFFF1E7; + } else if (bmv <= 0.66) { + c = 0xFFFFEFE1; + } else if (bmv <= 0.74) { + c = 0xFFFFEEDD; + } else if (bmv <= 0.82) { + c = 0xFFFFEAD5; + } else if (bmv <= 0.92) { + c = 0xFFFFE4C4; + } else if (bmv <= 1.15) { + c = 0xFFFFFDFB8; + } else if (bmv <= 1.3) { + c = 0xFFFFDDB4; + } else if (bmv <= 1.41) { + c = 0xFFFFD39D; + } else if (bmv <= 1.48) { + c = 0xFFFFCD91; + } else if (bmv <= 1.52) { + c = 0xFFFFC987; + } else if (bmv <= 1.55) { + c = 0xFFFFC57F; + } else if (bmv <= 1.56) { + c = 0xFFFFC177; + } else if (bmv <= 1.61) { + c = 0xFFFFBD71; + } else if (bmv <= 1.72) { + c = 0xFFFFB866; + } else if (bmv <= 1.84) { + c = 0xFFFFB25B; + } else if (bmv <= 2) { + c = 0xFFFFAD51; + } + + this.col = Color.fromInt(c); + } +}; + +registerType("Star", [Star, Star$, null]); + + +// wwtlib.Galaxy + +export function Galaxy(br) { + this.RA = 0; + this.dec = 0; + this.distance = 0; + this.type = 0; + this.eTypeBucket = 0; + this.size = 5; + this.sdssID = 0; + this.sdssID = br.readInt64(); + this.RA = br.readSingle(); + this.dec = br.readSingle(); + this.distance = br.readSingle(); + this.eTypeBucket = br.readByte(); + this.size = br.readSingle(); +} + +Galaxy._eTypeBuckets = [-3, -0.186, -0.168, -0.158, -0.15, -0.143, -0.137, -0.13, -0.123, -0.115, -0.104, -0.089, -0.068, -0.042, -0.011, 0.024, 0.064, 0.111, 0.169, 0.252, 3]; + +Galaxy.getEType = function (value) { + var a = 0; + var b = Galaxy._eTypeBuckets.length - 1; + while (b - a > 1) { + var m = (a + b) / 2; + if (value > Galaxy._eTypeBuckets[m]) { + a = m; + } else { + b = m; + } + } + return a; +}; + +var Galaxy$ = {}; + +registerType("Galaxy", [Galaxy, Galaxy$, null]); diff --git a/engine/esm/tangent_tile.js b/engine/esm/tangent_tile.js new file mode 100644 index 00000000..1ccdb68f --- /dev/null +++ b/engine/esm/tangent_tile.js @@ -0,0 +1,216 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses a tangential (gnomonic) projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { tileCacheRemoveFromQueue, tilePrepDevice, useGlVersion2 } from "./render_globals.js"; +import { Vector3d, PositionTexture } from "./double3d.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { FitsImage } from "./layers/fits_image.js"; +import { Tile } from "./tile.js"; + + +// wwtlib.LatLngEdges + +export function LatLngEdges() { + this.latMin = 0; + this.latMax = 0; + this.lngMin = 0; + this.lngMax = 0; +} + +var LatLngEdges$ = {}; + +registerType("LatLngEdges", [LatLngEdges, LatLngEdges$, null]); + + +// wwtlib.TangentTile + +export function TangentTile(level, x, y, dataset, parent) { + this._topDown$1 = true; + Tile.call(this); + this.parent = parent; + this.level = level; + this.tileX = x; + this.tileY = y; + this.dataset = dataset; + this._topDown$1 = !dataset.get_bottomsUp(); + this.computeBoundingSphere(); +} + +var TangentTile$ = { + computeBoundingSphere: function () { + if (!this._topDown$1) { + this.computeBoundingSphereBottomsUp(); + return; + } + var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var latMin = (this.dataset.get_baseTileDegrees() / 2 - (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); + var latMax = (this.dataset.get_baseTileDegrees() / 2 - ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); + var lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + var lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + var latCenter = (latMin + latMax) / 2; + var lngCenter = (lngMin + lngMax) / 2; + this.sphereCenter = this.geoTo3dTan(latCenter, lngCenter); + this.topLeft = this.geoTo3dTan(latMin, lngMin); + this.bottomRight = this.geoTo3dTan(latMax, lngMax); + this.topRight = this.geoTo3dTan(latMin, lngMax); + this.bottomLeft = this.geoTo3dTan(latMax, lngMin); + var distVect = this.geoTo3dTan(latMin, lngMin); + distVect.subtract(this.sphereCenter); + this.sphereRadius = distVect.length(); + }, + + computeBoundingSphereBottomsUp: function () { + var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var latMin = (this.dataset.get_baseTileDegrees() / 2 + ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); + var latMax = (this.dataset.get_baseTileDegrees() / 2 + (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); + var lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + var lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + this.topLeft = this.geoTo3dTan(latMin, lngMin); + this.bottomRight = this.geoTo3dTan(latMax, lngMax); + this.topRight = this.geoTo3dTan(latMin, lngMax); + this.bottomLeft = this.geoTo3dTan(latMax, lngMin); + }, + + getLatLngEdges: function () { + var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); + var edges = new LatLngEdges(); + edges.latMin = (this.dataset.get_baseTileDegrees() / 2 - (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); + edges.latMax = (this.dataset.get_baseTileDegrees() / 2 - ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); + edges.lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + edges.lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); + return edges; + }, + + geoTo3dTan: function (lat, lng) { + lng = -lng; + var fac1 = this.dataset.get_baseTileDegrees() / 2; + var factor = Math.tan(fac1 * Tile.RC); + return this.dataset.get_matrix().transform(Vector3d.create(1, (lat / fac1 * factor), (lng / fac1 * factor))); + }, + + requestImage: function () { + this.fitsImage = ss.safeCast(this.dataset.get_wcsImage(), FitsImage); + if (this.fitsImage != null) { + this.texReady = true; + this.downloading = false; + this.errored = this.fitsImage.errored; + this.requestPending = false; + tileCacheRemoveFromQueue(this.get_key(), true); + if (useGlVersion2) { + this.makeTexture(); + this.readyToRender = true; + } + else { + //Cached bitmap for performance reasons + //Only used in legacy rendering of FITS (WebGL 1.0) inside SkyImageTile + this.bmp = this.fitsImage.getBitmap(); + this.texture2d = this.bmp.getTexture(); + this.readyToRender = true; + } + } else { + Tile.prototype.requestImage.call(this); + } + }, + + createGeometry: function (renderContext) { + if (this.geometryCreated) { + return true; + } + this.geometryCreated = true; + for (var i = 0; i < 4; i++) { + this._renderTriangleLists[i] = []; + } + this.globalCenter = this.geoTo3dTan(0, 0); + var edges = this.getLatLngEdges(); + this.topLeft = this.geoTo3dTan(edges.latMin, edges.lngMin).subtract(this.globalCenter); + this.bottomRight = this.geoTo3dTan(edges.latMax, edges.lngMax).subtract(this.globalCenter); + this.topRight = this.geoTo3dTan(edges.latMin, edges.lngMax).subtract(this.globalCenter); + this.bottomLeft = this.geoTo3dTan(edges.latMax, edges.lngMin).subtract(this.globalCenter); + var center = Vector3d.midPoint(this.topLeft, this.bottomRight); + var leftCenter = Vector3d.midPoint(this.topLeft, this.bottomLeft); + var rightCenter = Vector3d.midPoint(this.topRight, this.bottomRight); + var topCenter = Vector3d.midPoint(this.topLeft, this.topRight); + var bottomCenter = Vector3d.midPoint(this.bottomLeft, this.bottomRight); + if (renderContext.gl == null) { + this._renderTriangleLists[0].push(RenderTriangle.create(PositionTexture.createPos(this.topLeft, 0, 0), PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(topCenter, 0.5, 0), this.texture, this.level)); + this._renderTriangleLists[0].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(topCenter, 0.5, 0), this.texture, this.level)); + this._renderTriangleLists[1].push(RenderTriangle.create(PositionTexture.createPos(topCenter, 0.5, 0), PositionTexture.createPos(rightCenter, 1, 0.5), PositionTexture.createPos(this.topRight, 1, 0), this.texture, this.level)); + this._renderTriangleLists[1].push(RenderTriangle.create(PositionTexture.createPos(topCenter, 0.5, 0), PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(rightCenter, 1, 0.5), this.texture, this.level)); + this._renderTriangleLists[2].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(bottomCenter, 0.5, 1), PositionTexture.createPos(center, 0.5, 0.5), this.texture, this.level)); + this._renderTriangleLists[2].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(this.bottomLeft, 0, 1), PositionTexture.createPos(bottomCenter, 0.5, 1), this.texture, this.level)); + this._renderTriangleLists[3].push(RenderTriangle.create(PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(this.bottomRight, 1, 1), PositionTexture.createPos(rightCenter, 1, 0.5), this.texture, this.level)); + this._renderTriangleLists[3].push(RenderTriangle.create(PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(bottomCenter, 0.5, 1), PositionTexture.createPos(this.bottomRight, 1, 1), this.texture, this.level)); + this.readyToRender = true; + } else { + //process vertex list + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(9 * 5); + var buffer = f32array; + var index = 0; + index = this.addVertex(buffer, index, PositionTexture.createPos(bottomCenter, 0.5, 1)); + index = this.addVertex(buffer, index, PositionTexture.createPos(this.bottomLeft, 0, 1)); + index = this.addVertex(buffer, index, PositionTexture.createPos(this.bottomRight, 1, 1)); + index = this.addVertex(buffer, index, PositionTexture.createPos(center, 0.5, 0.5)); + index = this.addVertex(buffer, index, PositionTexture.createPos(leftCenter, 0, 0.5)); + index = this.addVertex(buffer, index, PositionTexture.createPos(rightCenter, 1, 0.5)); + index = this.addVertex(buffer, index, PositionTexture.createPos(topCenter, 0.5, 0)); + index = this.addVertex(buffer, index, PositionTexture.createPos(this.topLeft, 0, 0)); + index = this.addVertex(buffer, index, PositionTexture.createPos(this.topRight, 1, 0)); + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + + // process index buffers + for (var i = 0; i < 4; i++) { + index = 0; + this.triangleCount = 2; + var ui16array = new Uint16Array(this.triangleCount * 3); + var indexArray = ui16array; + switch (i) { + case 0: + indexArray[index++] = 7; + indexArray[index++] = 4; + indexArray[index++] = 6; + indexArray[index++] = 4; + indexArray[index++] = 3; + indexArray[index++] = 6; + break; + case 1: + indexArray[index++] = 6; + indexArray[index++] = 5; + indexArray[index++] = 8; + indexArray[index++] = 6; + indexArray[index++] = 3; + indexArray[index++] = 5; + break; + case 2: + indexArray[index++] = 4; + indexArray[index++] = 0; + indexArray[index++] = 3; + indexArray[index++] = 4; + indexArray[index++] = 1; + indexArray[index++] = 0; + break; + case 3: + indexArray[index++] = 3; + indexArray[index++] = 2; + indexArray[index++] = 5; + indexArray[index++] = 3; + indexArray[index++] = 0; + indexArray[index++] = 2; + break; + } + this._indexBuffers[i] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, this._indexBuffers[i]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, ui16array, WEBGL.STATIC_DRAW); + } + } + return true; + } +}; + +registerType("TangentTile", [TangentTile, TangentTile$, Tile]); diff --git a/engine/esm/tile.js b/engine/esm/tile.js new file mode 100644 index 00000000..be8c8fc5 --- /dev/null +++ b/engine/esm/tile.js @@ -0,0 +1,841 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The base class for tiles in image tile pyramids. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d, Vector4d, ConvexHull } from "./double3d.js"; +import { + tileCacheAddTileToQueue, + tileCacheGetCachedTile, + tileCacheGetTile, + tileCacheRemoveFromQueue, + tilePrepDevice, + tileDemEnabled, + useGlVersion2, + inc_tileCacheAccessID, + set_tileDemEnabled, + set_tileUvMultiple, +} from "./render_globals.js"; +import { freestandingMode } from "./data_globals.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { Texture } from "./graphics/texture.js"; +import { FitsShader, TileShader } from "./graphics/shaders.js"; +import { getTileKey } from "./util.js"; +import { BlendState } from "./blend_state.js"; +import { URLHelpers } from "./url_helpers.js"; +import { ColorMapContainer } from "./layers/color_map_container.js"; +import { FitsImageJs } from "./layers/fits_image_js.js"; +import { FitsImageTile } from "./layers/fits_image_tile.js"; + + +// wwtlib.Tile + +export function Tile() { + this._renderTriangleLists = new Array(4); + this._indexBuffers = new Array(4); + this.level = 0; + this.tileX = 0; + this.tileY = 0; + this.texture = null; + this.texture2d = null; + this.isCatalogTile = false; + this.readyToRender = false; + this.inViewFrustum = true; + this.globalCenter = Vector3d.zero; + this.children = [null, null, null, null]; + this.parent = null; + this.localCenter = new Vector3d(); + this.renderedAtOrBelowGeneration = 0; + this._demScaleFactor = 6371000; + this.demIndex = 0; + this.demAverage = 0; + this.demReady = false; + this.texReady = false; + this.demTile = false; + this.demDownloading = false; + this.renderedGeneration = 0; + this.accomidation = 0; + this.accessCount = 0; + this.downloading = false; + this.geometryCreated = false; + this._isHdTile = false; + this.demSize = 33 * 33; + this._topLeftScreen = new Vector3d(); + this._bottomRightScreen = new Vector3d(); + this._topRightScreen = new Vector3d(); + this._bottomLeftScreen = new Vector3d(); + this.sphereRadius = 0; + this.sphereCenter = new Vector3d(); + this.radius = 1; + this.triangleCount = 0; + this.requestHits = 0; + this.requestPending = false; + this.errored = false; + this._key = null; + this._tileId = null; + this._vertexCount = 0; + this.renderChildPart = null; + this.renderChildPart = new Array(4); + for (var i = 0; i < 4; i++) { + this.renderChildPart[i] = BlendState.create(false, 500); + } +} + +Tile.currentRenderGeneration = 0; +Tile.tileTargetX = -1; +Tile.tileTargetY = -1; +Tile.tileTargetLevel = -1; +Tile.tilesInView = 0; +Tile.trianglesRendered = 0; +Tile.tilesTouched = 0; +Tile.frustumList = null; +set_tileUvMultiple(1); +Tile.callCount = 0; +Tile.useAccomidation = true; +set_tileDemEnabled(true); +Tile.maxLevel = 20; +Tile.meshComplexity = 50; +Tile.imageQuality = 50; +Tile.lastDeepestLevel = 0; +Tile.deepestLevel = 0; +Tile.RC = (3.1415927 / 180); + +Tile.getFrustumList = function () { + try { + return Tile.frustumList; + } + catch ($e1) { + return null; + } +}; + +Tile.get_subDivisions = function () { + return 32; +}; + +var Tile$ = { + getIndexBuffer: function (index, accomidation) { + return this._indexBuffers[index]; + }, + + isPointInTile: function (lat, lng) { + return false; + }, + + getSurfacePointAltitude: function (lat, lng, meters) { + return 0; + }, + + makeTexture: function () { + if (tilePrepDevice != null) { + try { + this.texture2d = tilePrepDevice.createTexture(); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, this.texture2d); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_S, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_T, WEBGL.CLAMP_TO_EDGE); + if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1 && useGlVersion2) { + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.R32F, ss.truncate(this.fitsImage.get_sizeX()), ss.truncate(this.fitsImage.get_sizeY()), 0, WEBGL.RED, WEBGL.FLOAT, this.fitsImage.dataUnit); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.NEAREST); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MAG_FILTER, WEBGL.NEAREST); + } + else { + var image = this.texture; + // Before we bind resize to a power of two if nessesary so we can MIPMAP + if ((!Texture.isPowerOfTwo(this.texture.height) | !Texture.isPowerOfTwo(this.texture.width)) === 1) { + var temp = document.createElement('canvas'); + temp.height = Texture.fitPowerOfTwo(image.height); + temp.width = Texture.fitPowerOfTwo(image.width); + var ctx = temp.getContext('2d'); + ctx.drawImage(image, 0, 0, temp.width, temp.height); + //Substitute the resized image + image = temp; + } + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGBA, WEBGL.RGBA, WEBGL.UNSIGNED_BYTE, image); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.LINEAR_MIPMAP_NEAREST); + tilePrepDevice.generateMipmap(WEBGL.TEXTURE_2D); + } + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, null); + } + catch ($e1) { + this.errored = true; + } + } + }, + + addVertex: function (buffer, index, p) { + buffer[index++] = p.position.x; + buffer[index++] = p.position.y; + buffer[index++] = p.position.z; + buffer[index++] = p.tu; + buffer[index++] = p.tv; + return index; + }, + + geoTo3dWithAlt: function (lat, lng, useLocalCenter, rev) { + lat = Math.max(Math.min(90, lat), -90); + lng = Math.max(Math.min(180, lng), -180); + if (!tileDemEnabled || this.demData == null) { + return this.geoTo3d(lat, lng, useLocalCenter); + } + if (rev) { + lng -= 180; + } + var altitude = this.demData[this.demIndex]; + var retVal = this.geoTo3dWithAltitude(lat, lng, altitude, useLocalCenter); + return retVal; + }, + + geoTo3dWithAltitude: function (lat, lng, altitude, useLocalCenter) { + var radius = 1 + (altitude / this.get__demScaleFactor()); + var retVal = Vector3d.create((Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * radius), (Math.sin(lat * Tile.RC) * radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * radius)); + if (useLocalCenter) { + retVal.subtract(this.localCenter); + } + return retVal; + }, + + get__demScaleFactor: function () { + return this._demScaleFactor; // / Properties.Settings.Default.TerrainScaling; + }, + + set__demScaleFactor: function (value) { + this._demScaleFactor = value; + return value; + }, + + requestImage: function () { + var $this = this; + + if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1) { + if (!this.downloading && !this.readyToRender) { + this.downloading = true; + if (useGlVersion2) { + this.fitsImage = new FitsImageTile(this.dataset, this.get_URL(), function (wcsImage) { + $this.downloading = false; + $this.errored = $this.fitsImage.errored; + tileCacheRemoveFromQueue($this.get_key(), true); + if (!$this.fitsImage.errored) { + if (!$this.level) { + // For a non-HiPS tiled FITS, this is our + // mechanism for notifying the layer creator + // that the initial FITS data have loaded and + // the FitsProperties can be trusted. + $this.dataset.get_fitsProperties()._fireMainImageLoaded($this.fitsImage); + $this.fitsImage.applyDisplaySettings(); + } + $this.texReady = true; + $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); + $this.requestPending = false; + $this.makeTexture(); + } + }); + } + else { + this.fitsImage = FitsImageJs.createTiledFits(this.dataset, this.get_URL(), function (wcsImage) { + if (!$this.level) { + $this.dataset.get_fitsProperties()._fireMainImageLoaded($this.fitsImage); + } + $this.texReady = true; + $this.downloading = false; + $this.errored = $this.fitsImage.errored; + $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); + $this.requestPending = false; + tileCacheRemoveFromQueue($this.get_key(), true); + $this.texture2d = wcsImage.getBitmap().getTexture(); + }); + } + } + } else { + if (this.get_dataset().get_wcsImage() != null) { + this.texReady = true; + this.downloading = false; + this.errored = false; + this.readyToRender = true; + this.requestPending = false; + tileCacheRemoveFromQueue(this.get_key(), true); + return; + } + if (!this.downloading && !this.readyToRender) { + this.downloading = true; + this.texture = document.createElement('img'); + var xdomimg = this.texture; + this.texture.addEventListener('load', function (e) { + $this.texReady = true; + $this.downloading = false; + $this.errored = false; + $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); + $this.requestPending = false; + tileCacheRemoveFromQueue($this.get_key(), true); + $this.makeTexture(); + }, false); + this.texture.addEventListener('error', function (e) { + if (!$this.texture.hasAttribute('proxyattempt')) { + $this.texture.setAttribute('proxyattempt', true); + // NOTE: `this.URL` is dynamically generated using + // URLHelpers.rewrite(). Say that we request tiles from + // example.com, which requires CORS proxying. Say also + // that this callback is called for a request to a tile + // that should in fact be available. If a different + // request fails before this callback is called, + // activateProxy() will be called on the example.com + // domain, making it so that `this.URL` in the following + // call goes through the proxy, making it so that + // `new_url` is null, making it so that this tile is + // erroneously marked as failed when it should not be. + // The solution: make sure to check proxy activation + // with the *original* request URL, `texture.Src`, not + // the one that may have been updated, `this.URL`. + var new_url = URLHelpers.singleton.activateProxy($this.texture.src); + if (new_url != null) { + // null => don't bother: we know that the proxy won't help + $this.texture.src = new_url; + return; + } + } + $this.downloading = false; + $this.readyToRender = false; + $this.errored = true; + $this.requestPending = false; + tileCacheRemoveFromQueue($this.get_key(), true); + }, false); + xdomimg.crossOrigin = 'anonymous'; + this.texture.src = this.get_URL(); + } + } + }, + + createDemFromParent: function () { + return false; + }, + + _loadDemData: function () { + if (this.demFile == null) { + return this.createDemFromParent(); + } + this.demData = this.demFile; + if (this.demFile.length !== 1089 && this.demFile.length !== 513) { + return this.createDemFromParent(); + } + var total = 0; + var $enum1 = ss.enumerate(this.demData); + while ($enum1.moveNext()) { + var fv = $enum1.current; + total += fv; + } + this.demAverage /= this.demData.length; + return true; + }, + + requestDem: function () { + var $this = this; + + if (!this.readyToRender && !this.demDownloading) { + this.demTile = true; + this.demDownloading = true; + Tile.callCount++; + var xhr = new XMLHttpRequest(); + xhr.addEventListener('load', function (e) { + $this.demReady = true; + $this.demDownloading = false; + $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); + $this.requestPending = false; + try { + $this.demFile = new Float32Array(xhr.response); + } + catch ($e1) { + } + tileCacheRemoveFromQueue($this.get_key(), true); + }, false); + xhr.addEventListener('error', function (e) { + $this.demDownloading = false; + $this.demReady = false; + $this.readyToRender = false; + $this.errored = true; + $this.requestPending = false; + tileCacheRemoveFromQueue($this.get_key(), true); + }, false); + xhr.open('GET', this.get_demURL(), true); + xhr.responseType = 'arraybuffer'; + xhr.send(); + } + }, + + draw3D: function (renderContext, opacity) { + this.renderedGeneration = Tile.currentRenderGeneration; + Tile.tilesTouched++; + this.accessCount = inc_tileCacheAccessID(); + if (this.errored) { + return false; + } + var xMax = 2; + this.inViewFrustum = true; + if (!this.readyToRender) { + tileCacheAddTileToQueue(this); + return false; + } + var transitioning = false; + var childIndex = 0; + var yOffset = 0; + if (this.dataset.get_mercator() || this.dataset.get_bottomsUp()) { + yOffset = 1; + } + var xOffset = 0; + var anythingToRender = false; + var childRendered = false; + for (var y1 = 0; y1 < 2; y1++) { + for (var x1 = 0; x1 < xMax; x1++) { + if (this.level < this.dataset.get_levels()) { + // make children + if (this.children[childIndex] == null) { + this.children[childIndex] = tileCacheGetTile(this.level + 1, this.tileX * 2 + ((x1 + xOffset) % 2), this.tileY * 2 + ((y1 + yOffset) % 2), this.dataset, this); + } + if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { + this.inViewFrustum = true; + if (this.children[childIndex].isTileBigEnough(renderContext)) { + this.renderChildPart[childIndex].set_targetState(!this.children[childIndex].draw3D(renderContext, opacity)); + if (this.renderChildPart[childIndex].get_targetState()) { + childRendered = true; + } + } + else { + this.renderChildPart[childIndex].set_targetState(true); + } + } + else { + this.renderChildPart[childIndex].set_targetState(this.renderChildPart[childIndex].set_state(false)); + } + if (this.renderChildPart[childIndex].get_targetState() !== this.renderChildPart[childIndex].get_state()) { + transitioning = true; + } + } + else { + this.renderChildPart[childIndex].set_state(true); + } + if (!!this.renderChildPart[childIndex].get_state()) { + anythingToRender = true; + } + childIndex++; + } + } + if (childRendered || anythingToRender) { + this.renderedAtOrBelowGeneration = Tile.currentRenderGeneration; + if (this.parent != null) { + this.parent.renderedAtOrBelowGeneration = this.renderedAtOrBelowGeneration; + } + } + if (!anythingToRender) { + return true; + } + if (!this.createGeometry(renderContext)) { + return false; + } + Tile.tilesInView++; + this.accomidation = this._computeAccomidation(); + for (var i = 0; i < 4; i++) { + if (this.renderChildPart[i].get_targetState()) { + this.renderPart(renderContext, i, (opacity / 100), false); + } + } + return true; + }, + + _computeAccomidation: function () { + var accVal = 0; + if (!Tile.useAccomidation) { + return 0; + } + var top = tileCacheGetCachedTile(this.level, this.tileX, this.tileY + 1, this.dataset, this); + if (top == null || top.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { + accVal += 1; + } + var right = tileCacheGetCachedTile(this.level, this.tileX + 1, this.tileY, this.dataset, this); + if (right == null || right.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { + accVal += 2; + } + var bottom = tileCacheGetCachedTile(this.level, this.tileX, this.tileY - 1, this.dataset, this); + if (bottom == null || bottom.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { + accVal += 4; + } + var left = tileCacheGetCachedTile(this.level, this.tileX - 1, this.tileY, this.dataset, this); + if (left == null || left.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { + accVal += 8; + } + return accVal; + }, + + renderPart: function (renderContext, part, opacity, combine) { + if (tilePrepDevice == null) { + var lighting = renderContext.lighting && renderContext.get_sunPosition() != null; + var $enum1 = ss.enumerate(this._renderTriangleLists[part]); + while ($enum1.moveNext()) { + var tri = $enum1.current; + tri.opacity = opacity; + if (lighting) { + // transform normal by WV + var norm = tri.normal.copy(); + renderContext.get_world().multiplyVector(norm); + norm.normalize(); + + // Dot product from sun angle + var light = Vector3d.dot(norm, renderContext.get_sunPosition()); + if (light < 0) { + light = 0; + } + else { + light = Math.min(1, (light * 1)); + } + + // set lighting + tri.lighting = light; + } + else { + tri.lighting = 1; + } + tri.draw(renderContext.device, renderContext.WVP); + } + } else { + if (useGlVersion2 && this.fitsImage != null) { + ColorMapContainer.bindColorMapTexture(tilePrepDevice, this.dataset.get_fitsProperties().colorMapName); + FitsShader.min = this.dataset.get_fitsProperties().lowerCut; + FitsShader.max = this.dataset.get_fitsProperties().upperCut; + FitsShader.containsBlanks = this.dataset.get_fitsProperties().containsBlanks; + FitsShader.blankValue = this.dataset.get_fitsProperties().blankValue; + FitsShader.bZero = this.dataset.get_fitsProperties().bZero; + FitsShader.bScale = this.dataset.get_fitsProperties().bScale; + FitsShader.scaleType = this.dataset.get_fitsProperties().scaleType; + FitsShader.transparentBlack = this.dataset.get_fitsProperties().transparentBlack; + FitsShader.use(renderContext, this._vertexBuffer, this.getIndexBuffer(part, this.accomidation), this.texture2d, opacity, false, this.globalCenter); + } + else { + TileShader.use(renderContext, this._vertexBuffer, this.getIndexBuffer(part, this.accomidation), this.texture2d, opacity, false, this.globalCenter); + } + renderContext.gl.drawElements(WEBGL.TRIANGLES, this.triangleCount * 3, WEBGL.UNSIGNED_SHORT, 0); + } + }, + + cleanUp: function (removeFromParent) { + this.readyToRender = false; + this.demData = null; + this.demFile = null; + this.demDownloading = false; + this.texReady = false; + this.demReady = false; + this.errored = false; + if (this.texture != null) { + this.texture = null; + } + this._renderTriangleLists = new Array(4); + this.geometryCreated = false; + if (removeFromParent && this.parent != null) { + this.parent.removeChild(this); + this.parent = null; + } + if (tilePrepDevice != null) { + var $enum1 = ss.enumerate(this._indexBuffers); + while ($enum1.moveNext()) { + var buf = $enum1.current; + tilePrepDevice.deleteBuffer(buf); + } + this._indexBuffers = new Array(4); + if (this._vertexBuffer != null) { + tilePrepDevice.deleteBuffer(this._vertexBuffer); + this._vertexBuffer = null; + } + if (this.texture2d != null) { + tilePrepDevice.deleteTexture(this.texture2d); + this.texture2d = null; + } + } + }, + + removeChild: function (child) { + for (var i = 0; i < 4; i++) { + if (this.children[i] === child) { + this.children[i] = null; + return; + } + } + }, + + createGeometry: function (renderContext) { + if (tileDemEnabled && this.demReady && this.demData == null) { + if (!this._loadDemData()) { + return false; + } + } + if (tileDemEnabled && this.demData == null) { + return false; + } + this.readyToRender = true; + return true; + }, + + calcSphere: function () { + var corners = new Array(4); + corners[0] = this.topLeft; + corners[1] = this.bottomRight; + corners[2] = this.topRight; + corners[3] = this.bottomLeft; + var result = ConvexHull.findEnclosingSphere(corners); + this.sphereCenter = result.center; + this.sphereRadius = result.radius; + }, + + isTileBigEnough: function (renderContext) { + if (this.level > 1) { + // Test for tile scale in view. + var wvp = renderContext.WVP; + wvp._transformTo(this.topLeft, this._topLeftScreen); + wvp._transformTo(this.bottomRight, this._bottomRightScreen); + wvp._transformTo(this.topRight, this._topRightScreen); + wvp._transformTo(this.bottomLeft, this._bottomLeftScreen); + var top = this._topLeftScreen; + top.subtract(this._topRightScreen); + var topLength = top.length(); + var bottom = this._bottomLeftScreen; + bottom.subtract(this._bottomRightScreen); + var bottomLength = bottom.length(); + var left = this._bottomLeftScreen; + left.subtract(this._topLeftScreen); + var leftLength = left.length(); + var right = this._bottomRightScreen; + right.subtract(this._topRightScreen); + var rightLength = right.length(); + var lengthMax = Math.max(Math.max(rightLength, leftLength), Math.max(bottomLength, topLength)); + if (lengthMax < 300) { // was 220 + return false; + } + else { + Tile.deepestLevel = (this.level > Tile.deepestLevel) ? this.level : Tile.deepestLevel; + } + } + return true; + }, + + isTileInFrustum: function (frustum) { + if (this.level < 2 && (!this.dataset.get_projection() || this.dataset.get_projection() === 3)) { + // return true; + } + this.inViewFrustum = false; + var centerV4 = new Vector4d(this.sphereCenter.x, this.sphereCenter.y, this.sphereCenter.z, 1); + for (var i = 0; i < 6; i++) { + if (frustum[i].dot(centerV4) < -this.sphereRadius) { + return false; + } + } + this.inViewFrustum = true; + return true; + }, + + get_sphereRadius: function () { + return this.sphereRadius; + }, + + get_sphereCenter: function () { + return this.sphereCenter; + }, + + geoTo3d: function (lat, lng, useLocalCenter) { + if (this.dataset.get_dataSetType() === 3) { + var retVal = Vector3d.create(-(Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius), (Math.sin(lat * Tile.RC) * this.radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius)); + return retVal; + } else { + lng -= 180; + var retVal = Vector3d.create((Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius), (Math.sin(lat * Tile.RC) * this.radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius)); + return retVal; + } + }, + + onCreateVertexBuffer: function (sender, e) { }, + + get_dataset: function () { + return this.dataset; + }, + + set_dataset: function (value) { + this.dataset = value; + return value; + }, + + get_key: function () { + if (this._key == null) { + this._key = getTileKey(this.dataset, this.level, this.tileX, this.tileY, this.parent); + } + return this._key; + }, + + // URL parameters + // + //{0} ImageSetID + //{1} level + //{2} x tile id + //{3} y tile id + //{4} quadtree address (VE style) + //{5} quadtree address (Google maps style) + //{6} top left corner RA + //{7} top left corner Dec + //{8} bottom right corner RA + //{9} bottom right corner dec + //{10} bottom left corner RA + //{11} bottom left corner dec + //{12} top right corner RA + //{13} top right corner dec + //{X} - Tile X value + //{Y} - Tile Y value + //{L} - Tile Level + //{Q} - Quad Key ID + //{S} - Last Digit of Quadkey + get_URL: function () { + var rewritten_url = URLHelpers.singleton.rewrite(this.dataset.get_url(), 0); + var returnUrl = rewritten_url; + if (rewritten_url.indexOf('{1}') > -1) { + // Old style URL + if (!this.dataset.get_projection() && !ss.emptyString(this.dataset.get_quadTreeTileMap())) { + returnUrl = ss.format(rewritten_url, this.getServerID(), this.getTileID()); + if (returnUrl.indexOf('virtualearth.net') > -1) { + returnUrl += '&n=z'; + } + return returnUrl; + } + else { + return ss.format(rewritten_url, this.dataset.get_imageSetID(), this.level, this.tileX, this.tileY); + } + } + returnUrl = ss.replaceString(returnUrl, '{X}', this.tileX.toString()); + returnUrl = ss.replaceString(returnUrl, '{Y}', this.tileY.toString()); + returnUrl = ss.replaceString(returnUrl, '{L}', this.level.toString()); + var hash = 0; + if (returnUrl.indexOf('{S:0}') > -1) { + hash = 0; + returnUrl = ss.replaceString(returnUrl, '{S:0}', '{S}'); + } + if (returnUrl.indexOf('{S:1}') > -1) { + hash = 1; + returnUrl = ss.replaceString(returnUrl, '{S:1}', '{S}'); + } + if (returnUrl.indexOf('{S:2}') > -1) { + hash = 2; + returnUrl = ss.replaceString(returnUrl, '{S:2}', '{S}'); + } + if (returnUrl.indexOf('{S:3}') > -1) { + hash = 3; + returnUrl = ss.replaceString(returnUrl, '{S:3}', '{S}'); + } + if (returnUrl.indexOf('a{S}') > -1) { + returnUrl = ss.replaceString(returnUrl, 'a{S}', 'r{S}'); + } + if (returnUrl.indexOf('h{S}') > -1) { + returnUrl = ss.replaceString(returnUrl, 'h{S}', 'r{S}'); + } + if (returnUrl.indexOf('//r{S}.ortho.tiles.virtualearth.net') > -1) { + returnUrl = ss.replaceString(returnUrl, '//r{S}.ortho.tiles.virtualearth.net', '//ecn.t{S}.tiles.virtualearth.net'); + } + var id = this.getTileID(); + var server = ''; + if (!id.length) { + server = hash.toString(); + } else { + server = id.substr(id.length - 1, 1); + } + returnUrl = ss.replaceString(returnUrl, '{Q}', id); + returnUrl = ss.replaceString(returnUrl, '{S}', server); + if (returnUrl.indexOf('virtualearth.net') > -1) { + returnUrl += '&n=z'; + } + return returnUrl; + }, + + get_demURL: function () { + var rewritten_url = URLHelpers.singleton.rewrite(this.dataset.get_demUrl(), 0); + if (!this.dataset.get_projection() && !freestandingMode) { + var baseUrl = URLHelpers.singleton.coreStaticUrl('wwtweb/demtile.aspx?q={0},{1},{2},M'); + if (!ss.emptyString(rewritten_url)) { + baseUrl = rewritten_url; + } + } + if (rewritten_url.indexOf('{1}') > -1) { + return ss.format(rewritten_url + '&new', this.level, this.tileX, this.tileY); + } + var returnUrl = rewritten_url; + returnUrl = ss.replaceString(returnUrl, '{X}', this.tileX.toString()); + returnUrl = ss.replaceString(returnUrl, '{Y}', this.tileY.toString()); + returnUrl = ss.replaceString(returnUrl, '{L}', this.level.toString()); + var hash = 0; + if (returnUrl.indexOf('{S:0}') > -1) { + hash = 0; + returnUrl = ss.replaceString(returnUrl, '{S:0}', '{S}'); + } + if (returnUrl.indexOf('{S:1}') > -1) { + hash = 1; + returnUrl = ss.replaceString(returnUrl, '{S:1}', '{S}'); + } + if (returnUrl.indexOf('{S:2}') > -1) { + hash = 2; + returnUrl = ss.replaceString(returnUrl, '{S:2}', '{S}'); + } + if (returnUrl.indexOf('{S:3}') > -1) { + hash = 3; + returnUrl = ss.replaceString(returnUrl, '{S:3}', '{S}'); + } + var id = this.getTileID(); + var server = ''; + if (!id.length) { + server = hash.toString(); + } else { + server = id.substr(id.length - 1, 1); + } + returnUrl = ss.replaceString(returnUrl, '{Q}', id); + returnUrl = ss.replaceString(returnUrl, '{S}', server); + return returnUrl; + }, + + getServerID: function () { + var server = (this.tileX & 1) + ((this.tileY & 1) << 1); + return server; + }, + + getTileID: function () { + if (this._tileId != null) { + return this._tileId; + } + var netLevel = this.level; + var netX = this.tileX; + var netY = this.tileY; + if (this.dataset.get_projection() === 1) { + netLevel++; + } + var tileMap = this.dataset.get_quadTreeTileMap(); + if (!ss.emptyString(tileMap)) { + var sb = new ss.StringBuilder(); + for (var i = netLevel; i > 0; --i) { + var mask = 1 << (i - 1); + var val = 0; + if (!!(netX & mask)) { + val = 1; + } + if (!!(netY & mask)) { + val += 2; + } + sb.append(tileMap.substr(val, 1)); + } + this._tileId = sb.toString(); + return this._tileId; + } else { + this._tileId = '0'; + return this._tileId; + } + }, + + get_vertexCount: function () { + return this._vertexCount; + }, + + set_vertexCount: function (value) { + this._vertexCount = value; + return value; + } +}; + +registerType("Tile", [Tile, Tile$, null]); diff --git a/engine/esm/tile_cache.js b/engine/esm/tile_cache.js new file mode 100644 index 00000000..724ec64c --- /dev/null +++ b/engine/esm/tile_cache.js @@ -0,0 +1,292 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The cache of tiles and associated download queue. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { + set_tileCacheAddTileToQueue, + set_tileCacheGetCachedTile, + set_tileCacheGetTile, + set_tileCacheRemoveFromQueue, +} from "./render_globals.js"; +import { getTileKey } from "./util.js"; +import { Tile } from "./tile.js"; +import { Imageset, ProjectionType } from "./imageset.js"; + + +// wwtlib.TileCache + +export function TileCache() { } + +TileCache._queue = {}; +TileCache._tiles = {}; +TileCache.openThreads = 8; +TileCache.readyToRenderCount = 0; +TileCache.maxTileCacheSize = 800; +TileCache.maxReadyToRenderSize = 200; +TileCache._maxTotalToPurge = 0; + +TileCache.get_queueCount = function () { + return ss.keyCount(TileCache._queue); +}; + +// This name is no longer used internally, but preserve it +// for API compatibility. +TileCache.getTile = function (level, x, y, dataset, parent) { + var retTile = null; + var tileKey = getTileKey(dataset, level, x, y, parent); + if (!ss.keyExists(TileCache._tiles, tileKey)) { + retTile = Imageset.getNewTile(dataset, level, x, y, parent); + if (retTile != null) { + TileCache._tiles[tileKey] = retTile; + } + } + else { + retTile = TileCache._tiles[tileKey]; + } + var p = 0; + return retTile; +}; + +set_tileCacheGetTile(TileCache.getTile); + +// This name is no longer used internally, but preserve it +// for API compatibility. +TileCache.getCachedTile = function (level, x, y, dataset, parent) { + if (level < dataset.get_baseLevel()) { + return null; + } + var retTile = null; + var tileKey = getTileKey(dataset, level, x, y, parent); + try { + if (!ss.keyExists(TileCache._tiles, tileKey)) { + return null; + } else { + retTile = TileCache._tiles[tileKey]; + } + } + catch ($e1) { } + return retTile; +}; + +set_tileCacheGetCachedTile(TileCache.getCachedTile); + +TileCache.getReadyToRenderTileCount = function () { + var notReadyCullList = []; + var readyCullList = []; + try { + try { + var $enum1 = ss.enumerate(ss.keys(TileCache._tiles)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var tile = TileCache._tiles[key]; + if (tile.renderedGeneration < (Tile.currentRenderGeneration - 10) && !(tile.requestPending || tile.downloading)) { + if (tile.readyToRender) { + readyCullList.push(tile); + } + else { + notReadyCullList.push(tile); + } + } + } + } + catch ($e2) { + } + return readyCullList.length; + } + catch ($e3) { + return -1; + } +}; + +TileCache.processQueue = function (renderContext) { + while (ss.keyCount(TileCache._queue) > 0 && TileCache.openThreads > 0) { + var minDistance = 100000; + var overlayTile = false; + var maxKey = null; + var level = 1000; + var $enum1 = ss.enumerate(ss.keys(TileCache._queue)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var t = TileCache._queue[key]; + if (!t.requestPending && t.inViewFrustum) { + var vectTemp = Vector3d.makeCopy(t.get_sphereCenter()); + vectTemp._transformByMatrics(renderContext.get_world()); + if (renderContext.space) { + vectTemp.subtract(Vector3d.create(0, 0, -1)); + } + else { + vectTemp.subtract(renderContext.cameraPosition); + } + var distTemp = Math.max(0, vectTemp.length() - t.get_sphereRadius()); + var thisIsOverlay = (t.get_dataset().get_projection() === ProjectionType.tangent) || (t.get_dataset().get_projection() === ProjectionType.skyImage); + if (distTemp < minDistance && (!overlayTile || thisIsOverlay)) { + minDistance = distTemp; + maxKey = t.get_key(); + level = t.level; + overlayTile = thisIsOverlay; + } + } + } + if (maxKey != null) { + var workTile = TileCache._queue[maxKey]; + workTile.requestPending = true; + TileCache.openThreads--; + if (TileCache.openThreads < 0) { + TileCache.openThreads = 0; + } + workTile.requestImage(); + if (workTile.get_dataset().get_elevationModel()) { + workTile.requestDem(); + } + } else { + return; + } + } +}; + +// This name is no longer used internally, but preserve it +// for API compatibility. +TileCache.addTileToQueue = function (tile) { + var hitValue; + hitValue = 256; + if (!tile.downloading && !tile.readyToRender) { + if (ss.keyExists(TileCache._queue, tile.get_key())) { + TileCache._queue[tile.get_key()].requestHits += hitValue; + } else { + tile.requestHits = hitValue; + TileCache._queue[tile.get_key()] = tile; + } + } + return true; +}; + +set_tileCacheAddTileToQueue(TileCache.addTileToQueue); + +// This name is no longer used internally, but preserve it +// for API compatibility. +TileCache.removeFromQueue = function (key, complete) { + if (complete) { + var workTile = TileCache._queue[key]; + if (workTile != null) { + workTile.requestPending = false; + delete TileCache._queue[workTile.get_key()]; + } + TileCache.openThreads++; + } + delete TileCache._queue[key]; +}; + +set_tileCacheRemoveFromQueue(TileCache.removeFromQueue); + +TileCache.clearCache = function () { + ss.clearKeys(TileCache._tiles); +}; + +TileCache.purgeQueue = function () { + ss.clearKeys(TileCache._queue); +}; + +TileCache.purgeLRU = function () { + if (ss.keyCount(TileCache._tiles) < TileCache.maxReadyToRenderSize) { + return; + } + var notReadyCullList = []; + var readyCullList = []; + try { + try { + var $enum1 = ss.enumerate(ss.keys(TileCache._tiles)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var tile = TileCache._tiles[key]; + if (tile.renderedGeneration < (Tile.currentRenderGeneration - 10) && !(tile.requestPending || tile.downloading)) { + if (tile.readyToRender) { + readyCullList.push(tile); + } + else { + notReadyCullList.push(tile); + } + } + } + } + catch ($e2) { + } + TileCache.readyToRenderCount = readyCullList.length; + if (readyCullList.length > TileCache.maxReadyToRenderSize) { + readyCullList.sort(function (t1, t2) { + return (t2.accessCount < t1.accessCount) ? 1 : ((t2.accessCount === t1.accessCount) ? 0 : -1); + }); + var totalToPurge = readyCullList.length - TileCache.maxReadyToRenderSize; + var $enum3 = ss.enumerate(readyCullList); + while ($enum3.moveNext()) { + var tile = $enum3.current; + if (totalToPurge < 1) { + break; + } + tile.cleanUp(false); + totalToPurge--; + } + } + if (ss.keyCount(TileCache._tiles) < TileCache.maxTileCacheSize) { + return; + } + if (notReadyCullList.length > TileCache.maxTileCacheSize) { + notReadyCullList.sort(function (t1, t2) { + return (t2.accessCount < t1.accessCount) ? 1 : ((t2.accessCount === t1.accessCount) ? 0 : -1); + }); + var totalToPurge = notReadyCullList.length - TileCache.maxTileCacheSize; + if (totalToPurge > 20) { + totalToPurge = 20; + } + var $enum4 = ss.enumerate(notReadyCullList); + while ($enum4.moveNext()) { + var tile = $enum4.current; + if (totalToPurge < 1) { + break; + } + tile.cleanUp(true); + delete TileCache._tiles[tile.get_key()]; + totalToPurge--; + } + } + } + catch ($e5) { } + finally { } + return; +}; + +// Age things in queue. If they are not visible they will go away in time +TileCache.decimateQueue = function () { + var list = []; + var $enum1 = ss.enumerate(ss.keys(TileCache._queue)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var t = TileCache._queue[key]; + if (!t.requestPending) { + t.requestHits = t.requestHits / 2; + try { + if (t.requestHits < 2) { + list.push(t); + } + else if (!t.inViewFrustum) { + list.push(t); + } + } + catch ($e2) { + } + } + } + var $enum3 = ss.enumerate(list); + while ($enum3.moveNext()) { + var t = $enum3.current; + delete TileCache._queue[t.get_key()]; + } +}; + +var TileCache$ = {}; + +registerType("TileCache", [TileCache, TileCache$, null]); + diff --git a/engine/esm/toast_tile.js b/engine/esm/toast_tile.js new file mode 100644 index 00000000..5e441737 --- /dev/null +++ b/engine/esm/toast_tile.js @@ -0,0 +1,603 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses a TOAST projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { tileCacheGetTile, tilePrepDevice, tileUvMultiple } from "./render_globals.js"; +import { Vector2d, Vector3d, PositionTexture, ConvexHull } from "./double3d.js"; +import { WEBGL } from "./graphics/webgl_constants.js"; +import { Coordinates } from "./coordinates.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Tile } from "./tile.js"; +import { Triangle } from "./triangle.js"; +import { DistanceCalc } from "./util.js"; + + +// wwtlib.ToastTile + +export function ToastTile() { + this._topDown$1 = true; + this.backslash = false; + this._vertexList$1 = null; + this._childTriangleList$1 = null; + this._subDivisionLevel$1 = 4; + this._subDivided$1 = false; + Tile.call(this); +} + +ToastTile.slashIndexBuffer = new Array(64); +ToastTile.backSlashIndexBuffer = new Array(64); +ToastTile.rootIndexBuffer = new Array(4); + +ToastTile._cloneArray$1 = function (indexArray) { + var count = indexArray.length; + var ui16array = new Uint16Array(count); + var indexArrayNew = ui16array; + for (var i = 0; i < count; i++) { + indexArrayNew[i] = indexArray[i]; + } + return indexArrayNew; +}; + +ToastTile.create = function (level, xc, yc, dataset, parent) { + var temp = new ToastTile(); + temp.parent = parent; + temp.level = level; + temp.tileX = xc; + temp.tileY = yc; + temp.dataset = dataset; + temp._topDown$1 = !dataset.get_bottomsUp(); + if (temp.tileX !== xc) { + alert('bad'); + } + if (!!dataset.get_meanRadius()) { + temp.set__demScaleFactor(dataset.get_meanRadius()); + } + else { + if (!dataset.get_dataSetType()) { + temp.set__demScaleFactor(6371000); + } else { + temp.set__demScaleFactor(3396010); + } + } + temp.computeBoundingSphere(); + return temp; +}; + +var ToastTile$ = { + computeBoundingSphere: function () { + this._initializeGrids$1(); + this.topLeft = this.bounds[0 + 3 * 0].position.copy(); + this.bottomRight = this.bounds[2 + 3 * 2].position.copy(); + this.topRight = this.bounds[2 + 3 * 0].position.copy(); + this.bottomLeft = this.bounds[0 + 3 * 2].position.copy(); + this.calcSphere(); + }, + + getIndexBuffer: function (index, accomidation) { + if (!this.level) { + return ToastTile.rootIndexBuffer[index]; + } + if (this.backslash) { + return ToastTile.backSlashIndexBuffer[index * 16 + accomidation]; + } else { + return ToastTile.slashIndexBuffer[index * 16 + accomidation]; + } + }, + _processIndexBuffer$1: function (indexArray, part) { + if (!this.level) { + ToastTile.rootIndexBuffer[part] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, ToastTile.rootIndexBuffer[part]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, indexArray, WEBGL.STATIC_DRAW); + return; + } + for (var a = 0; a < 16; a++) { + var partArray = ToastTile._cloneArray$1(indexArray); + this._processAccomindations$1(partArray, a); + if (this.backslash) { + ToastTile.backSlashIndexBuffer[part * 16 + a] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, ToastTile.backSlashIndexBuffer[part * 16 + a]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, partArray, WEBGL.STATIC_DRAW); + } + else { + ToastTile.slashIndexBuffer[part * 16 + a] = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ELEMENT_ARRAY_BUFFER, ToastTile.slashIndexBuffer[part * 16 + a]); + tilePrepDevice.bufferData(WEBGL.ELEMENT_ARRAY_BUFFER, partArray, WEBGL.STATIC_DRAW); + } + } + }, + _processAccomindations$1: function (indexArray, a) { + var map = {}; + var gridMap = {}; + var $enum1 = ss.enumerate(indexArray); + while ($enum1.moveNext()) { + var index = $enum1.current; + var vert = this._vertexList$1[index]; + var arrayX = ss.truncate((vert.tu * 16 + 0.5)); + var arrayY = ss.truncate((vert.tv * 16 + 0.5)); + var ii = (arrayY << 8) + arrayX; + if (!ss.keyExists(gridMap, ii)) { + gridMap[ii] = index; + } + } + var sections = 16; + if ((a & 1) === 1) { + for (var x = 1; x < sections; x += 2) { + var y = sections; + var key = (y << 8) + x; + var val = (y << 8) + x + 1; + if (ss.keyExists(gridMap, key)) { + map[gridMap[key]] = gridMap[val]; + } + } + } + if ((a & 2) === 2) { + for (var y = 1; y < sections; y += 2) { + var x = sections; + var key = (y << 8) + x; + var val = ((y + 1) << 8) + x; + if (ss.keyExists(gridMap, key)) { + map[gridMap[key]] = gridMap[val]; + } + } + } + if ((a & 4) === 4) { + for (var x = 1; x < sections; x += 2) { + var y = 0; + var key = (y << 8) + x; + var val = (y << 8) + x + 1; + if (ss.keyExists(gridMap, key)) { + map[gridMap[key]] = gridMap[val]; + } + } + } + if ((a & 8) === 8) { + for (var y = 1; y < sections; y += 2) { + var x = 0; + var key = (y << 8) + x; + var val = ((y + 1) << 8) + x; + if (ss.keyExists(gridMap, key)) { + map[gridMap[key]] = gridMap[val]; + } + } + } + if (!ss.keyCount(map)) { + //nothing to process + return; + } + for (var i = 0; i < indexArray.length; i++) { + if (ss.keyExists(map, indexArray[i])) { + indexArray[i] = map[indexArray[i]]; + } + } + }, + + calculateFullSphere: function (list) { + var result = ConvexHull.findEnclosingSphere(list); + this.sphereCenter = result.center; + this.sphereRadius = result.radius; + }, + + isPointInTile: function (lat, lng) { + if (!this.level) { + return true; + } + if (this.level === 1) { + if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { + return true; + } + if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { + return true; + } + if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { + return true; + } + if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { + return true; + } + return false; + } + if (!this.demReady || this.demData == null) { + return false; + } + var testPoint = Coordinates.geoTo3dDouble(-lat, lng); + var top = this._isLeftOfHalfSpace$1(this.topLeft.copy(), this.topRight.copy(), testPoint); + var right = this._isLeftOfHalfSpace$1(this.topRight.copy(), this.bottomRight.copy(), testPoint); + var bottom = this._isLeftOfHalfSpace$1(this.bottomRight.copy(), this.bottomLeft.copy(), testPoint); + var left = this._isLeftOfHalfSpace$1(this.bottomLeft.copy(), this.topLeft.copy(), testPoint); + if (top && right && bottom && left) { + return true; + } + return false; + }, + _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { + pntA.normalize(); + pntB.normalize(); + var cross = Vector3d.cross(pntA, pntB); + var dot = Vector3d.dot(cross, pntTest); + return dot < 0; + }, + + getSurfacePointAltitude: function (lat, lng, meters) { + if (this.level < Tile.lastDeepestLevel) { + for (var ii = 0; ii < 4; ii++) { + var child = this.children[ii]; + if (child != null) { + if (child.isPointInTile(lat, lng)) { + var retVal = child.getSurfacePointAltitude(lat, lng, meters); + if (!!retVal) { + return retVal; + } + else { + break; + } + } + } + } + } + Tile.tileTargetLevel = this.level; + Tile.tileTargetX = this.tileX; + Tile.tileTargetY = this.tileY; + var testPoint = Coordinates.geoTo3dDouble(-lat, lng); + testPoint = Vector3d.subtractVectors(new Vector3d(), testPoint); + var uv = DistanceCalc.getUVFromInnerPoint(this.topLeft.copy(), this.topRight.copy(), this.bottomLeft.copy(), this.bottomRight.copy(), testPoint.copy()); + + // Get 4 samples and interpolate + var uud = Math.max(0, Math.min(16, (uv.x * 16))); + var vvd = Math.max(0, Math.min(16, (uv.y * 16))); + var uu = Math.max(0, Math.min(15, ss.truncate((uv.x * 16)))); + var vv = Math.max(0, Math.min(15, ss.truncate((uv.y * 16)))); + var ha = uud - uu; + var va = vvd - vv; + + if (this.demArray != null) { + // 4 nearest neighbors + var ul = this.demArray[uu + 17 * vv]; + var ur = this.demArray[(uu + 1) + 17 * vv]; + var ll = this.demArray[uu + 17 * (vv + 1)]; + var lr = this.demArray[(uu + 1) + 17 * (vv + 1)]; + var top = ul * (1 - ha) + ha * ur; + var bottom = ll * (1 - ha) + ha * lr; + var val = top * (1 - va) + va * bottom; + return val / this.get__demScaleFactor(); + } + return this.demAverage / this.get__demScaleFactor(); + }, + _initializeGrids$1: function () { + this._vertexList$1 = []; + this._childTriangleList$1 = new Array(4); + this._childTriangleList$1[0] = []; + this._childTriangleList$1[1] = []; + this._childTriangleList$1[2] = []; + this._childTriangleList$1[3] = []; + this.bounds = new Array(9); + if (this.level > 0) { + if (this.parent == null) { + this.parent = tileCacheGetTile(this.level - 1, this.tileX / 2, this.tileY / 2, this.dataset, null); + } + var parent = this.parent; + var xIndex = this.tileX % 2; + var yIndex = this.tileY % 2; + if (this.level > 1) { + this.backslash = parent.backslash; + } + else { + this.backslash = (xIndex === 1 ^ yIndex === 1) === 1; + } + this.bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].copy(); + this.bounds[1 + 3 * 0] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); + this.bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].copy(); + this.bounds[0 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); + if (this.backslash) { + this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + } + else { + this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); + } + this.bounds[2 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + this.bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].copy(); + this.bounds[1 + 3 * 2] = this._midpoint$1(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); + this.bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].copy(); + this.bounds[0 + 3 * 0].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[1 + 3 * 0].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[2 + 3 * 0].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 0].tv = 0 * tileUvMultiple; + this.bounds[0 + 3 * 1].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 1].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[2 + 3 * 1].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 1].tv = 0.5 * tileUvMultiple; + this.bounds[0 + 3 * 2].tu = 0 * tileUvMultiple; + this.bounds[0 + 3 * 2].tv = 1 * tileUvMultiple; + this.bounds[1 + 3 * 2].tu = 0.5 * tileUvMultiple; + this.bounds[1 + 3 * 2].tv = 1 * tileUvMultiple; + this.bounds[2 + 3 * 2].tu = 1 * tileUvMultiple; + this.bounds[2 + 3 * 2].tv = 1 * tileUvMultiple; + this._vertexList$1.push(this.bounds[0 + 3 * 0]); + this._vertexList$1.push(this.bounds[1 + 3 * 0]); + this._vertexList$1.push(this.bounds[2 + 3 * 0]); + this._vertexList$1.push(this.bounds[0 + 3 * 1]); + this._vertexList$1.push(this.bounds[1 + 3 * 1]); + this._vertexList$1.push(this.bounds[2 + 3 * 1]); + this._vertexList$1.push(this.bounds[0 + 3 * 2]); + this._vertexList$1.push(this.bounds[1 + 3 * 2]); + this._vertexList$1.push(this.bounds[2 + 3 * 2]); + if (this.backslash) { + this._childTriangleList$1[0].push(Triangle.create(4, 1, 0)); + this._childTriangleList$1[0].push(Triangle.create(3, 4, 0)); + this._childTriangleList$1[1].push(Triangle.create(5, 2, 1)); + this._childTriangleList$1[1].push(Triangle.create(4, 5, 1)); + this._childTriangleList$1[2].push(Triangle.create(7, 4, 3)); + this._childTriangleList$1[2].push(Triangle.create(6, 7, 3)); + this._childTriangleList$1[3].push(Triangle.create(8, 5, 4)); + this._childTriangleList$1[3].push(Triangle.create(7, 8, 4)); + } + else { + this._childTriangleList$1[0].push(Triangle.create(3, 1, 0)); + this._childTriangleList$1[0].push(Triangle.create(4, 1, 3)); + this._childTriangleList$1[1].push(Triangle.create(4, 2, 1)); + this._childTriangleList$1[1].push(Triangle.create(5, 2, 4)); + this._childTriangleList$1[2].push(Triangle.create(6, 4, 3)); + this._childTriangleList$1[2].push(Triangle.create(7, 4, 6)); + this._childTriangleList$1[3].push(Triangle.create(7, 5, 4)); + this._childTriangleList$1[3].push(Triangle.create(8, 5, 7)); + } + } else { + this.bounds[0 + 3 * 0] = PositionTexture.create(0, -1, 0, 0, 0); + this.bounds[1 + 3 * 0] = PositionTexture.create(0, 0, 1, 0.5, 0); + this.bounds[2 + 3 * 0] = PositionTexture.create(0, -1, 0, 1, 0); + this.bounds[0 + 3 * 1] = PositionTexture.create(-1, 0, 0, 0, 0.5); + this.bounds[1 + 3 * 1] = PositionTexture.create(0, 1, 0, 0.5, 0.5); + this.bounds[2 + 3 * 1] = PositionTexture.create(1, 0, 0, 1, 0.5); + this.bounds[0 + 3 * 2] = PositionTexture.create(0, -1, 0, 0, 1); + this.bounds[1 + 3 * 2] = PositionTexture.create(0, 0, -1, 0.5, 1); + this.bounds[2 + 3 * 2] = PositionTexture.create(0, -1, 0, 1, 1); + this._vertexList$1.push(this.bounds[0 + 3 * 0]); + this._vertexList$1.push(this.bounds[1 + 3 * 0]); + this._vertexList$1.push(this.bounds[2 + 3 * 0]); + this._vertexList$1.push(this.bounds[0 + 3 * 1]); + this._vertexList$1.push(this.bounds[1 + 3 * 1]); + this._vertexList$1.push(this.bounds[2 + 3 * 1]); + this._vertexList$1.push(this.bounds[0 + 3 * 2]); + this._vertexList$1.push(this.bounds[1 + 3 * 2]); + this._vertexList$1.push(this.bounds[2 + 3 * 2]); + this._childTriangleList$1[0].push(Triangle.create(3, 1, 0)); + this._childTriangleList$1[0].push(Triangle.create(4, 1, 3)); + this._childTriangleList$1[1].push(Triangle.create(5, 2, 1)); + this._childTriangleList$1[1].push(Triangle.create(4, 5, 1)); + this._childTriangleList$1[2].push(Triangle.create(7, 4, 3)); + this._childTriangleList$1[2].push(Triangle.create(6, 7, 3)); + this._childTriangleList$1[3].push(Triangle.create(7, 5, 4)); + this._childTriangleList$1[3].push(Triangle.create(8, 5, 7)); + } + }, + _midpoint$1: function (positionNormalTextured, positionNormalTextured_2) { + var a1 = Vector3d.lerp(positionNormalTextured.position, positionNormalTextured_2.position, 0.5); + var a1uv = Vector2d.lerp(Vector2d.create(positionNormalTextured.tu, positionNormalTextured.tv), Vector2d.create(positionNormalTextured_2.tu, positionNormalTextured_2.tv), 0.5); + a1.normalize(); + return PositionTexture.createPos(a1, a1uv.x, a1uv.y); + }, + + createGeometry: function (renderContext) { + if (this.geometryCreated) { + return true; + } + this.geometryCreated = true; + Tile.prototype.createGeometry.call(this, renderContext); + if (!this._subDivided$1) { + if (this._vertexList$1 == null) { + this._initializeGrids$1(); + } + if (tileUvMultiple == 256) { + if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { + this._subDivisionLevel$1 = Math.min(5, Math.max(0, 5 - this.level)); + } + else { + this._subDivisionLevel$1 = Math.min(5, Math.max(0, 5 - this.level)); + } + } + else { + if (this.demTile && this.level > 1) { + this.demArray = new Array(17 * 17); + this.demSize = 17 * 17; + if (this.backslash) { + if (ToastTile._backslashYIndex$1 == null) { + this._tempBackslashYIndex$1 = new Array(this.demSize); + this._tempBackslashXIndex$1 = new Array(this.demSize); + } + } + else { + if (ToastTile._slashYIndex$1 == null) { + this._tempSlashYIndex$1 = new Array(this.demSize); + this._tempSlashXIndex$1 = new Array(this.demSize); + } + } + } + } + for (var i = 0; i < 4; i++) { + var count = this._subDivisionLevel$1; + while (count-- > 1) { + var newList = []; + var $enum1 = ss.enumerate(this._childTriangleList$1[i]); + while ($enum1.moveNext()) { + var tri = $enum1.current; + tri.subDivide(newList, this._vertexList$1); + } + this._childTriangleList$1[i] = newList; + } + } + if (renderContext.gl == null) { + for (var i = 0; i < 4; i++) { + this._renderTriangleLists[i] = []; + var $enum2 = ss.enumerate(this._childTriangleList$1[i]); + while ($enum2.moveNext()) { + var tri = $enum2.current; + var p1 = this._vertexList$1[tri.c]; + var p2 = this._vertexList$1[tri.b]; + var p3 = this._vertexList$1[tri.a]; + this._renderTriangleLists[i].push(RenderTriangle.create(p1, p2, p3, this.texture, this.level)); + } + } + } + else { + this._vertexBuffer = tilePrepDevice.createBuffer(); + tilePrepDevice.bindBuffer(WEBGL.ARRAY_BUFFER, this._vertexBuffer); + var f32array = new Float32Array(this._vertexList$1.length * 5); + var buffer = f32array; + var index = 0; + var $enum3 = ss.enumerate(this._vertexList$1); + while ($enum3.moveNext()) { + var pt = $enum3.current; + if (this.demTile) { + index = this.addVertex(buffer, index, this._getMappedVertex(pt)); + this.demIndex++; + } + else { + index = this.addVertex(buffer, index, pt); + } + } + if (this.demTile) { + if (this.backslash) { + if (this._tempBackslashXIndex$1 != null) { + ToastTile._backslashXIndex$1 = this._tempBackslashXIndex$1; + ToastTile._backslashYIndex$1 = this._tempBackslashYIndex$1; + this._tempBackslashXIndex$1 = null; + this._tempBackslashYIndex$1 = null; + } + } + else { + if (this._tempSlashYIndex$1 != null) { + ToastTile._slashXIndex$1 = this._tempSlashXIndex$1; + ToastTile._slashYIndex$1 = this._tempSlashYIndex$1; + this._tempSlashYIndex$1 = null; + this._tempSlashXIndex$1 = null; + } + } + } + tilePrepDevice.bufferData(WEBGL.ARRAY_BUFFER, f32array, WEBGL.STATIC_DRAW); + for (var i = 0; i < 4; i++) { + this.triangleCount = this._childTriangleList$1[i].length; + if (this.getIndexBuffer(i, 0) == null) { + var ui16array = new Uint16Array(this.triangleCount * 3); + var indexArray = ui16array; + index = 0; + var $enum4 = ss.enumerate(this._childTriangleList$1[i]); + while ($enum4.moveNext()) { + var tri = $enum4.current; + indexArray[index++] = tri.c; + indexArray[index++] = tri.b; + indexArray[index++] = tri.a; + } + this._processIndexBuffer$1(indexArray, i); + } + } + } + this._subDivided$1 = true; + } + return true; + }, + + _getMappedVertex: function (vert) { + var vertOut = new PositionTexture(); + var latLng = Coordinates.cartesianToSpherical2(vert.position); + if (latLng.get_lng() < -180) { + latLng.set_lng(latLng.get_lng() + 360); + } + if (latLng.get_lng() > 180) { + latLng.set_lng(latLng.get_lng() - 360); + } + if (this.level > 1) { + var arrayX = ss.truncate((vert.tu * 16 + 0.5)); + var arrayY = ss.truncate((vert.tv * 16 + 0.5)); + this.demArray[arrayX + arrayY * 17] = this.demData[this.demIndex]; + if (this.backslash) { + if (this._tempBackslashYIndex$1 != null) { + this._tempBackslashXIndex$1[this.demIndex] = arrayX; + this._tempBackslashYIndex$1[this.demIndex] = arrayY; + } + } + else { + if (this._tempSlashYIndex$1 != null) { + this._tempSlashXIndex$1[this.demIndex] = arrayX; + this._tempSlashYIndex$1[this.demIndex] = arrayY; + } + } + } + var pos = this.geoTo3dWithAlt(latLng.get_lat(), latLng.get_lng(), false, false); + vertOut.tu = vert.tu; + vertOut.tv = vert.tv; + pos.subtract(this.localCenter); + vertOut.position = pos; + return vertOut; + }, + + cleanUp: function (removeFromParent) { + Tile.prototype.cleanUp.call(this, removeFromParent); + if (this._vertexList$1 != null) { + this._vertexList$1 = null; + } + if (this._childTriangleList$1 != null) { + this._childTriangleList$1 = null; + } + this._subDivided$1 = false; + this.demArray = null; + }, + _getDemSample$1: function (xc, yc) { + return this.demArray[(16 - yc) * 17 + xc]; + }, + + createDemFromParent: function () { + var parent = ss.safeCast(this.parent, ToastTile); + if (parent == null) { + return false; + } + var offsetX = (((this.tileX % 2) === 1) ? 8 : 0); + var offsetY = ((!(this.tileY % 2)) ? 8 : 0); + this.demArray = new Array(17 * 17); + + // Interpolate across + for (var yy1 = 0; yy1 < 17; yy1 += 2) { + var copy = true; + for (var xx1 = 0; xx1 < 17; xx1++) { + if (copy) { + this.demArray[(16 - yy1) * 17 + xx1] = parent._getDemSample$1((xx1 / 2) + offsetX, (yy1 / 2) + offsetY); + } + else { + this.demArray[(16 - yy1) * 17 + xx1] = ((parent._getDemSample$1((xx1 / 2) + offsetX, (yy1 / 2) + offsetY) + parent._getDemSample$1(((xx1 / 2) + offsetX) + 1, (yy1 / 2) + offsetY)) / 2); + } + copy = !copy; + } + } + + // Interpolate down + for (var yy2 = 1; yy2 < 17; yy2 += 2) { + for (var xx2 = 0; xx2 < 17; xx2++) { + this.demArray[(16 - yy2) * 17 + xx2] = ((this._getDemSample$1(xx2, yy2 - 1) + this._getDemSample$1(xx2, yy2 + 1)) / 2); + } + } + + // Convert the dem array back to the arranged DEM list thu slash/backslash mapping tables + this.demData = new Array(this.demSize); + for (var i = 0; i < this.demSize; i++) { + if (this.backslash) { + this.demData[i] = this.demArray[ToastTile._backslashXIndex$1[i] + ToastTile._backslashYIndex$1[i] * 17]; + } + else { + this.demData[i] = this.demArray[ToastTile._slashXIndex$1[i] + ToastTile._slashYIndex$1[i] * 17]; + } + this.demAverage += this.demData[i]; + } + + // Get Average value for new DemData table + this.demAverage /= this.demData.length; + this.demReady = true; + return true; + } +}; + +registerType("ToastTile", [ToastTile, ToastTile$, Tile]); diff --git a/engine/esm/tour.js b/engine/esm/tour.js new file mode 100644 index 00000000..7f4d1b6d --- /dev/null +++ b/engine/esm/tour.js @@ -0,0 +1,151 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Top-level information about a tour. + +import { ss } from "./ss.js"; +import { registerType, Enums } from "./typesystem.js"; +import { freestandingMode } from "./data_globals.js"; +import { IThumbnail } from "./interfaces.js"; +import { URLHelpers } from "./url_helpers.js"; + + +// wwtlib.Tour + +export function Tour() { + this.userLevel = 0; + this.classification = 0; + this.averageRating = 0; + this.lengthInSecs = 0; + this._thumbnailUrlField = ''; +} + +Tour._fromXml = function (child) { + var temp = new Tour(); + if (child.attributes.getNamedItem('ID') != null) { + temp.id = child.attributes.getNamedItem('ID').nodeValue; + } + if (child.attributes.getNamedItem('TourUrl') != null) { + temp._tourUrl = child.attributes.getNamedItem('TourUrl').nodeValue; + } + if (child.attributes.getNamedItem('Title') != null) { + temp.title = child.attributes.getNamedItem('Title').nodeValue; + } + if (child.attributes.getNamedItem('Description') != null) { + temp.description = child.attributes.getNamedItem('Description').nodeValue; + } + if (child.attributes.getNamedItem('Classification') != null) { + temp.classification = Enums.parse('Classification', child.attributes.getNamedItem('Classification').nodeValue); + } + if (child.attributes.getNamedItem('AuthorEmail') != null) { + temp.authorEmail = child.attributes.getNamedItem('AuthorEmail').nodeValue; + } + if (child.attributes.getNamedItem('Author') != null) { + temp.author = child.attributes.getNamedItem('Author').nodeValue; + } + if (child.attributes.getNamedItem('AuthorURL') != null) { + temp.authorURL = child.attributes.getNamedItem('AuthorURL').nodeValue; + } + if (child.attributes.getNamedItem('AuthorImageUrl') != null) { + temp.authorImageUrl = child.attributes.getNamedItem('AuthorImageUrl').nodeValue; + } + if (child.attributes.getNamedItem('AverageRating') != null) { + temp.averageRating = parseFloat(child.attributes.getNamedItem('AverageRating').nodeValue); + } + if (child.attributes.getNamedItem('LengthInSecs') != null) { + temp.lengthInSecs = parseFloat(child.attributes.getNamedItem('LengthInSecs').nodeValue); + } + if (child.attributes.getNamedItem('OrganizationUrl') != null) { + temp.organizationUrl = child.attributes.getNamedItem('OrganizationUrl').nodeValue; + } + if (child.attributes.getNamedItem('OrganizationName') != null) { + temp.organizationName = child.attributes.getNamedItem('OrganizationName').nodeValue; + } + if (child.attributes.getNamedItem('RelatedTours') != null) { + temp.relatedTours = child.attributes.getNamedItem('RelatedTours').nodeValue; + } + if (child.attributes.getNamedItem('Keywords') != null) { + temp.keywords = child.attributes.getNamedItem('Keywords').nodeValue; + } + if (child.attributes.getNamedItem('ThumbnailUrl') != null) { + temp.set_thumbnailUrl(child.attributes.getNamedItem('ThumbnailUrl').nodeValue); + } + return temp; +}; + +var Tour$ = { + get_name: function () { + return this.title; + }, + + get_thumbnail: function () { + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + return value; + }, + + get_thumbnailUrl: function () { + if (!ss.emptyString(this._thumbnailUrlField)) { + return this._thumbnailUrlField; + } else if (freestandingMode) { + return URLHelpers.singleton.engineAssetUrl('thumb_star.jpg'); + } + return ss.format(URLHelpers.singleton.coreStaticUrl('wwtweb/GetTourThumbnail.aspx?GUID={0}'), this.id); + }, + + set_thumbnailUrl: function (value) { + this._thumbnailUrlField = value; + return value; + }, + + get_tourUrl: function () { + if (ss.emptyString(this._tourUrl) && !freestandingMode) { + return ss.format(URLHelpers.singleton.coreStaticUrl('wwtweb/GetTour.aspx?GUID={0}'), this.id); + } else { + return this._tourUrl; + } + }, + + set_tourUrl: function (value) { + this._tourUrl = value; + return value; + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_isImage: function () { + return false; + }, + + get_isTour: function () { + return true; + }, + + get_isFolder: function () { + return false; + }, + + get_isCloudCommunityItem: function () { + return false; + }, + + get_readOnly: function () { + return false; + }, + + get_children: function () { + return []; + } +}; + +registerType("Tour", [Tour, Tour$, null, IThumbnail]); diff --git a/engine/esm/tours/file_cabinet.js b/engine/esm/tours/file_cabinet.js new file mode 100644 index 00000000..181cfa7f --- /dev/null +++ b/engine/esm/tours/file_cabinet.js @@ -0,0 +1,232 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A simple XML-based file archive format. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Util } from "../baseutil.js"; +import { XmlTextWriter } from "../utilities/xml_text_writer.js"; +import { WebFile } from "../web_file.js"; + + +// wwtlib.FileEntry + +export function FileEntry(filename, size) { + this.size = 0; + this.offset = 0; + this.filename = filename; + this.size = size; +} + +var FileEntry$ = { + toString: function () { + return this.filename; + } +}; + +registerType("FileEntry", [FileEntry, FileEntry$, null]); + + +// wwtlib.FileCabinet + +export function FileCabinet() { + this.tempDirectory = ''; + this._currentOffset = 0; + this._packageID = ''; + this.url = ''; + this.clearFileList(); +} + +FileCabinet.fromUrl = function (url, callMe) { + var temp = new FileCabinet(); + temp.url = url; + temp._callMe = callMe; + temp._webFile = new WebFile(url); + temp._webFile.responseType = 'blob'; + temp._webFile.onStateChange = ss.bind('_loadCabinet', temp); + temp._webFile.send(); + return temp; +}; + +var FileCabinet$ = { + get_packageID: function () { + return this._packageID; + }, + + set_packageID: function (value) { + this._packageID = value; + return value; + }, + + addFile: function (filename, data) { + if (data == null) { + return; + } + if (!ss.keyExists(this._fileDirectory, filename)) { + var fe = new FileEntry(filename, data.size); + fe.offset = this._currentOffset; + fe.blob = data; + this.fileList.push(fe); + this._fileDirectory[filename] = fe; + this._currentOffset += fe.size; + } + }, + + clearFileList: function () { + if (this.fileList == null) { + this.fileList = []; + } + if (this._fileDirectory == null) { + this._fileDirectory = {}; + } + this.fileList.length = 0; + ss.clearKeys(this._fileDirectory); + this._currentOffset = 0; + }, + + packageFiles: function () { + var xmlWriter = new XmlTextWriter(); + xmlWriter.formatting = 1; + xmlWriter._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + xmlWriter._writeStartElement('FileCabinet'); + xmlWriter._writeAttributeString('HeaderSize', '0x0BADFOOD'); + xmlWriter._writeStartElement('Files'); + var $enum1 = ss.enumerate(this.fileList); + while ($enum1.moveNext()) { + var entry = $enum1.current; + xmlWriter._writeStartElement('File'); + xmlWriter._writeAttributeString('Name', entry.filename); + xmlWriter._writeAttributeString('Size', entry.size.toString()); + xmlWriter._writeAttributeString('Offset', entry.offset.toString()); + xmlWriter._writeEndElement(); + } + xmlWriter._writeEndElement(); + xmlWriter._writeFullEndElement(); + xmlWriter._close(); + var data = xmlWriter.body; + var blob = new Blob([data]); + var sizeText = ss.format('0x{0:x8}', blob.size); + data = ss.replaceString(data, '0x0BADFOOD', sizeText); + blob = new Blob([data]); + var blobs = []; + blobs.push(blob); + var $enum2 = ss.enumerate(this.fileList); + + // add the blobs to array to append in order + while ($enum2.moveNext()) { + var entry = $enum2.current; + blobs.push(entry.blob); + } + var cabBlob = new Blob(blobs, { type: 'application/x-wtt' }); + return cabBlob; + }, + + _loadCabinet: function () { + var $this = this; + + if (this._webFile.get_state() === 2) { + alert(this._webFile.get_message()); + } else if (this._webFile.get_state() === 1) { + this._mainBlob = this._webFile.getBlob(); + var chunck = new FileReader(); + chunck.onloadend = function (e) { + var offset = $this._getSize(chunck.result); + var header = new FileReader(); + header.onloadend = function (ee) { + var data = ss.safeCast(header.result, String); + var xParser = new DOMParser(); + $this.extract(xParser.parseFromString(data, 'text/xml'), offset); + $this._callMe(); + }; + header.readAsText($this._mainBlob.slice(0, offset)); + }; + chunck.readAsText(this._mainBlob.slice(0, 255)); + } + }, + + _getSize: function (data) { + var start = data.indexOf('0x'); + if (start === -1) { + return 0; + } + return parseInt(data.substring(start, start + 10), 16); + }, + + extract: function (doc, offset) { + try { + var cab = Util.selectSingleNode(doc, 'FileCabinet'); + var files = Util.selectSingleNode(cab, 'Files'); + this.fileList.length = 0; + var $enum1 = ss.enumerate(files.childNodes); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child.nodeName === 'File') { + var fe = new FileEntry(child.attributes.getNamedItem('Name').nodeValue, parseInt(child.attributes.getNamedItem('Size').nodeValue)); + fe.offset = offset; + offset += fe.size; + this.fileList.push(fe); + } + } + } + catch ($e2) { + } + }, + + getFileBlob: function (filename) { + var fe = this.getFileEntry(filename); + if (fe != null) { + var ext = filename.substr(filename.lastIndexOf('.')).toLowerCase(); + var type = null; + switch (ext) { + case '.png': + type = 'image/png'; + break; + case '.jpg': + case '.jpeg': + type = 'image/jpeg'; + break; + case '.mp3': + type = 'audio/mpeg3'; + break; + case '.txt': + type = 'text/plain'; + break; + case '.fit': + case '.fits': + type = 'application/octet-stream'; + break; + } + return this._mainBlob.slice(fe.offset, fe.offset + fe.size, type); + } + return null; + }, + + getFileEntry: function (filename) { + var $enum1 = ss.enumerate(this.fileList); + while ($enum1.moveNext()) { + var entry = $enum1.current; + if (entry.filename === filename) { + return entry; + } + } + return null; + }, + + get_masterFile: function () { + if (this.fileList.length > 0) { + return this.fileList[0].filename; + } else { + return null; + } + }, + + clearTempFiles: function () { + var $enum1 = ss.enumerate(this.fileList); + while ($enum1.moveNext()) { + var entry = $enum1.current; + } + } +}; + +registerType("FileCabinet", [FileCabinet, FileCabinet$, null]); diff --git a/engine/esm/tours/overlay.js b/engine/esm/tours/overlay.js new file mode 100644 index 00000000..59518e97 --- /dev/null +++ b/engine/esm/tours/overlay.js @@ -0,0 +1,1794 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A graphical overlay shown inside a tour. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { Vector2d, Vector3d, Matrix2d, Matrix3d, PositionColoredTextured } from "../double3d.js"; +import { globalRenderContext, useGl } from "../render_globals.js"; +import { Texture } from "../graphics/texture.js"; +import { Sprite2d } from "../graphics/sprite2d.js"; +import { Util } from "../baseutil.js"; +import { Color, Colors } from "../color.js"; +import { Coordinates } from "../coordinates.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { UiTools } from "../ui_tools.js"; +import { Rectangle } from "../util.js"; +import { TextObject } from "./text_object.js"; + + +// wwtlib.OverlayAnchor + +export var OverlayAnchor = { + sky: 0, + screen: 1 +}; + +registerType("OverlayAnchor", OverlayAnchor); +registerEnum("OverlayAnchor", OverlayAnchor); + + +// wwtlib.AudioType + +export var AudioType = { + music: 0, + voice: 1 +}; + +registerType("AudioType", AudioType); +registerEnum("AudioType", AudioType); + + +// wwtlib.ShapeType + +export var ShapeType = { + circle: 0, + rectagle: 1, + star: 2, + donut: 3, + arrow: 4, + line: 5, + openRectagle: 6 +}; + +registerType("ShapeType", ShapeType); +registerEnum("ShapeType", ShapeType); + + +// wwtlib.LoopTypes + +export var LoopTypes = { + loop: 0, + upDown: 1, + down: 2, + upDownOnce: 3, + once: 4, + begin: 5, + end: 6 +}; + +registerType("LoopTypes", LoopTypes); +registerEnum("LoopTypes", LoopTypes); + + +// wwtlib.Overlay + +export function Overlay() { + this.isDynamic = false; + this.isDesignTimeOnly = false; + this._name = ''; + + // this used to be a GUID and should become that again now that we have + // proper support for them in the web engine. + this.id = (Overlay.nextId++).toString(); + this._owner = null; + this._url = ''; + this._linkID = ''; + this._domeMatrix = Matrix3d.get_identity(); + this._domeMatX = 0; + this._domeMatY = 0; + this._domeAngle = 0; + this.points = null; + this._animate = false; + this._tweenFactor = 0; + this._endX = 0; + this._endY = 0; + this._endOpacity = 0; + this._endColor = new Color(); + this._endWidth = 0; + this._endHeight = 0; + this._endRotationAngle = 0; + this._anchor = 1; + this._x = 0; + this._y = 0; + this._width = 0; + this._height = 0; + this._color = Colors.get_white(); + this._opacity = 0.5; + this._rotationAngle = 0; + this.currentRotation = 0; + this.texture = null; + this.texture2d = null; + this._interpolationType = 5; +} + +Overlay.defaultAnchor = 1; +Overlay.clipboardFormat = 'WorldWideTelescope.Overlay'; +Overlay.nextId = 11231; +Overlay.RC = 3.1415927 / 180; + +Overlay._fromXml = function (owner, overlay) { + if (overlay.attributes == null) { + return null; + } + if (overlay.attributes.getNamedItem('Type') == null) { + return null; + } + var overlayClassName = overlay.attributes.getNamedItem('Type').nodeValue; + var overLayType = ss.replaceString(overlayClassName, 'TerraViewer.', ''); + var newOverlay = null; + switch (overLayType) { + case 'AudioOverlay': + newOverlay = new AudioOverlay(); + break; + case 'BitmapOverlay': + newOverlay = new BitmapOverlay(); + break; + case 'FlipBookOverlay': + newOverlay = new FlipbookOverlay(); + break; + case 'ShapeOverlay': + newOverlay = new ShapeOverlay(); + break; + case 'TextOverlay': + newOverlay = new TextOverlay(); + break; + default: + return null; + } + newOverlay._owner = owner; + newOverlay._initOverlayFromXml(overlay); + return newOverlay; +}; + +var Overlay$ = { + get_name: function () { + return this._name; + }, + + set_name: function (value) { + this._name = value; + return value; + }, + + get_owner: function () { + return this._owner; + }, + + set_owner: function (value) { + this._owner = value; + return value; + }, + + get_zOrder: function () { + var index = 0; + var $enum1 = ss.enumerate(this._owner.get_overlays()); + while ($enum1.moveNext()) { + var item = $enum1.current; + if (item === this) { + break; + } + index++; + } + return index; + }, + + get_url: function () { + return this._url; + }, + + set_url: function (value) { + this._url = value; + return value; + }, + + get_linkID: function () { + return this._linkID; + }, + + set_linkID: function (value) { + this._linkID = value; + return value; + }, + + play: function () { }, + + pause: function () { }, + + stop: function () { }, + + seek: function (time) { }, + + makePosition: function (centerX, centerY, offsetX, offsetY, angle) { + centerX -= 960; + centerY -= 558; + var point = Vector3d.create(centerX + offsetX, centerY + offsetY, 1347); + if (!!this._domeMatX || !!this._domeMatY || this._domeAngle !== angle) { + this._domeMatX = centerX; + this._domeMatY = centerY; + this._domeMatrix = Matrix3d.translation(Vector3d.create(-centerX, -centerY, 0)); + this._domeMatrix._multiply(Matrix3d._rotationZ((angle / 180 * Math.PI))); + this._domeMatrix._multiply(Matrix3d.translation(Vector3d.create(centerX, centerY, 0))); + } + point = Vector3d._transformCoordinate(point, this._domeMatrix); + return point; + }, + + draw3D: function (renderContext, designTime) { + if (useGl) { + if (this.texture == null || this.isDynamic) { + this.initializeTexture(); + } + if (!this.isDesignTimeOnly || designTime) { + this.initializeGeometry(); + this.updateRotation(); + } + } else { + } + }, + + cleanUp: function () { + if (this.texture != null) { + this.texture = null; + } + this.texture2d = null; + }, + + initializeTexture: function () { }, + + // This hook exists to deal with web browser autoplay restrictions. In the + // strictest case, we can't just start playing media files at will -- we + // need to start playing them in response to a user-initiated event. But + // there is a generally a scheme in which files are "unlocked" once they've + // started to be played, and after that point we can control their playback + // more precisely. So, this function should do any multimedia playback + // initialization needed. It will be called when the user initiates tour + // playback. + // + // Repeated calls should be idempotent. + prepMultimedia: function () { }, + + cleanUpGeometry: function () { + this.currentRotation = 0; + this.points = null; + }, + + initializeGeometry: function () { + if (this.points == null) { + this.currentRotation = 0; + this.points = new Array(4); + this.points[0] = new PositionColoredTextured(); + this.points[0].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, -this.get_height() / 2, this.get_rotationAngle()); + this.points[0].tu = 0; + this.points[0].tv = 0; + this.points[0].color = this.get_color(); + this.points[1] = new PositionColoredTextured(); + this.points[1].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, -this.get_height() / 2, this.get_rotationAngle()); + this.points[1].tu = 1; + this.points[1].tv = 0; + this.points[1].color = this.get_color(); + this.points[2] = new PositionColoredTextured(); + this.points[2].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 2, this.get_rotationAngle()); + this.points[2].tu = 0; + this.points[2].tv = 1; + this.points[2].color = this.get_color(); + this.points[3] = new PositionColoredTextured(); + this.points[3].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, this.get_height() / 2, this.get_rotationAngle()); + this.points[3].tu = 1; + this.points[3].tv = 1; + this.points[3].color = this.get_color(); + } + }, + + updateRotation: function () { }, + + // Animation Support + + get_animate: function () { + return this._animate; + }, + + set_animate: function (value) { + if (this._animate !== value) { + this._animate = value; + if (this._animate) { + this._endX = this._x; + this._endY = this._y; + this._endRotationAngle = this._rotationAngle; + this._endColor = this._color; + this._endWidth = this._width; + this._endHeight = this._height; + this.cleanUpGeometry(); + } + else { + this._endX = this._x = this.get_x(); + this._endY = this._y = this.get_y(); + this._endRotationAngle = this._rotationAngle = this.get_rotationAngle(); + this._endColor = this._color = this.get_color(); + this._endWidth = this._width = this.get_width(); + this._endHeight = this._height = this.get_height(); + this.cleanUpGeometry(); + this._tweenFactor = 0; + } + } + return value; + }, + + get_tweenFactor: function () { + return this._tweenFactor; + }, + + set_tweenFactor: function (value) { + if (!this._animate) { + this._tweenFactor = 0; + } else { + if (this._tweenFactor !== value) { + this._tweenFactor = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_anchor: function () { + return this._anchor; + }, + + set_anchor: function (value) { + this._anchor = value; + return value; + }, + + get_position: function () { + return Vector2d.create(this.get_x(), this.get_y()); + }, + + set_position: function (value) { + this.set_x(value.x); + this.set_y(value.y); + return value; + }, + + get_x: function () { + return (this._x * (1 - this._tweenFactor)) + (this._endX * this._tweenFactor); + }, + + set_x: function (value) { + if (this._tweenFactor < 0.5) { + if (this._x !== value) { + this._x = value; + this.cleanUpGeometry(); + } + } else { + if (this._endX !== value) { + this._endX = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_y: function () { + return (this._y * (1 - this._tweenFactor)) + (this._endY * this._tweenFactor); + }, + + set_y: function (value) { + if (this._tweenFactor < 0.5) { + if (this._y !== value) { + this._y = value; + this.cleanUpGeometry(); + } + } else { + if (this._endY !== value) { + this._endY = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_width: function () { + return (this._width * (1 - this._tweenFactor)) + (this._endWidth * this._tweenFactor); + }, + + set_width: function (value) { + if (value < 5 && !!value) { + value = 5; + } + if (this._tweenFactor < 0.5) { + if (this._width !== value) { + this._width = value; + this.cleanUpGeometry(); + } + } else { + if (this._endWidth !== value) { + this._endWidth = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_height: function () { + return (this._height * (1 - this._tweenFactor)) + (this._endHeight * this._tweenFactor); + }, + + set_height: function (value) { + if (value < 5 && !!value) { + value = 5; + } + if (this._tweenFactor < 0.5) { + if (this._height !== value) { + this._height = value; + this.cleanUpGeometry(); + } + } else { + if (this._endHeight !== value) { + this._endHeight = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_color: function () { + var red = ss.truncate(((this._color.r * (1 - this._tweenFactor)) + (this._endColor.r * this._tweenFactor))); + var green = ss.truncate(((this._color.g * (1 - this._tweenFactor)) + (this._endColor.g * this._tweenFactor))); + var blue = ss.truncate(((this._color.b * (1 - this._tweenFactor)) + (this._endColor.b * this._tweenFactor))); + var alpha = ss.truncate(((this._color.a * (1 - this._tweenFactor)) + (this._endColor.a * this._tweenFactor))); + return Color.fromArgb(Math.max(0, Math.min(255, alpha)), Math.max(0, Math.min(255, red)), Math.max(0, Math.min(255, green)), Math.max(0, Math.min(255, blue))); + }, + + set_color: function (value) { + if (this._tweenFactor < 0.5) { + if (this._color !== value) { + this._color = value; + this.cleanUpGeometry(); + } + } else { + if (this._endColor !== value) { + this._endColor = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + get_opacity: function () { + return this.get_color().a / 255; + }, + + set_opacity: function (value) { + var col = this.get_color(); + this.set_color(Color.fromArgb(Math.min(255, ss.truncate((value * 255))), col.r, col.g, col.b)); + this._opacity = value; + return value; + }, + + get_rotationAngle: function () { + return (this._rotationAngle * (1 - this._tweenFactor)) + (this._endRotationAngle * this._tweenFactor); + }, + + set_rotationAngle: function (value) { + if (this._tweenFactor < 0.5) { + if (this._rotationAngle !== value) { + this._rotationAngle = value; + this.cleanUpGeometry(); + } + } else { + if (this._endRotationAngle !== value) { + this._endRotationAngle = value; + this.cleanUpGeometry(); + } + } + return value; + }, + + hitTest: function (pntTest) { + var tempPoints = new Array(1); + tempPoints[0] = Vector2d.create(pntTest.x, pntTest.y); + var mat = Matrix2d.rotateAt(-this.get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.get_x(), this.get_y())); + mat._transformPoints(tempPoints); + var rect = Rectangle.create((this.get_x() - (this.get_width() / 2)), (this.get_y() - (this.get_height() / 2)), this.get_width(), this.get_height()); + return rect.contains(tempPoints[0]); + }, + + get_bounds: function () { + return this._bounds; + }, + + set_bounds: function (value) { + this._bounds = value; + return value; + }, + + get_interpolationType: function () { + return this._interpolationType; + }, + + set_interpolationType: function (value) { + this._interpolationType = value; + return value; + }, + + saveToXml: function (xmlWriter, saveKeys) { + xmlWriter._writeStartElement('Overlay'); + xmlWriter._writeAttributeString('Id', this.id); + xmlWriter._writeAttributeString('Type', this.getTypeName()); + xmlWriter._writeAttributeString('Name', this.get_name()); + xmlWriter._writeAttributeString('X', this._x.toString()); + xmlWriter._writeAttributeString('Y', this._y.toString()); + xmlWriter._writeAttributeString('Width', this._width.toString()); + xmlWriter._writeAttributeString('Height', this._height.toString()); + xmlWriter._writeAttributeString('Rotation', this._rotationAngle.toString()); + xmlWriter._writeAttributeString('Color', this._color.save()); + xmlWriter._writeAttributeString('Url', this._url); + xmlWriter._writeAttributeString('LinkID', this._linkID); + xmlWriter._writeAttributeString('Animate', this._animate.toString()); + if (this._animate) { + xmlWriter._writeAttributeString('EndX', this._endX.toString()); + xmlWriter._writeAttributeString('EndY', this._endY.toString()); + xmlWriter._writeAttributeString('EndWidth', this._endWidth.toString()); + xmlWriter._writeAttributeString('EndHeight', this._endHeight.toString()); + xmlWriter._writeAttributeString('EndRotation', this._endRotationAngle.toString()); + xmlWriter._writeAttributeString('EndColor', this._endColor.save()); + xmlWriter._writeAttributeString('InterpolationType', Enums.toXml('InterpolationType', this._interpolationType)); + } + xmlWriter._writeAttributeString('Anchor', Enums.toXml('OverlayAnchor', this._anchor)); + this.writeOverlayProperties(xmlWriter); + xmlWriter._writeEndElement(); + }, + + getTypeName: function () { + return 'TerraViewer.Overlay'; + }, + + addFilesToCabinet: function (fc) { }, + + writeOverlayProperties: function (xmlWriter) { }, + + _initOverlayFromXml: function (node) { + this.id = node.attributes.getNamedItem('Id').nodeValue; + this.set_name(node.attributes.getNamedItem('Name').nodeValue); + this._x = parseFloat(node.attributes.getNamedItem('X').nodeValue); + this._y = parseFloat(node.attributes.getNamedItem('Y').nodeValue); + this._width = parseFloat(node.attributes.getNamedItem('Width').nodeValue); + this._height = parseFloat(node.attributes.getNamedItem('Height').nodeValue); + this._rotationAngle = parseFloat(node.attributes.getNamedItem('Rotation').nodeValue); + this._color = Color.load(node.attributes.getNamedItem('Color').nodeValue); + if (node.attributes.getNamedItem('Url') != null) { + this.set_url(node.attributes.getNamedItem('Url').nodeValue); + } + if (node.attributes.getNamedItem('LinkID') != null) { + this.set_linkID(node.attributes.getNamedItem('LinkID').nodeValue); + } + if (node.attributes.getNamedItem('Animate') != null) { + this._animate = ss.boolean(node.attributes.getNamedItem('Animate').nodeValue); + if (this._animate) { + this._endX = parseFloat(node.attributes.getNamedItem('EndX').nodeValue); + this._endY = parseFloat(node.attributes.getNamedItem('EndY').nodeValue); + this._endColor = Color.load(node.attributes.getNamedItem('EndColor').nodeValue); + this._endWidth = parseFloat(node.attributes.getNamedItem('EndWidth').nodeValue); + this._endHeight = parseFloat(node.attributes.getNamedItem('EndHeight').nodeValue); + this._endRotationAngle = parseFloat(node.attributes.getNamedItem('EndRotation').nodeValue); + if (node.attributes.getNamedItem('InterpolationType') != null) { + this.set_interpolationType(Enums.parse('InterpolationType', node.attributes.getNamedItem('InterpolationType').nodeValue)); + } + } + } + this.initializeFromXml(node); + }, + + initializeFromXml: function (node) { }, + + toString: function () { + return this.get_name(); + } +}; + +registerType("Overlay", [Overlay, Overlay$, null]); + +// wwtlib.BitmapOverlay + +export function BitmapOverlay() { + this._textureReady$1 = false; + this._sprite$1 = new Sprite2d(); + Overlay.call(this); +} + +//todo figure out how to load local files into cloud and to cabinet +BitmapOverlay.create = function (owner, file) { + var temp = new BitmapOverlay(); + temp.set_owner(owner); + // to make directory and guid filename in tour temp dir. + temp._filename$1 = file.name; + temp.set_name(owner.getNextDefaultName('Image')); + temp.set_x(0); + temp.set_y(0); + owner.get_owner().addCachedFile(file.name, file); + return temp; +}; + +var BitmapOverlay$ = { + getTypeName: function () { + return 'TerraViewer.BitmapOverlay'; + }, + + copy: function (owner) { + var newBmpOverlay = new BitmapOverlay(); + newBmpOverlay.set_owner(owner); + newBmpOverlay._filename$1 = this._filename$1; + newBmpOverlay.set_x(this.get_x()); + newBmpOverlay.set_y(this.get_y()); + newBmpOverlay.set_width(this.get_width()); + newBmpOverlay.set_height(this.get_height()); + newBmpOverlay.set_color(this.get_color()); + newBmpOverlay.set_opacity(this.get_opacity()); + newBmpOverlay.set_rotationAngle(this.get_rotationAngle()); + newBmpOverlay.set_name(this.get_name() + ' - Copy'); + return newBmpOverlay; + }, + + cleanUp: function () { + this.texture = null; + if (this.texture2d != null) { + this.texture2d.cleanUp(); + this.texture2d = null; + } + }, + + initializeTexture: function () { + var $this = this; + + try { + if (useGl) { + this.texture2d = this.get_owner().get_owner().getCachedTexture2d(this._filename$1); + this._textureReady$1 = true; + } + else { + this.texture = this.get_owner().get_owner().getCachedTexture(this._filename$1, function () { + $this._textureReady$1 = true; + }); + } + } + catch ($e1) { + } + }, + + draw3D: function (renderContext, designTime) { + if (useGl) { + if (this.texture2d == null) { + this.initializeTexture(); + } + if (!this.get_width() && !this.get_height()) { + this.set_width(this.texture2d.imageElement.width); + this.set_height(this.texture2d.imageElement.height); + } + this.initializeGeometry(); + this.updateRotation(); + this._sprite$1.draw(renderContext, this.points, this.points.length, this.texture2d, true, 1); + } else { + if (this.texture == null) { + this.initializeTexture(); + } + if (!this._textureReady$1) { + return; + } + if (!this.get_width() && !this.get_height()) { + this.set_width(this.texture.width); + this.set_height(this.texture.height); + } + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.globalAlpha = this.get_opacity(); + ctx.drawImage(this.texture, -this.get_width() / 2, -this.get_height() / 2, this.get_width(), this.get_height()); + ctx.restore(); + } + }, + + addFilesToCabinet: function (fc) { + fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); + }, + + writeOverlayProperties: function (xmlWriter) { + xmlWriter._writeStartElement('Bitmap'); + xmlWriter._writeAttributeString('Filename', this._filename$1); + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + var bitmap = Util.selectSingleNode(node, 'Bitmap'); + this._filename$1 = bitmap.attributes.getNamedItem('Filename').nodeValue; + } +}; + +registerType("BitmapOverlay", [BitmapOverlay, BitmapOverlay$, Overlay]); + +// wwtlib.TextOverlay + +export function TextOverlay() { + this._sprite$1 = new Sprite2d(); + this._ctx$1 = null; + this._ce$1 = null; + Overlay.call(this); +} + +TextOverlay.create = function (textObject) { + var to = new TextOverlay(); + to.textObject = textObject; + to._calculateTextSize$1(); + return to; +}; + +var TextOverlay$ = { + getTypeName: function () { + return 'TerraViewer.TextOverlay'; + }, + + get_color: function () { + return Overlay.prototype.get_color.call(this); + }, + + set_color: function (value) { + if (this.textObject.foregroundColor !== value) { + this.textObject.foregroundColor = value; + Overlay.prototype.set_color.call(this, value); + this.cleanUp(); + } + return value; + }, + + draw3D: function (renderContext, designTime) { + if (useGl) { + this.initializeTexture(); + this.initializeGeometry(); + this.updateRotation(); + this._sprite$1.draw(renderContext, this.points, this.points.length, this.texture2d, true, 1); + } else { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.globalAlpha = this.get_opacity(); + this._drawCanvasText$1(ctx); + ctx.restore(); + } + }, + _drawCanvasText$1: function (ctx) { + ctx.fillStyle = this.textObject.foregroundColor.toString(); + ctx.font = ((this.textObject.italic) ? 'italic' : 'normal') + ' ' + ((this.textObject.bold) ? 'bold' : 'normal') + ' ' + Math.round(this.textObject.fontSize * 1.2).toString() + 'px ' + this.textObject.fontName; + ctx.textBaseline = 'top'; + var text = this.textObject.text; + if (text.indexOf('{$') > -1) { + if (text.indexOf('{$DATE}') > -1) { + var date = ss.format('{0:yyyy/MM/dd}', SpaceTimeController.get_now()); + text = ss.replaceString(text, '{$DATE}', date); + } + if (text.indexOf('{$TIME}') > -1) { + var time = ss.format('{0:HH:mm:ss}', SpaceTimeController.get_now()); + text = ss.replaceString(text, '{$TIME}', time); + } + text = ss.replaceString(text, '{$DIST}', UiTools.formatDistance(globalRenderContext.get_solarSystemCameraDistance())); + text = ss.replaceString(text, '{$LAT}', Coordinates.formatDMS(globalRenderContext.viewCamera.lat)); + text = ss.replaceString(text, '{$LNG}', Coordinates.formatDMS(globalRenderContext.viewCamera.lat)); + text = ss.replaceString(text, '{$RA}', Coordinates.formatDMS(globalRenderContext.viewCamera.get_RA())); + text = ss.replaceString(text, '{$DEC}', Coordinates.formatDMS(globalRenderContext.viewCamera.get_dec())); + text = ss.replaceString(text, '{$FOV}', Coordinates.formatDMS(globalRenderContext.get_fovAngle())); + } + var lines = text.split('\n'); + var baseline = -(this.get_height() / 2); + var lineSpace = this.textObject.fontSize * 1.7; + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var line = $enum1.current; + var parts = Util.getWrappedText(ctx, line, this.get_width()); + var $enum2 = ss.enumerate(parts); + while ($enum2.moveNext()) { + var part = $enum2.current; + ctx.fillText(part, -this.get_width() / 2, baseline); + baseline += lineSpace; + } + } + }, + _calculateTextSize$1: function () { + if (this._ctx$1 == null || this._ce$1 == null) { + this._ce$1 = document.createElement('canvas'); + this._ce$1.height = 100; + this._ce$1.width = 100; + this._ctx$1 = this._ce$1.getContext('2d'); + } + this._ctx$1.fillStyle = this.textObject.foregroundColor.toString(); + this._ctx$1.font = ((this.textObject.italic) ? 'italic' : 'normal') + ' ' + ((this.textObject.bold) ? 'bold' : 'normal') + ' ' + Math.round(this.textObject.fontSize * 1.2).toString() + 'px ' + this.textObject.fontName; + this._ctx$1.textBaseline = 'top'; + var text = this.textObject.text; + if (text.indexOf('{$') > -1) { + if (text.indexOf('{$DATE}') > -1) { + var date = ss.format('{0:yyyy/MM/dd}', SpaceTimeController.get_now()); + text = ss.replaceString(text, '{$DATE}', date); + } + if (text.indexOf('{$TIME}') > -1) { + var time = ss.format('{0:HH:mm:ss}', SpaceTimeController.get_now()); + text = ss.replaceString(text, '{$TIME}', time); + } + text = ss.replaceString(text, '{$DIST}', UiTools.formatDistance(globalRenderContext.get_solarSystemCameraDistance())); + text = ss.replaceString(text, '{$LAT}', Coordinates.formatDMS(globalRenderContext.viewCamera.lat)); + text = ss.replaceString(text, '{$LNG}', Coordinates.formatDMS(globalRenderContext.viewCamera.lat)); + text = ss.replaceString(text, '{$RA}', Coordinates.formatDMS(globalRenderContext.viewCamera.get_RA())); + text = ss.replaceString(text, '{$DEC}', Coordinates.formatDMS(globalRenderContext.viewCamera.get_dec())); + text = ss.replaceString(text, '{$FOV}', Coordinates.formatDMS(globalRenderContext.get_fovAngle())); + } + var lines = text.split('\n'); + var baseline = 0; + var lineSpace = this.textObject.fontSize * 1.7; + var maxWidth = 0; + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var line = $enum1.current; + var width = this._ctx$1.measureText(line).width; + maxWidth = Math.max(width, maxWidth); + baseline += lineSpace; + } + + //Width + fudge factor + this.set_width(maxWidth * 1.01); + this.set_height(baseline); + this._ce$1 = null; + this._ctx$1 = null; + }, + + initializeTexture: function () { + if (this.texture2d == null || (this.textObject.text.indexOf('{$') > -1)) { + if (!this.get_height() || !this.get_width()) { + this._calculateTextSize$1(); + } + if (this._ctx$1 == null || this._ce$1 == null) { + this._ce$1 = document.createElement('canvas'); + this._ce$1.height = ss.truncate(this.get_height()); + this._ce$1.width = ss.truncate(this.get_width()); + this._ctx$1 = this._ce$1.getContext('2d'); + } + this._ctx$1.translate(this.get_width() / 2, this.get_height() / 2); + this._ctx$1.clearRect(0, 0, this.get_width(), this.get_height()); + this._drawCanvasText$1(this._ctx$1); + this.texture2d = new Texture(); + this.texture2d.imageElement = this._ce$1; + this.texture2d.makeTexture(); + this._ce$1 = null; + this._ctx$1 = null; + } + }, + + writeOverlayProperties: function (xmlWriter) { + xmlWriter._writeStartElement('Text'); + this.textObject._saveToXml(xmlWriter); + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + var text = Util.selectSingleNode(node, 'Text'); + this.textObject = TextObject._fromXml(Util.selectSingleNode(text, 'TextObject')); + }, + + initializeGeometry: function () { + if (useGl) { + Overlay.prototype.initializeGeometry.call(this); + } + } +}; + +registerType("TextOverlay", [TextOverlay, TextOverlay$, Overlay]); + +// wwtlib.ShapeOverlay + +export function ShapeOverlay() { + this._shapeType$1 = 1; + this._sprite$1 = new Sprite2d(); + this._triangleStrip$1 = true; + Overlay.call(this); +} + +ShapeOverlay._create = function (currentTourStop, shapeType) { + var overlay = new ShapeOverlay(); + overlay._shapeType$1 = shapeType; + overlay.set_owner(currentTourStop); + return overlay; +}; + +var ShapeOverlay$ = { + getTypeName: function () { + return 'TerraViewer.ShapeOverlay'; + }, + + get_shapeType: function () { + return this._shapeType$1; + }, + + set_shapeType: function (value) { + this._shapeType$1 = value; + this.cleanUpGeometry(); + return value; + }, + + draw3D: function (renderContext, designTime) { + if (useGl) { + this.initializeGeometry(); + this._sprite$1.draw(renderContext, this.points, this.points.length, null, this._triangleStrip$1, this.get_opacity()); + } else { + switch (this._shapeType$1) { + case 0: + this._drawCircleGeometry$1(renderContext); + break; + case 1: + this._drawRectGeometry$1(renderContext); + break; + case 6: + this._drawOpenRectGeometry$1(renderContext); + break; + case 2: + this._drawStarGeometry$1(renderContext); + break; + case 3: + this._drawDonutGeometry$1(renderContext); + break; + case 4: + this._drawArrowGeometry$1(renderContext); + break; + case 5: + this._drawLineGeometry$1(renderContext); + break; + default: + break; + } + } + }, + + initializeGeometry: function () { + if (this.points == null) { + switch (this._shapeType$1) { + case 0: + this._createCircleGeometry$1(); + break; + case 1: + Overlay.prototype.initializeGeometry.call(this); + break; + case 6: + this._createOpenRectGeometry$1(); + break; + case 2: + this._createStarGeometry$1(); + break; + case 3: + this._createDonutGeometry$1(); + break; + case 4: + this._createArrowGeometry$1(); + break; + case 5: + this._createLineGeometry$1(); + break; + default: + break; + } + } + }, + _createLineGeometry$1: function () { + var centerX = this.get_x(); + var centerY = this.get_y(); + var radius = this.get_width() / 2; + var length = this.get_width(); + var segments = ss.truncate((length / 12)) + 1; + var radiansPerSegment = (Math.PI * 2) / segments; + if (this.points == null) { + this.points = new Array(segments * 2 + 2); + } + for (var j = 0; j <= segments; j++) { + var i = j * 2; + this.points[i] = new PositionColoredTextured(); + this.points[i].position = this.makePosition(this.get_x(), this.get_y(), ((j / segments) * this.get_width() - (this.get_width() / 2)), 6, this.get_rotationAngle()); + this.points[i].tu = (j % 2); + this.points[i].tv = 0; + this.points[i].color = this.get_color(); + this.points[i + 1] = new PositionColoredTextured(); + this.points[i + 1].position = this.makePosition(this.get_x(), this.get_y(), ((j / segments) * this.get_width() - (this.get_width() / 2)), -6, this.get_rotationAngle()); + this.points[i + 1].tu = (j % 2); + this.points[i + 1].tv = 1; + this.points[i + 1].color = this.get_color(); + } + }, + _createOpenRectGeometry$1: function () { + var centerX = this.get_x(); + var centerY = this.get_y(); + var radius = this.get_width() / 2; + var length = this.get_width(); + var segments = ss.truncate((length / 12)) + 1; + var segmentsHigh = ss.truncate((this.get_height() / 12)) + 1; + var totalPoints = (((segments + 1) * 2) + ((segmentsHigh + 1) * 2)) * 2; + if (this.points == null) { + this.points = new Array(totalPoints); + } + for (var j = 0; j <= segments; j++) { + var i = j * 2; + this.points[i] = new PositionColoredTextured(); + this.points[i].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (this.get_height() / 2), this.get_rotationAngle()); + this.points[i].tu = (j % 2); + this.points[i].tv = 0; + this.points[i].color = this.get_color(); + this.points[i + 1] = new PositionColoredTextured(); + this.points[i + 1].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), ((this.get_height() / 2) - 12), this.get_rotationAngle()); + this.points[i + 1].tu = (j % 2); + this.points[i + 1].tv = 1; + this.points[i + 1].color = this.get_color(); + var k = (((segments + 1) * 4) + ((segmentsHigh + 1) * 2) - 2) - i; + this.points[k] = new PositionColoredTextured(); + this.points[k].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (-(this.get_height() / 2)) + 12, this.get_rotationAngle()); + this.points[k].tu = (j % 2); + this.points[k].tv = 0; + this.points[k].color = this.get_color(); + this.points[k + 1] = new PositionColoredTextured(); + this.points[k + 1].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (-(this.get_height() / 2)), this.get_rotationAngle()); + this.points[k + 1].tu = (j % 2); + this.points[k + 1].tv = 1; + this.points[k + 1].color = this.get_color(); + } + var offset = ((segments + 1) * 2); + for (var j = 0; j <= segmentsHigh; j++) { + var top = ((segmentsHigh + 1) * 2) + offset - 2; + var i = j * 2; + this.points[top - i] = new PositionColoredTextured(); + this.points[top - i].position = this.makePosition(centerX, centerY, (this.get_width() / 2), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); + this.points[top - i].tu = (j % 2); + this.points[top - i].tv = 0; + this.points[top - i].color = this.get_color(); + this.points[top - i + 1] = new PositionColoredTextured(); + this.points[top - i + 1].position = this.makePosition(centerX, centerY, ((this.get_width() / 2) - 12), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); + this.points[top - i + 1].tu = (j % 2); + this.points[top - i + 1].tv = 1; + this.points[top - i + 1].color = this.get_color(); + var k = i + ((segments + 1) * 4) + ((segmentsHigh + 1) * 2); + this.points[k] = new PositionColoredTextured(); + this.points[k].position = this.makePosition(centerX, centerY, (-(this.get_width() / 2) + 12), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); + this.points[k].tu = (j % 2); + this.points[k].tv = 0; + this.points[k].color = this.get_color(); + this.points[k + 1] = new PositionColoredTextured(); + this.points[k + 1].position = this.makePosition(centerX, centerY, (-(this.get_width() / 2)), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); + this.points[k + 1].tu = (j % 2); + this.points[k + 1].tv = 1; + this.points[k + 1].color = this.get_color(); + } + }, + _createStarGeometry$1: function () { + var centerX = this.get_x(); + var centerY = this.get_y(); + var radius = this.get_width() / 2; + var radiansPerSegment = (Math.PI * 2) / 5; + if (this.points == null) { + this.points = new Array(12); + } + if (this._pnts$1 == null) { + this._pnts$1 = new Array(10); + } + for (var i = 0; i < 5; i++) { + var rads = i * radiansPerSegment - (Math.PI / 2); + this._pnts$1[i] = new PositionColoredTextured(); + this._pnts$1[i].position = this.makePosition(centerX, centerY, (Math.cos(rads) * (this.get_width() / 2)), (Math.sin(rads) * (this.get_height() / 2)), this.get_rotationAngle()); + this._pnts$1[i].tu = 0; + this._pnts$1[i].tv = 0; + this._pnts$1[i].color = this.get_color(); + } + for (var i = 5; i < 10; i++) { + var rads = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); + this._pnts$1[i] = new PositionColoredTextured(); + this._pnts$1[i].position = this.makePosition(centerX, centerY, (Math.cos(rads) * (this.get_width() / 5.3)), (Math.sin(rads) * (this.get_height() / 5.3)), this.get_rotationAngle()); + this._pnts$1[i].tu = 0; + this._pnts$1[i].tv = 0; + this._pnts$1[i].color = this.get_color(); + } + this.points[0] = this._pnts$1[0]; + this.points[1] = this._pnts$1[5]; + this.points[2] = this._pnts$1[9]; + this.points[3] = this._pnts$1[1]; + this.points[4] = this._pnts$1[7]; + this.points[5] = this._pnts$1[4]; + this.points[6] = this._pnts$1[6]; + this.points[7] = this._pnts$1[2]; + this.points[8] = this._pnts$1[7]; + this.points[9] = this._pnts$1[7]; + this.points[10] = this._pnts$1[3]; + this.points[11] = this._pnts$1[8]; + this._triangleStrip$1 = false; + }, + _createArrowGeometry$1: function () { + if (this.points == null) { + this.points = new Array(9); + } + this.points[0] = new PositionColoredTextured(); + this.points[0].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, -this.get_height() / 4, this.get_rotationAngle()); + this.points[0].tu = 0; + this.points[0].tv = 0; + this.points[0].color = this.get_color(); + this.points[1] = new PositionColoredTextured(); + this.points[1].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 4, this.get_rotationAngle()); + this.points[1].tu = 1; + this.points[1].tv = 0; + this.points[1].color = this.get_color(); + this.points[2] = new PositionColoredTextured(); + this.points[2].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 4, this.get_rotationAngle()); + this.points[2].tu = 0; + this.points[2].tv = 1; + this.points[2].color = this.get_color(); + this.points[3] = new PositionColoredTextured(); + this.points[3].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 4, this.get_rotationAngle()); + this.points[3].tu = 1; + this.points[3].tv = 0; + this.points[3].color = this.get_color(); + this.points[4] = new PositionColoredTextured(); + this.points[4].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 4, this.get_rotationAngle()); + this.points[4].tu = 0; + this.points[4].tv = 1; + this.points[4].color = this.get_color(); + this.points[5] = new PositionColoredTextured(); + this.points[5].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, this.get_height() / 4, this.get_rotationAngle()); + this.points[5].tu = 1; + this.points[5].tv = 1; + this.points[5].color = this.get_color(); + this.points[6] = new PositionColoredTextured(); + this.points[6].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 2, this.get_rotationAngle()); + this.points[6].tu = 1; + this.points[6].tv = 1; + this.points[6].color = this.get_color(); + this.points[7] = new PositionColoredTextured(); + this.points[7].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, 0, this.get_rotationAngle()); + this.points[7].tu = 1; + this.points[7].tv = 0.5; + this.points[7].color = this.get_color(); + this.points[8] = new PositionColoredTextured(); + this.points[8].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, this.get_height() / 2, this.get_rotationAngle()); + this.points[8].tu = 1; + this.points[8].tv = 1; + this.points[8].color = this.get_color(); + this._triangleStrip$1 = false; + }, + _createDonutGeometry$1: function () { + var centerX = this.get_x(); + var centerY = this.get_y(); + var radius = this.get_width() / 2; + var circumference = Math.PI * 2 * radius; + var segments = ss.truncate((circumference / 12)) + 1; + var radiansPerSegment = (Math.PI * 2) / segments; + if (this.points == null) { + this.points = new Array(segments * 2 + 2); + } + for (var j = 0; j <= segments; j++) { + var i = j * 2; + this.points[i] = new PositionColoredTextured(); + this.points[i].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * (this.get_width() / 2)), (Math.sin(j * radiansPerSegment) * (this.get_height() / 2)), this.get_rotationAngle()); + this.points[i].tu = (j % 2); + this.points[i].tv = 0; + this.points[i].color = this.get_color(); + this.points[i + 1] = new PositionColoredTextured(); + this.points[i + 1].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * ((this.get_width() / 2) - 10)), (Math.sin(j * radiansPerSegment) * ((this.get_height() / 2) - 10)), this.get_rotationAngle()); + this.points[i + 1].tu = (j % 2); + this.points[i + 1].tv = 1; + this.points[i + 1].color = this.get_color(); + } + }, + _createCircleGeometry$1: function () { + var centerX = this.get_x(); + var centerY = this.get_y(); + var radius = this.get_width() / 2; + var circumference = Math.PI * 2 * radius; + var segments = ss.truncate((circumference / 12)) + 1; + var radiansPerSegment = (Math.PI * 2) / segments; + if (this.points == null) { + this.points = new Array(segments * 2 + 2); + } + for (var j = 0; j <= segments; j++) { + var i = j * 2; + this.points[i] = new PositionColoredTextured(); + this.points[i].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * (this.get_width() / 2)), (Math.sin(j * radiansPerSegment) * (this.get_height() / 2)), this.get_rotationAngle()); + this.points[i].tu = (j % 2); + this.points[i].tv = 0; + this.points[i].color = this.get_color(); + this.points[i + 1] = new PositionColoredTextured(); + this.points[i + 1].position = this.makePosition(centerX, centerY, 0, 0, this.get_rotationAngle()); + this.points[i + 1].tu = (j % 2); + this.points[i + 1].tv = 1; + this.points[i + 1].color = this.get_color(); + } + }, + + initializeTexture: function () { + switch (this.get_shapeType()) { + case 5: + case 3: + case 6: + break; + case 0: + case 1: + case 2: + case 4: + default: + this.texture = null; + break; + } + }, + + //todo this needs to be Dashed rounded lines.. + _drawLineGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + var radius = this.get_width() / 2; + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.moveTo(-radius, 0); + ctx.lineTo(radius, 0); + ctx.lineWidth = 9; + ctx.strokeStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.stroke(); + ctx.restore(); + }, + + _drawOpenRectGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + ctx.moveTo(-this.get_width() / 2, -this.get_height() / 2); + ctx.lineTo(this.get_width() / 2, -this.get_height() / 2); + ctx.lineTo(this.get_width() / 2, this.get_height() / 2); + ctx.lineTo(-this.get_width() / 2, this.get_height() / 2); + ctx.closePath(); + ctx.lineWidth = 9; + ctx.strokeStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.stroke(); + ctx.restore(); + }, + + _drawRectGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + ctx.moveTo(-this.get_width() / 2, -this.get_height() / 2); + ctx.lineTo(this.get_width() / 2, -this.get_height() / 2); + ctx.lineTo(this.get_width() / 2, this.get_height() / 2); + ctx.lineTo(-this.get_width() / 2, this.get_height() / 2); + ctx.closePath(); + ctx.lineWidth = 0; + ctx.fillStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.fill(); + ctx.restore(); + }, + + _drawStarGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + var centerX = 0; + var centerY = 0; + var radius = this.get_width() / 2; + var radiansPerSegment = (Math.PI * 2) / 5; + var first = true; + for (var i = 0; i < 5; i++) { + var rads = i * radiansPerSegment - (Math.PI / 2); + if (first) { + first = false; + ctx.moveTo(centerX + Math.cos(rads) * (this.get_width() / 2), centerY + Math.sin(rads) * (this.get_height() / 2)); + } + else { + ctx.lineTo(centerX + Math.cos(rads) * (this.get_width() / 2), centerY + Math.sin(rads) * (this.get_height() / 2)); + } + var rads2 = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); + ctx.lineTo(centerX + Math.cos(rads2) * (this.get_width() / 5.3), centerY + Math.sin(rads2) * (this.get_height() / 5.3)); + } + ctx.closePath(); + ctx.lineWidth = 0; + ctx.fillStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.fill(); + ctx.restore(); + }, + + _drawArrowGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + ctx.moveTo((-(this.get_width() / 2)), (-(this.get_height() / 4))); + ctx.lineTo((this.get_width() / 4), (-(this.get_height() / 4))); + ctx.lineTo((this.get_width() / 4), (-(this.get_height() / 2))); + ctx.lineTo((this.get_width() / 2), 0); + ctx.lineTo((this.get_width() / 4), (this.get_height() / 2)); + ctx.lineTo((this.get_width() / 4), (this.get_height() / 4)); + ctx.lineTo((-(this.get_width() / 2)), (this.get_height() / 4)); + ctx.closePath(); + ctx.lineWidth = 0; + ctx.fillStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.fill(); + ctx.restore(); + }, + + //todo move to dashed lines in future + _drawDonutGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.translate(this.get_x(), this.get_y()); + ctx.scale(1, this.get_height() / this.get_width()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + ctx.arc(0, 0, this.get_width() / 2, 0, Math.PI * 2, false); + ctx.closePath(); + ctx.lineWidth = 9; + ctx.strokeStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.stroke(); + ctx.restore(); + }, + + _drawCircleGeometry$1: function (renderContext) { + var ctx = renderContext.device; + ctx.save(); + ctx.scale(1, this.get_width() / this.get_height()); + ctx.translate(this.get_x(), this.get_y()); + ctx.rotate(this.get_rotationAngle() * Overlay.RC); + ctx.beginPath(); + ctx.arc(0, 0, this.get_width(), 0, Math.PI * 2, false); + ctx.closePath(); + ctx.lineWidth = 0; + ctx.fillStyle = this.get_color().toString(); + ctx.globalAlpha = this.get_opacity(); + ctx.fill(); + ctx.restore(); + }, + + cleanUpGeometry: function () { + Overlay.prototype.cleanUpGeometry.call(this); + this.cleanUp(); + }, + + writeOverlayProperties: function (xmlWriter) { + xmlWriter._writeStartElement('Shape'); + xmlWriter._writeAttributeString('ShapeType', Enums.toXml('ShapeType', this._shapeType$1)); + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + var shape = Util.selectSingleNode(node, 'Shape'); + this._shapeType$1 = Enums.parse('ShapeType', shape.attributes.getNamedItem('ShapeType').nodeValue); + } +}; + +registerType("ShapeOverlay", [ShapeOverlay, ShapeOverlay$, Overlay]); + +// wwtlib.AudioOverlay + +export function AudioOverlay() { + this._audio$1 = null; + this._audioReady$1 = false; + this._wantPlaying$1 = false; + this._volume$1 = 100; + this._mute$1 = false; + this._position$1 = 0; + this._trackType$1 = 0; + Overlay.call(this); + this.isDesignTimeOnly = true; +} + +AudioOverlay.create = function (currentTourStop, file) { + var ao = new AudioOverlay(); + ao.set_owner(currentTourStop); + ao._filename$1 = file.name; + ao.get_owner().get_owner().addCachedFile(file.name, file); + return ao; +}; + +var AudioOverlay$ = { + getTypeName: function () { + return 'TerraViewer.AudioOverlay'; + }, + + get_mute: function () { + return this._mute$1; + }, + + set_mute: function (value) { + this._mute$1 = value; + this.set_volume(this.get_volume()); + return value; + }, + + get_volume: function () { + return this._volume$1; + }, + + set_volume: function (value) { + this._volume$1 = value; + if (this._audio$1 != null) { + this._audio$1.volume = (this._mute$1) ? 0 : (this._volume$1 / 100); + } + return value; + }, + + addFilesToCabinet: function (fc) { + fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); + }, + + play: function () { + if (this._audio$1 == null) { + this.prepMultimedia(); + } + this._wantPlaying$1 = true; + if (this._audio$1 != null && this._audioReady$1) { + this._audio$1.play(); + this.set_volume(this.get_volume()); + this._audio$1.currentTime = this._position$1; + } + }, + + pause: function () { + if (this._audio$1 == null) { + this.prepMultimedia(); + } + this._wantPlaying$1 = false; + if (this._audio$1 != null && this._audioReady$1) { + this._audio$1.pause(); + } + }, + + stop: function () { + this.pause(); // these operations are identical for audio + }, + + seek: function (time) { + this._position$1 = time; + if (this._audio$1 == null) { + this.prepMultimedia(); + } + if (this._audioReady$1) { + if (this._audio$1.duration < time) { + this._audio$1.pause(); + } + else { + this._audio$1.currentTime = this._position$1; + } + } + }, + + prepMultimedia: function () { + var $this = this; + + if (this._audio$1 != null) { + return; + } + this._audio$1 = document.createElement('audio'); + this._audio$1.addEventListener('canplaythrough', function () { + if (!$this._audioReady$1) { + $this._audioReady$1 = true; + if ($this._wantPlaying$1) { + $this.play(); + } + } + }, false); + + // As of December 2020, on Safari, we need to use a + // sub-element for the audio to play. If we set src/type on the + // parent element the playback breaks. This in turn breaks some + // older browsers -- in a world of infinite developer time we'd + // choose the behavior based on the browser version. + var source = document.createElement('source'); + this._audio$1.appendChild(source); + source.src = this.get_owner().get_owner().getFileStream(this._filename$1); + source.type = 'audio/mp3'; + this._audio$1.load(); + }, + + // TODO: understand better when/how this function is called. It ought to + // be called for every frame by the generic Draw3D implementation since + // we never set `texture`, I think. But note that the main music and + // voice tracks aren't "rendered" in this way, so this function doesn't + // get called for them, it looks. + initializeTexture: function () { + this.prepMultimedia(); + }, + + cleanUp: function () { + Overlay.prototype.cleanUp.call(this); + this._wantPlaying$1 = false; + if (this._audio$1 != null) { + this._audio$1.pause(); + this._audio$1.src = null; + this._audio$1 = null; + } + }, + + get_trackType: function () { + return this._trackType$1; + }, + + set_trackType: function (value) { + this._trackType$1 = value; + return value; + }, + + writeOverlayProperties: function (xmlWriter) { + xmlWriter._writeStartElement('Audio'); + xmlWriter._writeAttributeString('Filename', this._filename$1); + xmlWriter._writeAttributeString('Volume', this._volume$1.toString()); + xmlWriter._writeAttributeString('Mute', this._mute$1.toString()); + xmlWriter._writeAttributeString('TrackType', Enums.toXml('AudioType', this._trackType$1)); + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + var audio = Util.selectSingleNode(node, 'Audio'); + this._filename$1 = audio.attributes.getNamedItem('Filename').nodeValue; + if (audio.attributes.getNamedItem('Volume') != null) { + this._volume$1 = parseInt(audio.attributes.getNamedItem('Volume').nodeValue); + } + if (audio.attributes.getNamedItem('Mute') != null) { + this._mute$1 = ss.boolean(audio.attributes.getNamedItem('Mute').nodeValue); + } + if (audio.attributes.getNamedItem('TrackType') != null) { + this._trackType$1 = Enums.parse('AudioType', audio.attributes.getNamedItem('TrackType').nodeValue); + } + } +}; + +registerType("AudioOverlay", [AudioOverlay, AudioOverlay$, Overlay]); + +// wwtlib.FlipbookOverlay + +export function FlipbookOverlay() { + this._loopType$1 = 1; + this._startFrame$1 = 0; + this._framesList$1 = []; + this._frames$1 = 1; + this._framesX$1 = 8; + this._framesY$1 = 8; + this._textureReady$1 = false; + this._currentFrame$1 = 0; + this._cellHeight$1 = 256; + this._cellWidth$1 = 256; + this._timeStart$1 = ss.now(); + this._playing$1 = true; + Overlay.call(this); +} + +var FlipbookOverlay$ = { + getTypeName: function () { + return 'TerraViewer.FlipbookOverlay'; + }, + + get_loopType: function () { + return this._loopType$1; + }, + + set_loopType: function (value) { + this._loopType$1 = value; + return value; + }, + + get_startFrame: function () { + return this._startFrame$1; + }, + + set_startFrame: function (value) { + this._startFrame$1 = value; + return value; + }, + + get_frameSequence: function () { + return this._frameSequence$1; + }, + + set_frameSequence: function (value) { + if (this._frameSequence$1 !== value) { + this._frameSequence$1 = value; + this._framesList$1 = []; + if (!ss.emptyString(this._frameSequence$1)) { + try { + var parts = this._frameSequence$1.split(','); + var $enum1 = ss.enumerate(parts); + while ($enum1.moveNext()) { + var part = $enum1.current; + var x = parseInt(ss.trim(part)); + this._framesList$1.push(x); + } + } + catch ($e2) { + } + } + } + return value; + }, + + get_frames: function () { + return this._frames$1; + }, + + set_frames: function (value) { + this._frames$1 = value; + return value; + }, + + get_framesX: function () { + return this._framesX$1; + }, + + set_framesX: function (value) { + this._framesX$1 = value; + return value; + }, + + get_framesY: function () { + return this._framesY$1; + }, + + set_framesY: function (value) { + this._framesY$1 = value; + return value; + }, + + copy: function (owner) { + var newFlipbookOverlay = new FlipbookOverlay(); + newFlipbookOverlay.set_owner(owner); + newFlipbookOverlay._filename$1 = this._filename$1; + newFlipbookOverlay.set_x(this.get_x()); + newFlipbookOverlay.set_y(this.get_y()); + newFlipbookOverlay.set_width(this.get_width()); + newFlipbookOverlay.set_height(this.get_height()); + newFlipbookOverlay.set_color(this.get_color()); + newFlipbookOverlay.set_opacity(this.get_opacity()); + newFlipbookOverlay.set_rotationAngle(this.get_rotationAngle()); + newFlipbookOverlay.set_name(this.get_name() + ' - Copy'); + newFlipbookOverlay.set_startFrame(this.get_startFrame()); + newFlipbookOverlay.set_frames(this.get_frames()); + newFlipbookOverlay.set_loopType(this.get_loopType()); + newFlipbookOverlay.set_frameSequence(this.get_frameSequence()); + newFlipbookOverlay.set_framesX(this.get_framesX()); + newFlipbookOverlay.set_framesY(this.get_framesY()); + return newFlipbookOverlay; + }, + + cleanUp: function () { + this.texture = null; + }, + + initializeTexture: function () { + var $this = this; + + try { + var colorKey = ss.endsWith(this._filename$1.toLowerCase(), '.jpg'); + this.texture = this.get_owner().get_owner().getCachedTexture(this._filename$1, function () { + $this._textureReady$1 = true; + }); + } + catch ($e1) { + } + }, + + addFilesToCabinet: function (fc) { + fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); + }, + + writeOverlayProperties: function (xmlWriter) { + xmlWriter._writeStartElement('Flipbook'); + xmlWriter._writeAttributeString('Filename', this._filename$1); + xmlWriter._writeAttributeString('Frames', this._frames$1.toString()); + xmlWriter._writeAttributeString('Loop', Enums.toXml('LoopTypes', this._loopType$1)); + xmlWriter._writeAttributeString('FramesX', this._framesX$1.toString()); + xmlWriter._writeAttributeString('FramesY', this._framesY$1.toString()); + xmlWriter._writeAttributeString('StartFrame', this._startFrame$1.toString()); + if (!ss.emptyString(this._frameSequence$1)) { + xmlWriter._writeAttributeString('FrameSequence', this._frameSequence$1); + } + xmlWriter._writeEndElement(); + }, + + initializeFromXml: function (node) { + var flipbook = Util.selectSingleNode(node, 'Flipbook'); + this._filename$1 = flipbook.attributes.getNamedItem('Filename').nodeValue; + this._frames$1 = parseInt(flipbook.attributes.getNamedItem('Frames').nodeValue); + this._loopType$1 = Enums.parse('LoopTypes', flipbook.attributes.getNamedItem('Loop').nodeValue); + if (flipbook.attributes.getNamedItem('FramesX') != null) { + this.set_framesX(parseInt(flipbook.attributes.getNamedItem('FramesX').nodeValue)); + } + if (flipbook.attributes.getNamedItem('FramesY') != null) { + this.set_framesY(parseInt(flipbook.attributes.getNamedItem('FramesY').nodeValue)); + } + if (flipbook.attributes.getNamedItem('StartFrame') != null) { + this.set_startFrame(parseInt(flipbook.attributes.getNamedItem('StartFrame').nodeValue)); + } + if (flipbook.attributes.getNamedItem('FrameSequence') != null) { + this.set_frameSequence(flipbook.attributes.getNamedItem('FrameSequence').nodeValue); + } + }, + + play: function () { + this._playing$1 = true; + this._timeStart$1 = ss.now(); + }, + + pause: function () { + this._playing$1 = false; + }, + + stop: function () { + this._playing$1 = false; + this._currentFrame$1 = 0; + }, + + initializeGeometry: function () { + var frameCount = this._frames$1; + if (!ss.emptyString(this._frameSequence$1)) { + frameCount = this._framesList$1.length; + } + if (this._playing$1) { + var ts = ss.now() - this._timeStart$1; + switch (this._loopType$1) { + case 0: + this._currentFrame$1 = ss.truncate(((ts / 1000 * 24) % frameCount)) + this._startFrame$1; + break; + case 1: + this._currentFrame$1 = Math.abs(ss.truncate(((ts / 1000 * 24 + frameCount) % (frameCount * 2 - 1))) - (frameCount - 1)) + this._startFrame$1; + if (this._currentFrame$1 < 0 || this._currentFrame$1 > frameCount - 1) { + var p = 0; + } + break; + case 2: + this._currentFrame$1 = Math.max(0, frameCount - ss.truncate(((ts / 1000 * 24) % frameCount))) + this._startFrame$1; + break; + case 3: + var temp = Math.min(ts / 1000 * 24, frameCount * 2 + 1) + frameCount; + this._currentFrame$1 = Math.abs((temp % (frameCount * 2 - 1)) - (frameCount - 1)) + this._startFrame$1; + break; + case 4: + this._currentFrame$1 = Math.min(frameCount - 1, ss.truncate((ts / 1000 * 24))); + break; + case 5: + this._currentFrame$1 = this._startFrame$1; + break; + case 6: + this._currentFrame$1 = (frameCount - 1) + this._startFrame$1; + break; + default: + this._currentFrame$1 = this._startFrame$1; + break; + } + } + if (!ss.emptyString(this._frameSequence$1)) { + if (this._currentFrame$1 < this._framesList$1.length && this._currentFrame$1 > -1) { + this._currentFrame$1 = this._framesList$1[this._currentFrame$1]; + } + else { + this._currentFrame$1 = 0; + } + } + this.currentRotation = 0; + } +}; + +registerType("FlipbookOverlay", [FlipbookOverlay, FlipbookOverlay$, Overlay]); diff --git a/engine/esm/tours/selection.js b/engine/esm/tours/selection.js new file mode 100644 index 00000000..755370d7 --- /dev/null +++ b/engine/esm/tours/selection.js @@ -0,0 +1,249 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// An interactive selection for the tour editor. + +import { ss } from "../ss.js"; +import { registerType, registerEnum } from "../typesystem.js"; +import { Vector2d, Matrix2d, PositionColoredTextured } from "../double3d.js"; +import { Sprite2d } from "../graphics/sprite2d.js"; +import { Texture } from "../graphics/texture.js"; +import { Colors } from "../color.js"; +import { Rectangle } from "../util.js"; + + +// wwtlib.SelectionAnchor + +export var SelectionAnchor = { + topLeft: 0, + top: 1, + topRight: 2, + right: 3, + bottomRight: 4, + bottom: 5, + bottomLeft: 6, + left: 7, + rotate: 8, + move: 9, + center: 10, + none: 11 +}; + +registerType("SelectionAnchor", SelectionAnchor); +registerEnum("SelectionAnchor", SelectionAnchor); + + +// wwtlib.Selection +// +// Note: this type is a bit dangerous because there is a built-in browser type +// of the same name. So if you forget to import this type into your module, your +// code will likely get the other one instead. As usual, we're reluctant to +// rename it because that would break API compatibility. + +export function Selection() { + this._singleSelectHandles = null; + this._multiSelectHandles = null; + this._focusHandles = null; + this.selectionSet = []; + this._focus = null; + this._ratio = 1; + this._sprite = new Sprite2d(); + this._centerX = 0; + this._centerY = 0; +} + +Selection._points = new Array(9 * 3 * 2); + +var Selection$ = { + clearSelection: function () { + this.selectionSet.length = 0; + }, + + addSelection: function (overlay) { + if (overlay != null) { + if (!(this.selectionSet.indexOf(overlay) >= 0)) { + this.selectionSet.push(overlay); + } + } + }, + + addSelectionRange: function (overlays) { + var $enum1 = ss.enumerate(overlays); + while ($enum1.moveNext()) { + var ov = $enum1.current; + this.selectionSet.push(ov); + } + }, + + isOverlaySelected: function (overlay) { + return (this.selectionSet.indexOf(overlay) >= 0); + }, + + setSelection: function (overlay) { + this.selectionSet.length = 0; + if (overlay != null) { + this.selectionSet.push(overlay); + } + }, + + get_multiSelect: function () { + return this.selectionSet.length > 1; + }, + + setSelectionRange: function (overlays) { + this.selectionSet.length = 0; + var $enum1 = ss.enumerate(overlays); + while ($enum1.moveNext()) { + var ov = $enum1.current; + this.selectionSet.push(ov); + } + }, + + get_focus: function () { + return this._focus; + }, + + set_focus: function (value) { + this._focus = value; + return value; + }, + + draw3D: function (renderContext, transparancy) { + this._ratio = 1116 / renderContext.height; + if (this._singleSelectHandles == null) { + this._singleSelectHandles = Texture.fromUrl('images/Selhand.bmp'); + } + if (this._multiSelectHandles == null) { + this._multiSelectHandles = Texture.fromUrl('images/multiSelhand.bmp'); + } + if (this._focusHandles == null) { + this._focusHandles = Texture.fromUrl('images/FocusHandles.png'); + } + if (this.selectionSet.length > 1) { + var $enum1 = ss.enumerate(this.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (overlay === this._focus) { + this._drawSelectionHandles(renderContext, overlay, this._focusHandles); + } + else { + this._drawSelectionHandles(renderContext, overlay, this._multiSelectHandles); + } + } + } else { + var $enum2 = ss.enumerate(this.selectionSet); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + this._drawSelectionHandles(renderContext, overlay, this._singleSelectHandles); + } + } + }, + + _drawSelectionHandles: function (renderContext, overlay, handleTexture) { + var handles = this.makeHandles(overlay); + var angle = overlay.get_rotationAngle(); + var i = 0; + var j = 0; + var $enum1 = ss.enumerate(handles); + while ($enum1.moveNext()) { + var handle = $enum1.current; + Selection._points[i + 0] = new PositionColoredTextured(); + Selection._points[i + 0].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_top() - this._centerY, angle); + Selection._points[i + 0].tu = j * (1 / 9); + Selection._points[i + 0].tv = 0; + Selection._points[i + 0].color = Colors.get_white(); + Selection._points[i + 1] = new PositionColoredTextured(); + Selection._points[i + 1].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_top() - this._centerY, angle); + Selection._points[i + 1].tu = (j + 1) * (1 / 9); + Selection._points[i + 1].tv = 0; + Selection._points[i + 1].color = Colors.get_white(); + Selection._points[i + 2] = new PositionColoredTextured(); + Selection._points[i + 2].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_bottom() - this._centerY, angle); + Selection._points[i + 2].tu = j * (1 / 9); + Selection._points[i + 2].tv = 1; + Selection._points[i + 2].color = Colors.get_white(); + Selection._points[i + 3] = new PositionColoredTextured(); + Selection._points[i + 3].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_top() - this._centerY, angle); + Selection._points[i + 3].tu = (j + 1) * (1 / 9); + Selection._points[i + 3].tv = 0; + Selection._points[i + 3].color = Colors.get_white(); + Selection._points[i + 4] = new PositionColoredTextured(); + Selection._points[i + 4].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_bottom() - this._centerY, angle); + Selection._points[i + 4].tu = (j + 1) * (1 / 9); + Selection._points[i + 4].tv = 1; + Selection._points[i + 4].color = Colors.get_white(); + Selection._points[i + 5] = new PositionColoredTextured(); + Selection._points[i + 5].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_bottom() - this._centerY, angle); + Selection._points[i + 5].tu = j * (1 / 9); + Selection._points[i + 5].tv = 1; + Selection._points[i + 5].color = Colors.get_white(); + i += 6; + j++; + } + if (this.get_multiSelect()) { + this._sprite.draw(renderContext, Selection._points, Selection._points.length - 6, handleTexture, false, 1); + } else { + this._sprite.draw(renderContext, Selection._points, Selection._points.length, handleTexture, false, 1); + } + }, + + pointToSelectionSpace: function (pntIn) { + var tempPoints = new Array(1); + tempPoints[0] = Vector2d.create(pntIn.x, pntIn.y); + var mat = Matrix2d.rotateAt(-this.selectionSet[0].get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.selectionSet[0].get_x(), this.selectionSet[0].get_y())); + mat._transformPoints(tempPoints); + return tempPoints[0]; + }, + + pointToScreenSpace: function (pntIn) { + var tempPoints = new Array(1); + tempPoints[0] = Vector2d.create(pntIn.x, pntIn.y); + var mat = Matrix2d.rotateAt(this.selectionSet[0].get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.selectionSet[0].get_x(), this.selectionSet[0].get_y())); + mat._transformPoints(tempPoints); + return tempPoints[0]; + }, + + hitTest: function (position) { + if (this.selectionSet.length === 1) { + var $enum1 = ss.enumerate(this.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + var handles = this.makeHandles(overlay); + var index = 0; + var testPoint = this.pointToSelectionSpace(position); + var $enum2 = ss.enumerate(handles); + while ($enum2.moveNext()) { + var rectf = $enum2.current; + if (rectf.contains(testPoint)) { + return index; + } + index++; + } + } + } + return 11; + }, + + makeHandles: function (overlay) { + var x = ss.truncate((overlay.get_x() - (overlay.get_width() / 2))) + 0.5; + var y = (ss.truncate(overlay.get_y()) - (overlay.get_height() / 2)) + 0.5; + this._centerX = overlay.get_x(); + this._centerY = overlay.get_y(); + var width = overlay.get_width(); + var height = overlay.get_height(); + var handleSize = 12 * this._ratio; + var handles = new Array(9); + handles[0] = Rectangle.create(x - handleSize, y - handleSize, handleSize, handleSize); + handles[1] = Rectangle.create((x + (width / 2)) - (handleSize / 2), y - handleSize, handleSize, handleSize); + handles[2] = Rectangle.create(x + width, y - handleSize, handleSize, handleSize); + handles[3] = Rectangle.create(x + width, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); + handles[4] = Rectangle.create(x + width, (y + height), handleSize, handleSize); + handles[5] = Rectangle.create((x + (width / 2)) - (handleSize / 2), (y + height), handleSize, handleSize); + handles[6] = Rectangle.create(x - handleSize, (y + height), handleSize, handleSize); + handles[7] = Rectangle.create(x - handleSize, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); + handles[8] = Rectangle.create((x + (width / 2)) - (handleSize / 2), y - 30 * this._ratio, handleSize, handleSize); + return handles; + } +}; + +registerType("Selection", [Selection, Selection$, null]); diff --git a/engine/esm/tours/text_object.js b/engine/esm/tours/text_object.js new file mode 100644 index 00000000..9d91402a --- /dev/null +++ b/engine/esm/tours/text_object.js @@ -0,0 +1,88 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A basic text data object. + +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { Util } from "../baseutil.js"; +import { Color } from "../color.js"; + + + +// wwtlib.TextBorderStyle + +export var TextBorderStyle = { + none: 0, + tight: 1, + small: 2, + medium: 3, + large: 4 +}; + +registerType("TextBorderStyle", TextBorderStyle); +registerEnum("TextBorderStyle", TextBorderStyle); + + +// wwtlib.TextObject + +export function TextObject() { + this.bold = false; + this.italic = false; + this.underline = false; + this.fontSize = 0; + this.borderStyle = 0; +} + +TextObject.create = function (text, bold, italic, underline, fontSize, fontName, forgroundColor, backgroundColor, borderStyle) { + var temp = new TextObject(); + temp.text = text; + temp.bold = bold; + temp.italic = italic; + temp.underline = underline; + temp.fontSize = fontSize; + temp.fontName = fontName; + temp.foregroundColor = forgroundColor; + temp.backgroundColor = backgroundColor; + temp.borderStyle = borderStyle; + return temp; +}; + +TextObject._fromXml = function (node) { + var newTextObject = new TextObject(); + newTextObject.text = Util.getInnerText(node); + newTextObject.borderStyle = 0; + newTextObject.bold = ss.boolean(node.attributes.getNamedItem('Bold').nodeValue); + newTextObject.italic = ss.boolean(node.attributes.getNamedItem('Italic').nodeValue); + newTextObject.underline = ss.boolean(node.attributes.getNamedItem('Underline').nodeValue); + newTextObject.fontSize = parseFloat(node.attributes.getNamedItem('FontSize').nodeValue); + newTextObject.fontName = node.attributes.getNamedItem('FontName').nodeValue; + newTextObject.foregroundColor = Color.load(node.attributes.getNamedItem('ForgroundColor').nodeValue); + newTextObject.backgroundColor = Color.load(node.attributes.getNamedItem('BackgroundColor').nodeValue); + if (node.attributes.getNamedItem('BorderStyle') != null) { + newTextObject.borderStyle = Enums.parse('TextBorderStyle', node.attributes.getNamedItem('BorderStyle').nodeValue); + } + return newTextObject; +}; + +var TextObject$ = { + toString: function () { + return this.text; + }, + + _saveToXml: function (xmlWriter) { + xmlWriter._writeStartElement('TextObject'); + xmlWriter._writeAttributeString('Bold', this.bold.toString()); + xmlWriter._writeAttributeString('Italic', this.italic.toString()); + xmlWriter._writeAttributeString('Underline', this.underline.toString()); + xmlWriter._writeAttributeString('FontSize', this.fontSize.toString()); + xmlWriter._writeAttributeString('FontName', this.fontName); + xmlWriter._writeAttributeString('ForgroundColor', this.foregroundColor.save()); + xmlWriter._writeAttributeString('BackgroundColor', this.backgroundColor.save()); + xmlWriter._writeAttributeString('BorderStyle', Enums.toXml('TextBorderStyle', this.borderStyle)); + xmlWriter._writeString(this.text); + xmlWriter._writeEndElement(); + } +}; + +registerType("TextObject", [TextObject, TextObject$, null]); diff --git a/engine/esm/tours/tour_document.js b/engine/esm/tours/tour_document.js new file mode 100644 index 00000000..a81480f7 --- /dev/null +++ b/engine/esm/tours/tour_document.js @@ -0,0 +1,885 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A WWT Tour document. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { + globalScriptInterface, + globalWWTControl, + layerManagerGetAllMaps, + set_tourDocumentFromUrlRaw, +} from "../data_globals.js"; +import { globalRenderContext } from "../render_globals.js"; +import { Util } from "../baseutil.js"; +import { Texture } from "../graphics/texture.js"; +import { Guid } from "../util.js"; +import { XmlTextWriter } from "../utilities/xml_text_writer.js"; +import { ImageSetType, ProjectionType } from "../imageset.js"; +import { ViewMoverSlew } from "../view_mover.js"; +import { ReferenceFrame } from "../layers/reference_frame.js"; +import { FileCabinet } from "./file_cabinet.js"; +import { TourStop } from "./tour_stop.js"; +import { MasterTime } from "./tour_player.js"; +import { Layer } from "../layers/layer.js"; +import { ImageSetLayer } from "../layers/imageset_layer.js"; +import { LayerManager, LayerMap } from "../layers/layer_manager.js"; + + +// wwtlib.UserLevel + +export var UserLevel = { + beginner: 0, + intermediate: 1, + advanced: 2, + educator: 3, + professional: 4 +}; + +registerType("UserLevel", UserLevel); +registerEnum("UserLevel", UserLevel); + + +// wwtlib.TourDocument + +export function TourDocument() { + this._tourDirty = 0; + this._workingDirectory = ''; + this.url = ''; + this._tagId = ''; + this._representativeThumbnailTourstop = 0; + this._id = ''; + this._title = ''; + this._runTime = 0; + this._lastDirtyCheck = 0; + this._description = ''; + this._attributesAndCredits = ''; + this._authorEmailOther = ''; + this._authorEmail = ''; + this._authorUrl = ''; + this._authorPhone = ''; + this._authorContactText = ''; + this._orgName = 'None'; + this._orgUrl = ''; + this._author = ''; + this._authorImageUrl = ''; + this._authorImage = null; + this._organizationUrl = ''; + this._filename = ''; + this._level = 0; + this._type = 268435456; + this._taxonomy = ''; + this._keywords = ''; + this._objects = ''; + this._editMode = false; + this.explicitTourLinks = []; + this.implicitTourLinks = []; + this._tourStops = []; + this._currentTourstopIndex = -1; + this._textureList = {}; + this._textureList2d = {}; + + // This handles new files added while editing a tour + this._fileCache = {}; + this.dontCleanUpTempFiles = false; + this._id = Guid.newGuid().toString(); +} + +TourDocument.get_baseWorkingDirectory = function () { + return ''; +}; + +TourDocument.fromUrl = function (url, callMe) { + var temp = new TourDocument(); + temp.url = url; + temp._callMe = callMe; + temp._cabinet = FileCabinet.fromUrl(url, ss.bind('_loadXmlDocument', temp)); + return temp; +}; + +TourDocument.fromUrlRaw = function (url, callMe) { + var temp = new TourDocument(); + temp.url = url; + temp._callMe = callMe; + temp._cabinet = FileCabinet.fromUrl(url, callMe); + return temp; +}; + +set_tourDocumentFromUrlRaw(TourDocument.fromUrlRaw); + +var TourDocument$ = { + get_tourDirty: function () { + return this._tourDirty > 0; + }, + + set_tourDirty: function (value) { + if (value) { + this._tourDirty++; + } else { + this._tourDirty = 0; + } + return value; + }, + + get_workingDirectory: function () { + if (ss.emptyString(this._workingDirectory)) { + this._workingDirectory = TourDocument.get_baseWorkingDirectory() + this._id + '\\'; + } + return this._workingDirectory; + }, + + set_workingDirectory: function (value) { + this._workingDirectory = value; + return value; + }, + + _loadXmlDocument: function () { + var $this = this; + + try { + var master = this._cabinet.get_masterFile(); + var doc = new FileReader(); + doc.onloadend = function (ee) { + var data = ss.safeCast(doc.result, String); + var xParser = new DOMParser(); + $this.fromXml(xParser.parseFromString(data, 'text/xml')); + $this._callMe(); + }; + doc.readAsText(this._cabinet.getFileBlob(master)); + } + catch (ex) { + globalScriptInterface._fireTourError(ex); + } + }, + + fromXml: function (doc) { + var root = Util.selectSingleNode(doc, 'Tour'); + this._id = root.attributes.getNamedItem('ID').nodeValue; + this.set_title(root.attributes.getNamedItem('Title').nodeValue); + this.set_author(root.attributes.getNamedItem('Author').nodeValue); + if (root.attributes.getNamedItem('Descirption') != null) { + this.set_description(root.attributes.getNamedItem('Descirption').nodeValue); + } + if (root.attributes.getNamedItem('AuthorEmail') != null) { + this._authorEmail = root.attributes.getNamedItem('AuthorEmail').nodeValue; + } + if (root.attributes.getNamedItem('Keywords') != null) { + this.set_keywords(root.attributes.getNamedItem('Keywords').nodeValue); + } + if (root.attributes.getNamedItem('OrganizationName') != null) { + this.set_orgName(root.attributes.getNamedItem('OrganizationName').nodeValue); + } + this._organizationUrl = root.attributes.getNamedItem('OrganizationUrl').nodeValue; + this._level = Enums.parse('UserLevel', root.attributes.getNamedItem('UserLevel').nodeValue); + this._type = Enums.parse('Classification', root.attributes.getNamedItem('Classification').nodeValue); + this._taxonomy = root.attributes.getNamedItem('Taxonomy').nodeValue; + var TourStops = Util.selectSingleNode(root, 'TourStops'); + var $enum1 = ss.enumerate(TourStops.childNodes); + while ($enum1.moveNext()) { + var tourStop = $enum1.current; + if (tourStop.nodeName === 'TourStop') { + this.addTourStop(TourStop._fromXml(this, tourStop)); + } + } + var Frames = Util.selectSingleNode(root, 'ReferenceFrames'); + if (Frames != null) { + var $enum2 = ss.enumerate(Frames.childNodes); + while ($enum2.moveNext()) { + var frame = $enum2.current; + if (frame.nodeName === 'ReferenceFrame') { + var newFrame = new ReferenceFrame(); + newFrame.initializeFromXml(frame); + if (!ss.keyExists(layerManagerGetAllMaps(), newFrame.name)) { + var map = new LayerMap(newFrame.name, 18); + map.frame = newFrame; + map.loadedFromTour = true; + layerManagerGetAllMaps()[newFrame.name] = map; + } + } + } + LayerManager.connectAllChildren(); + LayerManager.loadTree(); + } + var Layers = Util.selectSingleNode(root, 'Layers'); + if (Layers != null) { + var $enum3 = ss.enumerate(Layers.childNodes); + while ($enum3.moveNext()) { + var layer = $enum3.current; + if (layer.nodeName === 'Layer') { + var newLayer = Layer.fromXml(layer, true); + if (newLayer != null) { + if (ss.canCast(newLayer, ImageSetLayer)) { + var imageSetLayer = newLayer; + var imageset = imageSetLayer.get_imageSet(); + if (imageset.get_projection() === ProjectionType.healpix && imageset.get_extension() === '.tsv') { + globalWWTControl.addCatalogHips(imageset); + continue; + } + } + var fileName = ss.format('{0}.txt', newLayer.id.toString()); + if (ss.keyExists(LayerManager.get_layerList(), newLayer.id)) { + LayerManager.deleteLayerByID(newLayer.id, true, false); + } + try { + newLayer.loadedFromTour = true; + newLayer.loadData(this, fileName); + LayerManager.add(newLayer, false); + } + catch ($e4) { + } + } + } + } + LayerManager.loadTree(); + } + this._tourDirty = 0; + }, + + saveToDataUrl: function () { + return URL.createObjectURL(this.saveToBlob()); + }, + + saveToBlob: function () { + var excludeAudio = false; + this.cleanUp(); + var tourXml = this.getTourXML(); + var fc = new FileCabinet(); + fc.set_packageID(this.get_id()); + fc.addFile('Tour.wwtxml', new Blob([tourXml])); + if (this._authorImage != null) { + } + var $enum1 = ss.enumerate(this.get_tourStops()); + while ($enum1.moveNext()) { + var stop = $enum1.current; + stop._addFilesToCabinet(fc, excludeAudio); + } + var masterList = this._createLayerMasterList(); + var $enum2 = ss.enumerate(masterList); + while ($enum2.moveNext()) { + var id = $enum2.current; + if (ss.keyExists(LayerManager.get_layerList(), id)) { + LayerManager.get_layerList()[id].addFilesToCabinet(fc); + } + } + this.set_tourDirty(false); + return fc.packageFiles(); + }, + + getTourXML: function () { + var xmlWriter = new XmlTextWriter(); + xmlWriter.formatting = 1; + xmlWriter._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + xmlWriter._writeStartElement('Tour'); + xmlWriter._writeAttributeString('ID', this._id); + xmlWriter._writeAttributeString('Title', this._title); + xmlWriter._writeAttributeString('Descirption', this.get_description()); + xmlWriter._writeAttributeString('Description', this.get_description()); + xmlWriter._writeAttributeString('RunTime', (this.get_runTime() / 1000).toString()); + xmlWriter._writeAttributeString('Author', this._author); + xmlWriter._writeAttributeString('AuthorEmail', this._authorEmail); + xmlWriter._writeAttributeString('OrganizationUrl', this._organizationUrl); + xmlWriter._writeAttributeString('OrganizationName', this.get_orgName()); + xmlWriter._writeAttributeString('Keywords', this.get_keywords()); + xmlWriter._writeAttributeString('UserLevel', Enums.toXml('UserLevel', this._level)); + xmlWriter._writeAttributeString('Classification', Enums.toXml('Classification', this._type)); + xmlWriter._writeAttributeString('Taxonomy', this._taxonomy); + var timeLineTour = this._isTimelineTour(); + xmlWriter._writeAttributeString('TimeLineTour', timeLineTour.toString()); + xmlWriter._writeStartElement('TourStops'); + var $enum1 = ss.enumerate(this.get_tourStops()); + while ($enum1.moveNext()) { + var stop = $enum1.current; + stop._saveToXml(xmlWriter, true); + } + xmlWriter._writeEndElement(); + var masterList = this._createLayerMasterList(); + + // This will now save and sync emtpy frames... + var referencedFrames = this._getReferenceFrameList(); + xmlWriter._writeStartElement('ReferenceFrames'); + var $enum2 = ss.enumerate(referencedFrames); + while ($enum2.moveNext()) { + var item = $enum2.current; + item.saveToXml(xmlWriter); + } + xmlWriter._writeEndElement(); + xmlWriter._writeStartElement('Layers'); + var $enum3 = ss.enumerate(masterList); + while ($enum3.moveNext()) { + var id = $enum3.current; + if (ss.keyExists(LayerManager.get_layerList(), id)) { + var layer = LayerManager.get_layerList()[id]; + var name = layer.get_name(); + var imageset = globalRenderContext.getCatalogHipsByName(name); + if (imageset != null) { + var imageSetLayer = ImageSetLayer.create(imageset); + imageSetLayer.id = id; + imageSetLayer.set_name(name); + imageSetLayer.set_referenceFrame('Sky'); + imageSetLayer.saveToXml(xmlWriter); + } + else { + LayerManager.get_layerList()[id].saveToXml(xmlWriter); + } + } + } + xmlWriter._writeEndElement(); + xmlWriter._writeFullEndElement(); + xmlWriter._close(); + return xmlWriter.body; + }, + + _getReferenceFrameList: function () { + var list = []; + var $enum1 = ss.enumerate(ss.keys(layerManagerGetAllMaps())); + while ($enum1.moveNext()) { + var key = $enum1.current; + var lm = layerManagerGetAllMaps()[key]; + if ((lm.frame.reference === 18 || lm.frame.reference === 19) && !(list.indexOf(lm.frame) >= 0) && !lm.frame._systemGenerated) { + list.push(lm.frame); + } + } + return list; + }, + + _createLayerMasterList: function () { + var masterList = []; + var $enum1 = ss.enumerate(this.get_tourStops()); + while ($enum1.moveNext()) { + var stop = $enum1.current; + var $enum2 = ss.enumerate(ss.keys(stop.layers)); + while ($enum2.moveNext()) { + var id = $enum2.current; + if (!(masterList.indexOf(id) >= 0)) { + if (ss.keyExists(LayerManager.get_layerList(), id)) { + masterList.push(id); + } + } + } + } + return masterList; + }, + + _isTimelineTour: function () { + return false; + }, + + get_tagId: function () { + return this._tagId; + }, + + set_tagId: function (value) { + this._tagId = value; + return value; + }, + + get_authorThumbnailFilename: function () { + return 'Author.Png'; + }, + + get_tourThumbnailFilename: function () { + if (this._representativeThumbnailTourstop < this._tourStops.length) { + return this._tourStops[this._representativeThumbnailTourstop].get_tourStopThumbnailFilename(); + } else { + return null; + } + }, + + get_id: function () { + return this._id; + }, + + set_id: function (value) { + this._id = value; + return value; + }, + + get_title: function () { + return this._title; + }, + + set_title: function (value) { + this._title = value; + this.set_tourDirty(true); + return value; + }, + + get_runTime: function () { + if (!this._runTime || this._lastDirtyCheck !== this._tourDirty) { + this._runTime = this._calculateRunTime(); + this._lastDirtyCheck = this._tourDirty; + } + return this._runTime; + }, + + get_description: function () { + return this._description; + }, + + set_description: function (value) { + this._description = value; + this.set_tourDirty(true); + return value; + }, + + get_attributesAndCredits: function () { + return this._attributesAndCredits; + }, + + set_attributesAndCredits: function (value) { + this._attributesAndCredits = value; + this.set_tourDirty(true); + return value; + }, + + get_authorEmailOther: function () { + return this._authorEmailOther; + }, + + set_authorEmailOther: function (value) { + this._authorEmailOther = value; + this.set_tourDirty(true); + return value; + }, + + get_authorEmail: function () { + return this._authorEmail; + }, + + set_authorEmail: function (value) { + this._authorEmail = value; + this.set_tourDirty(true); + return value; + }, + + get_authorUrl: function () { + return this._authorUrl; + }, + + set_authorUrl: function (value) { + this._authorUrl = value; + this.set_tourDirty(true); + return value; + }, + + get_authorPhone: function () { + return this._authorPhone; + }, + + set_authorPhone: function (value) { + this._authorPhone = value; + this.set_tourDirty(true); + return value; + }, + + get_authorContactText: function () { + return this._authorContactText; + }, + + set_authorContactText: function (value) { + this._authorContactText = value; + this.set_tourDirty(true); + return value; + }, + + get_orgName: function () { + return this._orgName; + }, + + set_orgName: function (value) { + this._orgName = value; + this.set_tourDirty(true); + return value; + }, + + get_orgUrl: function () { + return this._orgUrl; + }, + + set_orgUrl: function (value) { + this._orgUrl = value; + this.set_tourDirty(true); + return value; + }, + + get_author: function () { + return this._author; + }, + + set_author: function (value) { + this._author = value; + this.set_tourDirty(true); + return value; + }, + + get_authorImageUrl: function () { + return this._authorImageUrl; + }, + + set_authorImageUrl: function (value) { + this._authorImageUrl = value; + this.set_tourDirty(true); + return value; + }, + + get_authorImage: function () { + return this._authorImage; + }, + + set_authorImage: function (value) { + this._authorImage = value; + this.set_tourDirty(true); + return value; + }, + + get_organizationUrl: function () { + return this._organizationUrl; + }, + + set_organizationUrl: function (value) { + this._organizationUrl = value; + this.set_tourDirty(true); + return value; + }, + + get_fileName: function () { + return this._filename; + }, + + set_fileName: function (value) { + this._filename = value; + return value; + }, + + get_level: function () { + return this._level; + }, + + set_level: function (value) { + this._level = value; + this.set_tourDirty(true); + return value; + }, + + get_type: function () { + return this._type; + }, + + set_type: function (value) { + this._type = value; + this.set_tourDirty(true); + return value; + }, + + get_taxonomy: function () { + return this._taxonomy; + }, + + set_taxonomy: function (value) { + this._taxonomy = value; + this.set_tourDirty(true); + return value; + }, + + get_keywords: function () { + return this._keywords; + }, + + set_keywords: function (value) { + this._keywords = value; + this.set_tourDirty(true); + return value; + }, + + get_objects: function () { + return this._objects; + }, + + set_objects: function (value) { + this._objects = value; + this.set_tourDirty(true); + return value; + }, + + get_editMode: function () { + return this._editMode; + }, + + set_editMode: function (value) { + this._editMode = value; + return value; + }, + + get_tourStops: function () { + return this._tourStops; + }, + + set_tourStops: function (value) { + this._tourStops = value; + return value; + }, + + get_currentTourstopIndex: function () { + return this._currentTourstopIndex; + }, + + set_currentTourstopIndex: function (value) { + this._currentTourstopIndex = value; + return value; + }, + + addTourStop: function (ts) { + ts.set_owner(this); + this.get_tourStops().push(ts); + this._currentTourstopIndex = this._tourStops.length - 1; + this.set_tourDirty(true); + }, + + insertTourStop: function (ts) { + ts.set_owner(this); + if (this._currentTourstopIndex > -1) { + this.get_tourStops().splice(this._currentTourstopIndex, 0, ts); + } else { + this.get_tourStops().push(ts); + this._currentTourstopIndex = this._tourStops.length - 1; + } + this.set_tourDirty(true); + }, + + insertAfterTourStop: function (ts) { + ts.set_owner(this); + if (this._currentTourstopIndex > -1 || this._currentTourstopIndex < this.get_tourStops().length) { + this.get_tourStops().splice(this._currentTourstopIndex + 1, 0, ts); + } else { + this.get_tourStops().push(ts); + this._currentTourstopIndex = this._tourStops.length - 1; + } + this.set_tourDirty(true); + }, + + removeTourStop: function (ts) { + ss.remove(this._tourStops, ts); + if (this._currentTourstopIndex > this._tourStops.length - 1) { + this._currentTourstopIndex--; + } + this.set_tourDirty(true); + }, + + _calculateRunTime: function () { + var totalTime = 0; + for (var i = 0; i < this._tourStops.length; i++) { + totalTime += this._tourStops[i].get_duration(); + if (i > 0) { + switch (this._tourStops[i].get__transition()) { + case 0: + if (this._tourStops[i].get_target().get_backgroundImageset() == null || (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() != ImageSetType.solarSystem) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target())))) { + var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); + var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); + totalTime += slew.get_moveTime() * 1000; + } + break; + case 2: + break; + case 1: + break; + case 5: + break; + default: + break; + } + } + } + return ss.truncate(totalTime); + }, + + elapsedTimeTillTourstop: function (index) { + if (!index && index >= this._tourStops.length) { + return 0; + } + var totalTime = 0; + for (var i = 0; i < index; i++) { + totalTime += this._tourStops[i].get_duration(); + if (i > 0) { + switch (this._tourStops[i].get__transition()) { + case 0: + var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); + if (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() != ImageSetType.solarSystem) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target()))) { + var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); + totalTime += slew.get_moveTime() * 1000; + } + break; + case 2: + break; + case 1: + break; + case 5: + break; + default: + break; + } + } + } + return totalTime / 1000; + }, + + elapsedTimeSinceLastMaster: function (index) { + var masterOut = null; + if (!index && index >= this._tourStops.length) { + return null; + } + var totalTime = 0; + for (var i = 0; i < index; i++) { + if (this._tourStops[i].get_masterSlide()) { + totalTime = 0; + masterOut = this._tourStops[i]; + } + totalTime += this._tourStops[i].get_duration(); + if (i > 0) { + switch (this._tourStops[i].get__transition()) { + case 0: + var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); + if (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() != ImageSetType.solarSystem) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target()))) { + var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); + totalTime += slew.get_moveTime() * 1000; + } + break; + case 2: + break; + case 1: + break; + case 5: + break; + default: + break; + } + } + } + return new MasterTime(masterOut, totalTime / 1000); + }, + + getMasterSlideForIndex: function (index) { + var master = -1; + for (var i = 0; i < index; i++) { + if (this._tourStops[i].get_masterSlide()) { + master = i; + } + } + if (master === -1) { + return null; + } + return this._tourStops[master]; + }, + + getTourStopIndexByID: function (id) { + if (!id || id === 'Next') { + return this._currentTourstopIndex++; + } + var index = 0; + var $enum1 = ss.enumerate(this._tourStops); + while ($enum1.moveNext()) { + var stop = $enum1.current; + if (stop.get_id() === id) { + return index; + } + index++; + } + return -1; + }, + + cleanUp: function () { }, + + getCachedTexture: function (filename, callMe) { + if (this._textureList == null) { + this._textureList = {}; + } + if (ss.keyExists(this._textureList, filename)) { + callMe(); + return this._textureList[filename]; + } + var url = this.getFileStream(filename); + if (!ss.whitespace(url)) { + var texture = document.createElement('img'); + texture.src = this.getFileStream(filename); + texture.addEventListener('load', function () { + callMe(); + }, false); + this._textureList[filename] = texture; + return texture; + } else { + return null; + } + }, + + getCachedTexture2d: function (filename) { + if (this._textureList2d == null) { + this._textureList2d = {}; + } + if (ss.keyExists(this._textureList2d, filename)) { + return this._textureList2d[filename]; + } + var texture = new Texture(); + texture.load(this.getFileStream(filename)); + this._textureList2d[filename] = texture; + return texture; + }, + + addCachedFile: function (filename, file) { + this._fileCache[filename] = file; + + //Clean up old Cached Textures if they are based on this file. + + if (ss.keyExists(this._textureList2d, filename)) { + delete this._textureList2d[filename]; + } + if (ss.keyExists(this._textureList, filename)) { + delete this._textureList[filename]; + } + }, + + getFileStream: function (filename) { + var blob = this.getFileBlob(filename); + if (blob == null) { + return null; + } + return URL.createObjectURL(blob); + }, + + getFileBlob: function (filename) { + if (ss.keyExists(this._fileCache, filename)) { + return this._fileCache[filename]; + } else if (this._cabinet != null) { + return this._cabinet.getFileBlob(this.get_workingDirectory() + filename); + } else { + return null; + } + }, + + get_currentTourStop: function () { + if (this._currentTourstopIndex > -1) { + return this.get_tourStops()[this._currentTourstopIndex]; + } else { + return null; + } + }, + + set_currentTourStop: function (value) { + var i = 0; + var $enum1 = ss.enumerate(this.get_tourStops()); + while ($enum1.moveNext()) { + var stop = $enum1.current; + if (stop === value) { + if (this._currentTourstopIndex > -1) { + } + this._currentTourstopIndex = i; + break; + } + i++; + } + return value; + }, + + clearTempFiles: function () { } +}; + +registerType("TourDocument", [TourDocument, TourDocument$, null]); diff --git a/engine/esm/tours/tour_edit.js b/engine/esm/tours/tour_edit.js new file mode 100644 index 00000000..78a9420b --- /dev/null +++ b/engine/esm/tours/tour_edit.js @@ -0,0 +1,858 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The "tour editor tab" UX. +// +// This file defines `TourEditTab`; the types `TourEdit` and `TourEditor` are +// defined in `tour_editor.js`. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { globalWWTControl, setManagerVisibleLayerList } from "../data_globals.js"; +import { globalRenderContext } from "../render_globals.js"; +import { Vector2d } from "../double3d.js"; +import { Util } from "../baseutil.js"; +import { Colors } from "../color.js"; +import { XmlTextWriter } from "../utilities/xml_text_writer.js"; +import { ContextMenuStrip, ToolStripMenuItem, ToolStripSeparator } from "../utilities/context_menu_strip.js"; +import { Cursor, Cursors, Guid, Language, SelectLink } from "../util.js"; +import { Place } from "../place.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { UiTools } from "../ui_tools.js"; +import { LayerManager } from "../layers/layer_manager.js"; +import { Overlay } from "./overlay.js"; +import { Undo, UndoTourSlidelistChange } from "./undo.js"; +import { TourStop, UndoTourStopChange } from "./tour_stop.js"; +import { TourPlayer } from "./tour_player.js"; +import { TourEditor, TourEdit, SoundEditor, OverlayList, TourStopList, TimeLine } from "./tour_editor.js"; + + +// wwtlib.TourEditTab + +export function TourEditTab() { + this.musicTrack = new SoundEditor(); + this.voiceTrack = new SoundEditor(); + this._tour = null; + this.tourStopList = new TourStopList(); + this.tourEditorUI = new TourEditor(); + this._contextMenu = new ContextMenuStrip(); + this.nextSlideCallback = null; + this.playing = false; + this._player = null; + this._defultColor = Colors.get_white(); +} + +var TourEditTab$ = { + setUiStrings: function () { }, + + get_tour: function () { + return this._tour; + }, + + set_tour: function (value) { + this._tour = value; + this.tourEditorUI.set_tour(this._tour); + this.tourStopList.tour = this._tour; + Overlay.defaultAnchor = 1; + if (this._tour.get_tourStops().length > 0) { + globalWWTControl.gotoTarget(this._tour.get_tourStops()[0].get_target(), false, true, false); + this._tour.set_currentTourstopIndex(0); + this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); + this.musicTrack.target = this._tour.get_currentTourStop(); + this.voiceTrack.target = this._tour.get_currentTourStop(); + setManagerVisibleLayerList(this._tour.get_currentTourStop().layers); + } + this.setEditMode(this._tour.get_editMode()); + return value; + }, + + tour_CurrentTourstopChanged: function () { + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); + if (this.tourEditorUI != null) { + this.tourEditorUI.clearSelection(); + } + this.tourStopList.refresh(); + }, + + setFocusedChild: function () { }, + + selectCurrent: function () { + this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); + this.tourStopList.refresh(); + }, + + tourEdit_Load: function (sender, e) { }, + + playNow: function (fromStart) { + this.playing = true; + if (this.get_tour().get_editMode() || fromStart) { + this.get_tour().set_currentTourstopIndex(-1); + } + this.setPlayPauseMode(); + }, + + _tourPlayer_TourEnded: function (sender, e) { }, + + _endTour_CloseTour: function (sender, e) { }, + + _endTour_LaunchTour: function (sender, e) { + this.playNow(true); + }, + + setEditMode: function (visible) { }, + + tourStopList_ItemClicked: function (sender, e) { + if (this._tour.get_currentTourStop() !== e) { + this._tour.set_currentTourStop(e); + if (e != null) { + this.musicTrack.target = this._tour.get_currentTourStop(); + this.voiceTrack.target = this._tour.get_currentTourStop(); + } + else { + this.musicTrack.target = null; + this.voiceTrack.target = null; + } + this.tourEditorUI.clearSelection(); + } + if (this.playing) { + this._playFromHere_Click(sender, new ss.EventArgs()); + } + }, + + tourStopList_ItemDoubleClicked: function (sender, e) { + this.showSlideStartPosition(e); + }, + + showSlideStartPosition: function (ts) { + this._tour.set_currentTourStop(ts); + if (ts != null) { + this.musicTrack.target = this._tour.get_currentTourStop(); + this.voiceTrack.target = this._tour.get_currentTourStop(); + } else { + this.musicTrack.target = null; + this.voiceTrack.target = null; + } + this.tourEditorUI.clearSelection(); + if (this._tour.get_currentTourStop() != null) { + this._tour.get_currentTourStop().syncSettings(); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + globalWWTControl.gotoTarget(ts.get_target(), false, true, false); + this._tour.get_currentTourStop().set_tweenPosition(0); + this._tour.get_currentTourStop()._updateLayerOpacity(); + setManagerVisibleLayerList(this._tour.get_currentTourStop().layers); + } + }, + + tourStopList_MouseClick: function (sender, e) { + if (!this._tour.get_editMode()) { + } + if (this.tourStopList.multipleSelection) { + // MultiSelection Menu + if (this._contextMenu != null) { + this._contextMenu._dispose(); + } + this._contextMenu = new ContextMenuStrip(); + var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); + var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); + var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(429, 'Paste')); + var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); + cutMenu.click = ss.bind('_cutMenu_Click', this); + copyMenu.click = ss.bind('_copyMenu_Click', this); + pasteMenu.click = ss.bind('_pasteMenu_Click', this); + deleteMenu.click = ss.bind('_deleteMenu_Click', this); + selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); + var sep1 = new ToolStripSeparator(); + this._contextMenu.items.push(selectAllMenu); + this._contextMenu.items.push(sep1); + this._contextMenu.items.push(cutMenu); + this._contextMenu.items.push(copyMenu); + pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; + this._contextMenu.items.push(pasteMenu); + this._contextMenu.items.push(deleteMenu); + this._contextMenu._show(Cursor.get_position()); + } else if (this._tour.get_currentTourStop() == null) { + // Context menu for no selection + if (this._contextMenu != null) { + this._contextMenu._dispose(); + } + this._contextMenu = new ContextMenuStrip(); + var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); + var sep1 = new ToolStripSeparator(); + var sep2 = new ToolStripSeparator(); + var insertSlide = ToolStripMenuItem.create(Language.getLocalizedText(426, 'Add New Slide')); + pasteMenu.click = ss.bind('_pasteMenu_Click', this); + selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); + insertSlide.click = ss.bind('_addNewSlide_Click', this); + pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; + this._contextMenu.items.push(selectAllMenu); + this._contextMenu.items.push(sep1); + this._contextMenu.items.push(pasteMenu); + this._contextMenu.items.push(sep2); + this._contextMenu.items.push(insertSlide); + this._contextMenu._show(Cursor.get_position()); + } else { + if (this._contextMenu != null) { + this._contextMenu._dispose(); + } + this._contextMenu = new ContextMenuStrip(); + var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); + var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); + var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(429, 'Paste')); + var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); + var sep1 = new ToolStripSeparator(); + var sep3 = new ToolStripSeparator(); + var sep4 = new ToolStripSeparator(); + var sep5 = new ToolStripSeparator(); + var sep6 = new ToolStripSeparator(); + var sep7 = new ToolStripSeparator(); + var insertSlide = ToolStripMenuItem.create(Language.getLocalizedText(431, 'Insert New Slide')); + var insertDuplicate = ToolStripMenuItem.create(Language.getLocalizedText(627, 'Duplicate Slide at End Position')); + var insertSlideshow = ToolStripMenuItem.create(Language.getLocalizedText(628, 'Merge Tour after slide...')); + var playFromHere = ToolStripMenuItem.create(Language.getLocalizedText(432, 'Preview Tour From Here')); + var sep2 = new ToolStripSeparator(); + var captureThumbnail = ToolStripMenuItem.create(Language.getLocalizedText(433, 'Capture New Thumbnail')); + var setSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(434, 'Set Start Camera Position')); + var setEndSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(435, 'Set End Camera Position')); + var showSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(436, 'Show Start Camera Position')); + var showEndSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(437, 'Show End Camera Position')); + var masterSlide = ToolStripMenuItem.create(Language.getLocalizedText(438, 'Master Slide')); + var makeTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1346, 'Create Timeline')); + var showTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1347, 'Show Timeline')); + var linkString = this._tour.get_currentTourStop().get_nextSlide(); + switch (linkString) { + case '': + case null: + case 'Next': + linkString = ' (' + Language.getLocalizedText(610, 'Next Slide') + ')'; + break; + case 'Return': + linkString = ' (' + Language.getLocalizedText(602, 'Return to Caller') + ')'; + break; + default: + var index = this.get_tour().getTourStopIndexByID(linkString); + if (index > -1) { + if (ss.emptyString(this._tour.get_tourStops()[index].get_description())) { + linkString = ss.format(' (Slide {0})', index); + } + else { + linkString = ' (' + this._tour.get_tourStops()[index].get_description() + ')'; + } + } + break; + } + var setNextSlide = ToolStripMenuItem.create(Language.getLocalizedText(590, 'Set Next Slide') + linkString); + var trackSpaceTime = ToolStripMenuItem.create(Language.getLocalizedText(439, 'Track Date/Time/Location')); + var fadeInOverlays = ToolStripMenuItem.create(Language.getLocalizedText(629, 'Fade In Slide Elements')); + var properties = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); + var interpolation = ToolStripMenuItem.create(Language.getLocalizedText(1029, 'Animation Tween Type')); + var Linear = ToolStripMenuItem.create(Language.getLocalizedText(1030, 'Linear')); + var Ease = ToolStripMenuItem.create(Language.getLocalizedText(1031, 'Ease In/Out')); + var EaseIn = ToolStripMenuItem.create(Language.getLocalizedText(1032, 'Ease In')); + var EaseOut = ToolStripMenuItem.create(Language.getLocalizedText(1033, 'Ease Out')); + var Exponential = ToolStripMenuItem.create(Language.getLocalizedText(1034, 'Exponential')); + Linear.tag = 0; + Ease.tag = 3; + EaseIn.tag = 1; + EaseOut.tag = 2; + Exponential.tag = 4; + Linear.click = ss.bind('_interpolation_Click', this); + Ease.click = ss.bind('_interpolation_Click', this); + EaseIn.click = ss.bind('_interpolation_Click', this); + EaseOut.click = ss.bind('_interpolation_Click', this); + Exponential.click = ss.bind('_interpolation_Click', this); + switch (this._tour.get_currentTourStop().get_interpolationType()) { + case 0: + Linear.checked = true; + break; + case 1: + EaseIn.checked = true; + break; + case 2: + EaseOut.checked = true; + break; + case 3: + Ease.checked = true; + break; + case 4: + Exponential.checked = true; + break; + default: + break; + } + interpolation.dropDownItems.push(Linear); + interpolation.dropDownItems.push(Ease); + interpolation.dropDownItems.push(EaseIn); + interpolation.dropDownItems.push(EaseOut); + interpolation.dropDownItems.push(Exponential); + selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); + insertDuplicate.click = ss.bind('_insertDuplicate_Click', this); + cutMenu.click = ss.bind('_cutMenu_Click', this); + copyMenu.click = ss.bind('_copyMenu_Click', this); + pasteMenu.click = ss.bind('_pasteMenu_Click', this); + deleteMenu.click = ss.bind('_deleteMenu_Click', this); + insertSlide.click = ss.bind('_insertNewSlide_Click', this); + properties.click = ss.bind('_properties_Click', this); + captureThumbnail.click = ss.bind('_captureThumbnail_Click', this); + setSkyPosition.click = ss.bind('_setSkyPosition_Click', this); + setEndSkyPosition.click = ss.bind('_setEndSkyPosition_Click', this); + showEndSkyPosition.click = ss.bind('_showEndSkyPosition_Click', this); + showSkyPosition.click = ss.bind('_showSkyPosition_Click', this); + playFromHere.click = ss.bind('_playFromHere_Click', this); + masterSlide.click = ss.bind('_masterSlide_Click', this); + setNextSlide.click = ss.bind('_setNextSlide_Click', this); + trackSpaceTime.click = ss.bind('_trackSpaceTime_Click', this); + insertSlideshow.click = ss.bind('_insertSlideshow_Click', this); + fadeInOverlays.click = ss.bind('_fadeInOverlays_Click', this); + if (this._tour.get_currentTourStop().get_masterSlide()) { + masterSlide.checked = true; + } + if (this._tour.get_currentTourStop().get_hasTime()) { + trackSpaceTime.checked = true; + } + fadeInOverlays.checked = this._tour.get_currentTourStop().get_fadeInOverlays(); + this._contextMenu.items.push(selectAllMenu); + this._contextMenu.items.push(sep7); + this._contextMenu.items.push(cutMenu); + this._contextMenu.items.push(copyMenu); + pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; + this._contextMenu.items.push(pasteMenu); + this._contextMenu.items.push(deleteMenu); + this._contextMenu.items.push(sep1); + this._contextMenu.items.push(insertSlide); + this._contextMenu.items.push(insertDuplicate); + this._contextMenu.items.push(insertSlideshow); + this._contextMenu.items.push(sep2); + this._contextMenu.items.push(playFromHere); + this._contextMenu.items.push(sep3); + this._contextMenu.items.push(setSkyPosition); + this._contextMenu.items.push(setEndSkyPosition); + this._contextMenu.items.push(sep4); + this._contextMenu.items.push(showSkyPosition); + this._contextMenu.items.push(showEndSkyPosition); + this._contextMenu.items.push(sep5); + this._contextMenu.items.push(captureThumbnail); + this._contextMenu.items.push(sep6); + this._contextMenu.items.push(masterSlide); + this._contextMenu.items.push(setNextSlide); + this._contextMenu.items.push(fadeInOverlays); + this._contextMenu.items.push(trackSpaceTime); + this._contextMenu.items.push(interpolation); + this._contextMenu._show(Vector2d.create(e.clientX, e.clientY)); + } + }, + + _selectAllMenu_Click: function (sender, e) { + this.tourStopList.selectAll(); + }, + + _interpolation_Click: function (sender, e) { + var item = sender; + this._tour.get_currentTourStop().set_interpolationType(item.tag); + }, + + _nextSlideChosen: function () { + if (this._selectDialog.get_OK()) { + this._tour.get_currentTourStop().set_nextSlide(this._selectDialog.get_id()); + } + }, + + _setNextSlide_Click: function (sender, e) { + this._selectDialog = new SelectLink(null); + this.nextSlideCallback(this._selectDialog, ss.bind('_nextSlideChosen', this)); + }, + + _insertDuplicate_Click: function (sender, e) { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(530, 'Duplicate Slide at End Position'), this._tour)); + var ts = this._tour.get_currentTourStop().copy(); + if (ts == null) { + return; + } + if (ts.get_endTarget() != null) { + ts.get_endTarget().set_backgroundImageset(ts.get_target().get_backgroundImageset()); + ts.get_endTarget().set_studyImageset(ts.get_target().get_studyImageset()); + ts.set_target(ts.get_endTarget()); + ts.set_startTime(ts.get_endTime()); + ts.set_endTarget(null); + } + var $enum1 = ss.enumerate(ts.get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_tweenFactor(1); + overlay.set_animate(!overlay.get_animate()); + overlay.set_animate(!overlay.get_animate()); + } + ts.set_tweenPosition(0); + ts.set_fadeInOverlays(false); + this._tour.insertAfterTourStop(ts); + this.tourStopList.refresh(); + }, + + _fadeInOverlays_Click: function (sender, e) { + this._tour.get_currentTourStop().set_fadeInOverlays(!this._tour.get_currentTourStop().get_fadeInOverlays()); + }, + + _insertSlideshow_Click: function (sender, e) { }, + + _trackSpaceTime_Click: function (sender, e) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(532, 'Track Time Edit'), this._tour)); + this._tour.get_currentTourStop().set_hasTime(!this._tour.get_currentTourStop().get_hasTime()); + }, + + _masterSlide_Click: function (sender, e) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(533, 'Master Slide State Edit'), this._tour)); + this._tour.get_currentTourStop().set_masterSlide(!this._tour.get_currentTourStop().get_masterSlide()); + this.tourStopList.refresh(); + }, + + _playFromHere_Click: function (sender, e) { + this.playFromCurrentTourstop(); + }, + + playFromCurrentTourstop: function () { + this.playing = true; + globalWWTControl.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + this.setPlayPauseMode(); + }, + + playFromTourstop: function (ts) { + this._tour.set_currentTourStop(ts); + this.playFromCurrentTourstop(); + }, + + _showSkyPosition_Click: function (sender, e) { + if (this._tour.get_currentTourStop() != null) { + globalWWTControl.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); + this._tour.get_currentTourStop().syncSettings(); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + this._tour.get_currentTourStop().set_tweenPosition(0); + setManagerVisibleLayerList(this._tour.get_currentTourStop().layers); + this.tourStopList.refresh(); + } + }, + + _showEndSkyPosition_Click: function (sender, e) { + this._tour.get_currentTourStop().set_tweenPosition(1); + this._tour.get_currentTourStop()._updateLayerOpacity(); + if (this._tour.get_currentTourStop() != null && this._tour.get_currentTourStop().get_endTarget() != null) { + globalWWTControl.gotoTargetFull(false, true, this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_target().get_studyImageset(), this._tour.get_currentTourStop().get_target().get_backgroundImageset()); + globalRenderContext.set_solarSystemTrack(this._tour.get_currentTourStop().get_endTarget().get_target()); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_endTime()); + this._tour.get_currentTourStop().syncSettings(); + setManagerVisibleLayerList(this._tour.get_currentTourStop().layers); + SpaceTimeController.set_syncToClock(false); + this.tourStopList.refresh(); + this.tourEditorUI.clearSelection(); + } + }, + + _setEndSkyPosition_Click: function (sender, e) { + if (this._tour.get_currentTourStop() != null) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(435, 'Set End Camera Position'), this._tour)); + var newPlace = Place.createCameraParams('End Place', globalRenderContext.viewCamera.copy(), 268435456, globalWWTControl.constellation, globalRenderContext.get_backgroundImageset().get_dataSetType(), globalRenderContext.get_solarSystemTrack()); + this._tour.get_currentTourStop().set_endTarget(newPlace); + this._tour.get_currentTourStop().get_endTarget().set_constellation(globalWWTControl.constellation); + this._tour.get_currentTourStop().set_endTime(SpaceTimeController.get_now()); + this._tour.get_currentTourStop().set_tweenPosition(1); + var $enum1 = ss.enumerate(ss.keys(this._tour.get_currentTourStop().layers)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var info = this._tour.get_currentTourStop().layers[key]; + if (ss.keyExists(LayerManager.get_layerList(), info.id)) { + info.endOpacity = LayerManager.get_layerList()[info.id].get_opacity(); + info.endParams = LayerManager.get_layerList()[info.id].getParams(); + } + } + this._tour.get_currentTourStop()._updateLayerOpacity(); + this.tourStopList.refresh(); + TimeLine.refreshUi(); + this.tourEditorUI.clearSelection(); + } + }, + + _setSkyPosition_Click: function (sender, e) { + if (this._tour.get_currentTourStop() != null) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(434, 'Set Start Camera Position'), this._tour)); + this._tour.get_currentTourStop().get_target().set_target(globalRenderContext.get_solarSystemTrack()); + this._tour.get_currentTourStop().get_target().set_type(globalRenderContext.get_backgroundImageset().get_dataSetType()); + this._tour.get_currentTourStop().get_target().set_camParams(globalRenderContext.viewCamera.copy()); + this._tour.get_currentTourStop().get_target().set_constellation(globalWWTControl.constellation); + this._tour.get_currentTourStop().get_target().set_studyImageset(globalRenderContext.get_foregroundImageset()); + this._tour.get_currentTourStop().get_target().set_type(globalRenderContext.get_backgroundImageset().get_dataSetType()); + this._tour.get_currentTourStop().get_target().set_backgroundImageset(globalRenderContext.get_backgroundImageset().get_stockImageSet()); + this._tour.get_currentTourStop().captureSettings(); + this._tour.get_currentTourStop().layers = LayerManager._getVisibleLayerList(this._tour.get_currentTourStop().layers); + this._tour.get_currentTourStop().set_tweenPosition(0); + this.tourStopList.refresh(); + TimeLine.refreshUi(); + this.tourEditorUI.clearSelection(); + } + }, + + _captureThumbnail_Click: function (sender, e) { + if (this._tour.get_currentTourStop() != null) { + this._captureThumbnail(this._tour.get_currentTourStop()); + } + }, + + _captureThumbnail: function (tourStop) { + var $this = this; + + globalWWTControl.captureThumbnail(function (blob) { + var filename = ss.format('{0}.thumb.png', tourStop.get_id()); + $this._tour.addCachedFile(filename, blob); + tourStop.set_thumbnail($this._tour.getCachedTexture(filename, function () { + $this.tourStopList.refresh(); + })); + }); + }, + + _properties_Click: function (sender, e) { + throw new Error('The method or operation is not implemented.'); + }, + + tourStopList_AddNewSlide: function (sender, e) { + this.addSlide(false); + this.tourStopList.ensureAddVisible(); + }, + + _addNewSlide_Click: function (sender, e) { + this.addSlide(false); + this.tourStopList.ensureAddVisible(); + }, + + _insertNewSlide_Click: function (sender, e) { + this.addSlide(true); + }, + + addSlide: function (insert) { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(426, 'Add New Slide'), this._tour)); + Cursor.set_current(Cursors.get_waitCursor()); + var placeName = 'Current Screen'; + var newPlace = Place.createCameraParams(placeName, globalRenderContext.viewCamera.copy(), 268435456, globalWWTControl.constellation, globalRenderContext.get_backgroundImageset().get_dataSetType(), globalRenderContext.get_solarSystemTrack()); + newPlace.set_studyImageset(globalRenderContext.get_foregroundImageset()); + newPlace.set_backgroundImageset(globalRenderContext.get_backgroundImageset().get_stockImageSet()); + var newTourStop = TourStop.create(newPlace); + if (insert) { + this._tour.insertTourStop(newTourStop); + } else { + this._tour.addTourStop(newTourStop); + } + if (this._tour.get_currentTourStop() != null) { + this.musicTrack.target = this._tour.get_currentTourStop(); + this.voiceTrack.target = this._tour.get_currentTourStop(); + } else { + this.musicTrack.target = null; + this.voiceTrack.target = null; + } + this._tour.get_currentTourStop().layers = LayerManager._getVisibleLayerList(this._tour.get_currentTourStop().layers); + this._captureThumbnail(newTourStop); + this.tourStopList.selectedItem = this.tourStopList.findItem(newTourStop); + this.tourStopList.refresh(); + this.tourEditorUI.clearSelection(); + Cursor.set_current(Cursors.get_defaultV()); + TimeLine.refreshUi(); + }, + + _deleteMenu_Click: function (sender, e) { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(534, 'Delete Slide'), this._tour)); + var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var item = this.tourStopList.selectedItems[key]; + this._tour.removeTourStop(item); + } + ss.clearKeys(this.tourStopList.selectedItems); + this.tourStopList.selectedItem = -1; + this._tour.set_currentTourStop(null); + this.musicTrack.target = null; + this.voiceTrack.target = null; + this.tourStopList.refresh(); + this.tourEditorUI.clearSelection(); + }, + + _pasteMenu_Click: function (sender, e) { + if (this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide') { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(535, 'Paste Slide'), this._tour)); + var xParser = new DOMParser(); + var doc = xParser.parseFromString(this.tourEditorUI.clipboardData, 'text/xml'); + var node = Util.selectSingleNode(doc, 'TourStops'); + var pasteStack = new ss.Stack(); + var $enum1 = ss.enumerate(node.childNodes); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child.nodeName === 'TourStop') { + var ts = TourStop._fromXml(this._tour, child); + ts.set_id(Guid.newGuid().toString()); + pasteStack.push(ts); + } + } + ss.clearKeys(this.tourStopList.selectedItems); + var curIndex = this.tourStopList.selectedItem + pasteStack.count - 1; + while (pasteStack.count > 0) { + var ts = pasteStack.pop(); + this._tour.insertTourStop(ts); + this.tourStopList.selectedItems[curIndex--] = ts; + } + this.tourStopList.refresh(); + this.tourEditorUI.clearSelection(); + } + }, + + _copyMenu_Click: function (sender, e) { + var writer = new XmlTextWriter(); + writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + writer._writeStartElement('TourStops'); + var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var item = this.tourStopList.selectedItems[key]; + item._saveToXml(writer, true); + } + writer._writeEndElement(); + this.tourEditorUI.clipboardType = 'WorldWideTelescope.Slide'; + this.tourEditorUI.clipboardData = writer.body; + }, + + _cutMenu_Click: function (sender, e) { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(536, 'Cut Slide'), this._tour)); + this._copyMenu_Click(sender, e); + var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var item = this.tourStopList.selectedItems[key]; + this._tour.removeTourStop(item); + } + ss.clearKeys(this.tourStopList.selectedItems); + this.tourStopList.refresh(); + this.tourEditorUI.clearSelection(); + }, + + pauseTour: function () { + if (this.playing) { + this.playing = false; + } + this.setPlayPauseMode(); + }, + + preview_Click: function (sender, e) { + this.playing = !this.playing; + if (this.playing && this._tour.get_editMode()) { + this.get_tour().set_currentTourstopIndex(-1); + } + this.setPlayPauseMode(); + }, + + setPlayPauseMode: function () { + if (this._tour.get_editMode()) { + if (this.playing) { + if (this._player == null) { + this._player = new TourPlayer(); + } + this._player.set_tour(this._tour); + globalWWTControl.uiController = this._player; + this._player.play(); + this.tourStopList.showAddButton = false; + } + else { + globalWWTControl.uiController = this.tourEditorUI; + if (this._player != null) { + this._player.stop(false); + } + this._player = null; + globalWWTControl.set__mover(null); + this.tourStopList.showAddButton = this._tour.get_editMode(); + } + } else { + if (this.playing) { + if (this._player == null) { + this._player = new TourPlayer(); + } + this._player.set_tour(this._tour); + globalWWTControl.uiController = this._player; + this._player.play(); + this.tourStopList.showAddButton = false; + } + else { + globalWWTControl.uiController = null; + globalRenderContext.freezeView(); + if (this._player != null) { + this._player.stop(false); + } + this._player = null; + globalWWTControl.uiController = null; + globalWWTControl.set__mover(null); + this.tourStopList.showAddButton = this._tour.get_editMode(); + } + } + this.tourStopList.refresh(); + }, + + playerTimer_Tick: function (sender, e) { + if (this.playing) { + if (this._player != null) { + if (!TourPlayer.get_playing()) { + this.playing = false; + this.setPlayPauseMode(); + } + else { + if (this.tourStopList.selectedItem !== this._tour.get_currentTourstopIndex()) { + this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); + } + } + } + } + }, + + insertShapeCircle_Click: function (sender, e) { + this.tourEditorUI.addShape('', 0); + }, + + insertShapeRectangle_Click: function (sender, e) { + this.tourEditorUI.addShape('', 1); + }, + + insertShapeLine_Click: function (sender, e) { + this.tourEditorUI.addShape('', 5); + }, + + insertDonut_Click: function (sender, e) { + this.tourEditorUI.addShape('', 3); + }, + + _addArrow_Click: function (sender, e) { + this.tourEditorUI.addShape('', 4); + }, + + insertVideo_Click: function (sender, e) { }, + + insertAudio_Click: function (sender, e) { }, + + insertHyperlink_Click: function (sender, e) { }, + + colorPicker_Click: function (sender, e) { }, + + tourEditTab_Leave: function (sender, e) { }, + + editTourProperties_Click: function (sender, e) { }, + + saveTour_Click: function (sender, e) { + this.save(false); + }, + + save: function (saveAs) { + return true; + }, + + addVideo_Click: function (sender, e) { }, + + addPicture_Click: function (sender, e) { }, + + addShape_Click: function (sender, e) { }, + + _addOpenRectangle_Click: function (sender, e) { + this.tourEditorUI.addShape('', 6); + }, + + _addStar_Click: function (sender, e) { + this.tourEditorUI.addShape('', 2); + }, + + addText_Click: function (sender, e) { }, + + preview_EnabledChanged: function (sender, e) { + if (this.playing) { + } else { + } + }, + + preview_MouseEnter: function (sender, e) { }, + + preview_MouseLeave: function (sender, e) { }, + + preview_MouseUp: function (sender, e) { }, + + preview_MouseDown: function (sender, e) { }, + + tourStopList_ItemHover: function (sender, e) { }, + + refresh: function () { }, + + undoStep: function () { + if (Undo.peekAction()) { + Undo.stepBack(); + this.tourStopList.refresh(); + this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); + this.showSlideStartPosition(this._tour.get_currentTourStop()); + this.refresh(); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); + } + }, + + redoStep: function () { + if (Undo.peekRedoAction()) { + Undo.stepForward(); + this.tourStopList.refresh(); + this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); + this.showSlideStartPosition(this._tour.get_currentTourStop()); + this.refresh(); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); + } + }, + + tourStopList_ShowEndPosition: function (sender, e) { + this._showEndSkyPosition_Click(this, new ss.EventArgs()); + }, + + tourStopList_ShowStartPosition: function (sender, e) { + this.showSlideStartPosition(this.get_tour().get_currentTourStop()); + this.tourEditorUI.clearSelection(); + }, + + tourStopList_KeyDown: function (sender, e) { + if (e.ctrlKey) { + switch (e.keyCode) { + case 67: + this._copyMenu_Click(null, new ss.EventArgs()); + break; + case 86: + this._pasteMenu_Click(null, new ss.EventArgs()); + break; + case 88: + this._cutMenu_Click(null, new ss.EventArgs()); + break; + case 90: + if (Undo.peekAction()) { + TourEdit._undoStep(); + } + else { + UiTools._beep(); + } + break; + case 89: + if (Undo.peekRedoAction()) { + TourEdit._redoStep(); + } + else { + UiTools._beep(); + } + break; + } + } + if (e.keyCode === 46) { + this._deleteMenu_Click(null, new ss.EventArgs()); + } + }, + + _ensureSelectedVisible: function () { + this.tourStopList.ensureSelectedVisible(); + } +}; + +registerType("TourEditTab", [TourEditTab, TourEditTab$, null]); diff --git a/engine/esm/tours/tour_editor.js b/engine/esm/tours/tour_editor.js new file mode 100644 index 00000000..ef221d03 --- /dev/null +++ b/engine/esm/tours/tour_editor.js @@ -0,0 +1,1564 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Infrastructure for editing tours. +// +// This file defines `TourEdit` and `TourEditor`, among others; the type +// `TourEditTab` is defined in `tour_edit.js`. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Vector2d } from "../double3d.js"; +import { Util } from "../baseutil.js"; +import { Colors } from "../color.js"; +import { ColorPicker } from "../utilities/color_picker.js"; +import { ContextMenuStrip, ToolStripMenuItem, ToolStripSeparator } from "../utilities/context_menu_strip.js"; +import { SimpleInput } from "../utilities/simple_input.js"; +import { XmlTextWriter } from "../utilities/xml_text_writer.js"; +import { IUiController } from "../interfaces.js"; +import { globalRenderContext } from "../render_globals.js"; +import { Settings } from "../settings.js"; +import { UiTools } from "../ui_tools.js"; +import { Cursor, Cursors, Language, OverlayProperties, SelectLink, PopupVolume } from "../util.js"; +import { Overlay, AudioOverlay, BitmapOverlay, FlipbookOverlay, ShapeOverlay, TextOverlay } from "./overlay.js"; +import { Selection } from "./selection.js"; +import { Undo, UndoTourSlidelistChange } from "./undo.js"; +import { UndoTourStopChange } from "./tour_stop.js"; + + +// wwtlib.TourEditor + +export function TourEditor() { + this.selection = new Selection(); + this._contextMenu = new ContextMenuStrip(); + this._tour = null; + this._mouseDown = false; + this._selectionAction = 11; + this._needUndoFrame = false; + this._contextPoint = new Vector2d(); + this._dragCopying = false; + this._brokeThreshold = false; + this.nextSlideCallback = null; + this.clipboardData = ''; + this.clipboardType = ''; + this.editTextCallback = null; + this._defaultColor = Colors.get_white(); +} + +TourEditor.capturing = false; +TourEditor.currentEditor = null; + +var TourEditor$ = { + render: function (renderContext) { + renderContext.setupMatricesOverlays(); + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (overlay.get_animate() && this.get_tour().get_currentTourStop().get_keyFramed()) { + overlay.set_tweenFactor(this._tour.get_currentTourStop().get_tweenPosition()); + } + else if (!this.get_tour().get_currentTourStop().get_keyFramed()) { + overlay.set_tweenFactor((this._tour.get_currentTourStop().get_tweenPosition() < 0.5) ? 0 : 1); + } + overlay.draw3D(renderContext, true); + } + this.selection.draw3D(renderContext, 1); + if (TourEditor.currentEditor != null) { + TourEditor.currentEditor.render(renderContext); + } + Settings.tourSettings = null; + }, + + get_tour: function () { + return this._tour; + }, + + set_tour: function (value) { + this._tour = value; + return value; + }, + + close: function () { + if (this._tour != null) { + // todo check for changes + this._tour = null; + this.set_focus(null); + } + }, + + clearSelection: function () { + this.selection.clearSelection(); + OverlayList._updateOverlayListSelection(this.selection); + this.set_focus(null); + }, + + get_focus: function () { + return this.selection.get_focus(); + }, + + set_focus: function (value) { + this.selection.set_focus(value); + return value; + }, + + pointToView: function (pnt) { + var clientHeight = globalRenderContext.height; + var clientWidth = globalRenderContext.width; + var viewWidth = (globalRenderContext.width / globalRenderContext.height) * 1116; + var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); + var y = (pnt.y) / clientHeight * 1116; + return Vector2d.create(x, y); + }, + + mouseDown: function (sender, e) { + this._brokeThreshold = false; + this._needUndoFrame = true; + var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + if (this._tour == null || this._tour.get_currentTourStop() == null) { + this._needUndoFrame = false; + return false; + } + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.mouseDown(sender, e)) { + return true; + } + } + if (this.get_focus() != null) { + if (this.selection.get_multiSelect()) { + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (overlay.hitTest(location)) { + this._selectionAction = 9; + this._mouseDown = true; + this._pointDown = location; + this.set_focus(overlay); + if (e.ctrlKey) { + this._dragCopying = true; + } + return true; + } + } + } + else { + if (this.get_focus().hitTest(location)) { + this._selectionAction = 9; + this._mouseDown = true; + this._pointDown = location; + if (e.ctrlKey) { + this._dragCopying = true; + } + return true; + } + } + var hit = this.selection.hitTest(location); + if (hit !== 11) { + this._selectionAction = hit; + this._mouseDown = true; + if (hit === 8) { + this._pointDown = location; + } + else { + this._pointDown = this.selection.pointToSelectionSpace(location); + } + return true; + } + } + for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { + if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location)) { + this._selectionAction = 9; + this.set_focus(this._tour.get_currentTourStop().get_overlays()[i]); + if (e.ctrlKey || e.shiftKey) { + this.selection.addSelection(this.get_focus()); + } + else { + this.selection.setSelection(this.get_focus()); + } + OverlayList._updateOverlayListSelection(this.selection); + this._mouseDown = true; + this._pointDown = location; + return true; + } + } + this.set_focus(null); + this.clearSelection(); + this._needUndoFrame = false; + return false; + }, + + mouseUp: function (sender, e) { + this._brokeThreshold = false; + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.mouseUp(sender, e)) { + return true; + } + } + this._contextPoint = Vector2d.create(e.offsetX, e.offsetY); + if (this._mouseDown) { + this._mouseDown = false; + if (e.button === 2) { + if (this.get_focus() != null) { + this.showSelectionContextMenu(Vector2d.create(e.offsetX, e.offsetY)); + } + } + return true; + } + if (e.button === 2) { + if (this.get_focus() == null) { + this._showNoSelectionContextMenu(Vector2d.create(e.offsetX, e.offsetY)); + } + return true; + } + return false; + }, + + mouseMove: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.mouseMove(sender, e)) { + return true; + } + } + var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + if (this._mouseDown && this.get_focus() != null) { + var undoFrame = null; + var actionText = Language.getLocalizedText(502, 'Edit'); + if (this._needUndoFrame) { + undoFrame = new UndoTourStopChange(Language.getLocalizedText(502, 'Edit'), this._tour); + } + var moveX; + var moveY; + if (this._selectionAction !== 9 && this._selectionAction !== 8) { + var newPoint = this.selection.pointToSelectionSpace(location); + moveX = newPoint.x - this._pointDown.x; + moveY = newPoint.y - this._pointDown.y; + this._pointDown = newPoint; + } + else { + moveX = location.x - this._pointDown.x; + moveY = location.y - this._pointDown.y; + if (this._selectionAction === 9 && !this._brokeThreshold) { + if (Math.abs(moveX) > 3 || Math.abs(moveY) > 3) { + this._brokeThreshold = true; + } + else { + return true; + } + } + this._pointDown = location; + } + if (this._dragCopying) { + if (this.selection.get_multiSelect()) { + var set = this.selection.selectionSet; + this.clearSelection(); + var $enum1 = ss.enumerate(set); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + var newOverlay = this.addOverlay(overlay); + newOverlay.set_x(overlay.get_x()); + newOverlay.set_y(overlay.get_y()); + this.set_focus(newOverlay); + this.selection.addSelection(this.get_focus()); + } + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + this._dragCopying = false; + } + else { + var newOverlay = this.addOverlay(this.get_focus()); + newOverlay.set_x(this.get_focus().get_x()); + newOverlay.set_y(this.get_focus().get_y()); + this.set_focus(newOverlay); + this.selection.setSelection(this.get_focus()); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + this._dragCopying = false; + } + } + var aspect = this.get_focus().get_width() / this.get_focus().get_height(); + var center = Vector2d.create(this.get_focus().get_x(), this.get_focus().get_y()); + if (e.ctrlKey) { + actionText = Language.getLocalizedText(537, 'Resize'); + switch (this._selectionAction) { + case 0: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - (moveX / aspect) * 2)); + break; + case 1: + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - moveY * 2)); + break; + case 2: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + (moveX / aspect) * 2)); + break; + case 3: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); + break; + case 4: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + (moveX / aspect) * 2)); + break; + case 5: + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + moveY * 2)); + break; + case 6: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); + this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - (moveX / aspect) * 2)); + break; + case 7: + this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); + break; + case 8: + actionText = Language.getLocalizedText(538, 'Rotate'); + this.get_focus().set_rotationAngle(this.get_focus().get_rotationAngle() + moveX / 10); + break; + case 9: + actionText = Language.getLocalizedText(539, 'Drag Copy'); + center.x += moveX; + center.y += moveY; + break; + case 10: + break; + case 11: + break; + default: + break; + } + } + else { + if (this._selectionAction !== 8 && this._selectionAction !== 9) { + if (moveX > (this.get_focus().get_width() - 2)) { + moveX = 0; + } + if (moveY > (this.get_focus().get_height() - 2)) { + moveY = 0; + } + } + actionText = Language.getLocalizedText(537, 'Resize'); + switch (this._selectionAction) { + case 0: + this.get_focus().set_width(this.get_focus().get_width() - moveX); + this.get_focus().set_height(this.get_focus().get_height() - (moveX / aspect)); + center.x += (moveX / 2); + center.y += ((moveX / aspect) / 2); + break; + case 1: + this.get_focus().set_height(this.get_focus().get_height() - moveY); + center.y += (moveY / 2); + break; + case 2: + this.get_focus().set_width(this.get_focus().get_width() + moveX); + this.get_focus().set_height(this.get_focus().get_height() + (moveX / aspect)); + center.x += (moveX / 2); + center.y -= ((moveX / aspect) / 2); + break; + case 3: + this.get_focus().set_width(this.get_focus().get_width() + moveX); + center.x += (moveX / 2); + break; + case 4: + this.get_focus().set_width(this.get_focus().get_width() + moveX); + this.get_focus().set_height(this.get_focus().get_height() + (moveX / aspect)); + center.x += (moveX / 2); + center.y += ((moveX / aspect) / 2); + break; + case 5: + this.get_focus().set_height(this.get_focus().get_height() + moveY); + center.y += (moveY / 2); + break; + case 6: + this.get_focus().set_width(this.get_focus().get_width() - moveX); + this.get_focus().set_height(this.get_focus().get_height() - (moveX / aspect)); + center.x += (moveX / 2); + center.y -= ((moveX / aspect) / 2); + break; + case 7: + this.get_focus().set_width(this.get_focus().get_width() - moveX); + center.x += (moveX / 2); + break; + case 8: + actionText = Language.getLocalizedText(538, 'Rotate'); + this.get_focus().set_rotationAngle(this.get_focus().get_rotationAngle() + moveX); + break; + case 9: + actionText = Language.getLocalizedText(540, 'Move'); + center.x += moveX; + center.y += moveY; + break; + case 10: + break; + case 11: + break; + default: + break; + } + } + if (this._selectionAction !== 9 && this._selectionAction !== 8) { + center = this.selection.pointToScreenSpace(center); + } + if (this.selection.get_multiSelect()) { + var $enum2 = ss.enumerate(this.selection.selectionSet); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + overlay.set_x(overlay.get_x() + moveX); + overlay.set_y(overlay.get_y() + moveY); + } + } + else { + this.get_focus().set_x(center.x); + this.get_focus().set_y(center.y); + } + if (this._needUndoFrame) { + this._needUndoFrame = false; + undoFrame.set_actionText(actionText); + Undo.push(undoFrame); + } + } else { + if (this.get_focus() != null) { + if (this.get_focus().hitTest(location)) { + Cursor.set_current(Cursors.get_sizeAll()); + return false; + } + var hit = this.selection.hitTest(location); + if (hit === 11) { + return false; + } + switch (hit) { + case 0: + Cursor.set_current(Cursors.get_sizeNWSE()); + break; + case 1: + Cursor.set_current(Cursors.get_sizeNS()); + break; + case 2: + Cursor.set_current(Cursors.get_sizeNESW()); + break; + case 3: + Cursor.set_current(Cursors.get_sizeWE()); + break; + case 4: + Cursor.set_current(Cursors.get_sizeNWSE()); + break; + case 5: + Cursor.set_current(Cursors.get_sizeNS()); + break; + case 6: + Cursor.set_current(Cursors.get_sizeNESW()); + break; + case 7: + Cursor.set_current(Cursors.get_sizeWE()); + break; + case 8: + Cursor.set_current(Cursors.get_sizeWE()); + break; + case 10: + break; + case 11: + break; + default: + break; + } + } + } + return false; + }, + + _showNoSelectionContextMenu: function (position) { + if (this._contextMenu != null) { + this._contextMenu._dispose(); + } + if (this._tour.get_currentTourStop() == null) { + return; + } + this._contextMenu = new ContextMenuStrip(); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); + pasteMenu.enabled = this.clipboardType === 'WorldWideTelescope.Overlay'; + pasteMenu.click = ss.bind('_pasteMenu_Click', this); + this._contextMenu.items.push(pasteMenu); + this._contextMenu._show(position); + }, + + _addOpenRectangle_Click: function (sender, e) { + this.addShape('', 6); + }, + + _addStar_Click: function (sender, e) { + this.addShape('', 2); + }, + + _insertShapeCircle_Click: function (sender, e) { + this.addShape('', 0); + }, + + _insertShapeRectangle_Click: function (sender, e) { + this.addShape('', 1); + }, + + _insertShapeLine_Click: function (sender, e) { + this.addShape('', 5); + }, + + _insertDonut_Click: function (sender, e) { + this.addShape('', 3); + }, + + _addArrow_Click: function (sender, e) { + this.addShape('', 4); + }, + + showSelectionContextMenu: function (position) { + if (this.get_focus() == null) { + return; + } + var multiSelect = this.selection.get_multiSelect(); + if (this._contextMenu != null) { + this._contextMenu._dispose(); + } + this._contextMenu = new ContextMenuStrip(); + var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); + var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); + var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); + var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); + var sep1 = new ToolStripSeparator(); + var sep2 = new ToolStripSeparator(); + var sep3 = new ToolStripSeparator(); + var bringToFront = ToolStripMenuItem.create(Language.getLocalizedText(452, 'Bring to Front')); + var sendToBack = ToolStripMenuItem.create(Language.getLocalizedText(453, 'Send to Back')); + var bringForward = ToolStripMenuItem.create(Language.getLocalizedText(454, 'Bring Forward')); + var sendBackward = ToolStripMenuItem.create(Language.getLocalizedText(455, 'Send Backward')); + var properties = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); + var editText = ToolStripMenuItem.create(Language.getLocalizedText(502, 'Edit')); + var url = ToolStripMenuItem.create(Language.getLocalizedText(587, 'Hyperlink')); + var linkString = this.get_focus().get_linkID(); + switch (this.get_focus().get_linkID()) { + case '': + case null: + linkString = ' (' + Language.getLocalizedText(609, 'No Link') + ')'; + break; + case 'Next': + linkString = ' (' + Language.getLocalizedText(610, 'Next Slide') + ')'; + break; + case 'Return': + linkString = ' (' + Language.getLocalizedText(602, 'Return to Caller') + ')'; + break; + default: + var index = this.get_tour().getTourStopIndexByID(this.get_focus().get_linkID()); + if (index > -1) { + if (ss.emptyString(this._tour.get_tourStops()[index].get_description())) { + linkString = ss.format(' (' + Language.getLocalizedText(1340, 'Slide') + ' {0})', index); + } + else { + linkString = ' (' + this._tour.get_tourStops()[index].get_description() + ')'; + } + } + break; + } + var animateMenu = ToolStripMenuItem.create(Language.getLocalizedText(588, 'Animate')); + var linkID = ToolStripMenuItem.create(Language.getLocalizedText(589, 'Link to Slide') + linkString); + var pickColor = ToolStripMenuItem.create(Language.getLocalizedText(458, 'Color/Opacity')); + var flipbookProperties = ToolStripMenuItem.create(Language.getLocalizedText(630, 'Flipbook Properties')); + var interpolateMenu = ToolStripMenuItem.create(Language.getLocalizedText(1029, 'Animation Tween Type')); + var Linear = ToolStripMenuItem.create(Language.getLocalizedText(1030, 'Linear')); + var Ease = ToolStripMenuItem.create(Language.getLocalizedText(1031, 'Ease In/Out')); + var EaseIn = ToolStripMenuItem.create(Language.getLocalizedText(1032, 'Ease In')); + var EaseOut = ToolStripMenuItem.create(Language.getLocalizedText(1033, 'Ease Out')); + var Exponential = ToolStripMenuItem.create(Language.getLocalizedText(1034, 'Exponential')); + var Default = ToolStripMenuItem.create(Language.getLocalizedText(1035, 'Slide Default')); + var Align = ToolStripMenuItem.create(Language.getLocalizedText(790, 'Align')); + var AlignTop = ToolStripMenuItem.create(Language.getLocalizedText(1333, 'Top')); + var AlignBottom = ToolStripMenuItem.create(Language.getLocalizedText(1334, 'Bottom')); + var AlignLeft = ToolStripMenuItem.create(Language.getLocalizedText(1335, 'Left')); + var AlignRight = ToolStripMenuItem.create(Language.getLocalizedText(1336, 'Right')); + var AlignHorizon = ToolStripMenuItem.create(Language.getLocalizedText(1337, 'Horizontal')); + var AlignVertical = ToolStripMenuItem.create(Language.getLocalizedText(1338, 'Vertical')); + var AlignCenter = ToolStripMenuItem.create(Language.getLocalizedText(1339, 'Centered')); + Align.dropDownItems.push(AlignTop); + Align.dropDownItems.push(AlignBottom); + Align.dropDownItems.push(AlignLeft); + Align.dropDownItems.push(AlignRight); + Align.dropDownItems.push(AlignHorizon); + Align.dropDownItems.push(AlignVertical); + Align.dropDownItems.push(AlignCenter); + Linear.tag = 0; + Ease.tag = 3; + EaseIn.tag = 1; + EaseOut.tag = 2; + Exponential.tag = 4; + Default.tag = 5; + Linear.click = ss.bind('_interpolation_Click', this); + Ease.click = ss.bind('_interpolation_Click', this); + EaseIn.click = ss.bind('_interpolation_Click', this); + EaseOut.click = ss.bind('_interpolation_Click', this); + Exponential.click = ss.bind('_interpolation_Click', this); + Default.click = ss.bind('_interpolation_Click', this); + switch (this.get_focus().get_interpolationType()) { + case 0: + Linear.checked = true; + break; + case 1: + EaseIn.checked = true; + break; + case 2: + EaseOut.checked = true; + break; + case 3: + Ease.checked = true; + break; + case 4: + Exponential.checked = true; + break; + case 5: + Default.checked = true; + break; + default: + break; + } + interpolateMenu.dropDownItems.push(Default); + interpolateMenu.dropDownItems.push(Linear); + interpolateMenu.dropDownItems.push(Ease); + interpolateMenu.dropDownItems.push(EaseIn); + interpolateMenu.dropDownItems.push(EaseOut); + interpolateMenu.dropDownItems.push(Exponential); + cutMenu.click = ss.bind('_cutMenu_Click', this); + copyMenu.click = ss.bind('_copyMenu_Click', this); + deleteMenu.click = ss.bind('_deleteMenu_Click', this); + bringToFront.click = ss.bind('_bringToFront_Click', this); + sendToBack.click = ss.bind('_sendToBack_Click', this); + sendBackward.click = ss.bind('_sendBackward_Click', this); + bringForward.click = ss.bind('_bringForward_Click', this); + properties.click = ss.bind('_properties_Click', this); + editText.click = ss.bind('_editText_Click', this); + url.click = ss.bind('_url_Click', this); + pickColor.click = ss.bind('_pickColor_Click', this); + pasteMenu.click = ss.bind('_pasteMenu_Click', this); + animateMenu.click = ss.bind('_animateMenu_Click', this); + flipbookProperties.click = ss.bind('_flipbookProperties_Click', this); + linkID.click = ss.bind('_linkID_Click', this); + AlignTop.click = ss.bind('_alignTop_Click', this); + AlignBottom.click = ss.bind('_alignBottom_Click', this); + AlignLeft.click = ss.bind('_alignLeft_Click', this); + AlignRight.click = ss.bind('_alignRight_Click', this); + AlignHorizon.click = ss.bind('_alignHorizon_Click', this); + AlignVertical.click = ss.bind('_alignVertical_Click', this); + AlignCenter.click = ss.bind('_alignCenter_Click', this); + this._contextMenu.items.push(cutMenu); + this._contextMenu.items.push(copyMenu); + this._contextMenu.items.push(pasteMenu); + this._contextMenu.items.push(deleteMenu); + this._contextMenu.items.push(sep1); + this._contextMenu.items.push(bringToFront); + this._contextMenu.items.push(sendToBack); + this._contextMenu.items.push(bringForward); + this._contextMenu.items.push(sendBackward); + this._contextMenu.items.push(Align); + this._contextMenu.items.push(sep2); + pasteMenu.enabled = false; + this._contextMenu.items.push(pickColor); + this._contextMenu.items.push(url); + this._contextMenu.items.push(linkID); + this._contextMenu.items.push(animateMenu); + this._contextMenu.items.push(sep3); + this._contextMenu.items.push(flipbookProperties); + animateMenu.checked = this.get_focus().get_animate(); + this._contextMenu.items.push(interpolateMenu); + interpolateMenu.enabled = this.get_focus().get_animate(); + flipbookProperties.visible = (ss.canCast(this.get_focus(), FlipbookOverlay)); + sep3.visible = (ss.canCast(this.get_focus(), FlipbookOverlay)); + if (multiSelect) { + url.visible = false; + linkID.visible = false; + properties.visible = false; + flipbookProperties.visible = false; + bringForward.visible = false; + sendBackward.visible = false; + } else { + Align.visible = false; + } + this._contextMenu.items.push(properties); + if (this.get_focus() != null) { + if (ss.typeOf(this.get_focus()) === TextOverlay) { + this._contextMenu.items.push(editText); + } + } + this._contextMenu._show(position); + }, + + _editText_Click: function (sender, e) { + if (this.get_focus() != null) { + if (ss.typeOf(this.get_focus()) === TextOverlay) { + this._editText(); + } + } + }, + + _alignVertical_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1036, 'Vertical Align'), this._tour)); + var xCenter = this.get_focus().get_x(); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_x(xCenter); + } + }, + + _alignHorizon_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1037, 'Horizontal Align'), this._tour)); + var yCenter = this.get_focus().get_y(); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_y(yCenter); + } + }, + + _alignCenter_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1038, 'Align Centers'), this._tour)); + var yCenter = this.get_focus().get_y(); + var xCenter = this.get_focus().get_x(); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_y(yCenter); + overlay.set_x(xCenter); + } + }, + + _alignRight_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1040, 'Align Right'), this._tour)); + var left = this.get_focus().get_x() + this.get_focus().get_width() / 2; + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_x(left - overlay.get_width() / 2); + } + }, + + _alignLeft_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1041, 'Align Left'), this._tour)); + var right = this.get_focus().get_x() - this.get_focus().get_width() / 2; + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_x(right + overlay.get_width() / 2); + } + }, + + _alignBottom_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1042, 'Align Bottoms'), this._tour)); + var top = this.get_focus().get_y() + this.get_focus().get_height() / 2; + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_y(top - overlay.get_height() / 2); + } + }, + + _alignTop_Click: function (sender, e) { + if (this.get_focus() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(1039, 'Align Tops'), this._tour)); + var top = this.get_focus().get_y() - this.get_focus().get_height() / 2; + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_y(top + overlay.get_height() / 2); + } + }, + + _interpolation_Click: function (sender, e) { + var item = sender; + if (this.get_focus() != null) { + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_interpolationType(item.tag); + } + } + }, + + _linkSlideChosen: function () { + if (this.selectDialog.get_OK()) { + this.get_focus().set_linkID(this.selectDialog.get_id()); + } + }, + + _linkID_Click: function (sender, e) { + this.selectDialog = new SelectLink(this.get_focus().get_linkID()); + this.nextSlideCallback(this.selectDialog, ss.bind('_linkSlideChosen', this)); + }, + + _flipbookProperties_Click: function (sender, e) { }, + + _animateMenu_Click: function (sender, e) { + if (this.get_focus() != null) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(588, 'Animate'), this._tour)); + var animate = !this.get_focus().get_animate(); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_animate(animate); + } + } + }, + + _url_Click: function (sender, e) { + var $this = this; + + if (this.get_focus() != null) { + var input = new SimpleInput(Language.getLocalizedText(541, 'Edit Hyperlink'), Language.getLocalizedText(542, 'Url'), this.get_focus().get_url(), 2048); + input.show(Cursor.get_position(), function () { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(541, 'Edit Hyperlink'), $this._tour)); + $this.get_focus().set_url(input.text); + }); + } + }, + + _pickColor_Click: function (sender, e) { + var $this = this; + + var picker = new ColorPicker(); + picker.color = this.get_focus().get_color(); + picker.callBack = function () { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(543, 'Edit Color'), $this._tour)); + var $enum1 = ss.enumerate($this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.set_color(picker.color); + } + }; + picker.show(e); + }, + + _volume_Click: function (sender, e) { + var vol = new PopupVolume(); + vol.volume = (this.get_focus()).get_volume(); + vol.showDialog(); + (this.get_focus()).set_volume(vol.volume); + }, + + _deleteMenu_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(167, 'Delete'), this._tour)); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().removeOverlay(overlay); + } + this.set_focus(null); + this.clearSelection(); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _properties_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(549, 'Properties Edit'), this._tour)); + var props = new OverlayProperties(); + props.overlay = this.get_focus(); + props.showDialog(); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _bringForward_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(454, 'Bring Forward'), this._tour)); + var $enum1 = ss.enumerate(this._getSortedSelection(false)); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().bringForward(overlay); + } + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _sendBackward_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(455, 'Send Backward'), this._tour)); + var $enum1 = ss.enumerate(this._getSortedSelection(true)); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().sendBackward(overlay); + } + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _sendToBack_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(453, 'Send to Back'), this._tour)); + var $enum1 = ss.enumerate(this._getSortedSelection(true)); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().sendToBack(overlay); + } + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _bringToFront_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(452, 'Bring to Front'), this._tour)); + var $enum1 = ss.enumerate(this._getSortedSelection(false)); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().bringToFront(overlay); + } + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _getSortedSelection: function (reverse) { + var sorted = []; + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var ov = $enum1.current; + sorted.push(ov); + } + if (reverse) { + sorted.sort(function (p1, p2) { + return -Util.compare(p1.get_zOrder(), p2.get_zOrder()); + }); + } else { + sorted.sort(function (p1, p2) { + return Util.compare(p1.get_zOrder(), p2.get_zOrder()); + }); + } + return sorted; + }, + + _copyMenu_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + var writer = new XmlTextWriter(); + writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + writer._writeStartElement('Overlays'); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.saveToXml(writer, true); + } + writer._writeEndElement(); + this.clipboardData = writer.body; + this.clipboardType = 'WorldWideTelescope.Overlay'; + }, + + _cutMenu_Click: function (sender, e) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(427, 'Cut'), this._tour)); + this._copyMenu_Click(sender, e); + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + this._tour.get_currentTourStop().removeOverlay(overlay); + } + this.set_focus(null); + this.clearSelection(); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _pasteMenu_Click: function (sender, e) { + Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(544, 'Paste Object'), this._tour)); + if (this.clipboardType === 'WorldWideTelescope.Overlay') { + var xParser = new DOMParser(); + var doc = xParser.parseFromString(this.clipboardData, 'text/xml'); + this.clearSelection(); + var parent = Util.selectSingleNode(doc, 'Overlays'); + var $enum1 = ss.enumerate(parent.childNodes); + while ($enum1.moveNext()) { + var child = $enum1.current; + if (child.nodeName === 'Overlay') { + var copy = Overlay._fromXml(this._tour.get_currentTourStop(), child); + var found = false; + var maxX = 0; + var maxY = 0; + var $enum2 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum2.moveNext()) { + var item = $enum2.current; + if (item.id === copy.id && ss.typeOf(item) === ss.typeOf(copy)) { + found = true; + if (maxY < item.get_y() || maxX < item.get_x()) { + maxX = item.get_x(); + maxY = item.get_y(); + } + } + } + if (found) { + copy.set_x(maxX + 20); + copy.set_y(maxY + 20); + } + this._tour.get_currentTourStop().addOverlay(copy); + this.set_focus(copy); + this.selection.addSelection(this.get_focus()); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + } + } + } + }, + + mouseClick: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.mouseClick(sender, e)) { + return true; + } + } + return false; + }, + + click: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.click(sender, e)) { + return true; + } + } + return false; + }, + + mouseDoubleClick: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.mouseDoubleClick(sender, e)) { + return true; + } + } + if (this.get_focus() != null) { + if (ss.typeOf(this.get_focus()) === TextOverlay) { + this._editText(); + return true; + } + } + return true; + }, + + _doneEditing: function () { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(545, 'Text Edit'), this._tour)); + (this.get_focus()).set_width(0); + (this.get_focus()).set_height(0); + this.get_focus().set_color((this.get_focus()).textObject.foregroundColor); + this.get_focus().cleanUp(); + }, + + _editText: function () { + var textObj = (this.get_focus()).textObject; + this.editTextCallback(textObj, ss.bind('_doneEditing', this)); + }, + + keyDown: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.keyDown(sender, e)) { + return true; + } + } + var increment = 1; + if (e.ctrlKey) { + increment = 10; + } + switch (e.keyCode) { + case 65: + if (e.ctrlKey) { + this.clearSelection(); + this.selection.addSelectionRange(this._tour.get_currentTourStop().get_overlays()); + OverlayList._updateOverlayListSelection(this.selection); + if (this._tour.get_currentTourStop().get_overlays().length > 0) { + this.set_focus(this._tour.get_currentTourStop().get_overlays()[0]); + } + } + break; + case 90: + if (e.ctrlKey) { + if (Undo.peekAction()) { + TourEdit._undoStep(); + } + else { + UiTools._beep(); + } + } + break; + case 89: + if (e.ctrlKey) { + if (Undo.peekRedoAction()) { + TourEdit._redoStep(); + } + else { + UiTools._beep(); + } + } + break; + case 67: + if (e.ctrlKey) { + this._copyMenu_Click(this, new ss.EventArgs()); + } + break; + case 86: + if (e.ctrlKey) { + this._pasteMenu_Click(this, new ss.EventArgs()); + } + break; + case 88: + if (e.ctrlKey) { + this._cutMenu_Click(this, new ss.EventArgs()); + } + break; + case 46: + this._deleteMenu_Click(null, null); + return true; + case 9: + if (e.shiftKey) { + this._selectLast(); + } + else { + this._selectNext(); + } + return true; + case 37: + if (this.get_focus() != null) { + var $enum1 = ss.enumerate(this.selection.selectionSet); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (e.shiftKey) { + if (e.altKey) { + if (overlay.get_width() > increment) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + overlay.set_width(overlay.get_width() - increment); + } + } + else { + var aspect = overlay.get_width() / overlay.get_height(); + if (overlay.get_width() > increment && overlay.get_height() > (increment * aspect)) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + overlay.set_width(overlay.get_width() - increment); + overlay.set_height(overlay.get_height() - increment * aspect); + } + } + } + else if (e.altKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(538, 'Rotate'), this._tour)); + overlay.set_rotationAngle(overlay.get_rotationAngle() - increment); + } + else { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); + overlay.set_x(overlay.get_x() - increment); + } + } + return true; + } + break; + case 39: + if (this.get_focus() != null) { + var $enum2 = ss.enumerate(this.selection.selectionSet); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + if (e.shiftKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + if (e.altKey) { + overlay.set_width(overlay.get_width() + increment); + } + else { + var aspect = overlay.get_width() / overlay.get_height(); + overlay.set_width(overlay.get_width() + increment); + overlay.set_height(overlay.get_height() + increment * aspect); + } + } + else if (e.altKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(538, 'Rotate'), this._tour)); + overlay.set_rotationAngle(overlay.get_rotationAngle() + increment); + } + else { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); + overlay.set_x(overlay.get_x() + increment); + } + } + return true; + } + break; + case 38: + if (this.get_focus() != null) { + var $enum3 = ss.enumerate(this.selection.selectionSet); + while ($enum3.moveNext()) { + var overlay = $enum3.current; + if (e.shiftKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + if (e.altKey) { + overlay.set_height(overlay.get_height() + increment); + } + else { + var aspect = overlay.get_width() / overlay.get_height(); + overlay.set_width(overlay.get_width() + increment); + overlay.set_height(overlay.get_height() + increment * aspect); + } + } + else if (!e.altKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); + overlay.set_y(overlay.get_y() - increment); + } + } + return true; + } + break; + case 40: + if (this.get_focus() != null) { + var $enum4 = ss.enumerate(this.selection.selectionSet); + while ($enum4.moveNext()) { + var overlay = $enum4.current; + if (e.shiftKey) { + if (e.altKey) { + if (overlay.get_height() > increment) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + overlay.set_height(overlay.get_height() - increment); + } + } + else { + var aspect = overlay.get_width() / overlay.get_height(); + if (overlay.get_width() > increment && overlay.get_height() > (increment * aspect)) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); + overlay.set_width(overlay.get_width() - increment); + overlay.set_height(overlay.get_height() - increment * aspect); + } + } + } + else if (!e.altKey) { + Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); + overlay.set_y(overlay.get_y() + increment); + } + } + return true; + } + break; + case 34: + // Next Slide + if (e.altKey) { + if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { + this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; + TourEdit._selectCurrent(); + TourEdit._ensureSelectedVisible(); + } + return true; + } + break; + case 33: + // Prev Slide + if (e.altKey) { + if (this._tour.get_currentTourstopIndex() > 0) { + this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() - 1) + 1; + TourEdit._selectCurrent(); + TourEdit._ensureSelectedVisible(); + } + return true; + } + break; + } + return false; + }, + + _selectNext: function () { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + this.set_focus(this._tour.get_currentTourStop().getNextOverlay(this.get_focus())); + this.selection.setSelection(this.get_focus()); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + _selectLast: function () { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + this.set_focus(this._tour.get_currentTourStop().getPerviousOverlay(this.get_focus())); + this.selection.setSelection(this.get_focus()); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + }, + + keyUp: function (sender, e) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.keyUp(sender, e)) { + return true; + } + } + return false; + }, + + addPicture: function (file) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(546, 'Insert Picture'), this._tour)); + var bmp = BitmapOverlay.create(this._tour.get_currentTourStop(), file); + bmp.set_x(960); + bmp.set_y(600); + this._tour.get_currentTourStop().addOverlay(bmp); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + return true; + }, + + addFlipbook: function (filename) { + return false; + }, + + addAudio: function (file, music) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + var audio = AudioOverlay.create(this._tour.get_currentTourStop(), file); + audio.set_x(900); + audio.set_y(600); + if (music) { + this._tour.get_currentTourStop().set_musicTrack(audio); + } else { + this._tour.get_currentTourStop().set_voiceTrack(audio); + } + return true; + }, + + addVideo: function (filename) { + return true; + }, + + addText: function (p, textObject) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + var text = TextOverlay.create(textObject); + text.set_color(textObject.foregroundColor); + text.set_x(960); + text.set_y(600); + Undo.push(new UndoTourStopChange(Language.getLocalizedText(547, 'Insert Text'), this._tour)); + this._tour.get_currentTourStop().addOverlay(text); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + return true; + }, + + addOverlay: function (ol) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return null; + } + if (ss.typeOf(ol) === ShapeOverlay) { + var srcShapeOverlay = ol; + if (srcShapeOverlay != null) { + var shape = ShapeOverlay._create(this._tour.get_currentTourStop(), srcShapeOverlay.get_shapeType()); + shape.set_width(srcShapeOverlay.get_width()); + shape.set_height(srcShapeOverlay.get_height()); + shape.set_x(this._contextPoint.x); + shape.set_y(this._contextPoint.y); + shape.set_color(srcShapeOverlay.get_color()); + shape.set_rotationAngle(srcShapeOverlay.get_rotationAngle()); + this._tour.get_currentTourStop().addOverlay(shape); + return shape; + } + } else if (ss.typeOf(ol) === TextOverlay) { + var srcTxtOverlay = ol; + if (srcTxtOverlay != null) { + var text = TextOverlay.create(srcTxtOverlay.textObject); + text.set_x(this._contextPoint.x); + text.set_y(this._contextPoint.y); + text.set_color(srcTxtOverlay.get_color()); + this._tour.get_currentTourStop().addOverlay(text); + return text; + } + } else if (ss.typeOf(ol) === BitmapOverlay) { + var srcBmpOverlay = ol; + if (srcBmpOverlay != null) { + var bitmap = srcBmpOverlay.copy(this._tour.get_currentTourStop()); + bitmap.set_x(this._contextPoint.x); + bitmap.set_y(this._contextPoint.y); + this._tour.get_currentTourStop().addOverlay(bitmap); + return bitmap; + } + } else if (ss.typeOf(ol) === FlipbookOverlay) { + var srcFlipbookOverlay = ol; + if (srcFlipbookOverlay != null) { + var bitmap = srcFlipbookOverlay.copy(this._tour.get_currentTourStop()); + bitmap.set_x(this._contextPoint.x); + bitmap.set_y(this._contextPoint.y); + this._tour.get_currentTourStop().addOverlay(bitmap); + return bitmap; + } + } + return null; + }, + + addShape: function (p, shapeType) { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + Undo.push(new UndoTourStopChange(Language.getLocalizedText(548, 'Insert Shape'), this._tour)); + var shape = ShapeOverlay._create(this._tour.get_currentTourStop(), shapeType); + shape.set_width(200); + shape.set_height(200); + if (shapeType === 4) { + shape.set_height(shape.get_height() / 2); + } + if (shapeType === 5) { + shape.set_height(12); + } + shape.set_x(960); + shape.set_y(600); + this._tour.get_currentTourStop().addOverlay(shape); + this.set_focus(shape); + this.selection.setSelection(this.get_focus()); + OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); + return true; + }, + + getCurrentColor: function () { + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return this._defaultColor; + } + if (this.get_focus() != null) { + return this.get_focus().get_color(); + } else { + return this._defaultColor; + } + }, + + setCurrentColor: function (color) { + this._defaultColor = color; + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return; + } + if (this.get_focus() != null) { + this.get_focus().set_color(color); + } + }, + + dispose: function () { + if (this._contextMenu != null) { + this._contextMenu._dispose(); + this._contextMenu = null; + } + }, + + hover: function (pnt) { + if (TourEditor.currentEditor != null) { + if (TourEditor.currentEditor.hover(pnt)) { + return true; + } + } + return true; + } +}; + +registerType("TourEditor", [TourEditor, TourEditor$, null, IUiController]); + + +// wwtlib.OverlayList + +export function OverlayList() { } + +OverlayList._updateOverlayList = function (currentTourStop, selection) { }; + +OverlayList._updateOverlayListSelection = function (selection) { }; + +var OverlayList$ = {}; + +registerType("OverlayList", [OverlayList, OverlayList$, null]); + + +// wwtlib.TourEdit + +export function TourEdit() { } + +TourEdit._ensureSelectedVisible = function () { }; + +TourEdit._selectCurrent = function () { }; + +TourEdit._undoStep = function () { + if (Undo.peekAction()) { + Undo.stepBack(); + } +}; + +TourEdit._redoStep = function () { + if (Undo.peekRedoAction()) { + Undo.stepForward(); + } +}; + +var TourEdit$ = {}; + +registerType("TourEdit", [TourEdit, TourEdit$, null]); + + +// wwtlib.SoundEditor + +export function SoundEditor() { + this.target = null; +} + +var SoundEditor$ = {}; + +registerType("SoundEditor", [SoundEditor, SoundEditor$, null]); + + +// wwtlib.TourStopList + +export function TourStopList() { + this.tour = null; + this.showAddButton = false; + this.selectedItems = null; + this.selectedItem = -1; + this.refreshCallback = null; + this.multipleSelection = false; + this.hitType = false; +} + +var TourStopList$ = { + selectAll: function () { + this.selectedItems = {}; + for (var i = 0; i < this.tour.get_tourStops().length; i++) { + this.selectedItems[i] = this.tour.get_tourStops()[i]; + } + }, + + refresh: function () { + if (this.refreshCallback != null) { + this.refreshCallback(); + } + }, + + findItem: function (ts) { + return -1; + }, + + ensureSelectedVisible: function () { }, + + ensureAddVisible: function () { } +}; + +registerType("TourStopList", [TourStopList, TourStopList$, null]); + + +// wwtlib.TimeLine + +export function TimeLine() { } + +TimeLine.refreshUi = function () { }; + +var TimeLine$ = {}; + +registerType("TimeLine", [TimeLine, TimeLine$, null]); diff --git a/engine/esm/tours/tour_player.js b/engine/esm/tours/tour_player.js new file mode 100644 index 00000000..9f27d753 --- /dev/null +++ b/engine/esm/tours/tour_player.js @@ -0,0 +1,645 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Infrastructure for playing back tours. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Vector2d } from "../double3d.js"; +import { Util } from "../baseutil.js"; +import { BlendState } from "../blend_state.js"; +import { CameraParameters } from "../camera_parameters.js"; +import { IUiController } from "../interfaces.js"; +import { globalScriptInterface, globalWWTControl, setManagerVisibleLayerList } from "../data_globals.js"; +import { Settings } from "../settings.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { ViewMoverKenBurnsStyle } from "../view_mover.js"; +import { TextOverlay } from "./overlay.js"; + + +// wwtlib.TourPlayer + +export function TourPlayer() { + this._overlayBlend = BlendState.create(false, 1000); + this._tour = null; + this._onTarget = false; + this._currentMasterSlide = null; + this._callStack = new ss.Stack(); + this._leaveSettingsWhenStopped = false; +} + +TourPlayer._playing = false; +TourPlayer._switchedToFullScreen = false; +TourPlayer.noRestoreUIOnStop = false; + +TourPlayer.get_playing = function () { + return TourPlayer._playing; +}; + +TourPlayer.set_playing = function (value) { + TourPlayer._playing = value; + return value; +}; + +TourPlayer.add_tourEnded = function (value) { + TourPlayer.__tourEnded = ss.bindAdd(TourPlayer.__tourEnded, value); +}; + +TourPlayer.remove_tourEnded = function (value) { + TourPlayer.__tourEnded = ss.bindSub(TourPlayer.__tourEnded, value); +}; + +var TourPlayer$ = { + render: function (renderContext) { + if (this._tour == null || this._tour.get_currentTourStop() == null || !TourPlayer._playing) { + return; + } + renderContext.save(); + this.updateSlideStates(); + if (!this._onTarget) { + this._slideStartTime = ss.now(); + if (renderContext.onTarget(this.get_tour().get_currentTourStop().get_target())) { + this._onTarget = true; + this._overlayBlend.set_state(!this.get_tour().get_currentTourStop().get_fadeInOverlays()); + this._overlayBlend.set_targetState(true); + if (this._tour.get_currentTourStop().get_musicTrack() != null) { + this._tour.get_currentTourStop().get_musicTrack().seek(0); + this._tour.get_currentTourStop().get_musicTrack().play(); + } + if (this._tour.get_currentTourStop().get_voiceTrack() != null) { + this._tour.get_currentTourStop().get_voiceTrack().seek(0); + this._tour.get_currentTourStop().get_voiceTrack().play(); + } + var caption = ''; + var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (overlay.get_name().toLowerCase() === 'caption') { + var text = ss.safeCast(overlay, TextOverlay); + if (text != null) { + caption = text.textObject.text; + } + } + overlay.play(); + } + setManagerVisibleLayerList(this._tour.get_currentTourStop().layers); + if (this._tour.get_currentTourStop().get_endTarget() != null && this._tour.get_currentTourStop().get_endTarget().get_zoomLevel() !== -1) { + if (this._tour.get_currentTourStop().get_target().get_type() === 4) { + // TODO fix this when Planets are implemented + //tour.CurrentTourStop.Target.UpdatePlanetLocation(SpaceTimeController.UtcToJulian(tour.CurrentTourStop.StartTime)); + //tour.CurrentTourStop.EndTarget.UpdatePlanetLocation(SpaceTimeController.UtcToJulian(tour.CurrentTourStop.EndTime)); + } + renderContext.viewMover = new ViewMoverKenBurnsStyle(this._tour.get_currentTourStop().get_target().get_camParams(), this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_duration() / 1000, this._tour.get_currentTourStop().get_startTime(), this._tour.get_currentTourStop().get_endTime(), this._tour.get_currentTourStop().get_interpolationType()); + } + Settings.tourSettings = this._tour.get_currentTourStop(); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + globalScriptInterface._fireSlideChanged(caption); + } + } + if (renderContext.gl != null) { + renderContext.setupMatricesOverlays(); + if (this._currentMasterSlide != null) { + var $enum2 = ss.enumerate(this._currentMasterSlide.get_overlays()); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + overlay.set_tweenFactor(1); + overlay.draw3D(renderContext, false); + } + } + if (this._onTarget) { + var $enum3 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum3.moveNext()) { + var overlay = $enum3.current; + if (overlay.get_name().toLowerCase() !== 'caption' || globalScriptInterface.get_showCaptions()) { + overlay.set_tweenFactor(CameraParameters.easeCurve(this._tour.get_currentTourStop().get_tweenPosition(), (overlay.get_interpolationType() === 5) ? this._tour.get_currentTourStop().get_interpolationType() : overlay.get_interpolationType())); + overlay.draw3D(renderContext, false); + } + } + } + renderContext.restore(); + + // There used to be code to draw on-screen tour player controls here. + // In the web engine, that kind of work is now taken care of at higher levels. + //DrawPlayerControls(renderContext); + } else { + renderContext.device.scale(renderContext.height / 1116, renderContext.height / 1116); + var aspectOrig = 1920 / 1116; + var aspectNow = renderContext.width / renderContext.height; + renderContext.device.translate(-((1920 - (aspectNow * 1116)) / 2), 0); + if (this._currentMasterSlide != null) { + var $enum4 = ss.enumerate(this._currentMasterSlide.get_overlays()); + while ($enum4.moveNext()) { + var overlay = $enum4.current; + overlay.set_tweenFactor(1); + overlay.draw3D(renderContext, false); + } + } + if (this._onTarget) { + var $enum5 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum5.moveNext()) { + var overlay = $enum5.current; + if (overlay.get_name().toLowerCase() !== 'caption' || globalScriptInterface.get_showCaptions()) { + overlay.set_tweenFactor(CameraParameters.easeCurve(this._tour.get_currentTourStop().get_tweenPosition(), (overlay.get_interpolationType() === 5) ? this._tour.get_currentTourStop().get_interpolationType() : overlay.get_interpolationType())); + overlay.draw3D(renderContext, false); + } + } + } + else { + var i = 0; + } + renderContext.restore(); + } + }, + + get_tour: function () { + return this._tour; + }, + + set_tour: function (value) { + this._tour = value; + return value; + }, + + nextSlide: function () { + if (this._tour.get_currentTourStop() != null) { + if (!this._tour.get_currentTourStop().get_masterSlide()) { + if (this._tour.get_currentTourStop().get_musicTrack() != null) { + this._tour.get_currentTourStop().get_musicTrack().stop(); + } + if (this._tour.get_currentTourStop().get_voiceTrack() != null) { + this._tour.get_currentTourStop().get_voiceTrack().stop(); + } + var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.stop(); + } + } + else { + this._currentMasterSlide = this._tour.get_currentTourStop(); + } + } + if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1) || this._tour.get_currentTourStop().get_isLinked()) { + if (this._tour.get_currentTourStop().get_endTarget() != null) { + globalWWTControl.gotoTargetFull(false, true, this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_target().get_studyImageset(), this._tour.get_currentTourStop().get_target().get_backgroundImageset()); + globalWWTControl.set__mover(null); + } + this._onTarget = false; + if (this._tour.get_currentTourStop().get_isLinked()) { + try { + switch (this._tour.get_currentTourStop().get_nextSlide()) { + case 'Return': + if (this._callStack.count > 0) { + this.playFromTourstop(this._tour.get_tourStops()[this._callStack.pop()]); + } + else { + this._tour.set_currentTourstopIndex(this._tour.get_tourStops().length - 1); + } + break; + default: + this.playFromTourstop(this._tour.get_tourStops()[this._tour.getTourStopIndexByID(this._tour.get_currentTourStop().get_nextSlide())]); + break; + } + } + catch ($e2) { + if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { + this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; + } + } + } + else { + this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; + } + if (this._currentMasterSlide != null && this._tour.get_currentTourStop().get_masterSlide()) { + this._stopCurrentMaster(); + } + var instant = false; + switch (this._tour.get_currentTourStop().get__transition()) { + case 0: + break; + case 1: + instant = true; + break; + case 2: + instant = true; + break; + case 3: + instant = true; + break; + case 5: + instant = true; + break; + case 4: + instant = true; + break; + default: + break; + } + globalWWTControl.gotoTarget(this._tour.get_currentTourStop().get_target(), false, instant, false); + this._slideStartTime = ss.now(); + // Move to new settings + Settings.tourSettings = this._tour.get_currentTourStop(); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + } else { + this._stopCurrentMaster(); + TourPlayer._playing = false; + if (Settings.get_current().autoRepeatTour) { + this._tour.set_currentTourstopIndex(-1); + this.play(); + } + else { + globalWWTControl._freezeView(); + if (TourPlayer.__tourEnded != null) { + TourPlayer.__tourEnded(this, new ss.EventArgs()); + } + globalWWTControl._hideUI(false); + globalScriptInterface._fireTourEnded(); + } + } + }, + + _stopCurrentMaster: function () { + if (this._currentMasterSlide != null) { + if (this._currentMasterSlide.get_musicTrack() != null) { + this._currentMasterSlide.get_musicTrack().stop(); + } + if (this._currentMasterSlide.get_voiceTrack() != null) { + this._currentMasterSlide.get_voiceTrack().stop(); + } + var $enum1 = ss.enumerate(this._currentMasterSlide.get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.stop(); + } + this._currentMasterSlide = null; + } + }, + + get_leaveSettingsWhenStopped: function () { + return this._leaveSettingsWhenStopped; + }, + + set_leaveSettingsWhenStopped: function (value) { + this._leaveSettingsWhenStopped = value; + return value; + }, + + play: function () { + if (this._tour == null) { + return; + } + if (TourPlayer._playing) { + this.stop(true); + } else { + TourPlayer._playing = true; + } + globalWWTControl._hideUI(true); + TourPlayer._playing = true; + if (this._tour.get_tourStops().length > 0) { + this._onTarget = false; + if (this._tour.get_currentTourstopIndex() === -1) { + this._tour.set_currentTourStop(this._tour.get_tourStops()[0]); + } + + // Ensure that all multimedia elements are prepared. When + // playing back a tour in a browser, restrictions on autoplay + // mean that we have to ensure that all of our multimedia + // elements are prepared for playback inside code that is + // triggered by a user-initiated event. The PrepMultimedia + // callback should do whatever's needed to make sure that media + // files are all ready to go. + + var $enum1 = ss.enumerate(this._tour.get_tourStops()); + while ($enum1.moveNext()) { + var stop = $enum1.current; + if (stop.get_musicTrack() != null) { + stop.get_musicTrack().prepMultimedia(); + } + if (stop.get_voiceTrack() != null) { + stop.get_voiceTrack().prepMultimedia(); + } + var $enum2 = ss.enumerate(stop.get_overlays()); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + overlay.prepMultimedia(); + } + } + if (this._tour.get_currentTourstopIndex() > 0) { + this._playMasterForCurrent(); + } + globalWWTControl.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); + } + this._slideStartTime = ss.now(); + TourPlayer._playing = true; + }, + + _playMasterForCurrent: function () { + if (!this._tour.get_currentTourStop().get_masterSlide()) { + var currentMaster = this._tour.elapsedTimeSinceLastMaster(this._tour.get_currentTourstopIndex()); + if (currentMaster != null) { + var elapsed = currentMaster.duration; + this._currentMasterSlide = currentMaster.master; + if (this._currentMasterSlide.get_musicTrack() != null) { + this._currentMasterSlide.get_musicTrack().seek(elapsed); + this._currentMasterSlide.get_musicTrack().play(); + } + if (this._currentMasterSlide.get_voiceTrack() != null) { + this._currentMasterSlide.get_voiceTrack().seek(elapsed); + this._currentMasterSlide.get_voiceTrack().play(); + } + var $enum1 = ss.enumerate(this._currentMasterSlide.get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.seek(elapsed); + overlay.play(); + } + } + } + }, + + stop: function (noSwitchBackFullScreen) { + if (TourPlayer._switchedToFullScreen && !noSwitchBackFullScreen) { + } + + // By default, when you stop (or pause) a tour, the main WWT + // settings become active again. However, this can cause a jarring + // jump if, say, the tour has localHorizonMode active and the main + // settings don't. If you activate this option, we'll leave the tour + // settings lingering, preventing any dramatic changes. + if (!this._leaveSettingsWhenStopped) { + Settings.tourSettings = null; + } + TourPlayer._playing = false; + if (this._tour.get_currentTourStop() != null) { + if (this._tour.get_currentTourStop().get_musicTrack() != null) { + this._tour.get_currentTourStop().get_musicTrack().stop(); + } + if (this._tour.get_currentTourStop().get_voiceTrack() != null) { + this._tour.get_currentTourStop().get_voiceTrack().stop(); + } + var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.stop(); + } + } + if (this._currentMasterSlide != null) { + if (this._currentMasterSlide.get_musicTrack() != null) { + this._currentMasterSlide.get_musicTrack().stop(); + } + if (this._currentMasterSlide.get_voiceTrack() != null) { + this._currentMasterSlide.get_voiceTrack().stop(); + } + var $enum2 = ss.enumerate(this._currentMasterSlide.get_overlays()); + while ($enum2.moveNext()) { + var overlay = $enum2.current; + overlay.stop(); + } + } + globalWWTControl._hideUI(TourPlayer.noRestoreUIOnStop); + globalScriptInterface._fireTourEnded(); + }, + + updateSlideStates: function () { + var slideChanging = false; + var slideElapsedTime = ss.now() - this._slideStartTime; + if (slideElapsedTime > this._tour.get_currentTourStop().get_duration() && TourPlayer._playing) { + this.nextSlide(); + slideChanging = true; + } + slideElapsedTime = ss.now() - this._slideStartTime; + if (this._tour.get_currentTourStop() != null) { + this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, (slideElapsedTime / this._tour.get_currentTourStop().get_duration()))); + this._tour.get_currentTourStop().faderOpacity = 0; + var elapsedSeconds = this._tour.get_currentTourStop().get_tweenPosition() * this._tour.get_currentTourStop().get_duration() / 1000; + if (slideChanging) { + globalWWTControl.set_crossFadeFrame(false); + } + switch (this._tour.get_currentTourStop().get__transition()) { + case 0: + this._tour.get_currentTourStop().faderOpacity = 0; + globalWWTControl.set_crossFadeFrame(false); + break; + case 2: + if (slideChanging) { + } + if (elapsedSeconds < (elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime())) { + globalWWTControl.set_crossFadeFrame(true); + this._tour.get_currentTourStop().faderOpacity = 1; + } + else { + this._tour.get_currentTourStop().faderOpacity = 0; + globalWWTControl.set_crossFadeFrame(false); + } + break; + case 1: + globalWWTControl.set_crossFadeFrame(true); + var opacity = Math.max(0, 1 - Math.min(1, (elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime()) / this._tour.get_currentTourStop().get__transitionTime())); + this._tour.get_currentTourStop().faderOpacity = opacity; + if (slideChanging) { + } + break; + case 3: + case 4: + globalWWTControl.set_crossFadeFrame(false); + var opacity = Math.max(0, 1 - Math.max(0, elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime()) / this._tour.get_currentTourStop().get__transitionTime()); + this._tour.get_currentTourStop().faderOpacity = opacity; + break; + case 5: + globalWWTControl.set_crossFadeFrame(false); + break; + default: + break; + } + if (!this._tour.get_currentTourStop().get_isLinked() && this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { + var nextTrans = this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1].get__transition(); + var nextTransTime = this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1].get__transitionOutTime(); + switch (nextTrans) { + case 5: + case 3: + if (!this._tour.get_currentTourStop().faderOpacity) { + globalWWTControl.set_crossFadeFrame(false); + var opacity = Math.max(0, 1 - Math.min(1, ((this._tour.get_currentTourStop().get_duration() / 1000) - elapsedSeconds) / nextTransTime)); + this._tour.get_currentTourStop().faderOpacity = opacity; + } + break; + default: + break; + } + } + } + }, + + updateTweenPosition: function (tween) { + var slideElapsedTime = ss.now() - this._slideStartTime; + if (tween > -1) { + return this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, tween)); + } else { + return this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, (slideElapsedTime / this._tour.get_currentTourStop().get_duration()))); + } + }, + + close: function () { + if (this._tour != null) { + if (TourPlayer.get_playing()) { + this.stop(TourPlayer._switchedToFullScreen); + } + this._tour = null; + } + }, + + mouseDown: function (sender, e) { + var location; + location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { + if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location)) { + if (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_url())) { + var linkItem = this._tour.get_currentTourStop().get_overlays()[i]; + Util._openUrl(linkItem.get_url()); + return true; + } + if (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_linkID())) { + this._callStack.push(this._tour.get_currentTourstopIndex()); + this.playFromTourstop(this._tour.get_tourStops()[this._tour.getTourStopIndexByID(this._tour.get_currentTourStop().get_overlays()[i].get_linkID())]); + return true; + } + } + } + return false; + }, + + mouseUp: function (sender, e) { + return false; + }, + + mouseMove: function (sender, e) { + var location; + try { + location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); + } + catch ($e1) { + return false; + } + if (this._tour == null || this._tour.get_currentTourStop() == null) { + return false; + } + for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { + if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location) && (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_url()) || !ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_linkID()))) { + return true; + } + } + return false; + }, + + mouseClick: function (sender, e) { + return false; + }, + + click: function (sender, e) { + return false; + }, + + mouseDoubleClick: function (sender, e) { + return false; + }, + + keyDown: function (sender, e) { + switch (e.keyCode) { + case 27: // escape + this.stop(TourPlayer._switchedToFullScreen); + globalWWTControl._closeTour(); + return true; + case 32: // spacebar + this.pauseTour(); + return true; + case 39: // right arrow + this._playNextSlide(); + return true; + case 37: // left arrow + this._playPreviousSlide(); + return true; + case 35: // end key + if (this._tour.get_tourStops().length > 0) { + this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_tourStops().length - 1]); + } + return true; + case 36: // home key + if (this._tour.get_tourStops().length > 0) { + this.playFromTourstop(this._tour.get_tourStops()[0]); + } + return true; + } + return false; + }, + + _playNextSlide: function () { + if ((this._tour.get_currentTourstopIndex() < this._tour.get_tourStops().length - 1) && this._tour.get_tourStops().length > 0) { + this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1]); + } + }, + + _playPreviousSlide: function () { + if (this._tour.get_currentTourstopIndex() > 0) { + this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() - 1]); + } + }, + + playFromTourstop: function (tourStop) { + this.stop(true); + this._tour.set_currentTourStop(tourStop); + globalWWTControl.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); + SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); + SpaceTimeController.set_syncToClock(false); + this.play(); + }, + + pauseTour: function () { + if (TourPlayer._playing) { + this.stop(TourPlayer._switchedToFullScreen); + globalWWTControl._freezeView(); + globalScriptInterface._fireTourPaused(); + } else { + this.play(); + globalScriptInterface._fireTourResume(); + } + }, + + keyUp: function (sender, e) { + return false; + }, + + hover: function (pnt) { + if (TourPlayer._playing) { + return true; + } + return false; + }, + + pointToView: function (pnt) { + var clientHeight = globalWWTControl.canvas.height; + var clientWidth = globalWWTControl.canvas.width; + var viewWidth = (clientWidth / clientHeight) * 1116; + var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); + var y = (pnt.y) / clientHeight * 1116; + return Vector2d.create(x, y); + } +}; + +registerType("TourPlayer", [TourPlayer, TourPlayer$, null, IUiController]); + +// wwtlib.MasterTime + +export function MasterTime(master, duration) { + this.duration = 0; + this.master = master; + this.duration = duration; +} + +var MasterTime$ = {}; + +registerType("MasterTime", [MasterTime, MasterTime$, null]); diff --git a/engine/esm/tours/tour_stop.js b/engine/esm/tours/tour_stop.js new file mode 100644 index 00000000..6e562620 --- /dev/null +++ b/engine/esm/tours/tour_stop.js @@ -0,0 +1,1809 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A stop on a tour. + +import { ss } from "../ss.js"; +import { registerType, registerEnum, Enums } from "../typesystem.js"; +import { globalScriptInterface } from "../data_globals.js"; +import { XmlTextWriter } from "../utilities/xml_text_writer.js"; +import { Util } from "../baseutil.js"; +import { Color, Colors } from "../color.js"; +import { ConstellationFilter } from "../constellation_filter.js"; +import { ISettings, IUndoStep } from "../interfaces.js"; +import { Place } from "../place.js"; +import { Settings, SettingParameter } from "../settings.js"; +import { SpaceTimeController } from "../space_time_controller.js"; +import { Guid } from "../util.js"; +import { Overlay } from "./overlay.js"; + + +// wwtlib.TransitionType + +export var TransitionType = { + slew: 0, + crossFade: 1, + crossCut: 2, + fadeOutIn: 3, + fadeIn: 4, + fadeOut: 5 +}; + +registerType("TransitionType", TransitionType); +registerEnum("TransitionType", TransitionType); + + +// wwtlib.TourStop + +export function TourStop() { + this._tourStopType = 0; + this._keyFramed = false; + this._tweenPosition = 0; + this.faderOpacity = 0; + this._owner = null; + this._transition = 0; + this._transitionTime = 2; + this._transitionHoldTime = 4; + this._transitionOutTime = 2; + this._nextSlide = 'Next'; + this._fadeInOverlays = false; + this._masterSlide = false; + this._id = ''; + this._description = ''; + this._name = ''; + this._duration = 10000; + this._interpolationType = 0; + this._hasLocation = true; + this._hasTime = true; + this._startTime = SpaceTimeController.get_now(); + this._endTime = SpaceTimeController.get_now(); + this._actualPlanetScale = Settings.get_current().get_actualPlanetScale(); + this._locationAltitude = Settings.get_current().get_locationAltitude(); + this._locationLat = Settings.get_current().get_locationLat(); + this._locationLng = Settings.get_current().get_locationLng(); + this._showClouds = Settings.get_current().get_showClouds(); + this._showConstellationBoundries = Settings.get_current().get_showConstellationBoundries(); + this._showConstellationFigures = Settings.get_current().get_showConstellationFigures(); + this._showConstellationSelection = Settings.get_current().get_showConstellationSelection(); + this._showEcliptic = Settings.get_current().get_showEcliptic(); + this._showElevationModel = Settings.get_current().get_showElevationModel(); + this._showFieldOfView = Settings.get_current().get_showFieldOfView(); + this._showGrid = Settings.get_current().get_showGrid(); + this._showHorizon = Settings.get_current().get_showHorizon(); + this._showHorizonPanorama = Settings.get_current().get_showHorizonPanorama(); + this._showMoonsAsPointSource = Settings.get_current().get_showMoonsAsPointSource(); + this._showSolarSystem = Settings.get_current().get_showSolarSystem(); + this._fovTelescope = Settings.get_current().get_fovTelescope(); + this._fovEyepiece = Settings.get_current().get_fovEyepiece(); + this._fovCamera = Settings.get_current().get_fovCamera(); + this._localHorizonMode = Settings.get_current().get_localHorizonMode(); + this._galacticMode = Settings.get_current().get_galacticMode(); + this._solarSystemStars = Settings.get_current().get_solarSystemStars(); + this._solarSystemMilkyWay = Settings.get_current().get_solarSystemMilkyWay(); + this._solarSystemCosmos = Settings.get_current().get_solarSystemCosmos(); + this._solarSystemOrbits = Settings.get_current().get_solarSystemOrbits(); + this._solarSystemOverlays = Settings.get_current().get_solarSystemOverlays(); + this._solarSystemLighting = Settings.get_current().get_solarSystemLighting(); + this._solarSystemScale = Settings.get_current().get_solarSystemScale(); + this._solarSystemMultiRes = Settings.get_current().get_solarSystemMultiRes(); + this._showEquatorialGridText = Settings.get_current().get_showEquatorialGridText(); + this._showGalacticGrid = Settings.get_current().get_showGalacticGrid(); + this._showGalacticGridText = Settings.get_current().get_showGalacticGridText(); + this._showEclipticGrid = Settings.get_current().get_showEclipticGrid(); + this._showEclipticGridText = Settings.get_current().get_showEclipticGridText(); + this._showEclipticOverviewText = Settings.get_current().get_showEclipticOverviewText(); + this._showAltAzGrid = Settings.get_current().get_showAltAzGrid(); + this._showAltAzGridText = Settings.get_current().get_showAltAzGridText(); + this._showPrecessionChart = Settings.get_current().get_showPrecessionChart(); + this._showConstellationPictures = Settings.get_current().get_showConstellationPictures(); + this._showConstellationLabels = Settings.get_current().get_showConstellationLabels(); + this._solarSystemCMB = Settings.get_current().get_solarSystemCMB(); + this._solarSystemMinorPlanets = Settings.get_current().get_solarSystemMinorPlanets(); + this._solarSystemPlanets = Settings.get_current().get_solarSystemPlanets(); + this._showEarthSky = Settings.get_current().get_showEarthSky(); + this._solarSystemMinorOrbits = Settings.get_current().get_solarSystemMinorOrbits(); + this._constellationsEnabled = ''; + this._constellationFiguresFilter = Settings.get_current().get_constellationFiguresFilter().clone(); + this._constellationBoundariesFilter = Settings.get_current().get_constellationBoundariesFilter().clone(); + this._constellationNamesFilter = Settings.get_current().get_constellationNamesFilter().clone(); + this._constellationArtFilter = Settings.get_current().get_constellationArtFilter().clone(); + this._showSkyOverlays = Settings.get_current().get_showSkyOverlays(); + this._showConstellations = Settings.get_current().get_showConstellations(); + this._showSkyNode = Settings.get_current().get_showSkyNode(); + this._showSkyGrids = Settings.get_current().get_showSkyGrids(); + this._showSkyOverlaysIn3d = Settings.get_current().get_showSkyOverlaysIn3d(); + this._earthCutawayView = Settings.get_current().get_earthCutawayView(); + this._showISSModel = Settings.get_current().get_showISSModel(); + this._milkyWayModel = Settings.get_current().get_milkyWayModel(); + this._minorPlanetsFilter = Settings.get_current().get_minorPlanetsFilter(); + this._planetOrbitsFilter = Settings.get_current().get_planetOrbitsFilter(); + this._thumbnailString = ''; + this._thumbnail = null; + this.layers = {}; + this._overlays = []; + this._musicTrack = null; + this._voiceTrack = null; + this._eclipticGridColor = Colors.get_green(); + this._galacticGridColor = Colors.get_cyan(); + this._altAzGridColor = Colors.get_magenta(); + this._precessionChartColor = Colors.get_orange(); + this._eclipticColor = Colors.get_blue(); + this._equatorialGridColor = Colors.get_white(); + this._constellationLabelsHeight = 80; + this._id = Guid.newGuid().toString(); +} + +TourStop.clipboardFormat = 'WorldWideTelescope.Slide'; + +TourStop.create = function (target) { + var ts = new TourStop(); + ts._target = target; + return ts; +}; + +TourStop.getXmlText = function (ts) { + var writer = new XmlTextWriter(); + writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + ts._saveToXml(writer, true); + writer._close(); + return writer.body; +}; + +TourStop._fromXml = function (owner, tourStop) { + try { + var newTourStop = new TourStop(); + newTourStop._owner = owner; + newTourStop.set_id(tourStop.attributes.getNamedItem('Id').nodeValue); + newTourStop.set_name(tourStop.attributes.getNamedItem('Name').nodeValue); + newTourStop.set_description(tourStop.attributes.getNamedItem('Description').nodeValue); + newTourStop._thumbnailString = tourStop.attributes.getNamedItem('Thumbnail').nodeValue; + newTourStop._duration = Util.parseTimeSpan(tourStop.attributes.getNamedItem('Duration').nodeValue); + if (tourStop.attributes.getNamedItem('Master') != null) { + newTourStop._masterSlide = ss.boolean(tourStop.attributes.getNamedItem('Master').nodeValue); + } + if (tourStop.attributes.getNamedItem('NextSlide') != null) { + newTourStop._nextSlide = tourStop.attributes.getNamedItem('NextSlide').nodeValue; + } + if (tourStop.attributes.getNamedItem('InterpolationType') != null) { + newTourStop.set_interpolationType(Enums.parse('InterpolationType', tourStop.attributes.getNamedItem('InterpolationType').nodeValue)); + } + newTourStop._fadeInOverlays = true; + if (tourStop.attributes.getNamedItem('FadeInOverlays') != null) { + newTourStop._fadeInOverlays = ss.boolean(tourStop.attributes.getNamedItem('FadeInOverlays').nodeValue); + } + if (tourStop.attributes.getNamedItem('Transition') != null) { + newTourStop._transition = Enums.parse('TransitionType', tourStop.attributes.getNamedItem('Transition').nodeValue); + } + if (tourStop.attributes.getNamedItem('HasLocation') != null) { + newTourStop._hasLocation = ss.boolean(tourStop.attributes.getNamedItem('HasLocation').nodeValue); + } + if (newTourStop._hasLocation) { + if (tourStop.attributes.getNamedItem('LocationAltitude') != null) { + newTourStop._locationAltitude = parseFloat(tourStop.attributes.getNamedItem('LocationAltitude').nodeValue); + } + if (tourStop.attributes.getNamedItem('LocationLat') != null) { + newTourStop._locationLat = parseFloat(tourStop.attributes.getNamedItem('LocationLat').nodeValue); + } + if (tourStop.attributes.getNamedItem('LocationLng') != null) { + newTourStop._locationLng = parseFloat(tourStop.attributes.getNamedItem('LocationLng').nodeValue); + } + } + if (tourStop.attributes.getNamedItem('HasTime') != null) { + newTourStop._hasTime = ss.boolean(tourStop.attributes.getNamedItem('HasTime').nodeValue); + if (newTourStop._hasTime) { + if (tourStop.attributes.getNamedItem('StartTime') != null) { + newTourStop._startTime = ss.date(tourStop.attributes.getNamedItem('StartTime').nodeValue + ' UTC'); + } + if (tourStop.attributes.getNamedItem('EndTime') != null) { + newTourStop._endTime = ss.date(tourStop.attributes.getNamedItem('EndTime').nodeValue + ' UTC'); + } + } + } + if (tourStop.attributes.getNamedItem('ActualPlanetScale') != null) { + newTourStop._actualPlanetScale = ss.boolean(tourStop.attributes.getNamedItem('ActualPlanetScale').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowClouds') != null) { + newTourStop._showClouds = ss.boolean(tourStop.attributes.getNamedItem('ShowClouds').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowConstellationBoundries') != null) { + newTourStop._showConstellationBoundries = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationBoundries').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowConstellationFigures') != null) { + newTourStop._showConstellationFigures = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationFigures').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowConstellationSelection') != null) { + newTourStop._showConstellationSelection = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationSelection').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEcliptic') != null) { + newTourStop._showEcliptic = ss.boolean(tourStop.attributes.getNamedItem('ShowEcliptic').nodeValue); + } + if (tourStop.attributes.getNamedItem('EclipticColor') != null) { + newTourStop._eclipticColor = Color.load(tourStop.attributes.getNamedItem('EclipticColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowElevationModel') != null) { + newTourStop._showElevationModel = ss.boolean(tourStop.attributes.getNamedItem('ShowElevationModel').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowFieldOfView') != null) { + newTourStop._showFieldOfView = ss.boolean(tourStop.attributes.getNamedItem('ShowFieldOfView').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowGrid') != null) { + newTourStop._showGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowGrid').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowHorizon') != null) { + newTourStop._showHorizon = ss.boolean(tourStop.attributes.getNamedItem('ShowHorizon').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowHorizonPanorama') != null) { + newTourStop._showHorizonPanorama = ss.boolean(tourStop.attributes.getNamedItem('ShowHorizonPanorama').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowMoonsAsPointSource') != null) { + newTourStop._showMoonsAsPointSource = ss.boolean(tourStop.attributes.getNamedItem('ShowMoonsAsPointSource').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowSolarSystem') != null) { + newTourStop._showSolarSystem = ss.boolean(tourStop.attributes.getNamedItem('ShowSolarSystem').nodeValue); + } + if (tourStop.attributes.getNamedItem('FovTelescope') != null) { + newTourStop._fovTelescope = parseInt(tourStop.attributes.getNamedItem('FovTelescope').nodeValue); + } + if (tourStop.attributes.getNamedItem('FovEyepiece') != null) { + newTourStop._fovEyepiece = parseInt(tourStop.attributes.getNamedItem('FovEyepiece').nodeValue); + } + if (tourStop.attributes.getNamedItem('FovCamera') != null) { + newTourStop._fovCamera = parseInt(tourStop.attributes.getNamedItem('FovCamera').nodeValue); + } + if (tourStop.attributes.getNamedItem('LocalHorizonMode') != null) { + newTourStop._localHorizonMode = ss.boolean(tourStop.attributes.getNamedItem('LocalHorizonMode').nodeValue); + } + if (tourStop.attributes.getNamedItem('GalacticMode') != null) { + newTourStop._galacticMode = ss.boolean(tourStop.attributes.getNamedItem('GalacticMode').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemStars') != null) { + newTourStop._solarSystemStars = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemStars').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemMilkyWay') != null) { + newTourStop._solarSystemMilkyWay = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMilkyWay').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemCosmos') != null) { + newTourStop._solarSystemCosmos = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemCosmos').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemOrbits') != null) { + newTourStop._solarSystemOrbits = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemOrbits').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemOverlays') != null) { + newTourStop._solarSystemOverlays = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemOverlays').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemLighting') != null) { + newTourStop._solarSystemLighting = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemLighting').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemScale') != null) { + newTourStop._solarSystemScale = parseInt(tourStop.attributes.getNamedItem('SolarSystemScale').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemMultiRes') != null) { + newTourStop._solarSystemMultiRes = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMultiRes').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEquatorialGridText') != null) { + newTourStop._showEquatorialGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowEquatorialGridText').nodeValue); + } + if (tourStop.attributes.getNamedItem('EquatorialGridColor') != null) { + newTourStop._equatorialGridColor = Color.load(tourStop.attributes.getNamedItem('EquatorialGridColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowGalacticGrid') != null) { + newTourStop._showGalacticGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowGalacticGrid').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowGalacticGridText') != null) { + newTourStop._showGalacticGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowGalacticGridText').nodeValue); + } + if (tourStop.attributes.getNamedItem('GalacticGridColor') != null) { + newTourStop._galacticGridColor = Color.load(tourStop.attributes.getNamedItem('GalacticGridColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEclipticGrid') != null) { + newTourStop._showEclipticGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticGrid').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEclipticGridText') != null) { + newTourStop._showEclipticGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticGridText').nodeValue); + } + if (tourStop.attributes.getNamedItem('EclipticGridColor') != null) { + newTourStop._eclipticGridColor = Color.load(tourStop.attributes.getNamedItem('EclipticGridColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEclipticOverviewText') != null) { + newTourStop._showEclipticOverviewText = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticOverviewText').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowAltAzGrid') != null) { + newTourStop._showAltAzGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowAltAzGrid').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowAltAzGridText') != null) { + newTourStop._showAltAzGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowAltAzGridText').nodeValue); + } + if (tourStop.attributes.getNamedItem('AltAzGridColor') != null) { + newTourStop._altAzGridColor = Color.load(tourStop.attributes.getNamedItem('AltAzGridColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowPrecessionChart') != null) { + newTourStop._showPrecessionChart = ss.boolean(tourStop.attributes.getNamedItem('ShowPrecessionChart').nodeValue); + } + if (tourStop.attributes.getNamedItem('PrecessionChartColor') != null) { + newTourStop._precessionChartColor = Color.load(tourStop.attributes.getNamedItem('PrecessionChartColor').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowConstellationPictures') != null) { + newTourStop._showConstellationPictures = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationPictures').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowConstellationLabels') != null) { + newTourStop._showConstellationLabels = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationLabels').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemCMB') != null) { + newTourStop._solarSystemCMB = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemCMB').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemMinorPlanets') != null) { + newTourStop._solarSystemMinorPlanets = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMinorPlanets').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemPlanets') != null) { + newTourStop._solarSystemPlanets = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemPlanets').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowEarthSky') != null) { + newTourStop._showEarthSky = ss.boolean(tourStop.attributes.getNamedItem('ShowEarthSky').nodeValue); + } + if (tourStop.attributes.getNamedItem('SolarSystemMinorOrbits') != null) { + newTourStop._solarSystemMinorOrbits = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMinorOrbits').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowSkyOverlays') != null) { + newTourStop._showSkyOverlays = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyOverlays').nodeValue); + } else { + newTourStop._showSkyOverlays = true; + } + if (tourStop.attributes.getNamedItem('ShowConstellations') != null) { + newTourStop._showConstellations = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellations').nodeValue); + } else { + newTourStop._showConstellations = true; + } + if (tourStop.attributes.getNamedItem('ShowSkyNode') != null) { + newTourStop._showSkyNode = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyNode').nodeValue); + } else { + newTourStop._showSkyNode = true; + } + if (tourStop.attributes.getNamedItem('ShowSkyGrids') != null) { + newTourStop._showSkyGrids = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyGrids').nodeValue); + } else { + newTourStop._showSkyGrids = true; + } + if (tourStop.attributes.getNamedItem('ShowSkyOverlaysIn3d') != null) { + newTourStop._showSkyOverlaysIn3d = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyOverlaysIn3d').nodeValue); + } + if (tourStop.attributes.getNamedItem('EarthCutawayView') != null) { + newTourStop._earthCutawayView = ss.boolean(tourStop.attributes.getNamedItem('EarthCutawayView').nodeValue); + } + if (tourStop.attributes.getNamedItem('ShowISSModel') != null) { + newTourStop._showISSModel = ss.boolean(tourStop.attributes.getNamedItem('ShowISSModel').nodeValue); + } + if (tourStop.attributes.getNamedItem('MilkyWayModel') != null) { + newTourStop._milkyWayModel = ss.boolean(tourStop.attributes.getNamedItem('MilkyWayModel').nodeValue); + } + if (tourStop.attributes.getNamedItem('ConstellationBoundariesFilter') != null) { + newTourStop._constellationBoundariesFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationBoundariesFilter').nodeValue); + } else { + newTourStop._constellationBoundariesFilter = ConstellationFilter.get_allConstellation(); + } + if (tourStop.attributes.getNamedItem('ConstellationBoundariesFilter') != null) { + newTourStop._constellationFiguresFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationBoundariesFilter').nodeValue); + } else { + newTourStop._constellationFiguresFilter = new ConstellationFilter(); + } + if (tourStop.attributes.getNamedItem('ConstellationNamesFilter') != null) { + newTourStop._constellationNamesFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationNamesFilter').nodeValue); + } else { + newTourStop._constellationNamesFilter = new ConstellationFilter(); + } + if (tourStop.attributes.getNamedItem('ConstellationArtFilter') != null) { + newTourStop._constellationArtFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationArtFilter').nodeValue); + } else { + newTourStop._constellationArtFilter = new ConstellationFilter(); + } + if (tourStop.attributes.getNamedItem('MinorPlanetsFilter') != null) { + newTourStop._minorPlanetsFilter = parseInt(tourStop.attributes.getNamedItem('MinorPlanetsFilter').nodeValue); + } + if (tourStop.attributes.getNamedItem('PlanetOrbitsFilter') != null) { + newTourStop._planetOrbitsFilter = parseInt(tourStop.attributes.getNamedItem('PlanetOrbitsFilter').nodeValue); + } + var place = Util.selectSingleNode(tourStop, 'Place'); + newTourStop._target = Place._fromXml(place); + var endTarget = Util.selectSingleNode(tourStop, 'EndTarget'); + if (endTarget != null) { + newTourStop._endTarget = Place._fromXml(endTarget); + } + var overlays = Util.selectSingleNode(tourStop, 'Overlays'); + var $enum1 = ss.enumerate(overlays.childNodes); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (overlay.nodeName === 'Overlay') { + newTourStop.addOverlay(Overlay._fromXml(newTourStop, overlay)); + } + } + var musicNode = Util.selectSingleNode(tourStop, 'MusicTrack'); + if (musicNode != null) { + newTourStop._musicTrack = Overlay._fromXml(newTourStop, Util.selectSingleNode(musicNode, 'Overlay')); + } + var voiceNode = Util.selectSingleNode(tourStop, 'VoiceTrack'); + if (voiceNode != null) { + newTourStop._voiceTrack = Overlay._fromXml(newTourStop, Util.selectSingleNode(voiceNode, 'Overlay')); + } + var layerNode = Util.selectSingleNode(tourStop, 'VisibleLayers'); + if (layerNode != null) { + newTourStop._loadLayerList(layerNode); + } + newTourStop._thumbnail = owner.getCachedTexture(ss.format('{0}.thumb.png', newTourStop._id), function () { + var c = 0; + }); + return newTourStop; + } + catch (ex) { + globalScriptInterface._fireTourError(ex); + return null; + } +}; + +var TourStop$ = { + get_keyFramed: function () { + return this._keyFramed; + }, + + get_tourStopType: function () { + if (this._target.get_backgroundImageset() != null) { + return this._target.get_backgroundImageset().get_dataSetType(); + } else { + return this._tourStopType; + } + }, + + set_tourStopType: function (value) { + if (this._target.get_backgroundImageset() != null) { + if (this._target.get_backgroundImageset().get_dataSetType() !== value) { + this._target.set_backgroundImageset(null); + } + } + this._tourStopType = value; + return value; + }, + + get_tweenPosition: function () { + return this._tweenPosition; + }, + + set_tweenPosition: function (value) { + if (this._tweenPosition !== value) { + this._tweenPosition = Math.max(0, Math.min(1, value)); + this.updateTweenPosition(); + } + return value; + }, + + updateTweenPosition: function () { + if (this.get_keyFramed()) { + } + }, + + copy: function () { + var writer = new XmlTextWriter(); + writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); + this._saveToXml(writer, true); + try { + var xParser = new DOMParser(); + var doc = xParser.parseFromString(writer.body, 'text/xml'); + var node = Util.selectSingleNode(doc, 'TourStop'); + var ts = TourStop._fromXml(this.get_owner(), node); + ts.set_id(Guid.newGuid().toString()); + return ts; + } + catch ($e1) { + } + return null; + }, + + get_owner: function () { + return this._owner; + }, + + set_owner: function (value) { + this._owner = value; + return value; + }, + + get__transition: function () { + return this._transition; + }, + + set__transition: function (value) { + if (this._transition !== value) { + this._transition = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get__transitionTime: function () { + return this._transitionTime; + }, + + set__transitionTime: function (value) { + if (this._transitionTime !== value) { + this._transitionTime = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get__transitionHoldTime: function () { + return this._transitionHoldTime; + }, + + set__transitionHoldTime: function (value) { + if (this._transitionHoldTime !== value) { + this._transitionHoldTime = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get__transitionOutTime: function () { + return this._transitionOutTime; + }, + + set__transitionOutTime: function (value) { + if (this._transitionOutTime !== value) { + this._transitionOutTime = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_nextSlide: function () { + return this._nextSlide; + }, + + set_nextSlide: function (value) { + this._nextSlide = value; + return value; + }, + + get_isLinked: function () { + if (this._nextSlide == null || this._nextSlide === 'Next' || !this._nextSlide) { + return false; + } + return true; + }, + + get_fadeInOverlays: function () { + return this._fadeInOverlays; + }, + + set_fadeInOverlays: function (value) { + this._fadeInOverlays = value; + return value; + }, + + get_masterSlide: function () { + return this._masterSlide; + }, + + set_masterSlide: function (value) { + if (this._masterSlide !== value) { + this._masterSlide = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_id: function () { + return this._id; + }, + + set_id: function (value) { + this._id = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + return value; + }, + + toString: function () { + if (this._target != null) { + return this.get_target().get_name(); + } else { + return this._description; + } + }, + + get_description: function () { + return this._description; + }, + + set_description: function (value) { + if (this._description !== value) { + this._description = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_name: function () { + if (this._target != null) { + return this._target.get_name(); + } + return this._name; + }, + + set_name: function (value) { + if (this._name !== value) { + this._name = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_duration: function () { + return this._duration; + }, + + set_duration: function (value) { + if (this._duration !== value) { + this._duration = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_target: function () { + return this._target; + }, + + set_target: function (value) { + if (this._target !== value) { + this._target = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_endTarget: function () { + return this._endTarget; + }, + + set_endTarget: function (value) { + if (this._endTarget !== value) { + this._endTarget = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_interpolationType: function () { + return this._interpolationType; + }, + + set_interpolationType: function (value) { + this._interpolationType = value; + return value; + }, + + get_hasLocation: function () { + return this._hasTime; + }, + + set_hasLocation: function (value) { + if (this._hasLocation !== value) { + this._hasLocation = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_hasTime: function () { + return this._hasTime; + }, + + set_hasTime: function (value) { + if (this._hasTime !== value) { + this._hasTime = this._hasLocation = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_startTime: function () { + return this._startTime; + }, + + set_startTime: function (value) { + this._startTime = value; + if (!ss.compareDates(this._startTime, value)) { + this._startTime = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_endTime: function () { + return this._endTime; + }, + + set_endTime: function (value) { + if (!ss.compareDates(this._endTime, value)) { + this._endTime = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + captureSettings: function () { + this._startTime = SpaceTimeController.get_now(); + this._actualPlanetScale = Settings.get_current().get_actualPlanetScale(); + this._locationAltitude = Settings.get_current().get_locationAltitude(); + this._locationLat = Settings.get_current().get_locationLat(); + this._locationLng = Settings.get_current().get_locationLng(); + this._showClouds = Settings.get_current().get_showClouds(); + this._showConstellationBoundries = Settings.get_current().get_showConstellationBoundries(); + this._showConstellationFigures = Settings.get_current().get_showConstellationFigures(); + this._showConstellationSelection = Settings.get_current().get_showConstellationSelection(); + this._showEcliptic = Settings.get_current().get_showEcliptic(); + this._showElevationModel = Settings.get_current().get_showElevationModel(); + this._showFieldOfView = Settings.get_current().get_showFieldOfView(); + this._showGrid = Settings.get_current().get_showGrid(); + this._showHorizon = Settings.get_current().get_showHorizon(); + this._showHorizonPanorama = Settings.get_current().get_showHorizonPanorama(); + this._showMoonsAsPointSource = Settings.get_current().get_showMoonsAsPointSource(); + this._showSolarSystem = Settings.get_current().get_showSolarSystem(); + this._fovTelescope = Settings.get_current().get_fovTelescope(); + this._fovEyepiece = Settings.get_current().get_fovEyepiece(); + this._fovCamera = Settings.get_current().get_fovCamera(); + this._localHorizonMode = Settings.get_current().get_localHorizonMode(); + this._galacticMode = Settings.get_current().get_galacticMode(); + this._solarSystemStars = Settings.get_current().get_solarSystemStars(); + this._solarSystemMilkyWay = Settings.get_current().get_solarSystemMilkyWay(); + this._solarSystemCosmos = Settings.get_current().get_solarSystemCosmos(); + this._solarSystemOrbits = Settings.get_current().get_solarSystemOrbits(); + this._solarSystemOverlays = Settings.get_current().get_solarSystemOverlays(); + this._solarSystemLighting = Settings.get_current().get_solarSystemLighting(); + this._solarSystemScale = Settings.get_current().get_solarSystemScale(); + this._solarSystemMultiRes = Settings.get_current().get_solarSystemMultiRes(); + this._showEquatorialGridText = Settings.get_current().get_showEquatorialGridText(); + this._showGalacticGrid = Settings.get_current().get_showGalacticGrid(); + this._showGalacticGridText = Settings.get_current().get_showGalacticGridText(); + this._showEclipticGrid = Settings.get_current().get_showEclipticGrid(); + this._showEclipticGridText = Settings.get_current().get_showEclipticGridText(); + this._showEclipticOverviewText = Settings.get_current().get_showEclipticOverviewText(); + this._showAltAzGrid = Settings.get_current().get_showAltAzGrid(); + this._showAltAzGridText = Settings.get_current().get_showAltAzGridText(); + this._showPrecessionChart = Settings.get_current().get_showPrecessionChart(); + this._showConstellationPictures = Settings.get_current().get_showConstellationPictures(); + this._showConstellationLabels = Settings.get_current().get_showConstellationLabels(); + this._solarSystemCMB = Settings.get_current().get_solarSystemCMB(); + this._solarSystemMinorPlanets = Settings.get_current().get_solarSystemMinorPlanets(); + this._solarSystemPlanets = Settings.get_current().get_solarSystemPlanets(); + this._showEarthSky = Settings.get_current().get_showEarthSky(); + this._solarSystemMinorOrbits = Settings.get_current().get_solarSystemMinorOrbits(); + this._constellationFiguresFilter = Settings.get_current().get_constellationFiguresFilter().clone(); + this._constellationBoundariesFilter = Settings.get_current().get_constellationBoundariesFilter().clone(); + this._constellationNamesFilter = Settings.get_current().get_constellationNamesFilter().clone(); + this._constellationArtFilter = Settings.get_current().get_constellationArtFilter().clone(); + this._showSkyOverlays = Settings.get_current().get_showSkyOverlays(); + this._showConstellations = Settings.get_current().get_showConstellations(); + this._showSkyNode = Settings.get_current().get_showSkyNode(); + this._showSkyGrids = Settings.get_current().get_showSkyGrids(); + this._showSkyOverlaysIn3d = Settings.get_current().get_showSkyOverlaysIn3d(); + this._earthCutawayView = Settings.get_current().get_earthCutawayView(); + this._showISSModel = Settings.get_current().get_showISSModel(); + this._milkyWayModel = Settings.get_current().get_milkyWayModel(); + this._minorPlanetsFilter = Settings.get_current().get_minorPlanetsFilter(); + this._planetOrbitsFilter = Settings.get_current().get_planetOrbitsFilter(); + }, + + syncSettings: function () { + Settings.get_globalSettings().set_actualPlanetScale(this._actualPlanetScale); + Settings.get_globalSettings().set_locationAltitude(this._locationAltitude); + Settings.get_globalSettings().set_locationLat(this._locationLat); + Settings.get_globalSettings().set_locationLng(this._locationLng); + Settings.get_globalSettings().set_earthCutawayView(this._earthCutawayView); + Settings.get_globalSettings().set_showConstellationBoundries(this._showConstellationBoundries); + Settings.get_globalSettings().set_showConstellationFigures(this._showConstellationFigures); + Settings.get_globalSettings().set_showConstellationSelection(this._showConstellationSelection); + Settings.get_globalSettings().set_showEcliptic(this._showEcliptic); + Settings.get_globalSettings().set_showElevationModel(this._showElevationModel); + Settings.get_globalSettings().set_showGrid(this._showGrid); + Settings.get_globalSettings().set_showHorizon(this._showHorizon); + Settings.get_globalSettings().set_showSolarSystem(this._showSolarSystem); + Settings.get_globalSettings().set_localHorizonMode(this._localHorizonMode); + Settings.get_globalSettings().set_galacticMode(this._galacticMode); + Settings.get_globalSettings().set_solarSystemStars(this._solarSystemStars); + Settings.get_globalSettings().set_solarSystemMilkyWay(this._solarSystemMilkyWay); + Settings.get_globalSettings().set_solarSystemCosmos(this._solarSystemCosmos); + Settings.get_globalSettings().set_solarSystemCMB(this._solarSystemCMB); + Settings.get_globalSettings().set_solarSystemOrbits(this._solarSystemOrbits); + Settings.get_globalSettings().set_solarSystemMinorOrbits(this._solarSystemMinorOrbits); + Settings.get_globalSettings().set_solarSystemMinorPlanets(this._solarSystemMinorPlanets); + Settings.get_globalSettings().set_solarSystemOverlays(this._solarSystemOverlays); + Settings.get_globalSettings().set_solarSystemLighting(this._solarSystemLighting); + Settings.get_globalSettings().set_showISSModel(this._showISSModel); + Settings.get_globalSettings().set_solarSystemScale(this._solarSystemScale); + Settings.get_globalSettings().set_solarSystemMultiRes(this._solarSystemMultiRes); + Settings.get_globalSettings().set_showEarthSky(this._showEarthSky); + Settings.get_globalSettings().set_minorPlanetsFilter(this._minorPlanetsFilter); + Settings.get_globalSettings().set_planetOrbitsFilter(this._planetOrbitsFilter); + Settings.get_globalSettings().set_showEquatorialGridText(this._showEquatorialGridText); + Settings.get_globalSettings().set_showGalacticGrid(this._showGalacticGrid); + Settings.get_globalSettings().set_showGalacticGridText(this._showGalacticGridText); + Settings.get_globalSettings().set_showEclipticGrid(this._showEclipticGrid); + Settings.get_globalSettings().set_showEclipticGridText(this._showEclipticGridText); + Settings.get_globalSettings().set_showEclipticOverviewText(this._showEclipticOverviewText); + Settings.get_globalSettings().set_showAltAzGrid(this._showAltAzGrid); + Settings.get_globalSettings().set_showAltAzGridText(this._showAltAzGridText); + Settings.get_globalSettings().set_showPrecessionChart(this._showPrecessionChart); + Settings.get_globalSettings().set_showConstellationPictures(this._showConstellationPictures); + Settings.get_globalSettings().set_constellationsEnabled(this._constellationsEnabled); + Settings.get_globalSettings().set_showSkyOverlays(this._showSkyOverlays); + Settings.get_globalSettings().set_constellations(this._showConstellations); + Settings.get_globalSettings().set_showSkyNode(this._showSkyNode); + Settings.get_globalSettings().set_showSkyGrids(this._showSkyGrids); + Settings.get_globalSettings().set_constellationFiguresFilter(this._constellationFiguresFilter.clone()); + Settings.get_globalSettings().set_constellationBoundariesFilter(this._constellationBoundariesFilter.clone()); + Settings.get_globalSettings().set_constellationNamesFilter(this._constellationNamesFilter.clone()); + Settings.get_globalSettings().set_constellationArtFilter(this._constellationArtFilter.clone()); + }, + + get_solarSystemStars: function () { + return this._solarSystemStars; + }, + + get_solarSystemMultiRes: function () { + return this._solarSystemMultiRes; + }, + + get_solarSystemMilkyWay: function () { + return this._solarSystemMilkyWay; + }, + + get_solarSystemCosmos: function () { + return this._solarSystemCosmos; + }, + + get_solarSystemOrbits: function () { + return this._solarSystemOrbits; + }, + + get_solarSystemOverlays: function () { + return this._solarSystemOverlays; + }, + + get_solarSystemLighting: function () { + return this._solarSystemLighting; + }, + + get_solarSystemScale: function () { + return this._solarSystemScale; + }, + + get_actualPlanetScale: function () { + return this._actualPlanetScale; + }, + + get_fovCamera: function () { + return this._fovCamera; + }, + + get_fovEyepiece: function () { + return this._fovEyepiece; + }, + + get_fovTelescope: function () { + return this._fovTelescope; + }, + + get_locationAltitude: function () { + if (this._hasLocation) { + return this._locationAltitude; + } else { + return Settings.get_current().get_locationAltitude(); + } + }, + + get_locationLat: function () { + if (this._hasLocation) { + return this._locationLat; + } else { + return Settings.get_current().get_locationLat(); + } + }, + + get_locationLng: function () { + if (this._hasLocation) { + return this._locationLng; + } else { + return Settings.get_current().get_locationLng(); + } + }, + + get_showClouds: function () { + return this._showClouds; + }, + + get_showConstellationBoundries: function () { + return this._showConstellationBoundries; + }, + + get_showConstellationFigures: function () { + return this._showConstellationFigures; + }, + + get_showConstellationSelection: function () { + return this._showConstellationSelection; + }, + + get_showEcliptic: function () { + return this._showEcliptic; + }, + + get_showElevationModel: function () { + return this._showElevationModel; + }, + + get_showFieldOfView: function () { + return this._showFieldOfView; + }, + + get_showGrid: function () { + return this._showGrid; + }, + + get_showHorizon: function () { + return this._showHorizon; + }, + + get_showHorizonPanorama: function () { + return this._showHorizonPanorama; + }, + + get_showMoonsAsPointSource: function () { + return this._showMoonsAsPointSource; + }, + + get_showSolarSystem: function () { + return this._showSolarSystem; + }, + + get_localHorizonMode: function () { + return this._localHorizonMode; + }, + + get_galacticMode: function () { + return this._galacticMode; + }, + + get_thumbnail: function () { + if (this._target != null && this._thumbnail == null) { + return null; + } + return this._thumbnail; + }, + + set_thumbnail: function (value) { + this._thumbnail = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + return value; + }, + + get_overlays: function () { + return this._overlays; + }, + + get_musicTrack: function () { + return this._musicTrack; + }, + + set_musicTrack: function (value) { + if (this._musicTrack !== value) { + this._musicTrack = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + get_voiceTrack: function () { + return this._voiceTrack; + }, + + set_voiceTrack: function (value) { + if (this._voiceTrack !== value) { + this._voiceTrack = value; + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + } + return value; + }, + + addOverlay: function (overlay) { + if (overlay == null) { + return; + } + overlay.set_owner(this); + this._overlays.push(overlay); + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + removeOverlay: function (overlay) { + ss.remove(this._overlays, overlay); + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + cleanUp: function () { + // "todo this needs to be evaluated. Causes major pain in WebClient" + var $enum1 = ss.enumerate(this.get_overlays()); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.cleanUp(); + } + if (this._voiceTrack != null) { + this._voiceTrack.cleanUp(); + } + if (this._musicTrack != null) { + this._musicTrack.cleanUp(); + } + }, + + sendToBack: function (target) { + ss.remove(this._overlays, target); + this._overlays.splice(0, 0, target); + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + bringToFront: function (target) { + ss.remove(this._overlays, target); + this._overlays.push(target); + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + bringForward: function (target) { + var index = this._overlays.indexOf(target); + if (index < this._overlays.length - 1) { + ss.remove(this._overlays, target); + this._overlays.splice(index + 1, 0, target); + } + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + sendBackward: function (target) { + var index = this._overlays.indexOf(target); + if (index > 0) { + ss.remove(this._overlays, target); + this._overlays.splice(index - 1, 0, target); + } + if (this._owner != null) { + this._owner.set_tourDirty(true); + } + }, + + getNextOverlay: function (current) { + if (current == null) { + if (this._overlays.length > 0) { + return this._overlays[0]; + } + else { + return null; + } + } + var index = this._overlays.indexOf(current); + if (index < this._overlays.length - 1) { + return this._overlays[index + 1]; + } else { + return this._overlays[0]; + } + }, + + getPerviousOverlay: function (current) { + if (current == null) { + if (this._overlays.length > 0) { + return this._overlays[0]; + } + else { + return null; + } + } + var index = this._overlays.indexOf(current); + if (index > 0) { + return this._overlays[index - 1]; + } else { + return this._overlays[this._overlays.length - 1]; + } + }, + + getOverlayById: function (id) { + var $enum1 = ss.enumerate(this._overlays); + while ($enum1.moveNext()) { + var ol = $enum1.current; + if (ol.id === id) { + return ol; + } + } + return null; + }, + + get_tourStopThumbnailFilename: function () { + return ss.format('{0}.thumb.png', this._id); + }, + + _saveToXml: function (xmlWriter, saveContent) { + if (saveContent) { + if (this._thumbnail != null) { + } + } + xmlWriter._writeStartElement('TourStop'); + xmlWriter._writeAttributeString('Id', this._id); + xmlWriter._writeAttributeString('Name', this._name); + xmlWriter._writeAttributeString('Description', this._description); + xmlWriter._writeAttributeString('Thumbnail', this._thumbnailString); + xmlWriter._writeAttributeString('Duration', Util.xmlDuration(this._duration)); + xmlWriter._writeAttributeString('Master', this._masterSlide.toString()); + xmlWriter._writeAttributeString('TransitionType', Enums.toXml('TransitionType', this._transition)); + xmlWriter._writeAttributeString('TransitionTime', this._transitionTime.toString()); + xmlWriter._writeAttributeString('TransitionOutTime', this._transitionOutTime.toString()); + xmlWriter._writeAttributeString('TransitionHoldTime', this._transitionHoldTime.toString()); + xmlWriter._writeAttributeString('NextSlide', this._nextSlide); + xmlWriter._writeAttributeString('InterpolationType', Enums.toXml('InterpolationType', this._interpolationType)); + xmlWriter._writeAttributeString('HasLocation', this._hasLocation.toString()); + if (this._hasLocation) { + xmlWriter._writeAttributeString('LocationAltitude', this._locationAltitude.toString()); + xmlWriter._writeAttributeString('LocationLat', this._locationLat.toString()); + xmlWriter._writeAttributeString('LocationLng', this._locationLng.toString()); + } + xmlWriter._writeAttributeString('HasTime', this._hasTime.toString()); + if (this._hasTime) { + xmlWriter._writeAttributeString('StartTime', Util.xmlDate(this._startTime)); + xmlWriter._writeAttributeString('EndTime', Util.xmlDate(this._endTime)); + } + xmlWriter._writeAttributeString('ActualPlanetScale', this._actualPlanetScale.toString()); + xmlWriter._writeAttributeString('ShowClouds', this._showClouds.toString()); + xmlWriter._writeAttributeString('EarthCutawayView', this._earthCutawayView.toString()); + xmlWriter._writeAttributeString('ShowConstellationBoundries', this._showConstellationBoundries.toString()); + xmlWriter._writeAttributeString('ShowConstellationFigures', this._showConstellationFigures.toString()); + xmlWriter._writeAttributeString('ShowConstellationSelection', this._showConstellationSelection.toString()); + xmlWriter._writeAttributeString('ShowEcliptic', this._showEcliptic.toString()); + xmlWriter._writeAttributeString('EclipticColor', this._eclipticColor.save()); + xmlWriter._writeAttributeString('ShowElevationModel', this._showElevationModel.toString()); + this._showFieldOfView = false; + xmlWriter._writeAttributeString('ShowFieldOfView', this._showFieldOfView.toString()); + xmlWriter._writeAttributeString('ShowGrid', this._showGrid.toString()); + xmlWriter._writeAttributeString('ShowHorizon', this._showHorizon.toString()); + xmlWriter._writeAttributeString('ShowHorizonPanorama', this._showHorizonPanorama.toString()); + xmlWriter._writeAttributeString('ShowMoonsAsPointSource', this._showMoonsAsPointSource.toString()); + xmlWriter._writeAttributeString('ShowSolarSystem', this._showSolarSystem.toString()); + xmlWriter._writeAttributeString('FovTelescope', this._fovTelescope.toString()); + xmlWriter._writeAttributeString('FovEyepiece', this._fovEyepiece.toString()); + xmlWriter._writeAttributeString('FovCamera', this._fovCamera.toString()); + xmlWriter._writeAttributeString('LocalHorizonMode', this._localHorizonMode.toString()); + xmlWriter._writeAttributeString('GalacticMode', this._galacticMode.toString()); + xmlWriter._writeAttributeString('FadeInOverlays', this._fadeInOverlays.toString()); + xmlWriter._writeAttributeString('SolarSystemStars', this._solarSystemStars.toString()); + xmlWriter._writeAttributeString('SolarSystemMilkyWay', this._solarSystemMilkyWay.toString()); + xmlWriter._writeAttributeString('SolarSystemCosmos', this._solarSystemCosmos.toString()); + xmlWriter._writeAttributeString('SolarSystemCMB', this._solarSystemCMB.toString()); + xmlWriter._writeAttributeString('SolarSystemOrbits', this._solarSystemOrbits.toString()); + xmlWriter._writeAttributeString('SolarSystemMinorOrbits', this._solarSystemMinorOrbits.toString()); + xmlWriter._writeAttributeString('SolarSystemOverlays', this._solarSystemOverlays.toString()); + xmlWriter._writeAttributeString('SolarSystemLighting', this._solarSystemLighting.toString()); + xmlWriter._writeAttributeString('ShowISSModel', this._showISSModel.toString()); + xmlWriter._writeAttributeString('SolarSystemScale', this._solarSystemScale.toString()); + xmlWriter._writeAttributeString('MinorPlanetsFilter', this._minorPlanetsFilter.toString()); + xmlWriter._writeAttributeString('PlanetOrbitsFilter', this._planetOrbitsFilter.toString()); + xmlWriter._writeAttributeString('SolarSystemMultiRes', this._solarSystemMultiRes.toString()); + xmlWriter._writeAttributeString('SolarSystemMinorPlanets', this._solarSystemMinorPlanets.toString()); + xmlWriter._writeAttributeString('SolarSystemPlanets', this._solarSystemPlanets.toString()); + xmlWriter._writeAttributeString('ShowEarthSky', this._showEarthSky.toString()); + xmlWriter._writeAttributeString('ShowEquatorialGridText', this.get_showEquatorialGridText().toString()); + xmlWriter._writeAttributeString('EquatorialGridColor', this.get_equatorialGridColor().save()); + xmlWriter._writeAttributeString('ShowGalacticGrid', this.get_showGalacticGrid().toString()); + xmlWriter._writeAttributeString('ShowGalacticGridText', this.get_showGalacticGridText().toString()); + xmlWriter._writeAttributeString('GalacticGridColor', this.get_galacticGridColor().save()); + xmlWriter._writeAttributeString('ShowEclipticGrid', this.get_showEclipticGrid().toString()); + xmlWriter._writeAttributeString('ShowEclipticGridText', this.get_showEclipticGridText().toString()); + xmlWriter._writeAttributeString('EclipticGridColor', this.get_eclipticGridColor().save()); + xmlWriter._writeAttributeString('ShowEclipticOverviewText', this.get_showEclipticOverviewText().toString()); + xmlWriter._writeAttributeString('ShowAltAzGrid', this.get_showAltAzGrid().toString()); + xmlWriter._writeAttributeString('ShowAltAzGridText', this.get_showAltAzGridText().toString()); + xmlWriter._writeAttributeString('AltAzGridColor', this.get_altAzGridColor().save()); + xmlWriter._writeAttributeString('ShowPrecessionChart', this.get_showPrecessionChart().toString()); + xmlWriter._writeAttributeString('PrecessionChartColor', this.get_precessionChartColor().save()); + xmlWriter._writeAttributeString('ConstellationPictures', this.get_showConstellationPictures().toString()); + xmlWriter._writeAttributeString('ConstellationsEnabled', this.get_constellationsEnabled()); + xmlWriter._writeAttributeString('ShowConstellationLabels', this.get_showConstellationLabels().toString()); + xmlWriter._writeAttributeString('ShowSkyOverlays', this.get_showSkyOverlays().toString()); + xmlWriter._writeAttributeString('ShowConstellations', this.get_showConstellations().toString()); + xmlWriter._writeAttributeString('ShowSkyNode', this.get_showSkyNode().toString()); + xmlWriter._writeAttributeString('ShowSkyGrids', this.get_showSkyGrids().toString()); + xmlWriter._writeAttributeString('SkyOverlaysIn3d', this.get_showSkyOverlaysIn3d().toString()); + xmlWriter._writeAttributeString('ConstellationFiguresFilter', this._constellationFiguresFilter.toString()); + xmlWriter._writeAttributeString('ConstellationBoundariesFilter', this._constellationBoundariesFilter.toString()); + xmlWriter._writeAttributeString('ConstellationNamesFilter', this._constellationNamesFilter.toString()); + xmlWriter._writeAttributeString('ConstellationArtFilter', this._constellationArtFilter.toString()); + this._target._saveToXml(xmlWriter, 'Place'); + if (this._endTarget != null) { + this._endTarget._saveToXml(xmlWriter, 'EndTarget'); + } + xmlWriter._writeStartElement('Overlays'); + var $enum1 = ss.enumerate(this._overlays); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.saveToXml(xmlWriter, false); + } + xmlWriter._writeEndElement(); + if (this._musicTrack != null) { + xmlWriter._writeStartElement('MusicTrack'); + this._musicTrack.saveToXml(xmlWriter, false); + xmlWriter._writeEndElement(); + } + if (this._voiceTrack != null) { + xmlWriter._writeStartElement('VoiceTrack'); + this._voiceTrack.saveToXml(xmlWriter, false); + xmlWriter._writeEndElement(); + } + this._writeLayerList(xmlWriter); + xmlWriter._writeEndElement(); + }, + + _writeLayerList: function (xmlWriter) { + if (ss.keyCount(this.layers) > 0) { + xmlWriter._writeStartElement('VisibleLayers'); + var $enum1 = ss.enumerate(ss.keys(this.layers)); + while ($enum1.moveNext()) { + var key = $enum1.current; + var info = this.layers[key]; + xmlWriter._writeStartElement('Layer'); + xmlWriter._writeAttributeString('StartOpacity', info.startOpacity.toString()); + xmlWriter._writeAttributeString('EndOpacity', info.endOpacity.toString()); + var len = info.startParams.length; + xmlWriter._writeAttributeString('ParamCount', len.toString()); + for (var i = 0; i < len; i++) { + xmlWriter._writeAttributeString(ss.format('StartParam{0}', i), info.startParams[i].toString()); + xmlWriter._writeAttributeString(ss.format('EndParam{0}', i), info.endParams[i].toString()); + } + xmlWriter._writeValue(info.id.toString()); + xmlWriter._writeEndElement(); + } + xmlWriter._writeEndElement(); + } + }, + + _addFilesToCabinet: function (fc, excludeAudio) { + if (this._thumbnail != null) { + var filename = ss.format('{0}.thumb.png', this._id); + var blob = this._owner.getFileBlob(filename); + fc.addFile(this._owner.get_workingDirectory() + filename, blob); + } + if (!excludeAudio) { + if (this._musicTrack != null) { + this._musicTrack.addFilesToCabinet(fc); + } + if (this._voiceTrack != null) { + this._voiceTrack.addFilesToCabinet(fc); + } + } + var $enum1 = ss.enumerate(this._overlays); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + overlay.addFilesToCabinet(fc); + } + }, + + getNextDefaultName: function (baseName) { + var suffixId = 1; + var $enum1 = ss.enumerate(this._overlays); + while ($enum1.moveNext()) { + var overlay = $enum1.current; + if (ss.startsWith(overlay.get_name(), baseName)) { + var id = 0; + try { + id = parseInt(overlay.get_name().substr(baseName.length)); + } + catch ($e2) { + } + if (id >= suffixId) { + suffixId = id + 1; + } + } + } + return ss.format('{0} {1}', baseName, suffixId); + }, + + _loadLayerList: function (layersNode) { + var $enum1 = ss.enumerate(layersNode.childNodes); + while ($enum1.moveNext()) { + var layer = $enum1.current; + if (layer.nodeName === 'Layer') { + var info = new LayerInfo(); + var id = layer.innerHTML; + info.id = Guid.fromString(id); + info.startOpacity = parseFloat(layer.attributes.getNamedItem('StartOpacity').nodeValue); + info.endOpacity = parseFloat(layer.attributes.getNamedItem('EndOpacity').nodeValue); + var len = 0; + if (layer.attributes.getNamedItem('ParamCount') != null) { + len = parseInt(layer.attributes.getNamedItem('ParamCount').nodeValue); + } + info.startParams = new Array(len); + info.endParams = new Array(len); + info.frameParams = new Array(len); + for (var i = 0; i < len; i++) { + info.startParams[i] = parseFloat(layer.attributes.getNamedItem(ss.format('StartParam{0}', i)).nodeValue); + info.endParams[i] = parseFloat(layer.attributes.getNamedItem(ss.format('EndParam{0}', i)).nodeValue); + info.frameParams[i] = info.startParams[i]; + } + this.layers[info.id] = info; + } + } + }, + + _updateLayerOpacity: function () { + if (!this.get_keyFramed()) { + } else { + this.updateTweenPosition(); + } + }, + + get_showEquatorialGridText: function () { + return this._showEquatorialGridText; + }, + + set_showEquatorialGridText: function (value) { + this._showEquatorialGridText = value; + return value; + }, + + get_showGalacticGrid: function () { + return this._showGalacticGrid; + }, + + set_showGalacticGrid: function (value) { + this._showGalacticGrid = value; + return value; + }, + + get_showGalacticGridText: function () { + return this._showGalacticGridText; + }, + + set_showGalacticGridText: function (value) { + this._showGalacticGridText = value; + return value; + }, + + get_showEclipticGrid: function () { + return this._showEclipticGrid; + }, + + set_showEclipticGrid: function (value) { + this._showEclipticGrid = value; + return value; + }, + + get_showEclipticGridText: function () { + return this._showEclipticGridText; + }, + + set_showEclipticGridText: function (value) { + this._showEclipticGridText = value; + return value; + }, + + get_showEclipticOverviewText: function () { + return this._showEclipticOverviewText; + }, + + set_showEclipticOverviewText: function (value) { + this._showEclipticOverviewText = value; + return value; + }, + + get_showAltAzGrid: function () { + return this._showAltAzGrid; + }, + + set_showAltAzGrid: function (value) { + this._showAltAzGrid = value; + return value; + }, + + get_showAltAzGridText: function () { + return this._showAltAzGridText; + }, + + set_showAltAzGridText: function (value) { + this._showAltAzGridText = value; + return value; + }, + + get_showPrecessionChart: function () { + return this._showPrecessionChart; + }, + + set_showPrecessionChart: function (value) { + this._showPrecessionChart = value; + return value; + }, + + get_showConstellationPictures: function () { + return this._showConstellationPictures; + }, + + set_showConstellationPictures: function (value) { + this._showConstellationPictures = value; + return value; + }, + + get_showConstellationLabels: function () { + return this._showConstellationLabels; + }, + + set_showConstellationLabels: function (value) { + this._showConstellationLabels = value; + return value; + }, + + get_solarSystemCMB: function () { + return this._solarSystemCMB; + }, + + set_solarSystemCMB: function (value) { + this._solarSystemCMB = value; + return value; + }, + + get_solarSystemMinorPlanets: function () { + return this._solarSystemMinorPlanets; + }, + + set_solarSystemMinorPlanets: function (value) { + this._solarSystemMinorPlanets = value; + return value; + }, + + get_solarSystemPlanets: function () { + return this._solarSystemPlanets; + }, + + set_solarSystemPlanets: function (value) { + this._solarSystemPlanets = value; + return value; + }, + + get_showEarthSky: function () { + return this._showEarthSky; + }, + + set_showEarthSky: function (value) { + this._showEarthSky = value; + return value; + }, + + get_solarSystemMinorOrbits: function () { + return this._solarSystemMinorOrbits; + }, + + set_solarSystemMinorOrbits: function (value) { + this._solarSystemMinorOrbits = value; + return value; + }, + + get_constellationsEnabled: function () { + return this._constellationsEnabled; + }, + + set_constellationsEnabled: function (value) { + this._constellationsEnabled = value; + return value; + }, + + get_constellationFiguresFilter: function () { + return this._constellationFiguresFilter; + }, + + set_constellationFiguresFilter: function (value) { + this._constellationFiguresFilter = value; + return value; + }, + + get_constellationBoundariesFilter: function () { + return this._constellationBoundariesFilter; + }, + + set_constellationBoundariesFilter: function (value) { + this._constellationBoundariesFilter = value; + return value; + }, + + get_constellationNamesFilter: function () { + return this._constellationNamesFilter; + }, + + set_constellationNamesFilter: function (value) { + this._constellationNamesFilter = value; + return value; + }, + + get_constellationArtFilter: function () { + return this._constellationArtFilter; + }, + + set_constellationArtFilter: function (value) { + this._constellationArtFilter = value; + return value; + }, + + get_showSkyOverlays: function () { + return this._showSkyOverlays; + }, + + set_showSkyOverlays: function (value) { + this._showSkyOverlays = value; + return value; + }, + + get_showConstellations: function () { + return this._showConstellations; + }, + + set_showConstellations: function (value) { + this._showConstellations = value; + return value; + }, + + get_showSkyNode: function () { + return this._showSkyNode; + }, + + set_showSkyNode: function (value) { + this._showSkyNode = value; + return value; + }, + + get_showSkyGrids: function () { + return this._showSkyGrids; + }, + + set_showSkyGrids: function (value) { + this._showSkyGrids = value; + return value; + }, + + get_showSkyOverlaysIn3d: function () { + return this._showSkyOverlaysIn3d; + }, + + set_showSkyOverlaysIn3d: function (value) { + this._showSkyOverlaysIn3d = value; + return value; + }, + + get_earthCutawayView: function () { + return this._earthCutawayView; + }, + + set_earthCutawayView: function (value) { + this._earthCutawayView = value; + return value; + }, + + get_showISSModel: function () { + return this._showISSModel; + }, + + set_showISSModel: function (value) { + this._showISSModel = value; + return value; + }, + + get_milkyWayModel: function () { + return this._milkyWayModel; + }, + + set_milkyWayModel: function (value) { + this._milkyWayModel = value; + return value; + }, + + get_minorPlanetsFilter: function () { + return this._minorPlanetsFilter; + }, + + set_minorPlanetsFilter: function (value) { + this._minorPlanetsFilter = value; + return value; + }, + + get_planetOrbitsFilter: function () { + return this._planetOrbitsFilter; + }, + + set_planetOrbitsFilter: function (value) { + this._planetOrbitsFilter = value; + return value; + }, + + getSetting: function (type) { + if (type === 17) { + return new SettingParameter(true, this.faderOpacity, !!this.faderOpacity, null); + } + return new SettingParameter(false, 1, false, null); + }, + + get_eclipticGridColor: function () { + return this._eclipticGridColor; + }, + + set_eclipticGridColor: function (value) { + this._eclipticGridColor = value; + return value; + }, + + get_galacticGridColor: function () { + return this._galacticGridColor; + }, + + set_galacticGridColor: function (value) { + this._galacticGridColor = value; + return value; + }, + + get_altAzGridColor: function () { + return this._altAzGridColor; + }, + + set_altAzGridColor: function (value) { + this._altAzGridColor = value; + return value; + }, + + get_precessionChartColor: function () { + return this._precessionChartColor; + }, + + set_precessionChartColor: function (value) { + this._precessionChartColor = value; + return value; + }, + + get_eclipticColor: function () { + return this._eclipticColor; + }, + + set_eclipticColor: function (value) { + this._eclipticColor = value; + return value; + }, + + get_equatorialGridColor: function () { + return this._equatorialGridColor; + }, + + set_equatorialGridColor: function (value) { + this._equatorialGridColor = value; + return value; + }, + + get_constellationLabelsHeight: function () { + return this._constellationLabelsHeight; + }, + + set_constellationLabelsHeight: function (value) { + this._constellationLabelsHeight = value; + return value; + } +}; + +registerType("TourStop", [TourStop, TourStop$, null, ISettings]); + + +// wwtlib.LayerInfo + +export function LayerInfo() { + this.id = Guid.newGuid(); + this.startOpacity = 1; + this.endOpacity = 1; + this.frameOpacity = 1; + this.startParams = new Array(0); + this.endParams = new Array(0); + this.frameParams = new Array(0); +} + +var LayerInfo$ = {}; + +registerType("LayerInfo", [LayerInfo, LayerInfo$, null]); + + +// wwtlib.UndoTourStopChange + +export function UndoTourStopChange(text, tour) { + this._undoXml = ''; + this._redoXml = ''; + this._currentIndex = 0; + this._actionText = ''; + this._targetTour = null; + this._currentIndex = tour.get_currentTourstopIndex(); + this._actionText = text; + this._targetTour = tour; + this._undoXml = TourStop.getXmlText(tour.get_currentTourStop()); + this._targetTour.set_tourDirty(true); +} + +var UndoTourStopChange$ = { + get_actionText: function () { + return this._actionText; + }, + + set_actionText: function (value) { + this._actionText = value; + return value; + }, + + undo: function () { + var tsRedo = this._targetTour.get_tourStops()[this._currentIndex]; + var parser = new DOMParser(); + var doc = parser.parseFromString(this._undoXml, 'text/xml'); + var node = Util.selectSingleNode(doc, 'TourStop'); + this._targetTour.get_tourStops()[this._currentIndex] = TourStop._fromXml(this._targetTour, node); + this._targetTour.set_currentTourstopIndex(this._currentIndex); + if (ss.emptyString(this._redoXml)) { + this._redoXml = TourStop.getXmlText(tsRedo); + } + this._targetTour.set_tourDirty(true); + }, + + redo: function () { + var parser = new DOMParser(); + var doc = parser.parseFromString(this._redoXml, 'text/xml'); + var node = Util.selectSingleNode(doc, 'TourStop'); + this._targetTour.get_tourStops()[this._currentIndex] = TourStop._fromXml(this._targetTour, node); + this._targetTour.set_currentTourstopIndex(this._currentIndex); + this._targetTour.set_tourDirty(true); + }, + + toString: function () { + return this._actionText; + } +}; + +registerType("UndoTourStopChange", [UndoTourStopChange, UndoTourStopChange$, null, IUndoStep]); diff --git a/engine/esm/tours/undo.js b/engine/esm/tours/undo.js new file mode 100644 index 00000000..ded6b792 --- /dev/null +++ b/engine/esm/tours/undo.js @@ -0,0 +1,214 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Managing undos of changes made in the tour editor. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { IUndoStep } from "../interfaces.js"; +import { Language } from "../util.js"; + + +// wwtlib.Undo + +export function Undo() { } + +Undo._undoStack = new ss.Stack(); +Undo._redoStack = new ss.Stack(); + +Undo.clear = function () { + Undo._undoStack = new ss.Stack(); + Undo._redoStack = new ss.Stack(); +}; + +Undo.push = function (step) { + Undo._undoStack.push(step); + Undo._redoStack = new ss.Stack(); +}; + +Undo.peekActionString = function () { + if (Undo._undoStack.count > 0) { + return Undo._undoStack.peek().toString(); + } + else { + return Language.getLocalizedText(551, 'Nothing to Undo'); + } +}; + +Undo.peekRedoActionString = function () { + if (Undo._redoStack.count > 0) { + return Undo._redoStack.peek().toString(); + } + else { + return ''; + } +}; + +Undo.peekAction = function () { + return (Undo._undoStack.count > 0); +}; + +Undo.peekRedoAction = function () { + return (Undo._redoStack.count > 0); +}; + +Undo.stepBack = function () { + var step = Undo._undoStack.pop(); + step.undo(); + Undo._redoStack.push(step); +}; + +Undo.stepForward = function () { + var step = Undo._redoStack.pop(); + step.redo(); + Undo._undoStack.push(step); +}; + +var Undo$ = {}; + +registerType("Undo", [Undo, Undo$, null]); + + +// wwtlib.UndoStep + +export function UndoStep() { } + +var UndoStep$ = { + undo: function () { }, + + redo: function () { }, + + toString: function () { + return Language.getLocalizedText(551, 'Nothing to Undo'); + } +}; + +registerType("UndoStep", [UndoStep, UndoStep$, null, IUndoStep]); + + +// wwtlib.UndoTourSlidelistChange + +export function UndoTourSlidelistChange(text, tour) { + this._currentIndex = 0; + this._actionText = ''; + this._targetTour = null; + this._undoList = []; + for (var i = 0; i < tour.get_tourStops().length; i++) { + this._undoList.push(tour.get_tourStops()[i]); + } + this._currentIndex = tour.get_currentTourstopIndex(); + this._actionText = text; + this._targetTour = tour; + this._targetTour.set_tourDirty(true); +} + +var UndoTourSlidelistChange$ = { + get_actionText: function () { + return this._actionText; + }, + + set_actionText: function (value) { + this._actionText = value; + return value; + }, + + undo: function () { + this._redoList = this._targetTour.get_tourStops(); + this._targetTour.set_tourStops(this._undoList); + this._targetTour.set_currentTourstopIndex(this._currentIndex); + this._targetTour.set_tourDirty(true); + }, + + redo: function () { + this._undoList = this._targetTour.get_tourStops(); + this._targetTour.set_tourStops(this._redoList); + this._targetTour.set_currentTourstopIndex(this._currentIndex); + this._targetTour.set_tourDirty(true); + }, + + toString: function () { + return this._actionText; + } +}; + +registerType("UndoTourSlidelistChange", [UndoTourSlidelistChange, UndoTourSlidelistChange$, null, IUndoStep]); + + +// wwtlib.UndoTourPropertiesChange + +export function UndoTourPropertiesChange(text, tour) { + this._actionText = ''; + this._targetTour = null; + this._undoDomeMode = false; + this._undoLevel = 0; + this._redoDomeMode = false; + this._redoLevel = 0; + this._undoTitle = tour.get_title(); + this._undoAuthor = tour.get_author(); + this._undoAuthorEmail = tour.get_authorEmail(); + this._undoDescription = tour.get_description(); + this._undoAuthorImage = tour.get_authorImage(); + this._undoOrganizationUrl = tour.get_organizationUrl(); + this._undoOrgName = tour.get_orgName(); + this._undoKeywords = tour.get_keywords(); + this._undoTaxonomy = tour.get_taxonomy(); + this._undoLevel = tour.get_level(); + this._actionText = text; + this._targetTour = tour; + this._targetTour.set_tourDirty(true); +} + +var UndoTourPropertiesChange$ = { + get_actionText: function () { + return this._actionText; + }, + + set_actionText: function (value) { + this._actionText = value; + return value; + }, + + undo: function () { + this._redoTitle = this._targetTour.get_title(); + this._redoAuthor = this._targetTour.get_author(); + this._redoAuthorEmail = this._targetTour.get_authorEmail(); + this._redoDescription = this._targetTour.get_description(); + this._redoAuthorImage = this._targetTour.get_authorImage(); + this._redoOrganizationUrl = this._targetTour.get_organizationUrl(); + this._redoOrgName = this._targetTour.get_orgName(); + this._redoKeywords = this._targetTour.get_keywords(); + this._redoTaxonomy = this._targetTour.get_taxonomy(); + this._redoLevel = this._targetTour.get_level(); + this._targetTour.set_title(this._undoTitle); + this._targetTour.set_author(this._undoAuthor); + this._targetTour.set_authorEmail(this._undoAuthorEmail); + this._targetTour.set_description(this._undoDescription); + this._targetTour.set_authorImage(this._undoAuthorImage); + this._targetTour.set_organizationUrl(this._undoOrganizationUrl); + this._targetTour.set_orgName(this._undoOrgName); + this._targetTour.set_keywords(this._undoKeywords); + this._targetTour.set_taxonomy(this._undoTaxonomy); + this._targetTour.set_level(this._undoLevel); + this._targetTour.set_tourDirty(true); + }, + + redo: function () { + this._targetTour.set_title(this._redoTitle); + this._targetTour.set_author(this._redoAuthor); + this._targetTour.set_authorEmail(this._redoAuthorEmail); + this._targetTour.set_description(this._redoDescription); + this._targetTour.set_authorImage(this._redoAuthorImage); + this._targetTour.set_organizationUrl(this._redoOrganizationUrl); + this._targetTour.set_orgName(this._redoOrgName); + this._targetTour.set_keywords(this._redoKeywords); + this._targetTour.set_taxonomy(this._redoTaxonomy); + this._targetTour.set_level(this._redoLevel); + this._targetTour.set_tourDirty(true); + }, + + toString: function () { + return this._actionText; + } +}; + +registerType("UndoTourPropertiesChange", [UndoTourPropertiesChange, UndoTourPropertiesChange$, null, IUndoStep]); diff --git a/engine/esm/triangle.js b/engine/esm/triangle.js new file mode 100644 index 00000000..809d425b --- /dev/null +++ b/engine/esm/triangle.js @@ -0,0 +1,70 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A spherical triangle that can be subdivided. + +import { registerType } from "./typesystem.js"; +import { Vector2d, Vector3d, PositionTexture } from "./double3d.js"; + + +// wwtlib.Triangle + +export function Triangle() { + // Vertex Indices + this.a = -1; + this.b = -1; + this.c = -1; +} + +Triangle.create = function (a, b, c) { + var temp = new Triangle(); + temp.a = a; + temp.b = b; + temp.c = c; + return temp; +}; + +var Triangle$ = { + subDivide: function (triList, vertexList) { + var a1 = Vector3d.lerp(vertexList[this.b].position, vertexList[this.c].position, 0.5); + var b1 = Vector3d.lerp(vertexList[this.c].position, vertexList[this.a].position, 0.5); + var c1 = Vector3d.lerp(vertexList[this.a].position, vertexList[this.b].position, 0.5); + var a1uv = Vector2d.lerp(Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), 0.5); + var b1uv = Vector2d.lerp(Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), 0.5); + var c1uv = Vector2d.lerp(Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), 0.5); + a1.normalize(); + b1.normalize(); + c1.normalize(); + var aIndex = vertexList.length; + var bIndex = vertexList.length + 1; + var cIndex = vertexList.length + 2; + vertexList.push(PositionTexture.createPosRaw(a1, a1uv.x, a1uv.y)); + vertexList.push(PositionTexture.createPosRaw(b1, b1uv.x, b1uv.y)); + vertexList.push(PositionTexture.createPosRaw(c1, c1uv.x, c1uv.y)); + triList.push(Triangle.create(this.a, cIndex, bIndex)); + triList.push(Triangle.create(this.b, aIndex, cIndex)); + triList.push(Triangle.create(this.c, bIndex, aIndex)); + triList.push(Triangle.create(aIndex, bIndex, cIndex)); + }, + + subDivideNoNormalize: function (triList, vertexList) { + var a1 = Vector3d.lerp(vertexList[this.b].position, vertexList[this.c].position, 0.5); + var b1 = Vector3d.lerp(vertexList[this.c].position, vertexList[this.a].position, 0.5); + var c1 = Vector3d.lerp(vertexList[this.a].position, vertexList[this.b].position, 0.5); + var a1uv = Vector2d.lerp(Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), 0.5); + var b1uv = Vector2d.lerp(Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), 0.5); + var c1uv = Vector2d.lerp(Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), 0.5); + var aIndex = vertexList.length; + var bIndex = vertexList.length + 1; + var cIndex = vertexList.length + 2; + vertexList.push(PositionTexture.createPosRaw(a1, a1uv.x, a1uv.y)); + vertexList.push(PositionTexture.createPosRaw(b1, b1uv.x, b1uv.y)); + vertexList.push(PositionTexture.createPosRaw(c1, c1uv.x, c1uv.y)); + triList.push(Triangle.create(this.a, cIndex, bIndex)); + triList.push(Triangle.create(this.b, aIndex, cIndex)); + triList.push(Triangle.create(this.c, bIndex, aIndex)); + triList.push(Triangle.create(aIndex, bIndex, cIndex)); + } +}; + +registerType("Triangle", [Triangle, Triangle$, null]); diff --git a/engine/esm/typesystem.js b/engine/esm/typesystem.js new file mode 100644 index 00000000..61e328a0 --- /dev/null +++ b/engine/esm/typesystem.js @@ -0,0 +1,72 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Some small but helpful structures applied on top of the type system +// provided by ScriptSharp. + +import { ss } from "./ss.js"; + +const registry = ss.createRegistry("wwtlib"); +const enumTypes = {}; + + +// Finish the creation and registration of a type that plugs into the +// ScriptSharp type system. The return value is the new type object. +// +// The `typeinfo` argument has a complex structure and comes from the code +// generated by ScriptSharp. +export function registerType(name, typeinfo) { + // This function modifies the class object and returns it, but we can just + // ignore the return value. + ss.createType(name, typeinfo, registry); +} + + +// Register an enumeration with the type system. +// +// This is used to parse various enumerations from serialized formats. +export function registerEnum(name, type) { + enumTypes[name] = type; +} + + +// The Enums helper "class". We could easily port this to a non-OO interface. + +export function Enums() { } + +Enums.parse = function (enumType, value) { + if (value === "Default") { + value = "DefaultV"; + } + + if (value === "0") { + return 0; + } + + var val = value.substr(0, 1).toLowerCase() + value.substr(1); + return enumTypes[enumType][val]; +}; + +Enums.toXml = function (enumType, value) { + var x = "0"; + var p = Object.keys(enumTypes[enumType]); + + for (var i in p) { + if (enumTypes[enumType][p[i]] == value) { + x = p[i]; + break; + } + } + + var val = x; + var enumString = val.substr(0, 1).toUpperCase() + val.substr(1); + if (enumString === "DefaultV") { + enumString = "Default"; + } + + return enumString; +}; + +const Enums$ = {}; + +registerType("Enums", [Enums, Enums$, null]); diff --git a/engine/esm/ui_tools.js b/engine/esm/ui_tools.js new file mode 100644 index 00000000..64518dbf --- /dev/null +++ b/engine/esm/ui_tools.js @@ -0,0 +1,168 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A tile in a pyramid that uses a HEALPix projection. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; + + +// wwtlib.UiTools + +export function UiTools() { } + +UiTools.kilometersPerAu = 149598000; +UiTools.auPerParsec = 206264.806; +UiTools.auPerLightYear = 63239.6717; +UiTools.ssmUnitConversion = 370; // No idea where this fudge factor comes from + +UiTools.gamma = function (val, gamma) { + return Math.min(255, ss.truncate(((255 * Math.pow(val / 255, 1 / gamma)) + 0.5))); +}; + +UiTools.getNamesStringFromArray = function (array) { + var names = ''; + var delim = ''; + var $enum1 = ss.enumerate(array); + while ($enum1.moveNext()) { + var name = $enum1.current; + names += delim; + names += name; + delim = ';'; + } + return names; +}; + +UiTools.solarSystemToMeters = function (SolarSystemCameraDistance) { + return SolarSystemCameraDistance * 149598000 * 370; +}; + +UiTools.metersToSolarSystemDistance = function (meters) { + return meters / 370 * 149598000; +}; + +UiTools.metersToZoom = function (meters) { + return ((meters / 1000 / 370) - 1E-06) / 4 * 9; +}; + +// Distance is stored in AU in WWT but is displayed in KM AU, LY, MPC +UiTools.formatDistance = function (distance) { + if (distance < 0.1) { + var km = (distance * 149598000); + if (km < 10) { + var m = ss.truncate((km * 1000)); + return ss.format('{0} m', m); + } else { + km = ss.truncate(km); + return ss.format('{0} km', km); + } + } + else if (distance < (10)) { + var au = ss.truncate((distance * 10)) / 10; + return ss.format('{0} au', au); + } + else if (distance < (63239.6717 / 10)) { + var au = ss.truncate(distance); + return ss.format('{0} au', au); + } + else if (distance < (63239.6717 * 10)) { + var ly = ss.truncate(((distance * 10) / 63239.6717)) / 10; + return ss.format('{0} ly', ly); + } + else if (distance < (63239.6717 * 1000000)) { + var ly = ss.truncate((distance / 63239.6717)); + return ss.format('{0} ly', ly); + } + else if (distance < (206264.806 * 10000000)) { + var mpc = ss.truncate(((distance * 10) / (206264.806 * 1000000))) / 10; + return ss.format('{0} Mpc', mpc); + } + else if (distance < (206264.806 * 1000000000)) { + var mpc = ss.truncate((distance / (206264.806 * 1000000))); + return ss.format('{0} Mpc', mpc); + } + else { + var mpc = ss.truncate(((distance * 10) / (206264.806 * 1000000000))) / 10; + return ss.format('{0} Gpc', mpc); + } +}; + +UiTools.formatDecimalHours = function (dayFraction) { + var today = ss.now(); + var ts = today.getTimezoneOffset() / 60; + ts = 0; + var day = (dayFraction - ts) + 0.0083333334; + while (day > 24) { + day -= 24; + } + while (day < 0) { + day += 24; + } + var hours = ss.truncate(day); + var minutes = ss.truncate(((day * 60) - (hours * 60))); + var seconds = ss.truncate(((day * 3600) - ((hours * 3600) + (minutes * 60)))); + return ss.format('{0}:{1}', hours, minutes, seconds); +}; + +UiTools.splitString = function (data, delimiter) { + var output = []; + var nestingLevel = 0; + var current = 0; + var count = 0; + var start = 0; + while (current < data.length) { + if (data.substr(current, 1) === '(') { + nestingLevel++; + } + if (data.substr(current, 1) === ')') { + nestingLevel--; + } + if (current === (data.length - 1)) { + if (data.substr(current, 1) === delimiter) { + output.push(data.substr(start, count)); + output.push(''); + return output; + } + else { + count++; + } + } + if (current === (data.length - 1) || (data.substr(current, 1) === delimiter && delimiter === '\t') || (!nestingLevel && data.substr(current, 1) === delimiter)) { + output.push(data.substr(start, count)); + start = current + 1; + count = 0; + } else { + count++; + } + current++; + } + return output; +}; + +UiTools.split = function (data, delimiters) { + var output = []; + var nestingLevel = 0; + var current = 0; + var count = 0; + var start = 0; + while (current < data.length) { + if (current === (data.length - 1)) { + count++; + } + if (current === (data.length - 1) || delimiters.indexOf(data.substr(current, 1)) > -1) { + output.push(data.substr(start, count)); + start = current + 1; + count = 0; + } else { + count++; + } + current++; + } + return output; +}; + +UiTools._beep = function () { }; + +var UiTools$ = {}; + +registerType("UiTools", [UiTools, UiTools$, null]); diff --git a/engine/esm/url_helpers.js b/engine/esm/url_helpers.js new file mode 100644 index 00000000..fa37f24d --- /dev/null +++ b/engine/esm/url_helpers.js @@ -0,0 +1,367 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The helper class for rewriting URLs. This gets complicated, because we might +// need to proxy for CORS headers and/or HTTPS support, *and* we sometimes also +// want to change the host and/or path to allow the engine or the webclient to +// swap out the data backend or the frontend. + +import { registerType, registerEnum } from "./typesystem.js"; +import { ss } from "./ss.js"; +import { freestandingMode } from "./data_globals.js"; + +var DomainHandling = { + wwtFlagship: 0, // this host is worldwidetelescope.org or an equivalent + localhost: 1, // this host is localhost or an equivalent + neverProxy: 2, // this host is known to never need proxying + tryNoProxy: 3, // none of the above, and we hope that we can get data from it without needing to use our proxy + proxy: 4, // none of the above, and we need to proxy it for HTTPS/CORS reasons +} + +// wwtlib.URLRewriteMode + +export var URLRewriteMode = { + asIfAbsolute: 0, // act as if this URL is absolute even if it is missing a domain + originRelative: 1, // if this URL is relative, treat it as relative to the browser origin +}; + +registerType("URLRewriteMode", URLRewriteMode); +registerEnum("URLRewriteMode", URLRewriteMode); + + +// wwtlib.URLHelpers + +export function URLHelpers() { + // this will be "http:" or "https:" + this._origin_protocol = typeof window === "undefined" ? "https:" : window.location.protocol; + this._force_https = (this._origin_protocol === 'https:'); + + // host name, no port number + this._origin_domain = typeof window === "undefined" ? "" : window.location.hostname; + + + this._domain_handling = {}; + this._domain_handling['worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['www.worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['cdn.worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['content.worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['beta.worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['beta-cdn.worldwidetelescope.org'] = DomainHandling.wwtFlagship; + this._domain_handling['wwtstaging.azurewebsites.net'] = DomainHandling.wwtFlagship; + this._domain_handling['wwtfiles.blob.core.windows.net'] = DomainHandling.neverProxy; + this._domain_handling['wwttiles.blob.core.windows.net'] = DomainHandling.neverProxy; + this._domain_handling['web.wwtassets.org'] = DomainHandling.neverProxy; + this._domain_handling['data1.wwtassets.org'] = DomainHandling.neverProxy; + this._domain_handling['localhost'] = DomainHandling.localhost; + this._domain_handling['127.0.0.1'] = DomainHandling.localhost; + + switch (this._origin_domain) { + case 'worldwidetelescope.org': + case 'www.worldwidetelescope.org': + case 'cdn.worldwidetelescope.org': + this._core_static_baseurl = this._origin_protocol + '//cdn.worldwidetelescope.org'; + this._core_dynamic_baseurl = this._origin_protocol + '//worldwidetelescope.org'; + break; + case 'beta.worldwidetelescope.org': + case 'beta-cdn.worldwidetelescope.org': + this._core_static_baseurl = this._origin_protocol + '//beta-cdn.worldwidetelescope.org'; + this._core_dynamic_baseurl = this._origin_protocol + '//beta.worldwidetelescope.org'; + break; + default: + this._core_static_baseurl = this._origin_protocol + '//cdn.worldwidetelescope.org'; + this._core_dynamic_baseurl = this._origin_protocol + '//worldwidetelescope.org'; + break; + } + + this._engine_asset_baseurl = this._origin_protocol + '//web.wwtassets.org/engine/assets'; + + // this should be a set, but ScriptSharp had trouble with that. + this._flagship_static_lcpaths = {}; + this._flagship_static_lcpaths['/wwtweb/2massoct.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/bingdemtile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/bingdemtile2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/catalog.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/catalog2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/dem.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/dembath.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/demmars.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/demtile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/dss.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/dsstoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/dusttoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/earthblend.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/earthmerbath.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/fixedaltitudedemtile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/g360.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/galex4far.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/galex4near.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/galextoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/gettile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/gettour.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/gettourfile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/gettours.aspx'] = true; // maybe not? + this._flagship_static_lcpaths['/wwtweb/glimpse.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/halphatoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/hirise.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/hirisedem2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/hirisedem3.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/jupiter.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/mandel.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/mandel1.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/mars.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/marsdem.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/marshirise.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/marsmoc.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/martiantile.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/martiantile2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/mipsgal.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/moondem.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/moonoct.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/moontoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/moontoastdem.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/postmars.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/postmarsdem.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/postmarsdem2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/rasstoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/sdsstoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/sdsstoast2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/sdsstoast2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/thumbnail.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/tiles.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/tiles2.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/tilesthumb.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/twomasstoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/tychooct.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/veblend.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/vlsstoast.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/wmap.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/wmsmoon.aspx'] = true; + this._flagship_static_lcpaths['/wwtweb/wmstoast.aspx'] = true; +} + +var URLHelpers$ = { + overrideAssetBaseurl: function (baseurl) { + this._engine_asset_baseurl = baseurl; + }, + + rewrite: function (url, rwmode) { + // Sadly, we can't take advantage of JS/browser URL parsing + // because this function might be passed template URLs like + // "http://r{S:2}.ortho.tiles.virtualearth.net/..." that won't + // parse. So we have to split up the URL manually. + var lc = url.toLowerCase(); + var lcproto; + var url_no_protocol; + + if (ss.startsWith(lc, 'http://')) { + lcproto = 'http:'; + url_no_protocol = url.substring(7); + } else if (ss.startsWith(lc, 'https://')) { + lcproto = 'https:'; + url_no_protocol = url.substring(8); + } else if (ss.startsWith(lc, '//')) { + lcproto = ''; + url_no_protocol = url.substring(2); + } else if (ss.startsWith(lc, 'blob:')) { + // The web client uses URL.createObjectURL() to ingest local + // disk files into the web app. That function creates blob + // URLs, and it turns out that we definitely don't want to + // rewrite them! + return url; + } else { + switch (rwmode) { + case URLRewriteMode.asIfAbsolute: + default: + // Treat `foo/bar` as a domain name of `foo` and a + // path of `/bar`. Really we should demand that the + // caller always pass us an absolute URL, but URLs + // will be coming from random data sources and we're + // not currently rigorous enough to guarantee that + // this function will get validated inputs -- and in + // such cases, throwing exceptions won't help. + lcproto = ''; + url_no_protocol = url; + break; + + case URLRewriteMode.originRelative: + // Treat `foo/bar` as a URL relative to the window + // origin. Since it looks relative, any weird + // templating stuff in the URL text *ought* not cause + // problems for the browser URL parsing ... + url = (new URL(url, window.location.href)).toString(); + return this.rewrite(url, 0); + } + } + + // If we're freestanding, we can't use the proxy and we don't want + // to forcibly rewrite URLs to potentially point at any core WWT + // domains, so there is nothing more to do (now that we've potentially + // handled origin-relative URLs). + if (freestandingMode) { + return url; + } + + var domain; + var rest; // potentially "/foo/CASE/bar?q=1&b=1#fragment" + var slash_index = url_no_protocol.indexOf('/'); + + if (slash_index < 0) { + domain = url_no_protocol; + rest = '/'; + } else { + domain = url_no_protocol.substring(0, slash_index); + rest = url_no_protocol.substring(slash_index); // starts with "/" + } + + var lcdomain = domain.toLowerCase(); + var lcpath = rest.toLowerCase().split('?')[0]; + + if (!ss.keyExists(this._domain_handling, lcdomain)) { + // Domains include nonstandard port specifications, so it's + // possible that we could get here with a discernably + // localhost-y domain. + if (ss.startsWith(lcdomain, 'localhost:') || ss.startsWith(lcdomain, '127.0.0.1:')) { + this._domain_handling[lcdomain] = DomainHandling.localhost; + } else { + this._domain_handling[lcdomain] = DomainHandling.tryNoProxy; + } + } + + var mode = this._domain_handling[lcdomain]; + + switch (mode) { + case DomainHandling.localhost: + return url; // can't proxy, so we'll just have to hope it works + + case DomainHandling.neverProxy: + case DomainHandling.tryNoProxy: + default: + if (this._force_https && lcproto !== 'https:') { + // Force HTTPS and we'll see what happens. If + // downloading fails, we'll set a flag and use our + // proxy to launder the security. + // + // NOTE: it is important that we use `domain` and not + // `lcdomain`, even though domain names are + // case-insensitive, because we might be processing a + // template URL containing text like `{S}`, and WWT's + // replacements *are* case-sensitive. Yes, I did learn + // this the hard way. + return 'https://' + domain + rest; + } + return url; + + case DomainHandling.proxy: + if (!lcproto) { + // Make sure that we give the proxy a real absolute + // URL. Guess http, and if the proxy is forced to + // upgrade, so be it. + url = 'http://' + url; + } + + // We need to encode the URL as a query-string parameter + // to pass to the proxy. However, the encoding will turn + // "{}" into "%7B%7D", so that *if* this URL is then going + // to be fed into the templating system, + // search-and-replace for e.g. "{0}" will break. So we + // un-encode those particular characters, since it ought + // to be safe to do so anyway. + url = ss.replaceString(ss.replaceString(encodeURIComponent(url), '%7B', '{'), '%7D', '}'); + return this._core_dynamic_baseurl + '/webserviceproxy.aspx?targeturl=' + url; + + case DomainHandling.wwtFlagship: + // Rewrite "flagship"/core URLs to go through whatever our + // core bases are. Assume that URLs are dynamic (=> are + // not loaded through the CDN) unless proven otherwise. + var is_static = false; + + if (ss.startsWith(lcpath, '/data/')) { + is_static = true; + } else if (ss.keyExists(this._flagship_static_lcpaths, lcpath)) { + is_static = true; + } else if (ss.startsWith(lcpath, '/content/')) { + is_static = true; + } else if (ss.startsWith(lcpath, '/engine/assets/')) { + is_static = true; + } + + if (is_static) { + return this._core_static_baseurl + rest; + } + + return this._core_dynamic_baseurl + rest; + } + }, + + // Call this when you have tried to load a url via XMLHttpRequest or + // something along those lines, and the attempt has failed. We will mark the + // domain as needing proxying, and will return a new proxy-enabled URL to try. + // The exception is for flagship website URLs, which we know that the proxy + // won't help with. For those, null is returned. + activateProxy: function (url) { + // If we're freestanding, we never proxy. + if (freestandingMode) { + return null; + } + + // Get the domain. XXX copy/pastey from the above. + + var lc = url.toLowerCase(); + var url_no_protocol; + + if (ss.startsWith(lc, 'http://')) { + url_no_protocol = url.substring(7); + } else if (ss.startsWith(lc, 'https://')) { + url_no_protocol = url.substring(8); + } else if (ss.startsWith(lc, '//')) { + url_no_protocol = url.substring(2); + } else { + url_no_protocol = url; + } + + var lcdomain; + var slash_index = url_no_protocol.indexOf('/'); + + if (slash_index < 0) { + lcdomain = url_no_protocol; + } else { + lcdomain = url_no_protocol.substring(0, slash_index).toLowerCase(); + } + + // Is this a flagship or never-proxy URL? If so, don't bother proxying. + + if (!ss.keyExists(this._domain_handling, lcdomain)) { + if (ss.startsWith(lcdomain, 'localhost:') || ss.startsWith(lcdomain, '127.0.0.1:')) { + this._domain_handling[lcdomain] = DomainHandling.localhost; + } + else { + this._domain_handling[lcdomain] = DomainHandling.tryNoProxy; + } + } + + var mode = this._domain_handling[lcdomain]; + if (mode === DomainHandling.wwtFlagship || mode === DomainHandling.neverProxy || mode === DomainHandling.localhost) { + return null; + } + + // OK, we should try proxying. So: + this._domain_handling[lcdomain] = DomainHandling.proxy; + return this.rewrite(url, 0); + }, + + engineAssetUrl: function (subpath) { + return ss.format('{0}/{1}', this._engine_asset_baseurl, subpath); + }, + + coreDynamicUrl: function (subpath) { + return ss.format('{0}/{1}', this._core_dynamic_baseurl, subpath); + }, + + coreStaticUrl: function (subpath) { + return ss.format('{0}/{1}', this._core_static_baseurl, subpath); + } +}; + +registerType("URLHelpers", [URLHelpers, URLHelpers$, null]); + +URLHelpers.singleton = new URLHelpers(); diff --git a/engine/esm/util.js b/engine/esm/util.js new file mode 100644 index 00000000..2669d20e --- /dev/null +++ b/engine/esm/util.js @@ -0,0 +1,638 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Miscellaneous utilities. + +import * as uuid from "uuid"; + +import { registerType, registerEnum } from "./typesystem.js"; +import { ss } from "./ss.js"; +export { Util } from "./baseutil.js"; +import { Color } from "./color.js"; +import { Vector2d, Vector3d } from "./double3d.js"; + + +// wwtlib.Rectangle + +export function Rectangle() { + this.x = 0; + this.y = 0; + this.width = 0; + this.height = 0; +} + +Rectangle.create = function (x, y, width, height) { + var temp = new Rectangle(); + temp.x = x; + temp.y = y; + temp.width = width; + temp.height = height; + return temp; +}; + +var Rectangle$ = { + get_left: function () { + return this.x; + }, + + get_right: function () { + return this.x + this.width; + }, + + get_top: function () { + return this.y; + }, + + get_bottom: function () { + return this.y + this.height; + }, + + contains: function (point) { + return (this._between(point.x, this.x, this.x + this.width) && this._between(point.y, this.y, this.y + this.height)); + }, + + _between: function (n, n1, n2) { + if (n1 > n2) { + return !(n > n1) && !(n < n2); + } + else { + return !(n < n1) && !(n > n2); + } + }, + + copy: function () { + var temp = new Rectangle(); + temp.x = this.x; + temp.y = this.y; + temp.width = this.width; + temp.height = this.height; + return temp; + } +}; + +registerType("Rectangle", [Rectangle, Rectangle$, null]); + + +// wwtlib.Guid + +export function Guid() { + this._guid = Guid.create(); +} + +Guid.newGuid = function () { + return new Guid(); +}; + +Guid.fromString = function (id) { + var temp = new Guid(); + temp._guid = ss.trim(id); + return temp; +}; + +Guid.create = function () { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); +}; + +// The value 1420736a-a637-40a7-813a-ba692e72204e is a UUID (generated using the uuid CLI) +// that serves as a 'namespace' for our GUIDs +// The key property here is that this function always yields the same result for a given input +// See for example https://www.sohamkamani.com/uuid-versions-explained/ +Guid.createFrom = function (value) { + var str = uuid.v5(value, '1420736a-a637-40a7-813a-ba692e72204e'); + return Guid.fromString(str); +}; + +var Guid$ = { + toString: function () { + return this._guid; + } +}; + +registerType("Guid", [Guid, Guid$, null]); + + +// The "Enums" typed lived here in the C#, but is now in `typesystem.js`. + +// wwtlib.Mouse + +export function Mouse() { } + +Mouse.offsetX = function (canvas, e) { + var x = 0; + var element = canvas; + var me = e; + if (element.offsetParent != null) { + do { + x += element.offsetLeft; + } while ((element = element.offsetParent) != null); + } + return me.pageX - x; +}; + +Mouse.offsetY = function (canvas, e) { + var y = 0; + var element = canvas; + var me = e; + if (element.offsetParent != null) { + do { + y += element.offsetTop; + } while ((element = element.offsetParent) != null); + } + return me.pageY - y; +}; + +registerType("Mouse", [Mouse, null, null]); + + +// wwtlib.Language + +export function Language() { } + +Language.getLocalizedText = function (id, text) { + return text; +}; + +var Language$ = {}; + +registerType("Language", [Language, Language$, null]); + + +// wwtlib.Cursor + +export function Cursor() { } + +Cursor.get_position = function () { + return new Vector2d(); +}; + +Cursor.get_current = function () { + return document.body.style.cursor; +}; + +Cursor.set_current = function (value) { + document.body.style.cursor = value; + return value; +}; + +var Cursor$ = {}; + +registerType("Cursor", [Cursor, Cursor$, null]); + + +// wwtlib.Cursors + +export function Cursors() { } + +Cursors.get_arrow = function () { + return 'default'; +}; + +Cursors.get_cross = function () { + return 'crosshair'; +}; + +Cursors.get_defaultV = function () { + return 'default'; +}; + +Cursors.get_hand = function () { + return 'grab'; +}; + +Cursors.get_help = function () { + return 'help'; +}; + +Cursors.get_hSplit = function () { + return 'row-resize'; +}; + +Cursors.get_iBeam = function () { + return 'text'; +}; + +Cursors.get_no = function () { + return 'not-allowed'; +}; + +Cursors.get_sizeAll = function () { + return 'help'; +}; + +Cursors.get_sizeNESW = function () { + return 'nwse-resize'; +}; + +Cursors.get_sizeNS = function () { + return 'ns-resize'; +}; + +Cursors.get_sizeNWSE = function () { + return 'nwse-resize'; +}; + +Cursors.get_sizeWE = function () { + return 'ew-resize'; +}; + +Cursors.get_upArrow = function () { + return 'help'; +}; + +Cursors.get_vSplit = function () { + return 'col-resize'; +}; + +Cursors.get_waitCursor = function () { + return 'wait'; +}; + +var Cursors$ = {}; + +registerType("Cursors", [Cursors, Cursors$, null]); + + +// wwtlib.Keys + +export var Keys = { + modifiers: -65536, + none: 0, + lButton: 1, + rButton: 2, + cancel: 3, + mButton: 4, + xButton1: 5, + xButton2: 6, + back: 8, + tab: 9, + lineFeed: 10, + clearKey: 12, + returnKey: 13, + enter: 13, + shiftKey: 16, + controlKey: 17, + menu: 18, + pause: 19, + capital: 20, + capsLock: 20, + kanaMode: 21, + hanguelMode: 21, + hangulMode: 21, + junjaMode: 23, + finalMode: 24, + hanjaMode: 25, + kanjiMode: 25, + escape: 27, + imeConvert: 28, + imeNonconvert: 29, + imeAccept: 30, + imeAceept: 30, + imeModeChange: 31, + space: 32, + prior: 33, + pageUp: 33, + next: 34, + pageDown: 34, + end: 35, + home: 36, + left: 37, + up: 38, + right: 39, + down: 40, + select: 41, + print: 42, + execute: 43, + snapshot: 44, + printScreen: 44, + insertKey: 45, + deleteKey: 46, + help: 47, + d0: 48, + d1: 49, + d2: 50, + d3: 51, + d4: 52, + d5: 53, + d6: 54, + d7: 55, + d8: 56, + d9: 57, + a: 65, + b: 66, + c: 67, + d: 68, + e: 69, + f: 70, + g: 71, + h: 72, + i: 73, + j: 74, + k: 75, + l: 76, + m: 77, + n: 78, + o: 79, + p: 80, + q: 81, + r: 82, + s: 83, + t: 84, + u: 85, + v: 86, + w: 87, + x: 88, + y: 89, + z: 90, + lWin: 91, + rWin: 92, + apps: 93, + sleep: 95, + numPad0: 96, + numPad1: 97, + numPad2: 98, + numPad3: 99, + numPad4: 100, + numPad5: 101, + numPad6: 102, + numPad7: 103, + numPad8: 104, + numPad9: 105, + multiply: 106, + add: 107, + separator: 108, + subtract: 109, + decimal: 110, + divide: 111, + f1: 112, + f2: 113, + f3: 114, + f4: 115, + f5: 116, + f6: 117, + f7: 118, + f8: 119, + f9: 120, + f10: 121, + f11: 122, + f12: 123, + f13: 124, + f14: 125, + f15: 126, + f16: 127, + f17: 128, + f18: 129, + f19: 130, + f20: 131, + f21: 132, + f22: 133, + f23: 134, + f24: 135, + numLock: 144, + scroll: 145, + lShiftKey: 160, + rShiftKey: 161, + lControlKey: 162, + rControlKey: 163, + lMenu: 164, + rMenu: 165, + browserBack: 166, + browserForward: 167, + browserRefresh: 168, + browserStop: 169, + browserSearch: 170, + browserFavorites: 171, + browserHome: 172, + volumeMute: 173, + volumeDown: 174, + volumeUp: 175, + mediaNextTrack: 176, + mediaPreviousTrack: 177, + mediaStop: 178, + mediaPlayPause: 179, + launchMail: 180, + selectMedia: 181, + launchApplication1: 182, + launchApplication2: 183, + oemSemicolon: 186, + oem1: 186, + oemplus: 187, + oemcomma: 188, + oemMinus: 189, + oemPeriod: 190, + oemQuestion: 191, + oem2: 191, + oemtilde: 192, + oem3: 192, + oemOpenBrackets: 219, + oem4: 219, + oemPipe: 220, + oem5: 220, + oemCloseBrackets: 221, + oem6: 221, + oemQuotes: 222, + oem7: 222, + oem8: 223, + oemBackslash: 226, + oem102: 226, + processKey: 229, + packet: 231, + attn: 246, + crsel: 247, + exsel: 248, + eraseEof: 249, + play: 250, + zoom: 251, + noName: 252, + pa1: 253, + oemClear: 254, + keyCode: 65535, + shift: 65536, + control: 131072, + alt: 262144 +}; + +registerType("Keys", Keys); + + +// wwtlib.SelectLink + +export function SelectLink(id) { + this._return = false; + this._next = true; + this._linkSlide = false; + this._slide = null; + this._ok = false; + if (id != null) { + this.set_id(id); + } + else { + this.set_next(true); + } +} + +var SelectLink$ = { + get_returnCaller: function () { + return this._return; + }, + + set_returnCaller: function (value) { + if (value) { + this._slide = 'Return'; + } + this._return = value; + return value; + }, + + get_next: function () { + return this._next; + }, + + set_next: function (value) { + if (value) { + this._slide = 'Next'; + } + this._next = value; + return value; + }, + + get_linkToSlide: function () { + return this._linkSlide; + }, + + set_linkToSlide: function (value) { + if (value) { + this._slide = 'Next'; + } + this._linkSlide = value; + return value; + }, + + get_id: function () { + return this._slide; + }, + + set_id: function (value) { + this._return = false; + this._next = false; + this._linkSlide = true; + this._slide = value; + return value; + }, + + get_OK: function () { + return this._ok; + }, + + set_OK: function (value) { + this._ok = value; + return value; + } +}; + +registerType("SelectLink", [SelectLink, SelectLink$, null]); + + +// wwtlib.PopupVolume + +export function PopupVolume() { + this.volume = 0; +} + +var PopupVolume$ = { + showDialog: function () { + return 1; + } +}; + +registerType("PopupVolume", [PopupVolume, PopupVolume$, null]); + + +// wwtlib.PopupColorPicker + +export function PopupColorPicker() { + this.volume = 0; + this.location = new Vector2d(); + this.color = new Color(); +} + +var PopupColorPicker$ = { + showDialog: function () { + return 1; + } +}; + +registerType("PopupColorPicker", [PopupColorPicker, PopupColorPicker$, null]); + + +// wwtlib.OverlayProperties + +export function OverlayProperties() { + this.volume = 0; + this.location = new Vector2d(); + this.overlay = null; +} + +var OverlayProperties$ = { + showDialog: function () { + return 1; + } +}; + +registerType("OverlayProperties", [OverlayProperties, OverlayProperties$, null]); + + +// This used to be Imageset.getTileKey, but to break +// circular dependencies, we move it here. + +export function getTileKey(imageset, level, x, y, parent) { + if (imageset.get_projection() === 7 && parent != null) { + var ipix = (parent).ipix * 4 + y * 2 + x; + return imageset.get_imageSetID().toString() + '\\' + level.toString() + '\\' + ipix.toString(); + } + + return imageset.get_imageSetID().toString() + '\\' + level.toString() + '\\' + y.toString() + '_' + x.toString(); +} + + +// wwtlib.DistanceCalc +// +// This was originally defined in ToastTile.cs but we moved it to sort out the +// dependency graph. + +export function DistanceCalc() { } + +DistanceCalc.lineToPoint = function (l0, l1, p) { + var v = Vector3d.subtractVectors(l1, l0); + var w = Vector3d.subtractVectors(p, l0); + var dist = Vector3d.cross(w, v).length() / v.length(); + return dist; +}; + +DistanceCalc.getUVFromInnerPoint = function (ul, ur, ll, lr, pnt) { + ul.normalize(); + ur.normalize(); + ll.normalize(); + lr.normalize(); + pnt.normalize(); + var dUpper = DistanceCalc.lineToPoint(ul, ur, pnt); + var dLower = DistanceCalc.lineToPoint(ll, lr, pnt); + var dVert = dUpper + dLower; + var dRight = DistanceCalc.lineToPoint(ur, lr, pnt); + var dLeft = DistanceCalc.lineToPoint(ul, ll, pnt); + var dHoriz = dRight + dLeft; + return Vector2d.create(dLeft / dHoriz, dUpper / dVert); +}; + +var DistanceCalc$ = {}; + +registerType("DistanceCalc", [DistanceCalc, DistanceCalc$, null]); + + +// wwtlib.DialogResult + +export var DialogResult = { + OK: 1 +}; + +registerType("DialogResult", DialogResult); +registerEnum("DialogResult", DialogResult); diff --git a/engine/esm/utilities/binary_reader.js b/engine/esm/utilities/binary_reader.js new file mode 100644 index 00000000..1d1861d3 --- /dev/null +++ b/engine/esm/utilities/binary_reader.js @@ -0,0 +1,133 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Reading binary data from a stream. + +import { registerType } from "../typesystem.js"; + + +// wwtlib.BinaryReader + +export function BinaryReader(arraybuf) { + this.position = 0; + this._data = null; + this._data = arraybuf; +} + +BinaryReader.id = 1; + +var BinaryReader$ = { + get_position: function () { + return this.position; + }, + + seek: function (pos) { + this.position = pos; + }, + + seekRelative: function (pos) { + this.position += pos; + }, + + get_length: function () { + return this._data.length; + }, + + get_endOfStream: function () { + return this.position >= this.get_length(); + }, + + readByte: function () { + var result; + result = this._data[this.position]; + this.position += 1; + return result; + }, + + readSByte: function () { + var result; + result = this._data[this.position]; + this.position += 1; + return result; + }, + + readBytes: function (count) { + var buf = new Array(count); + for (var i = 0; i < count; i++) { + buf[i] = this._data[this.position + i]; + } + this.position += count; + return buf; + }, + + readRemainingI16: function (i16Remaining) { + var data = new Float32Array(i16Remaining); + for (var i = 0; i < i16Remaining; i++) { + data[i] = this.readInt16(true); + } + return data; + }, + + readByteString: function (count) { + var data = ''; + for (var i = 0; i < count; i++) { + data += String.fromCharCode(this._data[this.position + i]); + } + this.position += count; + return data; + }, + + readSingle: function () { + var tmp = new Uint8Array(4); + tmp[0] = this._data[this.position]; + tmp[1] = this._data[this.position + 1]; + tmp[2] = this._data[this.position + 2]; + tmp[3] = this._data[this.position + 3]; + var result = new Float32Array(tmp.buffer, 0, 1)[0]; + this.position += 4; + return result; + }, + + readUInt32: function () { + var result = (this._data[this.position] + (this._data[this.position + 1] << 8) + (this._data[this.position + 2] << 16) + (this._data[this.position + 3] << 24)); + this.position += 4; + return result; + }, + + readUInt16: function () { + var result = (this._data[this.position] + (this._data[this.position + 1] << 8)); + this.position += 2; + return result; + }, + + readUInt16LittleEndian: function () { + var result = ((this._data[this.position] << 8) + this._data[this.position + 1]); + this.position += 2; + return result; + }, + + readInt16: function (littleEndian) { + var result = (littleEndian) ? this.readUInt16LittleEndian() : this.readUInt16(); + if (!!(result & 0x8000)) { + return (-((result - 1) ^ 0xFFFF)); + } + return result; + }, + + readInt32: function () { + var result = this.readUInt32(); + if (!!(result & 0x80000000)) { + return (-((result - 1) ^ 0xFFFFFFFF)); + } + return result; + }, + + readInt64: function () { + this.position += 8; + return BinaryReader.id++; + }, + + close: function () { } +}; + +registerType("BinaryReader", [BinaryReader, BinaryReader$, null]); diff --git a/engine/esm/utilities/bitmap.js b/engine/esm/utilities/bitmap.js new file mode 100644 index 00000000..3edc5704 --- /dev/null +++ b/engine/esm/utilities/bitmap.js @@ -0,0 +1,51 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A basic bitmap class. + +import { registerType } from "../typesystem.js"; +import { tilePrepDevice } from "../render_globals.js"; +import { WEBGL } from "../graphics/webgl_constants.js"; +import { Texture } from "../graphics/texture.js"; + + +// wwtlib.Bitmap + +export function Bitmap() { + this.width = 0; + this.height = 0; +} + +Bitmap.create = function (width, height) { + height = Texture.fitPowerOfTwo(height); + width = Texture.fitPowerOfTwo(width); + var bmp = new Bitmap(); + bmp.height = height; + bmp.width = width; + bmp._buffer = new Uint8Array(width * height * 4); + return bmp; +}; + +var Bitmap$ = { + setPixel: function (x, y, r, g, b, a) { + var index = (x + y * this.width) * 4; + this._buffer[index++] = r; + this._buffer[index++] = g; + this._buffer[index++] = b; + this._buffer[index++] = a; + }, + + getTexture: function () { + var tex = tilePrepDevice.createTexture(); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, tex); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_S, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_WRAP_T, WEBGL.CLAMP_TO_EDGE); + tilePrepDevice.texImage2D(WEBGL.TEXTURE_2D, 0, WEBGL.RGBA, this.width, this.height, 0, WEBGL.RGBA, WEBGL.UNSIGNED_BYTE, this._buffer); + tilePrepDevice.texParameteri(WEBGL.TEXTURE_2D, WEBGL.TEXTURE_MIN_FILTER, WEBGL.LINEAR_MIPMAP_NEAREST); + tilePrepDevice.generateMipmap(WEBGL.TEXTURE_2D); + tilePrepDevice.bindTexture(WEBGL.TEXTURE_2D, null); + return tex; + } +}; + +registerType("Bitmap", [Bitmap, Bitmap$, null]); diff --git a/engine/esm/utilities/color_picker.js b/engine/esm/utilities/color_picker.js new file mode 100644 index 00000000..0744584d --- /dev/null +++ b/engine/esm/utilities/color_picker.js @@ -0,0 +1,42 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A color picker UI. + +import { registerType } from "../typesystem.js"; +import { Color, Colors } from "../color.js"; +import { globalScriptInterface } from "../data_globals.js"; + + +// wwtlib.ColorPicker + +export function ColorPicker() { + this.callBack = null; + this.color = Colors.get_white(); +} + +var ColorPicker$ = { + nonMenuClick: function (e) { }, + + show: function (e) { + globalScriptInterface.showColorPicker(this, e); + }, + + getColorFromClick: function (e) { + var image = document.getElementById('colorhex'); + var canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(image, 0, 0); + var pixels = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data; + this.color = Color.fromArgb(pixels[3], pixels[0], pixels[1], pixels[2]); + return this.color; + }, + + pickColor: function (e) { + this.callBack(this.color); + } +}; + +registerType("ColorPicker", [ColorPicker, ColorPicker$, null]); diff --git a/engine/esm/utilities/context_menu_strip.js b/engine/esm/utilities/context_menu_strip.js new file mode 100644 index 00000000..7df6c3b1 --- /dev/null +++ b/engine/esm/utilities/context_menu_strip.js @@ -0,0 +1,151 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Context menu items + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; +import { Vector2d } from "../double3d.js"; + + +// wwtlib.ContextMenuStrip + +export function ContextMenuStrip() { + this.items = []; +} + +var ContextMenuStrip$ = { + _dispose: function () { }, + + _nonMenuClick: function (e) { + var menu = document.getElementById('contextmenu'); + menu.style.display = 'none'; + window.removeEventListener('click', ss.bind('_nonMenuClick', this), false); + var popup = document.getElementById('popoutmenu'); + while (popup.firstChild != null) { + popup.removeChild(popup.firstChild); + } + popup.style.display = 'none'; + }, + + _menuItemClicked: function (e) { + var me = e.currentTarget; + me.itemTag.click(me.itemTag, new ss.EventArgs()); + }, + + _show: function (position) { + var menu = document.getElementById('contextmenu'); + while (menu.firstChild != null) { + menu.removeChild(menu.firstChild); + } + menu.className = 'contextmenu'; + menu.style.display = 'block'; + menu.style.left = position.x.toString() + 'px'; + menu.style.top = position.y.toString() + 'px'; + window.addEventListener('click', ss.bind('_nonMenuClick', this), true); + var $enum1 = ss.enumerate(this.items); + while ($enum1.moveNext()) { + var item = $enum1.current; + if (item.visible) { + var md = document.createElement('div'); + if (item.dropDownItems.length > 0) { + md.className = 'contextmenuitem submenu'; + } + else { + if (item.checked) { + md.className = 'contextmenuitem checkedmenu'; + } + else { + md.className = 'contextmenuitem'; + } + } + md.innerText = item.name; + var it = md; + it.itemTag = item; + md.addEventListener('mouseover', ss.bind('_openSubMenu', this), false); + if (item.click != null) { + md.addEventListener('click', ss.bind('_menuItemClicked', this), false); + } + menu.appendChild(md); + } + } + }, + + _openSubMenu: function (e) { + var me = e.currentTarget; + var child = me.itemTag; + var menu = document.getElementById('popoutmenu'); + while (menu.firstChild != null) { + menu.removeChild(menu.firstChild); + } + menu.style.display = 'none'; + if (!child.dropDownItems.length) { + return; + } + var position = new Vector2d(); + position.x = e.currentTarget.parentNode.offsetLeft + e.currentTarget.parentNode.clientWidth; + position.y = e.currentTarget.parentNode.offsetTop + e.currentTarget.offsetTop; + menu.className = 'contextmenu'; + menu.style.display = 'block'; + menu.style.left = position.x.toString() + 'px'; + menu.style.top = position.y.toString() + 'px'; + window.addEventListener('click', ss.bind('_nonMenuClick', this), true); + var $enum1 = ss.enumerate(child.dropDownItems); + while ($enum1.moveNext()) { + var item = $enum1.current; + if (item.visible) { + var md = document.createElement('div'); + md.className = (item.checked) ? 'contextmenuitem checkedmenu' : 'contextmenuitem'; + md.innerText = item.name; + var it = md; + it.itemTag = item; + md.addEventListener('click', ss.bind('_menuItemClicked', this), false); + menu.appendChild(md); + } + } + } +}; + +registerType("ContextMenuStrip", [ContextMenuStrip, ContextMenuStrip$, null]); + + +// wwtlib.ToolStripMenuItem + +export function ToolStripMenuItem() { + this.tag = null; + this.dropDownItems = []; + this.checked = false; + this.enabled = true; + this.visible = true; +} + +ToolStripMenuItem.create = function (name) { + var tsmi = new ToolStripMenuItem(); + tsmi.name = name; + return tsmi; +}; + +var ToolStripMenuItem$ = {}; + +registerType("ToolStripMenuItem", [ToolStripMenuItem, ToolStripMenuItem$, null]); + + +// wwtlib.ToolStripSeparator + +export function ToolStripSeparator() { + ToolStripMenuItem.call(this); + this.name = '--------------------------------------'; +} + +var ToolStripSeparator$ = {}; + +registerType("ToolStripSeparator", [ToolStripSeparator, ToolStripSeparator$, ToolStripMenuItem]); + + +// wwtlib.TagMe + +export function TagMe() { } + +var TagMe$ = {}; + +registerType("TagMe", [TagMe, TagMe$, null]); diff --git a/engine/esm/utilities/dialog.js b/engine/esm/utilities/dialog.js new file mode 100644 index 00000000..48041829 --- /dev/null +++ b/engine/esm/utilities/dialog.js @@ -0,0 +1,30 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Types corresponding to popup dialog boxes. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; + + +// wwtlib.Dialog + +export function Dialog() { } + +var Dialog$ = { + add_showDialogHook: function (value) { + this.__showDialogHook = ss.bindAdd(this.__showDialogHook, value); + }, + + remove_showDialogHook: function (value) { + this.__showDialogHook = ss.bindSub(this.__showDialogHook, value); + }, + + show: function (dialogArgs, e) { + if (this.__showDialogHook != null) { + this.__showDialogHook(dialogArgs, e); + } + } +}; + +registerType("Dialog", [Dialog, Dialog$, null]); diff --git a/engine/esm/utilities/histogram.js b/engine/esm/utilities/histogram.js new file mode 100644 index 00000000..14012abb --- /dev/null +++ b/engine/esm/utilities/histogram.js @@ -0,0 +1,276 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// UI for viewing and manipulating a data histogram. + +import { ss } from "../ss.js"; +import { registerType } from "../typesystem.js"; +import { Vector2d } from "../double3d.js"; +import { useGlVersion2, tileCacheGetTile } from "../render_globals.js"; +import { Mouse } from "../util.js"; +import { FitsImageJs } from "../layers/fits_image_js.js"; + + +// wwtlib.Histogram + +export function Histogram() { + this.image = null; + this.layer = null; + this.tile = null; + this._dropDown = null; + this._downPosition = 0; + this._lowPosition = 0; + this._highPosition = 255; + this._center = 127; + this._ignoreNextClick = false; + this._dragType = 4; + this._updated = false; + this.selectedCurveStyle = 0; +} + +Histogram.updateImage = function (isl, z) { + if (!useGlVersion2) { + var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); + var Tile = tileCacheGetTile(0, 0, 0, isl.get_imageSet(), null); + Tile.texture2d = image.getBitmap().getTexture(); + } +}; + +Histogram.updateScale = function (isl, scale, low, hi) { + isl.get_imageSet().get_fitsProperties().scaleType = scale; + isl.get_imageSet().get_fitsProperties().lowerCut = low; + isl.get_imageSet().get_fitsProperties().upperCut = hi; + if (!useGlVersion2) { + var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); + var Tile = tileCacheGetTile(0, 0, 0, isl.get_imageSet(), null); + Tile.texture2d = image.getBitmap().getTexture(); + } +}; + +Histogram.updateColorMapper = function (isl, colorMapperName) { + isl.get_imageSet().get_fitsProperties().colorMapName = colorMapperName; + if (!useGlVersion2) { + var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); + var Tile = tileCacheGetTile(0, 0, 0, isl.get_imageSet(), null); + Tile.texture2d = image.getBitmap().getTexture(); + } +}; + +var Histogram$ = { + close: function (e) { + var menu = document.getElementById('histogram'); + var closeBtn = document.getElementById('histogramClose'); + menu.style.display = 'none'; + window.removeEventListener('click', ss.bind('close', this), true); + var image = document.getElementById('graph'); + image.removeEventListener('mousedown', ss.bind('onPointerDown', this), false); + image.removeEventListener('mousemove', ss.bind('onPointerMove', this), false); + image.removeEventListener('mouseup', ss.bind('onPointerUp', this), false); + this._dropDown.removeEventListener('change', ss.bind('curveStyleSelected', this), false); + this._dropDown.removeEventListener('click', ss.bind('ignoreMe', this), true); + }, + + show: function (position) { + this.tile = tileCacheGetTile(0, 0, 0, this.layer.get_imageSet(), null); + var picker = document.getElementById('histogram'); + var closeBtn = document.getElementById('histogramClose'); + picker.style.display = 'block'; + picker.style.left = position.x.toString() + 'px'; + picker.style.top = position.y.toString() + 'px'; + this.selectedCurveStyle = this.layer.get_imageSet().get_fitsProperties().scaleType; + this._dropDown = document.getElementById('ScaleTypePicker'); + this._dropDown.addEventListener('change', ss.bind('curveStyleSelected', this), false); + this._dropDown.addEventListener('click', ss.bind('ignoreMe', this), true); + var canvas = document.getElementById('graph'); + canvas.addEventListener('pointerdown', ss.bind('onPointerDown', this), false); + canvas.addEventListener('pointermove', ss.bind('onPointerMove', this), false); + canvas.addEventListener('pointerup', ss.bind('onPointerUp', this), false); + closeBtn.addEventListener('click', ss.bind('close', this), true); + this.draw(); + }, + + ignoreMe: function (e) { + this._ignoreNextClick = true; + }, + + curveStyleSelected: function (e) { + this.selectedCurveStyle = this._dropDown.selectedIndex; + this.setUpdateTimer(); + this.layer.get_imageSet().get_fitsProperties().scaleType = this.selectedCurveStyle; + this.draw(); + this._ignoreNextClick = true; + }, + + onPointerDown: function (e) { + var canvas = document.getElementById('graph'); + var x = Mouse.offsetX(canvas, e); + var y = Mouse.offsetY(canvas, e); + canvas.setPointerCapture(e.pointerId); + if ((Math.abs(x - this._center) < 10) && Math.abs(y - 75) < 10) { + this._dragType = 3; + } else if (Math.abs(x - this._lowPosition) < 10) { + this._dragType = 0; + } else if (Math.abs(x - this._highPosition) < 10) { + this._dragType = 1; + } else { + this._dragType = 2; + this._downPosition = Math.min(255, Math.max(0, x)); + this.draw(); + } + e.cancelBubble = true; + }, + + onPointerMove: function (e) { + var canvas = document.getElementById('graph'); + var x = Mouse.offsetX(canvas, e); + var y = Mouse.offsetY(canvas, e); + switch (this._dragType) { + case 0: + this._lowPosition = Math.min(255, Math.max(0, x)); + break; + case 1: + this._highPosition = Math.min(255, Math.max(0, x)); + break; + case 2: + this._lowPosition = this._downPosition; + this._highPosition = Math.min(255, Math.max(0, x)); + break; + case 3: + var hWidth = Math.abs(this._highPosition - this._lowPosition) / 2; + var adCenter = Math.min(255 - hWidth, Math.max(hWidth, x)); + var moved = this._center - adCenter; + this._lowPosition -= moved; + this._highPosition -= moved; + break; + case 4: + return; + default: + break; + } + this._center = (this._lowPosition + this._highPosition) / 2; + this.draw(); + var factor = (this.layer.get_imageSet().get_fitsProperties().maxVal - this.layer.get_imageSet().get_fitsProperties().minVal) / 256; + var low = this.layer.get_imageSet().get_fitsProperties().minVal + (this._lowPosition * factor); + var hi = this.layer.get_imageSet().get_fitsProperties().minVal + (this._highPosition * factor); + this.setUpdateTimer(); + this.layer.get_imageSet().get_fitsProperties().upperCut = hi; + this.layer.get_imageSet().get_fitsProperties().lowerCut = low; + this.layer.get_imageSet().get_fitsProperties().scaleType = this.selectedCurveStyle; + e.cancelBubble = true; + }, + + onPointerUp: function (e) { + e.srcElement.releasePointerCapture(e.pointerId); + if (this._dragType !== 4) { + this._dragType = 4; + this.setUpdateTimer(); + this._ignoreNextClick = true; + } + e.cancelBubble = true; + }, + + setUpdateTimer: function () { + var $this = this; + + if (!useGlVersion2) { + setTimeout(function () { + $this.update(); + }, 500); + this._updated = false; + } + }, + + update: function () { + if (this._updated) { + return; + } + if (ss.canCast(this.image, FitsImageJs)) { + var factor = (this.layer.get_imageSet().get_fitsProperties().maxVal - this.layer.get_imageSet().get_fitsProperties().minVal) / 256; + var low = this.layer.get_imageSet().get_fitsProperties().minVal + (this._lowPosition * factor); + var hi = this.layer.get_imageSet().get_fitsProperties().minVal + (this._highPosition * factor); + this.tile.texture2d = (this.image).getScaledBitmap(low, hi, this.selectedCurveStyle, 0, null).getTexture(); + } + this._updated = true; + }, + + draw: function () { + var canvas = document.getElementById('graph'); + var ctx = canvas.getContext('2d'); + if (this.image != null) { + this.image.drawHistogram(ctx); + } + var red = 'rgba(255,0,0,255)'; + var green = 'rgba(0,255,0,255)'; + var blue = 'rgba(0,0,255,255)'; + ctx.strokeStyle = red; + ctx.beginPath(); + ctx.moveTo(this._lowPosition, 0); + ctx.lineTo(this._lowPosition, 150); + ctx.stroke(); + ctx.strokeStyle = green; + ctx.beginPath(); + ctx.moveTo(this._highPosition, 0); + ctx.lineTo(this._highPosition, 150); + ctx.stroke(); + ctx.strokeStyle = blue; + ctx.beginPath(); + ctx.arc(this._center, 75, 10, 0, Math.PI * 2, false); + ctx.closePath(); + ctx.stroke(); + var Curve = []; + switch (this.selectedCurveStyle) { + case 0: // linear + Curve.length = 0; + Curve.push(Vector2d.create(this._lowPosition, 150)); + Curve.push(Vector2d.create(this._highPosition, 0)); + break; + case 1: // log + Curve.length = 0; + var factor = 150 / Math.log(255); + var diff = (this._highPosition - this._lowPosition); + var jump = (diff < 0) ? -1 : 1; + var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); + var val = 1E-06; + for (var i = this._lowPosition; i !== this._highPosition; i += jump) { + Curve.push(Vector2d.create(i, (150 - (Math.log(val) * factor)))); + val += step; + } + break; + case 2: // power 2 + Curve.length = 0; + var factor = 150 / Math.pow(255, 2); + var diff = (this._highPosition - this._lowPosition); + var jump = (diff < 0) ? -1 : 1; + var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); + var val = 1E-06; + for (var i = this._lowPosition; i !== this._highPosition; i += jump) { + Curve.push(Vector2d.create(i, (150 - (Math.pow(val, 2) * factor)))); + val += step; + } + break; + case 3: // square root + Curve.length = 0; + var factor = 150 / Math.sqrt(255); + var diff = (this._highPosition - this._lowPosition); + var jump = (diff < 0) ? -1 : 1; + var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); + var val = 1E-06; + for (var i = this._lowPosition; i !== this._highPosition; i += jump) { + Curve.push(Vector2d.create(i, (150 - (Math.sqrt(val) * factor)))); + val += step; + } + break; + } + if (Curve.length > 1) { + ctx.beginPath(); + ctx.strokeStyle = blue; + ctx.moveTo(Curve[0].x, Curve[0].y); + for (var i = 1; i < Curve.length; i++) { + ctx.lineTo(Curve[i].x, Curve[i].y); + } + ctx.stroke(); + } + } +}; + +registerType("Histogram", [Histogram, Histogram$, null]); diff --git a/engine/esm/utilities/simple_input.js b/engine/esm/utilities/simple_input.js new file mode 100644 index 00000000..96dd4bc8 --- /dev/null +++ b/engine/esm/utilities/simple_input.js @@ -0,0 +1,88 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A manually-built HTML based input dialog. + +import { registerType } from "../typesystem.js"; +import { ss } from "../ss.js"; + + +// wwtlib.SimpleInput + +export function SimpleInput(title, label, text, v3) { + this.title = 'Tile'; + this.label = 'Enter Text Below'; + this.text = ''; + this._textElement = null; + this._ignoreNextClick = false; + this.title = title; + this.label = label; + this.text = text; +} + +var SimpleInput$ = { + showDialog: function () { + return 1; + }, + + nonMenuClick: function (e) { + if (!this._ignoreNextClick) { + this._close(); + } + this._ignoreNextClick = false; + }, + + show: function (position, callback) { + var simpleInputElement = document.getElementById('simpleinput'); + var modalElement = document.getElementById('simplemodal'); + modalElement.style.display = 'block'; + simpleInputElement.style.display = 'block'; + simpleInputElement.style.marginLeft = position.x.toString() + 'px'; + simpleInputElement.style.marginTop = position.y.toString() + 'px'; + this._textElement = document.getElementById('inputtext'); + this._textElement.value = this.text; + var titleDiv = document.getElementById('simpletitle'); + var labelDiv = document.getElementById('inputlabel'); + titleDiv.innerText = this.title; + labelDiv.innerText = this.label; + this._textElement.addEventListener('change', ss.bind('textChanged', this), false); + this._textElement.addEventListener('click', ss.bind('ignoreMe', this), true); + var okButton = document.getElementById('simpleinputok'); + var cancelButton = document.getElementById('simpleinputcancel'); + okButton.addEventListener('click', ss.bind('okClicked', this), false); + cancelButton.addEventListener('click', ss.bind('cancelClicked', this), false); + this._okCallback = callback; + }, + + okClicked: function (e) { + this._close(); + if (this._okCallback != null) { + this._okCallback(); + } + }, + + cancelClicked: function (e) { + this._close(); + }, + + _close: function () { + var simpleInputElement = document.getElementById('simplemodal'); + simpleInputElement.style.display = 'none'; + this._textElement.removeEventListener('change', ss.bind('textChanged', this), false); + var okButton = document.getElementById('simpleinputok'); + var cancelButton = document.getElementById('simpleinputcancel'); + okButton.removeEventListener('click', ss.bind('okClicked', this), false); + cancelButton.removeEventListener('click', ss.bind('cancelClicked', this), false); + }, + + ignoreMe: function (e) { + this._ignoreNextClick = true; + }, + + textChanged: function (e) { + this.text = this._textElement.value; + this._ignoreNextClick = true; + } +}; + +registerType("SimpleInput", [SimpleInput, SimpleInput$, null]); diff --git a/engine/esm/utilities/xml_text_writer.js b/engine/esm/utilities/xml_text_writer.js new file mode 100644 index 00000000..f10fa4e9 --- /dev/null +++ b/engine/esm/utilities/xml_text_writer.js @@ -0,0 +1,138 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Writing XML. + +import { registerType, registerEnum } from "../typesystem.js"; +import { ss } from "../ss.js"; + + +// wwtlib.Formatting + +export var Formatting = { + indented: 1 +}; + +registerType("Formatting", Formatting); +registerEnum("Formatting", Formatting); + + +// wwtlib.XmlTextWriter + +export function XmlTextWriter() { + this.body = "\r\n"; + this.formatting = 1; + this._elementStack = new ss.Stack(); + this._pending = false; + this._currentName = ''; + this._attributes = {}; + this._value = ''; +} + +var XmlTextWriter$ = { + _pushNewElement: function (name) { + //write pending element and attributes + this._writePending(false); + + //Push new attribute on to stack + this._elementStack.push(name); + + //setup pending structures + this._pending = true; + this._currentName = name; + }, + + _writePending: function (fullClose) { + var closed = true; + if (this._pending) { + for (var i = 1; i < this._elementStack.count; i++) { + this.body += ' '; + } + this.body += '<' + this._currentName; + if (ss.keyCount(this._attributes) > 0) { + var $enum1 = ss.enumerate(ss.keys(this._attributes)); + while ($enum1.moveNext()) { + var key = $enum1.current; + this.body += ss.format(' {0}="{1}"', key, this._attributes[key]); + } + } + if (!ss.emptyString(this._value)) { + this.body += '>'; + closed = false; + if (!ss.emptyString(this._value)) { + this.body += this._value; + } + } + else { + if (fullClose) { + this.body += ' />\r\n'; + closed = true; + } + else { + this.body += '>\r\n'; + } + } + this._pending = false; + this._currentName = ''; + this._value = ''; + this._attributes = {}; + return closed; + } + return false; + }, + + _writeProcessingInstruction: function (v1, v2) { }, + + _writeStartElement: function (name) { + this._pushNewElement(name); + }, + + _writeAttributeString: function (key, value) { + if (value != null) { + this._attributes[key] = ss.replaceString(value.toString(), '&', '&'); + } else { + this._attributes[key] = ''; + } + }, + + _writeEndElement: function () { + if (!this._writePending(true)) { + for (var i = 1; i < this._elementStack.count; i++) { + this.body += ' '; + } + this.body += ss.format('\r\n', this._elementStack.pop()); + } else { + this._elementStack.pop(); + } + }, + + _writeString: function (text) { + this._value = ss.replaceString(text, '&', '&'); + }, + + _writeFullEndElement: function () { + this._writePending(false); + for (var i = 1; i < this._elementStack.count; i++) { + this.body += ' '; + } + this.body += ss.format('\r\n', this._elementStack.pop()); + }, + + _close: function () { }, + + _writeElementString: function (name, value) { + this._writeStartElement(name); + this._writeValue(ss.replaceString(value, '&', '&')); + this._writeEndElement(); + }, + + _writeValue: function (val) { + this._value = ss.replaceString(val, '&', '&'); + }, + + _writeCData: function (htmlDescription) { + this._value = ss.format('', htmlDescription); + } +}; + +registerType("XmlTextWriter", [XmlTextWriter, XmlTextWriter$, null]); diff --git a/engine/esm/video_output_type.js b/engine/esm/video_output_type.js new file mode 100644 index 00000000..94d31c44 --- /dev/null +++ b/engine/esm/video_output_type.js @@ -0,0 +1,27 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Specifications of a requested video output format. + +import { registerType } from "./typesystem.js"; + + +// wwtlib.VideoOutputType + +export function VideoOutputType(width, height, fps, format, waitDownload) { + this.fps = 0; + this.width = 0; + this.height = 0; + this.totalFrames = 0; + this.waitDownload = false; + this.format = 'image/jpeg'; + this.width = width; + this.height = height; + this.fps = fps; + this.format = format; + this.waitDownload = waitDownload; +} + +var VideoOutputType$ = {}; + +registerType("VideoOutputType", [VideoOutputType, VideoOutputType$, null]); diff --git a/engine/esm/view_mover.js b/engine/esm/view_mover.js new file mode 100644 index 00000000..bf7ded7b --- /dev/null +++ b/engine/esm/view_mover.js @@ -0,0 +1,231 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Moving the view around. +// +// These types were originally implemented in `IViewMover.cs`, but we merged the +// `IViewMover` interface into `interfaces.js`, since currently in the JS +// implementation the interfaces don't contain any content. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Util } from "./baseutil.js"; +import { CameraParameters } from "./camera_parameters.js"; +import { IViewMover } from "./interfaces.js"; +import { globalRenderContext } from "./render_globals.js"; +import { Settings } from "./settings.js"; +import { SpaceTimeController } from "./space_time_controller.js"; + + +// wwtlib.ViewMoverKenBurnsStyle +// +// This was defined in `IViewMover.cs`, which we've folded into `interfaces.js`. + +export function ViewMoverKenBurnsStyle(from, to, time, fromDateTime, toDateTime, type) { + this.interpolationType = 0; + this.fastDirectionMove = false; + this._toTargetTime = 0; + this._dateTimeSpan = 0; + this._complete = false; + this._midpointFired = false; + this.interpolationType = type; + if (Math.abs(from.lng - to.lng) > 180) { + if (from.lng > to.lng) { + from.lng -= 360; + } else { + from.lng += 360; + } + } + this._fromDateTime = fromDateTime; + this._toDateTime = toDateTime; + this._dateTimeSpan = toDateTime - fromDateTime; + this._from = from.copy(); + this._to = to.copy(); + this._fromTime = SpaceTimeController.get_metaNow(); + this._toTargetTime = time; +} + +var ViewMoverKenBurnsStyle$ = { + get_complete: function () { + return this._complete; + }, + + get_currentPosition: function () { + var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; + var elapsedSeconds = (elapsed) / 1000; + var alpha = elapsedSeconds / this._toTargetTime; + if (!this._midpointFired && alpha >= 0.5) { + this._midpointFired = true; + if (this._midpoint != null) { + this._midpoint(); + } + } + if (alpha >= 1) { + alpha = 1; + this._complete = true; + return this._to.copy(); + } + if (Settings.get_active().get_galacticMode() && globalRenderContext.space) { + return CameraParameters.interpolateGreatCircle(this._from, this._to, alpha, this.interpolationType, this.fastDirectionMove); + } + return CameraParameters.interpolate(this._from, this._to, alpha, this.interpolationType, this.fastDirectionMove); + }, + + get_currentDateTime: function () { + var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; + var elapsedSeconds = (elapsed) / 1000; + var alpha = elapsedSeconds / this._toTargetTime; + var delta = this._dateTimeSpan * alpha; + var retDate = new Date(this._fromDateTime.getTime() + ss.truncate(delta)); + return retDate; + }, + + get_midpoint: function () { + return this._midpoint; + }, + + set_midpoint: function (value) { + this._midpoint = value; + return value; + }, + + get_moveTime: function () { + return this._toTargetTime; + } +}; + +registerType("ViewMoverKenBurnsStyle", [ViewMoverKenBurnsStyle, ViewMoverKenBurnsStyle$, null, IViewMover]); + + +// wwtlib.ViewMoverSlew +// +// This was defined in `IViewMover.cs`, which we've folded into `interfaces.js`. + +export function ViewMoverSlew() { + this._upTargetTime = 0; + this._downTargetTime = 0; + this._toTargetTime = 0; + this._upTimeFactor = 0.6; + this._downTimeFactor = 0.6; + this._travelTimeFactor = 7; + this._midpointFired = false; + this._complete = false; +} + +ViewMoverSlew.create = function (from, to) { + var temp = new ViewMoverSlew(); + temp.init(from, to); + return temp; +}; + +ViewMoverSlew.createUpDown = function (from, to, upDowFactor) { + var temp = new ViewMoverSlew(); + temp._upTimeFactor = temp._downTimeFactor = upDowFactor; + temp.init(from.copy(), to.copy()); + return temp; +}; + +var ViewMoverSlew$ = { + init: function (from, to) { + if (Math.abs(from.lng - to.lng) > 180) { + if (from.lng > to.lng) { + from.lng -= 360; + } + else { + from.lng += 360; + } + } + if (to.zoom <= 0) { + to.zoom = 360; + } + if (from.zoom <= 0) { + from.zoom = 360; + } + this._from = from; + this._to = to; + this._fromTime = SpaceTimeController.get_metaNow(); + var zoomUpTarget = 360; + var travelTime; + var lngDist = Math.abs(from.lng - to.lng); + var latDist = Math.abs(from.lat - to.lat); + var distance = Math.sqrt(latDist * latDist + lngDist * lngDist); + zoomUpTarget = (distance / 3) * 20; + if (zoomUpTarget > 360) { + zoomUpTarget = 360; + } + if (zoomUpTarget < from.zoom) { + zoomUpTarget = from.zoom; + } + travelTime = (distance / 180) * (360 / zoomUpTarget) * this._travelTimeFactor; + var rotateTime = Math.max(Math.abs(from.angle - to.angle), Math.abs(from.rotation - to.rotation)); + var logDistUp = Math.max(Math.abs(Util.logN(zoomUpTarget, 2) - Util.logN(from.zoom, 2)), rotateTime); + this._upTargetTime = this._upTimeFactor * logDistUp; + this._downTargetTime = this._upTargetTime + travelTime; + var logDistDown = Math.abs(Util.logN(zoomUpTarget, 2) - Util.logN(to.zoom, 2)); + this._toTargetTime = this._downTargetTime + Math.max((this._downTimeFactor * logDistDown), rotateTime); + this._fromTop = from.copy(); + this._fromTop.zoom = zoomUpTarget; + this._fromTop.angle = (from.angle + to.angle) / 2; + this._fromTop.rotation = (from.rotation + to.rotation) / 2; + this._toTop = to.copy(); + this._toTop.zoom = this._fromTop.zoom; + this._toTop.angle = this._fromTop.angle; + this._toTop.rotation = this._fromTop.rotation; + }, + + get_complete: function () { + return this._complete; + }, + + get_currentPosition: function () { + var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; + var elapsedSeconds = (elapsed) / 1000; + if (elapsedSeconds < this._upTargetTime) { + // Log interpolate from from to fromTop + return CameraParameters.interpolate(this._from, this._fromTop, elapsedSeconds / this._upTargetTime, 3, false); + } else if (elapsedSeconds < this._downTargetTime) { + elapsedSeconds -= this._upTargetTime; + if (Settings.get_active().get_galacticMode() && globalRenderContext.space) { + return CameraParameters.interpolateGreatCircle(this._fromTop, this._toTop, elapsedSeconds / (this._downTargetTime - this._upTargetTime), 3, false); + } + // interpolate linear fromTop and toTop + return CameraParameters.interpolate(this._fromTop, this._toTop, elapsedSeconds / (this._downTargetTime - this._upTargetTime), 3, false); + } else { + if (!this._midpointFired) { + this._midpointFired = true; + if (this._midpoint != null) { + this._midpoint(); + } + } + elapsedSeconds -= this._downTargetTime; + // Interpolate log from toTop and to + var alpha = elapsedSeconds / (this._toTargetTime - this._downTargetTime); + if (alpha > 1) { + alpha = 1; + this._complete = true; + return this._to.copy(); + } + return CameraParameters.interpolate(this._toTop, this._to, alpha, 3, false); + } + }, + + get_currentDateTime: function () { + SpaceTimeController.updateClock(); + return SpaceTimeController.get_now(); + }, + + get_midpoint: function () { + return this._midpoint; + }, + + set_midpoint: function (value) { + this._midpoint = value; + return value; + }, + + get_moveTime: function () { + return this._toTargetTime; + } +}; + +registerType("ViewMoverSlew", [ViewMoverSlew, ViewMoverSlew$, null, IViewMover]); diff --git a/engine/esm/viz_layer.js b/engine/esm/viz_layer.js new file mode 100644 index 00000000..54c0b864 --- /dev/null +++ b/engine/esm/viz_layer.js @@ -0,0 +1,103 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// A layer displaying catalog data? This type is unused in the WWT engine, but +// we preserve it because it is exported in the API. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { Vector3d } from "./double3d.js"; +import { DataItem } from "./graphics/primitives3d.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Coordinates } from "./coordinates.js"; + + +// wwtlib.VizLayer + +export function VizLayer() { + this.table = []; + this.items = []; + this._imageReady = false; + this._dateColumn = 0; + this._latColumn = 1; + this._lngColumn = 2; + this._depthColumn = 3; + this._magColumn = 4; +} + +VizLayer.earthRadius = 6371000; + +var VizLayer$ = { + load: function (data) { + var $this = this; + + var lines = data.split('\r\n'); + this._starProfile = document.createElement('img'); + this._starProfile.addEventListener('load', function (e) { + $this._imageReady = true; + }, false); + this._starProfile.src = URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png'); + var gotHeader = false; + var $enum1 = ss.enumerate(lines); + while ($enum1.moveNext()) { + var line = $enum1.current; + if (gotHeader) { + this.table.push(line.split('\t')); + } + else { + this.header = line.split('\t'); + gotHeader = true; + } + } + }, + + prepare: function () { + this._worldList = new Array(this.table.length); + this._transformedList = new Array(this.table.length); + var index = 0; + var $enum1 = ss.enumerate(this.table); + while ($enum1.moveNext()) { + var row = $enum1.current; + var item = new DataItem(); + item.eventTime = ss.date(row[this._dateColumn]); + var radius = (6371000 - parseFloat(row[this._depthColumn]) * 1000) / 6371000; + item.location = Coordinates.geoTo3dRad(parseFloat(row[this._latColumn]), parseFloat(row[this._lngColumn]) + 180, radius); + item.tranformed = new Vector3d(); + item.size = Math.pow(2, parseFloat(row[this._magColumn])) / 50; + this._worldList[index] = item.location; + this._transformedList[index] = item.tranformed; + this.items.push(item); + index++; + } + }, + + draw: function (renderContext) { + if (!this._imageReady) { + return; + } + renderContext.device.save(); + renderContext.WVP.projectArrayToScreen(this._worldList, this._transformedList); + var ctx = renderContext.device; + ctx.globalAlpha = 0.4; + var width = renderContext.width; + var height = renderContext.height; + var viewPoint = Vector3d.makeCopy(renderContext.get_viewPoint()); + var scaleFactor = renderContext.get_fovScale() / 100; + var $enum1 = ss.enumerate(this.items); + while ($enum1.moveNext()) { + var item = $enum1.current; + if (item.tranformed.z < 1) { + var x = item.tranformed.x; + var y = item.tranformed.y; + var size = 4 * item.size / scaleFactor; + var half = size / 2; + if (x > -half && x < width + half && y > -half && y < height + half) { + ctx.drawImage(this._starProfile, x - size / 2, y - size / 2, size, size); + } + } + } + renderContext.device.restore(); + } +}; + +registerType("VizLayer", [VizLayer, VizLayer$, null]); diff --git a/engine/esm/web_file.js b/engine/esm/web_file.js new file mode 100644 index 00000000..3b7e3330 --- /dev/null +++ b/engine/esm/web_file.js @@ -0,0 +1,141 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Files downloaded over the web. + +import { ss } from "./ss.js"; +import { registerType, registerEnum } from "./typesystem.js"; +import { URLHelpers } from "./url_helpers.js"; + + +// wwtlib.StateType + +export var StateType = { + pending: 0, + received: 1, + error: 2 +}; + +registerType("StateType", StateType); +registerEnum("StateType", StateType); + + +// wwtlib.WebFile + +export function WebFile(url) { + this._state = 0; + this.responseType = ''; + this._triedOnce = false; + this._url = url; +} + +var WebFile$ = { + send: function () { + // There used to be code here to work with IE 8/9, but we're not + // worrying about those anymore. + if (typeof navigator === "undefined") { return; } + this._CORS(); + this.set_state(StateType.pending); + }, + + get_message: function () { + return this._message; + }, + + get_state: function () { + return this._state; + }, + + set_state: function (value) { + this._state = value; + if (this.onStateChange != null) { + this.onStateChange(); + } + return value; + }, + + _loadData: function (textReceived) { + // received data, set the state vars and send statechange + this._data = textReceived; + this.set_state(StateType.received); + }, + + _loadBlob: function (blob) { + // received data, set the state vars and send statechange + this._blobdata = blob; + this.set_state(StateType.received); + }, + + _error: function () { + this._message = ss.format('Error encountered loading {0}', this._url); + this.set_state(StateType.error); + }, + + _timeOut: function () { + this._message = ss.format('Timeout encountered loading {0}', this._url); + this.set_state(StateType.error); + }, + + _CORS: function () { + var $this = this; + + this._xhr = new XMLHttpRequest(); + try { + this._xhr.open('GET', this._url); + if (this.responseType != null) { + this._xhr.responseType = this.responseType; + } + this._xhr.onreadystatechange = function () { + if ($this._xhr.readyState === 4) { + if (!$this._xhr.status) { + if (!$this._triedOnce) { + $this._triedOnce = true; + $this._xhr.onreadystatechange = null; + var new_url = URLHelpers.singleton.activateProxy($this._url); + + // null => don't bother: we know that the proxy won't help + if (new_url !== null) { + $this._url = new_url; + $this._CORS(); + } else { + $this._message = $this._xhr.statusText; + $this.set_state(StateType.error); + } + } + } else { + if ($this._xhr.status >= 400) { + $this._message = $this._xhr.statusText; + $this.set_state(StateType.error); + } else { + if (!$this.responseType) { + $this._loadData($this._xhr.responseText); + } else { + $this._loadBlob($this._xhr.response); + } + } + } + } + }; + this._xhr.send(); + } catch (err) { + this._message = err.message; + this.set_state(StateType.error); + throw err; + } + }, + + getText: function () { + return this._data; + }, + + getBlob: function () { + return this._blobdata; + }, + + getXml: function () { + var xParser = new DOMParser(); + return xParser.parseFromString(this._data, 'text/xml'); + } +}; + +registerType("WebFile", [WebFile, WebFile$, null]); diff --git a/engine/esm/wtml.js b/engine/esm/wtml.js new file mode 100644 index 00000000..a12fb9ab --- /dev/null +++ b/engine/esm/wtml.js @@ -0,0 +1,102 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// Global methods for dealing with WTML folders. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; +import { globalRenderContext } from "./render_globals.js"; +import { set_loadWtmlFile } from "./data_globals.js"; +import { Imageset } from "./imageset.js"; +import { Place } from "./place.js"; +import { Folder } from "./folder.js"; +import { WWTControl } from "./wwt_control.js"; + + +// wwtlib.FolderDownloadAction + +export function FolderDownloadAction(action, loadChildFolders) { + this.loadChildFolders = false; + this._numLoadingFolders = 0; + this._onComplete = action; + this.loadChildFolders = loadChildFolders; +} + +var FolderDownloadAction$ = { + _folderLoaded: function () { + this._numLoadingFolders--; + if (!this._numLoadingFolders) { + this._onComplete(); + } + }, + + startingNewFolderLoad: function (folder) { + var $this = this; + + this._numLoadingFolders++; + folder.childLoadCallback(function () { + Wtml.loadImagesets(folder, $this); + $this._folderLoaded(); + }); + } +}; + +registerType("FolderDownloadAction", [FolderDownloadAction, FolderDownloadAction$, null]); + + +// wwtlib.Wtml + +export function Wtml() { } + +Wtml.getWtmlFile = function (url, complete, loadChildFolders) { + if (loadChildFolders == null) { + loadChildFolders = false; + } + var folder = new Folder(); + folder.set_url(url); + var folderDownloadAction = new FolderDownloadAction(complete, loadChildFolders); + folderDownloadAction.startingNewFolderLoad(folder); + return folder; +}; + +set_loadWtmlFile(Wtml.getWtmlFile); + +Wtml.loadImagesets = function (folder, folderDownloadAction) { + var children = folder.get_children(); + var $enum1 = ss.enumerate(children); + + while ($enum1.moveNext()) { + var child = $enum1.current; + if (ss.canCast(child, Imageset)) { + var imageSet = child; + WWTControl.addImageSetToRepository(imageSet); + } + if (ss.canCast(child, Place)) { + var place = child; + if (place.get_studyImageset() != null) { + WWTControl.addImageSetToRepository(place.get_studyImageset()); + } + if (place.get_backgroundImageset() != null) { + WWTControl.addImageSetToRepository(place.get_backgroundImageset()); + } + } + if (ss.canCast(child, Folder) && folderDownloadAction.loadChildFolders) { + folderDownloadAction.startingNewFolderLoad((child)); + } + } + + if (!ss.emptyString(WWTControl.imageSetName)) { + var name = WWTControl.imageSetName.toLowerCase(); + var $enum2 = ss.enumerate(WWTControl.getImageSets()); + while ($enum2.moveNext()) { + var imageset = $enum2.current; + if (imageset.get_name().toLowerCase() === name) { + globalRenderContext.set_backgroundImageset(imageset); + } + } + } +}; + +var Wtml$ = {}; + +registerType("Wtml", [Wtml, Wtml$, null]); diff --git a/engine/esm/wwt_control.js b/engine/esm/wwt_control.js new file mode 100644 index 00000000..fa79b29b --- /dev/null +++ b/engine/esm/wwt_control.js @@ -0,0 +1,2283 @@ +// Copyright 2023 the .NET Foundation +// Licensed under the MIT License + +// The integrated WWT web engine application. +// +// This is named "WWTControl" due to its heritage of thinking of WWT as a "web +// control" in Microsoft-ese. + +import { ss } from "./ss.js"; +import { registerType } from "./typesystem.js"; + +import { + globalRenderContext, + set_tilePrepDevice, + set_useGl, + set_useGlVersion2, +} from "./render_globals.js"; + +import { + globalScriptInterface, + globalWWTControl, + loadWtmlFile, + set_freestandingMode, + set_globalScriptInterface, +} from "./data_globals.js"; + +import { BlendState } from "./blend_state.js"; +import { Color, Colors } from "./color.js"; +import { URLHelpers } from "./url_helpers.js"; +import { Mouse } from "./util.js"; + +import { + PositionColoredTextured, + Vector3d, + Vector2d, + Matrix3d, + DoubleUtilities, +} from "./double3d.js"; + +import { SimpleLineList } from "./graphics/primitives3d.js"; +import { Sprite2d } from "./graphics/sprite2d.js"; + +import { Annotation } from "./annotation.js"; +import { CameraParameters, SolarSystemObjects } from "./camera_parameters.js"; +import { Constellations } from "./constellations.js"; +import { Coordinates } from "./coordinates.js"; +import { Grids } from "./grids.js"; +import { BandPass, ProjectionType, ImageSetType, Imageset } from "./imageset.js"; +import { MinorPlanets } from "./minor_planets.js"; +import { Classification } from "./place.js"; +import { Planets } from "./planets.js"; +import { Settings } from "./settings.js"; +import { SpaceTimeController } from "./space_time_controller.js"; +import { RenderTriangle } from "./render_triangle.js"; +import { Tile } from "./tile.js"; +import { TileCache } from "./tile_cache.js"; +import { VideoOutputType } from "./video_output_type.js"; +import { UiTools } from "./ui_tools.js"; +import { ViewMoverSlew, ViewMoverKenBurnsStyle } from "./view_mover.js"; + +import { TourPlayer } from "./tours/tour_player.js"; + +import { LayerManager } from "./layers/layer_manager.js"; + +import { TourDocument } from "./tours/tour_document.js"; +import { TourEditTab } from "./tours/tour_edit.js"; + +import { Planets3d } from "./planets_3d.js"; +import { ScriptInterface } from "./script_interface.js"; + + +// wwtlib.WWTControl + +export function WWTControl() { + // In "freestanding" mode, no worldwidetelescope.org resources are + // relied upon. The default screen is black sky, and the 3D solar system + // mode is unavailable because it relies on so many built-in assets. If + // you want to see anything, you need to load it in yourself. + this.freestandingMode = false; + + this.uiController = null; + this._annotations = []; + this._hoverText = ''; + this._hoverTextPoint = new Vector2d(); + this._lastMouseMove = new Date(1900, 1, 0, 0, 0, 0, 0); + this.layers = []; + this._frameCount = 0; + this._zoomMax = 360; + this._zoomMaxSolarSystem = 10000000000000000; + this._zoomMin = 0.001373291015625; + this._zoomMinSolarSystem = 1E-08; + this.constellation = 'UMA'; + this._fadePoints = null; + this.fader = BlendState.create(true, 2000); + this._crossFadeFrame = false; + this._crossFadeTexture = null; + this._sprite = new Sprite2d(); + this.renderType = 2; + this._milkyWayBackground = null; + this.capturingVideo = false; + this._videoBlobReady = null; + this.dumpFrameParams = null; + this._videoBlobQueue = {}; + this._videoQueueIndex = 0; + this._emptyFrames = []; + + // Mouse, touch, gesture controls -- lots of different event listeners for different + // devices and browser support. + this._beginZoom = 1; + this._dragging = false; + this._mouseDown = false; + this._hasTwoTouches = false; + this._lastX = 0; + this._lastY = 0; + this._pointerIds = new Array(2); + this._pinchingZoomRect = new Array(2); + this._moved = false; + + this._foregroundCanvas = null; + this._fgDevice = null; + this._tracking = false; + this._trackingObject = null; + this.sandboxMode = false; + this._solarSystemTrack = 65536; + this._moving = false; + this._targetStudyImageset = null; + this._targetBackgroundImageset = null; + this.tour = null; + this.tourEdit = null; + this._crossHairs = null; +} + +// Note: these fields must remain public because there is JS code in the +// wild that accesses `WWTControl.imageSets`. +WWTControl.imageSets = []; +WWTControl.imageSetName = ''; +WWTControl.showDataLayers = false; +WWTControl._renderNeeded = false; +WWTControl.constellationsFigures = null; +WWTControl.constellationsBoundries = null; +WWTControl.solarSystemObjectsNames = ['Sun', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto', 'Moon', 'Io', 'Europa', 'Ganymede', 'Callisto', 'IoShadow', 'EuropaShadow', 'GanymedeShadow', 'CallistoShadow', 'SunEclipsed', 'Earth', 'Custom', 'Undefined']; + +WWTControl.addImageSetToRepository = function (imagesetToAdd) { + var $enum1 = ss.enumerate(WWTControl.imageSets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_imageSetID() === imagesetToAdd.get_imageSetID()) { + return imageset; + } + } + WWTControl.imageSets.push(imagesetToAdd); + return imagesetToAdd; +}; + +WWTControl.getImageSets = function () { + return WWTControl.imageSets; +}; + +// This parameter does nothing. We keep it to maintain API compatibility. +WWTControl.get_renderNeeded = function () { + return WWTControl._renderNeeded; +}; + +// This parameter does nothing. We keep it to maintain API compatibility. +WWTControl.set_renderNeeded = function (value) { + WWTControl._renderNeeded = true; + return value; +}; + +// Initialization + +// For backwards compatibility, we preserve the semantics that calling +// this function kicks off the rendering loop. +WWTControl.initControl = function (DivId) { + return WWTControl.initControl2(DivId, true); +}; + +// This function had a parameter to choose whether to use WebGL or HTML5 +// canvas, but at some point the argument was defused. We preserve it +// for backwards compatibility. +WWTControl.initControlParam = function (DivId, webgl_ignored) { + return WWTControl.initControl2(DivId, true); +}; + +// Prefer using WWTControlBuilder rather than this interface directly. +WWTControl.initControl2 = function (DivId, startRenderLoop) { + return WWTControl.initControl6(DivId, startRenderLoop, 0, 0, 360, 'Sky'); +}; + +// Prefer using WWTControlBuilder rather than this interface directly. +WWTControl.initControl6 = function (DivId, startRenderLoop, startLat, startLng, startZoom, startMode) { + if (globalRenderContext.device == null) { + WWTControl.scriptInterface = new ScriptInterface(); + WWTControl.scriptInterface.settings = Settings.get_current(); + set_globalScriptInterface(WWTControl.scriptInterface); + var canvas = WWTControl._createCanvasElement(DivId); + var gl = canvas.getContext('webgl2'); + + if (gl != null) { + set_useGlVersion2(true); + } else { + console.warn('This browser does not support WebGL 2.0. Some features will work suboptimally. To get the full AAS WWT experience, consider using the latest version of Chrome, Firefox or Edge. In case you would like to use Safari, we recommend that you enable WebGL 2.0'); + gl = canvas.getContext('webgl'); + } + + if (gl == null) { + gl = canvas.getContext('experimental-webgl'); + } + + if (gl == null) { + var ctx = canvas.getContext('2d'); + globalRenderContext.device = ctx; + } else { + set_tilePrepDevice(gl); + globalRenderContext.gl = gl; + set_useGl(true); + } + + globalWWTControl.canvas = canvas; + globalRenderContext.width = canvas.width; + globalRenderContext.height = canvas.height; + globalWWTControl.setup(canvas, startLat, startLng, startZoom); + + Constellations.initializeConstellations(); + LayerManager.oneTimeInitialization(); + + if (startMode === 'earth') { + globalRenderContext.set_backgroundImageset( + Imageset.create( + 'Blue Marble', // name + URLHelpers.singleton.coreStaticUrl('wwtweb/tiles.aspx?q={1},{2},{3},bm200407'), + ImageSetType.earth, // dataSetType + BandPass.visible, // bandPass + ProjectionType.toast, // projectionType + 101, // imageSetID + 0, // baseLevel + 7, // levels + 256, // tileSize (unused) + 180, // basetileDegrees + '.png', // extension + false, // bottomsUp + '', // quadTreeMap + 0, // centerX + 0, // centerY + 0, // rotation + false, // sparse + URLHelpers.singleton.coreStaticUrl('wwtweb/thumbnail.aspx?name=bm200407'), + true, // defaultSet + false, // elevationModel + 0, // widthFactor + 0, // offsetX + 0, // offsetY + '', // creditsText + '', // creditsUrl + '', // demUrl + '', // altUrl + 6371000, // meanRadius + 'Earth' // referenceFrame + ) + ); + } else if (startMode === 'black') { + // Black sky init -- probably because we are in freestanding mode + globalRenderContext.set_backgroundImageset( + Imageset.create( + 'Black Sky Background', // name + '', // url + ImageSetType.sky, // dataSetType + BandPass.visible, // bandPass + ProjectionType.toast, // projectionType + 102, // imageSetID + 0, // baseLevel + 0, // levels + 256, // tileSize (unused) + 180, // baseTileDegrees + '.png', // extension + false, // bottomsUp + '0123', // quadTreeMap + 0, // centerX + 0, // centerY + 0, // rotation + false, // sparse + '', // thumbnailUrl + false, // defaultSet + false, // elevationModel + 2, // widthFactor + 0, // offsetX + 0, // offsetY + '', // creditsText + '', // creditsUrl + '', // demUrl + '', // altUrl + 1, // meanRadius + 'Sky' // referenceFrame + ) + ); + } else { + globalRenderContext.set_backgroundImageset( + Imageset.create( + 'DSS', // name + URLHelpers.singleton.coreStaticUrl('wwtweb/dss.aspx?q={1},{2},{3}'), + ImageSetType.sky, // dataSetTYpe + BandPass.visible, // bandPass + ProjectionType.toast, // projectionType + 100, // imageSetId + 0, // baseLevel + 12, // levels + 256, // tileSize (unused) + 180, // baseTileDegrees + '.png', // extension + false, // bottomsUp + '', // quadTreeMap + 0, // centerX + 0, // centerY + 0, // rotation + false, // sparse + URLHelpers.singleton.coreStaticUrl('thumbnails/DSS.png'), + true, // defaultSet + false, // elevationModel + 0, // widthFactor + 0, // offsetX + 0, // offsetY + '', // creditsText + '', // creditsUrl + '', // demUrl + '', // altUrl + 1, // meanRadius + 'Sky' // referenceFrame + ) + ); + } + } + globalRenderContext.viewCamera.lng += 0; + globalRenderContext._initGL(); + if (startRenderLoop) { + globalWWTControl.render(); + } + return globalScriptInterface; +}; + +WWTControl._createCanvasElement = function (DivId) { + var div = document.getElementById(DivId); + var canvas = document.createElement('canvas'); + canvas.height = div.clientHeight; + canvas.width = div.clientWidth; + div.appendChild(canvas); + return canvas; +}; + +WWTControl.useUserLocation = function () { + navigator.geolocation.getCurrentPosition(WWTControl._getLocation, WWTControl._getLocationError); +}; + +WWTControl._getLocation = function (pos) { + if (!!pos.coords.latitude) { + Settings.get_globalSettings().set_locationLat(pos.coords.latitude); + } + if (!!pos.coords.longitude) { + Settings.get_globalSettings().set_locationLng(pos.coords.longitude); + } + if (!!pos.coords.altitude) { + Settings.get_globalSettings().set_locationAltitude(pos.coords.altitude); + } +}; + +WWTControl._getLocationError = function (pos) { + if (pos != null && pos.coords != null) { + var lat = pos.coords.latitude; + var lng = pos.coords.longitude; + } +}; + +WWTControl.setBackgroundImageName = function (name) { + WWTControl.imageSetName = name; +}; + +WWTControl.setForegroundImageName = function (name) { + WWTControl.imageSetName = name; +}; + +WWTControl.showLayers = function (show) { + WWTControl.showDataLayers = show; +}; + +var WWTControl$ = { + _addAnnotation: function (annotation) { + this._annotations.push(annotation); + Annotation.batchDirty = true; + }, + + _removeAnnotation: function (annotation) { + ss.remove(this._annotations, annotation); + Annotation.batchDirty = true; + }, + + _clearAnnotations: function () { + this._annotations.length = 0; + Annotation.batchDirty = true; + }, + + _annotationclicked: function (ra, dec, x, y) { + if (this._annotations != null && this._annotations.length > 0) { + var index = 0; + var $enum1 = ss.enumerate(this._annotations); + while ($enum1.moveNext()) { + var note = $enum1.current; + if (note.hitTest(this.renderContext, ra, dec, x, y)) { + globalScriptInterface._fireAnnotationclicked(ra, dec, note.get_id()); + return true; + } + index++; + } + } + return false; + }, + + _annotationHover: function (ra, dec, x, y) { + if (this._annotations != null && this._annotations.length > 0) { + var index = 0; + var $enum1 = ss.enumerate(this._annotations); + while ($enum1.moveNext()) { + var note = $enum1.current; + if (note.hitTest(this.renderContext, ra, dec, x, y)) { + this._hoverText = note.get_label(); + this._hoverTextPoint = Vector2d.create(x, y); + return true; + } + index++; + } + } + return false; + }, + + get_zoomMax: function () { + if (this.renderContext.get_backgroundImageset() != null && this.renderContext.get_backgroundImageset().get_dataSetType() == ImageSetType.solarSystem) { + return this._zoomMaxSolarSystem; + } else { + return this._zoomMax; + } + }, + + set_zoomMax: function (value) { + this._zoomMax = value; + return value; + }, + + setSolarSystemMaxZoom: function (value) { + this._zoomMaxSolarSystem = value; + }, + + get_zoomMin: function () { + if (this.renderContext.get_backgroundImageset() != null && this.renderContext.get_backgroundImageset().get_dataSetType() == ImageSetType.solarSystem) { + return this._zoomMinSolarSystem; + } else { + return this._zoomMin; + } + }, + + set_zoomMin: function (value) { + this._zoomMin = value; + return value; + }, + + setSolarSystemMinZoom: function (value) { + this._zoomMinSolarSystem = value; + }, + + _notifyMoveComplete: function () { }, + + get_crossFadeFrame: function () { + return this._crossFadeFrame; + }, + + set_crossFadeFrame: function (value) { + if (value && this._crossFadeFrame !== value) { + if (this._crossFadeTexture != null) { + } + this._crossFadeTexture = this.renderContext._getScreenTexture(); + } + this._crossFadeFrame = value; + if (!value) { + if (this._crossFadeTexture != null) { + this._crossFadeTexture = null; + } + } + return value; + }, + + _fadeFrame: function () { + if (this.renderContext.gl != null) { + var sp = Settings.get_active().getSetting(17); + if ((sp.opacity > 0)) { + var color = Color._fromArgbColor(255 - UiTools.gamma(255 - ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_black()); + if (!(sp.opacity > 0)) { + color = Color._fromArgbColor(255 - UiTools.gamma(255 - ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_black()); + } + if (this._crossFadeFrame) { + color = Color._fromArgbColor(UiTools.gamma(ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_white()); + } + else { + if (this._crossFadeTexture != null) { + this._crossFadeTexture = null; + } + } + if (this._fadePoints == null) { + this._fadePoints = new Array(4); + for (var i = 0; i < 4; i++) { + this._fadePoints[i] = new PositionColoredTextured(); + } + } + this._fadePoints[0].position.x = -this.renderContext.width / 2; + this._fadePoints[0].position.y = this.renderContext.height / 2; + this._fadePoints[0].position.z = 1347; + this._fadePoints[0].tu = 0; + this._fadePoints[0].tv = 1; + this._fadePoints[0].color = color; + this._fadePoints[1].position.x = -this.renderContext.width / 2; + this._fadePoints[1].position.y = -this.renderContext.height / 2; + this._fadePoints[1].position.z = 1347; + this._fadePoints[1].tu = 0; + this._fadePoints[1].tv = 0; + this._fadePoints[1].color = color; + this._fadePoints[2].position.x = this.renderContext.width / 2; + this._fadePoints[2].position.y = this.renderContext.height / 2; + this._fadePoints[2].position.z = 1347; + this._fadePoints[2].tu = 1; + this._fadePoints[2].tv = 1; + this._fadePoints[2].color = color; + this._fadePoints[3].position.x = this.renderContext.width / 2; + this._fadePoints[3].position.y = -this.renderContext.height / 2; + this._fadePoints[3].position.z = 1347; + this._fadePoints[3].tu = 1; + this._fadePoints[3].tv = 0; + this._fadePoints[3].color = color; + this._sprite.draw(this.renderContext, this._fadePoints, 4, this._crossFadeTexture, true, 1); + } + } + }, + + captureVideo: function (VideoBlobReady, Width, Height, FramesPerSecond, TotalFrames, Format) { + this.capturingVideo = true; + this._videoBlobReady = VideoBlobReady; + ss.clearKeys(this._videoBlobQueue); + this._videoQueueIndex = 0; + this._emptyFrames.length = 0; + this.dumpFrameParams = new VideoOutputType(Width, Height, FramesPerSecond, Format, true); + SpaceTimeController.frameDumping = true; + SpaceTimeController.framesPerSecond = FramesPerSecond; + SpaceTimeController.totalFrames = TotalFrames; + SpaceTimeController.currentFrameNumber = 0; + }, + + // To preserve semantic backwards compatibility, this function must requeue itself + // to be called again in a timeout. + render: function () { + var $this = this; + + this.renderOneFrame(); + setTimeout(function () { + $this.render(); + }, 10); + }, + + renderOneFrame: function () { + if (this.renderContext.get_backgroundImageset() != null) { + this.renderType = this.renderContext.get_backgroundImageset().get_dataSetType(); + } else { + this.renderType = 2; + } + var sizeChange = false; + if (this.canvas.width !== this.canvas.parentNode.clientWidth) { + this.canvas.width = this.canvas.parentNode.clientWidth; + sizeChange = true; + } + if (this.canvas.height !== this.canvas.parentNode.clientHeight) { + this.canvas.height = this.canvas.parentNode.clientHeight; + sizeChange = true; + } + if (sizeChange && this.explorer != null) { + this.explorer.refresh(); + } + + if (this.canvas.width < 1 || this.canvas.height < 1) { + // This can happen during initialization if perhaps some + // HTML/JavaScript interaction hasn't happened to set the canvas + // size correctly. If we don't exit this function early, we get + // NaNs in our transformation matrices that lead IsTileBigEnough + // to say "no" for everything so that we spin out of control + // downloading maximum-resolution DSS tiles for an enormous + // viewport. That's bad! + return; + } + + if (sizeChange) { + // In GL, the crosshairs are in viewport coordinates + // ([0,1]x[0,1]), so a size change alters their perceived aspect + // ratio. + this._crossHairs = null; + } + + Tile.lastDeepestLevel = Tile.deepestLevel; + RenderTriangle.width = this.renderContext.width = this.canvas.width; + RenderTriangle.height = this.renderContext.height = this.canvas.height; + Tile.tilesInView = 0; + Tile.tilesTouched = 0; + Tile.deepestLevel = 0; + SpaceTimeController.set_metaNow(ss.now()); + if (this.get__mover() != null) { + SpaceTimeController.set_now(this.get__mover().get_currentDateTime()); + Planets.updatePlanetLocations(this.get_solarSystemMode()); + if (this.get__mover() != null) { + var newCam = this.get__mover().get_currentPosition(); + this.renderContext.targetCamera = newCam.copy(); + this.renderContext.viewCamera = newCam.copy(); + if (this.renderContext.space && Settings.get_active().get_galacticMode()) { + var gPoint = Coordinates.j2000toGalactic(newCam.get_RA() * 15, newCam.get_dec()); + this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; + this.renderContext.targetAz = this.renderContext.az = gPoint[0]; + } + else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { + var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(newCam.get_RA(), newCam.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); + this.renderContext.targetAlt = this.renderContext.alt = currentAltAz.get_alt(); + this.renderContext.targetAz = this.renderContext.az = currentAltAz.get_az(); + } + if (this.get__mover().get_complete()) { + globalScriptInterface._fireArrived(this.get__mover().get_currentPosition().get_RA(), this.get__mover().get_currentPosition().get_dec(), globalRenderContext.viewCamera.zoom); + this.set__mover(null); + this._notifyMoveComplete(); + } + } + } else { + SpaceTimeController.updateClock(); + Planets.updatePlanetLocations(this.get_solarSystemMode()); + this._updateViewParameters(); + } + this.renderContext.clear(); + if (this.renderType === 4) { + if (this._solarSystemTrack < 20) { + var radius = Planets.getAdjustedPlanetRadius(this._solarSystemTrack); + var distance = this.renderContext.get_solarSystemCameraDistance(); + var camAngle = this.renderContext.get_fovLocal(); + } + if (this._trackingObject == null) { + } + this.renderContext.setupMatricesSolarSystem(true); + var zoom = this.renderContext.viewCamera.zoom; + var milkyWayBlend = Math.min(1, Math.max(0, (Math.log(zoom) - 8.4)) / 4.2); + var milkyWayBlendIn = Math.min(1, Math.max(0, (Math.log(zoom) - 17.9)) / 2.3); + var matOldMW = this.renderContext.get_world(); + var matLocalMW = this.renderContext.get_world().clone(); + matLocalMW._multiply(Matrix3d._scaling(100000, 100000, 100000)); + matLocalMW._multiply(Matrix3d._rotationX(23.5 / 180 * Math.PI)); + matLocalMW._multiply(Matrix3d.translation(this.renderContext.cameraPosition)); + this.renderContext.set_world(matLocalMW); + this.renderContext.set_worldBase(matLocalMW); + this.renderContext.space = true; + this.renderContext.makeFrustum(); + var lighting = this.renderContext.lighting; + this.renderContext.lighting = false; + if (Settings.get_active().get_solarSystemMilkyWay()) { + if (milkyWayBlend < 1) { + if (this._milkyWayBackground == null) { + this._milkyWayBackground = this.getImagesetByName('Digitized Sky Survey (Color)'); + } + if (this._milkyWayBackground != null) { + RenderTriangle.cullInside = true; + var c = (1 - milkyWayBlend) / 2; + this.renderContext.drawImageSet(this._milkyWayBackground, c * 100); + RenderTriangle.cullInside = false; + } + } + } + this._drawSkyOverlays(); + this.renderContext.lighting = lighting; + this.renderContext.space = false; + this.renderContext.set_world(matOldMW); + this.renderContext.set_worldBase(matOldMW); + this.renderContext.makeFrustum(); + var oldCamera = this.renderContext.cameraPosition; + var matOld = this.renderContext.get_world(); + var matLocal = this.renderContext.get_world(); + matLocal._multiply(Matrix3d.translation(this.renderContext.viewCamera.viewTarget)); + this.renderContext.cameraPosition = Vector3d.subtractVectors(this.renderContext.cameraPosition, this.renderContext.viewCamera.viewTarget); + this.renderContext.set_world(matLocal); + this.renderContext.makeFrustum(); + if (Settings.get_active().get_solarSystemCosmos()) { + Grids.drawCosmos3D(this.renderContext, 1); + } + if (Settings.get_active().get_solarSystemMilkyWay() && milkyWayBlendIn > 0) { + Grids.drawGalaxyImage(this.renderContext, milkyWayBlendIn); + } + if (Settings.get_active().get_solarSystemStars()) { + Grids.drawStars3D(this.renderContext, 1); + } + matLocal = matOld; + var pnt = this.renderContext.viewCamera.viewTarget; + var vt = Vector3d.create(-pnt.x, -pnt.y, -pnt.z); + this.renderContext.cameraPosition = oldCamera; + matLocal._multiply(Matrix3d.translation(vt)); + this.renderContext.set_world(matLocal); + this.renderContext.makeFrustum(); + LayerManager._draw(this.renderContext, 1, true, 'Sky', true, false); + this.renderContext.set_world(matOld); + this.renderContext.makeFrustum(); + if (this.renderContext.get_solarSystemCameraDistance() < 15000) { + this.renderContext.setupMatricesSolarSystem(false); + if (Settings.get_active().get_solarSystemMinorPlanets()) { + MinorPlanets.drawMPC3D(this.renderContext, 1, this.renderContext.viewCamera.viewTarget); + } + if (Settings.get_active().get_solarSystemPlanets()) { + Planets3d.drawPlanets3D(this.renderContext, 1, this.renderContext.viewCamera.viewTarget); + } + } + } else { + // RenderType is not SolarSystem + if (!this.renderType || this.renderType === 1) { + this.renderContext._setupMatricesLand3d(); + } + else { + this.renderContext.setupMatricesSpace3d(this.renderContext.width, this.renderContext.height); + } + this.renderContext.drawImageSet(this.renderContext.get_backgroundImageset(), 100); + if (this.renderContext.get_foregroundImageset() != null) { + if (this.renderContext.get_foregroundImageset().get_dataSetType() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { + this.renderContext.set_foregroundImageset(null); + } + else { + if (this.renderContext.viewCamera.opacity !== 100 && this.renderContext.gl == null) { + if (this._foregroundCanvas.width !== this.renderContext.width || this._foregroundCanvas.height !== this.renderContext.height) { + this._foregroundCanvas.width = ss.truncate(this.renderContext.width); + this._foregroundCanvas.height = ss.truncate(this.renderContext.height); + } + var saveDevice = this.renderContext.device; + this._fgDevice.clearRect(0, 0, this.renderContext.width, this.renderContext.height); + this.renderContext.device = this._fgDevice; + this.renderContext.drawImageSet(this.renderContext.get_foregroundImageset(), 100); + this.renderContext.device = saveDevice; + this.renderContext.device.save(); + this.renderContext.device.globalAlpha = this.renderContext.viewCamera.opacity / 100; + this.renderContext.device.drawImage(this._foregroundCanvas, 0, 0); + this.renderContext.device.restore(); + } + else { + this.renderContext.drawImageSet(this.renderContext.get_foregroundImageset(), this.renderContext.viewCamera.opacity); + } + } + } + if (this.renderType === 2) { + var $enum1 = ss.enumerate(this.renderContext.get_catalogHipsImagesets()); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_hipsProperties().get_catalogSpreadSheetLayer().enabled && imageset.get_hipsProperties().get_catalogSpreadSheetLayer().lastVersion === imageset.get_hipsProperties().get_catalogSpreadSheetLayer().get_version()) { + this.renderContext.drawImageSet(imageset, 100); + } + } + } + if (this.renderType === 2 && Settings.get_active().get_showSolarSystem()) { + Planets.drawPlanets(this.renderContext, 1); + this.constellation = Constellations.containment.findConstellationForPoint(this.renderContext.viewCamera.get_RA(), this.renderContext.viewCamera.get_dec()); + this._drawSkyOverlays(); + } + if (this.get_planetLike() || this.get_space()) { + if (!this.get_space()) { + var angle = Coordinates.mstFromUTC2(SpaceTimeController.get_now(), 0) / 180 * Math.PI; + this.renderContext.set_worldBaseNonRotating(Matrix3d.multiplyMatrix(Matrix3d._rotationY(angle), this.renderContext.get_worldBase())); + if (this._targetBackgroundImageset != null) { + this.renderContext.set_nominalRadius(this._targetBackgroundImageset.get_meanRadius()); + } + } + else { + this.renderContext.set_worldBaseNonRotating(this.renderContext.get_world()); + if (this._targetBackgroundImageset != null) { + this.renderContext.set_nominalRadius(this._targetBackgroundImageset.get_meanRadius()); + } + } + var referenceFrame = this.getCurrentReferenceFrame(); + LayerManager._draw(this.renderContext, 1, this.get_space(), referenceFrame, true, this.get_space()); + } + } + var worldSave = this.renderContext.get_world(); + var viewSave = this.renderContext.get_view(); + var projSave = this.renderContext.get_projection(); + if (Settings.get_current().get_showCrosshairs()) { + this._drawCrosshairs(this.renderContext); + } + if (this.uiController != null) { + this.uiController.render(this.renderContext); + } else { + var index = 0; + Annotation.prepBatch(this.renderContext); + var $enum2 = ss.enumerate(this._annotations); + while ($enum2.moveNext()) { + var item = $enum2.current; + item.draw(this.renderContext); + index++; + } + Annotation.drawBatch(this.renderContext); + if ((ss.now() - this._lastMouseMove) > 400) { + var raDecDown = this.getCoordinatesForScreenPoint(this._hoverTextPoint.x, this._hoverTextPoint.y); + this._annotationHover(raDecDown.x, raDecDown.y, this._hoverTextPoint.x, this._hoverTextPoint.y); + this._lastMouseMove = new Date(2100, 1, 1); + } + if (!ss.emptyString(this._hoverText)) { + this._drawHoverText(this.renderContext); + } + } + var tilesAllLoaded = !TileCache.get_queueCount(); + this.renderContext.setupMatricesOverlays(); + this._fadeFrame(); + this._frameCount++; + TileCache.decimateQueue(); + TileCache.processQueue(this.renderContext); + Tile.currentRenderGeneration++; + if (!TourPlayer.get_playing()) { + this.set_crossFadeFrame(false); + } + + // Restore Matrices for Finder Scope and such to map points + this.renderContext.set_world(worldSave); + this.renderContext.set_view(viewSave); + this.renderContext.set_projection(projSave); + var now = ss.now(); + var ms = now - this._lastUpdate; + if (ms > 1000) { + this._lastUpdate = now; + this._frameCount = 0; + RenderTriangle.trianglesRendered = 0; + RenderTriangle.trianglesCulled = 0; + } + if (this.capturingVideo) { + if ((this.dumpFrameParams != null) && (!this.dumpFrameParams.waitDownload || tilesAllLoaded)) { + this.captureFrameForVideo(this._videoBlobReady, this.dumpFrameParams.width, this.dumpFrameParams.height, this.dumpFrameParams.format); + SpaceTimeController.nextFrame(); + } + if (SpaceTimeController.get_doneDumping()) { + SpaceTimeController.frameDumping = false; + SpaceTimeController.cancelFrameDump = false; + this.capturingVideo = false; + } + } + }, + + getCurrentReferenceFrame: function () { + if (this.renderContext.get_backgroundImageset() == null) { + return 'Sun'; + } + if (!ss.emptyString(this.renderContext.get_backgroundImageset().get_referenceFrame())) { + return this.renderContext.get_backgroundImageset().get_referenceFrame(); + } + if (!this.renderContext.get_backgroundImageset().get_dataSetType()) { + return 'Earth'; + } + if (this.renderContext.get_backgroundImageset().get_name() === 'Visible Imagery' && this.renderContext.get_backgroundImageset().get_url().toLowerCase().indexOf('mars') > -1) { + this.renderContext.get_backgroundImageset().set_referenceFrame('Mars'); + return this.renderContext.get_backgroundImageset().get_referenceFrame(); + } + if (this.renderContext.get_backgroundImageset().get_dataSetType() === 1) { + var $enum1 = ss.enumerate(WWTControl.solarSystemObjectsNames); + while ($enum1.moveNext()) { + var name = $enum1.current; + if (this.renderContext.get_backgroundImageset().get_name().toLowerCase().indexOf(name.toLowerCase()) > -1) { + this.renderContext.get_backgroundImageset().set_referenceFrame(name); + return name; + } + } + } + if (this.renderContext.get_backgroundImageset().get_dataSetType() === 2) { + return 'Sky'; + } + return ''; + }, + + get_planetLike: function () { + if (this.renderContext.get_backgroundImageset() != null) { + return !this.renderContext.get_backgroundImageset().get_dataSetType() || this.renderContext.get_backgroundImageset().get_dataSetType() === 1; + } else { + return true; + } + }, + + get_space: function () { + if (this.renderContext.get_backgroundImageset() != null) { + return this.renderContext.get_backgroundImageset().get_dataSetType() === 2; + } else { + return true; + } + }, + + _drawSkyOverlays: function () { + if (Settings.get_active().get_showConstellationPictures() && !this.freestandingMode) { + Constellations.drawArtwork(this.renderContext); + } + if (Settings.get_active().get_showConstellationFigures()) { + if (WWTControl.constellationsFigures == null) { + WWTControl.constellationsFigures = Constellations.create( + 'Constellations', + URLHelpers.singleton.engineAssetUrl('figures.txt'), + false, // "boundry" + false, // "noInterpollation" + false, // "resource" + ); + } + WWTControl.constellationsFigures.draw(this.renderContext, false, 'UMA', false); + } + if (Settings.get_active().get_showEclipticGrid()) { + Grids.drawEclipticGrid(this.renderContext, 1, Settings.get_active().get_eclipticGridColor()); + if (Settings.get_active().get_showEclipticGridText()) { + Grids.drawEclipticGridText(this.renderContext, 1, Settings.get_active().get_eclipticGridColor()); + } + } + if (Settings.get_active().get_showGalacticGrid()) { + Grids.drawGalacticGrid(this.renderContext, 1, Settings.get_active().get_galacticGridColor()); + if (Settings.get_active().get_showGalacticGridText()) { + Grids.drawGalacticGridText(this.renderContext, 1, Settings.get_active().get_galacticGridColor()); + } + } + if (Settings.get_active().get_showAltAzGrid()) { + Grids.drawAltAzGrid(this.renderContext, 1, Settings.get_active().get_altAzGridColor()); + if (Settings.get_active().get_showAltAzGridText()) { + Grids.drawAltAzGridText(this.renderContext, 1, Settings.get_active().get_altAzGridColor()); + } + } + if (Settings.get_active().get_showPrecessionChart()) { + Grids.drawPrecessionChart(this.renderContext, 1, Settings.get_active().get_precessionChartColor()); + } + if (Settings.get_active().get_showEcliptic()) { + Grids.drawEcliptic(this.renderContext, 1, Settings.get_active().get_eclipticColor()); + if (Settings.get_active().get_showEclipticOverviewText()) { + Grids.drawEclipticText(this.renderContext, 1, Settings.get_active().get_eclipticColor()); + } + } + if (Settings.get_active().get_showGrid()) { + Grids.drawEquitorialGrid(this.renderContext, 1, Settings.get_active().get_equatorialGridColor()); + if (Settings.get_active().get_showEquatorialGridText()) { + Grids.drawEquitorialGridText(this.renderContext, 1, Settings.get_active().get_equatorialGridColor()); + } + } + if (Settings.get_active().get_showConstellationBoundries()) { + if (WWTControl.constellationsBoundries == null) { + WWTControl.constellationsBoundries = Constellations.create( + 'Constellations', + URLHelpers.singleton.engineAssetUrl('constellations.txt'), + true, // "boundry" + false, // "noInterpollation" + false, // "resource" + ); + } + WWTControl.constellationsBoundries.draw(this.renderContext, Settings.get_active().get_showConstellationSelection(), this.constellation, false); + } + if (Settings.get_active().get_showConstellationLabels()) { + Constellations.drawConstellationNames(this.renderContext, 1, Colors.get_yellow()); + } + }, + + _drawHoverText: function (RenderContext) { + if (RenderContext.gl == null) { + var ctx = RenderContext.device; + ctx.save(); + ctx.fillStyle = 'White'; + ctx.font = '15px Arial'; + ctx.fillText(this._hoverText, this._hoverTextPoint.x, this._hoverTextPoint.y); + ctx.restore(); + } + }, + + rAtoViewLng: function (ra) { + return (((180 - (ra / 24 * 360) - 180) + 540) % 360) - 180; + }, + + _updateViewParameters: function () { + if (this.renderContext.space && this._tracking && this._trackingObject != null) { + if (Settings.get_active().get_galacticMode() && this.renderContext.space) { + var gPoint = Coordinates.j2000toGalactic(this._trackingObject.get_RA() * 15, this._trackingObject.get_dec()); + this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; + this.renderContext.targetAz = this.renderContext.az = gPoint[0]; + } + else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { + var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(this._trackingObject.get_RA(), this._trackingObject.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); + this.renderContext.targetAlt = currentAltAz.get_alt(); + this.renderContext.targetAz = currentAltAz.get_az(); + } + else { + this.renderContext.viewCamera.lng = this.renderContext.targetCamera.lng = this.rAtoViewLng(this._trackingObject.get_RA()); + this.renderContext.viewCamera.lat = this.renderContext.targetCamera.lat = this._trackingObject.get_dec(); + } + } else if (!this.get_solarSystemMode()) { + this._tracking = false; + this._trackingObject = null; + } + var oneMinusDragCoefficient = 1 - 0.8; + var dc = 0.8; + if (!this._tracking) { + var minDelta = (this.renderContext.viewCamera.zoom / 4000); + if (this.renderContext.viewCamera.zoom > 360) { + minDelta = (360 / 40000); + } + if (this.renderContext.space && (Settings.get_active().get_localHorizonMode() || Settings.get_active().get_galacticMode())) { + if ((((Math.abs(this.renderContext.targetAlt - this.renderContext.alt) >= minDelta) | (Math.abs(this.renderContext.targetAz - this.renderContext.az) >= minDelta)) === 1)) { + this.renderContext.alt += (this.renderContext.targetAlt - this.renderContext.alt) / 10; + if (Math.abs(this.renderContext.targetAz - this.renderContext.az) > 170) { + if (this.renderContext.targetAz > this.renderContext.az) { + this.renderContext.az += (this.renderContext.targetAz - (360 + this.renderContext.az)) / 10; + } + else { + this.renderContext.az += ((360 + this.renderContext.targetAz) - this.renderContext.az) / 10; + } + } + else { + this.renderContext.az += (this.renderContext.targetAz - this.renderContext.az) / 10; + } + this.renderContext.az = ((this.renderContext.az + 720) % 360); + } + } + else { + if ((((Math.abs(this.renderContext.targetCamera.lat - this.renderContext.viewCamera.lat) >= minDelta) | (Math.abs(this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) >= minDelta)) === 1)) { + this.renderContext.viewCamera.lat += (this.renderContext.targetCamera.lat - this.renderContext.viewCamera.lat) / 10; + if (Math.abs(this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) > 170) { + if (this.renderContext.targetCamera.lng > this.renderContext.viewCamera.lng) { + this.renderContext.viewCamera.lng += (this.renderContext.targetCamera.lng - (360 + this.renderContext.viewCamera.lng)) / 10; + } + else { + this.renderContext.viewCamera.lng += ((360 + this.renderContext.targetCamera.lng) - this.renderContext.viewCamera.lng) / 10; + } + } + else { + this.renderContext.viewCamera.lng += (this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) / 10; + } + this.renderContext.viewCamera.lng = ((this.renderContext.viewCamera.lng + 720) % 360); + } + else { + if (this.renderContext.viewCamera.lat !== this.renderContext.targetCamera.lat || this.renderContext.viewCamera.lng !== this.renderContext.targetCamera.lng) { + this.renderContext.viewCamera.lat = this.renderContext.targetCamera.lat; + this.renderContext.viewCamera.lng = this.renderContext.targetCamera.lng; + } + } + } + } + this.renderContext.viewCamera.zoom = dc * this.renderContext.viewCamera.zoom + oneMinusDragCoefficient * this.renderContext.targetCamera.zoom; + this.renderContext.viewCamera.rotation = dc * this.renderContext.viewCamera.rotation + oneMinusDragCoefficient * this.renderContext.targetCamera.rotation; + this.renderContext.viewCamera.angle = dc * this.renderContext.viewCamera.angle + oneMinusDragCoefficient * this.renderContext.targetCamera.angle; + }, + + move: function (x, y) { + // Emulate MoveView() in the Windows client -- rotate the x and y + // offsets if the view is rotated. Our signs are the opposite of + // the Windows client. + + var angle = Math.atan2(y, x); + var distance = Math.sqrt(x * x + y * y); + if (this.get_solarSystemMode() || this.get_planetLike()) { + x = Math.cos(angle + this.renderContext.viewCamera.rotation) * distance; + y = Math.sin(angle + this.renderContext.viewCamera.rotation) * distance; + } else { + x = Math.cos(angle - this.renderContext.viewCamera.rotation) * distance; + y = Math.sin(angle - this.renderContext.viewCamera.rotation) * distance; + } + + // Apply the rotated offsets. The following merges up GetPixelScale{X,Y}() + // and MoveViewNative() of the Windows client. + + var scaleY = this.renderContext.get_fovScale() / 3600; + if (this.renderContext.get_backgroundImageset().get_dataSetType() == ImageSetType.solarSystem) { + scaleY = 0.06; + } + var scaleX = scaleY / Math.max(0.2, Math.cos(this.renderContext.viewCamera.lat / 180 * Math.PI)); + if (!this.renderContext.get_backgroundImageset().get_dataSetType() || this.renderContext.get_backgroundImageset().get_dataSetType() === 1 || this.renderContext.get_backgroundImageset().get_dataSetType() == ImageSetType.solarSystem) { + scaleX *= 6.3; // XXX don't know where this magic number comes from + scaleY *= 6.3; + } + if (this.renderContext.space && (Settings.get_active().get_galacticMode() || Settings.get_active().get_localHorizonMode())) { + x = (Settings.get_active().get_localHorizonMode()) ? -x : x; + this.renderContext.targetAz += x * scaleX; + this.renderContext.targetAz = ((this.renderContext.targetAz + 720) % 360); + this.renderContext.targetAlt += y * scaleY; + if (this.renderContext.targetAlt > 90) { + this.renderContext.targetAlt = 90; + } + if (this.renderContext.targetAlt < -90) { + this.renderContext.targetAlt = -90; + } + } else { + this.renderContext.targetCamera.lng -= x * scaleX; + this.renderContext.targetCamera.lng = ((this.renderContext.targetCamera.lng + 720) % 360); + this.renderContext.targetCamera.lat += y * scaleY; + if (this.renderContext.targetCamera.lat > 90) { + this.renderContext.targetCamera.lat = 90; + } + if (this.renderContext.targetCamera.lat < -90) { + this.renderContext.targetCamera.lat = -90; + } + } + if (!Settings.get_globalSettings().get_smoothPan()) { + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + } + if (!!x && !!y) { + this._tracking = false; + this._trackingObject = null; + } + }, + + zoom: function (factor) { + this.renderContext.targetCamera.zoom *= factor; + if (this.renderContext.targetCamera.zoom > this.get_zoomMax()) { + this.renderContext.targetCamera.zoom = this.get_zoomMax(); + } + if (!Settings.get_globalSettings().get_smoothPan()) { + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + } + }, + + roll: function (angle) { + this.renderContext.targetCamera.rotation += angle; + }, + + // Gesture events + + onGestureStart: function (e) { + this._mouseDown = false; + this._beginZoom = this.renderContext.viewCamera.zoom; + }, + + onGestureChange: function (e) { + var g = e; + this._mouseDown = false; + this.renderContext.targetCamera.zoom = this.renderContext.viewCamera.zoom = Math.min(360, this._beginZoom * (1 / g.scale)); + }, + + onGestureEnd: function (e) { + var g = e; + this._mouseDown = false; + }, + + // Touch events + + onTouchStart: function (e) { + var ev = e; + ev.preventDefault(); + ev.stopPropagation(); + this._lastX = ev.targetTouches[0].pageX; + this._lastY = ev.targetTouches[0].pageY; + if (ev.targetTouches.length === 2) { + this._hasTwoTouches = true; + return; + } + if (this.uiController != null) { + var ee = new WWTElementEvent(this._lastX, this._lastY); + if (this.uiController.mouseDown(this, ee)) { + this._mouseDown = false; + this._dragging = false; + return; + } + } + this._mouseDown = true; + }, + + onTouchMove: function (e) { + var ev = e; + if (this._hasTwoTouches) { + var t0 = ev.touches[0]; + var t1 = ev.touches[1]; + var newRect = new Array(2); + newRect[0] = Vector2d.create(t0.pageX, t0.pageY); + newRect[1] = Vector2d.create(t1.pageX, t1.pageY); + if (this._pinchingZoomRect[0] != null && this._pinchingZoomRect[1] != null) { + var centerPoint = Vector2d.create(this.renderContext.width / 2, this.renderContext.height / 2); + var delta1 = Vector2d.subtract(newRect[0], this._pinchingZoomRect[0]); + var delta2 = Vector2d.subtract(newRect[1], this._pinchingZoomRect[1]); + var radialDirection1 = Vector2d.subtract(this._pinchingZoomRect[0], centerPoint); + var radialDirection2 = Vector2d.subtract(this._pinchingZoomRect[1], centerPoint); + radialDirection1.normalize(); + radialDirection2.normalize(); + var radialDot1 = delta1.x * radialDirection1.x + delta1.y * radialDirection1.y; + var radialDot2 = delta2.x * radialDirection2.x + delta2.y * radialDirection2.y; + var radialComponent1 = Vector2d.create(radialDot1 * radialDirection1.x, radialDot1 * radialDirection1.y); + var radialComponent2 = Vector2d.create(radialDot2 * radialDirection2.x, radialDot2 * radialDirection2.y); + var angularComponent1 = Vector2d.subtract(delta1, radialComponent1); + var angularComponent2 = Vector2d.subtract(delta2, radialComponent2); + var radialMagnitude = radialComponent1.get_length() + radialComponent2.get_length(); + var angularMagnitude = angularComponent1.get_length() + angularComponent2.get_length(); + if (radialMagnitude >= angularMagnitude) { + var oldDist = this.getDistance(this._pinchingZoomRect[0], this._pinchingZoomRect[1]); + var newDist = this.getDistance(newRect[0], newRect[1]); + var ratio = oldDist / newDist; + this.zoom(ratio); + } + else { + var oldCenterDelta1 = Vector2d.subtract(this._pinchingZoomRect[0], centerPoint); + var oldCenterDelta2 = Vector2d.subtract(this._pinchingZoomRect[1], centerPoint); + var newCenterDelta1 = Vector2d.subtract(newRect[0], centerPoint); + var newCenterDelta2 = Vector2d.subtract(newRect[1], centerPoint); + var cross1 = this.crossProductZ(oldCenterDelta1, newCenterDelta1); + var cross2 = this.crossProductZ(oldCenterDelta2, newCenterDelta2); + var angle1 = Math.asin(cross1 / (oldCenterDelta1.get_length() * newCenterDelta1.get_length())); + var angle2 = Math.asin(cross2 / (oldCenterDelta2.get_length() * newCenterDelta2.get_length())); + if (angle1 * angle2 >= 0) { + var angle = angle1 + angle2; + if (this.get_planetLike() || this.get_solarSystemMode()) { + angle *= -1; + } + this.roll(angle); + } + } + } + this._pinchingZoomRect = newRect; + ev.stopPropagation(); + ev.preventDefault(); + return; + } + ev.preventDefault(); + ev.stopPropagation(); + if (this._mouseDown) { + this._dragging = true; + var curX = ev.targetTouches[0].pageX - this._lastX; + var curY = ev.targetTouches[0].pageY - this._lastY; + this.move(curX, curY); + this._lastX = ev.targetTouches[0].pageX; + this._lastY = ev.targetTouches[0].pageY; + } else { + //todo fix this to use syntheszed touch events. + if (this.uiController != null) { + if (this.uiController.mouseMove(this, e)) { + e.preventDefault(); + e.stopPropagation(); + return; + } + } + } + }, + + onTouchEnd: function (e) { + var ev = e; + ev.preventDefault(); + ev.stopPropagation(); + this._pinchingZoomRect[0] = null; + this._pinchingZoomRect[1] = null; + if (this._hasTwoTouches) { + if (ev.touches.length < 2) { + this._hasTwoTouches = false; + } + return; + } + if (this.uiController != null) { + var ee = new WWTElementEvent(this._lastX, this._lastY); + if (this.uiController.mouseUp(this, ee)) { + this._mouseDown = false; + this._dragging = false; + return; + } + } + this._mouseDown = false; + this._dragging = false; + }, + + // Pointer events + + onPointerDown: function (e) { + var pe = e; + var index = 0; + var evt = arguments[0], cnv = arguments[0].target; if (cnv.setPointerCapture) { cnv.setPointerCapture(evt.pointerId); } else if (cnv.msSetPointerCapture) { cnv.msSetPointerCapture(evt.pointerId); } + + // Check for this pointer already being in the list because as of July + // 2020, Chrome/Mac sometimes fails to deliver the pointerUp event. + + if (this._pointerIds[0] === pe.pointerId) { + index = 0; + } else if (this._pointerIds[1] === pe.pointerId) { + index = 1; + } else if (!this._pointerIds[0]) { + index = 0; + } else if (!this._pointerIds[1]) { + index = 1; + } else { + return; // only attempt to track two pointers at once + } + this._pointerIds[index] = pe.pointerId; + this._pinchingZoomRect[index] = Vector2d.create(e.offsetX, e.offsetY); + }, + + onPointerMove: function (e) { + var pe = e; + var index = 0; + + // Our pointerIds infrastructure is meant to track adjustments during a + // pinch motion. However, as seen in Firefox circa v81 on Linux and + // Android, in some cases the browser can just *lie* and swap pointerIds + // for the two fingers during a pinch gesture, leading to catastrophic + // failures. Therefore, ignore the pointerId information and infer which + // location is being updated from whichever change is smaller. + + if (this._pointerIds[0] === pe.pointerId) { + index = 0; + } else if (this._pointerIds[1] === pe.pointerId) { + index = 1; + } else { + return; + } + if (this._pinchingZoomRect[0] != null && this._pinchingZoomRect[1] != null) { + var oldDist = this.getDistance(this._pinchingZoomRect[0], this._pinchingZoomRect[1]); + var newRect = Vector2d.create(e.offsetX, e.offsetY); + var newDist0 = this.getDistance(newRect, this._pinchingZoomRect[0]); + var ratio0 = oldDist / newDist0; + var abslog0 = Math.abs(Math.log(ratio0)); + if (!isFinite(abslog0)) { + abslog0 = 1000; + } + var newDist1 = this.getDistance(newRect, this._pinchingZoomRect[1]); + var ratio1 = oldDist / newDist1; + var abslog1 = Math.abs(Math.log(ratio1)); + if (!isFinite(abslog1)) { + abslog1 = 1000; + } + if (abslog1 < abslog0) { + this._pinchingZoomRect[0] = newRect; + this.zoom(ratio1); + } + else { + this._pinchingZoomRect[1] = newRect; + this.zoom(ratio0); + } + } else { + // Before two fingers are available, just trust. + this._pinchingZoomRect[index] = Vector2d.create(e.offsetX, e.offsetY); + } + + // There doesn't seem to be a particular reason to call these + // but there also doesn't seem to be a reason NOT to + // and doing so hasn't caused any issues to this point + e.stopPropagation(); + e.preventDefault(); + }, + + // NOTE! As of July 2020, Chrome on Macs seems to sometimes fail to + // deliver this event. So our pinch-detection code needs to be robust to + // that. + onPointerUp: function (e) { + var pe = e; + + // The -2 here is intended to indicate "no pointer ID" + // with the hope being that no browser will use this value. + // Note that -1 is reserved by the W3 spec for + // "events generated by something other than a pointing device" + // which is why we don't use -1 + // (https://www.w3.org/TR/pointerevents3/#pointerevent-interface) + + if (this._pointerIds[0] === pe.pointerId) { + this._pointerIds[0] = -2; + this._pinchingZoomRect[0] = null; + } + + if (this._pointerIds[1] === pe.pointerId) { + this._pointerIds[1] = -2; + this._pinchingZoomRect[1] = null; + } + }, + + // Mouse events + + onMouseDown: function (e) { + document.addEventListener('mousemove', ss.bind('onMouseMove', this), false); + document.addEventListener('mouseup', ss.bind('onMouseUp', this), false); + if (this.uiController != null) { + if (this.uiController.mouseDown(this, e)) { + return; + } + } + this._mouseDown = true; + this._lastX = Mouse.offsetX(this.canvas, e); + this._lastY = Mouse.offsetY(this.canvas, e); + }, + + onMouseMove: function (e) { + this._lastMouseMove = ss.now(); + this._hoverTextPoint = Vector2d.create(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e)); + this._hoverText = ''; + if (this._mouseDown) { + e.preventDefault(); + e.stopPropagation(); + this._moved = true; + if (e.ctrlKey) { + this._tilt(Mouse.offsetX(this.canvas, e) - this._lastX, Mouse.offsetY(this.canvas, e) - this._lastY); + } + else { + this.move(Mouse.offsetX(this.canvas, e) - this._lastX, Mouse.offsetY(this.canvas, e) - this._lastY); + } + this._lastX = Mouse.offsetX(this.canvas, e); + this._lastY = Mouse.offsetY(this.canvas, e); + } else { + if (this.uiController != null) { + if (this.uiController.mouseMove(this, e)) { + e.preventDefault(); + e.stopPropagation(); + return; + } + } + } + }, + + onMouseUp: function (e) { + document.removeEventListener('mousemove', ss.bind('onMouseMove', this), false); + document.removeEventListener('mouseup', ss.bind('onMouseUp', this), false); + if (this.uiController != null) { + if (this.uiController.mouseUp(this, e)) { + this._mouseDown = false; + e.preventDefault(); + return; + } + } + if (this._mouseDown && !this._moved) { + var raDecDown = this.getCoordinatesForScreenPoint(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e)); + if (!this._annotationclicked(raDecDown.x, raDecDown.y, Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e))) { + globalScriptInterface._fireClick(raDecDown.x, raDecDown.y); + } + } + this._mouseDown = false; + this._moved = false; + }, + + // WheelEvent is a WWT-specific name that we use to abstract across the + // different wheel-motion events that browsers provide: "wheel", + // "mousewheel", "DOMMouseScroll". + onMouseWheel: function (e) { + var ev = e; + var delta; + if (!!ev.deltaY) { + delta = -ev.deltaY; + } else if (!!ev.detail) { + delta = ev.detail * -1; + } else { + delta = ev.wheelDelta; + } + if (delta > 0) { + this.zoom(0.9); + } else { + this.zoom(1.1); + } + e.stopPropagation(); + e.preventDefault(); + }, + + onDoubleClick: function (e) { + WWTControl.showDataLayers = true; + }, + + onKeyDown: function (e) { + if (this.uiController != null) { + this.uiController.keyDown(this, e); + } + }, + + getDistance: function (a, b) { + var x; + var y; + x = a.x - b.x; + y = a.y - b.y; + return Math.sqrt(x * x + y * y); + }, + + crossProductZ: function (a, b) { + return a.x * b.y - a.y * b.x; + }, + + onContextMenu: function (e) { + e.preventDefault(); + e.stopPropagation(); + }, + + _tilt: function (x, y) { + this.renderContext.targetCamera.rotation += x * 0.001; + this.renderContext.targetCamera.angle += y * 0.001; + if (this.renderContext.targetCamera.angle < -1.52) { + this.renderContext.targetCamera.angle = -1.52; + } + if (this.renderContext.targetCamera.angle > 0) { + this.renderContext.targetCamera.angle = 0; + } + }, + + getCoordinatesForScreenPoint: function (x, y) { + var pt = Vector2d.create(x, y); + var PickRayDir = this.transformPickPointToWorldSpace(pt, this.renderContext.width, this.renderContext.height); + return Coordinates.cartesianToSphericalSky(PickRayDir); + }, + + transformPickPointToWorldSpace: function (ptCursor, backBufferWidth, backBufferHeight) { + var vPickRayDir = new Vector3d(); + + // It is possible for this function to be called before the RenderContext is + // set up, in which case the Projection is null. In that case we'll leave the + // vector at its 0,0,0 default. + + if (this.renderContext.get_projection() != null) { + var v = new Vector3d(); + v.x = (((2 * ptCursor.x) / backBufferWidth) - 1) / this.renderContext.get_projection().get_m11(); + v.y = (((2 * ptCursor.y) / backBufferHeight) - 1) / this.renderContext.get_projection().get_m22(); + v.z = 1; + var m = Matrix3d.multiplyMatrix(this.renderContext.get_view(), this.renderContext.get_world()); + + m.invert(); + + // Transform the screen space pick ray into 3D space + vPickRayDir.x = v.x * m.get_m11() + v.y * m.get_m21() + v.z * m.get_m31(); + vPickRayDir.y = v.x * m.get_m12() + v.y * m.get_m22() + v.z * m.get_m32(); + vPickRayDir.z = v.x * m.get_m13() + v.y * m.get_m23() + v.z * m.get_m33(); + vPickRayDir.normalize(); + } + return vPickRayDir; + }, + + transformWorldPointToPickSpace: function (worldPoint, backBufferWidth, backBufferHeight) { + var m = Matrix3d.multiplyMatrix(this.renderContext.get_view(), this.renderContext.get_world()); + m.invert(); + var p = new Vector2d(); + var vz = worldPoint.x * m.get_m31() + worldPoint.y * m.get_m32() + worldPoint.z * m.get_m33(); + var vx = (worldPoint.x * m.get_m11() + worldPoint.y * m.get_m12() + worldPoint.z * m.get_m13()) / vz; + var vy = (worldPoint.x * m.get_m21() + worldPoint.y * m.get_m22() + worldPoint.z * m.get_m23()) / vz; + p.x = Math.round((1 + this.renderContext.get_projection().get_m11() * vx) * (backBufferWidth / 2)); + p.y = Math.round((1 + this.renderContext.get_projection().get_m22() * vy) * (backBufferHeight / 2)); + return p; + }, + + getScreenPointForCoordinates: function (ra, dec) { + var pt = Vector2d.create(ra, dec); + var cartesian = Coordinates.sphericalSkyToCartesian(pt); + var result = this.transformWorldPointToPickSpace(cartesian, this.renderContext.width, this.renderContext.height); + return result; + }, + + // Note that due to limitations of ScriptSharp, this method was public even + // though it should really have been private. + setup: function (canvas, startLat, startLng, startZoom) { + var $this = this; + + window.addEventListener('contextmenu', ss.bind('onContextMenu', this), false); + document.body.addEventListener('keydown', ss.bind('onKeyDown', this), false); + canvas.addEventListener('dblclick', ss.bind('onDoubleClick', this), false); + canvas.addEventListener('mousedown', ss.bind('onMouseDown', this), false); + canvas.addEventListener('wheel', ss.bind('onMouseWheel', this), false); + canvas.addEventListener('mousewheel', ss.bind('onMouseWheel', this), false); + canvas.addEventListener('DOMMouseScroll', ss.bind('onMouseWheel', this), false); // old Firefox + canvas.addEventListener('touchstart', ss.bind('onTouchStart', this), false); + canvas.addEventListener('touchmove', ss.bind('onTouchMove', this), false); + canvas.addEventListener('touchend', ss.bind('onTouchEnd', this), false); + canvas.addEventListener('gesturechange', ss.bind('onGestureChange', this), false); + canvas.addEventListener('gesturestart', ss.bind('onGestureStart', this), false); + canvas.addEventListener('gestureend', ss.bind('onGestureEnd', this), false); + canvas.addEventListener('pointerdown', ss.bind('onPointerDown', this), false); + canvas.addEventListener('pointermove', ss.bind('onPointerMove', this), false); + canvas.addEventListener('pointerup', ss.bind('onPointerUp', this), false); + this.renderContext.viewCamera.lat = startLat; + this.renderContext.viewCamera.lng = startLng; + this.renderContext.viewCamera.zoom = startZoom; + this.renderContext.targetCamera = this.renderContext.viewCamera.copy(); + if (this.renderContext.gl == null) { + this._foregroundCanvas = document.createElement('canvas'); + this._foregroundCanvas.width = canvas.width; + this._foregroundCanvas.height = canvas.height; + this._fgDevice = this._foregroundCanvas.getContext('2d'); + } + if (this.freestandingMode) { + setTimeout(function () { + $this._setupComplete(); + }, 0); + } else { + // To line up with Windows client history, this uses `X=` when `W=` + // would be more appropriate. + loadWtmlFile(URLHelpers.singleton.coreDynamicUrl('wwtweb/catalog.aspx?X=ImageSets6'), ss.bind('_setupComplete', this), true); + } + }, + + _setupComplete: function () { + globalScriptInterface._fireReady(); + }, + + gotoRADecZoom: function (ra, dec, zoom, instant, roll) { + this._tracking = false; + this._trackingObject = null; + this.gotoTargetFull( + false, // noZoom + instant, + this._cameraParametersFromRADecZoom(ra, dec, zoom, roll), + globalRenderContext.get_foregroundImageset(), + globalRenderContext.get_backgroundImageset() + ); + }, + + _cameraParametersFromRADecZoom: function (ra, dec, zoom, roll) { + while (ra > 24) { + ra -= 24; + } + while (ra < 0) { + ra += 24; + } + dec = DoubleUtilities.clamp(dec, -90, 90); + zoom = DoubleUtilities.clamp(zoom, this.get_zoomMin(), this.get_zoomMax()); + var rotation = (roll == null) ? globalRenderContext.viewCamera.rotation : roll; + var cameraParams = CameraParameters.create(dec, globalRenderContext.rAtoViewLng(ra), zoom, rotation, globalRenderContext.viewCamera.angle, globalRenderContext.viewCamera.opacity); + return cameraParams; + }, + + timeToRADecZoom: function (ra, dec, zoom, roll) { + var cameraParams = this._cameraParametersFromRADecZoom(ra, dec, zoom, roll); + return this.timeToTargetFull(cameraParams, false); + }, + + get_solarSystemMode: function () { + if (this.renderContext.get_backgroundImageset() == null) { + return false; + } + return this.renderContext.get_backgroundImageset().get_dataSetType() == ImageSetType.solarSystem; + }, + + gotoTarget: function (place, noZoom, instant, trackObject) { + if (place == null) { + return; + } + if ((trackObject && this.get_solarSystemMode())) { + if ((place.get_classification() === 536870912 && place.get_type() !== 4) || (place.get_classification() === 1) || (place.get_classification() === 1048576) && place.get_distance() > 0) { + var target = 65536; + if (place.get_classification() === 1 || place.get_classification() === 1048576) { + target = 20; + } + else { + try { + if (place.get_target() !== 65536) { + target = place.get_target(); + } + else { + target = Planets.getPlanetIDFromName(place.get_name()); + } + } + catch ($e1) { + } + } + if (target !== 65536) { + this._trackingObject = place; + if (target === this._solarSystemTrack && !(place.get_classification() === 1 || place.get_classification() === 1048576)) { + this.gotoTarget3(place.get_camParams(), noZoom, instant); + return; + } + var jumpTime = 4; + if (target === 20) { + jumpTime = 17; + } + else { + jumpTime += 13 * (101 - Settings.get_active().get_solarSystemScale()) / 100; + } + if (instant) { + jumpTime = 1; + } + var camTo = this.renderContext.viewCamera.copy(); + camTo.targetReferenceFrame = ''; + camTo.target = target; + var zoom = 10; + if (target === 20) { + if (place.get_classification() === Classification.galaxy) { + zoom = 1404946007758; + } + else { + zoom = 63239.6717 * 100; + } + + // Star or something outside of SS + var vect = Coordinates.raDecTo3dAu(place.get_RA(), place.get_dec(), place.get_distance()); + var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; + vect.rotateX(ecliptic); + camTo.viewTarget = Vector3d.negate(camTo.viewTarget); + } + else { + camTo.viewTarget = Planets.getPlanet3dLocationJD(target, SpaceTimeController.getJNowForFutureTime(jumpTime)); + switch (target) { + case 0: + zoom = 0.6; + break; + case 1: + zoom = 0.0004; + break; + case 2: + zoom = 0.0004; + break; + case 3: + zoom = 0.0004; + break; + case 4: + zoom = 0.007; + break; + case 5: + zoom = 0.007; + break; + case 6: + zoom = 0.004; + break; + case 7: + zoom = 0.004; + break; + case 8: + zoom = 0.0004; + break; + case 9: + zoom = 0.0004; + break; + case 10: + zoom = 0.0004; + break; + case 11: + zoom = 0.0004; + break; + case 12: + zoom = 0.0004; + break; + case 13: + zoom = 0.0004; + break; + case 19: + zoom = 0.0004; + break; + case 20: + zoom = 10; + break; + default: + break; + } + zoom = zoom * Settings.get_active().get_solarSystemScale(); + } + var fromParams = this.renderContext.viewCamera.copy(); + if (this._solarSystemTrack === 20 && !ss.emptyString(this.renderContext.get_trackingFrame())) { + fromParams = this.renderContext.customTrackingParams; + this.renderContext.set_trackingFrame(''); + } + camTo.zoom = zoom; + var toVector = camTo.viewTarget; + toVector.subtract(fromParams.viewTarget); + if (place.get_classification() === 1) { + toVector = Vector3d.negate(toVector); + } + if (!!toVector.length()) { + var raDec = toVector.toRaDec(); + if (target === 20) { + camTo.lat = -raDec.y; + } + else { + camTo.lat = raDec.y; + } + camTo.lng = raDec.x * 15 - 90; + } + else { + camTo.lat = this.renderContext.viewCamera.lat; + camTo.lng = this.renderContext.viewCamera.lng; + } + if (target !== SolarSystemObjects.custom) { + // replace with planet surface + camTo.viewTarget = Planets.getPlanetTargetPoint(target, camTo.lat, camTo.lng, SpaceTimeController.getJNowForFutureTime(jumpTime)); + } + var solarMover = new ViewMoverKenBurnsStyle(fromParams, camTo, jumpTime, SpaceTimeController.get_now(), SpaceTimeController.getTimeForFutureTime(jumpTime), 3); + solarMover.fastDirectionMove = true; + this.set__mover(solarMover); + return; + } + } + } + this._tracking = false; + this._trackingObject = null; + var camParams = place.get_camParams().copy(); + if (this.renderContext.get_backgroundImageset() != null && place.get_type() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { + this.renderContext.targetCamera = place.get_camParams().copy(); + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + this.renderContext.set_backgroundImageset(this.getDefaultImageset(place.get_type(), 3)); + instant = true; + } else if (this.get_solarSystemMode() && place.get_target() !== this._solarSystemTrack) { + this.renderContext.targetCamera = place.get_camParams().copy(); + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + this._solarSystemTrack = place.get_target(); + instant = true; + } + if (place.get_classification() === 128) { + camParams.zoom = this.get_zoomMax(); + this.gotoTargetFull(false, instant, camParams, null, null); + } else { + this._solarSystemTrack = place.get_target(); + this.gotoTargetFull(noZoom, instant, camParams, place.get_studyImageset(), place.get_backgroundImageset()); + if (trackObject) { + this._tracking = true; + this._trackingObject = place; + } + } + }, + + gotoTarget3: function (camParams, noZoom, instant) { + this._tracking = false; + this._trackingObject = null; + this.gotoTargetFull(noZoom, instant, camParams, this.renderContext.get_foregroundImageset(), this.renderContext.get_backgroundImageset()); + }, + + _tooCloseForSlewMove: function (cameraParams) { + return Math.abs(this.renderContext.viewCamera.lat - cameraParams.lat) < 1E-12 && Math.abs(this.renderContext.viewCamera.lng - cameraParams.lng) < 1E-12 && Math.abs(this.renderContext.viewCamera.zoom - cameraParams.zoom) < 1E-12 && Math.abs(this.renderContext.viewCamera.rotation - cameraParams.rotation) < 1E-12; + }, + + gotoTargetFull: function (noZoom, instant, cameraParams, studyImageSet, backgroundImageSet) { + this._tracking = false; + this._trackingObject = null; + this._targetStudyImageset = studyImageSet; + this._targetBackgroundImageset = backgroundImageSet; + if (noZoom) { + cameraParams.zoom = this.renderContext.viewCamera.zoom; + cameraParams.angle = this.renderContext.viewCamera.angle; + cameraParams.rotation = this.renderContext.viewCamera.rotation; + } else { + if (cameraParams.zoom === -1 || !cameraParams.zoom) { + if (this.renderContext.space) { + cameraParams.zoom = 1.40625; + } + else { + cameraParams.zoom = 0.09; + } + } + } + if (instant || this._tooCloseForSlewMove(cameraParams)) { + this.set__mover(null); + this.renderContext.targetCamera = cameraParams.copy(); + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + if (this.renderContext.space && Settings.get_active().get_galacticMode()) { + var gPoint = Coordinates.j2000toGalactic(this.renderContext.viewCamera.get_RA() * 15, this.renderContext.viewCamera.get_dec()); + this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; + this.renderContext.targetAz = this.renderContext.az = gPoint[0]; + } + else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { + var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(this.renderContext.viewCamera.get_RA(), this.renderContext.viewCamera.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); + this.renderContext.targetAlt = this.renderContext.alt = currentAltAz.get_alt(); + this.renderContext.targetAz = this.renderContext.az = currentAltAz.get_az(); + } + this._mover_Midpoint(); + } else { + this.set__mover(ViewMoverSlew.create(this.renderContext.viewCamera, cameraParams)); + this.get__mover().set_midpoint(ss.bind('_mover_Midpoint', this)); + } + }, + + _slewTimeBetweenTargets: function (from, to) { + var mover = ViewMoverSlew.create(from, to); + return mover.get_moveTime(); + }, + + timeToTargetFull: function (cameraParams, noZoom) { + if (noZoom) { + cameraParams.zoom = this.renderContext.viewCamera.zoom; + cameraParams.angle = this.renderContext.viewCamera.angle; + cameraParams.rotation = this.renderContext.viewCamera.rotation; + } + if (this._tooCloseForSlewMove(cameraParams)) { + return 0; + } + return this._slewTimeBetweenTargets(globalRenderContext.viewCamera, cameraParams); + }, + + _freezeView: function () { + this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); + this.set__mover(null); + }, + + get__mover: function () { + return this.renderContext.viewMover; + }, + + set__mover: function (value) { + this.renderContext.viewMover = value; + return value; + }, + + fadeInImageSet: function (newImageSet) { + if (this.renderContext.get_backgroundImageset() != null && newImageSet.get_dataSetType() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { + TileCache.purgeQueue(); + TileCache.clearCache(); + } + this.renderContext.set_backgroundImageset(newImageSet); + }, + + _mover_Midpoint: function () { + if ((this._targetStudyImageset != null && this.renderContext.get_foregroundImageset() == null) || (this.renderContext.get_foregroundImageset() != null && !this.renderContext.get_foregroundImageset().equals(this._targetStudyImageset))) { + this.renderContext.set_foregroundImageset(this._targetStudyImageset); + } + if (this.renderContext.get_backgroundImageset() != null && (this._targetBackgroundImageset != null && !this.renderContext.get_backgroundImageset().equals(this._targetBackgroundImageset))) { + if (this._targetBackgroundImageset != null && this._targetBackgroundImageset.get_generic()) { + this.fadeInImageSet(this._getRealImagesetFromGeneric(this._targetBackgroundImageset)); + } + else { + this.fadeInImageSet(this._targetBackgroundImageset); + } + } + }, + + getDefaultImageset: function (imageSetType, bandPass) { + var $enum1 = ss.enumerate(WWTControl.imageSets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_defaultSet() && imageset.get_bandPass() === bandPass && imageset.get_dataSetType() === imageSetType) { + return imageset; + } + } + var $enum2 = ss.enumerate(WWTControl.imageSets); + while ($enum2.moveNext()) { + var imageset = $enum2.current; + if (imageset.get_bandPass() === bandPass && imageset.get_dataSetType() === imageSetType) { + return imageset; + } + } + var $enum3 = ss.enumerate(WWTControl.imageSets); + while ($enum3.moveNext()) { + var imageset = $enum3.current; + if (imageset.get_dataSetType() === imageSetType) { + return imageset; + } + } + return WWTControl.imageSets[0]; + }, + + _getRealImagesetFromGeneric: function (generic) { + var $enum1 = ss.enumerate(WWTControl.imageSets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_defaultSet() && imageset.get_bandPass() === generic.get_bandPass() && imageset.get_dataSetType() === generic.get_dataSetType()) { + return imageset; + } + } + var $enum2 = ss.enumerate(WWTControl.imageSets); + while ($enum2.moveNext()) { + var imageset = $enum2.current; + if (imageset.get_bandPass() === generic.get_bandPass() && imageset.get_dataSetType() === generic.get_dataSetType()) { + return imageset; + } + } + return WWTControl.imageSets[0]; + }, + + _hideUI: function (p) { }, + + createTour: function (name) { + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.stop(false); + } + this.tour = new TourDocument(); + this.tour.set_title(name); + this.setupTour(); + this.tour.set_editMode(true); + return this.tour; + }, + + setupTour: function () { + this.tourEdit = new TourEditTab(); + this.tourEdit.set_tour(this.tour); + this.tour.set_currentTourstopIndex(0); + this.tour.set_editMode(false); + this.uiController = this.tourEdit.tourEditorUI; + }, + + loadTour: function (url) { + var $this = this; + + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.stop(false); + } + this.tour = TourDocument.fromUrl(url, function () { + $this.setupTour(); + var player = new TourPlayer(); + player.set_tour($this.tour); + globalWWTControl.uiController = player; + globalScriptInterface._fireTourReady(); + }); + }, + + playTour: function (url) { + var $this = this; + + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.stop(false); + } + this.tour = TourDocument.fromUrl(url, function () { + $this.setupTour(); + $this.tourEdit.playNow(true); // fromStart + globalScriptInterface._fireTourReady(); + }); + }, + + playCurrentTour: function () { + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.play(); + } + }, + + pauseCurrentTour: function () { + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.pauseTour(); + } + }, + + stopCurrentTour: function () { + if (ss.canCast(this.uiController, TourPlayer)) { + var player = this.uiController; + player.stop(false); + } + }, + + _closeTour: function () { }, + + getImagesetByName: function (name) { + var $enum1 = ss.enumerate(WWTControl.imageSets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_name().toLowerCase().indexOf(name.toLowerCase()) > -1) { + return imageset; + } + } + return null; + }, + + getImageSetByUrl: function (url) { + var $enum1 = ss.enumerate(WWTControl.imageSets); + while ($enum1.moveNext()) { + var imageset = $enum1.current; + if (imageset.get_url() === url) { + return imageset; + } + } + return null; + }, + + setBackgroundImageByName: function (name) { + var newBackground = this.getImagesetByName(name); + if (newBackground != null) { + this.renderContext.set_backgroundImageset(newBackground); + } + }, + + setForegroundImageByName: function (name) { + var newForeground = this.getImagesetByName(name); + if (newForeground != null) { + this.renderContext.set_foregroundImageset(newForeground); + } + }, + + addCatalogHips: function (catalogHips) { + this.renderContext.addCatalogHips(catalogHips, null); + }, + + addCatalogHipsByName: function (name) { + this.addCatalogHipsByNameWithCallback(name, null); + }, + + addCatalogHipsByNameWithCallback: function (name, onLoad) { + var catalogHips = this.getImagesetByName(name); + if (catalogHips != null) { + this.renderContext.addCatalogHips(catalogHips, onLoad); + } + }, + + removeCatalogHipsByName: function (name) { + var catalogHips = this.getImagesetByName(name); + if (catalogHips != null) { + this.renderContext.removeCatalogHips(catalogHips); + } + }, + + getCatalogHipsByName: function (name) { + return this.renderContext.getCatalogHipsByName(name); + }, + + getCatalogHipsDataInView: function (name, limit, onComplete) { + var catalogHips = this.getImagesetByName(name); + if (catalogHips != null) { + this.renderContext.getCatalogHipsDataInView(catalogHips, limit, onComplete); + } + }, + + setCutsForFits: function (imagesetName, min, max) { + var imageset = this.getImagesetByName(imagesetName); + if (imageset != null && imageset.get_fitsProperties() != null) { + imageset.get_fitsProperties().lowerCut = min; + imageset.get_fitsProperties().upperCut = max; + } else { + console.log(imagesetName + ' not found'); + } + }, + + setColorMapForFits: function (imagesetName, colorMapName) { + var imageset = this.getImagesetByName(imagesetName); + if (imageset != null && imageset.get_fitsProperties() != null) { + imageset.get_fitsProperties().colorMapName = colorMapName; + } else { + console.log(imagesetName + ' not found'); + } + }, + + setScaleTypeForFits: function (imagesetName, scaleType) { + var imageset = this.getImagesetByName(imagesetName); + if (imageset != null && imageset.get_fitsProperties() != null) { + imageset.get_fitsProperties().scaleType = scaleType; + } else { + console.log(imagesetName + ' not found'); + } + }, + + _drawCrosshairs: function (context) { + if (context.gl == null) { + var ctx = context.device; + ctx.save(); + ctx.beginPath(); + ctx.strokeStyle = Settings.get_current().get_crosshairsColor(); + ctx.lineWidth = 2; + var x = context.width / 2, y = context.height / 2; + var halfLength = 5; + ctx.moveTo(x, y + halfLength); + ctx.lineTo(x, y - halfLength); + ctx.moveTo(x + halfLength, y); + ctx.lineTo(x - halfLength, y); + ctx.stroke(); + ctx.restore(); + } else { + if (this._crossHairs == null) { + // These coordinates are in clip space where the shape of the + // viewport is 1x1, so to get the crosshairs to appear square on + // the screen we have to apply the aspect ratio. + var halfHeight = 0.03; + var halfWidth = halfHeight * context.height / context.width; + this._crossHairs = new SimpleLineList(); + this._crossHairs.set_depthBuffered(false); + this._crossHairs.pure2D = true; + this._crossHairs.addLine(Vector3d.create(-halfWidth, 0, 0), Vector3d.create(halfWidth, 0, 0)); + this._crossHairs.addLine(Vector3d.create(0, -halfHeight, 0), Vector3d.create(0, halfHeight, 0)); + } + this._crossHairs.drawLines(context, 1, Color.load(Settings.get_current().get_crosshairsColor())); + } + }, + + captureThumbnail: function (blobReady) { + this.captureFrame(blobReady, 96, 45, 'image/jpeg', true); + }, + + captureCurrentFrame: function (blobReady, width, height, format) { + this.captureFrame(blobReady, width, height, format, false); + }, + + captureFrameForVideo: function (blobReady, width, height, format) { + var $this = this; + + var frameNumber = SpaceTimeController.currentFrameNumber; + var forVideo = function (blob) { + var containsIndex; + if (frameNumber === $this._videoQueueIndex) { + blobReady(blob); + $this._videoQueueIndex += 1; + + // Keep moving forward until we hit the next index that we're still waiting on + while ((containsIndex = ss.keyExists($this._videoBlobQueue, $this._videoQueueIndex)) || ($this._emptyFrames.indexOf($this._videoQueueIndex) >= 0)) { + if (containsIndex) { + blobReady($this._videoBlobQueue[$this._videoQueueIndex]); + $this._videoBlobQueue[$this._videoQueueIndex] = null; + } + else { + ss.remove($this._emptyFrames, $this._videoQueueIndex); + } + $this._videoQueueIndex += 1; + } + } + else { + if (blob != null) { + $this._videoBlobQueue[frameNumber] = blob; + } + else { + $this._emptyFrames.push(frameNumber); + } + } + if ($this._videoQueueIndex >= SpaceTimeController.totalFrames) { + $this._videoBlobReady = null; + $this._videoBlobQueue = null; + $this._videoQueueIndex = 0; + $this._emptyFrames.length = 0; + } + }; + this.captureCurrentFrame(forVideo, width, height, format); + }, + + captureFrame: function (blobReady, width, height, format, needRender) { + if (needRender) { + this.renderOneFrame(); // NB: this used to be Render() but that was almost surely not what we want + } + var image = document.createElement('img'); + image.addEventListener('load', function (e) { + var imageAspect = (image.width) / image.height; + var clientAspect = width / height; + var cw = width; + var ch = height; + if (imageAspect < clientAspect) { + ch = ss.truncate((cw / imageAspect)); + } + else { + cw = ss.truncate((ch * imageAspect)); + } + var cx = (width - cw) / 2; + var cy = (height - ch) / 2; + var temp = document.createElement('canvas'); + temp.height = height; + temp.width = width; + var ctx = temp.getContext('2d'); + ctx.drawImage(image, cx, cy, cw, ch); + if (typeof temp.msToBlob == 'function') { var blob = temp.msToBlob(); blobReady(blob); } else { temp.toBlob(blobReady, format); } + }, false); + image.src = globalWWTControl.canvas.toDataURL(); + }, + + clampZooms: function (rc) { + rc.viewCamera.zoom = DoubleUtilities.clamp(rc.viewCamera.zoom, this.get_zoomMin(), this.get_zoomMax()); + rc.targetCamera.zoom = DoubleUtilities.clamp(rc.targetCamera.zoom, this.get_zoomMin(), this.get_zoomMax()); + } +}; + +registerType("WWTControl", [WWTControl, WWTControl$, null]); + +// wwtlib.WWTControlBuilder + +export function WWTControlBuilder(divId) { + this._divId = null; + this._startRenderLoop = false; + this._startLat = 0; + this._startLng = 0; + this._startZoom = 360; + this._freestandingAssetBaseurl = ''; + this._startMode = ''; + this._divId = divId; +} + +var WWTControlBuilder$ = { + startRenderLoop: function (value) { + this._startRenderLoop = value; + }, + + initialView: function (lat, lng, zoom) { + this._startLat = lat; + this._startLng = lng; + this._startZoom = zoom; + }, + + freestandingMode: function (asset_baseurl) { + this._freestandingAssetBaseurl = asset_baseurl; + }, + + initialMode: function (value) { + this._startMode = value; + }, + + create: function () { + var freestandingMode = !!this._freestandingAssetBaseurl; + var trueStartMode; + if (!!this._startMode) { + trueStartMode = this._startMode; + } else if (freestandingMode) { + trueStartMode = 'black'; + } else { + trueStartMode = 'sky'; + } + set_freestandingMode(freestandingMode); + if (freestandingMode) { + URLHelpers.singleton.overrideAssetBaseurl(this._freestandingAssetBaseurl); + } + return WWTControl.initControl6(this._divId, this._startRenderLoop, this._startLat, this._startLng, this._startZoom, trueStartMode); + } +}; + +registerType("WWTControlBuilder", [WWTControlBuilder, WWTControlBuilder$, null]); + +// wwtlib.WWTElementEvent + +export function WWTElementEvent(x, y) { + this.offsetX = 0; + this.offsetY = 0; + this.offsetX = x; + this.offsetY = y; +} + +var WWTElementEvent$ = {}; + +registerType("WWTElementEvent", [WWTElementEvent, WWTElementEvent$, null]); diff --git a/engine/js/transpiled.js b/engine/js/transpiled.js deleted file mode 100644 index c3c5a605..00000000 --- a/engine/js/transpiled.js +++ /dev/null @@ -1,47678 +0,0 @@ -"use strict"; - -define('wwtlib', ['ss'], function (ss) { - var $global = this; - - // DAY_OF_WEEK - - var DAY_OF_WEEK = { - SUNDAY: 0, - MONDAY: 1, - TUESDAY: 2, - WEDNESDAY: 3, - THURSDAY: 4, - FRIDAY: 5, - SATURDAY: 6 - }; - - - // EO - - var EO = { - SUN: 0, - MERCURY: 1, - VENUS: 2, - MARS: 3, - JUPITER: 4, - SATURN: 5, - URANUS: 6, - NEPTUNE: 7, - PLUTO: 8 - }; - - - // wwtlib.ScaleTypes - - var ScaleTypes = { - linear: 0, - log: 1, - power: 2, - squareRoot: 3, - histogramEqualization: 4 - }; - - - // wwtlib.URLRewriteMode - - var URLRewriteMode = { - asIfAbsolute: 0, - originRelative: 1 - }; - - - // wwtlib.SolarSystemObjects - - var SolarSystemObjects = { - sun: 0, - mercury: 1, - venus: 2, - mars: 3, - jupiter: 4, - saturn: 5, - uranus: 6, - neptune: 7, - pluto: 8, - moon: 9, - io: 10, - europa: 11, - ganymede: 12, - callisto: 13, - ioShadow: 14, - europaShadow: 15, - ganymedeShadow: 16, - callistoShadow: 17, - sunEclipsed: 18, - earth: 19, - custom: 20, - undefined: 65536 - }; - - - // wwtlib.InterpolationType - - var InterpolationType = { - linear: 0, - easeIn: 1, - easeOut: 2, - easeInOut: 3, - exponential: 4, - defaultV: 5 - }; - - - // wwtlib.PointType - - var PointType = { - move: 0, - line: 1, - dash: 2, - start: 3 - }; - - - // wwtlib.LocationHint - - var LocationHint = { - slash: 0, - backslash: 1, - top: 2 - }; - - - // wwtlib.FolderGroup - - var FolderGroup = { - explorer: 0, - tour: 1, - search: 2, - constellation: 3, - view: 4, - goTo: 5, - community: 6, - context: 7, - voTable: 8, - imageStack: 9 - }; - - - // wwtlib.FolderRefreshType - - var FolderRefreshType = { - interval: 0, - conditionalGet: 1, - viewChange: 2 - }; - - - // wwtlib.FolderType - - var FolderType = { - earth: 0, - planet: 1, - sky: 2, - panorama: 3 - }; - - - // wwtlib.ThumbnailSize - - var ThumbnailSize = { - small: 0, - big: 1 - }; - - - // wwtlib.CullMode - - var CullMode = { - none: 0, - counterClockwise: 2, - clockwise: 1 - }; - - - // wwtlib.PointScaleTypes - - var PointScaleTypes = { - linear: 0, - power: 1, - log: 2, - constant: 3, - stellarMagnitude: 4 - }; - - - // wwtlib.ProjectionType - - var ProjectionType = { - mercator: 0, - equirectangular: 1, - tangent: 2, - tan: 2, - toast: 3, - spherical: 4, - skyImage: 5, - plotted: 6, - healpix: 7 - }; - - - // wwtlib.ImageSetType - - var ImageSetType = { - earth: 0, - planet: 1, - sky: 2, - panorama: 3, - solarSystem: 4, - sandbox: 5 - }; - - - // wwtlib.BandPass - - var BandPass = { - gamma: 0, - xRay: 1, - ultraviolet: 2, - visible: 3, - hydrogenAlpha: 4, - IR: 4, - microwave: 5, - radio: 6, - visibleNight: 6 - }; - - - // wwtlib.Classification - - var Classification = { - star: 1, - supernova: 2, - blackHole: 4, - neutronStar: 8, - doubleStar: 16, - multipleStars: 32, - asterism: 64, - constellation: 128, - openCluster: 256, - globularCluster: 512, - nebulousCluster: 1024, - nebula: 2048, - emissionNebula: 4096, - planetaryNebula: 8192, - reflectionNebula: 16384, - darkNebula: 32768, - giantMolecularCloud: 65536, - supernovaRemnant: 131072, - interstellarDust: 262144, - quasar: 524288, - galaxy: 1048576, - spiralGalaxy: 2097152, - irregularGalaxy: 4194304, - ellipticalGalaxy: 8388608, - knot: 16777216, - plateDefect: 33554432, - clusterOfGalaxies: 67108864, - otherNGC: 134217728, - unidentified: 268435456, - solarSystem: 536870912, - unfiltered: 1073741823, - stellar: 63, - stellarGroupings: 2032, - nebulae: 523264, - galactic: 133693440, - other: 436207616 - }; - - - // wwtlib.DataTypes - - var DataTypes = { - byteT: 0, - int16T: 1, - int32T: 2, - floatT: 3, - doubleT: 4, - none: 5 - }; - - - // wwtlib.AltUnits - - var AltUnits = { - meters: 1, - feet: 2, - inches: 3, - miles: 4, - kilometers: 5, - astronomicalUnits: 6, - lightYears: 7, - parsecs: 8, - megaParsecs: 9, - custom: 10 - }; - - - // wwtlib.FadeType - - var FadeType = { - fadeIn: 1, - fadeOut: 2, - both: 3, - none: 4 - }; - - - // wwtlib.ReferenceFrames - - var ReferenceFrames = { - sky: 0, - ecliptic: 1, - galactic: 2, - sun: 3, - mercury: 4, - venus: 5, - earth: 6, - mars: 7, - jupiter: 8, - saturn: 9, - uranus: 10, - neptune: 11, - pluto: 12, - moon: 13, - io: 14, - europa: 15, - ganymede: 16, - callisto: 17, - custom: 18, - identity: 19, - sandbox: 20 - }; - - - // wwtlib.ReferenceFrameTypes - - var ReferenceFrameTypes = { - fixedSherical: 0, - orbital: 1, - trajectory: 2, - synodic: 3 - }; - - - // wwtlib.CoordinatesTypes - - var CoordinatesTypes = { - spherical: 0, - rectangular: 1, - orbital: 2 - }; - - - // wwtlib.AltTypes - - var AltTypes = { - depth: 0, - altitude: 1, - distance: 2, - seaLevel: 3, - terrain: 4 - }; - - - // wwtlib.MarkerMixes - - var MarkerMixes = { - same_For_All: 0 - }; - - - // wwtlib.ColorMaps - - var ColorMaps = { - same_For_All: 0, - group_by_Values: 2, - per_Column_Literal: 3 - }; - - - // wwtlib.PlotTypes - - var PlotTypes = { - gaussian: 0, - point: 1, - circle: 2, - square: 3, - pushPin: 4, - custom: 5 - }; - - - // wwtlib.MarkerScales - - var MarkerScales = { - screen: 0, - world: 1 - }; - - - // wwtlib.RAUnits - - var RAUnits = { - hours: 0, - degrees: 1 - }; - - - // wwtlib.Primitives - - var Primitives = { - voBoolean: 1, - voBit: 2, - voUnsignedByte: 3, - voShort: 4, - voInt: 5, - voLong: 6, - voChar: 7, - voUnicodeChar: 8, - voFloat: 9, - voDouble: 10, - voFloatComplex: 11, - voDoubleComplex: 12, - voUndefined: 13 - }; - - - // wwtlib.Alignment - - var Alignment = { - center: 0, - left: 1 - }; - - - // wwtlib.StockSkyOverlayTypes - - var StockSkyOverlayTypes = { - empty: 0, - equatorialGrid: 1, - equatorialGridText: 2, - galacticGrid: 3, - galacticGridText: 4, - eclipticGrid: 5, - eclipticGridText: 6, - eclipticOverview: 7, - eclipticOverviewText: 8, - precessionChart: 9, - altAzGrid: 10, - altAzGridText: 11, - constellationFigures: 12, - constellationBoundaries: 13, - constellationFocusedOnly: 14, - constellationNames: 15, - constellationPictures: 16, - fadeToBlack: 17, - fadeToLogo: 18, - fadeToGradient: 19, - screenBroadcast: 20, - fadeRemoteOnly: 21, - skyGrids: 22, - constellations: 23, - solarSystemStars: 24, - solarSystemMilkyWay: 25, - solarSystemCosmos: 26, - solarSystemOrbits: 27, - solarSystemPlanets: 28, - solarSystemAsteroids: 29, - solarSystemLighting: 30, - solarSystemMinorOrbits: 31, - showEarthCloudLayer: 32, - showElevationModel: 33, - showAtmosphere: 34, - multiResSolarSystemBodies: 35, - auroraBorialis: 36, - earthCutAway: 37, - showSolarSystem: 38, - clouds8k: 39, - filedOfView: 40, - showISSModel: 41, - solarSystemCMB: 42, - mpcZone1: 43, - mpcZone2: 44, - mpcZone3: 45, - mpcZone4: 46, - mpcZone5: 47, - mpcZone6: 48, - mpcZone7: 49, - orbitFilters: 50 - }; - - - // wwtlib.OverlayAnchor - - var OverlayAnchor = { - sky: 0, - screen: 1 - }; - - - // wwtlib.AudioType - - var AudioType = { - music: 0, - voice: 1 - }; - - - // wwtlib.ShapeType - - var ShapeType = { - circle: 0, - rectagle: 1, - star: 2, - donut: 3, - arrow: 4, - line: 5, - openRectagle: 6 - }; - - - // wwtlib.LoopTypes - - var LoopTypes = { - loop: 0, - upDown: 1, - down: 2, - upDownOnce: 3, - once: 4, - begin: 5, - end: 6 - }; - - - // wwtlib.SelectionAnchor - - var SelectionAnchor = { - topLeft: 0, - top: 1, - topRight: 2, - right: 3, - bottomRight: 4, - bottom: 5, - bottomLeft: 6, - left: 7, - rotate: 8, - move: 9, - center: 10, - none: 11 - }; - - - // wwtlib.TextBorderStyle - - var TextBorderStyle = { - none: 0, - tight: 1, - small: 2, - medium: 3, - large: 4 - }; - - - // wwtlib.UserLevel - - var UserLevel = { - beginner: 0, - intermediate: 1, - advanced: 2, - educator: 3, - professional: 4 - }; - - - // wwtlib.TransitionType - - var TransitionType = { - slew: 0, - crossFade: 1, - crossCut: 2, - fadeOutIn: 3, - fadeIn: 4, - fadeOut: 5 - }; - - - // wwtlib.Keys - - var Keys = { - modifiers: -65536, - none: 0, - lButton: 1, - rButton: 2, - cancel: 3, - mButton: 4, - xButton1: 5, - xButton2: 6, - back: 8, - tab: 9, - lineFeed: 10, - clearKey: 12, - returnKey: 13, - enter: 13, - shiftKey: 16, - controlKey: 17, - menu: 18, - pause: 19, - capital: 20, - capsLock: 20, - kanaMode: 21, - hanguelMode: 21, - hangulMode: 21, - junjaMode: 23, - finalMode: 24, - hanjaMode: 25, - kanjiMode: 25, - escape: 27, - imeConvert: 28, - imeNonconvert: 29, - imeAccept: 30, - imeAceept: 30, - imeModeChange: 31, - space: 32, - prior: 33, - pageUp: 33, - next: 34, - pageDown: 34, - end: 35, - home: 36, - left: 37, - up: 38, - right: 39, - down: 40, - select: 41, - print: 42, - execute: 43, - snapshot: 44, - printScreen: 44, - insertKey: 45, - deleteKey: 46, - help: 47, - d0: 48, - d1: 49, - d2: 50, - d3: 51, - d4: 52, - d5: 53, - d6: 54, - d7: 55, - d8: 56, - d9: 57, - a: 65, - b: 66, - c: 67, - d: 68, - e: 69, - f: 70, - g: 71, - h: 72, - i: 73, - j: 74, - k: 75, - l: 76, - m: 77, - n: 78, - o: 79, - p: 80, - q: 81, - r: 82, - s: 83, - t: 84, - u: 85, - v: 86, - w: 87, - x: 88, - y: 89, - z: 90, - lWin: 91, - rWin: 92, - apps: 93, - sleep: 95, - numPad0: 96, - numPad1: 97, - numPad2: 98, - numPad3: 99, - numPad4: 100, - numPad5: 101, - numPad6: 102, - numPad7: 103, - numPad8: 104, - numPad9: 105, - multiply: 106, - add: 107, - separator: 108, - subtract: 109, - decimal: 110, - divide: 111, - f1: 112, - f2: 113, - f3: 114, - f4: 115, - f5: 116, - f6: 117, - f7: 118, - f8: 119, - f9: 120, - f10: 121, - f11: 122, - f12: 123, - f13: 124, - f14: 125, - f15: 126, - f16: 127, - f17: 128, - f18: 129, - f19: 130, - f20: 131, - f21: 132, - f22: 133, - f23: 134, - f24: 135, - numLock: 144, - scroll: 145, - lShiftKey: 160, - rShiftKey: 161, - lControlKey: 162, - rControlKey: 163, - lMenu: 164, - rMenu: 165, - browserBack: 166, - browserForward: 167, - browserRefresh: 168, - browserStop: 169, - browserSearch: 170, - browserFavorites: 171, - browserHome: 172, - volumeMute: 173, - volumeDown: 174, - volumeUp: 175, - mediaNextTrack: 176, - mediaPreviousTrack: 177, - mediaStop: 178, - mediaPlayPause: 179, - launchMail: 180, - selectMedia: 181, - launchApplication1: 182, - launchApplication2: 183, - oemSemicolon: 186, - oem1: 186, - oemplus: 187, - oemcomma: 188, - oemMinus: 189, - oemPeriod: 190, - oemQuestion: 191, - oem2: 191, - oemtilde: 192, - oem3: 192, - oemOpenBrackets: 219, - oem4: 219, - oemPipe: 220, - oem5: 220, - oemCloseBrackets: 221, - oem6: 221, - oemQuotes: 222, - oem7: 222, - oem8: 223, - oemBackslash: 226, - oem102: 226, - processKey: 229, - packet: 231, - attn: 246, - crsel: 247, - exsel: 248, - eraseEof: 249, - play: 250, - zoom: 251, - noName: 252, - pa1: 253, - oemClear: 254, - keyCode: 65535, - shift: 65536, - control: 131072, - alt: 262144 - }; - - - // wwtlib.DialogResult - - var DialogResult = { - OK: 1 - }; - - - // wwtlib.Formatting - - var Formatting = { - indented: 1 - }; - - - // wwtlib.StateType - - var StateType = { - pending: 0, - received: 1, - error: 2 - }; - - - // wwtlib.IFolder - - function IFolder() { } - - - // wwtlib.IThumbnail - - function IThumbnail() { } - - - // wwtlib.IPlace - - function IPlace() { } - - - // wwtlib.IUiController - - function IUiController() { } - - - // wwtlib.IViewMover - - function IViewMover() { } - - - // wwtlib.IUIServicesCallbacks - - function IUIServicesCallbacks() { } - - - // wwtlib.ISettings - - function ISettings() { } - - - // wwtlib.IUndoStep - - function IUndoStep() { } - - - // Imports - - function Imports() { - } - - - // GFX - - function GFX() { - } - - - // ABR - - function ABR() { - } - ABR.earthVelocity = function (JD) { - var T = (JD - 2451545) / 36525; - var L2 = 3.1761467 + 1021.3285546 * T; - var L3 = 1.7534703 + 628.3075849 * T; - var L4 = 6.2034809 + 334.0612431 * T; - var L5 = 0.5995465 + 52.9690965 * T; - var L6 = 0.8740168 + 21.3299095 * T; - var L7 = 5.4812939 + 7.4781599 * T; - var L8 = 5.3118863 + 3.8133036 * T; - var Ldash = 3.8103444 + 8399.6847337 * T; - var D = 5.1984667 + 7771.3771486 * T; - var Mdash = 2.3555559 + 8328.6914289 * T; - var F = 1.6279052 + 8433.4661601 * T; - var velocity = new C3D(); - var nAberrationCoefficients = GFX.g_ACft.length; - for (var i = 0; i < nAberrationCoefficients; i++) { - var Argument = GFX.g_ACft[i].l2 * L2 + GFX.g_ACft[i].l3 * L3 + GFX.g_ACft[i].l4 * L4 + GFX.g_ACft[i].l5 * L5 + GFX.g_ACft[i].l6 * L6 + GFX.g_ACft[i].l7 * L7 + GFX.g_ACft[i].l8 * L8 + GFX.g_ACft[i].ldash * Ldash + GFX.g_ACft[i].d * D + GFX.g_ACft[i].mdash * Mdash + GFX.g_ACft[i].f * F; - velocity.x += (GFX.g_ACft[i].xsin + GFX.g_ACft[i].xsint * T) * Math.sin(Argument); - velocity.x += (GFX.g_ACft[i].xcos + GFX.g_ACft[i].xcost * T) * Math.cos(Argument); - velocity.y += (GFX.g_ACft[i].ysin + GFX.g_ACft[i].ysint * T) * Math.sin(Argument); - velocity.y += (GFX.g_ACft[i].ycos + GFX.g_ACft[i].ycost * T) * Math.cos(Argument); - velocity.z += (GFX.g_ACft[i].zsin + GFX.g_ACft[i].zsint * T) * Math.sin(Argument); - velocity.z += (GFX.g_ACft[i].zcos + GFX.g_ACft[i].zcost * T) * Math.cos(Argument); - } - return velocity; - }; - ABR.eclipticAberration = function (Lambda, Beta, JD) { - var aberration = new COR(); - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var e = 0.016708634 - 4.2037E-05 * T - 1.267E-07 * Tsquared; - var pi = 102.93735 + 1.71946 * T + 0.00046 * Tsquared; - var k = 20.49552; - var SunLongitude = CAASun.geometricEclipticLongitude(JD); - pi = CT.d2R(pi); - Lambda = CT.d2R(Lambda); - Beta = CT.d2R(Beta); - SunLongitude = CT.d2R(SunLongitude); - aberration.x = (-k * Math.cos(SunLongitude - Lambda) + e * k * Math.cos(pi - Lambda)) / Math.cos(Beta) / 3600; - aberration.y = -k * Math.sin(Beta) * (Math.sin(SunLongitude - Lambda) - e * Math.sin(pi - Lambda)) / 3600; - return aberration; - }; - ABR.equatorialAberration = function (Alpha, Delta, JD) { - Alpha = CT.d2R(Alpha * 15); - Delta = CT.d2R(Delta); - var cosAlpha = Math.cos(Alpha); - var sinAlpha = Math.sin(Alpha); - var cosDelta = Math.cos(Delta); - var sinDelta = Math.sin(Delta); - var velocity = ABR.earthVelocity(JD); - var aberration = new COR(); - aberration.x = CT.r2H((velocity.y * cosAlpha - velocity.x * sinAlpha) / (17314463350 * cosDelta)); - aberration.y = CT.r2D(-(((velocity.x * cosAlpha + velocity.y * sinAlpha) * sinDelta - velocity.z * cosDelta) / 17314463350)); - return aberration; - }; - var ABR$ = { - - }; - - - // ACFT - - function ACFT(L2, L3, L4, L5, L6, L7, L8, Ldash, D, Mdash, F, xsin, xsint, xcos, xcost, ysin, ysint, ycos, ycost, zsin, zsint, zcos, zcost) { - this.l2 = 0; - this.l3 = 0; - this.l4 = 0; - this.l5 = 0; - this.l6 = 0; - this.l7 = 0; - this.l8 = 0; - this.ldash = 0; - this.d = 0; - this.mdash = 0; - this.f = 0; - this.xsin = 0; - this.xsint = 0; - this.xcos = 0; - this.xcost = 0; - this.ysin = 0; - this.ysint = 0; - this.ycos = 0; - this.ycost = 0; - this.zsin = 0; - this.zsint = 0; - this.zcos = 0; - this.zcost = 0; - this.l2 = L2; - this.l3 = L3; - this.l4 = L4; - this.l5 = L5; - this.l6 = L6; - this.l7 = L7; - this.l8 = L8; - this.ldash = Ldash; - this.d = D; - this.mdash = Mdash; - this.f = F; - this.xsin = xsin; - this.xsint = xsint; - this.xcos = xcos; - this.xcost = xcost; - this.ysin = ysin; - this.ysint = ysint; - this.ycos = ycos; - this.ycost = ycost; - this.zsin = zsin; - this.zsint = zsint; - this.zcos = zcos; - this.zcost = zcost; - } - var ACFT$ = { - - }; - - - // ASEP - - function ASEP() { - } - ASEP.separation = function (Alpha1, Delta1, Alpha2, Delta2) { - Delta1 = CT.d2R(Delta1); - Delta2 = CT.d2R(Delta2); - Alpha1 = CT.h2R(Alpha1); - Alpha2 = CT.h2R(Alpha2); - var x = Math.cos(Delta1) * Math.sin(Delta2) - Math.sin(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); - var y = Math.cos(Delta2) * Math.sin(Alpha2 - Alpha1); - var z = Math.sin(Delta1) * Math.sin(Delta2) + Math.cos(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); - var vvalue = Math.atan2(Math.sqrt(x * x + y * y), z); - vvalue = CT.r2D(vvalue); - if (vvalue < 0) { - vvalue += 180; - } - return vvalue; - }; - ASEP.positionAngle = function (alpha1, delta1, alpha2, delta2) { - var Alpha1; - var Delta1; - var Alpha2; - var Delta2; - Delta1 = CT.d2R(delta1); - Delta2 = CT.d2R(delta2); - Alpha1 = CT.h2R(alpha1); - Alpha2 = CT.h2R(alpha2); - var DeltaAlpha = Alpha1 - Alpha2; - var demoninator = Math.cos(Delta2) * Math.tan(Delta1) - Math.sin(Delta2) * Math.cos(DeltaAlpha); - var numerator = Math.sin(DeltaAlpha); - var vvalue = Math.atan2(numerator, demoninator); - vvalue = CT.r2D(vvalue); - return vvalue; - }; - ASEP.distanceFromGreatArc = function (Alpha1, Delta1, Alpha2, Delta2, Alpha3, Delta3) { - Delta1 = CT.d2R(Delta1); - Delta2 = CT.d2R(Delta2); - Delta3 = CT.d2R(Delta3); - Alpha1 = CT.h2R(Alpha1); - Alpha2 = CT.h2R(Alpha2); - Alpha3 = CT.h2R(Alpha3); - var X1 = Math.cos(Delta1) * Math.cos(Alpha1); - var X2 = Math.cos(Delta2) * Math.cos(Alpha2); - var Y1 = Math.cos(Delta1) * Math.sin(Alpha1); - var Y2 = Math.cos(Delta2) * Math.sin(Alpha2); - var Z1 = Math.sin(Delta1); - var Z2 = Math.sin(Delta2); - var A = Y1 * Z2 - Z1 * Y2; - var B = Z1 * X2 - X1 * Z2; - var C = X1 * Y2 - Y1 * X2; - var m = Math.tan(Alpha3); - var n = Math.tan(Delta3) / Math.cos(Alpha3); - var vvalue = Math.asin((A + B * m + C * n) / (Math.sqrt(A * A + B * B + C * C) * Math.sqrt(1 + m * m + n * n))); - vvalue = CT.r2D(vvalue); - if (vvalue < 0) { - vvalue = Math.abs(vvalue); - } - return vvalue; - }; - var ASEP$ = { - - }; - - - // COR - - function COR() { - this.x = 0; - this.y = 0; - this.x = 0; - this.y = 0; - } - COR.create = function (x, y) { - var item = new COR(); - item.x = x; - item.y = y; - return item; - }; - var COR$ = { - - }; - - - // C3D - - function C3D() { - this.x = 0; - this.y = 0; - this.z = 0; - this.x = 0; - this.y = 0; - this.z = 0; - } - C3D.create = function (x, y, z) { - var item = new C3D(); - item.x = x; - item.y = y; - item.z = z; - return item; - }; - var C3D$ = { - - }; - - - // CT - - function CT() { - } - CT.eq2Ec = function (Alpha, Delta, Epsilon) { - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - Epsilon = CT.d2R(Epsilon); - var Ecliptic = new COR(); - Ecliptic.x = CT.r2D(Math.atan2(Math.sin(Alpha) * Math.cos(Epsilon) + Math.tan(Delta) * Math.sin(Epsilon), Math.cos(Alpha))); - if (Ecliptic.x < 0) { - Ecliptic.x += 360; - } - Ecliptic.y = CT.r2D(Math.asin(Math.sin(Delta) * Math.cos(Epsilon) - Math.cos(Delta) * Math.sin(Epsilon) * Math.sin(Alpha))); - return Ecliptic; - }; - CT.ec2Eq = function (Lambda, Beta, Epsilon) { - Lambda = CT.d2R(Lambda); - Beta = CT.d2R(Beta); - Epsilon = CT.d2R(Epsilon); - var Equatorial = new COR(); - Equatorial.x = CT.r2H(Math.atan2(Math.sin(Lambda) * Math.cos(Epsilon) - Math.tan(Beta) * Math.sin(Epsilon), Math.cos(Lambda))); - if (Equatorial.x < 0) { - Equatorial.x += 24; - } - Equatorial.y = CT.r2D(Math.asin(Math.sin(Beta) * Math.cos(Epsilon) + Math.cos(Beta) * Math.sin(Epsilon) * Math.sin(Lambda))); - return Equatorial; - }; - CT.eq2H = function (LocalHourAngle, Delta, Latitude) { - LocalHourAngle = CT.h2R(LocalHourAngle); - Delta = CT.d2R(Delta); - Latitude = CT.d2R(Latitude); - var Horizontal = new COR(); - Horizontal.x = CT.r2D(Math.atan2(Math.sin(LocalHourAngle), Math.cos(LocalHourAngle) * Math.sin(Latitude) - Math.tan(Delta) * Math.cos(Latitude))); - if (Horizontal.x < 0) { - Horizontal.x += 360; - } - Horizontal.y = CT.r2D(Math.asin(Math.sin(Latitude) * Math.sin(Delta) + Math.cos(Latitude) * Math.cos(Delta) * Math.cos(LocalHourAngle))); - return Horizontal; - }; - CT.h2Eq = function (Azimuth, Altitude, Latitude) { - Azimuth = CT.d2R(Azimuth); - Altitude = CT.d2R(Altitude); - Latitude = CT.d2R(Latitude); - var Equatorial = new COR(); - Equatorial.x = CT.r2H(Math.atan2(Math.sin(Azimuth), Math.cos(Azimuth) * Math.sin(Latitude) + Math.tan(Altitude) * Math.cos(Latitude))); - if (Equatorial.x < 0) { - Equatorial.x += 24; - } - Equatorial.y = CT.r2D(Math.asin(Math.sin(Latitude) * Math.sin(Altitude) - Math.cos(Latitude) * Math.cos(Altitude) * Math.cos(Azimuth))); - return Equatorial; - }; - CT.eq2G = function (Alpha, Delta) { - Alpha = 192.25 - CT.h2D(Alpha); - Alpha = CT.d2R(Alpha); - Delta = CT.d2R(Delta); - var Galactic = new COR(); - Galactic.x = CT.r2D(Math.atan2(Math.sin(Alpha), Math.cos(Alpha) * Math.sin(CT.d2R(27.4)) - Math.tan(Delta) * Math.cos(CT.d2R(27.4)))); - Galactic.x = 303 - Galactic.x; - if (Galactic.x >= 360) { - Galactic.x -= 360; - } - Galactic.y = CT.r2D(Math.asin(Math.sin(Delta) * Math.sin(CT.d2R(27.4)) + Math.cos(Delta) * Math.cos(CT.d2R(27.4)) * Math.cos(Alpha))); - return Galactic; - }; - CT.g2Eq = function (l, b) { - l -= 123; - l = CT.d2R(l); - b = CT.d2R(b); - var Equatorial = new COR(); - Equatorial.x = CT.r2D(Math.atan2(Math.sin(l), Math.cos(l) * Math.sin(CT.d2R(27.4)) - Math.tan(b) * Math.cos(CT.d2R(27.4)))); - Equatorial.x += 12.25; - if (Equatorial.x < 0) { - Equatorial.x += 360; - } - Equatorial.x = CT.d2H(Equatorial.x); - Equatorial.y = CT.r2D(Math.asin(Math.sin(b) * Math.sin(CT.d2R(27.4)) + Math.cos(b) * Math.cos(CT.d2R(27.4)) * Math.cos(l))); - return Equatorial; - }; - CT.d2R = function (Degrees) { - return Degrees * 0.0174532925199433; - }; - CT.r2D = function (Radians) { - return Radians * 57.2957795130823; - }; - CT.r2H = function (Radians) { - return Radians * 3.81971863420549; - }; - CT.h2R = function (Hours) { - return Hours * 0.261799387799149; - }; - CT.h2D = function (Hours) { - return Hours * 15; - }; - CT.d2H = function (Degrees) { - return Degrees / 15; - }; - CT.PI = function () { - return 3.14159265358979; - }; - CT.m360 = function (Degrees) { - return Degrees - Math.floor(Degrees / 360) * 360; - }; - CT.m24 = function (HourAngle) { - return HourAngle - Math.floor(HourAngle / 24) * 24; - }; - CT.dmS2D = function (Degrees, Minutes, Seconds) { - return CT.dmS2Dp(Degrees, Minutes, Seconds, true); - }; - CT.dmS2Dp = function (Degrees, Minutes, Seconds, bPositive) { - if (!bPositive) { - console.assert(Degrees >= 0); - console.assert(Minutes >= 0); - console.assert(Seconds >= 0); - } - if (bPositive) { - return Degrees + Minutes / 60 + Seconds / 3600; - } - else { - return -Degrees - Minutes / 60 - Seconds / 3600; - } - }; - var CT$ = { - - }; - - - // CalD - - function CalD() { - this.year = 0; - this.month = 0; - this.day = 0; - this.year = 0; - this.month = 0; - this.day = 0; - } - CalD.create = function (year, month, day) { - var item = new CalD(); - item.year = year; - item.month = month; - item.day = day; - return item; - }; - var CalD$ = { - - }; - - - // DT - - function DT() { - this.m_dblJulian = 0; - this.m_bGregorianCalendar = false; - this.m_dblJulian = 0; - this.m_bGregorianCalendar = false; - } - DT.create = function (Year, Month, Day, bGregorianCalendar) { - var item = new DT(); - item.set(Year, Month, Day, 0, 0, 0, bGregorianCalendar); - return item; - }; - DT.createHMS = function (Year, Month, Day, Hour, Minute, Second, bGregorianCalendar) { - var item = new DT(); - item.set(Year, Month, Day, Hour, Minute, Second, bGregorianCalendar); - return item; - }; - DT.createJD = function (JD, bGregorianCalendar) { - var item = new DT(); - item.setJD(JD, bGregorianCalendar); - return item; - }; - DT.dateToJD = function (Year, Month, Day, bGregorianCalendar) { - var Y = Year; - var M = Month; - if (M < 3) { - Y = Y - 1; - M = M + 12; - } - var A = 0; - var B = 0; - if (bGregorianCalendar) { - A = ss.truncate((Y / 100)); - B = 2 - A + ss.truncate((A / 4)); - } - return ss.truncate((365.25 * (Y + 4716))) + ss.truncate((30.6001 * (M + 1))) + Day + B - 1524.5; - }; - DT.isLeap = function (Year, bGregorianCalendar) { - if (bGregorianCalendar) { - if (!(Year % 100)) { - return (!(Year % 400)) ? true : false; - } - else { - return (!(Year % 4)) ? true : false; - } - } - else { - return (!(Year % 4)) ? true : false; - } - }; - DT.afterPapalReform = function (Year, Month, Day) { - return ((Year > 1582) || ((Year === 1582) && (Month > 10)) || ((Year === 1582) && (Month === 10) && (Day >= 15))); - }; - DT.afterPapalReformJD = function (JD) { - return (JD >= 2299160.5); - }; - DT.dayOfYearJD = function (JD, Year, bGregorianCalendar) { - return JD - DT.dateToJD(Year, 1, 1, bGregorianCalendar) + 1; - }; - DT.daysInMonthForMonth = function (Month, bLeap) { - console.assert(Month >= 1 && Month <= 12); - var MonthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]; - if (bLeap) { - MonthLength[1]++; - } - return MonthLength[Month - 1]; - }; - DT.INT = function (vvalue) { - if (vvalue >= 0) { - return ss.truncate(vvalue); - } - else { - return ss.truncate((vvalue - 1)); - } - }; - var DT$ = { - julian: function () { - return this.m_dblJulian; - }, - day: function () { - var D = this.get(); - return ss.truncate(D[2]); - }, - month: function () { - var D = this.get(); - return ss.truncate(D[1]); - }, - year: function () { - var D = this.get(); - return ss.truncate(D[0]); - }, - hour: function () { - var D = this.get(); - return ss.truncate(D[3]); - }, - minute: function () { - var D = this.get(); - return ss.truncate(D[4]); - }, - second: function () { - var D = this.get(); - return ss.truncate(D[5]); - }, - set: function (Year, Month, Day, Hour, Minute, Second, bGregorianCalendar) { - var dblDay = Day + (Hour / 24) + (Minute / 1440) + (Second / 86400); - this.setJD(DT.dateToJD(Year, Month, dblDay, bGregorianCalendar), bGregorianCalendar); - }, - setJD: function (JD, bGregorianCalendar) { - this.m_dblJulian = JD; - this.setInGregorianCalendar(bGregorianCalendar); - }, - setInGregorianCalendar: function (bGregorianCalendar) { - var bAfterPapalReform = (this.m_dblJulian >= 2299160.5); - this.m_bGregorianCalendar = bGregorianCalendar && bAfterPapalReform; - }, - get: function () { - var Year; - var Month; - var Day; - var Hour; - var Minute; - var Second; - var JD = this.m_dblJulian + 0.5; - var tempZ = Math.floor(JD); - var F = JD - tempZ; - var Z = ss.truncate(tempZ); - var A; - if (this.m_bGregorianCalendar) { - var alpha = ss.truncate(((Z - 1867216.25) / 36524.25)); - A = Z + 1 + alpha - ss.truncate((alpha / 4)); - } - else { - A = Z; - } - var B = A + 1524; - var C = ss.truncate(((B - 122.1) / 365.25)); - var D = ss.truncate((365.25 * C)); - var E = ss.truncate(((B - D) / 30.6001)); - var dblDay = B - D - ss.truncate((30.6001 * E)) + F; - Day = ss.truncate(dblDay); - if (E < 14) { - Month = E - 1; - } - else { - Month = E - 13; - } - if (Month > 2) { - Year = C - 4716; - } - else { - Year = C - 4715; - } - tempZ = Math.floor(dblDay); - F = dblDay - tempZ; - Hour = ss.truncate((F * 24)); - Minute = ss.truncate(((F - Hour / 24) * 1440)); - Second = (F - (Hour / 24) - (Minute / 1440)) * 86400; - return [Year, Month, Day, Hour, Minute, Second]; - }, - dayOfWeek: function () { - return (ss.truncate((this.m_dblJulian + 1.5)) % 7); - }, - dayOfYear: function () { - var year = ss.truncate(this.get()[0]); - return DT.dayOfYearJD(this.m_dblJulian, year, DT.afterPapalReform(year, 1, 1)); - }, - daysInMonth: function () { - var D = this.get(); - var Year = ss.truncate(D[0]); - var Month = ss.truncate(D[1]); - return DT.daysInMonthForMonth(Month, DT.isLeap(Year, this.m_bGregorianCalendar)); - }, - daysInYear: function () { - var D = this.get(); - var Year = ss.truncate(D[0]); - if (DT.isLeap(Year, this.m_bGregorianCalendar)) { - return 366; - } - else { - return 365; - } - }, - leap: function () { - return DT.isLeap(this.year(), this.m_bGregorianCalendar); - }, - inGregorianCalendar: function () { - return this.m_bGregorianCalendar; - }, - fractionalYear: function () { - var D = this.get(); - var Year = ss.truncate(D[0]); - var Month = ss.truncate(D[1]); - var Day = ss.truncate(D[2]); - var Hour = ss.truncate(D[3]); - var Minute = ss.truncate(D[4]); - var Second = D[5]; - var DaysInYear; - if (DT.isLeap(Year, this.m_bGregorianCalendar)) { - DaysInYear = 366; - } - else { - DaysInYear = 365; - } - return Year + ((this.m_dblJulian - DT.dateToJD(Year, 1, 1, DT.afterPapalReform(Year, 1, 1))) / DaysInYear); - } - }; - - - // DYT - - function DYT() { - } - DYT.deltaT = function (JD) { - var date = DT.createJD(JD, DT.afterPapalReformJD(JD)); - var y = date.fractionalYear(); - var T = (y - 2000) / 100; - var Delta; - if (y < 948) { - Delta = 2177 + (497 * T) + (44.1 * T * T); - } - else if (y < 1620) { - Delta = 102 + (102 * T) + (25.3 * T * T); - } - else if (y < 1998) { - var Index = ss.truncate(((y - 1620) / 2)); - console.assert(Index < GFX.deltaTTable.length); - y = y / 2 - Index - 810; - Delta = (GFX.deltaTTable[Index] + (GFX.deltaTTable[Index + 1] - GFX.deltaTTable[Index]) * y); - } - else if (y <= 2000) { - var nLookupSize = GFX.deltaTTable.length; - Delta = GFX.deltaTTable[nLookupSize - 1]; - } - else if (y < 2100) { - Delta = 102 + (102 * T) + (25.3 * T * T) + 0.37 * (y - 2100); - } - else { - Delta = 102 + (102 * T) + (25.3 * T * T); - } - return Delta; - }; - var DYT$ = { - - }; - - - // CAAEarth - - function CAAEarth() { - } - CAAEarth.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0EarthCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0EarthCoefficients[i].a * Math.cos(GFX.g_L0EarthCoefficients[i].b + GFX.g_L0EarthCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1EarthCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1EarthCoefficients[i].a * Math.cos(GFX.g_L1EarthCoefficients[i].b + GFX.g_L1EarthCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2EarthCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2EarthCoefficients[i].a * Math.cos(GFX.g_L2EarthCoefficients[i].b + GFX.g_L2EarthCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3EarthCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3EarthCoefficients[i].a * Math.cos(GFX.g_L3EarthCoefficients[i].b + GFX.g_L3EarthCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4EarthCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4EarthCoefficients[i].a * Math.cos(GFX.g_L4EarthCoefficients[i].b + GFX.g_L4EarthCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5EarthCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5EarthCoefficients[i].a * Math.cos(GFX.g_L5EarthCoefficients[i].b + GFX.g_L5EarthCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAEarth.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0EarthCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0EarthCoefficients[i].a * Math.cos(GFX.g_B0EarthCoefficients[i].b + GFX.g_B0EarthCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1EarthCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1EarthCoefficients[i].a * Math.cos(GFX.g_B1EarthCoefficients[i].b + GFX.g_B1EarthCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2EarthCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2EarthCoefficients[i].a * Math.cos(GFX.g_B2EarthCoefficients[i].b + GFX.g_B2EarthCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3EarthCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3EarthCoefficients[i].a * Math.cos(GFX.g_B3EarthCoefficients[i].b + GFX.g_B3EarthCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4EarthCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4EarthCoefficients[i].a * Math.cos(GFX.g_B4EarthCoefficients[i].b + GFX.g_B4EarthCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAEarth.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nR0Coefficients = GFX.g_R0EarthCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0EarthCoefficients[i].a * Math.cos(GFX.g_R0EarthCoefficients[i].b + GFX.g_R0EarthCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1EarthCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1EarthCoefficients[i].a * Math.cos(GFX.g_R1EarthCoefficients[i].b + GFX.g_R1EarthCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2EarthCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2EarthCoefficients[i].a * Math.cos(GFX.g_R2EarthCoefficients[i].b + GFX.g_R2EarthCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3EarthCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3EarthCoefficients[i].a * Math.cos(GFX.g_R3EarthCoefficients[i].b + GFX.g_R3EarthCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4EarthCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4EarthCoefficients[i].a * Math.cos(GFX.g_R4EarthCoefficients[i].b + GFX.g_R4EarthCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; - }; - CAAEarth.sunMeanAnomaly = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(357.5291092 + 35999.0502909 * T - 0.0001536 * Tsquared + Tcubed / 24490000); - }; - CAAEarth.eccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return 1 - 0.002516 * T - 7.4E-06 * Tsquared; - }; - CAAEarth.eclipticLongitudeJ2000 = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nL0Coefficients = GFX.g_L0EarthCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0EarthCoefficients[i].a * Math.cos(GFX.g_L0EarthCoefficients[i].b + GFX.g_L0EarthCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1EarthCoefficientsJ2000.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_L1EarthCoefficientsJ2000[i].b + GFX.g_L1EarthCoefficientsJ2000[i].c * rho); - } - var nL2Coefficients = GFX.g_L2EarthCoefficientsJ2000.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_L2EarthCoefficientsJ2000[i].b + GFX.g_L2EarthCoefficientsJ2000[i].c * rho); - } - var nL3Coefficients = GFX.g_L3EarthCoefficientsJ2000.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_L3EarthCoefficientsJ2000[i].b + GFX.g_L3EarthCoefficientsJ2000[i].c * rho); - } - var nL4Coefficients = GFX.g_L4EarthCoefficientsJ2000.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_L4EarthCoefficientsJ2000[i].b + GFX.g_L4EarthCoefficientsJ2000[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAEarth.eclipticLatitudeJ2000 = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0EarthCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0EarthCoefficients[i].a * Math.cos(GFX.g_B0EarthCoefficients[i].b + GFX.g_B0EarthCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1EarthCoefficientsJ2000.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_B1EarthCoefficientsJ2000[i].b + GFX.g_B1EarthCoefficientsJ2000[i].c * rho); - } - var nB2Coefficients = GFX.g_B2EarthCoefficientsJ2000.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_B2EarthCoefficientsJ2000[i].b + GFX.g_B2EarthCoefficientsJ2000[i].c * rho); - } - var nB3Coefficients = GFX.g_B3EarthCoefficientsJ2000.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_B3EarthCoefficientsJ2000[i].b + GFX.g_B3EarthCoefficientsJ2000[i].c * rho); - } - var nB4Coefficients = GFX.g_B4EarthCoefficientsJ2000.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4EarthCoefficientsJ2000[i].a * Math.cos(GFX.g_B4EarthCoefficientsJ2000[i].b + GFX.g_B4EarthCoefficientsJ2000[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - var CAAEarth$ = { - - }; - - - // VSC - - function VSC(a, b, c) { - this.a = 0; - this.b = 0; - this.c = 0; - this.a = a; - this.b = b; - this.c = c; - } - var VSC$ = { - - }; - - - // CAAEclipticalElementDetails - - function CAAEclipticalElementDetails() { - this.i = 0; - this.w = 0; - this.omega = 0; - this.i = 0; - this.w = 0; - this.omega = 0; - } - var CAAEclipticalElementDetails$ = { - - }; - - - // CAAEclipticalElements - - function CAAEclipticalElements() { - } - CAAEclipticalElements.calculate = function (i0, w0, omega0, JD0, JD) { - var T = (JD0 - 2451545) / 36525; - var Tsquared = T * T; - var t = (JD - JD0) / 36525; - var tsquared = t * t; - var tcubed = tsquared * t; - var i0rad = CT.d2R(i0); - var omega0rad = CT.d2R(omega0); - var eta = (47.0029 - 0.06603 * T + 0.000598 * Tsquared) * t + (-0.03302 + 0.000598 * T) * tsquared + 6E-05 * tcubed; - eta = CT.d2R(CT.dmS2D(0, 0, eta)); - var pi = 174.876384 * 3600 + 3289.4789 * T + 0.60622 * Tsquared - (869.8089 + 0.50491 * T) * t + 0.03536 * tsquared; - pi = CT.d2R(CT.dmS2D(0, 0, pi)); - var p = (5029.0966 + 2.22226 * T - 4.2E-05 * Tsquared) * t + (1.11113 - 4.2E-05 * T) * tsquared - 6E-06 * tcubed; - p = CT.d2R(CT.dmS2D(0, 0, p)); - var sini0rad = Math.sin(i0rad); - var cosi0rad = Math.cos(i0rad); - var sinomega0rad_pi = Math.sin(omega0rad - pi); - var cosomega0rad_pi = Math.cos(omega0rad - pi); - var sineta = Math.sin(eta); - var coseta = Math.cos(eta); - var A = sini0rad * sinomega0rad_pi; - var B = -sineta * cosi0rad + coseta * sini0rad * cosomega0rad_pi; - var irad = Math.asin(Math.sqrt(A * A + B * B)); - var details = new CAAEclipticalElementDetails(); - details.i = CT.r2D(irad); - var cosi = cosi0rad * coseta + sini0rad * sineta * cosomega0rad_pi; - if (cosi < 0) { - details.i = 180 - details.i; - } - var phi = pi + p; - details.omega = CT.m360(CT.r2D(Math.atan2(A, B) + phi)); - A = -sineta * sinomega0rad_pi; - B = sini0rad * coseta - cosi0rad * sineta * cosomega0rad_pi; - var deltaw = CT.r2D(Math.atan2(A, B)); - details.w = CT.m360(w0 + deltaw); - return details; - }; - CAAEclipticalElements.fK4B1950ToFK5J2000 = function (i0, w0, omega0) { - var L = CT.d2R(5.19856209); - var J = CT.d2R(0.00651966); - var i0rad = CT.d2R(i0); - var omega0rad = CT.d2R(omega0); - var sini0rad = Math.sin(i0rad); - var cosi0rad = Math.cos(i0rad); - var cosJ = Math.cos(J); - var sinJ = Math.sin(J); - var W = L + omega0rad; - var cosW = Math.cos(W); - var sinW = Math.sin(W); - var A = sinJ * sinW; - var B = sini0rad * cosJ + cosi0rad * sinJ * cosW; - var details = new CAAEclipticalElementDetails(); - details.i = CT.r2D(Math.asin(Math.sqrt(A * A + B * B))); - var cosi = cosi0rad * cosJ - sini0rad * sinJ * cosW; - if (cosi < 0) { - details.i = 180 - details.i; - } - details.w = CT.m360(w0 + CT.r2D(Math.atan2(A, B))); - details.omega = CT.m360(CT.r2D(Math.atan2(sini0rad * sinW, cosi0rad * sinJ + sini0rad * cosJ * cosW)) - 4.50001688); - return details; - }; - var CAAEclipticalElements$ = { - - }; - - - // EPO - - function EPO() { - } - EPO.mercuryMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(252.250906 + 149474.0722491 * T + 0.0003035 * Tsquared + 1.8E-08 * Tcubed); - }; - EPO.mercurySemimajorAxis = function (UnnamedParameter1) { - return 0.38709831; - }; - EPO.mercuryEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.20563175 + 2.0407E-05 * T - 2.83E-08 * Tsquared - 1.8E-10 * Tcubed; - }; - EPO.mercuryInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(7.004986 + 0.0018215 * T - 1.81E-05 * Tsquared + 5.6E-08 * Tcubed); - }; - EPO.mercuryLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(48.330893 + 1.1861883 * T + 0.00017542 * Tsquared + 2.15E-07 * Tcubed); - }; - EPO.mercuryLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(77.456119 + 1.5564776 * T + 0.00029544 * Tsquared + 9E-09 * Tcubed); - }; - EPO.venusMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(181.979801 + 58519.2130302 * T + 0.00031014 * Tsquared + 1.5E-08 * Tcubed); - }; - EPO.venusSemimajorAxis = function (UnnamedParameter1) { - return 0.72332982; - }; - EPO.venusEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.00677192 - 4.7765E-05 * T + 9.81E-08 * Tsquared + 4.6E-10 * Tcubed; - }; - EPO.venusInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(3.394662 + 0.0010037 * T - 8.8E-07 * Tsquared - 7E-09 * Tcubed); - }; - EPO.venusLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(76.67992 + 0.9011206 * T + 0.00040618 * Tsquared - 9.3E-08 * Tcubed); - }; - EPO.venusLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(131.563703 + 1.4022288 * T - 0.00107618 * Tsquared - 5.678E-06 * Tcubed); - }; - EPO.earthMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(100.466457 + 36000.7698278 * T + 0.00030322 * Tsquared + 2E-08 * Tcubed); - }; - EPO.earthSemimajorAxis = function (UnnamedParameter1) { - return 1.000001018; - }; - EPO.earthEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.01670863 - 4.2037E-05 * T - 1.267E-07 * Tsquared + 1.4E-10 * Tcubed; - }; - EPO.earthInclination = function (UnnamedParameter1) { - return 0; - }; - EPO.earthLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(102.937348 + 1.17195366 * T + 0.00045688 * Tsquared - 1.8E-08 * Tcubed); - }; - EPO.marsMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(355.433 + 19141.6964471 * T + 0.00031052 * Tsquared + 1.6E-08 * Tcubed); - }; - EPO.marsSemimajorAxis = function (UnnamedParameter1) { - return 1.523679342; - }; - EPO.marsEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.09340065 + 9.0484E-05 * T - 8.06E-08 * Tsquared - 2.5E-10 * Tcubed; - }; - EPO.marsInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(1.849726 - 0.0006011 * T + 1.276E-05 * Tsquared - 7E-09 * Tcubed); - }; - EPO.marsLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(49.588093 + 0.7720959 * T + 1.557E-05 * Tsquared + 2.267E-06 * Tcubed); - }; - EPO.marsLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(336.060234 + 1.8410449 * T + 0.00013477 * Tsquared + 5.36E-07 * Tcubed); - }; - EPO.jupiterMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(34.351519 + 3036.3027748 * T + 0.0002233 * Tsquared + 3.7E-08 * Tcubed); - }; - EPO.jupiterSemimajorAxis = function (JD) { - var T = (JD - 2451545) / 36525; - return 5.202603209 + 1.913E-07 * T; - }; - EPO.jupiterEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.04849793 + 0.000163225 * T - 4.714E-07 * Tsquared - 2.01E-09 * Tcubed; - }; - EPO.jupiterInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(1.303267 - 0.0054965 * T + 4.66E-06 * Tsquared - 2E-09 * Tcubed); - }; - EPO.jupiterLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(100.464407 + 1.0209774 * T + 0.00040315 * Tsquared + 4.04E-07 * Tcubed); - }; - EPO.jupiterLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(14.331207 + 1.6126352 * T + 0.00103042 * Tsquared - 4.464E-06 * Tcubed); - }; - EPO.saturnMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(50.077444 + 1223.5110686 * T + 0.00051908 * Tsquared - 3E-08 * Tcubed); - }; - EPO.saturnSemimajorAxis = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return 9.554909192 - 2.139E-06 * T + 4E-09 * Tsquared; - }; - EPO.saturnEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.05554814 - 0.0003446641 * T - 6.436E-07 * Tsquared + 3.4E-09 * Tcubed; - }; - EPO.saturnInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(2.488879 - 0.0037362 * T - 1.519E-05 * Tsquared + 8.7E-08 * Tcubed); - }; - EPO.saturnLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(113.665503 + 0.877088 * T - 0.00012176 * Tsquared - 2.249E-06 * Tcubed); - }; - EPO.saturnLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(93.057237 + 1.19637613 * T + 0.00083753 * Tsquared + 4.928E-06 * Tcubed); - }; - EPO.uranusMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(314.055005 + 429.8640561 * T + 0.0003039 * Tsquared + 2.6E-08 * Tcubed); - }; - EPO.uranusSemimajorAxis = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return 19.218446062 - 3.72E-08 * T + 9.8E-10 * Tsquared; - }; - EPO.uranusEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.04638122 - 2.7293E-05 * T + 7.89E-08 * Tsquared + 2.4E-10 * Tcubed; - }; - EPO.uranusInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(0.773197 + 0.0007744 * T + 3.749E-05 * Tsquared - 9.2E-08 * Tcubed); - }; - EPO.uranusLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(74.005957 + 0.5211278 * T + 0.00133947 * Tsquared + 1.8484E-05 * Tcubed); - }; - EPO.uranusLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(173.005291 + 1.486379 * T + 0.00021406 * Tsquared + 4.34E-07 * Tcubed); - }; - EPO.neptuneMeanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(304.348665 + 219.8833092 * T + 0.00030882 * Tsquared + 1.8E-08 * Tcubed); - }; - EPO.neptuneSemimajorAxis = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return 30.110386869 - 1.663E-07 * T + 6.9E-10 * Tsquared; - }; - EPO.neptuneEccentricity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tcubed = T * T * T; - return 0.00945575 + 6.033E-06 * T - 5E-11 * Tcubed; - }; - EPO.neptuneInclination = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(1.769953 - 0.0093082 * T - 7.08E-06 * Tsquared + 2.7E-08 * Tcubed); - }; - EPO.neptuneLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(131.784057 + 1.1022039 * T + 0.00025952 * Tsquared - 6.37E-07 * Tcubed); - }; - EPO.neptuneLongitudePerihelion = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(48.120276 + 1.4262957 * T + 0.00038434 * Tsquared + 2E-08 * Tcubed); - }; - EPO.mercuryMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(252.250906 + 149472.6746358 * T - 5.36E-06 * Tsquared + 2E-09 * Tcubed); - }; - EPO.mercuryInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(7.004986 - 0.0059516 * T + 8E-07 * Tsquared + 4.3E-08 * Tcubed); - }; - EPO.mercuryLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(48.330893 - 0.1254227 * T - 8.833E-05 * Tsquared - 2E-07 * Tcubed); - }; - EPO.mercuryLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(77.456119 + 0.1588643 * T - 1.342E-05 * Tsquared - 7E-09 * Tcubed); - }; - EPO.venusMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(181.979801 + 58517.815676 * T + 1.65E-06 * Tsquared - 2E-09 * Tcubed); - }; - EPO.venusInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(3.394662 - 0.0008568 * T - 3.244E-05 * Tsquared + 9E-09 * Tcubed); - }; - EPO.venusLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(76.67992 - 0.2780134 * T - 0.00014257 * Tsquared - 1.64E-07 * Tcubed); - }; - EPO.venusLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(131.563703 + 0.0048746 * T - 0.00138467 * Tsquared - 5.695E-06 * Tcubed); - }; - EPO.earthMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(100.466457 + 35999.3728565 * T - 5.68E-06 * Tsquared - 1E-09 * Tcubed); - }; - EPO.earthInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return 0.0130548 * T - 9.31E-06 * Tsquared - 3.4E-08 * Tcubed; - }; - EPO.earthLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(174.873176 - 0.241098 * T + 4.262E-05 * Tsquared + 1E-09 * Tcubed); - }; - EPO.earthLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(102.937348 + 0.3225654 * T + 0.00014799 * Tsquared - 3.9E-08 * Tcubed); - }; - EPO.marsMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(355.433 + 19140.2993039 * T + 2.62E-06 * Tsquared - 3E-09 * Tcubed); - }; - EPO.marsInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(1.849726 - 0.0081477 * T - 2.255E-05 * Tsquared - 2.9E-08 * Tcubed); - }; - EPO.marsLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(49.588093 - 0.295025 * T - 0.00064048 * Tsquared - 1.964E-06 * Tcubed); - }; - EPO.marsLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(336.060234 + 0.4439016 * T - 0.00017313 * Tsquared + 5.18E-07 * Tcubed); - }; - EPO.jupiterMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(34.351519 + 3034.9056606 * T - 8.501E-05 * Tsquared + 1.6E-08 * Tcubed); - }; - EPO.jupiterInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(1.303267 - 0.0019877 * T + 3.32E-05 * Tsquared + 9.7E-08 * Tcubed); - }; - EPO.jupiterLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(100.464407 + 0.1767232 * T + 0.000907 * Tsquared - 7.272E-06 * Tcubed); - }; - EPO.jupiterLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(14.331207 + 0.2155209 * T + 0.00072211 * Tsquared - 4.485E-06 * Tcubed); - }; - EPO.saturnMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(50.077444 + 1222.1138488 * T + 0.00021004 * Tsquared - 4.6E-08 * Tcubed); - }; - EPO.saturnInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(2.488879 + 0.0025514 * T - 4.906E-05 * Tsquared + 1.7E-08 * Tcubed); - }; - EPO.saturnLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(113.665503 - 0.2566722 * T - 0.00018399 * Tsquared + 4.8E-07 * Tcubed); - }; - EPO.saturnLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(93.057237 + 0.5665415 * T + 0.0005285 * Tsquared + 4.912E-06 * Tcubed); - }; - EPO.uranusMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(314.055005 + 428.4669983 * T - 4.86E-06 * Tsquared + 6E-09 * Tcubed); - }; - EPO.uranusInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(0.773197 - 0.0016869 * T + 3.49E-06 * Tsquared + 1.6E-08 * Tcubed); - }; - EPO.uranusLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(74.005957 + 0.0741431 * T + 0.00040539 * Tsquared + 1.19E-07 * Tcubed); - }; - EPO.uranusLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(173.005291 + 0.0893212 * T - 9.47E-05 * Tsquared + 4.14E-07 * Tcubed); - }; - EPO.neptuneMeanLongitudeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(304.348665 + 218.4862002 * T + 5.9E-07 * Tsquared - 2E-09 * Tcubed); - }; - EPO.neptuneInclinationJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return CT.m360(1.769953 + 0.0002256 * T + 2.3E-07 * Tsquared); - }; - EPO.neptuneLongitudeAscendingNodeJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - return CT.m360(131.784057 - 0.0061651 * T - 2.19E-06 * Tsquared - 7.8E-08 * Tcubed); - }; - EPO.neptuneLongitudePerihelionJ2000 = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - return CT.m360(48.120276 + 0.0291866 * T + 7.61E-05 * Tsquared); - }; - var EPO$ = { - - }; - - - // EOE - - function EOE() { - this.a = 0; - this.e = 0; - this.i = 0; - this.w = 0; - this.omega = 0; - this.jdEquinox = 0; - this.t = 0; - this.n = 0; - this.meanAnnomolyOut = 0; - this.a = 0; - this.e = 0; - this.i = 0; - this.w = 0; - this.omega = 0; - this.jdEquinox = 0; - this.t = 0; - } - EOE._create = function (br) { - var tmp = new EOE(); - tmp.a = br.readSingle(); - tmp.e = br.readSingle(); - tmp.i = br.readSingle(); - tmp.w = br.readSingle(); - tmp.omega = br.readSingle(); - tmp.jdEquinox = br.readSingle(); - tmp.t = br.readSingle(); - return tmp; - }; - var EOE$ = { - - }; - - - // EPD - - function EPD() { - this.apparentGeocentricLongitude = 0; - this.apparentGeocentricLatitude = 0; - this.apparentGeocentricDistance = 0; - this.apparentLightTime = 0; - this.apparentGeocentricRA = 0; - this.apparentGeocentricDeclination = 0; - this.apparentGeocentricLongitude = 0; - this.apparentGeocentricLatitude = 0; - this.apparentGeocentricDistance = 0; - this.apparentLightTime = 0; - this.apparentGeocentricRA = 0; - this.apparentGeocentricDeclination = 0; - } - var EPD$ = { - - }; - - - // EOD - - function EOD() { - this.heliocentricRectangularEquatorial = new C3D(); - this.heliocentricRectangularEcliptical = new C3D(); - this.heliocentricEclipticLongitude = 0; - this.heliocentricEclipticLatitude = 0; - this.trueGeocentricRA = 0; - this.trueGeocentricDeclination = 0; - this.trueGeocentricDistance = 0; - this.trueGeocentricLightTime = 0; - this.astrometricGeocenticRA = 0; - this.astrometricGeocentricDeclination = 0; - this.astrometricGeocentricDistance = 0; - this.astrometricGeocentricLightTime = 0; - this.elongation = 0; - this.phaseAngle = 0; - this.heliocentricEclipticLongitude = 0; - this.heliocentricEclipticLatitude = 0; - this.trueGeocentricRA = 0; - this.trueGeocentricDeclination = 0; - this.trueGeocentricDistance = 0; - this.trueGeocentricLightTime = 0; - this.astrometricGeocenticRA = 0; - this.astrometricGeocentricDeclination = 0; - this.astrometricGeocentricDistance = 0; - this.astrometricGeocentricLightTime = 0; - this.elongation = 0; - this.phaseAngle = 0; - } - var EOD$ = { - - }; - - - // ELL - - function ELL() { - } - ELL.distanceToLightTime = function (Distance) { - return Distance * 0.0057755183; - }; - ELL.calculate = function (JD, oobject) { - var details = new EPD(); - var JD0 = JD; - var L0 = 0; - var B0 = 0; - var R0 = 0; - var cosB0 = 0; - if (!!oobject) { - L0 = CAAEarth.eclipticLongitude(JD0); - B0 = CAAEarth.eclipticLatitude(JD0); - R0 = CAAEarth.radiusVector(JD0); - L0 = CT.d2R(L0); - B0 = CT.d2R(B0); - cosB0 = Math.cos(B0); - } - var L = 0; - var B = 0; - var R = 0; - var Lrad; - var Brad; - var cosB; - var cosL; - var x; - var y; - var z; - var bRecalc = true; - var bFirstRecalc = true; - var LPrevious = 0; - var BPrevious = 0; - var RPrevious = 0; - while (bRecalc) { - switch (oobject) { - case 0: - L = CAASun.geometricEclipticLongitude(JD0); - B = CAASun.geometricEclipticLatitude(JD0); - R = CAAEarth.radiusVector(JD0); - break; - case 1: - L = CAAMercury.eclipticLongitude(JD0); - B = CAAMercury.eclipticLatitude(JD0); - R = CAAMercury.radiusVector(JD0); - break; - case 2: - L = CAAVenus.eclipticLongitude(JD0); - B = CAAVenus.eclipticLatitude(JD0); - R = CAAVenus.radiusVector(JD0); - break; - case 3: - L = CAAMars.eclipticLongitude(JD0); - B = CAAMars.eclipticLatitude(JD0); - R = CAAMars.radiusVector(JD0); - break; - case 4: - L = CAAJupiter.eclipticLongitude(JD0); - B = CAAJupiter.eclipticLatitude(JD0); - R = CAAJupiter.radiusVector(JD0); - break; - case 5: - L = CAASaturn.eclipticLongitude(JD0); - B = CAASaturn.eclipticLatitude(JD0); - R = CAASaturn.radiusVector(JD0); - break; - case 6: - L = CAAUranus.eclipticLongitude(JD0); - B = CAAUranus.eclipticLatitude(JD0); - R = CAAUranus.radiusVector(JD0); - break; - case 7: - L = CAANeptune.eclipticLongitude(JD0); - B = CAANeptune.eclipticLatitude(JD0); - R = CAANeptune.radiusVector(JD0); - break; - case 8: - L = CAAPluto.eclipticLongitude(JD0); - B = CAAPluto.eclipticLatitude(JD0); - R = CAAPluto.radiusVector(JD0); - break; - default: - console.assert(false); - break; - } - if (!bFirstRecalc) { - bRecalc = ((Math.abs(L - LPrevious) > 1E-05) || (Math.abs(B - BPrevious) > 1E-05) || (Math.abs(R - RPrevious) > 1E-06)); - LPrevious = L; - BPrevious = B; - RPrevious = R; - } - else { - bFirstRecalc = false; - } - if (bRecalc) { - var distance = 0; - if (!!oobject) { - Lrad = CT.d2R(L); - Brad = CT.d2R(B); - cosB = Math.cos(Brad); - cosL = Math.cos(Lrad); - x = R * cosB * cosL - R0 * cosB0 * Math.cos(L0); - y = R * cosB * Math.sin(Lrad) - R0 * cosB0 * Math.sin(L0); - z = R * Math.sin(Brad) - R0 * Math.sin(B0); - distance = Math.sqrt(x * x + y * y + z * z); - } - else { - distance = R; - } - JD0 = JD - ELL.distanceToLightTime(distance); - } - } - Lrad = CT.d2R(L); - Brad = CT.d2R(B); - cosB = Math.cos(Brad); - cosL = Math.cos(Lrad); - x = R * cosB * cosL - R0 * cosB0 * Math.cos(L0); - y = R * cosB * Math.sin(Lrad) - R0 * cosB0 * Math.sin(L0); - z = R * Math.sin(Brad) - R0 * Math.sin(B0); - var x2 = x * x; - var y2 = y * y; - details.apparentGeocentricLatitude = CT.r2D(Math.atan2(z, Math.sqrt(x2 + y2))); - details.apparentGeocentricDistance = Math.sqrt(x2 + y2 + z * z); - details.apparentGeocentricLongitude = CT.m360(CT.r2D(Math.atan2(y, x))); - details.apparentLightTime = ELL.distanceToLightTime(details.apparentGeocentricDistance); - var Aberration = ABR.eclipticAberration(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, JD); - details.apparentGeocentricLongitude += Aberration.x; - details.apparentGeocentricLatitude += Aberration.y; - var DeltaLong = CAAFK5.correctionInLongitude(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, JD); - details.apparentGeocentricLatitude += CAAFK5.correctionInLatitude(details.apparentGeocentricLongitude, JD); - details.apparentGeocentricLongitude += DeltaLong; - var NutationInLongitude = CAANutation.nutationInLongitude(JD); - var Epsilon = CAANutation.trueObliquityOfEcliptic(JD); - details.apparentGeocentricLongitude += CT.dmS2D(0, 0, NutationInLongitude); - var ApparentEqu = CT.ec2Eq(details.apparentGeocentricLongitude, details.apparentGeocentricLatitude, Epsilon); - details.apparentGeocentricRA = ApparentEqu.x; - details.apparentGeocentricDeclination = ApparentEqu.y; - return details; - }; - ELL.semiMajorAxisFromPerihelionDistance = function (q, e) { - return q / (1 - e); - }; - ELL.meanMotionFromSemiMajorAxis = function (a) { - return 0.9856076686 / (a * Math.sqrt(a)); - }; - ELL.calculateRectangularJD = function (JD, elements) { - var JD0 = JD; - var omega = CT.d2R(elements.omega); - var w = CT.d2R(elements.w); - var i = CT.d2R(elements.i); - var sinEpsilon = 0; - var cosEpsilon = 1; - var sinOmega = Math.sin(omega); - var cosOmega = Math.cos(omega); - var cosi = Math.cos(i); - var sini = Math.sin(i); - var F = cosOmega; - var G = sinOmega * cosEpsilon; - var H = sinOmega * sinEpsilon; - var P = -sinOmega * cosi; - var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; - var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; - var a = Math.sqrt(F * F + P * P); - var b = Math.sqrt(G * G + Q * Q); - var c = Math.sqrt(H * H + R * R); - var A = Math.atan2(F, P); - var B = Math.atan2(G, Q); - var C = Math.atan2(H, R); - var M = elements.n * (JD0 - elements.t); - elements.meanAnnomolyOut = M; - var E = CAAKepler.calculate(M, elements.e); - E = CT.d2R(E); - var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); - var r = elements.a * (1 - elements.e * Math.cos(E)); - var x = r * a * Math.sin(A + w + v); - var y = r * b * Math.sin(B + w + v); - var z = r * c * Math.sin(C + w + v); - return Vector3d.create(x, z, y); - }; - ELL.calculateRectangular = function (elements, meanAnomoly) { - var omega = CT.d2R(elements.omega); - var w = CT.d2R(elements.w); - var i = CT.d2R(elements.i); - var sinEpsilon = 0; - var cosEpsilon = 1; - var sinOmega = Math.sin(omega); - var cosOmega = Math.cos(omega); - var cosi = Math.cos(i); - var sini = Math.sin(i); - var F = cosOmega; - var G = sinOmega * cosEpsilon; - var H = sinOmega * sinEpsilon; - var P = -sinOmega * cosi; - var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; - var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; - var a = Math.sqrt(F * F + P * P); - var b = Math.sqrt(G * G + Q * Q); - var c = Math.sqrt(H * H + R * R); - var A = Math.atan2(F, P); - var B = Math.atan2(G, Q); - var C = Math.atan2(H, R); - var n = elements.n; - var M = meanAnomoly; - var E = CAAKepler.calculate(M, elements.e); - E = CT.d2R(E); - var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); - var r = elements.a * (1 - elements.e * Math.cos(E)); - var x = r * a * Math.sin(A + w + v); - var y = r * b * Math.sin(B + w + v); - var z = r * c * Math.sin(C + w + v); - return Vector3d.create(x, z, y); - }; - ELL.calculateElements = function (JD, elements) { - var Epsilon = CAANutation.meanObliquityOfEcliptic(elements.jdEquinox); - var JD0 = JD; - var details = new EOD(); - Epsilon = CT.d2R(Epsilon); - var omega = CT.d2R(elements.omega); - var w = CT.d2R(elements.w); - var i = CT.d2R(elements.i); - var sinEpsilon = Math.sin(Epsilon); - var cosEpsilon = Math.cos(Epsilon); - var sinOmega = Math.sin(omega); - var cosOmega = Math.cos(omega); - var cosi = Math.cos(i); - var sini = Math.sin(i); - var F = cosOmega; - var G = sinOmega * cosEpsilon; - var H = sinOmega * sinEpsilon; - var P = -sinOmega * cosi; - var Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon; - var R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon; - var a = Math.sqrt(F * F + P * P); - var b = Math.sqrt(G * G + Q * Q); - var c = Math.sqrt(H * H + R * R); - var A = Math.atan2(F, P); - var B = Math.atan2(G, Q); - var C = Math.atan2(H, R); - var n = ELL.meanMotionFromSemiMajorAxis(elements.a); - var SunCoord = CAASun.equatorialRectangularCoordinatesAnyEquinox(JD, elements.jdEquinox); - for (var j = 0; j < 2; j++) { - var M = n * (JD0 - elements.t); - var E = CAAKepler.calculate(M, elements.e); - E = CT.d2R(E); - var v = 2 * Math.atan(Math.sqrt((1 + elements.e) / (1 - elements.e)) * Math.tan(E / 2)); - var r = elements.a * (1 - elements.e * Math.cos(E)); - var x = r * a * Math.sin(A + w + v); - var y = r * b * Math.sin(B + w + v); - var z = r * c * Math.sin(C + w + v); - if (!j) { - details.heliocentricRectangularEquatorial.x = x; - details.heliocentricRectangularEquatorial.y = y; - details.heliocentricRectangularEquatorial.z = z; - var u = omega + v; - var cosu = Math.cos(u); - var sinu = Math.sin(u); - details.heliocentricRectangularEcliptical.x = r * (cosOmega * cosu - sinOmega * sinu * cosi); - details.heliocentricRectangularEcliptical.y = r * (sinOmega * cosu + cosOmega * sinu * cosi); - details.heliocentricRectangularEcliptical.z = r * sini * sinu; - details.heliocentricEclipticLongitude = Math.atan2(y, x); - details.heliocentricEclipticLongitude = CT.m24(CT.r2D(details.heliocentricEclipticLongitude) / 15); - details.heliocentricEclipticLatitude = Math.asin(z / r); - details.heliocentricEclipticLatitude = CT.r2D(details.heliocentricEclipticLatitude); - } - var psi = SunCoord.x + x; - var nu = SunCoord.y + y; - var sigma = SunCoord.z + z; - var Alpha = Math.atan2(nu, psi); - Alpha = CT.r2D(Alpha); - var Delta = Math.atan2(sigma, Math.sqrt(psi * psi + nu * nu)); - Delta = CT.r2D(Delta); - var Distance = Math.sqrt(psi * psi + nu * nu + sigma * sigma); - if (!j) { - details.trueGeocentricRA = CT.m24(Alpha / 15); - details.trueGeocentricDeclination = Delta; - details.trueGeocentricDistance = Distance; - details.trueGeocentricLightTime = ELL.distanceToLightTime(Distance); - } - else { - details.astrometricGeocenticRA = CT.m24(Alpha / 15); - details.astrometricGeocentricDeclination = Delta; - details.astrometricGeocentricDistance = Distance; - details.astrometricGeocentricLightTime = ELL.distanceToLightTime(Distance); - var RES = Math.sqrt(SunCoord.x * SunCoord.x + SunCoord.y * SunCoord.y + SunCoord.z * SunCoord.z); - details.elongation = Math.acos((RES * RES + Distance * Distance - r * r) / (2 * RES * Distance)); - details.elongation = CT.r2D(details.elongation); - details.phaseAngle = Math.acos((r * r + Distance * Distance - RES * RES) / (2 * r * Distance)); - details.phaseAngle = CT.r2D(details.phaseAngle); - } - if (!j) { - JD0 = JD - details.trueGeocentricLightTime; - } - } - return details; - }; - ELL.instantaneousVelocity = function (r, a) { - return 42.1219 * Math.sqrt((1 / r) - (1 / (2 * a))); - }; - ELL.velocityAtPerihelion = function (e, a) { - return 29.7847 / Math.sqrt(a) * Math.sqrt((1 + e) / (1 - e)); - }; - ELL.velocityAtAphelion = function (e, a) { - return 29.7847 / Math.sqrt(a) * Math.sqrt((1 - e) / (1 + e)); - }; - ELL.lengthOfEllipse = function (e, a) { - var b = a * Math.sqrt(1 - e * e); - return CT.PI() * (3 * (a + b) - Math.sqrt((a + 3 * b) * (3 * a + b))); - }; - ELL.cometMagnitude = function (g, delta, k, r) { - return g + 5 * Util.log10(delta) + k * Util.log10(r); - }; - ELL.minorPlanetMagnitude = function (H, delta, G, r, PhaseAngle) { - PhaseAngle = CT.d2R(PhaseAngle); - var phi1 = Math.exp(-3.33 * Math.pow(Math.tan(PhaseAngle / 2), 0.63)); - var phi2 = Math.exp(-1.87 * Math.pow(Math.tan(PhaseAngle / 2), 1.22)); - return H + 5 * Util.log10(r * delta) - 2.5 * Util.log10((1 - G) * phi1 + G * phi2); - }; - var ELL$ = { - - }; - - - // EOT - - function EOT() { - } - EOT.calculate = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var L0 = CT.m360(280.4664567 + 360007.6982779 * rho + 0.03032028 * rhosquared + rhocubed / 49931 - rho4 / 15300 - rho5 / 2000000); - var SunLong = CAASun.apparentEclipticLongitude(JD); - var SunLat = CAASun.apparentEclipticLatitude(JD); - var epsilon = CAANutation.trueObliquityOfEcliptic(JD); - var Equatorial = CT.ec2Eq(SunLong, SunLat, epsilon); - epsilon = CT.d2R(epsilon); - var E = L0 - 0.0057183 - Equatorial.x * 15 + CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)) * Math.cos(epsilon); - if (E > 180) { - E = -(360 - E); - } - E *= 4; - return E; - }; - var EOT$ = { - - }; - - - // CAAFK5 - - function CAAFK5() { - } - CAAFK5.correctionInLongitude = function (Longitude, Latitude, JD) { - var T = (JD - 2451545) / 36525; - var Ldash = Longitude - 1.397 * T - 0.00031 * T * T; - Ldash = CT.d2R(Ldash); - Longitude = CT.d2R(Longitude); - Latitude = CT.d2R(Latitude); - var vvalue = -0.09033 + 0.03916 * (Math.cos(Ldash) + Math.sin(Ldash)) * Math.tan(Latitude); - return CT.dmS2D(0, 0, vvalue); - }; - CAAFK5.correctionInLatitude = function (Longitude, JD) { - var T = (JD - 2451545) / 36525; - var Ldash = Longitude - 1.397 * T - 0.00031 * T * T; - Ldash = CT.d2R(Ldash); - Longitude = CT.d2R(Longitude); - var vvalue = 0.03916 * (Math.cos(Ldash) - Math.sin(Ldash)); - return CT.dmS2D(0, 0, vvalue); - }; - CAAFK5.convertVSOPToFK5J2000 = function (vvalue) { - var result = new C3D(); - result.x = vvalue.x + 4.4036E-07 * vvalue.y - 1.90919E-07 * vvalue.z; - result.y = -4.79966E-07 * vvalue.x + 0.917482137087 * vvalue.y - 0.397776982902 * vvalue.z; - result.z = 0.397776982902 * vvalue.y + 0.917482137087 * vvalue.z; - return result; - }; - CAAFK5.convertVSOPToFK5B1950 = function (vvalue) { - var result = new C3D(); - result.x = 0.999925702634 * vvalue.x + 0.012189716217 * vvalue.y + 1.1134016E-05 * vvalue.z; - result.y = -0.011179418036 * vvalue.x + 0.917413998946 * vvalue.y - 0.397777041885 * vvalue.z; - result.z = -0.004859003787 * vvalue.x + 0.397747363646 * vvalue.y + 0.917482111428 * vvalue.z; - return result; - }; - CAAFK5.convertVSOPToFK5AnyEquinox = function (vvalue, JDEquinox) { - var t = (JDEquinox - 2451545) / 36525; - var tsquared = t * t; - var tcubed = tsquared * t; - var sigma = 2306.2181 * t + 0.30188 * tsquared + 0.017988 * tcubed; - sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); - var zeta = 2306.2181 * t + 1.09468 * tsquared + 0.018203 * tcubed; - zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); - var phi = 2004.3109 * t - 0.42665 * tsquared - 0.041833 * tcubed; - phi = CT.d2R(CT.dmS2D(0, 0, phi)); - var cossigma = Math.cos(sigma); - var coszeta = Math.cos(zeta); - var cosphi = Math.cos(phi); - var sinsigma = Math.sin(sigma); - var sinzeta = Math.sin(zeta); - var sinphi = Math.sin(phi); - var xx = cossigma * coszeta * cosphi - sinsigma * sinzeta; - var xy = sinsigma * coszeta + cossigma * sinzeta * cosphi; - var xz = cossigma * sinphi; - var yx = -cossigma * sinzeta - sinsigma * coszeta * cosphi; - var yy = cossigma * coszeta - sinsigma * sinzeta * cosphi; - var yz = -sinsigma * sinphi; - var zx = -coszeta * sinphi; - var zy = -sinzeta * sinphi; - var zz = cosphi; - var result = new C3D(); - result.x = xx * vvalue.x + yx * vvalue.y + zx * vvalue.z; - result.y = xy * vvalue.x + yy * vvalue.y + zy * vvalue.z; - result.z = xz * vvalue.x + yz * vvalue.y + zz * vvalue.z; - return result; - }; - var CAAFK5$ = { - - }; - - - // GMD - - function GMD() { - this.meanLongitude = 0; - this.trueLongitude = 0; - this.tropicalLongitude = 0; - this.equatorialLatitude = 0; - this.r = 0; - this.eclipticRectangularCoordinates = new C3D(); - this.trueRectangularCoordinates = new C3D(); - this.apparentRectangularCoordinates = new C3D(); - this.bInTransit = false; - this.bInOccultation = false; - this.bInEclipse = false; - this.bInShadowTransit = false; - this.apparentShadowRectangularCoordinates = new C3D(); - this.meanLongitude = 0; - this.trueLongitude = 0; - this.tropicalLongitude = 0; - this.equatorialLatitude = 0; - this.r = 0; - this.bInTransit = false; - this.bInOccultation = false; - this.bInEclipse = false; - this.bInShadowTransit = false; - } - var GMD$ = { - - }; - - - // GMDS - - function GMDS() { - this.satellite1 = new GMD(); - this.satellite2 = new GMD(); - this.satellite3 = new GMD(); - this.satellite4 = new GMD(); - } - var GMDS$ = { - - }; - - - // GM - - function GM() { - } - GM.calculate = function (JD) { - var sunlong = CAASun.geometricEclipticLongitude(JD); - var sunlongrad = CT.d2R(sunlong); - var beta = CAASun.geometricEclipticLatitude(JD); - var betarad = CT.d2R(beta); - var R = CAAEarth.radiusVector(JD); - var DELTA = 5; - var PreviousEarthLightTravelTime = 0; - var EarthLightTravelTime = ELL.distanceToLightTime(DELTA); - var JD1 = JD - EarthLightTravelTime; - var bIterate = true; - var x = 0; - var y = 0; - var z = 0; - var l = 0; - var lrad = 0; - var b = 0; - var brad = 0; - var r = 0; - while (bIterate) { - l = CAAJupiter.eclipticLongitude(JD1); - lrad = CT.d2R(l); - b = CAAJupiter.eclipticLatitude(JD1); - brad = CT.d2R(b); - r = CAAJupiter.radiusVector(JD1); - x = r * Math.cos(brad) * Math.cos(lrad) + R * Math.cos(sunlongrad); - y = r * Math.cos(brad) * Math.sin(lrad) + R * Math.sin(sunlongrad); - z = r * Math.sin(brad) + R * Math.sin(betarad); - DELTA = Math.sqrt(x * x + y * y + z * z); - EarthLightTravelTime = ELL.distanceToLightTime(DELTA); - bIterate = (Math.abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-06); - if (bIterate) { - JD1 = JD - EarthLightTravelTime; - PreviousEarthLightTravelTime = EarthLightTravelTime; - } - } - var details1 = GM.calculateHelper(JD, sunlongrad, betarad, R); - GM.fillInPhenomenaDetails(details1.satellite1); - GM.fillInPhenomenaDetails(details1.satellite2); - GM.fillInPhenomenaDetails(details1.satellite3); - GM.fillInPhenomenaDetails(details1.satellite4); - JD1 = JD - EarthLightTravelTime; - l = CAAJupiter.eclipticLongitude(JD1); - lrad = CT.d2R(l); - b = CAAJupiter.eclipticLatitude(JD1); - brad = CT.d2R(b); - r = CAAJupiter.radiusVector(JD1); - x = r * Math.cos(brad) * Math.cos(lrad); - y = r * Math.cos(brad) * Math.sin(lrad); - z = r * Math.sin(brad); - DELTA = Math.sqrt(x * x + y * y + z * z); - var SunLightTravelTime = ELL.distanceToLightTime(DELTA); - var details2 = GM.calculateHelper(JD + SunLightTravelTime - EarthLightTravelTime, sunlongrad, betarad, 0); - GM.fillInPhenomenaDetails(details2.satellite1); - GM.fillInPhenomenaDetails(details2.satellite2); - GM.fillInPhenomenaDetails(details2.satellite3); - GM.fillInPhenomenaDetails(details2.satellite4); - details1.satellite1.bInEclipse = details2.satellite1.bInOccultation; - details1.satellite2.bInEclipse = details2.satellite2.bInOccultation; - details1.satellite3.bInEclipse = details2.satellite3.bInOccultation; - details1.satellite4.bInEclipse = details2.satellite4.bInOccultation; - details1.satellite1.bInShadowTransit = details2.satellite1.bInTransit; - details1.satellite2.bInShadowTransit = details2.satellite2.bInTransit; - details1.satellite3.bInShadowTransit = details2.satellite3.bInTransit; - details1.satellite4.bInShadowTransit = details2.satellite4.bInTransit; - details1.satellite1.apparentShadowRectangularCoordinates = details2.satellite1.apparentRectangularCoordinates; - details1.satellite2.apparentShadowRectangularCoordinates = details2.satellite2.apparentRectangularCoordinates; - details1.satellite3.apparentShadowRectangularCoordinates = details2.satellite3.apparentRectangularCoordinates; - details1.satellite4.apparentShadowRectangularCoordinates = details2.satellite4.apparentRectangularCoordinates; - return details1; - }; - GM.calculateHelper = function (JD, sunlongrad, betarad, R) { - var details = new GMDS(); - var DELTA = 5; - var PreviousLightTravelTime = 0; - var LightTravelTime = ELL.distanceToLightTime(DELTA); - var x = 0; - var y = 0; - var z = 0; - var l = 0; - var lrad = 0; - var b = 0; - var brad = 0; - var r = 0; - var JD1 = JD - LightTravelTime; - var bIterate = true; - while (bIterate) { - l = CAAJupiter.eclipticLongitude(JD1); - lrad = CT.d2R(l); - b = CAAJupiter.eclipticLatitude(JD1); - brad = CT.d2R(b); - r = CAAJupiter.radiusVector(JD1); - x = r * Math.cos(brad) * Math.cos(lrad) + R * Math.cos(sunlongrad); - y = r * Math.cos(brad) * Math.sin(lrad) + R * Math.sin(sunlongrad); - z = r * Math.sin(brad) + R * Math.sin(betarad); - DELTA = Math.sqrt(x * x + y * y + z * z); - LightTravelTime = ELL.distanceToLightTime(DELTA); - bIterate = (Math.abs(LightTravelTime - PreviousLightTravelTime) > 2E-06); - if (bIterate) { - JD1 = JD - LightTravelTime; - PreviousLightTravelTime = LightTravelTime; - } - } - var lambda0 = Math.atan2(y, x); - var beta0 = Math.atan(z / Math.sqrt(x * x + y * y)); - var t = JD - 2443000.5 - LightTravelTime; - var l1 = 106.07719 + 203.48895579 * t; - var l1rad = CT.d2R(l1); - var l2 = 175.73161 + 101.374724735 * t; - var l2rad = CT.d2R(l2); - var l3 = 120.55883 + 50.317609207 * t; - var l3rad = CT.d2R(l3); - var l4 = 84.44459 + 21.571071177 * t; - var l4rad = CT.d2R(l4); - var pi1 = CT.d2R(CT.m360(97.0881 + 0.16138586 * t)); - var pi2 = CT.d2R(CT.m360(154.8663 + 0.04726307 * t)); - var pi3 = CT.d2R(CT.m360(188.184 + 0.00712734 * t)); - var pi4 = CT.d2R(CT.m360(335.2868 + 0.00184 * t)); - var w1 = 312.3346 - 0.13279386 * t; - var w1rad = CT.d2R(w1); - var w2 = 100.4411 - 0.03263064 * t; - var w2rad = CT.d2R(w2); - var w3 = 119.1942 - 0.00717703 * t; - var w3rad = CT.d2R(w3); - var w4 = 322.6186 - 0.00175934 * t; - var w4rad = CT.d2R(w4); - var GAMMA = 0.33033 * Math.sin(CT.d2R(163.679 + 0.0010512 * t)) + 0.03439 * Math.sin(CT.d2R(34.486 - 0.0161731 * t)); - var philambda = CT.d2R(199.6766 + 0.1737919 * t); - var psi = CT.d2R(316.5182 - 2.08E-06 * t); - var G = CT.d2R(30.23756 + 0.0830925701 * t + GAMMA); - var Gdash = CT.d2R(31.97853 + 0.0334597339 * t); - var PI = CT.d2R(13.469942); - var Sigma1 = 0.47259 * Math.sin(2 * (l1rad - l2rad)) + -0.03478 * Math.sin(pi3 - pi4) + 0.01081 * Math.sin(l2rad - 2 * l3rad + pi3) + 0.00738 * Math.sin(philambda) + 0.00713 * Math.sin(l2rad - 2 * l3rad + pi2) + -0.00674 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00666 * Math.sin(l2rad - 2 * l3rad + pi4) + 0.00445 * Math.sin(l1rad - pi3) + -0.00354 * Math.sin(l1rad - l2rad) + -0.00317 * Math.sin(2 * psi - 2 * PI) + 0.00265 * Math.sin(l1rad - pi4) + -0.00186 * Math.sin(G) + 0.00162 * Math.sin(pi2 - pi3) + 0.00158 * Math.sin(4 * (l1rad - l2rad)) + -0.00155 * Math.sin(l1rad - l3rad) + -0.00138 * Math.sin(psi + w3rad - 2 * PI - 2 * G) + -0.00115 * Math.sin(2 * (l1rad - 2 * l2rad + w2rad)) + 0.00089 * Math.sin(pi2 - pi4) + 0.00085 * Math.sin(l1rad + pi3 - 2 * PI - 2 * G) + 0.00083 * Math.sin(w2rad - w3rad) + 0.00053 * Math.sin(psi - w2rad); - var Sigma2 = 1.06476 * Math.sin(2 * (l2rad - l3rad)) + 0.04256 * Math.sin(l1rad - 2 * l2rad + pi3) + 0.03581 * Math.sin(l2rad - pi3) + 0.02395 * Math.sin(l1rad - 2 * l2rad + pi4) + 0.01984 * Math.sin(l2rad - pi4) + -0.01778 * Math.sin(philambda) + 0.01654 * Math.sin(l2rad - pi2) + 0.01334 * Math.sin(l2rad - 2 * l3rad + pi2) + 0.01294 * Math.sin(pi3 - pi4) + -0.01142 * Math.sin(l2rad - l3rad) + -0.01057 * Math.sin(G) + -0.00775 * Math.sin(2 * (psi - PI)) + 0.00524 * Math.sin(2 * (l1rad - l2rad)) + -0.0046 * Math.sin(l1rad - l3rad) + 0.00316 * Math.sin(psi - 2 * G + w3rad - 2 * PI) + -0.00203 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00146 * Math.sin(psi - w3rad) + -0.00145 * Math.sin(2 * G) + 0.00125 * Math.sin(psi - w4rad) + -0.00115 * Math.sin(l1rad - 2 * l3rad + pi3) + -0.00094 * Math.sin(2 * (l2rad - w2rad)) + 0.00086 * Math.sin(2 * (l1rad - 2 * l2rad + w2rad)) + -0.00086 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + -0.00078 * Math.sin(l2rad - l4rad) + -0.00064 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00064 * Math.sin(pi1 - pi4) + -0.00063 * Math.sin(l1rad - 2 * l3rad + pi4) + 0.00058 * Math.sin(w3rad - w4rad) + 0.00056 * Math.sin(2 * (psi - PI - G)) + 0.00056 * Math.sin(2 * (l2rad - l4rad)) + 0.00055 * Math.sin(2 * (l1rad - l3rad)) + 0.00052 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + -0.00043 * Math.sin(l1rad - pi3) + 0.00041 * Math.sin(5 * (l2rad - l3rad)) + 0.00041 * Math.sin(pi4 - PI) + 0.00032 * Math.sin(w2rad - w3rad) + 0.00032 * Math.sin(2 * (l3rad - G - PI)); - var Sigma3 = 0.1649 * Math.sin(l3rad - pi3) + 0.09081 * Math.sin(l3rad - pi4) + -0.06907 * Math.sin(l2rad - l3rad) + 0.03784 * Math.sin(pi3 - pi4) + 0.01846 * Math.sin(2 * (l3rad - l4rad)) + -0.0134 * Math.sin(G) + -0.01014 * Math.sin(2 * (psi - PI)) + 0.00704 * Math.sin(l2rad - 2 * l3rad + pi3) + -0.0062 * Math.sin(l2rad - 2 * l3rad + pi2) + -0.00541 * Math.sin(l3rad - l4rad) + 0.00381 * Math.sin(l2rad - 2 * l3rad + pi4) + 0.00235 * Math.sin(psi - w3rad) + 0.00198 * Math.sin(psi - w4rad) + 0.00176 * Math.sin(philambda) + 0.0013 * Math.sin(3 * (l3rad - l4rad)) + 0.00125 * Math.sin(l1rad - l3rad) + -0.00119 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + 0.00109 * Math.sin(l1rad - l2rad) + -0.001 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00091 * Math.sin(w3rad - w4rad) + 0.0008 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + -0.00075 * Math.sin(2 * l2rad - 3 * l3rad + pi3) + 0.00072 * Math.sin(pi1 + pi3 - 2 * PI - 2 * G) + 0.00069 * Math.sin(pi4 - PI) + -0.00058 * Math.sin(2 * l3rad - 3 * l4rad + pi4) + -0.00057 * Math.sin(l3rad - 2 * l4rad + pi4) + 0.00056 * Math.sin(l3rad + pi3 - 2 * PI - 2 * G) + -0.00052 * Math.sin(l2rad - 2 * l3rad + pi1) + -0.0005 * Math.sin(pi2 - pi3) + 0.00048 * Math.sin(l3rad - 2 * l4rad + pi3) + -0.00045 * Math.sin(2 * l2rad - 3 * l3rad + pi4) + -0.00041 * Math.sin(pi2 - pi4) + -0.00038 * Math.sin(2 * G) + -0.00037 * Math.sin(pi3 - pi4 + w3rad - w4rad) + -0.00032 * Math.sin(3 * l3rad - 7 * l4rad + 2 * pi3 + 2 * pi4) + 0.0003 * Math.sin(4 * (l3rad - l4rad)) + 0.00029 * Math.sin(l3rad + pi4 - 2 * PI - 2 * G) + -0.00028 * Math.sin(w3rad + psi - 2 * PI - 2 * G) + 0.00026 * Math.sin(l3rad - PI - G) + 0.00024 * Math.sin(l2rad - 3 * l3rad + 2 * l4rad) + 0.00021 * Math.sin(l3rad - PI - G) + -0.00021 * Math.sin(l3rad - pi2) + 0.00017 * Math.sin(2 * (l3rad - pi3)); - var Sigma4 = 0.84287 * Math.sin(l4rad - pi4) + 0.03431 * Math.sin(pi4 - pi3) + -0.03305 * Math.sin(2 * (psi - PI)) + -0.03211 * Math.sin(G) + -0.01862 * Math.sin(l4rad - pi3) + 0.01186 * Math.sin(psi - w4rad) + 0.00623 * Math.sin(l4rad + pi4 - 2 * G - 2 * PI) + 0.00387 * Math.sin(2 * (l4rad - pi4)) + -0.00284 * Math.sin(5 * Gdash - 2 * G + CT.d2R(52.225)) + -0.00234 * Math.sin(2 * (psi - pi4)) + -0.00223 * Math.sin(l3rad - l4rad) + -0.00208 * Math.sin(l4rad - PI) + 0.00178 * Math.sin(psi + w4rad - 2 * pi4) + 0.00134 * Math.sin(pi4 - PI) + 0.00125 * Math.sin(2 * (l4rad - G - PI)) + -0.00117 * Math.sin(2 * G) + -0.00112 * Math.sin(2 * (l3rad - l4rad)) + 0.00107 * Math.sin(3 * l3rad - 7 * l4rad + 4 * pi4) + 0.00102 * Math.sin(l4rad - G - PI) + 0.00096 * Math.sin(2 * l4rad - psi - w4rad) + 0.00087 * Math.sin(2 * (psi - w4rad)) + -0.00085 * Math.sin(3 * l3rad - 7 * l4rad + pi3 + 3 * pi4) + 0.00085 * Math.sin(l3rad - 2 * l4rad + pi4) + -0.00081 * Math.sin(2 * (l4rad - psi)) + 0.00071 * Math.sin(l4rad + pi4 - 2 * PI - 3 * G) + 0.00061 * Math.sin(l1rad - l4rad) + -0.00056 * Math.sin(psi - w3rad) + -0.00054 * Math.sin(l3rad - 2 * l4rad + pi3) + 0.00051 * Math.sin(l2rad - l4rad) + 0.00042 * Math.sin(2 * (psi - G - PI)) + 0.00039 * Math.sin(2 * (pi4 - w4rad)) + 0.00036 * Math.sin(psi + PI - pi4 - w4rad) + 0.00035 * Math.sin(2 * Gdash - G + CT.d2R(188.37)) + -0.00035 * Math.sin(l4rad - pi4 + 2 * PI - 2 * psi) + -0.00032 * Math.sin(l4rad + pi4 - 2 * PI - G) + 0.0003 * Math.sin(2 * Gdash - 2 * G + CT.d2R(149.15)) + 0.00029 * Math.sin(3 * l3rad - 7 * l4rad + 2 * pi3 + 2 * pi4) + 0.00028 * Math.sin(l4rad - pi4 + 2 * psi - 2 * PI) + -0.00028 * Math.sin(2 * (l4rad - w4rad)) + -0.00027 * Math.sin(pi3 - pi4 + w3rad - w4rad) + -0.00026 * Math.sin(5 * Gdash - 3 * G + CT.d2R(188.37)) + 0.00025 * Math.sin(w4rad - w3rad) + -0.00025 * Math.sin(l2rad - 3 * l3rad + 2 * l4rad) + -0.00023 * Math.sin(3 * (l3rad - l4rad)) + 0.00021 * Math.sin(2 * l4rad - 2 * PI - 3 * G) + -0.00021 * Math.sin(2 * l3rad - 3 * l4rad + pi4) + 0.00019 * Math.sin(l4rad - pi4 - G) + -0.00019 * Math.sin(2 * l4rad - pi3 - pi4) + -0.00018 * Math.sin(l4rad - pi4 + G) + -0.00016 * Math.sin(l4rad + pi3 - 2 * PI - 2 * G); - details.satellite1.meanLongitude = CT.m360(l1); - details.satellite1.trueLongitude = CT.m360(l1 + Sigma1); - var L1 = CT.d2R(details.satellite1.trueLongitude); - details.satellite2.meanLongitude = CT.m360(l2); - details.satellite2.trueLongitude = CT.m360(l2 + Sigma2); - var L2 = CT.d2R(details.satellite2.trueLongitude); - details.satellite3.meanLongitude = CT.m360(l3); - details.satellite3.trueLongitude = CT.m360(l3 + Sigma3); - var L3 = CT.d2R(details.satellite3.trueLongitude); - details.satellite4.meanLongitude = CT.m360(l4); - details.satellite4.trueLongitude = CT.m360(l4 + Sigma4); - var L4 = CT.d2R(details.satellite4.trueLongitude); - var B1 = Math.atan(0.0006393 * Math.sin(L1 - w1rad) + 0.0001825 * Math.sin(L1 - w2rad) + 3.29E-05 * Math.sin(L1 - w3rad) + -3.11E-05 * Math.sin(L1 - psi) + 9.3E-06 * Math.sin(L1 - w4rad) + 7.5E-06 * Math.sin(3 * L1 - 4 * l2rad - 1.9927 * Sigma1 + w2rad) + 4.6E-06 * Math.sin(L1 + psi - 2 * PI - 2 * G)); - details.satellite1.equatorialLatitude = CT.r2D(B1); - var B2 = Math.atan(0.0081004 * Math.sin(L2 - w2rad) + 0.0004512 * Math.sin(L2 - w3rad) + -0.0003284 * Math.sin(L2 - psi) + 0.000116 * Math.sin(L2 - w4rad) + 2.72E-05 * Math.sin(l1rad - 2 * l3rad + 1.0146 * Sigma2 + w2rad) + -1.44E-05 * Math.sin(L2 - w1rad) + 1.43E-05 * Math.sin(L2 + psi - 2 * PI - 2 * G) + 3.5E-06 * Math.sin(L2 - psi + G) + -2.8E-06 * Math.sin(l1rad - 2 * l3rad + 1.0146 * Sigma2 + w3rad)); - details.satellite2.equatorialLatitude = CT.r2D(B2); - var B3 = Math.atan(0.0032402 * Math.sin(L3 - w3rad) + -0.0016911 * Math.sin(L3 - psi) + 0.0006847 * Math.sin(L3 - w4rad) + -0.0002797 * Math.sin(L3 - w2rad) + 3.21E-05 * Math.sin(L3 + psi - 2 * PI - 2 * G) + 5.1E-06 * Math.sin(L3 - psi + G) + -4.5E-06 * Math.sin(L3 - psi - G) + -4.5E-06 * Math.sin(L3 + psi - 2 * PI) + 3.7E-06 * Math.sin(L3 + psi - 2 * PI - 3 * G) + 3E-06 * Math.sin(2 * l2rad - 3 * L3 + 4.03 * Sigma3 + w2rad) + -2.1E-06 * Math.sin(2 * l2rad - 3 * L3 + 4.03 * Sigma3 + w3rad)); - details.satellite3.equatorialLatitude = CT.r2D(B3); - var B4 = Math.atan(-0.0076579 * Math.sin(L4 - psi) + 0.0044134 * Math.sin(L4 - w4rad) + -0.0005112 * Math.sin(L4 - w3rad) + 7.73E-05 * Math.sin(L4 + psi - 2 * PI - 2 * G) + 1.04E-05 * Math.sin(L4 - psi + G) + -1.02E-05 * Math.sin(L4 - psi - G) + 8.8E-06 * Math.sin(L4 + psi - 2 * PI - 3 * G) + -3.8E-06 * Math.sin(L4 + psi - 2 * PI - G)); - details.satellite4.equatorialLatitude = CT.r2D(B4); - details.satellite1.r = 5.90569 * (1 + (-0.0041339 * Math.cos(2 * (l1rad - l2rad)) + -3.87E-05 * Math.cos(l1rad - pi3) + -2.14E-05 * Math.cos(l1rad - pi4) + 1.7E-05 * Math.cos(l1rad - l2rad) + -1.31E-05 * Math.cos(4 * (l1rad - l2rad)) + 1.06E-05 * Math.cos(l1rad - l3rad) + -6.6E-06 * Math.cos(l1rad + pi3 - 2 * PI - 2 * G))); - details.satellite2.r = 9.39657 * (1 + (0.0093848 * Math.cos(l1rad - l2rad) + -0.0003116 * Math.cos(l2rad - pi3) + -0.0001744 * Math.cos(l2rad - pi4) + -0.0001442 * Math.cos(l2rad - pi2) + 5.53E-05 * Math.cos(l2rad - l3rad) + 5.23E-05 * Math.cos(l1rad - l3rad) + -2.9E-05 * Math.cos(2 * (l1rad - l2rad)) + 1.64E-05 * Math.cos(2 * (l2rad - w2rad)) + 1.07E-05 * Math.cos(l1rad - 2 * l3rad + pi3) + -1.02E-05 * Math.cos(l2rad - pi1) + -9.1E-06 * Math.cos(2 * (l1rad - l3rad)))); - details.satellite3.r = 14.98832 * (1 + (-0.0014388 * Math.cos(l3rad - pi3) + -0.0007919 * Math.cos(l3rad - pi4) + 0.0006342 * Math.cos(l2rad - l3rad) + -0.0001761 * Math.cos(2 * (l3rad - l4rad)) + 2.94E-05 * Math.cos(l3rad - l4rad) + -1.56E-05 * Math.cos(3 * (l3rad - l4rad)) + 1.56E-05 * Math.cos(l1rad - l3rad) + -1.53E-05 * Math.cos(l1rad - l2rad) + 7E-06 * Math.cos(2 * l2rad - 3 * l3rad + pi3) + -5.1E-06 * Math.cos(l3rad + pi3 - 2 * PI - 2 * G))); - details.satellite4.r = 26.36273 * (1 + (-0.0073546 * Math.cos(l4rad - pi4) + 0.0001621 * Math.cos(l4rad - pi3) + 9.74E-05 * Math.cos(l3rad - l4rad) + -5.43E-05 * Math.cos(l4rad + pi4 - 2 * PI - 2 * G) + -2.71E-05 * Math.cos(2 * (l4rad - pi4)) + 1.82E-05 * Math.cos(l4rad - PI) + 1.77E-05 * Math.cos(2 * (l3rad - l4rad)) + -1.67E-05 * Math.cos(2 * l4rad - psi - w4rad) + 1.67E-05 * Math.cos(psi - w4rad) + -1.55E-05 * Math.cos(2 * (l4rad - PI - G)) + 1.42E-05 * Math.cos(2 * (l4rad - psi)) + 1.05E-05 * Math.cos(l1rad - l4rad) + 9.2E-06 * Math.cos(l2rad - l4rad) + -8.9E-06 * Math.cos(l4rad - PI - G) + -6.2E-06 * Math.cos(l4rad + pi4 - 2 * PI - 3 * G) + 4.8E-06 * Math.cos(2 * (l4rad - w4rad)))); - var T0 = (JD - 2433282.423) / 36525; - var P = CT.d2R(1.3966626 * T0 + 0.0003088 * T0 * T0); - L1 += P; - details.satellite1.tropicalLongitude = CT.m360(CT.r2D(L1)); - L2 += P; - details.satellite2.tropicalLongitude = CT.m360(CT.r2D(L2)); - L3 += P; - details.satellite3.tropicalLongitude = CT.m360(CT.r2D(L3)); - L4 += P; - details.satellite4.tropicalLongitude = CT.m360(CT.r2D(L4)); - psi += P; - var T = (JD - 2415020.5) / 36525; - var I = 3.120262 + 0.0006 * T; - var Irad = CT.d2R(I); - var X1 = details.satellite1.r * Math.cos(L1 - psi) * Math.cos(B1); - var X2 = details.satellite2.r * Math.cos(L2 - psi) * Math.cos(B2); - var X3 = details.satellite3.r * Math.cos(L3 - psi) * Math.cos(B3); - var X4 = details.satellite4.r * Math.cos(L4 - psi) * Math.cos(B4); - var X5 = 0; - var Y1 = details.satellite1.r * Math.sin(L1 - psi) * Math.cos(B1); - var Y2 = details.satellite2.r * Math.sin(L2 - psi) * Math.cos(B2); - var Y3 = details.satellite3.r * Math.sin(L3 - psi) * Math.cos(B3); - var Y4 = details.satellite4.r * Math.sin(L4 - psi) * Math.cos(B4); - var Y5 = 0; - var Z1 = details.satellite1.r * Math.sin(B1); - var Z2 = details.satellite2.r * Math.sin(B2); - var Z3 = details.satellite3.r * Math.sin(B3); - var Z4 = details.satellite4.r * Math.sin(B4); - var Z5 = 1; - var omega = CT.d2R(EPO.jupiterLongitudeAscendingNode(JD)); - var i = CT.d2R(EPO.jupiterInclination(JD)); - var A6 = 0; - var B6 = 0; - var C6 = 0; - var north = new C3D(); - var abc = GM.rotations(X5, Y5, Z5, Irad, psi, i, omega, lambda0, beta0, north); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - var D = Math.atan2(A6, C6); - abc = GM.rotations(X1, Y1, Z1, Irad, psi, i, omega, lambda0, beta0, details.satellite1.eclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - details.satellite1.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); - details.satellite1.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); - details.satellite1.trueRectangularCoordinates.z = B6; - abc = GM.rotations(X2, Y2, Z2, Irad, psi, i, omega, lambda0, beta0, details.satellite2.eclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - details.satellite2.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); - details.satellite2.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); - details.satellite2.trueRectangularCoordinates.z = B6; - abc = GM.rotations(X3, Y3, Z3, Irad, psi, i, omega, lambda0, beta0, details.satellite3.eclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - details.satellite3.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); - details.satellite3.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); - details.satellite3.trueRectangularCoordinates.z = B6; - abc = GM.rotations(X4, Y4, Z4, Irad, psi, i, omega, lambda0, beta0, details.satellite4.eclipticRectangularCoordinates); - A6 = abc[0]; - B6 = abc[1]; - C6 = abc[2]; - details.satellite4.trueRectangularCoordinates.x = A6 * Math.cos(D) - C6 * Math.sin(D); - details.satellite4.trueRectangularCoordinates.y = A6 * Math.sin(D) + C6 * Math.cos(D); - details.satellite4.trueRectangularCoordinates.z = B6; - details.satellite1.apparentRectangularCoordinates.x = details.satellite1.trueRectangularCoordinates.x + Math.abs(details.satellite1.trueRectangularCoordinates.z) / 17295 * Math.sqrt(1 - (details.satellite1.trueRectangularCoordinates.x / details.satellite1.r) * (details.satellite1.trueRectangularCoordinates.x / details.satellite1.r)); - details.satellite1.apparentRectangularCoordinates.y = details.satellite1.trueRectangularCoordinates.y; - details.satellite1.apparentRectangularCoordinates.z = details.satellite1.trueRectangularCoordinates.z; - details.satellite2.apparentRectangularCoordinates.x = details.satellite2.trueRectangularCoordinates.x + Math.abs(details.satellite2.trueRectangularCoordinates.z) / 21819 * Math.sqrt(1 - (details.satellite2.trueRectangularCoordinates.x / details.satellite2.r) * (details.satellite2.trueRectangularCoordinates.x / details.satellite2.r)); - details.satellite2.apparentRectangularCoordinates.y = details.satellite2.trueRectangularCoordinates.y; - details.satellite2.apparentRectangularCoordinates.z = details.satellite2.trueRectangularCoordinates.z; - details.satellite3.apparentRectangularCoordinates.x = details.satellite3.trueRectangularCoordinates.x + Math.abs(details.satellite3.trueRectangularCoordinates.z) / 27558 * Math.sqrt(1 - (details.satellite3.trueRectangularCoordinates.x / details.satellite3.r) * (details.satellite3.trueRectangularCoordinates.x / details.satellite3.r)); - details.satellite3.apparentRectangularCoordinates.y = details.satellite3.trueRectangularCoordinates.y; - details.satellite3.apparentRectangularCoordinates.z = details.satellite3.trueRectangularCoordinates.z; - details.satellite4.apparentRectangularCoordinates.x = details.satellite4.trueRectangularCoordinates.x + Math.abs(details.satellite4.trueRectangularCoordinates.z) / 36548 * Math.sqrt(1 - (details.satellite4.trueRectangularCoordinates.x / details.satellite4.r) * (details.satellite4.trueRectangularCoordinates.x / details.satellite4.r)); - details.satellite4.apparentRectangularCoordinates.y = details.satellite4.trueRectangularCoordinates.y; - details.satellite4.apparentRectangularCoordinates.z = details.satellite4.trueRectangularCoordinates.z; - var W = DELTA / (DELTA + details.satellite1.trueRectangularCoordinates.z / 2095); - details.satellite1.apparentRectangularCoordinates.x *= W; - details.satellite1.apparentRectangularCoordinates.y *= W; - W = DELTA / (DELTA + details.satellite2.trueRectangularCoordinates.z / 2095); - details.satellite2.apparentRectangularCoordinates.x *= W; - details.satellite2.apparentRectangularCoordinates.y *= W; - W = DELTA / (DELTA + details.satellite3.trueRectangularCoordinates.z / 2095); - details.satellite3.apparentRectangularCoordinates.x *= W; - details.satellite3.apparentRectangularCoordinates.y *= W; - W = DELTA / (DELTA + details.satellite4.trueRectangularCoordinates.z / 2095); - details.satellite4.apparentRectangularCoordinates.x *= W; - details.satellite4.apparentRectangularCoordinates.y *= W; - return details; - }; - GM.rotations = function (X, Y, Z, I, psi, i, omega, lambda0, beta0, eclipticCoord) { - var A6; - var B6; - var C6; - var phi = psi - omega; - var A1 = X; - var B1 = Y * Math.cos(I) - Z * Math.sin(I); - var C1 = Y * Math.sin(I) + Z * Math.cos(I); - var A2 = A1 * Math.cos(phi) - B1 * Math.sin(phi); - var B2 = A1 * Math.sin(phi) + B1 * Math.cos(phi); - var C2 = C1; - var A3 = A2; - var B3 = B2 * Math.cos(i) - C2 * Math.sin(i); - var C3 = B2 * Math.sin(i) + C2 * Math.cos(i); - var A4 = A3 * Math.cos(omega) - B3 * Math.sin(omega); - var B4 = A3 * Math.sin(omega) + B3 * Math.cos(omega); - var C4 = C3; - var JupiterRadiiToAU = 1 / 2095; - eclipticCoord.x = A4 * JupiterRadiiToAU; - eclipticCoord.y = B4 * JupiterRadiiToAU; - eclipticCoord.z = C4 * JupiterRadiiToAU; - var A5 = A4 * Math.sin(lambda0) - B4 * Math.cos(lambda0); - var B5 = A4 * Math.cos(lambda0) + B4 * Math.sin(lambda0); - var C5 = C4; - A6 = A5; - B6 = C5 * Math.sin(beta0) + B5 * Math.cos(beta0); - C6 = C5 * Math.cos(beta0) - B5 * Math.sin(beta0); - return [A6, B6, C6]; - }; - GM.fillInPhenomenaDetails = function (detail) { - var Y1 = 1.071374 * detail.apparentRectangularCoordinates.y; - var r = Y1 * Y1 + detail.apparentRectangularCoordinates.x * detail.apparentRectangularCoordinates.x; - if (r < 1) { - if (detail.apparentRectangularCoordinates.z < 0) { - detail.bInTransit = true; - detail.bInOccultation = false; - } - else { - detail.bInTransit = false; - detail.bInOccultation = true; - } - } - else { - detail.bInTransit = false; - detail.bInOccultation = false; - } - }; - var GM$ = { - - }; - - - // CAAGlobe - - function CAAGlobe() { - } - CAAGlobe.rhoSinThetaPrime = function (GeographicalLatitude, Height) { - GeographicalLatitude = CT.d2R(GeographicalLatitude); - var U = Math.atan(0.99664719 * Math.tan(GeographicalLatitude)); - return 0.99664719 * Math.sin(U) + (Height / 6378149 * Math.sin(GeographicalLatitude)); - }; - CAAGlobe.rhoCosThetaPrime = function (GeographicalLatitude, Height) { - GeographicalLatitude = CT.d2R(GeographicalLatitude); - var U = Math.atan(0.99664719 * Math.tan(GeographicalLatitude)); - return Math.cos(U) + (Height / 6378149 * Math.cos(GeographicalLatitude)); - }; - CAAGlobe.radiusOfParallelOfLatitude = function (GeographicalLatitude) { - GeographicalLatitude = CT.d2R(GeographicalLatitude); - var sinGeo = Math.sin(GeographicalLatitude); - return (6378.14 * Math.cos(GeographicalLatitude)) / Math.sqrt(1 - 0.0066943847614084 * sinGeo * sinGeo); - }; - CAAGlobe.radiusOfCurvature = function (GeographicalLatitude) { - GeographicalLatitude = CT.d2R(GeographicalLatitude); - var sinGeo = Math.sin(GeographicalLatitude); - return (6378.14 * (1 - 0.0066943847614084)) / Math.pow((1 - 0.0066943847614084 * sinGeo * sinGeo), 1.5); - }; - CAAGlobe.distanceBetweenPoints = function (GeographicalLatitude1, GeographicalLongitude1, GeographicalLatitude2, GeographicalLongitude2) { - GeographicalLatitude1 = CT.d2R(GeographicalLatitude1); - GeographicalLatitude2 = CT.d2R(GeographicalLatitude2); - GeographicalLongitude1 = CT.d2R(GeographicalLongitude1); - GeographicalLongitude2 = CT.d2R(GeographicalLongitude2); - var F = (GeographicalLatitude1 + GeographicalLatitude2) / 2; - var G = (GeographicalLatitude1 - GeographicalLatitude2) / 2; - var lambda = (GeographicalLongitude1 - GeographicalLongitude2) / 2; - var sinG = Math.sin(G); - var cosG = Math.cos(G); - var cosF = Math.cos(F); - var sinF = Math.sin(F); - var sinLambda = Math.sin(lambda); - var cosLambda = Math.cos(lambda); - var S = (sinG * sinG * cosLambda * cosLambda) + (cosF * cosF * sinLambda * sinLambda); - var C = (cosG * cosG * cosLambda * cosLambda) + (sinF * sinF * sinLambda * sinLambda); - var w = Math.atan(Math.sqrt(S / C)); - var R = Math.sqrt(S * C) / w; - var D = 2 * w * 6378.14; - var Hprime = (3 * R - 1) / (2 * C); - var Hprime2 = (3 * R + 1) / (2 * S); - var f = 0.00335281317789691; - return D * (1 + (f * Hprime * sinF * sinF * cosG * cosG) - (f * Hprime2 * cosF * cosF * sinG * sinG)); - }; - var CAAGlobe$ = { - - }; - - - // IFR - - function IFR() { - } - IFR.phaseAngle = function (r, R, Delta) { - return CT.m360(CT.r2D(Math.acos((r * r + Delta * Delta - R * R) / (2 * r * Delta)))); - }; - IFR.phaseAngle2 = function (R, R0, B, L, L0, Delta) { - B = CT.d2R(B); - L = CT.d2R(L); - L0 = CT.d2R(L0); - return CT.m360(CT.r2D(Math.acos((R - R0 * Math.cos(B) * Math.cos(L - L0)) / Delta))); - }; - IFR.phaseAngleRectangular = function (x, y, z, B, L, Delta) { - B = CT.d2R(B); - L = CT.d2R(L); - var cosB = Math.cos(B); - return CT.m360(CT.r2D(Math.acos((x * cosB * Math.cos(L) + y * cosB * Math.sin(L) + z * Math.sin(B)) / Delta))); - }; - IFR.illuminatedFraction = function (PhaseAngle) { - PhaseAngle = CT.d2R(PhaseAngle); - return (1 + Math.cos(PhaseAngle)) / 2; - }; - IFR.illuminatedFraction2 = function (r, R, Delta) { - return (((r + Delta) * (r + Delta) - R * R) / (4 * r * Delta)); - }; - IFR.mercuryMagnitudeMuller = function (r, Delta, i) { - var I_50 = i - 50; - return 1.16 + 5 * Util.log10(r * Delta) + 0.02838 * I_50 + 0.0001023 * I_50 * I_50; - }; - IFR.venusMagnitudeMuller = function (r, Delta, i) { - return -4 + 5 * Util.log10(r * Delta) + 0.01322 * i + 4.247E-07 * i * i * i; - }; - IFR.marsMagnitudeMuller = function (r, Delta, i) { - return -1.3 + 5 * Util.log10(r * Delta) + 0.01486 * i; - }; - IFR.jupiterMagnitudeMuller = function (r, Delta) { - return -8.93 + 5 * Util.log10(r * Delta); - }; - IFR.saturnMagnitudeMuller = function (r, Delta, DeltaU, B) { - B = CT.d2R(B); - var sinB = Math.sin(B); - return -8.68 + 5 * Util.log10(r * Delta) + 0.044 * Math.abs(DeltaU) - 2.6 * Math.sin(Math.abs(B)) + 1.25 * sinB * sinB; - }; - IFR.uranusMagnitudeMuller = function (r, Delta) { - return -6.85 + 5 * Util.log10(r * Delta); - }; - IFR.neptuneMagnitudeMuller = function (r, Delta) { - return -7.05 + 5 * Util.log10(r * Delta); - }; - IFR.mercuryMagnitudeAA = function (r, Delta, i) { - var i2 = i * i; - var i3 = i2 * i; - return -0.42 + 5 * Util.log10(r * Delta) + 0.038 * i - 0.000273 * i2 + 2E-06 * i3; - }; - IFR.venusMagnitudeAA = function (r, Delta, i) { - var i2 = i * i; - var i3 = i2 * i; - return -4.4 + 5 * Util.log10(r * Delta) + 0.0009 * i + 0.000239 * i2 - 6.5E-07 * i3; - }; - IFR.marsMagnitudeAA = function (r, Delta, i) { - return -1.52 + 5 * Util.log10(r * Delta) + 0.016 * i; - }; - IFR.jupiterMagnitudeAA = function (r, Delta, i) { - return -9.4 + 5 * Util.log10(r * Delta) + 0.005 * i; - }; - IFR.saturnMagnitudeAA = function (r, Delta, DeltaU, B) { - B = CT.d2R(B); - var sinB = Math.sin(B); - return -8.88 + 5 * Util.log10(r * Delta) + 0.044 * Math.abs(DeltaU) - 2.6 * Math.sin(Math.abs(B)) + 1.25 * sinB * sinB; - }; - IFR.uranusMagnitudeAA = function (r, Delta) { - return -7.19 + 5 * Util.log10(r * Delta); - }; - IFR.neptuneMagnitudeAA = function (r, Delta) { - return -6.87 + 5 * Util.log10(r * Delta); - }; - IFR.plutoMagnitudeAA = function (r, Delta) { - return -1 + 5 * Util.log10(r * Delta); - }; - var IFR$ = { - - }; - - - // INTP - - function INTP() { - } - INTP.interpolate = function (n, Y1, Y2, Y3) { - var a = Y2 - Y1; - var b = Y3 - Y2; - var c = Y1 + Y3 - 2 * Y2; - return Y2 + n / 2 * (a + b + n * c); - }; - INTP.interpolate2 = function (n, Y1, Y2, Y3, Y4, Y5) { - var A = Y2 - Y1; - var B = Y3 - Y2; - var C = Y4 - Y3; - var D = Y5 - Y4; - var E = B - A; - var F = C - B; - var G = D - C; - var H = F - E; - var J = G - F; - var K = J - H; - var N2 = n * n; - var N3 = N2 * n; - var N4 = N3 * n; - return Y3 + n * ((B + C) / 2 - (H + J) / 12) + N2 * (F / 2 - K / 24) + N3 * ((H + J) / 12) + N4 * (K / 24); - }; - INTP.interpolateToHalves = function (Y1, Y2, Y3, Y4) { - return (9 * (Y2 + Y3) - Y1 - Y4) / 16; - }; - INTP.lagrangeInterpolate = function (X, n, pX, pY) { - var V = 0; - for (var i = 1; i <= n; i++) { - var C = 1; - for (var j = 1; j <= n; j++) { - if (j !== i) { - C = C * (X - pX[j - 1]) / (pX[i - 1] - pX[j - 1]); - } - } - V += C * pY[i - 1]; - } - return V; - }; - INTP.zero = function (Y1, Y2, Y3) { - var a = Y2 - Y1; - var b = Y3 - Y2; - var c = Y1 + Y3 - 2 * Y2; - var bRecalc = true; - var n0prev = 0; - var n0 = n0prev; - while (bRecalc) { - n0 = -2 * Y2 / (a + b + c * n0prev); - bRecalc = (Math.abs(n0 - n0prev) > 1E-12); - if (bRecalc) { - n0prev = n0; - } - } - return n0; - }; - INTP.zeroB = function (Y1, Y2, Y3, Y4, Y5) { - var A = Y2 - Y1; - var B = Y3 - Y2; - var C = Y4 - Y3; - var D = Y5 - Y4; - var E = B - A; - var F = C - B; - var G = D - C; - var H = F - E; - var J = G - F; - var K = J - H; - var bRecalc = true; - var n0prev = 0; - var n0 = n0prev; - while (bRecalc) { - var n0prev2 = n0prev * n0prev; - var n0prev3 = n0prev2 * n0prev; - var n0prev4 = n0prev3 * n0prev; - n0 = (-24 * Y3 + n0prev2 * (K - 12 * F) - 2 * n0prev3 * (H + J) - n0prev4 * K) / (2 * (6 * B + 6 * C - H - J)); - bRecalc = (Math.abs(n0 - n0prev) > 1E-12); - if (bRecalc) { - n0prev = n0; - } - } - return n0; - }; - INTP.zero2 = function (Y1, Y2, Y3) { - var a = Y2 - Y1; - var b = Y3 - Y2; - var c = Y1 + Y3 - 2 * Y2; - var bRecalc = true; - var n0prev = 0; - var n0 = n0prev; - while (bRecalc) { - var deltan0 = -(2 * Y2 + n0prev * (a + b + c * n0prev)) / (a + b + 2 * c * n0prev); - n0 = n0prev + deltan0; - bRecalc = (Math.abs(deltan0) > 1E-12); - if (bRecalc) { - n0prev = n0; - } - } - return n0; - }; - INTP.zero2B = function (Y1, Y2, Y3, Y4, Y5) { - var A = Y2 - Y1; - var B = Y3 - Y2; - var C = Y4 - Y3; - var D = Y5 - Y4; - var E = B - A; - var F = C - B; - var G = D - C; - var H = F - E; - var J = G - F; - var K = J - H; - var M = K / 24; - var N = (H + J) / 12; - var P = F / 2 - M; - var Q = (B + C) / 2 - N; - var bRecalc = true; - var n0prev = 0; - var n0 = n0prev; - while (bRecalc) { - var n0prev2 = n0prev * n0prev; - var n0prev3 = n0prev2 * n0prev; - var n0prev4 = n0prev3 * n0prev; - var deltan0 = -(M * n0prev4 + N * n0prev3 + P * n0prev2 + Q * n0prev + Y3) / (4 * M * n0prev3 + 3 * N * n0prev2 + 2 * P * n0prev + Q); - n0 = n0prev + deltan0; - bRecalc = (Math.abs(deltan0) > 1E-12); - if (bRecalc) { - n0prev = n0; - } - } - return n0; - }; - var INTP$ = { - - }; - - - // CAAJupiter - - function CAAJupiter() { - } - CAAJupiter.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0JupiterCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0JupiterCoefficients[i].a * Math.cos(GFX.g_L0JupiterCoefficients[i].b + GFX.g_L0JupiterCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1JupiterCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1JupiterCoefficients[i].a * Math.cos(GFX.g_L1JupiterCoefficients[i].b + GFX.g_L1JupiterCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2JupiterCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2JupiterCoefficients[i].a * Math.cos(GFX.g_L2JupiterCoefficients[i].b + GFX.g_L2JupiterCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3JupiterCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3JupiterCoefficients[i].a * Math.cos(GFX.g_L3JupiterCoefficients[i].b + GFX.g_L3JupiterCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4JupiterCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4JupiterCoefficients[i].a * Math.cos(GFX.g_L4JupiterCoefficients[i].b + GFX.g_L4JupiterCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5JupiterCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5JupiterCoefficients[i].a * Math.cos(GFX.g_L5JupiterCoefficients[i].b + GFX.g_L5JupiterCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAJupiter.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nB0Coefficients = GFX.g_B0JupiterCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0JupiterCoefficients[i].a * Math.cos(GFX.g_B0JupiterCoefficients[i].b + GFX.g_B0JupiterCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1JupiterCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1JupiterCoefficients[i].a * Math.cos(GFX.g_B1JupiterCoefficients[i].b + GFX.g_B1JupiterCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2JupiterCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2JupiterCoefficients[i].a * Math.cos(GFX.g_B2JupiterCoefficients[i].b + GFX.g_B2JupiterCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3JupiterCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3JupiterCoefficients[i].a * Math.cos(GFX.g_B3JupiterCoefficients[i].b + GFX.g_B3JupiterCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4JupiterCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4JupiterCoefficients[i].a * Math.cos(GFX.g_B4JupiterCoefficients[i].b + GFX.g_B4JupiterCoefficients[i].c * rho); - } - var nB5Coefficients = GFX.g_B5JupiterCoefficients.length; - var B5 = 0; - for (i = 0; i < nB5Coefficients; i++) { - B5 += GFX.g_B5JupiterCoefficients[i].a * Math.cos(GFX.g_B5JupiterCoefficients[i].b + GFX.g_B5JupiterCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4 + B5 * rho5) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAJupiter.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nR0Coefficients = GFX.g_R0JupiterCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0JupiterCoefficients[i].a * Math.cos(GFX.g_R0JupiterCoefficients[i].b + GFX.g_R0JupiterCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1JupiterCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1JupiterCoefficients[i].a * Math.cos(GFX.g_R1JupiterCoefficients[i].b + GFX.g_R1JupiterCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2JupiterCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2JupiterCoefficients[i].a * Math.cos(GFX.g_R2JupiterCoefficients[i].b + GFX.g_R2JupiterCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3JupiterCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3JupiterCoefficients[i].a * Math.cos(GFX.g_R3JupiterCoefficients[i].b + GFX.g_R3JupiterCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4JupiterCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4JupiterCoefficients[i].a * Math.cos(GFX.g_R4JupiterCoefficients[i].b + GFX.g_R4JupiterCoefficients[i].c * rho); - } - var nR5Coefficients = GFX.g_R5JupiterCoefficients.length; - var R5 = 0; - for (i = 0; i < nR5Coefficients; i++) { - R5 += GFX.g_R5JupiterCoefficients[i].a * Math.cos(GFX.g_R5JupiterCoefficients[i].b + GFX.g_R5JupiterCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4 + R5 * rho5) / 100000000; - }; - var CAAJupiter$ = { - - }; - - - // CAAKepler - - function CAAKepler() { - } - CAAKepler.calculate = function (M, e) { - return CAAKepler.calculateIter(M, e, 53); - }; - CAAKepler.calculateIter = function (M, e, nIterations) { - M = CT.d2R(M); - var PI = CT.PI(); - var F = 1; - if (M < 0) { - F = -1; - } - M = Math.abs(M) / (2 * PI); - M = (M - ss.truncate(M)) * 2 * PI * F; - if (M < 0) { - M += 2 * PI; - } - F = 1; - if (M > PI) { - F = -1; - } - if (M > PI) { - M = 2 * PI - M; - } - var E = PI / 2; - var scale = PI / 4; - for (var i = 0; i < nIterations; i++) { - var R = E - e * Math.sin(E); - if (M > R) { - E += scale; - } - else { - E -= scale; - } - scale /= 2; - } - return CT.r2D(E) * F; - }; - var CAAKepler$ = { - - }; - - - // CAAMars - - function CAAMars() { - } - CAAMars.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0MarsCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0MarsCoefficients[i].a * Math.cos(GFX.g_L0MarsCoefficients[i].b + GFX.g_L0MarsCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1MarsCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1MarsCoefficients[i].a * Math.cos(GFX.g_L1MarsCoefficients[i].b + GFX.g_L1MarsCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2MarsCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2MarsCoefficients[i].a * Math.cos(GFX.g_L2MarsCoefficients[i].b + GFX.g_L2MarsCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3MarsCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3MarsCoefficients[i].a * Math.cos(GFX.g_L3MarsCoefficients[i].b + GFX.g_L3MarsCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4MarsCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4MarsCoefficients[i].a * Math.cos(GFX.g_L4MarsCoefficients[i].b + GFX.g_L4MarsCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5MarsCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5MarsCoefficients[i].a * Math.cos(GFX.g_L5MarsCoefficients[i].b + GFX.g_L5MarsCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAMars.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0MarsCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0MarsCoefficients[i].a * Math.cos(GFX.g_B0MarsCoefficients[i].b + GFX.g_B0MarsCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1MarsCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1MarsCoefficients[i].a * Math.cos(GFX.g_B1MarsCoefficients[i].b + GFX.g_B1MarsCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2MarsCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2MarsCoefficients[i].a * Math.cos(GFX.g_B2MarsCoefficients[i].b + GFX.g_B2MarsCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3MarsCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3MarsCoefficients[i].a * Math.cos(GFX.g_B3MarsCoefficients[i].b + GFX.g_B3MarsCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4MarsCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4MarsCoefficients[i].a * Math.cos(GFX.g_B4MarsCoefficients[i].b + GFX.g_B4MarsCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAMars.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nR0Coefficients = GFX.g_R0MarsCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0MarsCoefficients[i].a * Math.cos(GFX.g_R0MarsCoefficients[i].b + GFX.g_R0MarsCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1MarsCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1MarsCoefficients[i].a * Math.cos(GFX.g_R1MarsCoefficients[i].b + GFX.g_R1MarsCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2MarsCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2MarsCoefficients[i].a * Math.cos(GFX.g_R2MarsCoefficients[i].b + GFX.g_R2MarsCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3MarsCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3MarsCoefficients[i].a * Math.cos(GFX.g_R3MarsCoefficients[i].b + GFX.g_R3MarsCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4MarsCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4MarsCoefficients[i].a * Math.cos(GFX.g_R4MarsCoefficients[i].b + GFX.g_R4MarsCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; - }; - var CAAMars$ = { - - }; - - - // CAAMercury - - function CAAMercury() { - } - CAAMercury.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0MercuryCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0MercuryCoefficients[i].a * Math.cos(GFX.g_L0MercuryCoefficients[i].b + GFX.g_L0MercuryCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1MercuryCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1MercuryCoefficients[i].a * Math.cos(GFX.g_L1MercuryCoefficients[i].b + GFX.g_L1MercuryCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2MercuryCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2MercuryCoefficients[i].a * Math.cos(GFX.g_L2MercuryCoefficients[i].b + GFX.g_L2MercuryCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3MercuryCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3MercuryCoefficients[i].a * Math.cos(GFX.g_L3MercuryCoefficients[i].b + GFX.g_L3MercuryCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4MercuryCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4MercuryCoefficients[i].a * Math.cos(GFX.g_L4MercuryCoefficients[i].b + GFX.g_L4MercuryCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5MercuryCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5MercuryCoefficients[i].a * Math.cos(GFX.g_L5MercuryCoefficients[i].b + GFX.g_L5MercuryCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAMercury.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0MercuryCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0MercuryCoefficients[i].a * Math.cos(GFX.g_B0MercuryCoefficients[i].b + GFX.g_B0MercuryCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1MercuryCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1MercuryCoefficients[i].a * Math.cos(GFX.g_B1MercuryCoefficients[i].b + GFX.g_B1MercuryCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2MercuryCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2MercuryCoefficients[i].a * Math.cos(GFX.g_B2MercuryCoefficients[i].b + GFX.g_B2MercuryCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3MercuryCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3MercuryCoefficients[i].a * Math.cos(GFX.g_B3MercuryCoefficients[i].b + GFX.g_B3MercuryCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4MercuryCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4MercuryCoefficients[i].a * Math.cos(GFX.g_B4MercuryCoefficients[i].b + GFX.g_B4MercuryCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAMercury.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var nR0Coefficients = GFX.g_R0MercuryCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0MercuryCoefficients[i].a * Math.cos(GFX.g_R0MercuryCoefficients[i].b + GFX.g_R0MercuryCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1MercuryCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1MercuryCoefficients[i].a * Math.cos(GFX.g_R1MercuryCoefficients[i].b + GFX.g_R1MercuryCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2MercuryCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2MercuryCoefficients[i].a * Math.cos(GFX.g_R2MercuryCoefficients[i].b + GFX.g_R2MercuryCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3MercuryCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3MercuryCoefficients[i].a * Math.cos(GFX.g_R3MercuryCoefficients[i].b + GFX.g_R3MercuryCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed) / 100000000; - }; - var CAAMercury$ = { - - }; - - - // CAAMoon - - function CAAMoon() { - } - CAAMoon.meanLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(218.3164477 + 481267.88123421 * T - 0.0015786 * Tsquared + Tcubed / 538841 - T4 / 65194000); - }; - CAAMoon.meanElongation = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(297.8501921 + 445267.1114034 * T - 0.0018819 * Tsquared + Tcubed / 545868 - T4 / 113065000); - }; - CAAMoon.meanAnomaly = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(134.9633964 + 477198.8675055 * T + 0.0087414 * Tsquared + Tcubed / 69699 - T4 / 14712000); - }; - CAAMoon.argumentOfLatitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(93.272095 + 483202.0175233 * T - 0.0036539 * Tsquared - Tcubed / 3526000 + T4 / 863310000); - }; - CAAMoon.meanLongitudeAscendingNode = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(125.0445479 - 1934.1362891 * T + 0.0020754 * Tsquared + Tcubed / 467441 - T4 / 60616000); - }; - CAAMoon.meanLongitudePerigee = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return CT.m360(83.3532465 + 4069.0137287 * T - 0.01032 * Tsquared - Tcubed / 80053 + T4 / 18999000); - }; - CAAMoon.trueLongitudeAscendingNode = function (JD) { - var TrueAscendingNode = CAAMoon.meanLongitudeAscendingNode(JD); - var D = CAAMoon.meanElongation(JD); - D = CT.d2R(D); - var M = CAAEarth.sunMeanAnomaly(JD); - M = CT.d2R(M); - var Mdash = CAAMoon.meanAnomaly(JD); - Mdash = CT.d2R(Mdash); - var F = CAAMoon.argumentOfLatitude(JD); - F = CT.d2R(F); - TrueAscendingNode -= 1.4979 * Math.sin(2 * (D - F)); - TrueAscendingNode -= 0.15 * Math.sin(M); - TrueAscendingNode -= 0.1226 * Math.sin(2 * D); - TrueAscendingNode += 0.1176 * Math.sin(2 * F); - TrueAscendingNode -= 0.0801 * Math.sin(2 * (Mdash - F)); - return CT.m360(TrueAscendingNode); - }; - CAAMoon.eclipticLongitude = function (JD) { - var Ldash = CAAMoon.meanLongitude(JD); - var LdashDegrees = Ldash; - Ldash = CT.d2R(Ldash); - var D = CAAMoon.meanElongation(JD); - D = CT.d2R(D); - var M = CAAEarth.sunMeanAnomaly(JD); - M = CT.d2R(M); - var Mdash = CAAMoon.meanAnomaly(JD); - Mdash = CT.d2R(Mdash); - var F = CAAMoon.argumentOfLatitude(JD); - F = CT.d2R(F); - var E = CAAEarth.eccentricity(JD); - var T = (JD - 2451545) / 36525; - var A1 = CT.m360(119.75 + 131.849 * T); - A1 = CT.d2R(A1); - var A2 = CT.m360(53.09 + 479264.29 * T); - A2 = CT.d2R(A2); - var A3 = CT.m360(313.45 + 481266.484 * T); - A3 = CT.d2R(A3); - var nLCoefficients = GFX.g_MoonCoefficients1.length; - console.assert(GFX.g_MoonCoefficients2.length === nLCoefficients); - var SigmaL = 0; - for (var i = 0; i < nLCoefficients; i++) { - var ThisSigma = GFX.g_MoonCoefficients2[i].a * Math.sin(GFX.g_MoonCoefficients1[i].d * D + GFX.g_MoonCoefficients1[i].m * M + GFX.g_MoonCoefficients1[i].mdash * Mdash + GFX.g_MoonCoefficients1[i].f * F); - if (!!GFX.g_MoonCoefficients1[i].m) { - ThisSigma *= E; - } - SigmaL += ThisSigma; - } - SigmaL += 3958 * Math.sin(A1); - SigmaL += 1962 * Math.sin(Ldash - F); - SigmaL += 318 * Math.sin(A2); - var NutationInLong = CAANutation.nutationInLongitude(JD); - return CT.m360(LdashDegrees + SigmaL / 1000000 + NutationInLong / 3600); - }; - CAAMoon.eclipticLatitude = function (JD) { - var Ldash = CAAMoon.meanLongitude(JD); - Ldash = CT.d2R(Ldash); - var D = CAAMoon.meanElongation(JD); - D = CT.d2R(D); - var M = CAAEarth.sunMeanAnomaly(JD); - M = CT.d2R(M); - var Mdash = CAAMoon.meanAnomaly(JD); - Mdash = CT.d2R(Mdash); - var F = CAAMoon.argumentOfLatitude(JD); - F = CT.d2R(F); - var E = CAAEarth.eccentricity(JD); - var T = (JD - 2451545) / 36525; - var A1 = CT.m360(119.75 + 131.849 * T); - A1 = CT.d2R(A1); - var A2 = CT.m360(53.09 + 479264.29 * T); - A2 = CT.d2R(A2); - var A3 = CT.m360(313.45 + 481266.484 * T); - A3 = CT.d2R(A3); - var nBCoefficients = GFX.g_MoonCoefficients3.length; - console.assert(GFX.g_MoonCoefficients4.length === nBCoefficients); - var SigmaB = 0; - for (var i = 0; i < nBCoefficients; i++) { - var ThisSigma = GFX.g_MoonCoefficients4[i] * Math.sin(GFX.g_MoonCoefficients3[i].d * D + GFX.g_MoonCoefficients3[i].m * M + GFX.g_MoonCoefficients3[i].mdash * Mdash + GFX.g_MoonCoefficients3[i].f * F); - if (!!GFX.g_MoonCoefficients3[i].m) { - ThisSigma *= E; - } - SigmaB += ThisSigma; - } - SigmaB -= 2235 * Math.sin(Ldash); - SigmaB += 382 * Math.sin(A3); - SigmaB += 175 * Math.sin(A1 - F); - SigmaB += 175 * Math.sin(A1 + F); - SigmaB += 127 * Math.sin(Ldash - Mdash); - SigmaB -= 115 * Math.sin(Ldash + Mdash); - return SigmaB / 1000000; - }; - CAAMoon.radiusVector = function (JD) { - var Ldash = CAAMoon.meanLongitude(JD); - Ldash = CT.d2R(Ldash); - var D = CAAMoon.meanElongation(JD); - D = CT.d2R(D); - var M = CAAEarth.sunMeanAnomaly(JD); - M = CT.d2R(M); - var Mdash = CAAMoon.meanAnomaly(JD); - Mdash = CT.d2R(Mdash); - var F = CAAMoon.argumentOfLatitude(JD); - F = CT.d2R(F); - var E = CAAEarth.eccentricity(JD); - var T = (JD - 2451545) / 36525; - var A1 = CT.m360(119.75 + 131.849 * T); - A1 = CT.d2R(A1); - var A2 = CT.m360(53.09 + 479264.29 * T); - A2 = CT.d2R(A2); - var A3 = CT.m360(313.45 + 481266.484 * T); - A3 = CT.d2R(A3); - var nRCoefficients = GFX.g_MoonCoefficients1.length; - console.assert(GFX.g_MoonCoefficients2.length === nRCoefficients); - var SigmaR = 0; - for (var i = 0; i < nRCoefficients; i++) { - var ThisSigma = GFX.g_MoonCoefficients2[i].b * Math.cos(GFX.g_MoonCoefficients1[i].d * D + GFX.g_MoonCoefficients1[i].m * M + GFX.g_MoonCoefficients1[i].mdash * Mdash + GFX.g_MoonCoefficients1[i].f * F); - if (!!GFX.g_MoonCoefficients1[i].m) { - ThisSigma *= E; - } - SigmaR += ThisSigma; - } - return 385000.56 + SigmaR / 1000; - }; - CAAMoon.radiusVectorToHorizontalParallax = function (RadiusVector) { - return CT.r2D(Math.asin(6378.14 / RadiusVector)); - }; - CAAMoon.horizontalParallaxToRadiusVector = function (Parallax) { - return 6378.14 / Math.sin(CT.d2R(Parallax)); - }; - var CAAMoon$ = { - - }; - - - // MoonCoefficient1 - - function MoonCoefficient1(d, m, mdash, f) { - this.d = 0; - this.m = 0; - this.mdash = 0; - this.f = 0; - this.d = d; - this.m = m; - this.mdash = mdash; - this.f = f; - } - var MoonCoefficient1$ = { - - }; - - - // MoonCoefficient2 - - function MoonCoefficient2(a, b) { - this.a = 0; - this.b = 0; - this.a = a; - this.b = b; - } - var MoonCoefficient2$ = { - - }; - - - // MIFR - - function MIFR() { - } - MIFR.geocentricElongation = function (ObjectAlpha, ObjectDelta, SunAlpha, SunDelta) { - ObjectAlpha = CT.d2R(ObjectAlpha * 15); - SunAlpha = CT.d2R(SunAlpha * 15); - ObjectDelta = CT.d2R(ObjectDelta); - SunDelta = CT.d2R(SunDelta); - return CT.r2D(Math.acos(Math.sin(SunDelta) * Math.sin(ObjectDelta) + Math.cos(SunDelta) * Math.cos(ObjectDelta) * Math.cos(SunAlpha - ObjectAlpha))); - }; - MIFR.phaseAngle = function (GeocentricElongation, EarthObjectDistance, EarthSunDistance) { - GeocentricElongation = CT.d2R(GeocentricElongation); - return CT.m360(CT.r2D(Math.atan2(EarthSunDistance * Math.sin(GeocentricElongation), EarthObjectDistance - EarthSunDistance * Math.cos(GeocentricElongation)))); - }; - MIFR.illuminatedFraction = function (PhaseAngle) { - PhaseAngle = CT.d2R(PhaseAngle); - return (1 + Math.cos(PhaseAngle)) / 2; - }; - MIFR.positionAngle = function (Alpha0, Delta0, Alpha, Delta) { - Alpha0 = CT.h2R(Alpha0); - Alpha = CT.h2R(Alpha); - Delta0 = CT.d2R(Delta0); - Delta = CT.d2R(Delta); - return CT.m360(CT.r2D(Math.atan2(Math.cos(Delta0) * Math.sin(Alpha0 - Alpha), Math.sin(Delta0) * Math.cos(Delta) - Math.cos(Delta0) * Math.sin(Delta) * Math.cos(Alpha0 - Alpha)))); - }; - var MIFR$ = { - - }; - - - // CAAMoonNodes - - function CAAMoonNodes() { - } - CAAMoonNodes.k = function (Year) { - return 13.4223 * (Year - 2000.05); - }; - CAAMoonNodes.passageThroNode = function (k) { - var T = k / 1342.23; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - var D = CT.m360(183.638 + 331.73735682 * k + 0.0014852 * Tsquared + 2.09E-06 * Tcubed - 1E-08 * T4); - var M = CT.m360(17.4006 + 26.8203725 * k + 0.0001186 * Tsquared + 6E-08 * Tcubed); - var Mdash = CT.m360(38.3776 + 355.52747313 * k + 0.0123499 * Tsquared + 1.4627E-05 * Tcubed - 6.9E-08 * T4); - var omega = CT.m360(123.9767 - 1.44098956 * k + 0.0020608 * Tsquared + 2.14E-06 * Tcubed - 1.6E-08 * T4); - var V = CT.m360(299.75 + 132.85 * T - 0.009173 * Tsquared); - var P = CT.m360(omega + 272.75 - 2.3 * T); - var E = 1 - 0.002516 * T - 7.4E-06 * Tsquared; - D = CT.d2R(D); - var D2 = 2 * D; - var D4 = D2 * D2; - M = CT.d2R(M); - Mdash = CT.d2R(Mdash); - var Mdash2 = 2 * Mdash; - omega = CT.d2R(omega); - V = CT.d2R(V); - P = CT.d2R(P); - var JD = 2451565.1619 + 27.212220817 * k + 0.0002762 * Tsquared + 2.1E-08 * Tcubed - 8.8E-11 * T4 - 0.4721 * Math.sin(Mdash) - 0.1649 * Math.sin(D2) - 0.0868 * Math.sin(D2 - Mdash) + 0.0084 * Math.sin(D2 + Mdash) - E * 0.0083 * Math.sin(D2 - M) - E * 0.0039 * Math.sin(D2 - M - Mdash) + 0.0034 * Math.sin(Mdash2) - 0.0031 * Math.sin(D2 - Mdash2) + E * 0.003 * Math.sin(D2 + M) + E * 0.0028 * Math.sin(M - Mdash) + E * 0.0026 * Math.sin(M) + 0.0025 * Math.sin(D4) + 0.0024 * Math.sin(D) + E * 0.0022 * Math.sin(M + Mdash) + 0.0017 * Math.sin(omega) + 0.0014 * Math.sin(D4 - Mdash) + E * 0.0005 * Math.sin(D2 + M - Mdash) + E * 0.0004 * Math.sin(D2 - M + Mdash) - E * 0.0003 * Math.sin(D2 - M * M) + E * 0.0003 * Math.sin(D4 - M) + 0.0003 * Math.sin(V) + 0.0003 * Math.sin(P); - return JD; - }; - var CAAMoonNodes$ = { - - }; - - - // CAAMoonPerigeeApogee - - function CAAMoonPerigeeApogee() { - } - CAAMoonPerigeeApogee.k = function (Year) { - return 13.2555 * (Year - 1999.97); - }; - CAAMoonPerigeeApogee.meanPerigee = function (k) { - var T = k / 1325.55; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - return 2451534.6698 + 27.55454989 * k - 0.0006691 * Tsquared - 1.098E-06 * Tcubed + 5.2E-09 * T4; - }; - CAAMoonPerigeeApogee.meanApogee = function (k) { - return CAAMoonPerigeeApogee.meanPerigee(k); - }; - CAAMoonPerigeeApogee.truePerigee = function (k) { - var MeanJD = CAAMoonPerigeeApogee.meanPerigee(k); - var T = k / 1325.55; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); - D = CT.d2R(D); - var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); - M = CT.d2R(M); - var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); - F = CT.d2R(F); - var nPerigeeCoefficients = GFX.g_MoonPerigeeApogeeCoefficients1.length; - var Sigma = 0; - for (var i = 0; i < nPerigeeCoefficients; i++) { - Sigma += GFX.g_MoonPerigeeApogeeCoefficients1[i].c * Math.sin(D * GFX.g_MoonPerigeeApogeeCoefficients1[i].d + M * GFX.g_MoonPerigeeApogeeCoefficients1[i].m + F * GFX.g_MoonPerigeeApogeeCoefficients1[i].f + T * GFX.g_MoonPerigeeApogeeCoefficients1[i].t); - } - return MeanJD + Sigma; - }; - CAAMoonPerigeeApogee.trueApogee = function (k) { - var MeanJD = CAAMoonPerigeeApogee.meanApogee(k); - var T = k / 1325.55; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); - D = CT.d2R(D); - var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); - M = CT.d2R(M); - var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); - F = CT.d2R(F); - var nApogeeCoefficients = GFX.g_MoonPerigeeApogeeCoefficients2.length; - var Sigma = 0; - for (var i = 0; i < nApogeeCoefficients; i++) { - Sigma += (GFX.g_MoonPerigeeApogeeCoefficients2[i].c + T * GFX.g_MoonPerigeeApogeeCoefficients2[i].t) * Math.sin(D * GFX.g_MoonPerigeeApogeeCoefficients2[i].d + M * GFX.g_MoonPerigeeApogeeCoefficients2[i].m + F * GFX.g_MoonPerigeeApogeeCoefficients2[i].f); - } - return MeanJD + Sigma; - }; - CAAMoonPerigeeApogee.perigeeParallax = function (k) { - var T = k / 1325.55; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); - D = CT.d2R(D); - var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); - M = CT.d2R(M); - var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); - F = CT.d2R(F); - var nPerigeeCoefficients = GFX.g_MoonPerigeeApogeeCoefficients3.length; - var Parallax = 3629.215; - for (var i = 0; i < nPerigeeCoefficients; i++) { - Parallax += (GFX.g_MoonPerigeeApogeeCoefficients3[i].c + T * GFX.g_MoonPerigeeApogeeCoefficients3[i].t) * Math.cos(D * GFX.g_MoonPerigeeApogeeCoefficients3[i].d + M * GFX.g_MoonPerigeeApogeeCoefficients3[i].m + F * GFX.g_MoonPerigeeApogeeCoefficients3[i].f); - } - return Parallax / 3600; - }; - CAAMoonPerigeeApogee.apogeeParallax = function (k) { - var T = k / 1325.55; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var T4 = Tcubed * T; - var D = CT.m360(171.9179 + 335.9106046 * k - 0.0100383 * Tsquared - 1.156E-05 * Tcubed + 5.5E-08 * T4); - D = CT.d2R(D); - var M = CT.m360(347.3477 + 27.1577721 * k - 0.000813 * Tsquared - 1E-06 * Tcubed); - M = CT.d2R(M); - var F = CT.m360(316.6109 + 364.5287911 * k - 0.0125053 * Tsquared - 1.48E-05 * Tcubed); - F = CT.d2R(F); - var nApogeeCoefficients = GFX.g_MoonPerigeeApogeeCoefficients4.length; - var Parallax = 3245.251; - for (var i = 0; i < nApogeeCoefficients; i++) { - Parallax += (GFX.g_MoonPerigeeApogeeCoefficients4[i].c + T * GFX.g_MoonPerigeeApogeeCoefficients4[i].t) * Math.cos(D * GFX.g_MoonPerigeeApogeeCoefficients4[i].d + M * GFX.g_MoonPerigeeApogeeCoefficients4[i].m + F * GFX.g_MoonPerigeeApogeeCoefficients4[i].f); - } - return Parallax / 3600; - }; - var CAAMoonPerigeeApogee$ = { - - }; - - - // MPAC - - function MPAC(D, M, F, C, T) { - this.d = 0; - this.m = 0; - this.f = 0; - this.c = 0; - this.t = 0; - this.d = D; - this.m = M; - this.f = F; - this.c = C; - this.t = T; - } - var MPAC$ = { - - }; - - - // CAAMoonPhases - - function CAAMoonPhases() { - } - CAAMoonPhases.k = function (Year) { - return 12.3685 * (Year - 2000); - }; - CAAMoonPhases.meanPhase = function (k) { - var T = k / 1236.85; - var T2 = T * T; - var T3 = T2 * T; - var T4 = T3 * T; - return 2451550.09766 + 29.530588861 * k + 0.00015437 * T2 - 1.5E-07 * T3 + 7.3E-10 * T4; - }; - CAAMoonPhases.truePhase = function (k) { - var JD = CAAMoonPhases.meanPhase(k); - var T = k / 1236.85; - var T2 = T * T; - var T3 = T2 * T; - var T4 = T3 * T; - var E = 1 - 0.002516 * T - 7.4E-06 * T2; - var E2 = E * E; - var M = CT.m360(2.5534 + 29.1053567 * k - 1.4E-06 * T2 - 1.1E-07 * T3); - M = CT.d2R(M); - var Mdash = CT.m360(201.5643 + 385.81693528 * k + 0.0107582 * T2 + 1.238E-05 * T3 - 5.8E-08 * T4); - Mdash = CT.d2R(Mdash); - var F = CT.m360(160.7108 + 390.67050284 * k - 0.0016118 * T2 - 2.27E-06 * T3 + 1E-08 * T4); - F = CT.d2R(F); - var omega = CT.m360(124.7746 - 1.56375588 * k + 0.0020672 * T2 + 2.15E-06 * T3); - omega = CT.d2R(omega); - var A1 = CT.m360(299.77 + 0.107408 * k - 0.009173 * T2); - A1 = CT.d2R(A1); - var A2 = CT.m360(251.88 + 0.016321 * k); - A2 = CT.d2R(A2); - var A3 = CT.m360(251.83 + 26.651886 * k); - A3 = CT.d2R(A3); - var A4 = CT.m360(349.42 + 36.412478 * k); - A4 = CT.d2R(A4); - var A5 = CT.m360(84.66 + 18.206239 * k); - A5 = CT.d2R(A5); - var A6 = CT.m360(141.74 + 53.303771 * k); - A6 = CT.d2R(A6); - var A7 = CT.m360(207.14 + 2.453732 * k); - A7 = CT.d2R(A7); - var A8 = CT.m360(154.84 + 7.30686 * k); - A8 = CT.d2R(A8); - var A9 = CT.m360(34.52 + 27.261239 * k); - A9 = CT.d2R(A9); - var A10 = CT.m360(207.19 + 0.121824 * k); - A10 = CT.d2R(A10); - var A11 = CT.m360(291.34 + 1.844379 * k); - A11 = CT.d2R(A11); - var A12 = CT.m360(161.72 + 24.198154 * k); - A12 = CT.d2R(A12); - var A13 = CT.m360(239.56 + 25.513099 * k); - A13 = CT.d2R(A13); - var A14 = CT.m360(331.55 + 3.592518 * k); - A14 = CT.d2R(A14); - var kint = Math.floor(k); - var kfrac = k - kint; - if (kfrac < 0) { - kfrac = 1 + kfrac; - } - if (!kfrac) { - var DeltaJD = -0.4072 * Math.sin(Mdash) + 0.17241 * E * Math.sin(M) + 0.01608 * Math.sin(2 * Mdash) + 0.01039 * Math.sin(2 * F) + 0.00739 * E * Math.sin(Mdash - M) + -0.00514 * E * Math.sin(Mdash + M) + 0.00208 * E2 * Math.sin(2 * M) + -0.00111 * Math.sin(Mdash - 2 * F) + -0.00057 * Math.sin(Mdash + 2 * F) + 0.00056 * E * Math.sin(2 * Mdash + M) + -0.00042 * Math.sin(3 * Mdash) + 0.00042 * E * Math.sin(M + 2 * F) + 0.00038 * E * Math.sin(M - 2 * F) + -0.00024 * E * Math.sin(2 * Mdash - M) + -0.00017 * Math.sin(omega) + -7E-05 * Math.sin(Mdash + 2 * M) + 4E-05 * Math.sin(2 * Mdash - 2 * F) + 4E-05 * Math.sin(3 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(2 * Mdash + 2 * F) + -3E-05 * Math.sin(Mdash + M + 2 * F) + 3E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(Mdash - M - 2 * F) + -2E-05 * Math.sin(3 * Mdash + M) + 2E-05 * Math.sin(4 * Mdash); - JD += DeltaJD; - } - else if ((kfrac === 0.25) || (kfrac === 0.75)) { - var DeltaJD = -0.62801 * Math.sin(Mdash) + 0.17172 * E * Math.sin(M) + -0.01183 * E * Math.sin(Mdash + M) + 0.00862 * Math.sin(2 * Mdash) + 0.00804 * Math.sin(2 * F) + 0.00454 * E * Math.sin(Mdash - M) + 0.00204 * E2 * Math.sin(2 * M) + -0.0018 * Math.sin(Mdash - 2 * F) + -0.0007 * Math.sin(Mdash + 2 * F) + -0.0004 * Math.sin(3 * Mdash) + -0.00034 * E * Math.sin(2 * Mdash - M) + 0.00032 * E * Math.sin(M + 2 * F) + 0.00032 * E * Math.sin(M - 2 * F) + -0.00028 * E2 * Math.sin(Mdash + 2 * M) + 0.00027 * E * Math.sin(2 * Mdash + M) + -0.00017 * Math.sin(omega) + -5E-05 * Math.sin(Mdash - M - 2 * F) + 4E-05 * Math.sin(2 * Mdash + 2 * F) + -4E-05 * Math.sin(Mdash + M + 2 * F) + 4E-05 * Math.sin(Mdash - 2 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(3 * M) + 2E-05 * Math.sin(2 * Mdash - 2 * F) + 2E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(3 * Mdash + M); - JD += DeltaJD; - var W = 0.00306 - 0.00038 * E * Math.cos(M) + 0.00026 * Math.cos(Mdash) - 2E-05 * Math.cos(Mdash - M) + 2E-05 * Math.cos(Mdash + M) + 2E-05 * Math.cos(2 * F); - if (kfrac === 0.25) { - JD += W; - } - else { - JD -= W; - } - } - else if (kfrac === 0.5) { - var DeltaJD = -0.40614 * Math.sin(Mdash) + 0.17302 * E * Math.sin(M) + 0.01614 * Math.sin(2 * Mdash) + 0.01043 * Math.sin(2 * F) + 0.00734 * E * Math.sin(Mdash - M) + -0.00514 * E * Math.sin(Mdash + M) + 0.00209 * E2 * Math.sin(2 * M) + -0.00111 * Math.sin(Mdash - 2 * F) + -0.00057 * Math.sin(Mdash + 2 * F) + 0.00056 * E * Math.sin(2 * Mdash + M) + -0.00042 * Math.sin(3 * Mdash) + 0.00042 * E * Math.sin(M + 2 * F) + 0.00038 * E * Math.sin(M - 2 * F) + -0.00024 * E * Math.sin(2 * Mdash - M) + -0.00017 * Math.sin(omega) + -7E-05 * Math.sin(Mdash + 2 * M) + 4E-05 * Math.sin(2 * Mdash - 2 * F) + 4E-05 * Math.sin(3 * M) + 3E-05 * Math.sin(Mdash + M - 2 * F) + 3E-05 * Math.sin(2 * Mdash + 2 * F) + -3E-05 * Math.sin(Mdash + M + 2 * F) + 3E-05 * Math.sin(Mdash - M + 2 * F) + -2E-05 * Math.sin(Mdash - M - 2 * F) + -2E-05 * Math.sin(3 * Mdash + M) + 2E-05 * Math.sin(4 * Mdash); - JD += DeltaJD; - } - else { - console.assert(false); - } - var DeltaJD2 = 0.000325 * Math.sin(A1) + 0.000165 * Math.sin(A2) + 0.000164 * Math.sin(A3) + 0.000126 * Math.sin(A4) + 0.00011 * Math.sin(A5) + 6.2E-05 * Math.sin(A6) + 6E-05 * Math.sin(A7) + 5.6E-05 * Math.sin(A8) + 4.7E-05 * Math.sin(A9) + 4.2E-05 * Math.sin(A10) + 4E-05 * Math.sin(A11) + 3.7E-05 * Math.sin(A12) + 3.5E-05 * Math.sin(A13) + 2.3E-05 * Math.sin(A14); - JD += DeltaJD2; - return JD; - }; - var CAAMoonPhases$ = { - - }; - - - // CAANeptune - - function CAANeptune() { - } - CAANeptune.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nL0Coefficients = GFX.g_L0NC.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0NC[i].a * Math.cos(GFX.g_L0NC[i].b + GFX.g_L0NC[i].c * rho); - } - var nL1Coefficients = GFX.g_L1NC.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1NC[i].a * Math.cos(GFX.g_L1NC[i].b + GFX.g_L1NC[i].c * rho); - } - var nL2Coefficients = GFX.g_L2NC.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2NC[i].a * Math.cos(GFX.g_L2NC[i].b + GFX.g_L2NC[i].c * rho); - } - var nL3Coefficients = GFX.g_L3NC.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3NC[i].a * Math.cos(GFX.g_L3NC[i].b + GFX.g_L3NC[i].c * rho); - } - var nL4Coefficients = GFX.g_L4NC.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4NC[i].a * Math.cos(GFX.g_L4NC[i].b + GFX.g_L4NC[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAANeptune.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0NC.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0NC[i].a * Math.cos(GFX.g_B0NC[i].b + GFX.g_B0NC[i].c * rho); - } - var nB1Coefficients = GFX.g_B1NC.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1NC[i].a * Math.cos(GFX.g_B1NC[i].b + GFX.g_B1NC[i].c * rho); - } - var nB2Coefficients = GFX.g_B2NC.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2NC[i].a * Math.cos(GFX.g_B2NC[i].b + GFX.g_B2NC[i].c * rho); - } - var nB3Coefficients = GFX.g_B3NC.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3NC[i].a * Math.cos(GFX.g_B3NC[i].b + GFX.g_B3NC[i].c * rho); - } - var nB4Coefficients = GFX.g_B4NC.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4NC[i].a * Math.cos(GFX.g_B4NC[i].b + GFX.g_B4NC[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAANeptune.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var nR0Coefficients = GFX.g_R0NC.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0NC[i].a * Math.cos(GFX.g_R0NC[i].b + GFX.g_R0NC[i].c * rho); - } - var nR1Coefficients = GFX.g_R1NC.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1NC[i].a * Math.cos(GFX.g_R1NC[i].b + GFX.g_R1NC[i].c * rho); - } - var nR2Coefficients = GFX.g_R2NC.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2NC[i].a * Math.cos(GFX.g_R2NC[i].b + GFX.g_R2NC[i].c * rho); - } - var nR3Coefficients = GFX.g_R3NC.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3NC[i].a * Math.cos(GFX.g_R3NC[i].b + GFX.g_R3NC[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed) / 100000000; - }; - var CAANeptune$ = { - - }; - - - // CAANutation - - function CAANutation() { - } - CAANutation.nutationInLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var D = 297.85036 + 445267.11148 * T - 0.0019142 * Tsquared + Tcubed / 189474; - D = CT.m360(D); - var M = 357.52772 + 35999.05034 * T - 0.0001603 * Tsquared - Tcubed / 300000; - M = CT.m360(M); - var Mprime = 134.96298 + 477198.867398 * T + 0.0086972 * Tsquared + Tcubed / 56250; - Mprime = CT.m360(Mprime); - var F = 93.27191 + 483202.017538 * T - 0.0036825 * Tsquared + Tcubed / 327270; - F = CT.m360(F); - var omega = 125.04452 - 1934.136261 * T + 0.0020708 * Tsquared + Tcubed / 450000; - omega = CT.m360(omega); - var nCoefficients = GFX.g_NuC.length; - var vvalue = 0; - for (var i = 0; i < nCoefficients; i++) { - var argument = GFX.g_NuC[i].d * D + GFX.g_NuC[i].m * M + GFX.g_NuC[i].mprime * Mprime + GFX.g_NuC[i].f * F + GFX.g_NuC[i].omega * omega; - var radargument = CT.d2R(argument); - vvalue += (GFX.g_NuC[i].sincoeff1 + GFX.g_NuC[i].sincoeff2 * T) * Math.sin(radargument) * 0.0001; - } - return vvalue; - }; - CAANutation.nutationInObliquity = function (JD) { - var T = (JD - 2451545) / 36525; - var Tsquared = T * T; - var Tcubed = Tsquared * T; - var D = 297.85036 + 445267.11148 * T - 0.0019142 * Tsquared + Tcubed / 189474; - D = CT.m360(D); - var M = 357.52772 + 35999.05034 * T - 0.0001603 * Tsquared - Tcubed / 300000; - M = CT.m360(M); - var Mprime = 134.96298 + 477198.867398 * T + 0.0086972 * Tsquared + Tcubed / 56250; - Mprime = CT.m360(Mprime); - var F = 93.27191 + 483202.017538 * T - 0.0036825 * Tsquared + Tcubed / 327270; - F = CT.m360(F); - var omega = 125.04452 - 1934.136261 * T + 0.0020708 * Tsquared + Tcubed / 450000; - omega = CT.m360(omega); - var nCoefficients = GFX.g_NuC.length; - var vvalue = 0; - for (var i = 0; i < nCoefficients; i++) { - var argument = GFX.g_NuC[i].d * D + GFX.g_NuC[i].m * M + GFX.g_NuC[i].mprime * Mprime + GFX.g_NuC[i].f * F + GFX.g_NuC[i].omega * omega; - var radargument = CT.d2R(argument); - vvalue += (GFX.g_NuC[i].coscoeff1 + GFX.g_NuC[i].coscoeff2 * T) * Math.cos(radargument) * 0.0001; - } - return vvalue; - }; - CAANutation.nutationInRightAscension = function (Alpha, Delta, Obliquity, NutationInLongitude, NutationInObliquity) { - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - Obliquity = CT.d2R(Obliquity); - return (Math.cos(Obliquity) + Math.sin(Obliquity) * Math.sin(Alpha) * Math.tan(Delta)) * NutationInLongitude - Math.cos(Alpha) * Math.tan(Delta) * NutationInObliquity; - }; - CAANutation.nutationInDeclination = function (Alpha, Delta, Obliquity, NutationInLongitude, NutationInObliquity) { - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - Obliquity = CT.d2R(Obliquity); - return Math.sin(Obliquity) * Math.cos(Alpha) * NutationInLongitude + Math.sin(Alpha) * NutationInObliquity; - }; - CAANutation.meanObliquityOfEcliptic = function (JD) { - var U = (JD - 2451545) / 3652500; - var Usquared = U * U; - var Ucubed = Usquared * U; - var U4 = Ucubed * U; - var U5 = U4 * U; - var U6 = U5 * U; - var U7 = U6 * U; - var U8 = U7 * U; - var U9 = U8 * U; - var U10 = U9 * U; - return CT.dmS2D(23, 26, 21.448) - CT.dmS2D(0, 0, 4680.93) * U - CT.dmS2D(0, 0, 1.55) * Usquared + CT.dmS2D(0, 0, 1999.25) * Ucubed - CT.dmS2D(0, 0, 51.38) * U4 - CT.dmS2D(0, 0, 249.67) * U5 - CT.dmS2D(0, 0, 39.05) * U6 + CT.dmS2D(0, 0, 7.12) * U7 + CT.dmS2D(0, 0, 27.87) * U8 + CT.dmS2D(0, 0, 5.79) * U9 + CT.dmS2D(0, 0, 2.45) * U10; - }; - CAANutation.trueObliquityOfEcliptic = function (JD) { - return CAANutation.meanObliquityOfEcliptic(JD) + CT.dmS2D(0, 0, CAANutation.nutationInObliquity(JD)); - }; - var CAANutation$ = { - - }; - - - // NUC - - function NUC(D, M, Mprime, F, omega, sincoeff1, sincoeff2, coscoeff1, coscoeff2) { - this.d = 0; - this.m = 0; - this.mprime = 0; - this.f = 0; - this.omega = 0; - this.sincoeff1 = 0; - this.sincoeff2 = 0; - this.coscoeff1 = 0; - this.coscoeff2 = 0; - this.d = D; - this.m = M; - this.mprime = Mprime; - this.f = F; - this.omega = omega; - this.sincoeff1 = sincoeff1; - this.sincoeff2 = sincoeff2; - this.coscoeff1 = coscoeff1; - this.coscoeff2 = coscoeff2; - } - var NUC$ = { - - }; - - - // CAATopocentricEclipticDetails - - function CAATopocentricEclipticDetails() { - this.lambda = 0; - this.beta = 0; - this.semidiameter = 0; - this.lambda = 0; - this.beta = 0; - this.semidiameter = 0; - } - var CAATopocentricEclipticDetails$ = { - - }; - - - // CAAParallax - - function CAAParallax() { - } - CAAParallax.equatorial2TopocentricDelta = function (Alpha, Delta, Distance, Longitude, Latitude, Height, JD) { - var RhoSinThetaPrime = CAAGlobe.rhoSinThetaPrime(Latitude, Height); - var RhoCosThetaPrime = CAAGlobe.rhoCosThetaPrime(Latitude, Height); - var theta = CAASidereal.apparentGreenwichSiderealTime(JD); - Delta = CT.d2R(Delta); - var cosDelta = Math.cos(Delta); - var pi = Math.asin(GFX.g_AAParallax_C1 / Distance); - var H = CT.h2R(theta - Longitude / 15 - Alpha); - var cosH = Math.cos(H); - var sinH = Math.sin(H); - var DeltaTopocentric = new COR(); - DeltaTopocentric.x = CT.r2H(-pi * RhoCosThetaPrime * sinH / cosDelta); - DeltaTopocentric.y = CT.r2D(-pi * (RhoSinThetaPrime * cosDelta - RhoCosThetaPrime * cosH * Math.sin(Delta))); - return DeltaTopocentric; - }; - CAAParallax.equatorial2Topocentric = function (Alpha, Delta, Distance, Longitude, Latitude, Height, JD) { - var RhoSinThetaPrime = CAAGlobe.rhoSinThetaPrime(Latitude, Height); - var RhoCosThetaPrime = CAAGlobe.rhoCosThetaPrime(Latitude, Height); - var theta = CAASidereal.apparentGreenwichSiderealTime(JD); - Delta = CT.d2R(Delta); - var cosDelta = Math.cos(Delta); - var pi = Math.asin(GFX.g_AAParallax_C1 / Distance); - var sinpi = Math.sin(pi); - var H = CT.h2R(theta - Longitude / 15 - Alpha); - var cosH = Math.cos(H); - var sinH = Math.sin(H); - var DeltaAlpha = Math.atan2(-RhoCosThetaPrime * sinpi * sinH, cosDelta - RhoCosThetaPrime * sinpi * cosH); - var Topocentric = new COR(); - Topocentric.x = CT.m24(Alpha + CT.r2H(DeltaAlpha)); - Topocentric.y = CT.r2D(Math.atan2((Math.sin(Delta) - RhoSinThetaPrime * sinpi) * Math.cos(DeltaAlpha), cosDelta - RhoCosThetaPrime * sinpi * cosH)); - return Topocentric; - }; - CAAParallax.ecliptic2Topocentric = function (Lambda, Beta, Semidiameter, Distance, Epsilon, Longitude, Latitude, Height, JD) { - var S = CAAGlobe.rhoSinThetaPrime(Latitude, Height); - var C = CAAGlobe.rhoCosThetaPrime(Latitude, Height); - Lambda = CT.d2R(Lambda); - Beta = CT.d2R(Beta); - Epsilon = CT.d2R(Epsilon); - Longitude = CT.d2R(Longitude); - Latitude = CT.d2R(Latitude); - Semidiameter = CT.d2R(Semidiameter); - var sine = Math.sin(Epsilon); - var cose = Math.cos(Epsilon); - var cosBeta = Math.cos(Beta); - var sinBeta = Math.sin(Beta); - var theta = CAASidereal.apparentGreenwichSiderealTime(JD); - theta = CT.h2R(theta); - var sintheta = Math.sin(theta); - var pi = Math.asin(GFX.g_AAParallax_C1 / Distance); - var sinpi = Math.sin(pi); - var N = Math.cos(Lambda) * cosBeta - C * sinpi * Math.cos(theta); - var Topocentric = new CAATopocentricEclipticDetails(); - Topocentric.lambda = Math.atan2(Math.sin(Lambda) * cosBeta - sinpi * (S * sine + C * cose * sintheta), N); - var cosTopocentricLambda = Math.cos(Topocentric.lambda); - Topocentric.beta = Math.atan(cosTopocentricLambda * (sinBeta - sinpi * (S * cose - C * sine * sintheta)) / N); - Topocentric.semidiameter = Math.asin(cosTopocentricLambda * Math.cos(Topocentric.beta) * Math.sin(Semidiameter) / N); - Topocentric.semidiameter = CT.r2D(Topocentric.semidiameter); - Topocentric.lambda = CT.m360(CT.r2D(Topocentric.lambda)); - Topocentric.beta = CT.r2D(Topocentric.beta); - return Topocentric; - }; - CAAParallax.parallaxToDistance = function (Parallax) { - return GFX.g_AAParallax_C1 / Math.sin(CT.d2R(Parallax)); - }; - CAAParallax.distanceToParallax = function (Distance) { - var pi = Math.asin(GFX.g_AAParallax_C1 / Distance); - return CT.r2D(pi); - }; - var CAAParallax$ = { - - }; - - - // CAAPhysicalJupiterDetails - - function CAAPhysicalJupiterDetails() { - this.DE = 0; - this.DS = 0; - this.geometricw1 = 0; - this.geometricw2 = 0; - this.apparentw1 = 0; - this.apparentw2 = 0; - this.p = 0; - this.DE = 0; - this.DS = 0; - this.geometricw1 = 0; - this.geometricw2 = 0; - this.apparentw1 = 0; - this.apparentw2 = 0; - this.p = 0; - } - var CAAPhysicalJupiterDetails$ = { - - }; - - - // CAAPhysicalJupiter - - function CAAPhysicalJupiter() { - } - CAAPhysicalJupiter.calculate = function (JD) { - var details = new CAAPhysicalJupiterDetails(); - var d = JD - 2433282.5; - var T1 = d / 36525; - var alpha0 = 268 + 0.1061 * T1; - var alpha0rad = CT.d2R(alpha0); - var delta0 = 64.5 - 0.0164 * T1; - var delta0rad = CT.d2R(delta0); - var W1 = CT.m360(17.71 + 877.90003539 * d); - var W2 = CT.m360(16.838 + 870.27003539 * d); - var l0 = CAAEarth.eclipticLongitude(JD); - var l0rad = CT.d2R(l0); - var b0 = CAAEarth.eclipticLatitude(JD); - var b0rad = CT.d2R(b0); - var R = CAAEarth.radiusVector(JD); - var l = CAAJupiter.eclipticLongitude(JD); - var lrad = CT.d2R(l); - var b = CAAJupiter.eclipticLatitude(JD); - var brad = CT.d2R(b); - var r = CAAJupiter.radiusVector(JD); - var x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); - var y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); - var z = r * Math.sin(brad) - R * Math.sin(b0rad); - var DELTA = Math.sqrt(x * x + y * y + z * z); - l -= 0.01299 * DELTA / (r * r); - lrad = CT.d2R(l); - x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); - y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); - z = r * Math.sin(brad) - R * Math.sin(b0rad); - DELTA = Math.sqrt(x * x + y * y + z * z); - var e0 = CAANutation.meanObliquityOfEcliptic(JD); - var e0rad = CT.d2R(e0); - var alphas = Math.atan2(Math.cos(e0rad) * Math.sin(lrad) - Math.sin(e0rad) * Math.tan(brad), Math.cos(lrad)); - var deltas = Math.asin(Math.cos(e0rad) * Math.sin(brad) + Math.sin(e0rad) * Math.cos(brad) * Math.sin(lrad)); - details.DS = CT.r2D(Math.asin(-Math.sin(delta0rad) * Math.sin(deltas) - Math.cos(delta0rad) * Math.cos(deltas) * Math.cos(alpha0rad - alphas))); - var u = y * Math.cos(e0rad) - z * Math.sin(e0rad); - var v = y * Math.sin(e0rad) + z * Math.cos(e0rad); - var alpharad = Math.atan2(u, x); - var alpha = CT.r2D(alpharad); - var deltarad = Math.atan2(v, Math.sqrt(x * x + u * u)); - var delta = CT.r2D(deltarad); - var xi = Math.atan2(Math.sin(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad) - Math.sin(deltarad) * Math.cos(delta0rad), Math.cos(deltarad) * Math.sin(alpha0rad - alpharad)); - details.DE = CT.r2D(Math.asin(-Math.sin(delta0rad) * Math.sin(deltarad) - Math.cos(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad))); - details.geometricw1 = CT.m360(W1 - CT.r2D(xi) - 5.07033 * DELTA); - details.geometricw2 = CT.m360(W2 - CT.r2D(xi) - 5.02626 * DELTA); - var C = 57.2958 * (2 * r * DELTA + R * R - r * r - DELTA * DELTA) / (4 * r * DELTA); - if (Math.sin(lrad - l0rad) > 0) { - details.apparentw1 = CT.m360(details.geometricw1 + C); - details.apparentw2 = CT.m360(details.geometricw2 + C); - } - else { - details.apparentw1 = CT.m360(details.geometricw1 - C); - details.apparentw2 = CT.m360(details.geometricw2 - C); - } - var NutationInLongitude = CAANutation.nutationInLongitude(JD); - var NutationInObliquity = CAANutation.nutationInObliquity(JD); - e0 += NutationInObliquity / 3600; - e0rad = CT.d2R(e0); - alpha += 0.005693 * (Math.cos(alpharad) * Math.cos(l0rad) * Math.cos(e0rad) + Math.sin(alpharad) * Math.sin(l0rad)) / Math.cos(deltarad); - alpha = CT.m360(alpha); - alpharad = CT.d2R(alpha); - delta += 0.005693 * (Math.cos(l0rad) * Math.cos(e0rad) * (Math.tan(e0rad) * Math.cos(deltarad) - Math.sin(alpharad) * Math.sin(deltarad)) + Math.cos(alpharad) * Math.sin(deltarad) * Math.sin(l0rad)); - deltarad = CT.d2R(delta); - var NutationRA = CAANutation.nutationInRightAscension(alpha / 15, delta, e0, NutationInLongitude, NutationInObliquity); - var alphadash = alpha + NutationRA / 3600; - var alphadashrad = CT.d2R(alphadash); - var NutationDec = CAANutation.nutationInDeclination(alpha / 15, delta, e0, NutationInLongitude, NutationInObliquity); - var deltadash = delta + NutationDec / 3600; - var deltadashrad = CT.d2R(deltadash); - NutationRA = CAANutation.nutationInRightAscension(alpha0 / 15, delta0, e0, NutationInLongitude, NutationInObliquity); - var alpha0dash = alpha0 + NutationRA / 3600; - var alpha0dashrad = CT.d2R(alpha0dash); - NutationDec = CAANutation.nutationInDeclination(alpha0 / 15, delta0, e0, NutationInLongitude, NutationInObliquity); - var delta0dash = delta0 + NutationDec / 3600; - var delta0dashrad = CT.d2R(delta0dash); - details.p = CT.m360(CT.r2D(Math.atan2(Math.cos(delta0dashrad) * Math.sin(alpha0dashrad - alphadashrad), Math.sin(delta0dashrad) * Math.cos(deltadashrad) - Math.cos(delta0dashrad) * Math.sin(deltadashrad) * Math.cos(alpha0dashrad - alphadashrad)))); - return details; - }; - var CAAPhysicalJupiter$ = { - - }; - - - // CAAPhysicalMarsDetails - - function CAAPhysicalMarsDetails() { - this.DE = 0; - this.DS = 0; - this.w = 0; - this.p = 0; - this.x = 0; - this.k = 0; - this.q = 0; - this.d = 0; - this.DE = 0; - this.DS = 0; - this.w = 0; - this.p = 0; - this.x = 0; - this.k = 0; - this.q = 0; - this.d = 0; - } - var CAAPhysicalMarsDetails$ = { - - }; - - - // CAAPhysicalMars - - function CAAPhysicalMars() { - } - CAAPhysicalMars.calculate = function (JD) { - var details = new CAAPhysicalMarsDetails(); - var T = (JD - 2451545) / 36525; - var Lambda0 = 352.9065 + 1.1733 * T; - var Lambda0rad = CT.d2R(Lambda0); - var Beta0 = 63.2818 - 0.00394 * T; - var Beta0rad = CT.d2R(Beta0); - var l0 = CAAEarth.eclipticLongitude(JD); - var l0rad = CT.d2R(l0); - var b0 = CAAEarth.eclipticLatitude(JD); - var b0rad = CT.d2R(b0); - var R = CAAEarth.radiusVector(JD); - var PreviousLightTravelTime = 0; - var LightTravelTime = 0; - var x = 0; - var y = 0; - var z = 0; - var bIterate = true; - var DELTA = 0; - var l = 0; - var lrad = 0; - var b = 0; - var brad = 0; - var r = 0; - while (bIterate) { - var JD2 = JD - LightTravelTime; - l = CAAMars.eclipticLongitude(JD2); - lrad = CT.d2R(l); - b = CAAMars.eclipticLatitude(JD2); - brad = CT.d2R(b); - r = CAAMars.radiusVector(JD2); - x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); - y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); - z = r * Math.sin(brad) - R * Math.sin(b0rad); - DELTA = Math.sqrt(x * x + y * y + z * z); - LightTravelTime = ELL.distanceToLightTime(DELTA); - bIterate = (Math.abs(LightTravelTime - PreviousLightTravelTime) > 2E-06); - if (bIterate) { - PreviousLightTravelTime = LightTravelTime; - } - } - var lambdarad = Math.atan2(y, x); - var lambda = CT.r2D(lambdarad); - var betarad = Math.atan2(z, Math.sqrt(x * x + y * y)); - var beta = CT.r2D(betarad); - details.DE = CT.r2D(Math.asin(-Math.sin(Beta0rad) * Math.sin(betarad) - Math.cos(Beta0rad) * Math.cos(betarad) * Math.cos(Lambda0rad - lambdarad))); - var N = 49.5581 + 0.7721 * T; - var Nrad = CT.d2R(N); - var ldash = l - 0.00697 / r; - var ldashrad = CT.d2R(ldash); - var bdash = b - 0.000225 * (Math.cos(lrad - Nrad) / r); - var bdashrad = CT.d2R(bdash); - details.DS = CT.r2D(Math.asin(-Math.sin(Beta0rad) * Math.sin(bdashrad) - Math.cos(Beta0rad) * Math.cos(bdashrad) * Math.cos(Lambda0rad - ldashrad))); - var W = CT.m360(11.504 + 350.89200025 * (JD - LightTravelTime - 2433282.5)); - var e0 = CAANutation.meanObliquityOfEcliptic(JD); - var e0rad = CT.d2R(e0); - var PoleEquatorial = CT.ec2Eq(Lambda0, Beta0, e0); - var alpha0rad = CT.h2R(PoleEquatorial.x); - var delta0rad = CT.d2R(PoleEquatorial.y); - var u = y * Math.cos(e0rad) - z * Math.sin(e0rad); - var v = y * Math.sin(e0rad) + z * Math.cos(e0rad); - var alpharad = Math.atan2(u, x); - var alpha = CT.r2H(alpharad); - var deltarad = Math.atan2(v, Math.sqrt(x * x + u * u)); - var delta = CT.r2D(deltarad); - var xi = Math.atan2(Math.sin(delta0rad) * Math.cos(deltarad) * Math.cos(alpha0rad - alpharad) - Math.sin(deltarad) * Math.cos(delta0rad), Math.cos(deltarad) * Math.sin(alpha0rad - alpharad)); - details.w = CT.m360(W - CT.r2D(xi)); - var NutationInLongitude = CAANutation.nutationInLongitude(JD); - var NutationInObliquity = CAANutation.nutationInObliquity(JD); - lambda += 0.005693 * Math.cos(l0rad - lambdarad) / Math.cos(betarad); - beta += 0.005693 * Math.sin(l0rad - lambdarad) * Math.sin(betarad); - Lambda0 += NutationInLongitude / 3600; - Lambda0rad = CT.d2R(Lambda0); - lambda += NutationInLongitude / 3600; - lambdarad = CT.d2R(lambda); - e0 += NutationInObliquity / 3600; - e0rad = CT.d2R(e0rad); - var ApparentPoleEquatorial = CT.ec2Eq(Lambda0, Beta0, e0); - var alpha0dash = CT.h2R(ApparentPoleEquatorial.x); - var delta0dash = CT.d2R(ApparentPoleEquatorial.y); - var ApparentMars = CT.ec2Eq(lambda, beta, e0); - var alphadash = CT.h2R(ApparentMars.x); - var deltadash = CT.d2R(ApparentMars.y); - details.p = CT.m360(CT.r2D(Math.atan2(Math.cos(delta0dash) * Math.sin(alpha0dash - alphadash), Math.sin(delta0dash) * Math.cos(deltadash) - Math.cos(delta0dash) * Math.sin(deltadash) * Math.cos(alpha0dash - alphadash)))); - var SunLambda = CAASun.geometricEclipticLongitude(JD); - var SunBeta = CAASun.geometricEclipticLatitude(JD); - var SunEquatorial = CT.ec2Eq(SunLambda, SunBeta, e0); - details.x = MIFR.positionAngle(SunEquatorial.x, SunEquatorial.y, alpha, delta); - details.d = 9.36 / DELTA; - details.k = IFR.illuminatedFraction2(r, R, DELTA); - details.q = (1 - details.k) * details.d; - return details; - }; - var CAAPhysicalMars$ = { - - }; - - - // CAAPhysicalSunDetails - - function CAAPhysicalSunDetails() { - this.p = 0; - this.b0 = 0; - this.l0 = 0; - this.p = 0; - this.b0 = 0; - this.l0 = 0; - } - var CAAPhysicalSunDetails$ = { - - }; - - - // CAAPhysicalSun - - function CAAPhysicalSun() { - } - CAAPhysicalSun.calculate = function (JD) { - var theta = CT.m360((JD - 2398220) * 360 / 25.38); - var I = 7.25; - var K = 73.6667 + 1.3958333 * (JD - 2396758) / 36525; - var L = CAAEarth.eclipticLongitude(JD); - var R = CAAEarth.radiusVector(JD); - var SunLong = L + 180 - CT.dmS2D(0, 0, 20.4898 / R); - var SunLongDash = SunLong + CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)); - var epsilon = CAANutation.trueObliquityOfEcliptic(JD); - epsilon = CT.d2R(epsilon); - SunLong = CT.d2R(SunLong); - SunLongDash = CT.d2R(SunLongDash); - K = CT.d2R(K); - I = CT.d2R(I); - theta = CT.d2R(theta); - var x = Math.atan(-Math.cos(SunLong) * Math.tan(epsilon)); - var y = Math.atan(-Math.cos(SunLong - K) * Math.tan(I)); - var details = new CAAPhysicalSunDetails(); - details.p = CT.r2D(x + y); - details.b0 = CT.r2D(Math.asin(Math.sin(SunLong - K) * Math.sin(I))); - var eta = Math.atan(Math.tan(SunLong - K) * Math.cos(I)); - details.l0 = CT.m360(CT.r2D(eta - theta)); - return details; - }; - CAAPhysicalSun.timeOfStartOfRotation = function (C) { - var JED = 2398140.227 + 27.2752316 * C; - var M = CT.m360(281.96 + 26.882476 * C); - M = CT.d2R(M); - JED += (0.1454 * Math.sin(M) - 0.0085 * Math.sin(2 * M) - 0.0141 * Math.cos(2 * M)); - return JED; - }; - var CAAPhysicalSun$ = { - - }; - - - // CAAPluto - - function CAAPluto() { - } - CAAPluto.eclipticLongitude = function (JD) { - var T = (JD - 2451545) / 36525; - var J = 34.35 + 3034.9057 * T; - var S = 50.08 + 1222.1138 * T; - var P = 238.96 + 144.96 * T; - var L = 0; - var nPlutoCoefficients = GFX.g_PlutoArgumentCoefficients.length; - for (var i = 0; i < nPlutoCoefficients; i++) { - var Alpha = GFX.g_PlutoArgumentCoefficients[i].j * J + GFX.g_PlutoArgumentCoefficients[i].s * S + GFX.g_PlutoArgumentCoefficients[i].p * P; - Alpha = CT.d2R(Alpha); - L += ((GFX.g_PlutoLongitudeCoefficients[i].a * Math.sin(Alpha)) + (GFX.g_PlutoLongitudeCoefficients[i].b * Math.cos(Alpha))); - } - L = L / 1000000; - L += (238.958116 + 144.96 * T); - L = CT.m360(L); - return L; - }; - CAAPluto.eclipticLatitude = function (JD) { - var T = (JD - 2451545) / 36525; - var J = 34.35 + 3034.9057 * T; - var S = 50.08 + 1222.1138 * T; - var P = 238.96 + 144.96 * T; - var L = 0; - var nPlutoCoefficients = GFX.g_PlutoArgumentCoefficients.length; - for (var i = 0; i < nPlutoCoefficients; i++) { - var Alpha = GFX.g_PlutoArgumentCoefficients[i].j * J + GFX.g_PlutoArgumentCoefficients[i].s * S + GFX.g_PlutoArgumentCoefficients[i].p * P; - Alpha = CT.d2R(Alpha); - L += ((GFX.g_PlutoLatitudeCoefficients[i].a * Math.sin(Alpha)) + (GFX.g_PlutoLatitudeCoefficients[i].b * Math.cos(Alpha))); - } - L = L / 1000000; - L += -3.908239; - return L; - }; - CAAPluto.radiusVector = function (JD) { - var T = (JD - 2451545) / 36525; - var J = 34.35 + 3034.9057 * T; - var S = 50.08 + 1222.1138 * T; - var P = 238.96 + 144.96 * T; - var R = 0; - var nPlutoCoefficients = GFX.g_PlutoArgumentCoefficients.length; - for (var i = 0; i < nPlutoCoefficients; i++) { - var Alpha = GFX.g_PlutoArgumentCoefficients[i].j * J + GFX.g_PlutoArgumentCoefficients[i].s * S + GFX.g_PlutoArgumentCoefficients[i].p * P; - Alpha = CT.d2R(Alpha); - R += ((GFX.g_PlutoRadiusCoefficients[i].a * Math.sin(Alpha)) + (GFX.g_PlutoRadiusCoefficients[i].b * Math.cos(Alpha))); - } - R = R / 10000000; - R += 40.7241346; - return R; - }; - var CAAPluto$ = { - - }; - - - // PlutoCoefficient1 - - function PlutoCoefficient1(j, s, p) { - this.j = 0; - this.s = 0; - this.p = 0; - this.j = j; - this.s = s; - this.p = p; - } - var PlutoCoefficient1$ = { - - }; - - - // PlutoCoefficient2 - - function PlutoCoefficient2(a, b) { - this.a = 0; - this.b = 0; - this.a = a; - this.b = b; - } - var PlutoCoefficient2$ = { - - }; - - - // CAAPrecession - - function CAAPrecession() { - } - CAAPrecession.precessEquatorial = function (Alpha, Delta, JD0, JD) { - var T = (JD0 - 2451545) / 36525; - var Tsquared = T * T; - var t = (JD - JD0) / 36525; - var tsquared = t * t; - var tcubed = tsquared * t; - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - var sigma = (2306.2181 + 1.39656 * T - 0.000139 * Tsquared) * t + (0.30188 - 3.44E-05 * T) * tsquared + 0.017988 * tcubed; - sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); - var zeta = (2306.2181 + 1.39656 * T - 0.000138 * Tsquared) * t + (1.09468 + 6.6E-05 * T) * tsquared + 0.018203 * tcubed; - zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); - var phi = (2004.3109 - 0.8533 * T - 0.000217 * Tsquared) * t - (0.42665 + 0.000217 * T) * tsquared - 0.041833 * tcubed; - phi = CT.d2R(CT.dmS2D(0, 0, phi)); - var A = Math.cos(Delta) * Math.sin(Alpha + sigma); - var B = Math.cos(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) - Math.sin(phi) * Math.sin(Delta); - var C = Math.sin(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) + Math.cos(phi) * Math.sin(Delta); - var vvalue = new COR(); - vvalue.x = CT.r2H(Math.atan2(A, B) + zeta); - if (vvalue.x < 0) { - vvalue.x += 24; - } - vvalue.y = CT.r2D(Math.asin(C)); - return vvalue; - }; - CAAPrecession.precessEquatorialFK4 = function (Alpha, Delta, JD0, JD) { - var T = (JD0 - 2415020.3135) / 36524.2199; - var t = (JD - JD0) / 36524.2199; - var tsquared = t * t; - var tcubed = tsquared * t; - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - var sigma = (2304.25 + 1.396 * T) * t + 0.302 * tsquared + 0.018 * tcubed; - sigma = CT.d2R(CT.dmS2D(0, 0, sigma)); - var zeta = 0.791 * tsquared + 0.001 * tcubed; - zeta = CT.d2R(CT.dmS2D(0, 0, zeta)); - zeta += sigma; - var phi = (2004.682 - 0.853 * T) * t - 0.426 * tsquared - 0.042 * tcubed; - phi = CT.d2R(CT.dmS2D(0, 0, phi)); - var A = Math.cos(Delta) * Math.sin(Alpha + sigma); - var B = Math.cos(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) - Math.sin(phi) * Math.sin(Delta); - var C = Math.sin(phi) * Math.cos(Delta) * Math.cos(Alpha + sigma) + Math.cos(phi) * Math.sin(Delta); - var vvalue = new COR(); - vvalue.x = CT.r2H(Math.atan2(A, B) + zeta); - if (vvalue.x < 0) { - vvalue.x += 24; - } - vvalue.y = CT.r2D(Math.asin(C)); - return vvalue; - }; - CAAPrecession.precessEcliptic = function (Lambda, Beta, JD0, JD) { - var T = (JD0 - 2451545) / 36525; - var Tsquared = T * T; - var t = (JD - JD0) / 36525; - var tsquared = t * t; - var tcubed = tsquared * t; - Lambda = CT.d2R(Lambda); - Beta = CT.d2R(Beta); - var eta = (47.0029 - 0.06603 * T + 0.000598 * Tsquared) * t + (-0.03302 + 0.000598 * T) * tsquared + 6E-05 * tcubed; - eta = CT.d2R(CT.dmS2D(0, 0, eta)); - var pi = 174.876384 * 3600 + 3289.4789 * T + 0.60622 * Tsquared - (869.8089 + 0.50491 * T) * t + 0.03536 * tsquared; - pi = CT.d2R(CT.dmS2D(0, 0, pi)); - var p = (5029.0966 + 2.22226 * T - 4.2E-05 * Tsquared) * t + (1.11113 - 4.2E-05 * T) * tsquared - 6E-06 * tcubed; - p = CT.d2R(CT.dmS2D(0, 0, p)); - var A = Math.cos(eta) * Math.cos(Beta) * Math.sin(pi - Lambda) - Math.sin(eta) * Math.sin(Beta); - var B = Math.cos(Beta) * Math.cos(pi - Lambda); - var C = Math.cos(eta) * Math.sin(Beta) + Math.sin(eta) * Math.cos(Beta) * Math.sin(pi - Lambda); - var vvalue = new COR(); - vvalue.x = CT.r2D(p + pi - Math.atan2(A, B)); - if (vvalue.x < 0) { - vvalue.x += 360; - } - vvalue.y = CT.r2D(Math.asin(C)); - return vvalue; - }; - CAAPrecession.equatorialPMToEcliptic = function (Alpha, Delta, Beta, PMAlpha, PMDelta, Epsilon) { - Epsilon = CT.d2R(Epsilon); - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - Beta = CT.d2R(Beta); - var cosb = Math.cos(Beta); - var sinEpsilon = Math.sin(Epsilon); - var vvalue = new COR(); - vvalue.x = (PMDelta * sinEpsilon * Math.cos(Alpha) + PMAlpha * Math.cos(Delta) * (Math.cos(Epsilon) * Math.cos(Delta) + sinEpsilon * Math.sin(Delta) * Math.sin(Alpha))) / (cosb * cosb); - vvalue.y = (PMDelta * (Math.cos(Epsilon) * Math.cos(Delta) + sinEpsilon * Math.sin(Delta) * Math.sin(Alpha)) - PMAlpha * sinEpsilon * Math.cos(Alpha) * Math.cos(Delta)) / cosb; - return vvalue; - }; - CAAPrecession.adjustPositionUsingUniformProperMotion = function (t, Alpha, Delta, PMAlpha, PMDelta) { - var vvalue = new COR(); - vvalue.x = Alpha + (PMAlpha * t / 3600); - vvalue.y = Delta + (PMDelta * t / 3600); - return vvalue; - }; - CAAPrecession.adjustPositionUsingMotionInSpace = function (r, DeltaR, t, Alpha, Delta, PMAlpha, PMDelta) { - DeltaR /= 977792; - PMAlpha /= 13751; - PMDelta /= 206265; - Alpha = CT.h2R(Alpha); - Delta = CT.d2R(Delta); - var x = r * Math.cos(Delta) * Math.cos(Alpha); - var y = r * Math.cos(Delta) * Math.sin(Alpha); - var z = r * Math.sin(Delta); - var DeltaX = x / r * DeltaR - z * PMDelta * Math.cos(Alpha) - y * PMAlpha; - var DeltaY = y / r * DeltaR - z * PMDelta * Math.sin(Alpha) + x * PMAlpha; - var DeltaZ = z / r * DeltaR + r * PMDelta * Math.cos(Delta); - x += t * DeltaX; - y += t * DeltaY; - z += t * DeltaZ; - var vvalue = new COR(); - vvalue.x = CT.r2H(Math.atan2(y, x)); - if (vvalue.x < 0) { - vvalue.x += 24; - } - vvalue.y = CT.r2D(Math.atan2(z, Math.sqrt(x * x + y * y))); - return vvalue; - }; - var CAAPrecession$ = { - - }; - - - // CAARiseTransitSetDetails - - function CAARiseTransitSetDetails() { - this.bValid = false; - this.rise = 0; - this.transit = 0; - this.set = 0; - this.bValid = false; - this.rise = 0; - this.transit = 0; - this.set = 0; - } - var CAARiseTransitSetDetails$ = { - - }; - - - // CAARiseTransitSet - - function CAARiseTransitSet() { - } - CAARiseTransitSet.rise = function (JD, Alpha1, Delta1, Alpha2, Delta2, Alpha3, Delta3, Longitude, Latitude, h0) { - var details = new CAARiseTransitSetDetails(); - details.bValid = false; - var theta0 = CAASidereal.apparentGreenwichSiderealTime(JD); - theta0 *= 15; - var deltaT = DYT.deltaT(JD); - var Delta2Rad = CT.d2R(Delta2); - var LatitudeRad = CT.d2R(Latitude); - var h0Rad = CT.d2R(h0); - var cosH0 = (Math.sin(h0Rad) - Math.sin(LatitudeRad) * Math.sin(Delta2Rad)) / (Math.cos(LatitudeRad) * Math.cos(Delta2Rad)); - if ((cosH0 > 1) || (cosH0 < -1)) { - return details; - } - var H0 = Math.acos(cosH0); - H0 = CT.r2D(H0); - var M0 = (Alpha2 * 15 + Longitude - theta0) / 360; - var M1 = M0 - H0 / 360; - var M2 = M0 + H0 / 360; - if (M0 > 1) { - M0 -= 1; - } - else if (M0 < 0) { - M0 += 1; - } - if (M1 > 1) { - M1 -= 1; - } - else if (M1 < 0) { - M1 += 1; - } - if (M2 > 1) { - M2 -= 1; - } - else if (M2 < 0) { - M2 += 1; - } - for (var i = 0; i < 2; i++) { - var theta1 = theta0 + 360.985647 * M1; - theta1 = CT.m360(theta1); - var n = M1 + deltaT / 86400; - var Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); - var Delta = INTP.interpolate(n, Delta1, Delta2, Delta3); - var H = theta1 - Longitude - Alpha * 15; - var Horizontal = CT.eq2H(H / 15, Delta, Latitude); - var DeltaM = (Horizontal.y - h0) / (360 * Math.cos(CT.d2R(Delta)) * Math.cos(LatitudeRad) * Math.sin(CT.d2R(H))); - M1 += DeltaM; - theta1 = theta0 + 360.985647 * M0; - theta1 = CT.m360(theta1); - n = M0 + deltaT / 86400; - Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); - H = theta1 - Longitude - Alpha * 15; - if (H < -180) { - H += 360; - } - DeltaM = -H / 360; - M0 += DeltaM; - theta1 = theta0 + 360.985647 * M2; - theta1 = CT.m360(theta1); - n = M2 + deltaT / 86400; - Alpha = INTP.interpolate(n, Alpha1, Alpha2, Alpha3); - Delta = INTP.interpolate(n, Delta1, Delta2, Delta3); - H = theta1 - Longitude - Alpha * 15; - Horizontal = CT.eq2H(H / 15, Delta, Latitude); - DeltaM = (Horizontal.y - h0) / (360 * Math.cos(CT.d2R(Delta)) * Math.cos(LatitudeRad) * Math.sin(CT.d2R(H))); - M2 += DeltaM; - } - details.bValid = true; - details.rise = M1 * 24; - details.set = M2 * 24; - details.transit = M0 * 24; - return details; - }; - var CAARiseTransitSet$ = { - - }; - - - // CAASaturn - - function CAASaturn() { - } - CAASaturn.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0SaturnCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0SaturnCoefficients[i].a * Math.cos(GFX.g_L0SaturnCoefficients[i].b + GFX.g_L0SaturnCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1SaturnCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1SaturnCoefficients[i].a * Math.cos(GFX.g_L1SaturnCoefficients[i].b + GFX.g_L1SaturnCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2SaturnCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2SaturnCoefficients[i].a * Math.cos(GFX.g_L2SaturnCoefficients[i].b + GFX.g_L2SaturnCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3SaturnCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3SaturnCoefficients[i].a * Math.cos(GFX.g_L3SaturnCoefficients[i].b + GFX.g_L3SaturnCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4SaturnCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4SaturnCoefficients[i].a * Math.cos(GFX.g_L4SaturnCoefficients[i].b + GFX.g_L4SaturnCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5SaturnCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5SaturnCoefficients[i].a * Math.cos(GFX.g_L5SaturnCoefficients[i].b + GFX.g_L5SaturnCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAASaturn.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nB0Coefficients = GFX.g_B0SaturnCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0SaturnCoefficients[i].a * Math.cos(GFX.g_B0SaturnCoefficients[i].b + GFX.g_B0SaturnCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1SaturnCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1SaturnCoefficients[i].a * Math.cos(GFX.g_B1SaturnCoefficients[i].b + GFX.g_B1SaturnCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2SaturnCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2SaturnCoefficients[i].a * Math.cos(GFX.g_B2SaturnCoefficients[i].b + GFX.g_B2SaturnCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3SaturnCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3SaturnCoefficients[i].a * Math.cos(GFX.g_B3SaturnCoefficients[i].b + GFX.g_B3SaturnCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4SaturnCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4SaturnCoefficients[i].a * Math.cos(GFX.g_B4SaturnCoefficients[i].b + GFX.g_B4SaturnCoefficients[i].c * rho); - } - var nB5Coefficients = GFX.g_B5SaturnCoefficients.length; - var B5 = 0; - for (i = 0; i < nB5Coefficients; i++) { - B5 += GFX.g_B5SaturnCoefficients[i].a * Math.cos(GFX.g_B5SaturnCoefficients[i].b + GFX.g_B5SaturnCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4 + B5 * rho5) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAASaturn.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nR0Coefficients = GFX.g_R0SaturnCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0SaturnCoefficients[i].a * Math.cos(GFX.g_R0SaturnCoefficients[i].b + GFX.g_R0SaturnCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1SaturnCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1SaturnCoefficients[i].a * Math.cos(GFX.g_R1SaturnCoefficients[i].b + GFX.g_R1SaturnCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2SaturnCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2SaturnCoefficients[i].a * Math.cos(GFX.g_R2SaturnCoefficients[i].b + GFX.g_R2SaturnCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3SaturnCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3SaturnCoefficients[i].a * Math.cos(GFX.g_R3SaturnCoefficients[i].b + GFX.g_R3SaturnCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4SaturnCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4SaturnCoefficients[i].a * Math.cos(GFX.g_R4SaturnCoefficients[i].b + GFX.g_R4SaturnCoefficients[i].c * rho); - } - var nR5Coefficients = GFX.g_R5SaturnCoefficients.length; - var R5 = 0; - for (i = 0; i < nR5Coefficients; i++) { - R5 += GFX.g_R5SaturnCoefficients[i].a * Math.cos(GFX.g_R5SaturnCoefficients[i].b + GFX.g_R5SaturnCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4 + R5 * rho5) / 100000000; - }; - var CAASaturn$ = { - - }; - - - // CAASaturnRingDetails - - function CAASaturnRingDetails() { - this.b = 0; - this.bdash = 0; - this.p = 0; - this.a = 0; - this.b = 0; - this.deltaU = 0; - this.b = 0; - this.bdash = 0; - this.p = 0; - this.a = 0; - this.b = 0; - this.deltaU = 0; - } - var CAASaturnRingDetails$ = { - - }; - - - // CAASaturnRings - - function CAASaturnRings() { - } - CAASaturnRings.calculate = function (JD) { - var details = new CAASaturnRingDetails(); - var T = (JD - 2451545) / 36525; - var T2 = T * T; - var i = 28.075216 - 0.012998 * T + 4E-06 * T2; - var irad = CT.d2R(i); - var omega = 169.50847 + 1.394681 * T + 0.000412 * T2; - var omegarad = CT.d2R(omega); - var l0 = CAAEarth.eclipticLongitude(JD); - var b0 = CAAEarth.eclipticLatitude(JD); - l0 += CAAFK5.correctionInLongitude(l0, b0, JD); - var l0rad = CT.d2R(l0); - b0 += CAAFK5.correctionInLatitude(l0, JD); - var b0rad = CT.d2R(b0); - var R = CAAEarth.radiusVector(JD); - var DELTA = 9; - var PreviousEarthLightTravelTime = 0; - var EarthLightTravelTime = ELL.distanceToLightTime(DELTA); - var JD1 = JD - EarthLightTravelTime; - var bIterate = true; - var x = 0; - var y = 0; - var z = 0; - var l = 0; - var b = 0; - var r = 0; - while (bIterate) { - l = CAASaturn.eclipticLongitude(JD1); - b = CAASaturn.eclipticLatitude(JD1); - l += CAAFK5.correctionInLongitude(l, b, JD1); - b += CAAFK5.correctionInLatitude(l, JD1); - var lrad = CT.d2R(l); - var brad = CT.d2R(b); - r = CAASaturn.radiusVector(JD1); - x = r * Math.cos(brad) * Math.cos(lrad) - R * Math.cos(l0rad); - y = r * Math.cos(brad) * Math.sin(lrad) - R * Math.sin(l0rad); - z = r * Math.sin(brad) - R * Math.sin(b0rad); - DELTA = Math.sqrt(x * x + y * y + z * z); - EarthLightTravelTime = ELL.distanceToLightTime(DELTA); - bIterate = (Math.abs(EarthLightTravelTime - PreviousEarthLightTravelTime) > 2E-06); - if (bIterate) { - JD1 = JD - EarthLightTravelTime; - PreviousEarthLightTravelTime = EarthLightTravelTime; - } - } - var lambda = Math.atan2(y, x); - var beta = Math.atan2(z, Math.sqrt(x * x + y * y)); - details.b = Math.asin(Math.sin(irad) * Math.cos(beta) * Math.sin(lambda - omegarad) - Math.cos(irad) * Math.sin(beta)); - details.a = 375.35 / DELTA; - details.b = details.a * Math.sin(Math.abs(details.b)); - details.b = CT.r2D(details.b); - var N = 113.6655 + 0.8771 * T; - var Nrad = CT.d2R(N); - var ldash = l - 0.01759 / r; - var ldashrad = CT.d2R(ldash); - var bdash = b - 0.000764 * Math.cos(ldashrad - Nrad) / r; - var bdashrad = CT.d2R(bdash); - details.bdash = CT.r2D(Math.asin(Math.sin(irad) * Math.cos(bdashrad) * Math.sin(ldashrad - omegarad) - Math.cos(irad) * Math.sin(bdashrad))); - var U1 = Math.atan2(Math.sin(irad) * Math.sin(bdashrad) + Math.cos(irad) * Math.cos(bdashrad) * Math.sin(ldashrad - omegarad), Math.cos(bdashrad) * Math.cos(ldashrad - omegarad)); - var U2 = Math.atan2(Math.sin(irad) * Math.sin(beta) + Math.cos(irad) * Math.cos(beta) * Math.sin(lambda - omegarad), Math.cos(beta) * Math.cos(lambda - omegarad)); - details.deltaU = CT.r2D(Math.abs(U1 - U2)); - var Obliquity = CAANutation.trueObliquityOfEcliptic(JD); - var NutationInLongitude = CAANutation.nutationInLongitude(JD); - var lambda0 = omega - 90; - var beta0 = 90 - i; - lambda += CT.d2R(0.005693 * Math.cos(l0rad - lambda) / Math.cos(beta)); - beta += CT.d2R(0.005693 * Math.sin(l0rad - lambda) * Math.sin(beta)); - lambda = CT.r2D(lambda); - lambda += NutationInLongitude / 3600; - lambda = CT.m360(lambda); - lambda0 += NutationInLongitude / 3600; - lambda0 = CT.m360(lambda0); - beta = CT.r2D(beta); - var GeocentricEclipticSaturn = CT.ec2Eq(lambda, beta, Obliquity); - var alpha = CT.h2R(GeocentricEclipticSaturn.x); - var delta = CT.d2R(GeocentricEclipticSaturn.y); - var GeocentricEclipticNorthPole = CT.ec2Eq(lambda0, beta0, Obliquity); - var alpha0 = CT.h2R(GeocentricEclipticNorthPole.x); - var delta0 = CT.d2R(GeocentricEclipticNorthPole.y); - details.p = CT.r2D(Math.atan2(Math.cos(delta0) * Math.sin(alpha0 - alpha), Math.sin(delta0) * Math.cos(delta) - Math.cos(delta0) * Math.sin(delta) * Math.cos(alpha0 - alpha))); - return details; - }; - var CAASaturnRings$ = { - - }; - - - // CAASidereal - - function CAASidereal() { - } - CAASidereal.meanGreenwichSiderealTime = function (JD) { - var date = new DT(); - date.setJD(JD, DT.afterPapalReformJD(JD)); - var D = date.get(); - var Year = ss.truncate(D[0]); - var Month = ss.truncate(D[1]); - var Day = ss.truncate(D[2]); - var Hour = ss.truncate(D[3]); - var Minute = ss.truncate(D[4]); - var Second = D[5]; - date.set(Year, Month, Day, 0, 0, 0, date.inGregorianCalendar()); - var JDMidnight = date.julian(); - var T = (JDMidnight - 2451545) / 36525; - var TSquared = T * T; - var TCubed = TSquared * T; - var Value = 100.46061837 + (36000.770053608 * T) + (0.000387933 * TSquared) - (TCubed / 38710000); - Value += (((Hour * 15) + (Minute * 0.25) + (Second * 0.00416666666666667)) * 1.00273790935); - Value = CT.d2H(Value); - return CT.m24(Value); - }; - CAASidereal.apparentGreenwichSiderealTime = function (JD) { - var MeanObliquity = CAANutation.meanObliquityOfEcliptic(JD); - var TrueObliquity = MeanObliquity + CAANutation.nutationInObliquity(JD) / 3600; - var NutationInLongitude = CAANutation.nutationInLongitude(JD); - var Value = CAASidereal.meanGreenwichSiderealTime(JD) + (NutationInLongitude * Math.cos(CT.d2R(TrueObliquity)) / 54000); - return CT.m24(Value); - }; - var CAASidereal$ = { - - }; - - - // CAAStellarMagnitudes - - function CAAStellarMagnitudes() { - } - CAAStellarMagnitudes.combinedMagnitude = function (m1, m2) { - var x = 0.4 * (m2 - m1); - return m2 - 2.5 * Util.log10(Math.pow(10, x) + 1); - }; - CAAStellarMagnitudes.combinedMagnitude2 = function (Magnitudes, pMagnitudes) { - var vvalue = 0; - for (var i = 0; i < Magnitudes; i++) { - vvalue += Math.pow(10, -0.4 * pMagnitudes[i]); - } - return -2.5 * Util.log10(vvalue); - }; - CAAStellarMagnitudes.brightnessRatio = function (m1, m2) { - var x = 0.4 * (m2 - m1); - return Math.pow(10, x); - }; - CAAStellarMagnitudes.magnitudeDifference = function (brightnessRatio) { - return 2.5 * Util.log10(brightnessRatio); - }; - var CAAStellarMagnitudes$ = { - - }; - - - // CAASun - - function CAASun() { - } - CAASun.geometricEclipticLongitude = function (JD) { - return CT.m360(CAAEarth.eclipticLongitude(JD) + 180); - }; - CAASun.geometricEclipticLatitude = function (JD) { - return -CAAEarth.eclipticLatitude(JD); - }; - CAASun.geometricEclipticLongitudeJ2000 = function (JD) { - return CT.m360(CAAEarth.eclipticLongitudeJ2000(JD) + 180); - }; - CAASun.geometricEclipticLatitudeJ2000 = function (JD) { - return -CAAEarth.eclipticLatitudeJ2000(JD); - }; - CAASun.geometricFK5EclipticLongitude = function (JD) { - var Longitude = CAASun.geometricEclipticLongitude(JD); - var Latitude = CAASun.geometricEclipticLatitude(JD); - Longitude += CAAFK5.correctionInLongitude(Longitude, Latitude, JD); - return Longitude; - }; - CAASun.geometricFK5EclipticLatitude = function (JD) { - var Longitude = CAASun.geometricEclipticLongitude(JD); - var Latitude = CAASun.geometricEclipticLatitude(JD); - var SunLatCorrection = CAAFK5.correctionInLatitude(Longitude, JD); - Latitude += SunLatCorrection; - return Latitude; - }; - CAASun.apparentEclipticLongitude = function (JD) { - var Longitude = CAASun.geometricFK5EclipticLongitude(JD); - Longitude += CT.dmS2D(0, 0, CAANutation.nutationInLongitude(JD)); - var R = CAAEarth.radiusVector(JD); - Longitude -= CT.dmS2D(0, 0, 20.4898 / R); - return Longitude; - }; - CAASun.apparentEclipticLatitude = function (JD) { - return CAASun.geometricFK5EclipticLatitude(JD); - }; - CAASun.eclipticRectangularCoordinatesMeanEquinox = function (JD) { - var Longitude = CT.d2R(CAASun.geometricFK5EclipticLongitude(JD)); - var Latitude = CT.d2R(CAASun.geometricFK5EclipticLatitude(JD)); - var R = CAAEarth.radiusVector(JD); - var epsilon = CT.d2R(CAANutation.meanObliquityOfEcliptic(JD)); - var vvalue = new C3D(); - vvalue.x = R * Math.cos(Latitude) * Math.cos(Longitude); - vvalue.y = R * (Math.cos(Latitude) * Math.sin(Longitude) * Math.cos(epsilon) - Math.sin(Latitude) * Math.sin(epsilon)); - vvalue.z = R * (Math.cos(Latitude) * Math.sin(Longitude) * Math.sin(epsilon) + Math.sin(Latitude) * Math.cos(epsilon)); - return vvalue; - }; - CAASun.eclipticRectangularCoordinatesJ2000 = function (JD) { - var Longitude = CAASun.geometricEclipticLongitudeJ2000(JD); - Longitude = CT.d2R(Longitude); - var Latitude = CAASun.geometricEclipticLatitudeJ2000(JD); - Latitude = CT.d2R(Latitude); - var R = CAAEarth.radiusVector(JD); - var vvalue = new C3D(); - var coslatitude = Math.cos(Latitude); - vvalue.x = R * coslatitude * Math.cos(Longitude); - vvalue.y = R * coslatitude * Math.sin(Longitude); - vvalue.z = R * Math.sin(Latitude); - return vvalue; - }; - CAASun.equatorialRectangularCoordinatesJ2000 = function (JD) { - var vvalue = CAASun.eclipticRectangularCoordinatesJ2000(JD); - vvalue = CAAFK5.convertVSOPToFK5J2000(vvalue); - return vvalue; - }; - CAASun.equatorialRectangularCoordinatesB1950 = function (JD) { - var vvalue = CAASun.eclipticRectangularCoordinatesJ2000(JD); - vvalue = CAAFK5.convertVSOPToFK5B1950(vvalue); - return vvalue; - }; - CAASun.equatorialRectangularCoordinatesAnyEquinox = function (JD, JDEquinox) { - var vvalue = CAASun.equatorialRectangularCoordinatesJ2000(JD); - vvalue = CAAFK5.convertVSOPToFK5AnyEquinox(vvalue, JDEquinox); - return vvalue; - }; - var CAASun$ = { - - }; - - - // CAAUranus - - function CAAUranus() { - } - CAAUranus.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nL0Coefficients = GFX.g_L0UranusCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0UranusCoefficients[i].a * Math.cos(GFX.g_L0UranusCoefficients[i].b + GFX.g_L0UranusCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1UranusCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1UranusCoefficients[i].a * Math.cos(GFX.g_L1UranusCoefficients[i].b + GFX.g_L1UranusCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2UranusCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2UranusCoefficients[i].a * Math.cos(GFX.g_L2UranusCoefficients[i].b + GFX.g_L2UranusCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3UranusCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3UranusCoefficients[i].a * Math.cos(GFX.g_L3UranusCoefficients[i].b + GFX.g_L3UranusCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4UranusCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4UranusCoefficients[i].a * Math.cos(GFX.g_L4UranusCoefficients[i].b + GFX.g_L4UranusCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAUranus.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0UranusCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0UranusCoefficients[i].a * Math.cos(GFX.g_B0UranusCoefficients[i].b + GFX.g_B0UranusCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1UranusCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1UranusCoefficients[i].a * Math.cos(GFX.g_B1UranusCoefficients[i].b + GFX.g_B1UranusCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2UranusCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2UranusCoefficients[i].a * Math.cos(GFX.g_B2UranusCoefficients[i].b + GFX.g_B2UranusCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3UranusCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3UranusCoefficients[i].a * Math.cos(GFX.g_B3UranusCoefficients[i].b + GFX.g_B3UranusCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4UranusCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4UranusCoefficients[i].a * Math.cos(GFX.g_B4UranusCoefficients[i].b + GFX.g_B4UranusCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAUranus.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nR0Coefficients = GFX.g_R0UranusCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0UranusCoefficients[i].a * Math.cos(GFX.g_R0UranusCoefficients[i].b + GFX.g_R0UranusCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1UranusCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1UranusCoefficients[i].a * Math.cos(GFX.g_R1UranusCoefficients[i].b + GFX.g_R1UranusCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2UranusCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2UranusCoefficients[i].a * Math.cos(GFX.g_R2UranusCoefficients[i].b + GFX.g_R2UranusCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3UranusCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3UranusCoefficients[i].a * Math.cos(GFX.g_R3UranusCoefficients[i].b + GFX.g_R3UranusCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4UranusCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4UranusCoefficients[i].a * Math.cos(GFX.g_R4UranusCoefficients[i].b + GFX.g_R4UranusCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; - }; - var CAAUranus$ = { - - }; - - - // CAAVenus - - function CAAVenus() { - } - CAAVenus.eclipticLongitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var rho5 = rho4 * rho; - var nL0Coefficients = GFX.g_L0VenusCoefficients.length; - var L0 = 0; - var i; - for (i = 0; i < nL0Coefficients; i++) { - L0 += GFX.g_L0VenusCoefficients[i].a * Math.cos(GFX.g_L0VenusCoefficients[i].b + GFX.g_L0VenusCoefficients[i].c * rho); - } - var nL1Coefficients = GFX.g_L1VenusCoefficients.length; - var L1 = 0; - for (i = 0; i < nL1Coefficients; i++) { - L1 += GFX.g_L1VenusCoefficients[i].a * Math.cos(GFX.g_L1VenusCoefficients[i].b + GFX.g_L1VenusCoefficients[i].c * rho); - } - var nL2Coefficients = GFX.g_L2VenusCoefficients.length; - var L2 = 0; - for (i = 0; i < nL2Coefficients; i++) { - L2 += GFX.g_L2VenusCoefficients[i].a * Math.cos(GFX.g_L2VenusCoefficients[i].b + GFX.g_L2VenusCoefficients[i].c * rho); - } - var nL3Coefficients = GFX.g_L3VenusCoefficients.length; - var L3 = 0; - for (i = 0; i < nL3Coefficients; i++) { - L3 += GFX.g_L3VenusCoefficients[i].a * Math.cos(GFX.g_L3VenusCoefficients[i].b + GFX.g_L3VenusCoefficients[i].c * rho); - } - var nL4Coefficients = GFX.g_L4VenusCoefficients.length; - var L4 = 0; - for (i = 0; i < nL4Coefficients; i++) { - L4 += GFX.g_L4VenusCoefficients[i].a * Math.cos(GFX.g_L4VenusCoefficients[i].b + GFX.g_L4VenusCoefficients[i].c * rho); - } - var nL5Coefficients = GFX.g_L5VenusCoefficients.length; - var L5 = 0; - for (i = 0; i < nL5Coefficients; i++) { - L5 += GFX.g_L5VenusCoefficients[i].a * Math.cos(GFX.g_L5VenusCoefficients[i].b + GFX.g_L5VenusCoefficients[i].c * rho); - } - var vvalue = (L0 + L1 * rho + L2 * rhosquared + L3 * rhocubed + L4 * rho4 + L5 * rho5) / 100000000; - vvalue = CT.m360(CT.r2D(vvalue)); - return vvalue; - }; - CAAVenus.eclipticLatitude = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nB0Coefficients = GFX.g_B0VenusCoefficients.length; - var B0 = 0; - var i; - for (i = 0; i < nB0Coefficients; i++) { - B0 += GFX.g_B0VenusCoefficients[i].a * Math.cos(GFX.g_B0VenusCoefficients[i].b + GFX.g_B0VenusCoefficients[i].c * rho); - } - var nB1Coefficients = GFX.g_B1VenusCoefficients.length; - var B1 = 0; - for (i = 0; i < nB1Coefficients; i++) { - B1 += GFX.g_B1VenusCoefficients[i].a * Math.cos(GFX.g_B1VenusCoefficients[i].b + GFX.g_B1VenusCoefficients[i].c * rho); - } - var nB2Coefficients = GFX.g_B2VenusCoefficients.length; - var B2 = 0; - for (i = 0; i < nB2Coefficients; i++) { - B2 += GFX.g_B2VenusCoefficients[i].a * Math.cos(GFX.g_B2VenusCoefficients[i].b + GFX.g_B2VenusCoefficients[i].c * rho); - } - var nB3Coefficients = GFX.g_B3VenusCoefficients.length; - var B3 = 0; - for (i = 0; i < nB3Coefficients; i++) { - B3 += GFX.g_B3VenusCoefficients[i].a * Math.cos(GFX.g_B3VenusCoefficients[i].b + GFX.g_B3VenusCoefficients[i].c * rho); - } - var nB4Coefficients = GFX.g_B4VenusCoefficients.length; - var B4 = 0; - for (i = 0; i < nB4Coefficients; i++) { - B4 += GFX.g_B4VenusCoefficients[i].a * Math.cos(GFX.g_B4VenusCoefficients[i].b + GFX.g_B4VenusCoefficients[i].c * rho); - } - var vvalue = (B0 + B1 * rho + B2 * rhosquared + B3 * rhocubed + B4 * rho4) / 100000000; - vvalue = CT.r2D(vvalue); - return vvalue; - }; - CAAVenus.radiusVector = function (JD) { - var rho = (JD - 2451545) / 365250; - var rhosquared = rho * rho; - var rhocubed = rhosquared * rho; - var rho4 = rhocubed * rho; - var nR0Coefficients = GFX.g_R0VenusCoefficients.length; - var R0 = 0; - var i; - for (i = 0; i < nR0Coefficients; i++) { - R0 += GFX.g_R0VenusCoefficients[i].a * Math.cos(GFX.g_R0VenusCoefficients[i].b + GFX.g_R0VenusCoefficients[i].c * rho); - } - var nR1Coefficients = GFX.g_R1VenusCoefficients.length; - var R1 = 0; - for (i = 0; i < nR1Coefficients; i++) { - R1 += GFX.g_R1VenusCoefficients[i].a * Math.cos(GFX.g_R1VenusCoefficients[i].b + GFX.g_R1VenusCoefficients[i].c * rho); - } - var nR2Coefficients = GFX.g_R2VenusCoefficients.length; - var R2 = 0; - for (i = 0; i < nR2Coefficients; i++) { - R2 += GFX.g_R2VenusCoefficients[i].a * Math.cos(GFX.g_R2VenusCoefficients[i].b + GFX.g_R2VenusCoefficients[i].c * rho); - } - var nR3Coefficients = GFX.g_R3VenusCoefficients.length; - var R3 = 0; - for (i = 0; i < nR3Coefficients; i++) { - R3 += GFX.g_R3VenusCoefficients[i].a * Math.cos(GFX.g_R3VenusCoefficients[i].b + GFX.g_R3VenusCoefficients[i].c * rho); - } - var nR4Coefficients = GFX.g_R4VenusCoefficients.length; - var R4 = 0; - for (i = 0; i < nR4Coefficients; i++) { - R4 += GFX.g_R4VenusCoefficients[i].a * Math.cos(GFX.g_R4VenusCoefficients[i].b + GFX.g_R4VenusCoefficients[i].c * rho); - } - return (R0 + R1 * rho + R2 * rhosquared + R3 * rhocubed + R4 * rho4) / 100000000; - }; - var CAAVenus$ = { - - }; - - - // wwtlib.VideoOutputType - - function VideoOutputType(width, height, fps, format, waitDownload) { - this.fps = 0; - this.width = 0; - this.height = 0; - this.totalFrames = 0; - this.waitDownload = false; - this.format = 'image/jpeg'; - this.width = width; - this.height = height; - this.fps = fps; - this.format = format; - this.waitDownload = waitDownload; - } - var VideoOutputType$ = { - - }; - - - // wwtlib.FitsProperties - - function FitsProperties() { - this.bZero = 0; - this.bScale = 1; - this.containsBlanks = false; - this.blankValue = Number.MIN_VALUE; - this.maxVal = Number.MIN_VALUE; - this.minVal = Number.MAX_VALUE; - this.upperCut = Number.MIN_VALUE; - this.lowerCut = Number.MAX_VALUE; - this.transparentBlack = false; - this.colorMapName = 'viridis'; - this.scaleType = 0; - this.onMainImageLoaded = null; - this.mainImageLoadedEventHasFired = false; - } - var FitsProperties$ = { - _fireMainImageLoaded: function (image) { - if (this.onMainImageLoaded != null && !this.mainImageLoadedEventHasFired) { - this.mainImageLoadedEventHasFired = true; - this.onMainImageLoaded(image); - } - } - }; - - - // wwtlib.HipsProperties - - function HipsProperties(dataset) { - this._properties = {}; - this._catalogColumnInfo = null; - this._catalogSpreadSheetLayer = new CatalogSpreadSheetLayer(); - this._downloadComplete = false; - this.dataset = dataset; - this._datasetName = dataset.get_name(); - this._url = dataset.get_url(); - if (this._url.toLowerCase().indexOf('norder') > -1) { - this._url = this._url.substring(0, this._url.toLowerCase().indexOf('norder')); - } - this._url += 'properties'; - this._download(); - } - var HipsProperties$ = { - get_properties: function () { - return this._properties; - }, - get_catalogSpreadSheetLayer: function () { - return this._catalogSpreadSheetLayer; - }, - set_catalogSpreadSheetLayer: function (value) { - this._catalogSpreadSheetLayer = value; - return value; - }, - get_catalogColumnInfo: function () { - return this._catalogColumnInfo; - }, - set_catalogColumnInfo: function (value) { - this._catalogColumnInfo = value; - return value; - }, - get_downloadComplete: function () { - return this._downloadComplete; - }, - _download: function () { - this._webFile = new WebFile(this._url); - this._webFile.onStateChange = ss.bind('_onPropertiesDownloadComplete', this); - this._webFile.send(); - }, - _onPropertiesDownloadComplete: function () { - if (this._webFile.get_state() === 1) { - this._parseProperties(this._webFile.getText()); - if (ss.keyExists(this.get_properties(), 'dataproduct_type') && this.get_properties()['dataproduct_type'].toLowerCase() === 'catalog') { - this._catalogColumnInfo = VoTable.loadFromUrl(ss.replaceString(this._url, '/properties', '/metadata.xml'), ss.bind('_onCatalogMetadataDownloadComplete', this)); - } - else { - if (ss.keyExists(this.get_properties(), 'hips_data_range')) { - var hips_data_range = this.get_properties()['hips_data_range']; - this.dataset.get_fitsProperties().minVal = parseFloat(hips_data_range.split(' ')[0]); - this.dataset.get_fitsProperties().maxVal = parseFloat(hips_data_range.split(' ')[1]); - this.dataset.get_fitsProperties().lowerCut = this.dataset.get_fitsProperties().minVal; - this.dataset.get_fitsProperties().upperCut = this.dataset.get_fitsProperties().maxVal; - } - if (ss.keyExists(this.get_properties(), 'hips_pixel_cut')) { - var hips_pixel_cut = this.get_properties()['hips_pixel_cut']; - this.dataset.get_fitsProperties().lowerCut = parseFloat(hips_pixel_cut.split(' ')[0]); - this.dataset.get_fitsProperties().upperCut = parseFloat(hips_pixel_cut.split(' ')[1]); - if (!ss.keyExists(this.get_properties(), 'hips_data_range')) { - this.dataset.get_fitsProperties().minVal = this.dataset.get_fitsProperties().lowerCut; - this.dataset.get_fitsProperties().maxVal = this.dataset.get_fitsProperties().upperCut; - } - } - this._downloadComplete = true; - if (this._onDownloadComplete != null) { - this._onDownloadComplete(); - } - } - } - }, - _onCatalogMetadataDownloadComplete: function () { - this._catalogSpreadSheetLayer.useHeadersFromVoTable(this._catalogColumnInfo); - this._catalogSpreadSheetLayer.set_name(this._datasetName); - this._catalogSpreadSheetLayer.id = Guid.createFrom(this._datasetName); - LayerManager.addSpreadsheetLayer(this.get_catalogSpreadSheetLayer(), 'Sky'); - this._downloadComplete = true; - if (this._onDownloadComplete != null) { - this._onDownloadComplete(); - } - }, - setDownloadCompleteListener: function (listener) { - this._onDownloadComplete = listener; - }, - _parseProperties: function (data) { - var lines = data.split('\n'); - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var line = $enum1.current; - if (!ss.whitespace(line) && !ss.startsWith(line, '#')) { - var parts = line.split('='); - if (parts.length === 2) { - var key = ss.trim(parts[0]); - var val = ss.trim(parts[1]); - if (!ss.whitespace(key) && !ss.whitespace(val)) { - this.get_properties()[key] = val; - } - } - } - } - } - }; - - - // wwtlib.FastMath - - function FastMath() { - } - FastMath._mulsign = function (x, y) { - return FastMath._sign(y) * x; - }; - FastMath._isnan = function (d) { - return d !== d; - }; - FastMath._isinf = function (d) { - return Math.abs(d) === Number.POSITIVE_INFINITY; - }; - FastMath._sign = function (d) { - if (!d) { - return 0; - } - return (d > 0) ? 1 : -1; - }; - FastMath._atanhelper = function (s) { - var t = s * s; - var u = -1.88796008463073E-05; - u = u * t + (0.000209850076645817); - u = u * t + (-0.00110611831486672); - u = u * t + (0.00370026744188713); - u = u * t + (-0.00889896195887655); - u = u * t + (0.0165993297735292); - u = u * t + (-0.0254517624932313); - u = u * t + (0.0337852580001353); - u = u * t + (-0.0407629191276837); - u = u * t + (0.0466667150077841); - u = u * t + (-0.0523674852303482); - u = u * t + (0.0587666392926674); - u = u * t + (-0.0666573579361081); - u = u * t + (0.076921953831177); - u = u * t + (-0.090908995008245); - u = u * t + (0.111111105648261); - u = u * t + (-0.142857142667713); - u = u * t + (0.199999999996591); - u = u * t + (-0.333333333333311); - return u * t * s + s; - }; - FastMath._atan2k = function (y, x) { - var q = 0; - if (x < 0) { - x = -x; - q = -2; - } - if (y > x) { - var t = x; - x = y; - y = -t; - q += 1; - } - return FastMath._atanhelper(y / x) + q * (Math.PI / 2); - }; - FastMath.atan2 = function (y, x) { - var r = FastMath._atan2k(Math.abs(y), x); - r = FastMath._mulsign(r, x); - if (FastMath._isinf(x) || !x) { - r = Math.PI / 2 - ((FastMath._isinf(x)) ? (FastMath._sign(x) * (Math.PI / 2)) : 0); - } - if (FastMath._isinf(y)) { - r = Math.PI / 2 - ((FastMath._isinf(x)) ? (FastMath._sign(x) * (Math.PI * 1 / 4)) : 0); - } - if (!y) { - r = ((FastMath._sign(x) === -1) ? Math.PI : 0); - } - return (FastMath._isnan(x) || FastMath._isnan(y)) ? Number.NaN : FastMath._mulsign(r, y); - }; - FastMath.asin = function (d) { - return FastMath._mulsign(FastMath._atan2k(Math.abs(d), Math.sqrt((1 + d) * (1 - d))), d); - }; - FastMath.acos = function (d) { - return FastMath._mulsign(FastMath._atan2k(Math.sqrt((1 + d) * (1 - d)), Math.abs(d)), d) + ((d < 0) ? Math.PI : 0); - }; - FastMath.atan = function (s) { - var q = 0; - if (s < 0) { - s = -s; - q = 2; - } - if (s > 1) { - s = 1 / s; - q |= 1; - } - var t = FastMath._atanhelper(s); - if (!!(q & 1)) { - t = 1.5707963267949 - t; - } - if (!!(q & 2)) { - t = -t; - } - return t; - }; - FastMath._sincoshelper = function (d) { - var s = d * d; - var u = -7.97255955009038E-18; - u = u * s + 2.81009972710863E-15; - u = u * s - 7.64712219118159E-13; - u = u * s + 1.60590430605665E-10; - u = u * s - 2.50521083763502E-08; - u = u * s + 2.75573192239199E-06; - u = u * s - 0.000198412698412696; - u = u * s + 0.00833333333333333; - u = u * s - 0.166666666666667; - return s * u * d + d; - }; - FastMath.sin = function (d) { - var u = d * FastMath._m_1_PI; - var q = Math.floor((u < 0) ? u - 0.5 : u + 0.5); - var x = 4 * q; - d -= x * FastMath._pI4_A; - d -= x * FastMath._pI4_B; - d -= x * FastMath._pI4_C; - if (!!(q & 1)) { - d = -d; - } - return FastMath._sincoshelper(d); - }; - FastMath.cos = function (d) { - var u = d * FastMath._m_1_PI - 0.5; - var q = 1 + 2 * Math.floor((u < 0) ? u - 0.5 : u + 0.5); - var x = 2 * q; - d -= x * FastMath._pI4_A; - d -= x * FastMath._pI4_B; - d -= x * FastMath._pI4_C; - if (!(q & 2)) { - d = -d; - } - return FastMath._sincoshelper(d); - }; - var FastMath$ = { - - }; - - - // wwtlib.HealpixTables - - function HealpixTables() { - } - var HealpixTables$ = { - - }; - - - // wwtlib.Xyf - - function Xyf() { - this.ix = 0; - this.iy = 0; - this.face = 0; - } - Xyf.create = function (x, y, f) { - var temp = new Xyf(); - temp.ix = x; - temp.iy = y; - temp.face = f; - return temp; - }; - var Xyf$ = { - - }; - - - // wwtlib.HealpixUtils - - function HealpixUtils() { - } - HealpixUtils.check = function (cond, errtxt) { - if (!cond) { - throw new Error(errtxt); - } - }; - HealpixUtils.isqrt = function (arg) { - var res = Math.sqrt((arg) + 0.5); - if (arg < (1 << 50)) { - return res; - } - if (res * res > arg) { - --res; - } - else if ((res + 1) * (res + 1) <= arg) { - ++res; - } - return res; - }; - HealpixUtils.cosdist_zphi = function (z1, phi1, z2, phi2) { - return z1 * z2 + FastMath.cos(phi1 - phi2) * Math.sqrt((1 - z1 * z1) * (1 - z2 * z2)); - }; - HealpixUtils.fmodulo = function (v1, v2) { - if (v1 >= 0) { - return (v1 < v2) ? v1 : v1 % v2; - } - var tmp = v1 % v2 + v2; - return (tmp === v2) ? 0 : tmp; - }; - var HealpixUtils$ = { - - }; - - - // wwtlib.Hploc - - function Hploc() { - this.z = 0; - this.phi = 0; - this.sth = 0; - this.have_sth = false; - } - Hploc.create = function (v) { - var temp = new Hploc(); - var xl = 1 / v.length(); - temp.z = v.z * xl; - temp.phi = FastMath.atan2(v.y, v.x); - if (Math.abs(temp.z) > 0.99) { - temp.sth = Math.sqrt(v.x * v.x + v.y * v.y) * xl; - temp.have_sth = true; - } - return temp; - }; - var Hploc$ = { - toVec3: function () { - var st; - if (this.have_sth) { - st = this.sth; - } - else { - st = Math.sqrt((1 - this.z) * (1 + this.z)); - } - var x = st * FastMath.cos(this.phi); - var y = st * FastMath.sin(this.phi); - return Vector3d.create(x, this.z, y); - } - }; - - - // wwtlib.Pointing - - function Pointing() { - this.theta = 0; - this.phi = 0; - } - Pointing.create = function (theta, phi) { - var temp = new Pointing(); - temp.theta = theta; - temp.phi = phi; - return temp; - }; - var Pointing$ = { - normalizeTheta: function () { - this.theta = HealpixUtils.fmodulo(this.theta, 2 * Math.PI); - if (this.theta > Math.PI) { - this.phi += Math.PI; - this.theta = 2 * Math.PI - this.theta; - } - }, - normalize: function () { - this.normalizeTheta(); - this.phi = HealpixUtils.fmodulo(this.phi, 2 * Math.PI); - }, - toString: function () { - var s = new ss.StringBuilder(); - s.append('ptg('); - s.append(this.theta); - s.append(','); - s.append(this.phi); - s.append(')'); - return s.toString(); - } - }; - - - // wwtlib.URLHelpers - - function URLHelpers() { - this._force_https = false; - this._origin_protocol = typeof window === "undefined" ? "https:" : window.location.protocol; - this._origin_domain = typeof window === "undefined" ? "" : window.location.hostname; - this._force_https = (this._origin_protocol === 'https:'); - this._domain_handling = {}; - this._domain_handling['worldwidetelescope.org'] = 0; - this._domain_handling['www.worldwidetelescope.org'] = 0; - this._domain_handling['cdn.worldwidetelescope.org'] = 0; - this._domain_handling['content.worldwidetelescope.org'] = 0; - this._domain_handling['beta.worldwidetelescope.org'] = 0; - this._domain_handling['beta-cdn.worldwidetelescope.org'] = 0; - this._domain_handling['wwtstaging.azurewebsites.net'] = 0; - this._domain_handling['wwtfiles.blob.core.windows.net'] = 2; - this._domain_handling['wwttiles.blob.core.windows.net'] = 2; - this._domain_handling['web.wwtassets.org'] = 2; - this._domain_handling['data1.wwtassets.org'] = 2; - this._domain_handling['localhost'] = 1; - this._domain_handling['127.0.0.1'] = 1; - switch (this._origin_domain) { - case 'worldwidetelescope.org': - case 'www.worldwidetelescope.org': - case 'cdn.worldwidetelescope.org': - this._core_static_baseurl = this._origin_protocol + '//cdn.worldwidetelescope.org'; - this._core_dynamic_baseurl = this._origin_protocol + '//worldwidetelescope.org'; - break; - case 'beta.worldwidetelescope.org': - case 'beta-cdn.worldwidetelescope.org': - this._core_static_baseurl = this._origin_protocol + '//beta-cdn.worldwidetelescope.org'; - this._core_dynamic_baseurl = this._origin_protocol + '//beta.worldwidetelescope.org'; - break; - default: - this._core_static_baseurl = this._origin_protocol + '//cdn.worldwidetelescope.org'; - this._core_dynamic_baseurl = this._origin_protocol + '//worldwidetelescope.org'; - break; - } - this._engine_asset_baseurl = this._origin_protocol + '//web.wwtassets.org/engine/assets'; - this._flagship_static_lcpaths = {}; - this._flagship_static_lcpaths['/wwtweb/2massoct.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/bingdemtile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/bingdemtile2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/catalog.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/catalog2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/dem.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/dembath.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/demmars.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/demtile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/dss.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/dsstoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/dusttoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/earthblend.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/earthmerbath.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/fixedaltitudedemtile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/g360.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/galex4far.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/galex4near.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/galextoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/gettile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/gettour.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/gettourfile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/gettours.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/glimpse.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/halphatoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/hirise.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/hirisedem2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/hirisedem3.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/jupiter.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/mandel.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/mandel1.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/mars.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/marsdem.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/marshirise.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/marsmoc.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/martiantile.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/martiantile2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/mipsgal.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/moondem.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/moonoct.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/moontoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/moontoastdem.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/postmars.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/postmarsdem.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/postmarsdem2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/rasstoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/sdsstoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/sdsstoast2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/sdsstoast2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/thumbnail.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/tiles.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/tiles2.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/tilesthumb.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/twomasstoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/tychooct.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/veblend.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/vlsstoast.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/wmap.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/wmsmoon.aspx'] = true; - this._flagship_static_lcpaths['/wwtweb/wmstoast.aspx'] = true; - } - var URLHelpers$ = { - overrideAssetBaseurl: function (baseurl) { - this._engine_asset_baseurl = baseurl; - }, - rewrite: function (url, rwmode) { - var lc = url.toLowerCase(); - var lcproto; - var url_no_protocol; - if (ss.startsWith(lc, 'http://')) { - lcproto = 'http:'; - url_no_protocol = url.substring(7); - } - else if (ss.startsWith(lc, 'https://')) { - lcproto = 'https:'; - url_no_protocol = url.substring(8); - } - else if (ss.startsWith(lc, '//')) { - lcproto = ''; - url_no_protocol = url.substring(2); - } - else if (ss.startsWith(lc, 'blob:')) { - return url; - } - else { - switch (rwmode) { - case 0: - default: - lcproto = ''; - url_no_protocol = url; - break; - case 1: - url = (new URL(url, window.location.href)).toString(); - return this.rewrite(url, 0); - } - } - if (WWTControl.singleton.freestandingMode) { - return url; - } - var domain; - var rest; - var slash_index = url_no_protocol.indexOf('/'); - if (slash_index < 0) { - domain = url_no_protocol; - rest = '/'; - } - else { - domain = url_no_protocol.substring(0, slash_index); - rest = url_no_protocol.substring(slash_index); - } - var lcdomain = domain.toLowerCase(); - var lcpath = rest.toLowerCase().split('?')[0]; - if (!ss.keyExists(this._domain_handling, lcdomain)) { - if (ss.startsWith(lcdomain, 'localhost:') || ss.startsWith(lcdomain, '127.0.0.1:')) { - this._domain_handling[lcdomain] = 1; - } - else { - this._domain_handling[lcdomain] = 3; - } - } - var mode = this._domain_handling[lcdomain]; - switch (mode) { - case 1: - return url; - case 2: - case 3: - default: - if (this._force_https && lcproto !== 'https:') { - return 'https://' + domain + rest; - } - return url; - case 4: - if (!lcproto) { - url = 'http://' + url; - } - url = ss.replaceString(ss.replaceString(encodeURIComponent(url), '%7B', '{'), '%7D', '}'); - return this._core_dynamic_baseurl + '/webserviceproxy.aspx?targeturl=' + url; - case 0: - var is_static = false; - if (ss.startsWith(lcpath, '/data/')) { - is_static = true; - } - else if (ss.keyExists(this._flagship_static_lcpaths, lcpath)) { - is_static = true; - } - else if (ss.startsWith(lcpath, '/content/')) { - is_static = true; - } - else if (ss.startsWith(lcpath, '/engine/assets/')) { - is_static = true; - } - if (is_static) { - return this._core_static_baseurl + rest; - } - return this._core_dynamic_baseurl + rest; - } - }, - activateProxy: function (url) { - if (WWTControl.singleton.freestandingMode) { - return null; - } - var lc = url.toLowerCase(); - var url_no_protocol; - if (ss.startsWith(lc, 'http://')) { - url_no_protocol = url.substring(7); - } - else if (ss.startsWith(lc, 'https://')) { - url_no_protocol = url.substring(8); - } - else if (ss.startsWith(lc, '//')) { - url_no_protocol = url.substring(2); - } - else { - url_no_protocol = url; - } - var lcdomain; - var slash_index = url_no_protocol.indexOf('/'); - if (slash_index < 0) { - lcdomain = url_no_protocol; - } - else { - lcdomain = url_no_protocol.substring(0, slash_index).toLowerCase(); - } - if (!ss.keyExists(this._domain_handling, lcdomain)) { - if (ss.startsWith(lcdomain, 'localhost:') || ss.startsWith(lcdomain, '127.0.0.1:')) { - this._domain_handling[lcdomain] = 1; - } - else { - this._domain_handling[lcdomain] = 3; - } - } - var mode = this._domain_handling[lcdomain]; - if (!mode || mode === 2 || mode === 1) { - return null; - } - this._domain_handling[lcdomain] = 4; - return this.rewrite(url, 0); - }, - engineAssetUrl: function (subpath) { - return ss.format('{0}/{1}', this._engine_asset_baseurl, subpath); - }, - coreDynamicUrl: function (subpath) { - return ss.format('{0}/{1}', this._core_dynamic_baseurl, subpath); - }, - coreStaticUrl: function (subpath) { - return ss.format('{0}/{1}', this._core_static_baseurl, subpath); - } - }; - - - // wwtlib.Annotation - - function Annotation() { - this.addedToPrimitives = false; - this.annotationDirty = true; - this._opacity = 1; - this._showHoverLabel = false; - } - Annotation.prepBatch = function (renderContext) { - if (Annotation.pointList == null || Annotation.batchDirty) { - Annotation.pointList = new PointList(renderContext); - Annotation.lineList = new LineList(); - Annotation.triangleFanPointList = new TriangleFanList(); - Annotation.triangleList = new TriangleList(); - Annotation.lineList.set_depthBuffered(false); - Annotation.triangleList.depthBuffered = false; - } - }; - Annotation.drawBatch = function (renderContext) { - Annotation.batchDirty = false; - if (renderContext.gl == null) { - return; - } - if (Annotation.pointList != null) { - Annotation.pointList.draw(renderContext, 1, false); - } - if (Annotation.lineList != null) { - Annotation.lineList.drawLines(renderContext, 1); - } - if (Annotation.triangleFanPointList != null) { - Annotation.triangleFanPointList.draw(renderContext, 1); - } - if (Annotation.triangleList != null) { - Annotation.triangleList.draw(renderContext, 1, 0); - } - }; - Annotation.separation = function (Alpha1, Delta1, Alpha2, Delta2) { - Delta1 = Delta1 / 180 * Math.PI; - Delta2 = Delta2 / 180 * Math.PI; - Alpha1 = Alpha1 / 12 * Math.PI; - Alpha2 = Alpha2 / 12 * Math.PI; - var x = Math.cos(Delta1) * Math.sin(Delta2) - Math.sin(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); - var y = Math.cos(Delta2) * Math.sin(Alpha2 - Alpha1); - var z = Math.sin(Delta1) * Math.sin(Delta2) + Math.cos(Delta1) * Math.cos(Delta2) * Math.cos(Alpha2 - Alpha1); - var vvalue = Math.atan2(Math.sqrt(x * x + y * y), z); - vvalue = vvalue / Math.PI * 180; - if (vvalue < 0) { - vvalue += 180; - } - return vvalue; - }; - Annotation.colorToUint = function (col) { - return (col.a) << 24 | (col.r << 16) | (col.g) << 8 | col.b; - }; - Annotation.colorToUintAlpha = function (col, opacity) { - return opacity << 24 | col.r << 16 | col.g << 8 | col.b; - }; - var Annotation$ = { - draw: function (renderContext) { - }, - get_opacity: function () { - return this._opacity; - }, - set_opacity: function (value) { - Annotation.batchDirty = true; - this._opacity = value; - return value; - }, - get_id: function () { - return this._id; - }, - set_id: function (value) { - this._id = value; - return value; - }, - get_tag: function () { - return this._tag; - }, - set_tag: function (value) { - this._tag = value; - return value; - }, - get_label: function () { - return this._label; - }, - set_label: function (value) { - this._label = value; - return value; - }, - get_showHoverLabel: function () { - return this._showHoverLabel; - }, - set_showHoverLabel: function (value) { - this._showHoverLabel = value; - return value; - }, - hitTest: function (renderContext, RA, dec, x, y) { - return false; - }, - get_center: function () { - return this.center; - }, - set_center: function (value) { - this.center = value; - return value; - } - }; - - - // wwtlib.AstroRaDec - - function AstroRaDec(ra, dec, dist, shadow, eclipsed) { - this.RA = 0; - this.dec = 0; - this.distance = 0; - this.shadow = false; - this.eclipsed = false; - this.RA = ra; - this.dec = dec; - this.distance = dist; - this.shadow = shadow; - this.eclipsed = eclipsed; - } - var AstroRaDec$ = { - - }; - - - // wwtlib.RiseSetDetails - - function RiseSetDetails(bValid, Rise, Transit, Set, neverRises) { - this.bValid = false; - this.rise = 0; - this.transit = 0; - this.set = 0; - this.bNeverRises = false; - this.bValid = bValid; - this.rise = Rise; - this.transit = Transit; - this.set = Set; - this.bNeverRises = neverRises; - } - var RiseSetDetails$ = { - - }; - - - // wwtlib.AstroCalc - - function AstroCalc() { - } - AstroCalc.getPlanet = function (jDate, planetIn, locLat, locLong, locHeight) { - var planet = planetIn; - locLong = -locLong; - if (planet < 9) { - var Details = ELL.calculate(jDate, planetIn); - var corrected = CAAParallax.equatorial2Topocentric(Details.apparentGeocentricRA, Details.apparentGeocentricDeclination, Details.apparentGeocentricDistance, locLong, locLat, locHeight, jDate); - return new AstroRaDec(corrected.x, corrected.y, Details.apparentGeocentricDistance, false, false); - } - else if (planet === 9) { - var lat = CAAMoon.eclipticLatitude(jDate); - var lng = CAAMoon.eclipticLongitude(jDate); - var dis = CAAMoon.radiusVector(jDate) / 149598000; - var epsilon = CAANutation.trueObliquityOfEcliptic(jDate); - var d = CT.ec2Eq(lng, lat, epsilon); - var corrected = CAAParallax.equatorial2Topocentric(d.x, d.y, dis, locLong, locLat, locHeight, jDate); - return new AstroRaDec(corrected.x, corrected.y, dis, false, false); - } - else { - if (jDate !== AstroCalc._jDateLast) { - AstroCalc._jupDetails = ELL.calculate(jDate, 4); - AstroCalc._jupPhisical = CAAPhysicalJupiter.calculate(jDate); - var corrected = CAAParallax.equatorial2Topocentric(AstroCalc._jupDetails.apparentGeocentricRA, AstroCalc._jupDetails.apparentGeocentricDeclination, AstroCalc._jupDetails.apparentGeocentricDistance, locLong, locLat, locHeight, jDate); - AstroCalc._jupDetails.apparentGeocentricRA = corrected.x; - AstroCalc._jupDetails.apparentGeocentricDeclination = corrected.y; - AstroCalc._galDetails = GM.calculate(jDate); - AstroCalc._jDateLast = jDate; - } - var jupiterDiameter = 0.000954501; - var scale = Math.atan(0.5 * (jupiterDiameter / AstroCalc._jupDetails.apparentGeocentricDistance)) / 3.1415927 * 180; - var raScale = (scale / Math.cos(AstroCalc._jupDetails.apparentGeocentricDeclination / 180 * 3.1415927)) / 15; - var xMoon = 0; - var yMoon = 0; - var zMoon = 0; - var shadow = false; - var eclipsed = false; - switch (planet) { - case 10: - xMoon = AstroCalc._galDetails.satellite1.apparentRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite1.apparentRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite1.apparentRectangularCoordinates.z; - eclipsed = AstroCalc._galDetails.satellite1.bInEclipse; - shadow = AstroCalc._galDetails.satellite1.bInShadowTransit; - break; - case 11: - xMoon = AstroCalc._galDetails.satellite2.apparentRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite2.apparentRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite2.apparentRectangularCoordinates.z; - eclipsed = AstroCalc._galDetails.satellite2.bInEclipse; - shadow = AstroCalc._galDetails.satellite2.bInShadowTransit; - break; - case 12: - xMoon = AstroCalc._galDetails.satellite3.apparentRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite3.apparentRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite3.apparentRectangularCoordinates.z; - eclipsed = AstroCalc._galDetails.satellite3.bInEclipse; - shadow = AstroCalc._galDetails.satellite3.bInShadowTransit; - break; - case 13: - xMoon = AstroCalc._galDetails.satellite4.apparentRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite4.apparentRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite4.apparentRectangularCoordinates.z; - eclipsed = AstroCalc._galDetails.satellite4.bInEclipse; - shadow = AstroCalc._galDetails.satellite4.bInShadowTransit; - break; - case 14: - xMoon = AstroCalc._galDetails.satellite1.apparentShadowRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite1.apparentShadowRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite1.apparentShadowRectangularCoordinates.z * 0.9; - shadow = AstroCalc._galDetails.satellite1.bInShadowTransit; - break; - case 15: - xMoon = AstroCalc._galDetails.satellite2.apparentShadowRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite2.apparentShadowRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite2.apparentShadowRectangularCoordinates.z * 0.9; - shadow = AstroCalc._galDetails.satellite2.bInShadowTransit; - break; - case 16: - xMoon = AstroCalc._galDetails.satellite3.apparentShadowRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite3.apparentShadowRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite3.apparentShadowRectangularCoordinates.z * 0.9; - shadow = AstroCalc._galDetails.satellite3.bInShadowTransit; - break; - case 17: - xMoon = AstroCalc._galDetails.satellite4.apparentShadowRectangularCoordinates.x; - yMoon = AstroCalc._galDetails.satellite4.apparentShadowRectangularCoordinates.y; - zMoon = AstroCalc._galDetails.satellite4.apparentShadowRectangularCoordinates.z * 0.9; - shadow = AstroCalc._galDetails.satellite4.bInShadowTransit; - break; - } - var xTemp; - var yTemp; - var radians = AstroCalc._jupPhisical.p / 180 * 3.1415927; - xTemp = xMoon * Math.cos(radians) - yMoon * Math.sin(radians); - yTemp = xMoon * Math.sin(radians) + yMoon * Math.cos(radians); - xMoon = xTemp; - yMoon = yTemp; - return new AstroRaDec(AstroCalc._jupDetails.apparentGeocentricRA - (xMoon * raScale), AstroCalc._jupDetails.apparentGeocentricDeclination + yMoon * scale, AstroCalc._jupDetails.apparentGeocentricDistance + (zMoon * jupiterDiameter / 2), shadow, eclipsed); - } - }; - AstroCalc.getJulianDay = function (year, month, day) { - return DT.dateToJD(ss.truncate(year), ss.truncate(month), day, true); - }; - AstroCalc.eclipticToJ2000 = function (l, b, jNow) { - var radec = CT.ec2Eq(l, b, CAANutation.trueObliquityOfEcliptic(jNow)); - return new AstroRaDec(radec.x, radec.y, 0, false, false); - }; - AstroCalc.galacticToJ2000 = function (l, b) { - var radec = CT.g2Eq(l, b); - return new AstroRaDec(radec.x, radec.y, 0, false, false); - }; - AstroCalc.j2000ToGalactic = function (ra, dec) { - var galactic = CT.eq2G(ra, dec); - return new AstroRaDec(galactic.x, galactic.y, 0, false, false); - }; - AstroCalc.getRiseTrinsitSet = function (jd, lat, lng, ra1, dec1, ra2, dec2, ra3, dec3, type) { - var alt = -0.5667; - switch (type) { - case 0: - alt = -0.5667; - break; - case 1: - alt = -0.8333; - break; - case 2: - alt = 0.125; - break; - } - var RiseTransitSetTime = CAARiseTransitSet.rise(jd, ra1, dec1, ra2, dec2, ra3, dec3, lng, lat, alt); - var neverRises = false; - if (!RiseTransitSetTime.bValid) { - neverRises = Util.sign(lat) !== Util.sign(dec2); - } - return new RiseSetDetails(RiseTransitSetTime.bValid, RiseTransitSetTime.rise, RiseTransitSetTime.transit, RiseTransitSetTime.set, neverRises); - }; - var AstroCalc$ = { - - }; - - - // wwtlib.BlendState - - function BlendState() { - this._state = false; - this._targetState = false; - this._delayTime = 0; - this._switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); - this._state = false; - this._targetState = this._state; - this._delayTime = 1000; - } - BlendState.create = function (initialState, delayTime) { - var temp = new BlendState(); - temp._state = initialState; - temp._targetState = initialState; - temp._delayTime = delayTime; - return temp; - }; - var BlendState$ = { - get_state: function () { - if (this._targetState !== this._state) { - var ts = ss.now() - this._switchedTime; - if (ts > this._delayTime) { - this._state = this._targetState; - } - return true; - } - return this._state; - }, - set_state: function (value) { - this._switchedTime = new Date(1990, 0, 0, 0, 0, 0, 0); - this._state = value; - this._targetState = this._state; - return value; - }, - get_targetState: function () { - return this._targetState; - }, - set_targetState: function (value) { - if (this._targetState !== value) { - this._switchedTime = ss.now(); - this._targetState = value; - } - return value; - }, - get_opacity: function () { - if (this._targetState !== this._state) { - var ts = ss.now() - this._switchedTime; - if (ts > this._delayTime) { - this._state = this._targetState; - } - else { - var opacity = (ts / this._delayTime); - return (this._targetState) ? opacity : 1 - opacity; - } - } - return (this._state) ? 1 : 0; - }, - get_delayTime: function () { - return this._delayTime; - }, - set_delayTime: function (value) { - this._delayTime = value; - return value; - } - }; - - - // wwtlib.CameraParameters - - function CameraParameters() { - this.lat = 0; - this.lng = 0; - this.zoom = 0; - this.rotation = 0; - this.angle = 0; - this.raDec = false; - this.opacity = 0; - this.target = 0; - this.zoom = 360; - this.viewTarget = new Vector3d(); - } - CameraParameters.create = function (lat, lng, zoom, rotation, angle, opactity) { - var temp = new CameraParameters(); - temp.lat = lat; - temp.lng = lng; - temp.zoom = zoom; - temp.rotation = rotation; - temp.angle = angle; - temp.raDec = false; - temp.opacity = opactity; - temp.viewTarget = Vector3d.create(0, 0, 0); - temp.target = 20; - temp.targetReferenceFrame = ''; - return temp; - }; - CameraParameters.logN = function (num, b) { - return Math.log(num) / Math.log(b); - }; - CameraParameters.sinh = function (v) { - return (Math.exp(v) - Math.exp(-v)) / 2; - }; - CameraParameters.interpolate = function (from, to, alphaIn, type, fastDirectionMove) { - var result = new CameraParameters(); - var alpha = CameraParameters.easeCurve(alphaIn, type); - var alphaBIn = Math.min(1, alphaIn * 2); - var alphaB = CameraParameters.easeCurve(alphaBIn, type); - result.angle = to.angle * alpha + from.angle * (1 - alpha); - result.rotation = to.rotation * alpha + from.rotation * (1 - alpha); - if (fastDirectionMove) { - result.lat = to.lat * alphaB + from.lat * (1 - alphaB); - result.lng = to.lng * alphaB + from.lng * (1 - alphaB); - } - else { - result.lat = to.lat * alpha + from.lat * (1 - alpha); - result.lng = to.lng * alpha + from.lng * (1 - alpha); - } - result.zoom = Math.pow(2, CameraParameters.logN(to.zoom, 2) * alpha + CameraParameters.logN(from.zoom, 2) * (1 - alpha)); - result.opacity = (to.opacity * alpha + from.opacity * (1 - alpha)); - result.viewTarget = Vector3d.lerp(from.viewTarget, to.viewTarget, alpha); - result.targetReferenceFrame = to.targetReferenceFrame; - if (to.target === from.target) { - result.target = to.target; - } - else { - result.target = 20; - } - return result; - }; - CameraParameters.interpolateGreatCircle = function (from, to, alphaIn, type, fastDirectionMove) { - var result = new CameraParameters(); - var alpha = CameraParameters.easeCurve(alphaIn, type); - var alphaBIn = Math.min(1, alphaIn * 2); - var alphaB = CameraParameters.easeCurve(alphaBIn, type); - result.angle = to.angle * alpha + from.angle * (1 - alpha); - result.rotation = to.rotation * alpha + from.rotation * (1 - alpha); - var left = Coordinates.geoTo3dDouble(from.lat, from.lng); - var right = Coordinates.geoTo3dDouble(to.lat, to.lng); - var mid = Vector3d.slerp(left, right, alpha); - var midV2 = Coordinates.cartesianToLatLng(mid); - result.lat = midV2.y; - result.lng = midV2.x; - result.zoom = Math.pow(2, CameraParameters.logN(to.zoom, 2) * alpha + CameraParameters.logN(from.zoom, 2) * (1 - alpha)); - result.opacity = (to.opacity * alpha + from.opacity * (1 - alpha)); - result.viewTarget = Vector3d.lerp(from.viewTarget, to.viewTarget, alpha); - result.targetReferenceFrame = to.targetReferenceFrame; - if (to.target === from.target) { - result.target = to.target; - } - else { - result.target = 20; - } - return result; - }; - CameraParameters.easeCurve = function (alpha, type) { - switch (type) { - case 0: - return alpha; - case 4: - return Math.pow(alpha, 2); - case 1: - return ((1 - alpha) * CameraParameters.sinh(alpha / (0.1085712344 * 2)) / 100) + alpha * alpha; - case 2: - return (alpha * (1 - CameraParameters.sinh((1 - alpha) / (0.1085712344 * 2)) / 100)) + (1 - alpha) * alpha; - case 3: - if (alpha < 0.5) { - return CameraParameters.sinh(alpha / 0.1085712344) / 100; - } - else { - return 1 - (CameraParameters.sinh((1 - alpha) / 0.1085712344) / 100); - } - default: - return alpha; - } - }; - var CameraParameters$ = { - copy: function () { - var temp = new CameraParameters(); - temp.lat = this.lat; - temp.lng = this.lng; - temp.zoom = this.zoom; - temp.rotation = this.rotation; - temp.angle = this.angle; - temp.raDec = this.raDec; - temp.opacity = this.opacity; - temp.viewTarget = this.viewTarget.copy(); - temp.target = this.target; - temp.targetReferenceFrame = this.targetReferenceFrame; - return temp; - }, - get_RA: function () { - return ((((180 - (this.lng - 180)) / 360) * 24) % 24); - }, - set_RA: function (value) { - this.lng = 180 - (value / 24 * 360) - 180; - this.raDec = true; - return value; - }, - get_dec: function () { - return this.lat; - }, - set_dec: function (value) { - this.lat = value; - return value; - }, - equals: function (obj) { - if (ss.canCast(obj, CameraParameters)) { - var cam = obj; - if (Math.abs(cam.angle - this.angle) > 0.01 || Math.abs(cam.lat - this.lat) > (cam.zoom / 10000) || Math.abs(cam.get_RA() - this.get_RA()) > (cam.zoom / 1000) || Math.abs(cam.rotation - this.rotation) > 0.1 || Math.abs(cam.zoom - this.zoom) > (Math.abs(cam.zoom) / 1000)) { - return false; - } - return true; - } - else { - return false; - } - } - }; - - - // wwtlib.Color - - function Color() { - this.a = 255; - this.b = 255; - this.g = 255; - this.r = 255; - this.name = ''; - } - Color.fromArgb = function (a, r, g, b) { - var temp = new Color(); - temp.a = a; - temp.r = r; - temp.g = g; - temp.b = b; - return temp; - }; - Color._fromArgbColor = function (a, col) { - var temp = new Color(); - temp.a = a; - temp.r = col.r; - temp.g = col.g; - temp.b = col.b; - return temp; - }; - Color.fromName = function (name) { - var temp = Color.load(name); - return temp; - }; - Color.load = function (color) { - var a = 255, r = 255, g = 255, b = 255; - var pieces = color.split(':'); - if (pieces.length === 5) { - a = parseInt(pieces[1]); - r = parseInt(pieces[2]); - g = parseInt(pieces[3]); - b = parseInt(pieces[4]); - } - else if (pieces.length === 2) { - return Color.fromName(pieces[1].toLowerCase()); - } - else if (pieces.length === 1 && ss.startsWith(pieces[0], '#')) { - return Color.fromHex(pieces[0]); - } - else if (pieces.length === 1 && pieces[0].length === 8) { - return Color.fromSimpleHex(pieces[0]); - } - else if (pieces.length === 1) { - return Color._fromWindowsNamedColor(pieces[0]); - } - return Color.fromArgb(a, r, g, b); - }; - Color._fromWindowsNamedColor = function (color) { - switch (color.toLowerCase()) { - case 'activeborder': - return Color.fromArgb(255, 180, 180, 180); - case 'activecaption': - return Color.fromArgb(255, 153, 180, 209); - case 'activecaptiontext': - return Color.fromArgb(255, 0, 0, 0); - case 'appworkspace': - return Color.fromArgb(255, 171, 171, 171); - case 'control': - return Color.fromArgb(255, 240, 240, 240); - case 'controldark': - return Color.fromArgb(255, 160, 160, 160); - case 'controldarkdark': - return Color.fromArgb(255, 105, 105, 105); - case 'controllight': - return Color.fromArgb(255, 227, 227, 227); - case 'controllightlight': - return Color.fromArgb(255, 255, 255, 255); - case 'controltext': - return Color.fromArgb(255, 0, 0, 0); - case 'desktop': - return Color.fromArgb(255, 255, 255, 255); - case 'graytext': - return Color.fromArgb(255, 109, 109, 109); - case 'highlight': - return Color.fromArgb(255, 51, 153, 255); - case 'highlighttext': - return Color.fromArgb(255, 255, 255, 255); - case 'hottrack': - return Color.fromArgb(255, 0, 102, 204); - case 'inactiveborder': - return Color.fromArgb(255, 244, 247, 252); - case 'inactivecaption': - return Color.fromArgb(255, 191, 205, 219); - case 'inactivecaptiontext': - return Color.fromArgb(255, 0, 0, 0); - case 'info': - return Color.fromArgb(255, 255, 255, 225); - case 'infotext': - return Color.fromArgb(255, 0, 0, 0); - case 'menu': - return Color.fromArgb(255, 240, 240, 240); - case 'menutext': - return Color.fromArgb(255, 0, 0, 0); - case 'scrollbar': - return Color.fromArgb(255, 200, 200, 200); - case 'window': - return Color.fromArgb(255, 255, 255, 255); - case 'windowframe': - return Color.fromArgb(255, 100, 100, 100); - case 'windowtext': - return Color.fromArgb(255, 0, 0, 0); - case 'transparent': - return Color.fromArgb(0, 255, 255, 255); - case 'aliceblue': - return Color.fromArgb(255, 240, 248, 255); - case 'antiquewhite': - return Color.fromArgb(255, 250, 235, 215); - case 'aqua': - return Color.fromArgb(255, 0, 255, 255); - case 'aquamarine': - return Color.fromArgb(255, 127, 255, 212); - case 'azure': - return Color.fromArgb(255, 240, 255, 255); - case 'beige': - return Color.fromArgb(255, 245, 245, 220); - case 'bisque': - return Color.fromArgb(255, 255, 228, 196); - case 'black': - return Color.fromArgb(255, 0, 0, 0); - case 'blanchedalmond': - return Color.fromArgb(255, 255, 235, 205); - case 'blue': - return Color.fromArgb(255, 0, 0, 255); - case 'blueviolet': - return Color.fromArgb(255, 138, 43, 226); - case 'brown': - return Color.fromArgb(255, 165, 42, 42); - case 'burlywood': - return Color.fromArgb(255, 222, 184, 135); - case 'cadetblue': - return Color.fromArgb(255, 95, 158, 160); - case 'chartreuse': - return Color.fromArgb(255, 127, 255, 0); - case 'chocolate': - return Color.fromArgb(255, 210, 105, 30); - case 'coral': - return Color.fromArgb(255, 255, 127, 80); - case 'cornflowerblue': - return Color.fromArgb(255, 100, 149, 237); - case 'cornsilk': - return Color.fromArgb(255, 255, 248, 220); - case 'crimson': - return Color.fromArgb(255, 220, 20, 60); - case 'cyan': - return Color.fromArgb(255, 0, 255, 255); - case 'darkblue': - return Color.fromArgb(255, 0, 0, 139); - case 'darkcyan': - return Color.fromArgb(255, 0, 139, 139); - case 'darkgoldenrod': - return Color.fromArgb(255, 184, 134, 11); - case 'darkgray': - return Color.fromArgb(255, 169, 169, 169); - case 'darkgreen': - return Color.fromArgb(255, 0, 100, 0); - case 'darkkhaki': - return Color.fromArgb(255, 189, 183, 107); - case 'darkmagenta': - return Color.fromArgb(255, 139, 0, 139); - case 'darkolivegreen': - return Color.fromArgb(255, 85, 107, 47); - case 'darkorange': - return Color.fromArgb(255, 255, 140, 0); - case 'darkorchid': - return Color.fromArgb(255, 153, 50, 204); - case 'darkred': - return Color.fromArgb(255, 139, 0, 0); - case 'darksalmon': - return Color.fromArgb(255, 233, 150, 122); - case 'darkseagreen': - return Color.fromArgb(255, 143, 188, 139); - case 'darkslateblue': - return Color.fromArgb(255, 72, 61, 139); - case 'darkslategray': - return Color.fromArgb(255, 47, 79, 79); - case 'darkturquoise': - return Color.fromArgb(255, 0, 206, 209); - case 'darkviolet': - return Color.fromArgb(255, 148, 0, 211); - case 'deeppink': - return Color.fromArgb(255, 255, 20, 147); - case 'deepskyblue': - return Color.fromArgb(255, 0, 191, 255); - case 'dimgray': - return Color.fromArgb(255, 105, 105, 105); - case 'dodgerblue': - return Color.fromArgb(255, 30, 144, 255); - case 'firebrick': - return Color.fromArgb(255, 178, 34, 34); - case 'floralwhite': - return Color.fromArgb(255, 255, 250, 240); - case 'forestgreen': - return Color.fromArgb(255, 34, 139, 34); - case 'fuchsia': - return Color.fromArgb(255, 255, 0, 255); - case 'gainsboro': - return Color.fromArgb(255, 220, 220, 220); - case 'ghostwhite': - return Color.fromArgb(255, 248, 248, 255); - case 'gold': - return Color.fromArgb(255, 255, 215, 0); - case 'goldenrod': - return Color.fromArgb(255, 218, 165, 32); - case 'gray': - return Color.fromArgb(255, 128, 128, 128); - case 'green': - return Color.fromArgb(255, 0, 128, 0); - case 'greenyellow': - return Color.fromArgb(255, 173, 255, 47); - case 'honeydew': - return Color.fromArgb(255, 240, 255, 240); - case 'hotpink': - return Color.fromArgb(255, 255, 105, 180); - case 'indianred': - return Color.fromArgb(255, 205, 92, 92); - case 'indigo': - return Color.fromArgb(255, 75, 0, 130); - case 'ivory': - return Color.fromArgb(255, 255, 255, 240); - case 'khaki': - return Color.fromArgb(255, 240, 230, 140); - case 'lavender': - return Color.fromArgb(255, 230, 230, 250); - case 'lavenderblush': - return Color.fromArgb(255, 255, 240, 245); - case 'lawngreen': - return Color.fromArgb(255, 124, 252, 0); - case 'lemonchiffon': - return Color.fromArgb(255, 255, 250, 205); - case 'lightblue': - return Color.fromArgb(255, 173, 216, 230); - case 'lightcoral': - return Color.fromArgb(255, 240, 128, 128); - case 'lightcyan': - return Color.fromArgb(255, 224, 255, 255); - case 'lightgoldenrodyellow': - return Color.fromArgb(255, 250, 250, 210); - case 'lightgray': - return Color.fromArgb(255, 211, 211, 211); - case 'lightgreen': - return Color.fromArgb(255, 144, 238, 144); - case 'lightpink': - return Color.fromArgb(255, 255, 182, 193); - case 'lightsalmon': - return Color.fromArgb(255, 255, 160, 122); - case 'lightseagreen': - return Color.fromArgb(255, 32, 178, 170); - case 'lightskyblue': - return Color.fromArgb(255, 135, 206, 250); - case 'lightslategray': - return Color.fromArgb(255, 119, 136, 153); - case 'lightsteelblue': - return Color.fromArgb(255, 176, 196, 222); - case 'lightyellow': - return Color.fromArgb(255, 255, 255, 224); - case 'lime': - return Color.fromArgb(255, 0, 255, 0); - case 'limegreen': - return Color.fromArgb(255, 50, 205, 50); - case 'linen': - return Color.fromArgb(255, 250, 240, 230); - case 'magenta': - return Color.fromArgb(255, 255, 0, 255); - case 'maroon': - return Color.fromArgb(255, 128, 0, 0); - case 'mediumaquamarine': - return Color.fromArgb(255, 102, 205, 170); - case 'mediumblue': - return Color.fromArgb(255, 0, 0, 205); - case 'mediumorchid': - return Color.fromArgb(255, 186, 85, 211); - case 'mediumpurple': - return Color.fromArgb(255, 147, 112, 219); - case 'mediumseagreen': - return Color.fromArgb(255, 60, 179, 113); - case 'mediumslateblue': - return Color.fromArgb(255, 123, 104, 238); - case 'mediumspringgreen': - return Color.fromArgb(255, 0, 250, 154); - case 'mediumturquoise': - return Color.fromArgb(255, 72, 209, 204); - case 'mediumvioletred': - return Color.fromArgb(255, 199, 21, 133); - case 'midnightblue': - return Color.fromArgb(255, 25, 25, 112); - case 'mintcream': - return Color.fromArgb(255, 245, 255, 250); - case 'mistyrose': - return Color.fromArgb(255, 255, 228, 225); - case 'moccasin': - return Color.fromArgb(255, 255, 228, 181); - case 'navajowhite': - return Color.fromArgb(255, 255, 222, 173); - case 'navy': - return Color.fromArgb(255, 0, 0, 128); - case 'oldlace': - return Color.fromArgb(255, 253, 245, 230); - case 'olive': - return Color.fromArgb(255, 128, 128, 0); - case 'olivedrab': - return Color.fromArgb(255, 107, 142, 35); - case 'orange': - return Color.fromArgb(255, 255, 165, 0); - case 'orangered': - return Color.fromArgb(255, 255, 69, 0); - case 'orchid': - return Color.fromArgb(255, 218, 112, 214); - case 'palegoldenrod': - return Color.fromArgb(255, 238, 232, 170); - case 'palegreen': - return Color.fromArgb(255, 152, 251, 152); - case 'paleturquoise': - return Color.fromArgb(255, 175, 238, 238); - case 'palevioletred': - return Color.fromArgb(255, 219, 112, 147); - case 'papayawhip': - return Color.fromArgb(255, 255, 239, 213); - case 'peachpuff': - return Color.fromArgb(255, 255, 218, 185); - case 'peru': - return Color.fromArgb(255, 205, 133, 63); - case 'pink': - return Color.fromArgb(255, 255, 192, 203); - case 'plum': - return Color.fromArgb(255, 221, 160, 221); - case 'powderblue': - return Color.fromArgb(255, 176, 224, 230); - case 'purple': - return Color.fromArgb(255, 128, 0, 128); - case 'red': - return Color.fromArgb(255, 255, 0, 0); - case 'rosybrown': - return Color.fromArgb(255, 188, 143, 143); - case 'royalblue': - return Color.fromArgb(255, 65, 105, 225); - case 'saddlebrown': - return Color.fromArgb(255, 139, 69, 19); - case 'salmon': - return Color.fromArgb(255, 250, 128, 114); - case 'sandybrown': - return Color.fromArgb(255, 244, 164, 96); - case 'seagreen': - return Color.fromArgb(255, 46, 139, 87); - case 'seashell': - return Color.fromArgb(255, 255, 245, 238); - case 'sienna': - return Color.fromArgb(255, 160, 82, 45); - case 'silver': - return Color.fromArgb(255, 192, 192, 192); - case 'skyblue': - return Color.fromArgb(255, 135, 206, 235); - case 'slateblue': - return Color.fromArgb(255, 106, 90, 205); - case 'slategray': - return Color.fromArgb(255, 112, 128, 144); - case 'snow': - return Color.fromArgb(255, 255, 250, 250); - case 'springgreen': - return Color.fromArgb(255, 0, 255, 127); - case 'steelblue': - return Color.fromArgb(255, 70, 130, 180); - case 'tan': - return Color.fromArgb(255, 210, 180, 140); - case 'teal': - return Color.fromArgb(255, 0, 128, 128); - case 'thistle': - return Color.fromArgb(255, 216, 191, 216); - case 'tomato': - return Color.fromArgb(255, 255, 99, 71); - case 'turquoise': - return Color.fromArgb(255, 64, 224, 208); - case 'violet': - return Color.fromArgb(255, 238, 130, 238); - case 'wheat': - return Color.fromArgb(255, 245, 222, 179); - case 'white': - return Color.fromArgb(255, 255, 255, 255); - case 'whitesmoke': - return Color.fromArgb(255, 245, 245, 245); - case 'yellow': - return Color.fromArgb(255, 255, 255, 0); - case 'yellowgreen': - return Color.fromArgb(255, 154, 205, 50); - case 'buttonface': - return Color.fromArgb(255, 240, 240, 240); - case 'buttonhighlight': - return Color.fromArgb(255, 255, 255, 255); - case 'buttonshadow': - return Color.fromArgb(255, 160, 160, 160); - case 'gradientactivecaption': - return Color.fromArgb(255, 185, 209, 234); - case 'gradientinactivecaption': - return Color.fromArgb(255, 215, 228, 242); - case 'menubar': - return Color.fromArgb(255, 240, 240, 240); - case 'menuhighlight': - return Color.fromArgb(255, 51, 153, 255); - } - return Color.fromArgb(255, 255, 255, 255); - }; - Color.fromHex = function (data) { - var r = Util.fromHex(data.substr(1, 2)); - var g = Util.fromHex(data.substr(3, 2)); - var b = Util.fromHex(data.substr(5, 2)); - var a = 255; - return Color.fromArgb(a, r, g, b); - }; - Color.fromSimpleHex = function (data) { - var a = Util.fromHex(data.substr(0, 2)); - var r = Util.fromHex(data.substr(2, 2)); - var g = Util.fromHex(data.substr(4, 2)); - var b = Util.fromHex(data.substr(6, 2)); - return Color.fromArgb(a, r, g, b); - }; - Color.fromInt = function (color) { - var r = (color & 4278190080) >>> 24; - var g = (color & 16711680) >>> 16; - var b = (color & 65280) >>> 8; - var a = (color & 255); - return Color.fromArgb(a, r, g, b); - }; - var Color$ = { - toFormat: function () { - if (ss.emptyString(this.name)) { - return ss.format('rgb({0},{1},{2})', this.r.toString(), this.g.toString(), this.b.toString()); - } - else { - return this.name; - } - }, - save: function () { - if (!ss.emptyString(this.name)) { - return ss.format('{0}:{1}', 0, this.name); - } - else { - return ss.format('{0}:{1}:{2}:{3}:{4}', 1, this.a, this.r, this.g, this.b); - } - }, - toString: function () { - if (ss.emptyString(this.name)) { - return ss.format('#{0}{1}{2}', Util.toHex(this.r), Util.toHex(this.g), Util.toHex(this.b)); - } - else { - return this.name; - } - }, - toSimpleHex: function () { - if (ss.emptyString(this.name)) { - return ss.format('{0}{1}{2}{3}', Util.toHex(this.a), Util.toHex(this.r), Util.toHex(this.g), Util.toHex(this.b)); - } - else { - return this.name; - } - }, - _clone: function () { - return Color.fromArgb(this.a, this.r, this.g, this.b); - } - }; - - - // wwtlib.Colors - - function Colors() { - } - Colors.get_black = function () { - return Color.fromArgb(255, 0, 0, 0); - }; - Colors.get_blue = function () { - return Color.fromArgb(255, 0, 0, 255); - }; - Colors.get_brown = function () { - return Color.fromArgb(255, 165, 42, 42); - }; - Colors.get_cyan = function () { - return Color.fromArgb(255, 0, 255, 255); - }; - Colors.get_darkGray = function () { - return Color.fromArgb(255, 169, 169, 169); - }; - Colors.get_gray = function () { - return Color.fromArgb(255, 128, 128, 128); - }; - Colors.get_green = function () { - return Color.fromArgb(255, 0, 255, 0); - }; - Colors.get_lightGray = function () { - return Color.fromArgb(255, 211, 211, 211); - }; - Colors.get_magenta = function () { - return Color.fromArgb(255, 255, 0, 255); - }; - Colors.get_orange = function () { - return Color.fromArgb(255, 255, 165, 0); - }; - Colors.get_purple = function () { - return Color.fromArgb(255, 128, 0, 128); - }; - Colors.get_red = function () { - return Color.fromArgb(255, 255, 0, 0); - }; - Colors.get_transparent = function () { - return Color.fromArgb(0, 255, 255, 255); - }; - Colors.get_white = function () { - return Color.fromArgb(255, 255, 255, 255); - }; - Colors.get_yellow = function () { - return Color.fromArgb(255, 255, 255, 0); - }; - var Colors$ = { - - }; - - - // wwtlib.Constellations - - function Constellations() { - this._pointCount = 0; - this._boundry = false; - this._noInterpollation = false; - this.readOnly = false; - this.radius = 1; - this._drawCount = 0; - this._constellationVertexBuffers = {}; - } - Constellations.createBasic = function (name) { - var temp = new Constellations(); - temp._name = name; - temp._url = null; - temp.lines = []; - var $enum1 = ss.enumerate(ss.keys(Constellations.fullNames)); - while ($enum1.moveNext()) { - var abbrv = $enum1.current; - temp.lines.push(new Lineset(abbrv)); - } - return temp; - }; - Constellations.create = function (name, url, boundry, noInterpollation, resource) { - var temp = new Constellations(); - temp._noInterpollation = noInterpollation; - temp._boundry = boundry; - temp._name = name; - temp._url = url; - temp.getFile(); - return temp; - }; - Constellations.drawConstellationNames = function (renderContext, opacity, drawColor) { - if (Constellations._namesBatch == null) { - Constellations.initializeConstellationNames(); - if (Constellations._namesBatch == null) { - return; - } - } - Constellations._namesBatch.draw(renderContext, opacity, drawColor); - }; - Constellations.initializeConstellationNames = function () { - if (Constellations.constellationCentroids == null) { - return; - } - Constellations._namesBatch = new Text3dBatch(Settings.get_active().get_constellationLabelsHeight()); - var $enum1 = ss.enumerate(ss.keys(Constellations.constellationCentroids)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var centroid = Constellations.constellationCentroids[key]; - var center = Coordinates.raDecTo3dAu(centroid.get_RA(), centroid.get_dec(), 1); - var up = Vector3d.create(0, 1, 0); - var name = centroid.get_name(); - if (centroid.get_name() === 'Triangulum Australe') { - name = ss.replaceString(name, ' ', '\n '); - } - Constellations._namesBatch.add(new Text3d(center, up, name, Settings.get_active().get_constellationLabelsHeight(), 0.000125)); - } - }; - Constellations.drawArtwork = function (renderContext) { - if (Constellations.artwork == null) { - if (Constellations._artFile == null) { - Constellations._artFile = new Folder(); - Constellations._artFile.loadFromUrl(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?W=hevelius'), Constellations._onArtReady); - } - return; - } - Constellations._maxSeperation = Math.max(0.5, Math.cos((renderContext.get_fovAngle() * 2) / 180 * Math.PI)); - var $enum1 = ss.enumerate(Constellations.artwork); - while ($enum1.moveNext()) { - var place = $enum1.current; - var bs = Constellations.pictureBlendStates[place.get_constellation()]; - bs.set_targetState(Settings.get_active().get_constellationArtFilter().isSet(place.get_constellation())); - if (bs.get_state()) { - var reverse = false; - var centroid = Constellations.constellationCentroids[place.get_constellation()]; - if (centroid != null) { - var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); - if (Vector3d.dot(renderContext.get_viewPoint(), pos) > Constellations._maxSeperation) { - renderContext.drawImageSet(place.get_studyImageset(), 100); - } - } - } - } - }; - Constellations._onArtReady = function () { - Constellations._artFile.childLoadCallback(Constellations._loadArtList); - }; - Constellations._loadArtList = function () { - Constellations.artwork = Constellations._artFile.get_places(); - }; - Constellations.initializeConstellations = function () { - if (Constellations.containment == null) { - var url = URLHelpers.singleton.engineAssetUrl('ConstellationNamePositions_EN.txt'); - Constellations._webFileConstNames = new WebFile(url); - Constellations._webFileConstNames.onStateChange = Constellations._loadNames; - Constellations._webFileConstNames.send(); - Constellations.containment = Constellations.create('Constellations', URLHelpers.singleton.engineAssetUrl('constellations.txt'), true, true, true); - } - }; - Constellations._loadNames = function () { - if (Constellations._webFileConstNames.get_state() === 2) { - alert(Constellations._webFileConstNames.get_message()); - } - else if (Constellations._webFileConstNames.get_state() === 1) { - Constellations._centroidsReady(Constellations._webFileConstNames.getText()); - } - }; - Constellations._centroidsReady = function (file) { - Constellations.constellationCentroids = {}; - Constellations.fullNames = {}; - Constellations.abbreviations = {}; - Constellations.bitIDs = {}; - var rows = file.split('\r\n'); - var id = 0; - var line; - var $enum1 = ss.enumerate(rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - line = row; - var data = line.split(','); - Constellations.fullNames[data[1]] = data[0]; - Constellations.abbreviations[data[0]] = data[1]; - Constellations.bitIDs[data[1]] = id++; - Constellations.pictureBlendStates[data[1]] = BlendState.create(true, 1000); - Constellations.constellationCentroids[data[1]] = Place.create(data[0], parseFloat(data[3]), parseFloat(data[2]), 128, data[1], 2, 360); - } - WWTControl.set_renderNeeded(true); - ConstellationFilter.buildConstellationFilters(); - }; - Constellations.fullName = function (name) { - if (ss.keyExists(Constellations.fullNames, name)) { - return Constellations.fullNames[name]; - } - return name; - }; - Constellations.abbreviation = function (name) { - if (Constellations.abbreviations != null && !ss.emptyString(name) && ss.keyExists(Constellations.abbreviations, name)) { - return Constellations.abbreviations[name]; - } - return name; - }; - var Constellations$ = { - get_name: function () { - return this._name; - }, - set_name: function (value) { - this._name = value; - return value; - }, - getFile: function () { - this._webFile = new WebFile(this._url); - this._webFile.onStateChange = ss.bind('fileStateChange', this); - this._webFile.send(); - }, - fileStateChange: function () { - if (this._webFile.get_state() === 2) { - alert(this._webFile.get_message()); - } - else if (this._webFile.get_state() === 1) { - this._loadConstellationData(this._webFile.getText()); - } - }, - _loadConstellationData: function (data) { - if (this._boundry && !this._noInterpollation) { - Constellations.boundries = {}; - } - this.lines = []; - var lineSet = null; - try { - var rows = data.split('\r\n'); - var abrv; - var abrvOld = ''; - var ra; - var dec; - var lastRa = 0; - var type = 0; - var $enum1 = ss.enumerate(rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - var line = row; - if (line.substr(11, 2) === '- ') { - line = line.substr(0, 11) + ' -' + line.substr(13, (line.length - 13)); - } - if (line.substr(11, 2) === '+ ') { - line = line.substr(0, 11) + ' +' + line.substr(13, (line.length - 13)); - } - dec = parseFloat(line.substr(11, 10)); - if (this._noInterpollation) { - ra = parseFloat(line.substr(0, 10)); - } - else { - ra = parseFloat(line.substr(0, 10)); - } - abrv = ss.trim(line.substr(23, 4)); - if (!this._boundry) { - if (!!ss.trim(line.substr(28, 1))) { - type = parseInt(line.substr(28, 1)); - } - } - else { - if (this._noInterpollation && line.substr(28, 1) !== 'O') { - continue; - } - } - if (abrv !== abrvOld) { - type = 3; - lineSet = new Lineset(abrv); - this.lines.push(lineSet); - if (this._boundry && !this._noInterpollation) { - Constellations.boundries[abrv] = lineSet; - } - abrvOld = abrv; - lastRa = 0; - } - if (this._noInterpollation) { - if (Math.abs(ra - lastRa) > 12) { - ra = ra - (24 * (((ra - lastRa) < 0) ? -1 : 1)); - } - lastRa = ra; - } - var starName = null; - if (line.length > 30) { - starName = ss.trim(line.substr(30)); - } - if (starName == null || starName !== 'Empty') { - lineSet.add(ra, dec, type, starName); - } - this._pointCount++; - type = 1; - } - } - catch ($e2) { - } - WWTControl.set_renderNeeded(true); - }, - draw: function (renderContext, showOnlySelected, focusConsteallation, clearExisting) { - Constellations._maxSeperation = Math.max(0.6, Math.cos((renderContext.get_fovAngle() * 2) / 180 * Math.PI)); - this._drawCount = 0; - var lsSelected = null; - if (this.lines == null || Constellations.constellationCentroids == null) { - return; - } - Constellations._constToDraw = focusConsteallation; - var $enum1 = ss.enumerate(this.lines); - while ($enum1.moveNext()) { - var ls = $enum1.current; - if (Constellations._constToDraw === ls.get_name() && this._boundry) { - lsSelected = ls; - } - else if (!showOnlySelected || !this._boundry) { - this._drawSingleConstellation(renderContext, ls, 1); - } - } - if (lsSelected != null) { - this._drawSingleConstellation(renderContext, lsSelected, 1); - } - }, - _drawSingleConstellation: function (renderContext, ls, opacity) { - var reverse = false; - var centroid = Constellations.constellationCentroids[ls.get_name()]; - if (centroid != null) { - var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); - if (Vector3d.dot(renderContext.get_viewPoint(), pos) < Constellations._maxSeperation) { - return; - } - } - if (!ss.keyExists(this._constellationVertexBuffers, ls.get_name())) { - var count = ls.points.length; - var linelist = new SimpleLineList(); - linelist.set_depthBuffered(false); - this._constellationVertexBuffers[ls.get_name()] = linelist; - var currentPoint = new Vector3d(); - var temp; - for (var i = 0; i < count; i++) { - if (!ls.points[i].pointType || !i) { - currentPoint = Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec); - } - else { - temp = Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec); - linelist.addLine(currentPoint, temp); - currentPoint = temp; - } - } - if (this._boundry) { - temp = Coordinates.raDecTo3d(ls.points[0].RA, ls.points[0].dec); - linelist.addLine(currentPoint, temp); - } - } - var col = 'red'; - if (this._boundry) { - if (Constellations._constToDraw !== ls.get_name()) { - col = Settings.get_globalSettings().get_constellationBoundryColor(); - } - else { - col = Settings.get_globalSettings().get_constellationSelectionColor(); - } - } - else { - col = Settings.get_globalSettings().get_constellationFigureColor(); - } - this._constellationVertexBuffers[ls.get_name()].drawLines(renderContext, opacity, Color.load(col)); - }, - _drawSingleConstellationOld: function (renderContext, ls) { - var reverse = false; - var centroid = Constellations.constellationCentroids[ls.get_name()]; - if (centroid != null) { - var pos = Coordinates.raDecTo3d((reverse) ? -centroid.get_RA() - 6 : centroid.get_RA(), (reverse) ? centroid.get_dec() : centroid.get_dec()); - if (Vector3d.dot(renderContext.get_viewPoint(), pos) < Constellations._maxSeperation) { - return; - } - } - this._drawCount++; - var col; - if (this._boundry) { - if (Constellations._constToDraw !== ls.get_name()) { - col = Settings.get_globalSettings().get_constellationBoundryColor(); - } - else { - col = Settings.get_globalSettings().get_constellationSelectionColor(); - } - } - else { - col = Settings.get_globalSettings().get_constellationFigureColor(); - } - if (renderContext.gl == null) { - var ctx = renderContext.device; - var count = ls.points.length; - var lastPoint = new Vector3d(); - ctx.save(); - var linePending = false; - ctx.beginPath(); - ctx.strokeStyle = col; - ctx.lineWidth = 2; - ctx.globalAlpha = 0.25; - for (var i = 0; i < count; i++) { - if (!ls.points[i].pointType || !i) { - if (linePending) { - ctx.stroke(); - } - lastPoint = renderContext.WVP.transform(Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec)); - ctx.moveTo(lastPoint.x, lastPoint.y); - } - else { - var newPoint = renderContext.WVP.transform(Coordinates.raDecTo3d(ls.points[i].RA, ls.points[i].dec)); - ctx.lineTo(newPoint.x, newPoint.y); - linePending = true; - } - } - if (this._boundry) { - ctx.closePath(); - } - ctx.stroke(); - ctx.restore(); - } - else { - } - }, - findConstellationForPoint: function (ra, dec) { - if (dec > 88.402 || this.lines == null) { - return 'UMI'; - } - var $enum1 = ss.enumerate(this.lines); - while ($enum1.moveNext()) { - var ls = $enum1.current; - var count = ls.points.length; - var i; - var j; - var inside = false; - for (i = 0, j = count - 1; i < count; j = i++) { - if ((((ls.points[i].dec <= dec) && (dec < ls.points[j].dec)) || ((ls.points[j].dec <= dec) && (dec < ls.points[i].dec))) && (ra < (ls.points[j].RA - ls.points[i].RA) * (dec - ls.points[i].dec) / (ls.points[j].dec - ls.points[i].dec) + ls.points[i].RA)) { - inside = !inside; - } - } - if (inside) { - return ls.get_name(); - } - } - if (ra > 0) { - return this.findConstellationForPoint(ra - 24, dec); - } - if (dec > 65.5) { - return 'UMI'; - } - if (dec < -65.5) { - return 'OCT'; - } - return 'Error'; - } - }; - - - // wwtlib.Lineset - - function Lineset(name) { - this._name = name; - this.points = []; - } - var Lineset$ = { - get_name: function () { - return this._name; - }, - set_name: function (value) { - this._name = value; - return value; - }, - add: function (ra, dec, pointType, name) { - this.points.push(new Linepoint(ra, dec, pointType, name)); - } - }; - - - // wwtlib.Linepoint - - function Linepoint(ra, dec, type, name) { - this.RA = 0; - this.dec = 0; - this.pointType = 0; - this.name = null; - this.RA = ra; - this.dec = dec; - this.pointType = type; - this.name = name; - } - var Linepoint$ = { - toString: function () { - if (ss.emptyString(this.name)) { - return Coordinates.formatDMS((((this.RA / 360) * 24 + 12) % 24)) + ', ' + Coordinates.formatDMS(this.dec) + ', ' + this.pointType.toString(); - } - else { - return this.name + ', ' + this.pointType.toString(); - } - } - }; - - - // wwtlib.ConstellationFilter - - function ConstellationFilter() { - this.bits = new Array(3); - this.oldBits = new Array(3); - this.blendState = BlendState.create(false, 1000); - this.internal = false; - this.settingsOwned = false; - for (var i = 0; i < 3; i++) { - this.bits[i] = ~this.bits[i]; - this.oldBits[i] = this.bits[i]; - } - } - ConstellationFilter.buildConstellationFilters = function () { - var all = ConstellationFilter.get_allConstellation(); - all.internal = true; - ConstellationFilter.families['AllConstellation'] = all; - ConstellationFilter.families['Zodiacal'] = ConstellationFilter.get_zodiacal(); - ConstellationFilter.families['Ursa Major Family'] = ConstellationFilter.get_ursaMajorFamily(); - ConstellationFilter.families['Perseus Family'] = ConstellationFilter.get_perseusFamily(); - ConstellationFilter.families['Hercules Family'] = ConstellationFilter.get_herculesFamily(); - ConstellationFilter.families['Orion Family'] = ConstellationFilter.get_orionFamily(); - ConstellationFilter.families['Heavenly Waters'] = ConstellationFilter.get_heavenlyWaters(); - ConstellationFilter.families['Bayer Family'] = ConstellationFilter.get_bayerFamily(); - ConstellationFilter.families['La Caille Family'] = ConstellationFilter.get_laCaileFamily(); - }; - ConstellationFilter.saveCustomFilters = function () { - var sb = new ss.StringBuilder(); - var $dict1 = ConstellationFilter.families; - for (var $key2 in $dict1) { - var kv = { key: $key2, value: $dict1[$key2] }; - if (!kv.value.internal) { - sb.append(kv.key); - sb.append(';'); - sb.appendLine(kv.value.toString()); - } - } - }; - ConstellationFilter.get_allConstellation = function () { - var all = new ConstellationFilter(); - all.setAll(true); - return all; - }; - ConstellationFilter.get_zodiacal = function () { - var zodiacal = new ConstellationFilter(); - zodiacal.set('ARI', true); - zodiacal.set('TAU', true); - zodiacal.set('GEM', true); - zodiacal.set('CNC', true); - zodiacal.set('LEO', true); - zodiacal.set('VIR', true); - zodiacal.set('LIB', true); - zodiacal.set('SCO', true); - zodiacal.set('SGR', true); - zodiacal.set('CAP', true); - zodiacal.set('AQR', true); - zodiacal.set('PSC', true); - zodiacal.internal = true; - return zodiacal; - }; - ConstellationFilter.get_ursaMajorFamily = function () { - var uma = new ConstellationFilter(); - uma.set('UMA', true); - uma.set('UMI', true); - uma.set('DRA', true); - uma.set('CVN', true); - uma.set('BOO', true); - uma.set('COM', true); - uma.set('CRB', true); - uma.set('CAM', true); - uma.set('LYN', true); - uma.set('LMI', true); - uma.internal = true; - return uma; - }; - ConstellationFilter.get_perseusFamily = function () { - var Perseus = new ConstellationFilter(); - Perseus.set('CAS', true); - Perseus.set('CEP', true); - Perseus.set('AND', true); - Perseus.set('PER', true); - Perseus.set('PEG', true); - Perseus.set('CET', true); - Perseus.set('AUR', true); - Perseus.set('LAC', true); - Perseus.set('TRI', true); - Perseus.internal = true; - return Perseus; - }; - ConstellationFilter.get_herculesFamily = function () { - var hercules = new ConstellationFilter(); - hercules.set('HER', true); - hercules.set('SGE', true); - hercules.set('AQL', true); - hercules.set('LYR', true); - hercules.set('CYG', true); - hercules.set('VUL', true); - hercules.set('HYA', true); - hercules.set('SEX', true); - hercules.set('CRT', true); - hercules.set('CRV', true); - hercules.set('OPH', true); - hercules.set('SER1', true); - hercules.set('SER2', true); - hercules.set('SCT', true); - hercules.set('CEN', true); - hercules.set('LUP', true); - hercules.set('CRA', true); - hercules.set('ARA', true); - hercules.set('TRA', true); - hercules.set('CRU', true); - hercules.internal = true; - return hercules; - }; - ConstellationFilter.get_orionFamily = function () { - var orion = new ConstellationFilter(); - orion.set('ORI', true); - orion.set('CMA', true); - orion.set('CMI', true); - orion.set('MON', true); - orion.set('LEP', true); - orion.internal = true; - return orion; - }; - ConstellationFilter.get_heavenlyWaters = function () { - var waters = new ConstellationFilter(); - waters.set('DEL', true); - waters.set('EQU', true); - waters.set('ERI', true); - waters.set('PSA', true); - waters.set('CAR', true); - waters.set('PUP', true); - waters.set('VEL', true); - waters.set('PYX', true); - waters.set('COL', true); - waters.internal = true; - return waters; - }; - ConstellationFilter.get_bayerFamily = function () { - var bayer = new ConstellationFilter(); - bayer.set('HYA', true); - bayer.set('DOR', true); - bayer.set('VOL', true); - bayer.set('APS', true); - bayer.set('PAV', true); - bayer.set('GRU', true); - bayer.set('PHE', true); - bayer.set('TUC', true); - bayer.set('IND', true); - bayer.set('CHA', true); - bayer.set('MUS', true); - bayer.internal = true; - return bayer; - }; - ConstellationFilter.get_laCaileFamily = function () { - var LaCaile = new ConstellationFilter(); - LaCaile.set('NOR', true); - LaCaile.set('CIR', true); - LaCaile.set('TEL', true); - LaCaile.set('MIC', true); - LaCaile.set('SCL', true); - LaCaile.set('FOR', true); - LaCaile.set('CAE', true); - LaCaile.set('HOR', true); - LaCaile.set('OCT', true); - LaCaile.set('MEN', true); - LaCaile.set('RET', true); - LaCaile.set('PIC', true); - LaCaile.set('ANT', true); - LaCaile.internal = true; - return LaCaile; - }; - ConstellationFilter.parse = function (val) { - var parts = (val).split(','); - var cf = new ConstellationFilter(); - try { - for (var i = 0; i < 3; i++) { - cf.bits[i] = parseInt(parts[i]); - } - } - catch ($e1) { - } - return cf; - }; - var ConstellationFilter$ = { - _saveBits: function () { - for (var i = 0; i < 3; i++) { - this.oldBits[i] = this.bits[i]; - } - }, - _isChanged: function () { - for (var i = 0; i < 3; i++) { - if (this.oldBits[i] !== this.bits[i]) { - return true; - } - } - return false; - }, - _checkChanged: function () { - if (this._isChanged()) { - this._fireChanged(); - } - }, - isEnabled: function (abbrev) { - var bitID = Constellations.bitIDs[abbrev]; - var index = bitID / 32; - bitID = bitID % 32; - return this.blendState.get_state() && !!((1 << bitID) & this.bits[index]); - }, - isSet: function (abbrev) { - this._saveBits(); - var bitID = Constellations.bitIDs[abbrev]; - var index = ss.truncate((bitID / 32)); - bitID = bitID % 32; - return !!((1 << bitID) & this.bits[index]); - }, - set: function (abbrev, state) { - this._saveBits(); - var bitID = Constellations.bitIDs[abbrev]; - var index = bitID / 32; - bitID = bitID % 32; - if (state) { - this.bits[index] = this.bits[index] | (1 << bitID); - } - else { - this.bits[index] = this.bits[index] ^ (1 << bitID); - } - this._checkChanged(); - }, - setAll: function (state) { - this._saveBits(); - for (var bitID = 0; bitID < 89; bitID++) { - var index = bitID / 32; - var bit = bitID % 32; - if (state) { - this.bits[index] = this.bits[index] | (1 << bit); - } - else { - this.bits[index] = this.bits[index] ^ (1 << bit); - } - } - this._checkChanged(); - }, - setBits: function (bits) { - this._saveBits(); - for (var i = 0; i < 3; i++) { - this.bits[i] = (bits[i * 4]) + ((bits[i * 4 + 1]) << 8) + ((bits[i * 4 + 2]) << 16) + ((bits[i * 4 + 3]) << 24); - } - this._checkChanged(); - }, - getBits: function () { - var bits = new Array(12); - var index = 0; - for (var i = 0; i < 3; i++) { - bits[index++] = this.bits[i]; - bits[index++] = (this.bits[i] >> 8); - bits[index++] = (this.bits[i] >> 16); - bits[index++] = (this.bits[i] >> 24); - } - return bits; - }, - cloneFilter: function (filter) { - this._saveBits(); - for (var i = 0; i < 3; i++) { - this.bits[i] = filter.bits[i]; - } - this._checkChanged(); - }, - clone: function () { - var newFilter = new ConstellationFilter(); - newFilter.cloneFilter(this); - return newFilter; - }, - combine: function (filter) { - this._saveBits(); - for (var i = 0; i < 3; i++) { - this.bits[i] = this.bits[i] | filter.bits[i]; - } - this._checkChanged(); - }, - remove: function (filter) { - this._saveBits(); - for (var i = 0; i < 3; i++) { - this.bits[i] = this.bits[i] & ~filter.bits[i]; - } - this._checkChanged(); - }, - _fireChanged: function () { - if (this.settingsOwned) { - } - }, - toString: function () { - return ss.format('{0},{1},{2}', this.bits[0], this.bits[1], this.bits[2]); - } - }; - - - // wwtlib.PositionTexture - - function PositionTexture() { - this.tu = 0; - this.tv = 0; - this.position = new Vector3d(); - } - PositionTexture.createPos = function (pos, u, v) { - var temp = new PositionTexture(); - temp.tu = u * Tile.uvMultiple; - temp.tv = v * Tile.uvMultiple; - temp.position = pos; - return temp; - }; - PositionTexture.createPosRaw = function (pos, u, v) { - var temp = new PositionTexture(); - temp.tu = u; - temp.tv = v; - temp.position = pos; - return temp; - }; - PositionTexture.createPosSize = function (pos, u, v, width, height) { - var temp = new PositionTexture(); - temp.tu = u * width; - temp.tv = v * height; - temp.position = pos; - return temp; - }; - PositionTexture.create = function (xvalue, yvalue, zvalue, u, v) { - var temp = new PositionTexture(); - temp.position = Vector3d.create(xvalue, yvalue, zvalue); - temp.tu = u * Tile.uvMultiple; - temp.tv = v * Tile.uvMultiple; - return temp; - }; - var PositionTexture$ = { - copy: function () { - var temp = new PositionTexture(); - temp.position = Vector3d.makeCopy(this.position); - temp.tu = this.tu; - temp.tv = this.tv; - return temp; - }, - toString: function () { - return ss.format('{0}, {1}, {2}, {3}, {4}', this.position.x, this.position.y, this.position.z, this.tu, this.tv); - } - }; - - - // wwtlib.PositionColoredTextured - - function PositionColoredTextured() { - this.tu = 0; - this.tv = 0; - this.color = new Color(); - this.position = new Vector3d(); - } - PositionColoredTextured.createPos = function (pos, u, v) { - var temp = new PositionColoredTextured(); - temp.tu = u * Tile.uvMultiple; - temp.tv = v * Tile.uvMultiple; - temp.position = pos; - return temp; - }; - PositionColoredTextured.createPosRaw = function (pos, u, v) { - var temp = new PositionColoredTextured(); - temp.tu = u; - temp.tv = v; - temp.position = pos; - return temp; - }; - PositionColoredTextured.createPosSize = function (pos, u, v, width, height) { - var temp = new PositionColoredTextured(); - temp.tu = u * width; - temp.tv = v * height; - temp.position = pos; - return temp; - }; - PositionColoredTextured.create = function (xvalue, yvalue, zvalue, u, v) { - var temp = new PositionTexture(); - temp.position = Vector3d.create(xvalue, yvalue, zvalue); - temp.tu = u * Tile.uvMultiple; - temp.tv = v * Tile.uvMultiple; - return temp; - }; - var PositionColoredTextured$ = { - copy: function () { - var temp = new PositionTexture(); - temp.position = Vector3d.makeCopy(this.position); - temp.tu = this.tu; - temp.tv = this.tv; - return temp; - }, - toString: function () { - return ss.format('{0}, {1}, {2}, {3}, {4}', this.position.x, this.position.y, this.position.z, this.tu, this.tv); - } - }; - - - // wwtlib.PositionColored - - function PositionColored(pos, color) { - this.color = new Color(); - this.color = color._clone(); - this.position = pos.copy(); - } - var PositionColored$ = { - copy: function () { - var temp = new PositionColored(this.position, this.color); - return temp; - }, - toString: function () { - return ss.format('{0}, {1}, {2}, {3}', this.position.x, this.position.y, this.position.z, this.color.toString()); - } - }; - - - // wwtlib.PositionNormalTexturedTangent - - function PositionNormalTexturedTangent(position, normal, texCoord, tangent) { - this.x = 0; - this.y = 0; - this.z = 0; - this.nx = 0; - this.ny = 0; - this.nz = 0; - this.tu = 0; - this.tv = 0; - this.tanx = 0; - this.tany = 0; - this.tanz = 0; - this.x = position.x; - this.y = position.y; - this.z = position.z; - this.nx = normal.x; - this.ny = normal.y; - this.nz = normal.z; - this.tu = texCoord.x; - this.tv = texCoord.y; - this.tanx = tangent.x; - this.tany = tangent.y; - this.tanz = tangent.z; - } - var PositionNormalTexturedTangent$ = { - get_normal: function () { - return Vector3d.create(this.nx, this.ny, this.nz); - }, - set_normal: function (value) { - this.nx = value.x; - this.ny = value.y; - this.nz = value.z; - return value; - }, - get_position: function () { - return Vector3d.create(this.x, this.y, this.z); - }, - set_position: function (value) { - this.x = value.x; - this.y = value.y; - this.z = value.z; - return value; - }, - get_texCoord: function () { - return Vector2d.create(this.tu, this.tv); - }, - set_texCoord: function (value) { - this.tu = value.x; - this.tv = value.y; - return value; - }, - get_tangent: function () { - return Vector3d.create(this.tanx, this.tany, this.tanz); - }, - set_tangent: function (value) { - this.tanx = value.x; - this.tany = value.y; - this.tanz = value.z; - return value; - }, - toString: function () { - return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, TanX={8}, TanY={9}, TanZ={10}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv, this.tanx, this.tany, this.tanz); - } - }; - - - // wwtlib.Vector3d - - function Vector3d() { - this.x = 0; - this.y = 0; - this.z = 0; - } - Vector3d.create = function (valueX, valueY, valueZ) { - var temp = new Vector3d(); - temp.x = valueX; - temp.y = valueY; - temp.z = valueZ; - return temp; - }; - Vector3d.makeCopy = function (value) { - var temp = new Vector3d(); - temp.x = value.x; - temp.y = value.y; - temp.z = value.z; - return temp; - }; - Vector3d.negate = function (vec) { - return Vector3d.create(-vec.x, -vec.y, -vec.z); - }; - Vector3d.midPoint = function (left, right) { - var result = Vector3d.create((left.x + right.x) / 2, (left.y + right.y) / 2, (left.z + right.z) / 2); - return result; - }; - Vector3d.midPointByLength = function (left, right) { - var result = Vector3d.create((left.x + right.x) / 2, (left.y + right.y) / 2, (left.z + right.z) / 2); - result.normalize(); - result.multiply(left.length()); - return result; - }; - Vector3d.get_empty = function () { - return Vector3d.create(0, 0, 0); - }; - Vector3d.addVectors = function (left, right) { - return Vector3d.create(left.x + right.x, left.y + right.y, left.z + right.z); - }; - Vector3d.cross = function (left, right) { - return Vector3d.create(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); - }; - Vector3d.dot = function (left, right) { - return left.x * right.x + left.y * right.y + left.z * right.z; - }; - Vector3d.getLength = function (source) { - return Math.sqrt(source.x * source.x + source.y * source.y + source.z * source.z); - }; - Vector3d.getLengthSq = function (source) { - return source.x * source.x + source.y * source.y + source.z * source.z; - }; - Vector3d.lerp = function (left, right, interpolater) { - return Vector3d.create(left.x * (1 - interpolater) + right.x * interpolater, left.y * (1 - interpolater) + right.y * interpolater, left.z * (1 - interpolater) + right.z * interpolater); - }; - Vector3d.midpoint = function (left, right) { - var tmp = Vector3d.create(left.x * (0.5) + right.x * 0.5, left.y * (0.5) + right.y * 0.5, left.z * (0.5) + right.z * 0.5); - tmp.normalize(); - return tmp; - }; - Vector3d.slerp = function (left, right, interpolater) { - var dot = Vector3d.dot(left, right); - while (dot < 0.98) { - var middle = Vector3d.midpoint(left, right); - if (interpolater > 0.5) { - left = middle; - interpolater -= 0.5; - interpolater *= 2; - } - else { - right = middle; - interpolater *= 2; - } - dot = Vector3d.dot(left, right); - } - var tmp = Vector3d.lerp(left, right, interpolater); - tmp.normalize(); - return tmp; - }; - Vector3d.multiplyScalar = function (source, f) { - var result = source.copy(); - result.multiply(f); - return result; - }; - Vector3d.scale = function (source, scalingFactor) { - var result = source; - result.multiply(scalingFactor); - return result; - }; - Vector3d.subtractVectors = function (left, right) { - var result = left.copy(); - result.subtract(right); - return result; - }; - Vector3d.parse = function (data) { - var newVector = new Vector3d(); - var list = data.split(','); - if (list.length === 3) { - newVector.x = parseFloat(list[0]); - newVector.y = parseFloat(list[1]); - newVector.z = parseFloat(list[2]); - } - return newVector; - }; - Vector3d._transformCoordinate = function (vector3d, mat) { - return mat.transform(vector3d); - }; - var Vector3d$ = { - set: function (valueX, valueY, valueZ) { - this.x = valueX; - this.y = valueY; - this.z = valueZ; - }, - copy: function () { - var temp = new Vector3d(); - temp.x = this.x; - temp.y = this.y; - temp.z = this.z; - return temp; - }, - round: function () { - this.x = ss.truncate((this.x * 65536)) / 65536; - this.y = ss.truncate((this.y * 65536)) / 65536; - this.z = ss.truncate((this.z * 65536)) / 65536; - }, - add: function (source) { - this.x += source.x; - this.y += source.y; - this.z += source.z; - }, - length: function () { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - }, - lengthSq: function () { - return this.x * this.x + this.y * this.y + this.z * this.z; - }, - multiply: function (s) { - this.x *= s; - this.y *= s; - this.z *= s; - }, - normalize: function () { - var length = this.length(); - if (!!length) { - this.x /= length; - this.y /= length; - this.z /= length; - } - }, - rotateX: function (radians) { - var zTemp; - var yTemp; - yTemp = this.y * Math.cos(radians) - this.z * Math.sin(radians); - zTemp = this.y * Math.sin(radians) + this.z * Math.cos(radians); - this.z = zTemp; - this.y = yTemp; - }, - rotateZ: function (radians) { - var xTemp; - var yTemp; - xTemp = this.x * Math.cos(radians) - this.y * Math.sin(radians); - yTemp = this.x * Math.sin(radians) + this.y * Math.cos(radians); - this.y = yTemp; - this.x = xTemp; - }, - rotateY: function (radians) { - var zTemp; - var xTemp; - zTemp = this.z * Math.cos(radians) - this.x * Math.sin(radians); - xTemp = this.z * Math.sin(radians) + this.x * Math.cos(radians); - this.x = xTemp; - this.z = zTemp; - }, - subtract: function (source) { - this.x -= source.x; - this.y -= source.y; - this.z -= source.z; - return this; - }, - toString: function () { - return ss.format('{0}, {1}, {2}', this.x, this.y, this.z); - }, - toSpherical: function () { - var ascention; - var declination; - var radius = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - var XZ = Math.sqrt(this.x * this.x + this.z * this.z); - declination = Math.asin(this.y / radius); - if (!XZ) { - ascention = 0; - } - else if (0 <= this.x) { - ascention = Math.asin(this.z / XZ); - } - else { - ascention = Math.PI - Math.asin(this.z / XZ); - } - return Vector2d.create(((ascention + Math.PI) % (2 * Math.PI)), (declination + (Math.PI / 2))); - }, - toRaDec: function () { - var point = this.toSpherical(); - point.x = point.x / Math.PI * 12; - point.y = (point.y / Math.PI * 180) - 90; - return point; - }, - distanceToLine: function (x1, x2) { - var t1 = Vector3d.subtractVectors(x2, x1); - var t2 = Vector3d.subtractVectors(x1, this); - var t3 = Vector3d.cross(t1, t2); - var d1 = t3.length(); - var t4 = Vector3d.subtractVectors(x2, x1); - var d2 = t4.length(); - return d1 / d2; - }, - _transformByMatrics: function (lookAtAdjust) { - var temp = lookAtAdjust.transform(this); - this.x = temp.x; - this.y = temp.y; - this.z = temp.z; - } - }; - - - // wwtlib.Vector2d - - function Vector2d() { - this.x = 0; - this.y = 0; - } - Vector2d.lerp = function (left, right, interpolater) { - return Vector2d.create(left.x * (1 - interpolater) + right.x * interpolater, left.y * (1 - interpolater) + right.y * interpolater); - }; - Vector2d.cartesianToSpherical2 = function (vector) { - var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var longitude = Math.atan2(vector.z, vector.x); - var latitude = Math.asin(vector.y / rho); - return Vector2d.create(longitude / Math.PI * 180, latitude / Math.PI * 180); - }; - Vector2d.average3d = function (left, right) { - var pntLeft = Coordinates.geoTo3dDouble(left.y, left.x); - var pntRight = Coordinates.geoTo3dDouble(right.y, right.x); - var pntOut = Vector3d.addVectors(pntLeft, pntRight); - pntOut.multiply(0.5); - pntOut.normalize(); - return Vector2d.cartesianToSpherical2(pntOut); - }; - Vector2d.create = function (x, y) { - var temp = new Vector2d(); - temp.x = x; - temp.y = y; - return temp; - }; - Vector2d.subtract = function (left, right) { - return Vector2d.create(left.x - right.x, left.y - right.y); - }; - var Vector2d$ = { - distance3d: function (pointB) { - var pnt1 = Coordinates.geoTo3dDouble(pointB.y, pointB.x); - var pnt2 = Coordinates.geoTo3dDouble(this.y, this.x); - var pntDiff = Vector3d.subtractVectors(pnt1, pnt2); - return pntDiff.length() / Math.PI * 180; - }, - get_length: function () { - return Math.sqrt(this.x * this.x + this.y * this.y); - }, - normalize: function () { - var length = this.get_length(); - if (!!length) { - this.x /= length; - this.y /= length; - } - }, - extend: function (factor) { - this.x = this.x * factor; - this.y = this.y * factor; - } - }; - - - // wwtlib.Matrix3d - - function Matrix3d() { - this._m11 = 0; - this._m12 = 0; - this._m13 = 0; - this._m14 = 0; - this._m21 = 0; - this._m22 = 0; - this._m23 = 0; - this._m24 = 0; - this._m31 = 0; - this._m32 = 0; - this._m33 = 0; - this._m34 = 0; - this._offsetX = 0; - this._offsetY = 0; - this._offsetZ = 0; - this._m44 = 0; - this._isNotKnownToBeIdentity = false; - } - Matrix3d.create = function (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, offsetX, offsetY, offsetZ, m44) { - var temp = new Matrix3d(); - temp._m11 = m11; - temp._m12 = m12; - temp._m13 = m13; - temp._m14 = m14; - temp._m21 = m21; - temp._m22 = m22; - temp._m23 = m23; - temp._m24 = m24; - temp._m31 = m31; - temp._m32 = m32; - temp._m33 = m33; - temp._m34 = m34; - temp._offsetX = offsetX; - temp._offsetY = offsetY; - temp._offsetZ = offsetZ; - temp._m44 = m44; - temp._isNotKnownToBeIdentity = true; - return temp; - }; - Matrix3d.get_identity = function () { - var temp = new Matrix3d(); - temp.set(Matrix3d._s_identity); - return temp; - }; - Matrix3d.multiplyMatrix = function (matrix1, matrix2) { - if (matrix1.get__isDistinguishedIdentity()) { - return matrix2; - } - if (matrix2.get__isDistinguishedIdentity()) { - return matrix1; - } - return Matrix3d.create((((matrix1._m11 * matrix2._m11) + (matrix1._m12 * matrix2._m21)) + (matrix1._m13 * matrix2._m31)) + (matrix1._m14 * matrix2._offsetX), (((matrix1._m11 * matrix2._m12) + (matrix1._m12 * matrix2._m22)) + (matrix1._m13 * matrix2._m32)) + (matrix1._m14 * matrix2._offsetY), (((matrix1._m11 * matrix2._m13) + (matrix1._m12 * matrix2._m23)) + (matrix1._m13 * matrix2._m33)) + (matrix1._m14 * matrix2._offsetZ), (((matrix1._m11 * matrix2._m14) + (matrix1._m12 * matrix2._m24)) + (matrix1._m13 * matrix2._m34)) + (matrix1._m14 * matrix2._m44), (((matrix1._m21 * matrix2._m11) + (matrix1._m22 * matrix2._m21)) + (matrix1._m23 * matrix2._m31)) + (matrix1._m24 * matrix2._offsetX), (((matrix1._m21 * matrix2._m12) + (matrix1._m22 * matrix2._m22)) + (matrix1._m23 * matrix2._m32)) + (matrix1._m24 * matrix2._offsetY), (((matrix1._m21 * matrix2._m13) + (matrix1._m22 * matrix2._m23)) + (matrix1._m23 * matrix2._m33)) + (matrix1._m24 * matrix2._offsetZ), (((matrix1._m21 * matrix2._m14) + (matrix1._m22 * matrix2._m24)) + (matrix1._m23 * matrix2._m34)) + (matrix1._m24 * matrix2._m44), (((matrix1._m31 * matrix2._m11) + (matrix1._m32 * matrix2._m21)) + (matrix1._m33 * matrix2._m31)) + (matrix1._m34 * matrix2._offsetX), (((matrix1._m31 * matrix2._m12) + (matrix1._m32 * matrix2._m22)) + (matrix1._m33 * matrix2._m32)) + (matrix1._m34 * matrix2._offsetY), (((matrix1._m31 * matrix2._m13) + (matrix1._m32 * matrix2._m23)) + (matrix1._m33 * matrix2._m33)) + (matrix1._m34 * matrix2._offsetZ), (((matrix1._m31 * matrix2._m14) + (matrix1._m32 * matrix2._m24)) + (matrix1._m33 * matrix2._m34)) + (matrix1._m34 * matrix2._m44), (((matrix1._offsetX * matrix2._m11) + (matrix1._offsetY * matrix2._m21)) + (matrix1._offsetZ * matrix2._m31)) + (matrix1._m44 * matrix2._offsetX), (((matrix1._offsetX * matrix2._m12) + (matrix1._offsetY * matrix2._m22)) + (matrix1._offsetZ * matrix2._m32)) + (matrix1._m44 * matrix2._offsetY), (((matrix1._offsetX * matrix2._m13) + (matrix1._offsetY * matrix2._m23)) + (matrix1._offsetZ * matrix2._m33)) + (matrix1._m44 * matrix2._offsetZ), (((matrix1._offsetX * matrix2._m14) + (matrix1._offsetY * matrix2._m24)) + (matrix1._offsetZ * matrix2._m34)) + (matrix1._m44 * matrix2._m44)); - }; - Matrix3d.lookAtLH = function (cameraPosition, cameraTarget, cameraUpVector) { - var zaxis = Vector3d.subtractVectors(cameraTarget, cameraPosition); - zaxis.normalize(); - var xaxis = Vector3d.cross(cameraUpVector, zaxis); - xaxis.normalize(); - var yaxis = Vector3d.cross(zaxis, xaxis); - var mat = Matrix3d.create(xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, -Vector3d.dot(xaxis, cameraPosition), -Vector3d.dot(yaxis, cameraPosition), -Vector3d.dot(zaxis, cameraPosition), 1); - return mat; - }; - Matrix3d._createIdentity = function () { - var matrixd = Matrix3d.create(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - matrixd.set__isDistinguishedIdentity(true); - return matrixd; - }; - Matrix3d.equals = function (matrix1, matrix2) { - if (matrix1.get__isDistinguishedIdentity() || matrix2.get__isDistinguishedIdentity()) { - return (matrix1.get_isIdentity() === matrix2.get_isIdentity()); - } - if ((((matrix1.get_m11() === matrix2.get_m11() && matrix1.get_m12() === matrix2.get_m12()) && (matrix1.get_m13() === matrix2.get_m13() && matrix1.get_m14() === matrix2.get_m14())) && ((matrix1.get_m21() === matrix2.get_m21() && matrix1.get_m22() === matrix2.get_m22()) && (matrix1.get_m23() === matrix2.get_m23() && matrix1.get_m24() === matrix2.get_m24()))) && (((matrix1.get_m31() === matrix2.get_m31() && matrix1.get_m32() === matrix2.get_m32()) && (matrix1.get_m33() === matrix2.get_m33() && matrix1.get_m34() === matrix2.get_m34())) && ((matrix1.get_offsetX() === matrix2.get_offsetX() && matrix1.get_offsetY() === matrix2.get_offsetY()) && matrix1.get_offsetZ() === matrix2.get_offsetZ()))) { - return matrix1.get_m44() === matrix2.get_m44(); - } - return false; - }; - Matrix3d.fromMatrix2d = function (mat) { - var mat3d = Matrix3d._createIdentity(); - mat3d.set_m11(mat.m11); - mat3d.set_m12(mat.m12); - mat3d.set_m13(mat.m13); - mat3d.set_m21(mat.m21); - mat3d.set_m22(mat.m22); - mat3d.set_m23(mat.m23); - mat3d.set_m31(mat.m31); - mat3d.set_m32(mat.m32); - mat3d.set_m33(mat.m33); - mat3d._isNotKnownToBeIdentity = true; - return mat3d; - }; - Matrix3d.rotationYawPitchRoll = function (heading, pitch, roll) { - var matX = Matrix3d._rotationX(pitch); - var matY = Matrix3d._rotationY(heading); - var matZ = Matrix3d._rotationZ(roll); - return Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(matY, matX), matZ); - }; - Matrix3d._rotationY = function (p) { - var v = p; - var matNew = Matrix3d.get_identity(); - matNew._m11 = Math.cos(v); - matNew._m22 = 1; - matNew._m31 = Math.sin(v); - matNew._m13 = -Math.sin(v); - matNew._m33 = Math.cos(v); - matNew._isNotKnownToBeIdentity = true; - return matNew; - }; - Matrix3d._rotationX = function (p) { - var v = p; - var matNew = Matrix3d.get_identity(); - matNew._m11 = 1; - matNew._m22 = Math.cos(v); - matNew._m32 = -Math.sin(v); - matNew._m23 = Math.sin(v); - matNew._m33 = Math.cos(v); - matNew._isNotKnownToBeIdentity = true; - return matNew; - }; - Matrix3d._rotationZ = function (p) { - var v = p; - var matNew = Matrix3d.get_identity(); - matNew._m11 = Math.cos(v); - matNew._m21 = -Math.sin(v); - matNew._m12 = Math.sin(v); - matNew._m22 = Math.cos(v); - matNew._m33 = 1; - matNew._isNotKnownToBeIdentity = true; - return matNew; - }; - Matrix3d._scaling = function (x, y, z) { - var matNew = Matrix3d.get_identity(); - matNew._m11 = x; - matNew._m22 = y; - matNew._m33 = z; - matNew._isNotKnownToBeIdentity = true; - return matNew; - }; - Matrix3d._translationXYZ = function (x, y, z) { - var matNew = Matrix3d.get_identity(); - matNew.set_offsetX(x); - matNew.set_offsetY(y); - matNew.set_offsetZ(z); - matNew._isNotKnownToBeIdentity = true; - return matNew; - }; - Matrix3d.perspectiveFovLH = function (fieldOfViewY, aspectRatio, znearPlane, zfarPlane) { - var h = 1 / Math.tan(fieldOfViewY / 2); - var w = h / aspectRatio; - return Matrix3d.create(w, 0, 0, 0, 0, h, 0, 0, 0, 0, zfarPlane / (zfarPlane - znearPlane), 1, 0, 0, -znearPlane * zfarPlane / (zfarPlane - znearPlane), 0); - }; - Matrix3d.perspectiveOffCenterLH = function (left, right, bottom, top, znearPlane, zfarPlane) { - return Matrix3d.create(2 * znearPlane / (right - left), 0, 0, 0, 0, 2 * znearPlane / (top - bottom), 0, 0, (left + right) / (left - right), (top + bottom) / (bottom - top), zfarPlane / (zfarPlane - znearPlane), 1, 0, 0, znearPlane * zfarPlane / (znearPlane - zfarPlane), 0); - }; - Matrix3d.invertMatrix = function (matrix3d) { - var mat = matrix3d.clone(); - mat.invert(); - return mat; - }; - Matrix3d.translation = function (vector3d) { - return Matrix3d._translationXYZ(vector3d.x, vector3d.y, vector3d.z); - }; - Matrix3d.getMapMatrix = function (center, fieldWidth, fieldHeight, rotation) { - var offsetX = 0; - var offsetY = 0; - offsetX = -((center.get_lng() + 180 - (fieldWidth / 2)) / 360); - offsetY = -(1 - ((center.get_lat() + 90 + (fieldHeight / 2)) / 180)); - var mat = new Matrix2d(); - var scaleX = 0; - var scaleY = 0; - scaleX = 360 / fieldWidth; - scaleY = 180 / fieldHeight; - mat = Matrix2d.multiply(mat, Matrix2d.translation(offsetX, offsetY)); - mat = Matrix2d.multiply(mat, Matrix2d.scaling(scaleX, scaleY)); - if (!!rotation) { - mat = Matrix2d.multiply(mat, Matrix2d.translation(-0.5, -0.5)); - mat = Matrix2d.multiply(mat, Matrix2d.rotation(rotation)); - mat = Matrix2d.multiply(mat, Matrix2d.translation(0.5, 0.5)); - } - return Matrix3d.fromMatrix2d(mat); - }; - var Matrix3d$ = { - clone: function () { - var tmp = new Matrix3d(); - tmp.set(this); - return tmp; - }, - setIdentity: function () { - this.set(Matrix3d._s_identity); - }, - set: function (mat) { - this._m11 = mat._m11; - this._m12 = mat._m12; - this._m13 = mat._m13; - this._m14 = mat._m14; - this._m21 = mat._m21; - this._m22 = mat._m22; - this._m23 = mat._m23; - this._m24 = mat._m24; - this._m31 = mat._m31; - this._m32 = mat._m32; - this._m33 = mat._m33; - this._m34 = mat._m34; - this._offsetX = mat._offsetX; - this._offsetY = mat._offsetY; - this._offsetZ = mat._offsetZ; - this._m44 = mat._m44; - this._isNotKnownToBeIdentity = true; - }, - floatArray: function () { - var array = new Array(16); - array[0] = this._m11; - array[1] = this._m12; - array[2] = this._m13; - array[3] = this._m14; - array[4] = this._m21; - array[5] = this._m22; - array[6] = this._m23; - array[7] = this._m24; - array[8] = this._m31; - array[9] = this._m32; - array[10] = this._m33; - array[11] = this._m34; - array[12] = this._offsetX; - array[13] = this._offsetY; - array[14] = this._offsetZ; - array[15] = this._m44; - return array; - }, - get_isIdentity: function () { - if (this.get__isDistinguishedIdentity()) { - return true; - } - if (((((this._m11 === 1) && (!this._m12)) && ((!this._m13) && (!this._m14))) && (((!this._m21) && (this._m22 === 1)) && ((!this._m23) && (!this._m24)))) && ((((!this._m31) && (!this._m32)) && ((this._m33 === 1) && (!this._m34))) && (((!this._offsetX) && (!this._offsetY)) && ((!this._offsetZ) && (this._m44 === 1))))) { - this.set__isDistinguishedIdentity(true); - return true; - } - return false; - }, - prepend: function (matrix) { - this.set(Matrix3d.multiplyMatrix(matrix, this)); - }, - append: function (matrix) { - this._multiply(matrix); - }, - scale: function (scale) { - if (this.get__isDistinguishedIdentity()) { - this._setScaleMatrix(scale); - } - else { - this._m11 *= scale.x; - this._m12 *= scale.y; - this._m13 *= scale.z; - this._m21 *= scale.x; - this._m22 *= scale.y; - this._m23 *= scale.z; - this._m31 *= scale.x; - this._m32 *= scale.y; - this._m33 *= scale.z; - this._offsetX *= scale.x; - this._offsetY *= scale.y; - this._offsetZ *= scale.z; - } - }, - scalePrepend: function (scale) { - if (this.get__isDistinguishedIdentity()) { - this._setScaleMatrix(scale); - } - else { - this._m11 *= scale.x; - this._m12 *= scale.x; - this._m13 *= scale.x; - this._m14 *= scale.x; - this._m21 *= scale.y; - this._m22 *= scale.y; - this._m23 *= scale.y; - this._m24 *= scale.y; - this._m31 *= scale.z; - this._m32 *= scale.z; - this._m33 *= scale.z; - this._m34 *= scale.z; - } - }, - scaleAt: function (scale, center) { - if (this.get__isDistinguishedIdentity()) { - this._setScaleMatrixCenter(scale, center); - } - else { - var num = this._m14 * center.x; - this._m11 = num + (scale.x * (this._m11 - num)); - num = this._m14 * center.y; - this._m12 = num + (scale.y * (this._m12 - num)); - num = this._m14 * center.z; - this._m13 = num + (scale.z * (this._m13 - num)); - num = this._m24 * center.x; - this._m21 = num + (scale.x * (this._m21 - num)); - num = this._m24 * center.y; - this._m22 = num + (scale.y * (this._m22 - num)); - num = this._m24 * center.z; - this._m23 = num + (scale.z * (this._m23 - num)); - num = this._m34 * center.x; - this._m31 = num + (scale.x * (this._m31 - num)); - num = this._m34 * center.y; - this._m32 = num + (scale.y * (this._m32 - num)); - num = this._m34 * center.z; - this._m33 = num + (scale.z * (this._m33 - num)); - num = this._m44 * center.x; - this._offsetX = num + (scale.x * (this._offsetX - num)); - num = this._m44 * center.y; - this._offsetY = num + (scale.y * (this._offsetY - num)); - num = this._m44 * center.z; - this._offsetZ = num + (scale.z * (this._offsetZ - num)); - } - }, - scaleAtPrepend: function (scale, center) { - if (this.get__isDistinguishedIdentity()) { - this._setScaleMatrixCenter(scale, center); - } - else { - var num3 = center.x - (center.x * scale.x); - var num2 = center.y - (center.y * scale.y); - var num = center.z - (center.z * scale.z); - this._offsetX += ((this._m11 * num3) + (this._m21 * num2)) + (this._m31 * num); - this._offsetY += ((this._m12 * num3) + (this._m22 * num2)) + (this._m32 * num); - this._offsetZ += ((this._m13 * num3) + (this._m23 * num2)) + (this._m33 * num); - this._m44 += ((this._m14 * num3) + (this._m24 * num2)) + (this._m34 * num); - this._m11 *= scale.x; - this._m12 *= scale.x; - this._m13 *= scale.x; - this._m14 *= scale.x; - this._m21 *= scale.y; - this._m22 *= scale.y; - this._m23 *= scale.y; - this._m24 *= scale.y; - this._m31 *= scale.z; - this._m32 *= scale.z; - this._m33 *= scale.z; - this._m34 *= scale.z; - } - }, - translate: function (offset) { - if (this.get__isDistinguishedIdentity()) { - this._setTranslationMatrix(offset); - } - else { - this._m11 += this._m14 * offset.x; - this._m12 += this._m14 * offset.y; - this._m13 += this._m14 * offset.z; - this._m21 += this._m24 * offset.x; - this._m22 += this._m24 * offset.y; - this._m23 += this._m24 * offset.z; - this._m31 += this._m34 * offset.x; - this._m32 += this._m34 * offset.y; - this._m33 += this._m34 * offset.z; - this._offsetX += this._m44 * offset.x; - this._offsetY += this._m44 * offset.y; - this._offsetZ += this._m44 * offset.z; - } - }, - translatePrepend: function (offset) { - if (this.get__isDistinguishedIdentity()) { - this._setTranslationMatrix(offset); - } - else { - this._offsetX += ((this._m11 * offset.x) + (this._m21 * offset.y)) + (this._m31 * offset.z); - this._offsetY += ((this._m12 * offset.x) + (this._m22 * offset.y)) + (this._m32 * offset.z); - this._offsetZ += ((this._m13 * offset.x) + (this._m23 * offset.y)) + (this._m33 * offset.z); - this._m44 += ((this._m14 * offset.x) + (this._m24 * offset.y)) + (this._m34 * offset.z); - } - }, - transform: function (point) { - var temp = new Vector3d(); - if (!this.get__isDistinguishedIdentity()) { - var x = point.x; - var y = point.y; - var z = point.z; - temp.x = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; - temp.y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; - temp.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - if (!this.get_isAffine()) { - var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - temp.x /= num4; - temp.y /= num4; - temp.z /= num4; - } - } - return temp; - }, - _transformTo: function (input, output) { - output.x = (((input.x * this._m11) + (input.y * this._m21)) + (input.z * this._m31)) + this._offsetX; - output.y = (((input.x * this._m12) + (input.y * this._m22)) + (input.z * this._m32)) + this._offsetY; - output.z = (((input.x * this._m13) + (input.y * this._m23)) + (input.z * this._m33)) + this._offsetZ; - var num4 = (((input.x * this._m14) + (input.y * this._m24)) + (input.z * this._m34)) + this._m44; - output.x /= num4; - output.y /= num4; - output.z /= num4; - }, - transformArray: function (points) { - if (points != null) { - for (var i = 0; i < points.length; i++) { - this._multiplyPoint(points[i]); - } - } - }, - projectArrayToScreen: function (input, output) { - if (input != null && output != null) { - var affine = this.get_isAffine(); - for (var i = 0; i < input.length; i++) { - var x = input[i].x; - var y = input[i].y; - var z = input[i].z; - if (affine) { - output[i].x = ((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX); - output[i].y = ((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY); - output[i].z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - } - else { - var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - output[i].x = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4); - output[i].y = (((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4); - output[i].z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; - } - } - } - }, - projectToScreen: function (input, width, height) { - var output = new Vector3d(); - var x = input.x; - var y = input.y; - var z = input.z; - if (this.get_isAffine()) { - output.x = (((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) + 0.5) * width; - output.y = (-((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) + 0.5) * height; - output.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - } - else { - var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - output.x = ((((((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX) / num4) + 0.5) * width; - output.y = (-(((((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY) / num4) + 0.5) * height; - output.z = ((((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ) / num4; - } - return output; - }, - get_isAffine: function () { - if (this.get__isDistinguishedIdentity()) { - return true; - } - if (((!this._m14) && (!this._m24)) && (!this._m34)) { - return (this._m44 === 1); - } - return false; - }, - get_determinant: function () { - if (this.get__isDistinguishedIdentity()) { - return 1; - } - if (this.get_isAffine()) { - return this._getNormalizedAffineDeterminant(); - } - var num6 = (this._m13 * this._m24) - (this._m23 * this._m14); - var num5 = (this._m13 * this._m34) - (this._m33 * this._m14); - var num4 = (this._m13 * this._m44) - (this._offsetZ * this._m14); - var num3 = (this._m23 * this._m34) - (this._m33 * this._m24); - var num2 = (this._m23 * this._m44) - (this._offsetZ * this._m24); - var num = (this._m33 * this._m44) - (this._offsetZ * this._m34); - var num10 = ((this._m22 * num5) - (this._m32 * num6)) - (this._m12 * num3); - var num9 = ((this._m12 * num2) - (this._m22 * num4)) + (this._offsetY * num6); - var num8 = ((this._m32 * num4) - (this._offsetY * num5)) - (this._m12 * num); - var num7 = ((this._m22 * num) - (this._m32 * num2)) + (this._offsetY * num3); - return ((((this._offsetX * num10) + (this._m31 * num9)) + (this._m21 * num8)) + (this._m11 * num7)); - }, - get_hasInverse: function () { - return !DoubleUtilities.isZero(this.get_determinant()); - }, - invert: function () { - if (!this._invertCore()) { - return; - } - }, - transpose: function () { - var that = new Matrix3d(); - that.set(this); - this._m12 = that._m21; - this._m13 = that._m31; - this._m14 = that._offsetX; - this._m23 = that._m32; - this._m24 = that._offsetY; - this._m34 = that._offsetZ; - this._m21 = that._m12; - this._m31 = that._m13; - this._offsetX = that._m14; - this._m32 = that._m23; - this._offsetY = that._m24; - this._offsetZ = that._m34; - }, - get_m11: function () { - if (this.get__isDistinguishedIdentity()) { - return 1; - } - return this._m11; - }, - set_m11: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m11 = value; - return value; - }, - get_m12: function () { - return this._m12; - }, - set_m12: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m12 = value; - return value; - }, - get_m13: function () { - return this._m13; - }, - set_m13: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m13 = value; - return value; - }, - get_m14: function () { - return this._m14; - }, - set_m14: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m14 = value; - return value; - }, - get_m21: function () { - return this._m21; - }, - set_m21: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m21 = value; - return value; - }, - get_m22: function () { - if (this.get__isDistinguishedIdentity()) { - return 1; - } - return this._m22; - }, - set_m22: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m22 = value; - return value; - }, - get_m23: function () { - return this._m23; - }, - set_m23: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m23 = value; - return value; - }, - get_m24: function () { - return this._m24; - }, - set_m24: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m24 = value; - return value; - }, - get_m31: function () { - return this._m31; - }, - set_m31: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m31 = value; - return value; - }, - get_m32: function () { - return this._m32; - }, - set_m32: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m32 = value; - return value; - }, - get_m33: function () { - if (this.get__isDistinguishedIdentity()) { - return 1; - } - return this._m33; - }, - set_m33: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m33 = value; - return value; - }, - get_m34: function () { - return this._m34; - }, - set_m34: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m34 = value; - return value; - }, - get_m41: function () { - return this.get_offsetX(); - }, - set_m41: function (value) { - this.set_offsetX(value); - return value; - }, - get_m42: function () { - return this.get_offsetY(); - }, - set_m42: function (value) { - this.set_offsetY(value); - return value; - }, - get_m43: function () { - return this.get_offsetZ(); - }, - set_m43: function (value) { - this.set_offsetZ(value); - return value; - }, - get_offsetX: function () { - return this._offsetX; - }, - set_offsetX: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._offsetX = value; - return value; - }, - get_offsetY: function () { - return this._offsetY; - }, - set_offsetY: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._offsetY = value; - return value; - }, - get_offsetZ: function () { - return this._offsetZ; - }, - set_offsetZ: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._offsetZ = value; - return value; - }, - get_m44: function () { - if (this.get__isDistinguishedIdentity()) { - return 1; - } - return this._m44; - }, - set_m44: function (value) { - if (this.get__isDistinguishedIdentity()) { - this.set(Matrix3d._s_identity); - this.set__isDistinguishedIdentity(false); - } - this._m44 = value; - return value; - }, - _setScaleMatrix: function (scale) { - this._m11 = scale.x; - this._m22 = scale.y; - this._m33 = scale.z; - this._m44 = 1; - this.set__isDistinguishedIdentity(false); - }, - _setScaleMatrixCenter: function (scale, center) { - this._m11 = scale.x; - this._m22 = scale.y; - this._m33 = scale.z; - this._m44 = 1; - this._offsetX = center.x - (center.x * scale.x); - this._offsetY = center.y - (center.y * scale.y); - this._offsetZ = center.z - (center.z * scale.z); - this.set__isDistinguishedIdentity(false); - }, - _setTranslationMatrix: function (offset) { - this._m11 = this._m22 = this._m33 = this._m44 = 1; - this._offsetX = offset.x; - this._offsetY = offset.y; - this._offsetZ = offset.z; - this.set__isDistinguishedIdentity(false); - }, - _multiplyPoint: function (point) { - if (!this.get__isDistinguishedIdentity()) { - var x = point.x; - var y = point.y; - var z = point.z; - point.x = (((x * this._m11) + (y * this._m21)) + (z * this._m31)) + this._offsetX; - point.y = (((x * this._m12) + (y * this._m22)) + (z * this._m32)) + this._offsetY; - point.z = (((x * this._m13) + (y * this._m23)) + (z * this._m33)) + this._offsetZ; - if (!this.get_isAffine()) { - var num4 = (((x * this._m14) + (y * this._m24)) + (z * this._m34)) + this._m44; - point.x /= num4; - point.y /= num4; - point.z /= num4; - } - } - }, - multiplyVector: function (vector) { - if (!this.get__isDistinguishedIdentity()) { - var x = vector.x; - var y = vector.y; - var z = vector.z; - vector.x = ((x * this._m11) + (y * this._m21)) + (z * this._m31); - vector.y = ((x * this._m12) + (y * this._m22)) + (z * this._m32); - vector.z = ((x * this._m13) + (y * this._m23)) + (z * this._m33); - } - }, - _getNormalizedAffineDeterminant: function () { - var num3 = (this._m12 * this._m23) - (this._m22 * this._m13); - var num2 = (this._m32 * this._m13) - (this._m12 * this._m33); - var num = (this._m22 * this._m33) - (this._m32 * this._m23); - return (((this._m31 * num3) + (this._m21 * num2)) + (this._m11 * num)); - }, - _normalizedAffineInvert: function () { - var num11 = (this._m12 * this._m23) - (this._m22 * this._m13); - var num10 = (this._m32 * this._m13) - (this._m12 * this._m33); - var num9 = (this._m22 * this._m33) - (this._m32 * this._m23); - var num8 = ((this._m31 * num11) + (this._m21 * num10)) + (this._m11 * num9); - if (DoubleUtilities.isZero(num8)) { - return false; - } - var num20 = (this._m21 * this._m13) - (this._m11 * this._m23); - var num19 = (this._m11 * this._m33) - (this._m31 * this._m13); - var num18 = (this._m31 * this._m23) - (this._m21 * this._m33); - var num7 = (this._m11 * this._m22) - (this._m21 * this._m12); - var num6 = (this._m11 * this._m32) - (this._m31 * this._m12); - var num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); - var num4 = (this._m21 * this._m32) - (this._m31 * this._m22); - var num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); - var num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); - var num17 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); - var num16 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); - var num15 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); - var num14 = num7; - var num13 = -num6; - var num12 = num4; - var num = 1 / num8; - this._m11 = num9 * num; - this._m12 = num10 * num; - this._m13 = num11 * num; - this._m21 = num18 * num; - this._m22 = num19 * num; - this._m23 = num20 * num; - this._m31 = num12 * num; - this._m32 = num13 * num; - this._m33 = num14 * num; - this._offsetX = num15 * num; - this._offsetY = num16 * num; - this._offsetZ = num17 * num; - return true; - }, - _invertCore: function () { - if (!this.get__isDistinguishedIdentity()) { - if (this.get_isAffine()) { - return this._normalizedAffineInvert(); - } - var num7 = (this._m13 * this._m24) - (this._m23 * this._m14); - var num6 = (this._m13 * this._m34) - (this._m33 * this._m14); - var num5 = (this._m13 * this._m44) - (this._offsetZ * this._m14); - var num4 = (this._m23 * this._m34) - (this._m33 * this._m24); - var num3 = (this._m23 * this._m44) - (this._offsetZ * this._m24); - var num2 = (this._m33 * this._m44) - (this._offsetZ * this._m34); - var num12 = ((this._m22 * num6) - (this._m32 * num7)) - (this._m12 * num4); - var num11 = ((this._m12 * num3) - (this._m22 * num5)) + (this._offsetY * num7); - var num10 = ((this._m32 * num5) - (this._offsetY * num6)) - (this._m12 * num2); - var num9 = ((this._m22 * num2) - (this._m32 * num3)) + (this._offsetY * num4); - var num8 = (((this._offsetX * num12) + (this._m31 * num11)) + (this._m21 * num10)) + (this._m11 * num9); - if (DoubleUtilities.isZero(num8)) { - return false; - } - var num24 = ((this._m11 * num4) - (this._m21 * num6)) + (this._m31 * num7); - var num23 = ((this._m21 * num5) - (this._offsetX * num7)) - (this._m11 * num3); - var num22 = ((this._m11 * num2) - (this._m31 * num5)) + (this._offsetX * num6); - var num21 = ((this._m31 * num3) - (this._offsetX * num4)) - (this._m21 * num2); - num7 = (this._m11 * this._m22) - (this._m21 * this._m12); - num6 = (this._m11 * this._m32) - (this._m31 * this._m12); - num5 = (this._m11 * this._offsetY) - (this._offsetX * this._m12); - num4 = (this._m21 * this._m32) - (this._m31 * this._m22); - num3 = (this._m21 * this._offsetY) - (this._offsetX * this._m22); - num2 = (this._m31 * this._offsetY) - (this._offsetX * this._m32); - var num20 = ((this._m13 * num4) - (this._m23 * num6)) + (this._m33 * num7); - var num19 = ((this._m23 * num5) - (this._offsetZ * num7)) - (this._m13 * num3); - var num18 = ((this._m13 * num2) - (this._m33 * num5)) + (this._offsetZ * num6); - var num17 = ((this._m33 * num3) - (this._offsetZ * num4)) - (this._m23 * num2); - var num16 = ((this._m24 * num6) - (this._m34 * num7)) - (this._m14 * num4); - var num15 = ((this._m14 * num3) - (this._m24 * num5)) + (this._m44 * num7); - var num14 = ((this._m34 * num5) - (this._m44 * num6)) - (this._m14 * num2); - var num13 = ((this._m24 * num2) - (this._m34 * num3)) + (this._m44 * num4); - var num = 1 / num8; - this._m11 = num9 * num; - this._m12 = num10 * num; - this._m13 = num11 * num; - this._m14 = num12 * num; - this._m21 = num21 * num; - this._m22 = num22 * num; - this._m23 = num23 * num; - this._m24 = num24 * num; - this._m31 = num13 * num; - this._m32 = num14 * num; - this._m33 = num15 * num; - this._m34 = num16 * num; - this._offsetX = num17 * num; - this._offsetY = num18 * num; - this._offsetZ = num19 * num; - this._m44 = num20 * num; - } - return true; - }, - get__isDistinguishedIdentity: function () { - return !this._isNotKnownToBeIdentity; - }, - set__isDistinguishedIdentity: function (value) { - this._isNotKnownToBeIdentity = !value; - return value; - }, - _multiply: function (mat) { - this.set(Matrix3d.multiplyMatrix(this, mat)); - } - }; - - - // wwtlib.Matrix2d - - function Matrix2d() { - this.m11 = 1; - this.m12 = 0; - this.m13 = 0; - this.m21 = 0; - this.m22 = 1; - this.m23 = 0; - this.m31 = 0; - this.m32 = 0; - this.m33 = 1; - } - Matrix2d.create = function (m11, m12, m13, m21, m22, m23, m31, m32, m33) { - var mat = new Matrix2d(); - mat.m11 = m11; - mat.m12 = m12; - mat.m13 = m13; - mat.m21 = m21; - mat.m22 = m22; - mat.m23 = m23; - mat.m31 = m31; - mat.m32 = m32; - mat.m33 = m33; - return mat; - }; - Matrix2d.rotation = function (angle) { - var mat = new Matrix2d(); - mat.m11 = Math.cos(angle); - mat.m21 = -Math.sin(angle); - mat.m12 = Math.sin(angle); - mat.m22 = Math.cos(angle); - return mat; - }; - Matrix2d.translation = function (x, y) { - var mat = new Matrix2d(); - mat.m31 = x; - mat.m32 = y; - return mat; - }; - Matrix2d.scaling = function (x, y) { - var mat = new Matrix2d(); - mat.m11 = x; - mat.m22 = y; - return mat; - }; - Matrix2d.multiply = function (matrix1, matrix2) { - return Matrix2d.create((((matrix1.m11 * matrix2.m11) + (matrix1.m12 * matrix2.m21)) + (matrix1.m13 * matrix2.m31)), (((matrix1.m11 * matrix2.m12) + (matrix1.m12 * matrix2.m22)) + (matrix1.m13 * matrix2.m32)), (((matrix1.m11 * matrix2.m13) + (matrix1.m12 * matrix2.m23)) + (matrix1.m13 * matrix2.m33)), (((matrix1.m21 * matrix2.m11) + (matrix1.m22 * matrix2.m21)) + (matrix1.m23 * matrix2.m31)), (((matrix1.m21 * matrix2.m12) + (matrix1.m22 * matrix2.m22)) + (matrix1.m23 * matrix2.m32)), (((matrix1.m21 * matrix2.m13) + (matrix1.m22 * matrix2.m23)) + (matrix1.m23 * matrix2.m33)), (((matrix1.m31 * matrix2.m11) + (matrix1.m32 * matrix2.m21)) + (matrix1.m33 * matrix2.m31)), (((matrix1.m31 * matrix2.m12) + (matrix1.m32 * matrix2.m22)) + (matrix1.m33 * matrix2.m32)), (((matrix1.m31 * matrix2.m13) + (matrix1.m32 * matrix2.m23)) + (matrix1.m33 * matrix2.m33))); - }; - Matrix2d.rotateAt = function (angle, pnt) { - var matT0 = Matrix2d.translation(-pnt.x, -pnt.y); - var matR = Matrix2d.rotation(angle); - var matT1 = Matrix2d.translation(pnt.x, pnt.y); - return Matrix2d.multiply(Matrix2d.multiply(matT0, matR), matT1); - }; - var Matrix2d$ = { - _transformPoints: function (points) { - var $enum1 = ss.enumerate(points); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - this.multiplyPoint(pnt); - } - }, - multiplyPoint: function (point) { - var x = point.x; - var y = point.y; - point.x = (((x * this.m11) + (y * this.m21)) + this.m31); - point.y = (((x * this.m12) + (y * this.m22)) + this.m32); - } - }; - - - // wwtlib.DoubleUtilities - - function DoubleUtilities() { - } - DoubleUtilities.isZero = function (value) { - return (Math.abs(value) < 2.22044604925031E-50); - }; - DoubleUtilities.isOne = function (value) { - return (Math.abs(value - 1) < 2.22044604925031E-50); - }; - DoubleUtilities.radiansToDegrees = function (radians) { - return radians * 180 / Math.PI; - }; - DoubleUtilities.degreesToRadians = function (degrees) { - return degrees * Math.PI / 180; - }; - DoubleUtilities.clamp = function (x, min, max) { - return Math.max(min, Math.min(x, max)); - }; - - - // wwtlib.PlaneD - - function PlaneD(valuePointA, valuePointB, valuePointC, valuePointD) { - this.a = 0; - this.b = 0; - this.c = 0; - this.d = 0; - this.a = valuePointA; - this.b = valuePointB; - this.c = valuePointC; - this.d = valuePointD; - } - var PlaneD$ = { - normalize: function () { - var length = Math.sqrt(this.a * this.a + this.b * this.b + this.c * this.c); - this.a /= length; - this.b /= length; - this.c /= length; - this.d /= length; - }, - dot: function (v) { - return this.b * v.y + this.c * v.z + this.d * v.w + this.a * v.x; - } - }; - - - // wwtlib.Vector4d - - function Vector4d(valueX, valueY, valueZ, valueW) { - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; - this.x = valueX; - this.y = valueY; - this.z = valueZ; - this.w = valueW; - } - var Vector4d$ = { - - }; - - - // wwtlib.PositionNormalTexturedX2 - - function PositionNormalTexturedX2() { - this.x = 0; - this.y = 0; - this.z = 0; - this.nx = 0; - this.ny = 0; - this.nz = 0; - this.tu = 0; - this.tv = 0; - this.tu1 = 0; - this.tv1 = 0; - } - PositionNormalTexturedX2.create2UV = function (pos, nor, u, v, u1, v1) { - var temp = new PositionNormalTexturedX2(); - temp.x = pos.x; - temp.y = pos.y; - temp.z = pos.z; - temp.nx = nor.x; - temp.ny = nor.y; - temp.nz = nor.z; - temp.tu = u; - temp.tv = v; - temp.tu1 = u1; - temp.tv1 = v1; - return temp; - }; - PositionNormalTexturedX2.create = function (pos, nor, u, v) { - var temp = new PositionNormalTexturedX2(); - temp.x = pos.x; - temp.y = pos.y; - temp.z = pos.z; - temp.nx = nor.x; - temp.ny = nor.y; - temp.nz = nor.z; - temp.tu = u; - temp.tv = v; - var result = Coordinates.cartesianToSpherical2(nor); - temp.tu1 = ((result.get_lng() + 180) / 360); - temp.tv1 = (1 - ((result.get_lat() + 90) / 180)); - return temp; - }; - PositionNormalTexturedX2.createLong2UV = function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v, u1, v1) { - var temp = new PositionNormalTexturedX2(); - temp.x = xvalue; - temp.y = yvalue; - temp.z = zvalue; - temp.nx = nxvalue; - temp.ny = nyvalue; - temp.nz = nzvalue; - temp.tu = u; - temp.tv = v; - temp.tu1 = u1; - temp.tv1 = v1; - return temp; - }; - PositionNormalTexturedX2.get_strideSize = function () { - return 40; - }; - var PositionNormalTexturedX2$ = { - get_lat: function () { - return (1 - this.tv1) * 180 - 90; - }, - set_lat: function (value) { - this.tv1 = (1 - ((value + 90) / 180)); - return value; - }, - get_lng: function () { - return this.tu1 * 360 - 180; - }, - set_lng: function (value) { - this.tu1 = ((value + 180) / 360); - return value; - }, - createLong: function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v) { - var temp = new PositionNormalTexturedX2(); - temp.x = xvalue; - temp.y = yvalue; - temp.z = zvalue; - temp.nx = nxvalue; - temp.ny = nyvalue; - temp.nz = nzvalue; - temp.tu = u; - temp.tv = v; - var result = Coordinates.cartesianToSpherical2(Vector3d.create(this.nx, this.ny, this.nz)); - temp.tu1 = ((result.get_lng() + 180) / 360); - temp.tv1 = (1 - ((result.get_lat() + 90) / 180)); - return temp; - }, - get_normal: function () { - return Vector3d.create(this.nx, this.ny, this.nz); - }, - set_normal: function (value) { - this.nx = value.x; - this.ny = value.y; - this.nz = value.z; - return value; - }, - get_position: function () { - return Vector3d.create(this.x, this.y, this.y); - }, - set_position: function (value) { - this.x = value.x; - this.y = value.y; - this.z = value.z; - return value; - }, - toString: function () { - return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv, this.tu1, this.tv1); - } - }; - - - // wwtlib.PositionNormalTextured - - function PositionNormalTextured() { - this.x = 0; - this.y = 0; - this.z = 0; - this.nx = 0; - this.ny = 0; - this.nz = 0; - this.tu = 0; - this.tv = 0; - } - PositionNormalTextured.createShort = function (pos, nor, u, v) { - var temp = new PositionNormalTextured(); - temp.x = pos.x; - temp.y = pos.y; - temp.z = pos.z; - temp.nx = nor.x; - temp.ny = nor.y; - temp.nz = nor.z; - temp.tu = u; - temp.tv = v; - return temp; - }; - PositionNormalTextured._create = function (x, y, z, nx, ny, nz, tu, tv) { - var temp = new PositionNormalTextured(); - temp.x = x; - temp.y = y; - temp.z = z; - temp.nx = nx; - temp.ny = ny; - temp.nz = nz; - temp.tu = tu; - temp.tv = tv; - return temp; - }; - PositionNormalTextured.createUV = function (pos, nor, uv) { - var temp = new PositionNormalTextured(); - temp.x = pos.x; - temp.y = pos.y; - temp.z = pos.z; - temp.nx = nor.x; - temp.ny = nor.y; - temp.nz = nor.z; - temp.tu = uv.x; - temp.tv = uv.y; - return temp; - }; - var PositionNormalTextured$ = { - createLong: function (xvalue, yvalue, zvalue, nxvalue, nyvalue, nzvalue, u, v) { - var temp = new PositionNormalTexturedX2(); - temp.x = xvalue; - temp.y = yvalue; - temp.z = zvalue; - temp.nx = nxvalue; - temp.ny = nyvalue; - temp.nz = nzvalue; - temp.tu = u; - temp.tv = v; - return temp; - }, - get_normal: function () { - return Vector3d.create(this.nx, this.ny, this.nz); - }, - set_normal: function (value) { - this.nx = value.x; - this.ny = value.y; - this.nz = value.z; - return value; - }, - get_position: function () { - return Vector3d.create(this.x, this.y, this.z); - }, - set_position: function (value) { - this.x = value.x; - this.y = value.y; - this.z = value.z; - return value; - }, - toString: function () { - return ss.format('X={0}, Y={1}, Z={2}, Nx={3}, Ny={4}, Nz={5}, U={6}, V={7}, U1={8}, U2={9}', this.x, this.y, this.z, this.nx, this.ny, this.nz, this.tu, this.tv); - } - }; - - - // wwtlib.SphereHull - - function SphereHull() { - this.radius = 0; - } - SphereHull._create = function (Center, Radius) { - var temp = new SphereHull(); - temp.center = Center; - temp.radius = Radius; - return temp; - }; - var SphereHull$ = { - - }; - - - // wwtlib.ConvexHull - - function ConvexHull() { - } - ConvexHull.findEnclosingSphereFast = function (points) { - var result = new SphereHull(); - var count = points.length; - var center = Vector3d.zero; - for (var i = 0; i < count; ++i) { - center.add(points[i]); - } - center.multiply(1 / count); - var radius = 0; - for (var i = 0; i < count; ++i) { - var distance = Vector3d.getLengthSq(Vector3d.subtractVectors(points[i], center)); - if (distance > radius) { - radius = distance; - } - } - radius = Math.sqrt(radius); - result.center = center; - result.radius = radius; - return result; - }; - ConvexHull.findEnclosingSphere = function (list) { - var Center = new Vector3d(); - var Radius = 0; - var count = list.length; - var i; - var dx; - var dy; - var dz; - var rad_sq; - var xspan; - var yspan; - var zspan; - var maxspan; - var old_to_p; - var old_to_p_sq; - var old_to_new; - var xmin = new Vector3d(); - var xmax = new Vector3d(); - var ymin = new Vector3d(); - var ymax = new Vector3d(); - var zmin = new Vector3d(); - var zmax = new Vector3d(); - var dia1 = new Vector3d(); - var dia2 = new Vector3d(); - xmin.x = ymin.y = zmin.z = 100000000; - xmax.x = ymax.y = zmax.z = -1000000000; - for (i = 0; i < count; i++) { - var current = list[i]; - if (current.x < xmin.x) { - xmin = current; - } - if (current.x > xmax.x) { - xmax = current; - } - if (current.y < ymin.y) { - ymin = current; - } - if (current.y > ymax.y) { - ymax = current; - } - if (current.z < zmin.z) { - zmin = current; - } - if (current.z > zmax.z) { - zmax = current; - } - } - dx = xmax.x - xmin.x; - dy = xmax.y - xmin.y; - dz = xmax.z - xmin.z; - xspan = dx * dx + dy * dy + dz * dz; - dx = ymax.x - ymin.x; - dy = ymax.y - ymin.y; - dz = ymax.z - ymin.z; - yspan = dx * dx + dy * dy + dz * dz; - dx = zmax.x - zmin.x; - dy = zmax.y - zmin.y; - dz = zmax.z - zmin.z; - zspan = dx * dx + dy * dy + dz * dz; - dia1 = xmin; - dia2 = xmax; - maxspan = xspan; - if (yspan > maxspan) { - maxspan = yspan; - dia1 = ymin; - dia2 = ymax; - } - if (zspan > maxspan) { - dia1 = zmin; - dia2 = zmax; - } - Center.x = (dia1.x + dia2.x) / 2; - Center.y = (dia1.y + dia2.y) / 2; - Center.z = (dia1.z + dia2.z) / 2; - dx = dia2.x - Center.x; - dy = dia2.y - Center.y; - dz = dia2.z - Center.z; - rad_sq = dx * dx + dy * dy + dz * dz; - Radius = Math.sqrt(rad_sq); - for (i = 0; i < count; i++) { - var current = list[i]; - dx = current.x - Center.x; - dy = current.y - Center.y; - dz = current.z - Center.z; - old_to_p_sq = dx * dx + dy * dy + dz * dz; - if (old_to_p_sq > rad_sq) { - old_to_p = Math.sqrt(old_to_p_sq); - Radius = (Radius + old_to_p) / 2; - rad_sq = Radius * Radius; - old_to_new = old_to_p - Radius; - Center.x = (Radius * Center.x + old_to_new * current.x) / old_to_p; - Center.y = (Radius * Center.y + old_to_new * current.y) / old_to_p; - Center.z = (Radius * Center.z + old_to_new * current.z) / old_to_p; - } - } - return SphereHull._create(Center, Radius); - }; - var ConvexHull$ = { - - }; - - - // wwtlib.Folder - - function Folder() { - this.parent = null; - this.isProxy = false; - this._versionDependent = false; - this._readOnly = true; - this._dirty = false; - this._thumbnail = null; - this._proxyFolder = null; - this._lastUpdate = new Date(); - this._childList = []; - this._itemsField = []; - this._imagesets = []; - this._tours = []; - this._folders = []; - this._places = []; - this._groupField = 0; - this._refreshTypeField = 0; - this._refreshTypeFieldSpecified = false; - this._browseableField = true; - this._browseableFieldSpecified = false; - this._searchableField = false; - this._typeField = 0; - this._communityIdField = 0; - this._componentIdField = 0; - this._permissionField = 0; - } - var Folder$ = { - toString: function () { - return this._nameField; - }, - get_versionDependent: function () { - return this._versionDependent; - }, - set_versionDependent: function (value) { - this._versionDependent = value; - var $enum1 = ss.enumerate(this._folders); - while ($enum1.moveNext()) { - var folder = $enum1.current; - folder.set_versionDependent(this._versionDependent); - } - return value; - }, - get_readOnly: function () { - return this._readOnly; - }, - set_readOnly: function (value) { - this._readOnly = value; - return value; - }, - get_dirty: function () { - return this._dirty; - }, - set_dirty: function (value) { - this._dirty = value; - return value; - }, - loadFromUrlWithErrorCallback: function (url, complete, onError) { - this._onError = onError; - this.loadFromUrl(url, complete); - }, - loadFromUrl: function (url, complete) { - this._onComplete = complete; - this._webFile = new WebFile(URLHelpers.singleton.rewrite(url, 1)); - this._webFile.onStateChange = ss.bind('_loadData', this); - this._webFile.send(); - }, - _loadData: function () { - if (this._webFile.get_state() === 2) { - console.error(this._webFile.get_message()); - if (this._onError != null) { - this._onError(); - } - } - else if (this._webFile.get_state() === 1) { - var node = Util.selectSingleNode(this._webFile.getXml(), 'Folder'); - if (node == null) { - var doc = this._webFile.getXml(); - if (doc != null) { - node = Util.selectSingleNode(doc, 'Folder'); - } - } - if (node != null) { - this._clearChildren(); - this._parseXML(node); - } - if (this._onComplete != null) { - this._onComplete(); - } - } - }, - _clearChildren: function () { - this._folders.length = 0; - this._tours.length = 0; - this._places.length = 0; - this.get_imagesets().length = 0; - }, - _parseXML: function (node) { - if (node.attributes.getNamedItem('Name') != null) { - this._nameField = node.attributes.getNamedItem('Name').nodeValue; - } - else { - this._nameField = ''; - } - if (node.attributes.getNamedItem('Url') != null) { - this._urlField = node.attributes.getNamedItem('Url').nodeValue; - } - if (node.attributes.getNamedItem('Thumbnail') != null) { - this._thumbnailUrlField = node.attributes.getNamedItem('Thumbnail').nodeValue; - } - var $enum1 = ss.enumerate(node.childNodes); - while ($enum1.moveNext()) { - var child = $enum1.current; - switch (child.nodeName) { - case 'Folder': - var temp = new Folder(); - temp.parent = this; - temp._parseXML(child); - this._folders.push(temp); - break; - case 'Place': - this._places.push(Place._fromXml(child)); - break; - case 'ImageSet': - this.get_imagesets().push(Imageset.fromXMLNode(child)); - break; - case 'Tour': - this.get_tours().push(Tour._fromXml(child)); - break; - } - } - }, - addChildFolder: function (child) { - this._folders.push(child); - this._dirty = true; - }, - removeChildFolder: function (child) { - ss.remove(this._folders, child); - this._dirty = true; - }, - addChildPlace: function (child) { - this._places.push(child); - this._dirty = true; - }, - removeChildPlace: function (child) { - ss.remove(this._places, child); - this._dirty = true; - }, - get_thumbnail: function () { - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - return value; - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_isImage: function () { - return false; - }, - get_isTour: function () { - return false; - }, - get_isFolder: function () { - return true; - }, - get_isCloudCommunityItem: function () { - return !!this._communityIdField || this._permissionField > 0; - }, - refresh: function () { - if (this._proxyFolder == null) { - this._proxyFolder = new Folder(); - this._proxyFolder.isProxy = true; - this._proxyFolder.parent = this.parent; - } - this._proxyFolder.loadFromUrlWithErrorCallback(this._urlField, this._childReadyCallback, this._childReadyCallback); - this._childReadyCallback = null; - }, - childLoadCallback: function (callback) { - this._childReadyCallback = callback; - var temp = this.get_children(); - if (this._proxyFolder == null) { - callback(); - } - }, - get_children: function () { - if (ss.emptyString(this._urlField)) { - this._childList.length = 0; - if (this.parent != null) { - var folderUp = new FolderUp(); - folderUp.parent = this.parent; - this._childList.push(folderUp); - } - if (this.get_folders() != null) { - var $enum1 = ss.enumerate(this.get_folders()); - while ($enum1.moveNext()) { - var folder = $enum1.current; - this._childList.push(folder); - } - } - if (this.get_imagesets() != null) { - var $enum2 = ss.enumerate(this.get_imagesets()); - while ($enum2.moveNext()) { - var imset = $enum2.current; - this._childList.push(imset); - } - } - if (this.get_places() != null) { - var $enum3 = ss.enumerate(this.get_places()); - while ($enum3.moveNext()) { - var place = $enum3.current; - this._childList.push(place); - } - } - if (this.get_tours() != null) { - var $enum4 = ss.enumerate(this.get_tours()); - while ($enum4.moveNext()) { - var tour = $enum4.current; - this._childList.push(tour); - } - } - return this._childList; - } - else { - var ts = (this._lastUpdate - ss.now()) / 1000; - if (this.get_refreshType() === 1 || this._proxyFolder == null || (!this.get_refreshType() && (parseInt(this._refreshIntervalField) < ts))) { - this.refresh(); - } - if (this._proxyFolder != null) { - return this._proxyFolder.get_children(); - } - else { - return null; - } - } - }, - get_msrCommunityId: function () { - return this._communityIdField; - }, - set_msrCommunityId: function (value) { - this._communityIdField = value; - return value; - }, - get_msrComponentId: function () { - return this._componentIdField; - }, - set_msrComponentId: function (value) { - this._componentIdField = value; - return value; - }, - get_permission: function () { - return this._permissionField; - }, - set_permission: function (value) { - this._permissionField = value; - return value; - }, - get_folders: function () { - return this._folders; - }, - set_folders: function (value) { - this._folders = value; - return value; - }, - get_places: function () { - return this._places; - }, - set_places: function (value) { - this._places = value; - return value; - }, - get_imagesets: function () { - return this._imagesets; - }, - set_imagesets: function (value) { - this._imagesets = value; - return value; - }, - get_tours: function () { - return this._tours; - }, - set_tours: function (value) { - this._tours = value; - return value; - }, - get_name: function () { - if (this._nameField == null) { - return ''; - } - else { - return this._nameField; - } - }, - set_name: function (value) { - this._nameField = value; - return value; - }, - get_group: function () { - return this._groupField; - }, - set_group: function (value) { - this._groupField = value; - return value; - }, - get_url: function () { - return this._urlField; - }, - set_url: function (value) { - this._urlField = value; - return value; - }, - get_thumbnailUrl: function () { - if (ss.emptyString(this._thumbnailUrlField)) { - return URLHelpers.singleton.engineAssetUrl('thumb_folder.jpg'); - } - return this._thumbnailUrlField; - }, - set_thumbnailUrl: function (value) { - this._thumbnailUrlField = value; - return value; - }, - get_refreshType: function () { - return this._refreshTypeField; - }, - set_refreshType: function (value) { - this._refreshTypeField = value; - this.set_refreshTypeSpecified(true); - return value; - }, - get_refreshTypeSpecified: function () { - return this._refreshTypeFieldSpecified; - }, - set_refreshTypeSpecified: function (value) { - this._refreshTypeFieldSpecified = value; - return value; - }, - get_refreshInterval: function () { - return this._refreshIntervalField; - }, - set_refreshInterval: function (value) { - this._refreshIntervalField = value; - return value; - }, - get_browseable: function () { - return this._browseableField; - }, - set_browseable: function (value) { - this._browseableField = value; - this._browseableFieldSpecified = true; - return value; - }, - get_browseableSpecified: function () { - return this._browseableFieldSpecified; - }, - set_browseableSpecified: function (value) { - this._browseableFieldSpecified = value; - return value; - }, - get_searchable: function () { - return this._searchableField; - }, - set_searchable: function (value) { - this._searchableField = value; - return value; - }, - get_type: function () { - return this._typeField; - }, - set_type: function (value) { - this._typeField = value; - return value; - }, - get_subType: function () { - return this._subTypeField; - }, - set_subType: function (value) { - this._subTypeField = value; - return value; - } - }; - - - // wwtlib.FolderBrowser - - function FolderBrowser() { - this._items = []; - this.top = 10; - this.left = 10; - this._indexTouchDown = -1; - this._mouseDown = false; - this._lastX = 0; - this._lastY = 0; - this._ignoreClick = false; - this._thumbnailSize = 0; - this._horzSpacing = 110; - this._vertSpacing = 75; - this._thumbHeight = 65; - this._thumbWidth = 110; - this._horzMultiple = 110; - this._rowCount = 1; - this._colCount = 6; - this._dragging = false; - this._startIndex = 0; - this._startOffset = 0; - this._selectedItem = -1; - this._hoverItem = -1; - this.showAddButton = false; - this.width = 0; - this.height = 0; - this._addButtonHover = false; - this.imageClicked = false; - } - FolderBrowser.create = function () { - var temp = new FolderBrowser(); - temp.height = 85; - temp.width = 1920; - temp.canvas = document.createElement('canvas'); - temp.canvas.width = temp.width; - temp.canvas.height = temp.height; - temp.setup(); - temp.loadImages(); - return temp; - }; - var FolderBrowser$ = { - setup: function () { - this.canvas.addEventListener('click', ss.bind('onClick', this), false); - this.canvas.addEventListener('dblclick', ss.bind('onDoubleClick', this), false); - this.canvas.addEventListener('mousemove', ss.bind('onMouseMove', this), false); - this.canvas.addEventListener('mouseup', ss.bind('onMouseUp', this), false); - this.canvas.addEventListener('mousedown', ss.bind('onMouseDown', this), false); - this.canvas.addEventListener('touchstart', ss.bind('onTouchStart', this), false); - this.canvas.addEventListener('touchmove', ss.bind('onTouchMove', this), false); - this.canvas.addEventListener('touchend', ss.bind('onTouchEnd', this), false); - this.canvas.addEventListener('mouseout', ss.bind('onMouseUp', this), false); - }, - onTouchStart: function (e) { - var ev = e; - ev.preventDefault(); - this._mouseDown = true; - this._lastX = ev.targetTouches[0].pageX; - this._lastY = ev.targetTouches[0].pageY; - this._indexTouchDown = this._getItemIndexFromCursor(Vector2d.create(ev.targetTouches[0].pageX, ev.targetTouches[0].pageY)); - }, - onTouchMove: function (e) { - var ev = e; - ev.preventDefault(); - if (this._mouseDown) { - var curX = ev.targetTouches[0].pageX - this._lastX; - var curY = ev.targetTouches[0].pageY - this._lastY; - if (this._mouseDown) { - this._dragging = true; - } - if (!this._dragging) { - var newHover = this._getItemIndexFromCursor(Vector2d.create(ev.targetTouches[0].pageX, ev.targetTouches[0].pageY)); - if (this._hoverItem !== newHover) { - this._hoverItem = newHover; - } - } - else { - var tiles = Math.round(((ev.targetTouches[0].pageX - this._lastX) + this._startOffset) / this._horzSpacing); - var offset = Math.round(((ev.targetTouches[0].pageX - this._lastX) + this._startOffset) - (tiles * this._horzSpacing)); - this._startOffset = offset; - this._startIndex -= tiles; - if (this._startIndex < 0) { - this._startOffset -= (this._horzSpacing * this._startIndex); - this._startIndex = 0; - } - this._lastX = ev.targetTouches[0].pageX; - this._lastY = ev.targetTouches[0].pageY; - } - this.refresh(); - } - }, - onTouchEnd: function (e) { - var ev = e; - ev.preventDefault(); - if (this._dragging) { - this._dragging = false; - this._ignoreClick = true; - } - else if (this._indexTouchDown > -1 && this._mouseDown) { - this._handleClick(this._indexTouchDown); - } - this._startOffset = 0; - this._mouseDown = false; - this.refresh(); - }, - onClick: function (e) { - if (!this._ignoreClick) { - var index = this._getItemIndexFromCursor(Vector2d.create(e.offsetX, e.offsetY)); - this._handleClick(index); - } - else { - this._ignoreClick = false; - } - }, - _handleClick: function (index) { - var $this = this; - - if (index > -1) { - if (ss.canCast(this._items[index], Place)) { - var place = this._items[index]; - WWTControl.singleton.gotoTarget(place, false, false, true); - return; - } - if (ss.canCast(this._items[index], Imageset)) { - var imageset = this._items[index]; - WWTControl.singleton.renderContext.set_backgroundImageset(imageset); - return; - } - if (ss.canCast(this._items[index], Tour)) { - var tour = this._items[index]; - WWTControl.singleton.playTour(tour.get_tourUrl()); - return; - } - if (ss.canCast(this._items[index], Folder)) { - var folder = this._items[index]; - this._startIndex = 0; - folder.childLoadCallback(function () { - $this._items = folder.get_children(); - $this.refresh(); - }); - return; - } - if (ss.canCast(this._items[index], FolderUp)) { - var folderUp = this._items[index]; - if (folderUp.parent != null) { - this._startIndex = 0; - folderUp.parent.childLoadCallback(function () { - $this._items = folderUp.parent.get_children(); - $this.refresh(); - }); - } - return; - } - } - return; - }, - onDoubleClick: function (e) { - RenderTriangle.renderingOn = !RenderTriangle.renderingOn; - }, - onGestureChange: function (e) { - var g = e; - this._mouseDown = false; - var delta = g.scale; - }, - onMouseDown: function (e) { - this._mouseDown = true; - this._lastX = Mouse.offsetX(this.canvas, e); - this._lastY = Mouse.offsetY(this.canvas, e); - }, - onMouseMove: function (e) { - if (this._mouseDown) { - this._dragging = true; - } - if (!this._dragging) { - var newHover = this._getItemIndexFromCursor(Vector2d.create(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e))); - if (this._hoverItem !== newHover) { - this._hoverItem = newHover; - } - } - else { - var tiles = Math.round(((Mouse.offsetX(this.canvas, e) - this._lastX) + this._startOffset) / this._horzSpacing); - var offset = Math.round(((Mouse.offsetX(this.canvas, e) - this._lastX) + this._startOffset) - (tiles * this._horzSpacing)); - this._startOffset = offset; - this._startIndex -= tiles; - if (this._startIndex < 0) { - this._startOffset -= (this._horzSpacing * this._startIndex); - this._startIndex = 0; - } - this._lastX = Mouse.offsetX(this.canvas, e); - this._lastY = Mouse.offsetY(this.canvas, e); - } - this.refresh(); - }, - onMouseUp: function (e) { - if (this._dragging) { - this._startOffset = 0; - this._dragging = false; - this._ignoreClick = true; - } - this._mouseDown = false; - this.refresh(); - }, - loadImages: function () { - var $this = this; - - if (!FolderBrowser._imagesLoaded && !FolderBrowser._downloading) { - FolderBrowser._imageLoadCount = 0; - FolderBrowser._imagesLoaded = false; - FolderBrowser._downloading = true; - FolderBrowser._bmpBackground = document.createElement('img'); - FolderBrowser._bmpBackground.src = 'images/thumbBackground.png'; - FolderBrowser._bmpBackground.addEventListener('load', function (e) { - FolderBrowser._imageLoadCount++; - if (FolderBrowser._imageLoadCount === 5) { - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = true; - $this.refresh(); - } - }, false); - FolderBrowser._bmpBackgroundHover = document.createElement('img'); - FolderBrowser._bmpBackgroundHover.src = 'images/thumbBackgroundHover.png'; - FolderBrowser._bmpBackgroundHover.addEventListener('load', function (e) { - FolderBrowser._imageLoadCount++; - if (FolderBrowser._imageLoadCount === 5) { - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = true; - $this.refresh(); - } - }, false); - FolderBrowser._bmpBackgroundWide = document.createElement('img'); - FolderBrowser._bmpBackgroundWide.src = 'images/thumbBackgroundWide.png'; - FolderBrowser._bmpBackgroundWide.addEventListener('load', function (e) { - FolderBrowser._imageLoadCount++; - if (FolderBrowser._imageLoadCount === 5) { - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = true; - $this.refresh(); - } - }, false); - FolderBrowser._bmpBackgroundWideHover = document.createElement('img'); - FolderBrowser._bmpBackgroundWideHover.src = 'images/thumbBackgroundWideHover.png'; - FolderBrowser._bmpBackgroundWideHover.addEventListener('load', function (e) { - FolderBrowser._imageLoadCount++; - if (FolderBrowser._imageLoadCount === 5) { - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = true; - $this.refresh(); - } - }, false); - FolderBrowser._bmpDropInsertMarker = document.createElement('img'); - FolderBrowser._bmpDropInsertMarker.src = 'images/dragInsertMarker.png'; - FolderBrowser._bmpDropInsertMarker.addEventListener('load', function (e) { - FolderBrowser._imageLoadCount++; - if (FolderBrowser._imageLoadCount === 5) { - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = true; - $this.refresh(); - } - }, false); - } - }, - get_thumbnailSize: function () { - return this._thumbnailSize; - }, - set_thumbnailSize: function (value) { - this._thumbnailSize = value; - switch (value) { - case 1: - this._horzSpacing = 180; - this._vertSpacing = 75; - this._thumbHeight = 65; - this._thumbWidth = 180; - break; - case 0: - this._horzSpacing = 110; - this._vertSpacing = 75; - this._thumbHeight = 65; - this._thumbWidth = 110; - break; - } - this._updatePaginator(); - this.refresh(); - return value; - }, - refresh: function () { - if (this.width !== window.innerWidth) { - this.width = window.innerWidth; - this.canvas.width = this.canvas.width; - } - this.paint(); - }, - get_rowCount: function () { - return this._rowCount; - }, - set_rowCount: function (value) { - if (this._rowCount !== value) { - this._rowCount = value; - this._updatePaginator(); - } - return value; - }, - _updatePaginator: function () { - }, - get_colCount: function () { - return this._colCount; - }, - set_colCount: function (value) { - if (this._colCount !== value) { - this._colCount = value; - this._updatePaginator(); - } - return value; - }, - get_itemsPerPage: function () { - return this._rowCount * this._colCount; - }, - get_currentPage: function () { - return this._startIndex / this.get_itemsPerPage(); - }, - get_pageCount: function () { - return Math.max(1, ((this._items.length + this.get_itemsPerPage() - 1) + ((this.showAddButton) ? 1 : 0)) / this.get_itemsPerPage()); - }, - paint: function () { - var $this = this; - - var g = this.canvas.getContext('2d'); - g.fillStyle = 'rgb(20, 22, 31)'; - g.fillRect(0, 0, this.width, this.height); - if (!FolderBrowser._imagesLoaded) { - return; - } - var netHeight = (this.height - 10 * 2); - var netWidth = (this.width - 10 * 2); - this.set_rowCount(Math.round(Math.max(netHeight / this._thumbHeight, 1))); - this.set_colCount(Math.round(Math.max(netWidth / this._horzSpacing, 1))); - this._horzMultiple = (netWidth + 13) / this.get_colCount(); - this._startIndex = Math.round((this._startIndex / this.get_itemsPerPage()) * this.get_itemsPerPage()); - var rectf; - var index = this._startIndex; - for (var y = 0; y < this._rowCount; y++) { - for (var x = 0; x < this._colCount; x++) { - if (index >= this._items.length) { - if (!this._items.length || this.showAddButton) { - rectf = Rectangle.create(this.left + x * this._horzMultiple + 3 + this._startOffset, this.top + y * this._vertSpacing, this._thumbWidth - 10, 60); - g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWide : FolderBrowser._bmpBackground, ss.truncate((x * this._horzMultiple)) + this._startOffset, y * this._vertSpacing); - } - break; - } - rectf = Rectangle.create(this.left + x * this._horzMultiple + 3 + this._startOffset, this.top + y * this._vertSpacing, this._thumbWidth - 14, 60); - var textBrush = 'white'; - if (index === this._hoverItem || (index === this._selectedItem && this._hoverItem === -1)) { - g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWideHover : FolderBrowser._bmpBackgroundHover, this.left + ss.truncate((x * this._horzMultiple)) + this._startOffset, this.top + y * this._vertSpacing); - textBrush = 'yellow'; - } - else { - g.drawImage((this._thumbnailSize === 1) ? FolderBrowser._bmpBackgroundWide : FolderBrowser._bmpBackground, this.left + ss.truncate((x * this._horzMultiple)) + this._startOffset, this.top + y * this._vertSpacing); - } - this._items[index].set_bounds(Rectangle.create((this.left + x * this._horzMultiple) + this._startOffset, this.top + (y * this._vertSpacing), ss.truncate(this._horzMultiple), this._vertSpacing)); - try { - var bmpThumb = this._items[index].get_thumbnail(); - if (bmpThumb != null) { - g.drawImage(bmpThumb, this.left + (x * this._horzMultiple) + 2 + this._startOffset, this.top + y * this._vertSpacing + 3); - g.strokeStyle = 'rgb(0,0,0)'; - g.rect(this.left + ss.truncate((x * this._horzMultiple)) + 2 + this._startOffset, this.top + y * this._vertSpacing + 3, this._items[index].get_thumbnail().width, this._items[index].get_thumbnail().height); - } - else { - this._items[index].set_thumbnail(document.createElement('img')); - this._items[index].get_thumbnail().src = this._items[index].get_thumbnailUrl(); - this._items[index].get_thumbnail().addEventListener('load', function (e) { - $this.refresh(); - }, false); - } - } - catch ($e1) { - } - g.fillStyle = textBrush; - g.strokeStyle = textBrush; - g.lineWidth = 1; - g.font = 'normal 8pt Arial'; - g.fillText(this._items[index].get_name(), rectf.x, rectf.y + rectf.height, rectf.width); - index++; - } - if (index >= this._items.length) { - break; - } - } - }, - _getItemIndexFromCursor: function (testPointIn) { - var testPoint = Vector2d.create(testPointIn.x + this.left, testPointIn.y + this.top); - this.imageClicked = false; - var index = -1; - var xpos = ss.truncate((testPoint.x / this._horzMultiple)); - var xPart = ss.truncate((testPoint.x % this._horzMultiple)); - if (xpos >= this._colCount) { - return -1; - } - if (xpos < 0) { - return -1; - } - var ypos = ss.truncate((testPoint.y / this._vertSpacing)); - var yPart = ss.truncate((testPoint.y % this._vertSpacing)); - if (ypos >= this._rowCount) { - return -1; - } - if (ypos < 0) { - return -1; - } - index = this._startIndex + ypos * this._colCount + xpos; - if (index === this._items.length) { - this._addButtonHover = true; - } - else { - this._addButtonHover = false; - } - if (index > this._items.length - 1) { - return -1; - } - if ((this._items[index]).get_isImage() && yPart < 16 && xPart > 78) { - this.imageClicked = true; - } - return index; - }, - _addItems: function (list) { - this._items = list; - } - }; - - - // wwtlib.FolderUp - - function FolderUp() { - this.parent = null; - this._bounds = new Rectangle(); - } - var FolderUp$ = { - get_name: function () { - return 'Up Level'; - }, - get_thumbnail: function () { - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - return value; - }, - get_thumbnailUrl: function () { - return URLHelpers.singleton.engineAssetUrl('thumb_folderup.jpg'); - }, - set_thumbnailUrl: function (value) { - return value; - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_isImage: function () { - return false; - }, - get_isTour: function () { - return false; - }, - get_isFolder: function () { - return false; - }, - get_isCloudCommunityItem: function () { - return false; - }, - get_readOnly: function () { - return false; - }, - get_children: function () { - if (this.parent == null) { - return []; - } - else { - return this.parent.get_children(); - } - } - }; - - - // wwtlib.ShortIndexBuffer - - function ShortIndexBuffer(indexes) { - this.buffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this.buffer); - Tile.prepDevice.bufferData(34963, indexes, 35044); - } - var ShortIndexBuffer$ = { - - }; - - - // wwtlib.IndexBuffer - - function IndexBuffer(indexes) { - this.buffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this.buffer); - Tile.prepDevice.bufferData(34963, indexes, 35044); - } - var IndexBuffer$ = { - dispose: function () { - Tile.prepDevice.bindBuffer(34963, null); - Tile.prepDevice.deleteBuffer(this.buffer); - this.buffer = null; - } - }; - - - // wwtlib.VertexBufferBase - - function VertexBufferBase() { - } - var VertexBufferBase$ = { - dispose: function () { - Tile.prepDevice.bindBuffer(34962, null); - Tile.prepDevice.deleteBuffer(this.vertexBuffer); - this.vertexBuffer = null; - } - }; - - - // wwtlib.Dates - - function Dates(start, end) { - this.startDate = 0; - this.endDate = 0; - this.startDate = start; - this.endDate = end; - } - Dates.empty = function () { - return new Dates(0, 0); - }; - var Dates$ = { - copy: function () { - return new Dates(this.startDate, this.endDate); - } - }; - - - // wwtlib.SimpleLineList - - function SimpleLineList() { - this._zBuffer = true; - this._linePoints = []; - this._usingLocalCenter = false; - this.sky = true; - this.aaFix = true; - this.pure2D = false; - this.viewTransform = Matrix3d.get_identity(); - this._lineBuffers = []; - this._lineBufferCounts = []; - this.useLocalCenters = false; - } - var SimpleLineList$ = { - get_depthBuffered: function () { - return this._zBuffer; - }, - set_depthBuffered: function (value) { - this._zBuffer = value; - return value; - }, - addLine: function (v1, v2) { - this._linePoints.push(v1); - this._linePoints.push(v2); - this._emptyLineBuffer(); - }, - clear: function () { - this._linePoints.length = 0; - this._emptyLineBuffer(); - }, - drawLines: function (renderContext, opacity, color) { - if (this._linePoints.length < 2) { - return; - } - this._initLineBuffer(renderContext); - var count = this._linePoints.length; - if (renderContext.gl == null) { - var viewPoint = Vector3d._transformCoordinate(renderContext.get_viewPoint(), this.viewTransform); - var ctx = renderContext.device; - ctx.save(); - ctx.strokeStyle = color.toString(); - ctx.lineWidth = 2; - ctx.globalAlpha = 0.25; - var firstPoint = new Vector3d(); - var secondPoint = new Vector3d(); - for (var i = 0; i < count; i += 2) { - firstPoint = renderContext.WVP.transform(this._linePoints[i]); - secondPoint = renderContext.WVP.transform(this._linePoints[i + 1]); - if (Vector3d.dot(this._linePoints[i], viewPoint) > 0.6) { - ctx.beginPath(); - ctx.moveTo(firstPoint.x, firstPoint.y); - ctx.lineTo(secondPoint.x, secondPoint.y); - ctx.stroke(); - } - } - ctx.restore(); - } - else { - var $enum1 = ss.enumerate(this._lineBuffers); - while ($enum1.moveNext()) { - var lineBuffer = $enum1.current; - if (this.pure2D) { - SimpleLineShader2D.use(renderContext, lineBuffer.vertexBuffer, color, this._zBuffer); - } - else { - SimpleLineShader.use(renderContext, lineBuffer.vertexBuffer, color, this._zBuffer); - } - renderContext.gl.drawArrays(1, 0, lineBuffer.count); - } - } - }, - _initLineBuffer: function (renderContext) { - if (renderContext.gl != null) { - if (!this._lineBuffers.length) { - var count = this._linePoints.length; - var lineBuffer = null; - var linePointList = null; - this._localCenter = new Vector3d(); - if (this.get_depthBuffered()) { - var $enum1 = ss.enumerate(this._linePoints); - while ($enum1.moveNext()) { - var point = $enum1.current; - this._localCenter.add(point); - } - this._localCenter.x /= count; - this._localCenter.y /= count; - this._localCenter.z /= count; - } - var countLeft = count; - var index = 0; - var counter = 0; - var temp; - var $enum2 = ss.enumerate(this._linePoints); - while ($enum2.moveNext()) { - var point = $enum2.current; - if (counter >= 100000 || linePointList == null) { - if (lineBuffer != null) { - lineBuffer.unlock(); - } - var thisCount = Math.min(100000, countLeft); - countLeft -= thisCount; - lineBuffer = new PositionVertexBuffer(thisCount); - linePointList = lineBuffer.lock(); - this._lineBuffers.push(lineBuffer); - this._lineBufferCounts.push(thisCount); - counter = 0; - } - if (this.useLocalCenters) { - temp = Vector3d.subtractVectors(point, this._localCenter); - linePointList[counter] = temp; - } - else { - linePointList[counter] = point; - } - index++; - counter++; - } - if (lineBuffer != null) { - lineBuffer.unlock(); - } - } - } - }, - _emptyLineBuffer: function () { - } - }; - - - // wwtlib.OrbitLineList - - function OrbitLineList() { - this._zBuffer = true; - this._linePoints = []; - this._lineColors = []; - this.sky = true; - this.aaFix = true; - this.viewTransform = Matrix3d.get_identity(); - this._lineBuffers = []; - this._lineBufferCounts = []; - this.useLocalCenters = false; - } - var OrbitLineList$ = { - get_depthBuffered: function () { - return this._zBuffer; - }, - set_depthBuffered: function (value) { - this._zBuffer = value; - return value; - }, - addLine: function (v1, v2, c1, c2) { - this._linePoints.push(v1); - this._lineColors.push(c1); - this._linePoints.push(v2); - this._lineColors.push(c2); - this._emptyLineBuffer(); - }, - clear: function () { - this._linePoints.length = 0; - this._emptyLineBuffer(); - }, - drawLines: function (renderContext, opacity, color) { - if (this._linePoints.length < 2) { - return; - } - this._initLineBuffer(renderContext); - var count = this._linePoints.length; - var $enum1 = ss.enumerate(this._lineBuffers); - while ($enum1.moveNext()) { - var lineBuffer = $enum1.current; - OrbitLineShader.use(renderContext, lineBuffer.vertexBuffer, color); - renderContext.gl.drawArrays(1, 0, lineBuffer.count); - } - }, - _initLineBuffer: function (renderContext) { - if (renderContext.gl != null) { - if (!this._lineBuffers.length) { - var count = this._linePoints.length; - var lineBuffer = null; - var linePointList = null; - this._localCenter = new Vector3d(); - if (this.get_depthBuffered()) { - var $enum1 = ss.enumerate(this._linePoints); - while ($enum1.moveNext()) { - var point = $enum1.current; - this._localCenter.add(point); - } - this._localCenter.x /= count; - this._localCenter.y /= count; - this._localCenter.z /= count; - } - var countLeft = count; - var index = 0; - var counter = 0; - var temp; - var $enum2 = ss.enumerate(this._linePoints); - while ($enum2.moveNext()) { - var point = $enum2.current; - if (counter >= 100000 || linePointList == null) { - if (lineBuffer != null) { - lineBuffer.unlock(); - } - var thisCount = Math.min(100000, countLeft); - countLeft -= thisCount; - lineBuffer = new PositionColoredVertexBuffer(thisCount); - linePointList = lineBuffer.lock(); - this._lineBuffers.push(lineBuffer); - this._lineBufferCounts.push(thisCount); - counter = 0; - } - if (this.useLocalCenters) { - temp = Vector3d.subtractVectors(point, this._localCenter); - linePointList[counter] = new PositionColored(temp, this._lineColors[index]); - } - else { - linePointList[counter] = new PositionColored(point, this._lineColors[index]); - } - index++; - counter++; - } - if (lineBuffer != null) { - lineBuffer.unlock(); - } - } - } - }, - _emptyLineBuffer: function () { - var $enum1 = ss.enumerate(this._lineBuffers); - while ($enum1.moveNext()) { - var lineBuffer = $enum1.current; - lineBuffer.dispose(); - } - this._lineBuffers.length = 0; - } - }; - - - // wwtlib.LineList - - function LineList() { - this._zBuffer = true; - this.timeSeries = false; - this.showFarSide = true; - this.sky = false; - this.decay = 0; - this.useNonRotatingFrame = false; - this.jNow = 0; - this._linePoints = []; - this._lineColors = []; - this._lineDates = []; - this._usingLocalCenter = true; - this._lineBuffers = []; - this._lineBufferCounts = []; - } - var LineList$ = { - get_depthBuffered: function () { - return this._zBuffer; - }, - set_depthBuffered: function (value) { - this._zBuffer = value; - return value; - }, - addLine: function (v1, v2, color, date) { - this._linePoints.push(v1); - this._linePoints.push(v2); - this._lineColors.push(color); - this._lineDates.push(date); - this._emptyLineBuffer(); - }, - addLineNoDate: function (v1, v2, color) { - this._linePoints.push(v1); - this._linePoints.push(v2); - this._lineColors.push(color); - this._lineDates.push(new Dates(0, 0)); - this._emptyLineBuffer(); - }, - clear: function () { - this._linePoints.length = 0; - this._lineColors.length = 0; - this._lineDates.length = 0; - }, - drawLines: function (renderContext, opacity) { - if (this._linePoints.length < 2 || opacity <= 0) { - return; - } - if (renderContext.gl == null) { - } - else { - this._initLineBuffer(); - var $enum1 = ss.enumerate(this._lineBuffers); - while ($enum1.moveNext()) { - var lineBuffer = $enum1.current; - LineShaderNormalDates.use(renderContext, lineBuffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this._zBuffer, this.jNow, (this.timeSeries) ? this.decay : 0); - renderContext.gl.drawArrays(1, 0, lineBuffer.count); - } - } - }, - _initLineBuffer: function () { - if (!this._lineBuffers.length) { - var count = this._linePoints.length; - var lineBuffer = null; - var linePointList = null; - var countLeft = count; - var index = 0; - var counter = 0; - var temp; - var $enum1 = ss.enumerate(this._linePoints); - while ($enum1.moveNext()) { - var point = $enum1.current; - if (counter >= 100000 || linePointList == null) { - if (lineBuffer != null) { - lineBuffer.unlock(); - } - var thisCount = Math.min(100000, countLeft); - countLeft -= thisCount; - lineBuffer = new TimeSeriesLineVertexBuffer(thisCount); - linePointList = lineBuffer.lock(); - this._lineBuffers.push(lineBuffer); - this._lineBufferCounts.push(thisCount); - counter = 0; - } - var div2 = ss.truncate((index / 2)); - temp = point; - linePointList[counter] = new TimeSeriesLineVertex(); - linePointList[counter].position = temp; - linePointList[counter].normal = point; - linePointList[counter].tu = this._lineDates[div2].startDate; - linePointList[counter].tv = this._lineDates[div2].endDate; - linePointList[counter].set_color(this._lineColors[div2]); - index++; - counter++; - } - if (lineBuffer != null) { - lineBuffer.unlock(); - } - } - }, - _emptyLineBuffer: function () { - } - }; - - - // wwtlib.TriangleList - - function TriangleList() { - this._trianglePoints = []; - this._triangleColors = []; - this._triangleDates = []; - this.timeSeries = false; - this.showFarSide = false; - this.sky = false; - this.depthBuffered = true; - this.writeZbuffer = false; - this.decay = 0; - this.autoTime = true; - this.jNow = 0; - this._dataToDraw = false; - this._triangleBuffers = []; - this._triangleBufferCounts = []; - } - var TriangleList$ = { - addTriangle: function (v1, v2, v3, color, date) { - this._trianglePoints.push(v1); - this._trianglePoints.push(v2); - this._trianglePoints.push(v3); - this._triangleColors.push(color); - this._triangleDates.push(date); - this._emptyTriangleBuffer(); - }, - addSubdividedTriangles: function (v1, v2, v3, color, date, subdivisions) { - subdivisions--; - if (subdivisions < 0) { - this.addTriangle(v1, v2, v3, color, date); - } - else { - var v12; - var v23; - var v31; - v12 = Vector3d.midPointByLength(v1, v2); - v23 = Vector3d.midPointByLength(v2, v3); - v31 = Vector3d.midPointByLength(v3, v1); - this.addSubdividedTriangles(v1, v12, v31, color, date, subdivisions); - this.addSubdividedTriangles(v12, v23, v31, color, date, subdivisions); - this.addSubdividedTriangles(v12, v2, v23, color, date, subdivisions); - this.addSubdividedTriangles(v23, v3, v31, color, date, subdivisions); - } - }, - addQuad: function (v1, v2, v3, v4, color, date) { - this._trianglePoints.push(v1); - this._trianglePoints.push(v3); - this._trianglePoints.push(v2); - this._trianglePoints.push(v2); - this._trianglePoints.push(v3); - this._trianglePoints.push(v4); - this._triangleColors.push(color); - this._triangleDates.push(date); - this._triangleColors.push(color); - this._triangleDates.push(date); - this._emptyTriangleBuffer(); - }, - clear: function () { - this._triangleColors.length = 0; - this._trianglePoints.length = 0; - this._triangleDates.length = 0; - this._emptyTriangleBuffer(); - }, - _emptyTriangleBuffer: function () { - }, - _initTriangleBuffer: function () { - if (!this._triangleBuffers.length) { - var count = this._trianglePoints.length; - var triangleBuffer = null; - var triPointList = null; - var countLeft = count; - var index = 0; - var counter = 0; - var $enum1 = ss.enumerate(this._trianglePoints); - while ($enum1.moveNext()) { - var point = $enum1.current; - if (counter >= 90000 || triangleBuffer == null) { - if (triangleBuffer != null) { - triangleBuffer.unlock(); - } - var thisCount = Math.min(90000, countLeft); - countLeft -= thisCount; - triangleBuffer = new TimeSeriesLineVertexBuffer(thisCount); - this._triangleBuffers.push(triangleBuffer); - this._triangleBufferCounts.push(thisCount); - triPointList = triangleBuffer.lock(); - counter = 0; - } - triPointList[counter] = new TimeSeriesLineVertex(); - triPointList[counter].position = point; - triPointList[counter].normal = point; - var div3 = ss.truncate((index / 3)); - triPointList[counter].set_color(this._triangleColors[div3]); - triPointList[counter].tu = this._triangleDates[div3].startDate; - triPointList[counter].tv = this._triangleDates[div3].endDate; - index++; - counter++; - } - if (triangleBuffer != null) { - triangleBuffer.unlock(); - } - this._triangleColors.length = 0; - this._triangleDates.length = 0; - this._trianglePoints.length = 0; - this._dataToDraw = true; - } - }, - draw: function (renderContext, opacity, cull) { - if (this._trianglePoints.length < 1 && !this._dataToDraw) { - return; - } - if (renderContext.gl == null) { - } - else { - this._initTriangleBuffer(); - var $enum1 = ss.enumerate(this._triangleBuffers); - while ($enum1.moveNext()) { - var triBuffer = $enum1.current; - LineShaderNormalDates.use(renderContext, triBuffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this.depthBuffered, this.jNow, (this.timeSeries) ? this.decay : 0); - renderContext.gl.drawArrays(4, 0, triBuffer.count); - } - } - } - }; - - - // wwtlib.TriangleFanList - - function TriangleFanList() { - this._zBuffer = true; - this.timeSeries = false; - this.decay = 0; - this.jNow = 0; - this._shapes = []; - this._colors = []; - this._dates = []; - this._buffers = []; - this._bufferCounts = []; - } - var TriangleFanList$ = { - get_depthBuffered: function () { - return this._zBuffer; - }, - set_depthBuffered: function (value) { - this._zBuffer = value; - return value; - }, - addShape: function (shapePoints, color, date) { - this._shapes.push(shapePoints); - this._colors.push(color); - this._dates.push(date); - }, - draw: function (renderContext, opacity) { - if (opacity <= 0) { - return; - } - if (renderContext.gl != null) { - this._initBuffer(); - var $enum1 = ss.enumerate(this._buffers); - while ($enum1.moveNext()) { - var buffer = $enum1.current; - LineShaderNormalDates.use(renderContext, buffer.vertexBuffer, Color.fromArgb(255, 255, 255, 255), this._zBuffer, this.jNow, (this.timeSeries) ? this.decay : 0); - renderContext.gl.drawArrays(6, 0, buffer.count); - } - } - }, - _initBuffer: function () { - if (this._buffers.length !== this._shapes.length) { - this._buffers.length = 0; - var index = 0; - var $enum1 = ss.enumerate(this._shapes); - while ($enum1.moveNext()) { - var shape = $enum1.current; - var buffer = new TimeSeriesLineVertexBuffer(shape.length); - var pointList = buffer.lock(); - this._buffers.push(buffer); - this._bufferCounts.push(shape.length); - var counter = 0; - var $enum2 = ss.enumerate(shape); - while ($enum2.moveNext()) { - var point = $enum2.current; - pointList[counter] = new TimeSeriesLineVertex(); - pointList[counter].position = point; - pointList[counter].tu = this._dates[index].startDate; - pointList[counter].tv = this._dates[index].endDate; - pointList[counter].set_color(this._colors[index]); - counter++; - } - index++; - if (buffer != null) { - buffer.unlock(); - } - } - } - } - }; - - - // wwtlib.PointList - - function PointList(device) { - this._points = []; - this._colors = []; - this._dates = []; - this._sizes = []; - this.timeSeries = false; - this.showFarSide = false; - this.sky = false; - this.depthBuffered = true; - this.decay = 0; - this.scale = 1; - this.autoTime = true; - this.jNow = 0; - this._dataToDraw = false; - this.items = []; - this._imageReady = false; - this._init = false; - this.minSize = 2; - this._pointBuffers = []; - this._pointBufferCounts = []; - this._device = device; - } - var PointList$ = { - addPoint: function (v1, color, date, size) { - this._points.push(v1); - this._colors.push(color._clone()); - this._dates.push(date); - this._sizes.push(size); - this._emptyPointBuffer(); - }, - clear: function () { - this._colors.length = 0; - this._points.length = 0; - this._dates.length = 0; - this._sizes.length = 0; - this._emptyPointBuffer(); - }, - _emptyPointBuffer: function () { - var $enum1 = ss.enumerate(this._pointBuffers); - while ($enum1.moveNext()) { - var pointBuffer = $enum1.current; - pointBuffer.dispose(); - } - this._pointBuffers.length = 0; - this._init = false; - }, - _initBuffer: function (renderContext) { - var $this = this; - - if (!this._init) { - if (renderContext.gl == null) { - this._starProfile = document.createElement('img'); - this._starProfile.addEventListener('load', function (e) { - $this._imageReady = true; - }, false); - this._starProfile.src = URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png'); - this._worldList = new Array(this._points.length); - this._transformedList = new Array(this._points.length); - var index = 0; - var $enum1 = ss.enumerate(this._points); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - var item = new DataItem(); - item.location = pnt; - item.tranformed = new Vector3d(); - item.size = this._sizes[index]; - item.color = this._colors[index]; - this._worldList[index] = item.location; - this._transformedList[index] = item.tranformed; - this.items.push(item); - index++; - } - } - else { - if (!this._pointBuffers.length) { - if (PointList.starTexture == null) { - PointList.starTexture = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png')); - } - var count = this._points.length; - var pointBuffer = null; - var pointList = null; - var countLeft = count; - var index = 0; - var counter = 0; - var $enum2 = ss.enumerate(this._points); - while ($enum2.moveNext()) { - var point = $enum2.current; - if (counter >= 100000 || pointList == null) { - if (pointBuffer != null) { - pointBuffer.unlock(); - } - var thisCount = Math.min(100000, countLeft); - countLeft -= thisCount; - pointBuffer = new TimeSeriesPointVertexBuffer(thisCount); - pointList = pointBuffer.lock(); - this._pointBuffers.push(pointBuffer); - this._pointBufferCounts.push(thisCount); - counter = 0; - } - pointList[counter] = new TimeSeriesPointVertex(); - pointList[counter].position = point; - pointList[counter].pointSize = this._sizes[index]; - pointList[counter].tu = this._dates[index].startDate; - pointList[counter].tv = this._dates[index].endDate; - pointList[counter].set_color(this._colors[index]); - index++; - counter++; - } - if (pointBuffer != null) { - pointBuffer.unlock(); - } - } - } - this._init = true; - } - }, - draw: function (renderContext, opacity, cull) { - this._initBuffer(renderContext); - if (renderContext.gl == null) { - if (!this._imageReady) { - return; - } - renderContext.device.save(); - renderContext.WVP.projectArrayToScreen(this._worldList, this._transformedList); - var ctx = renderContext.device; - ctx.globalAlpha = 0.4; - var width = renderContext.width; - var height = renderContext.height; - var viewPoint = Vector3d.makeCopy(renderContext.get_viewPoint()); - var scaleFactor = renderContext.get_fovScale() / 100; - var $enum1 = ss.enumerate(this.items); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (item.tranformed.z < 1) { - var x = item.tranformed.x; - var y = item.tranformed.y; - var size = 0.1 * item.size / scaleFactor; - var half = size / 2; - if (x > -half && x < width + half && y > -half && y < height + half) { - ctx.beginPath(); - ctx.fillStyle = item.color.toFormat(); - ctx.arc(x, y, size, 0, Math.PI * 2, true); - ctx.fill(); - } - } - } - renderContext.device.restore(); - } - else { - var zero = new Vector3d(); - var matInv = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - matInv.invert(); - var cam = Vector3d._transformCoordinate(zero, matInv); - var $enum2 = ss.enumerate(this._pointBuffers); - while ($enum2.moveNext()) { - var pointBuffer = $enum2.current; - TimeSeriesPointSpriteShader.use(renderContext, pointBuffer.vertexBuffer, PointList.starTexture.texture2d, Color.fromArgb(255 * opacity, 255, 255, 255), this.depthBuffered, this.jNow, (this.timeSeries) ? this.decay : 0, cam, (this.scale * (renderContext.height / 960)), this.minSize, this.showFarSide, this.sky); - renderContext.gl.drawArrays(0, 0, pointBuffer.count); - } - } - }, - drawTextured: function (renderContext, texture, opacity) { - this._initBuffer(renderContext); - var zero = new Vector3d(); - var matInv = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - matInv.invert(); - var cam = Vector3d._transformCoordinate(zero, matInv); - var $enum1 = ss.enumerate(this._pointBuffers); - while ($enum1.moveNext()) { - var pointBuffer = $enum1.current; - TimeSeriesPointSpriteShader.use(renderContext, pointBuffer.vertexBuffer, texture, Color.fromArgb(255 * opacity, 255, 255, 255), this.depthBuffered, this.jNow, this.decay, cam, (this.scale * (renderContext.height / 960)), this.minSize, this.showFarSide, this.sky); - renderContext.gl.drawArrays(0, 0, pointBuffer.count); - } - } - }; - - - // wwtlib.TimeSeriesLineVertex - - function TimeSeriesLineVertex() { - this.position = new Vector3d(); - this.normal = new Vector3d(); - this.tu = 0; - this.tv = 0; - } - TimeSeriesLineVertex.create = function (position, normal, time, color) { - var temp = new TimeSeriesLineVertex(); - temp.position = position; - temp.normal = normal; - temp.tu = time; - temp.tv = 0; - temp.color = color; - return temp; - }; - var TimeSeriesLineVertex$ = { - get_color: function () { - return this.color; - }, - set_color: function (value) { - this.color = value; - return value; - } - }; - - - // wwtlib.TimeSeriesPointVertex - - function TimeSeriesPointVertex() { - this.pointSize = 0; - this.tu = 0; - this.tv = 0; - } - TimeSeriesPointVertex.create = function (position, size, time, color) { - var tmp = new TimeSeriesPointVertex(); - tmp.position = position; - tmp.pointSize = size; - tmp.tu = time; - tmp.tv = 0; - tmp.color = color; - return tmp; - }; - var TimeSeriesPointVertex$ = { - get_color: function () { - return this.color; - }, - set_color: function (value) { - this.color = value; - return value; - } - }; - - - // wwtlib.SimpleLineShader - - function SimpleLineShader() { - } - SimpleLineShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision highp float; \n' + ' uniform vec4 lineColor; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = lineColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' } \n' + ' \n'; - SimpleLineShader._frag = gl.createShader(35632); - gl.shaderSource(SimpleLineShader._frag, fragShaderText); - gl.compileShader(SimpleLineShader._frag); - var stat = gl.getShaderParameter(SimpleLineShader._frag, 35713); - SimpleLineShader._vert = gl.createShader(35633); - gl.shaderSource(SimpleLineShader._vert, vertexShaderText); - gl.compileShader(SimpleLineShader._vert); - var stat1 = gl.getShaderParameter(SimpleLineShader._vert, 35713); - SimpleLineShader._prog = gl.createProgram(); - gl.attachShader(SimpleLineShader._prog, SimpleLineShader._vert); - gl.attachShader(SimpleLineShader._prog, SimpleLineShader._frag); - gl.linkProgram(SimpleLineShader._prog); - var errcode = gl.getProgramParameter(SimpleLineShader._prog, 35714); - gl.useProgram(SimpleLineShader._prog); - SimpleLineShader.vertLoc = gl.getAttribLocation(SimpleLineShader._prog, 'aVertexPosition'); - SimpleLineShader.lineColorLoc = gl.getUniformLocation(SimpleLineShader._prog, 'lineColor'); - SimpleLineShader.projMatLoc = gl.getUniformLocation(SimpleLineShader._prog, 'uPMatrix'); - SimpleLineShader.mvMatLoc = gl.getUniformLocation(SimpleLineShader._prog, 'uMVMatrix'); - gl.enable(3042); - gl.blendFunc(770, 771); - SimpleLineShader.initialized = true; - }; - SimpleLineShader.use = function (renderContext, vertex, lineColor, useDepth) { - var gl = renderContext.gl; - if (gl != null) { - if (!SimpleLineShader.initialized) { - SimpleLineShader.init(renderContext); - } - gl.useProgram(SimpleLineShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(SimpleLineShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(SimpleLineShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform4f(SimpleLineShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); - if (renderContext.space || !useDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.enableVertexAttribArray(SimpleLineShader.vertLoc); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.vertexAttribPointer(SimpleLineShader.vertLoc, 3, 5126, false, 0, 0); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var SimpleLineShader$ = { - - }; - - - // wwtlib.SimpleLineShader2D - - function SimpleLineShader2D() { - } - SimpleLineShader2D.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision highp float; \n' + ' uniform vec4 lineColor; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = lineColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = vec4(aVertexPosition, 1.0); \n' + ' } \n' + ' \n'; - SimpleLineShader2D._frag = gl.createShader(35632); - gl.shaderSource(SimpleLineShader2D._frag, fragShaderText); - gl.compileShader(SimpleLineShader2D._frag); - var stat = gl.getShaderParameter(SimpleLineShader2D._frag, 35713); - SimpleLineShader2D._vert = gl.createShader(35633); - gl.shaderSource(SimpleLineShader2D._vert, vertexShaderText); - gl.compileShader(SimpleLineShader2D._vert); - var stat1 = gl.getShaderParameter(SimpleLineShader2D._vert, 35713); - SimpleLineShader2D._prog = gl.createProgram(); - gl.attachShader(SimpleLineShader2D._prog, SimpleLineShader2D._vert); - gl.attachShader(SimpleLineShader2D._prog, SimpleLineShader2D._frag); - gl.linkProgram(SimpleLineShader2D._prog); - var errcode = gl.getProgramParameter(SimpleLineShader2D._prog, 35714); - gl.useProgram(SimpleLineShader2D._prog); - SimpleLineShader2D.vertLoc = gl.getAttribLocation(SimpleLineShader2D._prog, 'aVertexPosition'); - SimpleLineShader2D.lineColorLoc = gl.getUniformLocation(SimpleLineShader2D._prog, 'lineColor'); - gl.enable(3042); - gl.blendFunc(770, 771); - SimpleLineShader2D.initialized = true; - }; - SimpleLineShader2D.use = function (renderContext, vertex, lineColor, useDepth) { - var gl = renderContext.gl; - if (gl != null) { - if (!SimpleLineShader2D.initialized) { - SimpleLineShader2D.init(renderContext); - } - gl.useProgram(SimpleLineShader2D._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform4f(SimpleLineShader2D.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); - if (renderContext.space || !useDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.enableVertexAttribArray(SimpleLineShader2D.vertLoc); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.vertexAttribPointer(SimpleLineShader2D.vertLoc, 3, 5126, false, 0, 0); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var SimpleLineShader2D$ = { - - }; - - - // wwtlib.OrbitLineShader - - function OrbitLineShader() { - } - OrbitLineShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision highp float; \n' + ' uniform vec4 lineColor; \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = lineColor * vColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec4 aVertexColor; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vColor = aVertexColor; \n' + ' } \n' + ' \n'; - OrbitLineShader._frag = gl.createShader(35632); - gl.shaderSource(OrbitLineShader._frag, fragShaderText); - gl.compileShader(OrbitLineShader._frag); - var stat = gl.getShaderParameter(OrbitLineShader._frag, 35713); - OrbitLineShader._vert = gl.createShader(35633); - gl.shaderSource(OrbitLineShader._vert, vertexShaderText); - gl.compileShader(OrbitLineShader._vert); - var stat1 = gl.getShaderParameter(OrbitLineShader._vert, 35713); - OrbitLineShader._prog = gl.createProgram(); - gl.attachShader(OrbitLineShader._prog, OrbitLineShader._vert); - gl.attachShader(OrbitLineShader._prog, OrbitLineShader._frag); - gl.linkProgram(OrbitLineShader._prog); - var errcode = gl.getProgramParameter(OrbitLineShader._prog, 35714); - gl.useProgram(OrbitLineShader._prog); - OrbitLineShader.vertLoc = gl.getAttribLocation(OrbitLineShader._prog, 'aVertexPosition'); - OrbitLineShader.colorLoc = gl.getAttribLocation(OrbitLineShader._prog, 'aVertexColor'); - OrbitLineShader.lineColorLoc = gl.getUniformLocation(OrbitLineShader._prog, 'lineColor'); - OrbitLineShader.projMatLoc = gl.getUniformLocation(OrbitLineShader._prog, 'uPMatrix'); - OrbitLineShader.mvMatLoc = gl.getUniformLocation(OrbitLineShader._prog, 'uMVMatrix'); - gl.enable(3042); - gl.blendFunc(770, 771); - OrbitLineShader.initialized = true; - }; - OrbitLineShader.use = function (renderContext, vertex, lineColor) { - var gl = renderContext.gl; - if (gl != null) { - if (!OrbitLineShader.initialized) { - OrbitLineShader.init(renderContext); - } - gl.useProgram(OrbitLineShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(OrbitLineShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(OrbitLineShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform4f(OrbitLineShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); - if (renderContext.space) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.enableVertexAttribArray(OrbitLineShader.vertLoc); - gl.enableVertexAttribArray(OrbitLineShader.colorLoc); - gl.vertexAttribPointer(OrbitLineShader.vertLoc, 3, 5126, false, 28, 0); - gl.vertexAttribPointer(OrbitLineShader.colorLoc, 4, 5126, false, 28, 12); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var OrbitLineShader$ = { - - }; - - - // wwtlib.LineShaderNormalDates - - function LineShaderNormalDates() { - } - LineShaderNormalDates.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision highp float; \n' + ' uniform vec4 lineColor; \n' + ' varying lowp vec4 vColor; \n' + ' void main(void) \n' + ' { \n' + ' gl_FragColor = lineColor * vColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec4 aVertexColor; \n' + ' attribute vec2 aTime; \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' uniform float jNow; \n' + ' uniform float decay; \n' + ' \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) \n' + ' { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' float dAlpha = 1.0; \n' + ' if ( decay > 0.0) \n' + ' { \n' + ' dAlpha = 1.0 - ((jNow - aTime.y) / decay); \n ' + ' if (dAlpha > 1.0 ) \n' + ' { \n' + ' dAlpha = 1.0; \n' + ' } \n' + ' } \n' + ' if (jNow < aTime.x && decay > 0.0) \n' + ' { \n' + ' vColor = vec4(1, 1, 1, 1); \n' + ' } \n' + ' else \n' + ' { \n' + ' vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha * aVertexColor.a); \n' + ' } \n' + ' } \n' + ' \n'; - LineShaderNormalDates._frag = gl.createShader(35632); - gl.shaderSource(LineShaderNormalDates._frag, fragShaderText); - gl.compileShader(LineShaderNormalDates._frag); - var stat = gl.getShaderParameter(LineShaderNormalDates._frag, 35713); - LineShaderNormalDates._vert = gl.createShader(35633); - gl.shaderSource(LineShaderNormalDates._vert, vertexShaderText); - gl.compileShader(LineShaderNormalDates._vert); - var stat1 = gl.getShaderParameter(LineShaderNormalDates._vert, 35713); - LineShaderNormalDates._prog = gl.createProgram(); - gl.attachShader(LineShaderNormalDates._prog, LineShaderNormalDates._vert); - gl.attachShader(LineShaderNormalDates._prog, LineShaderNormalDates._frag); - gl.linkProgram(LineShaderNormalDates._prog); - var errcode = gl.getProgramParameter(LineShaderNormalDates._prog, 35714); - gl.useProgram(LineShaderNormalDates._prog); - LineShaderNormalDates.vertLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aVertexPosition'); - LineShaderNormalDates.colorLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aVertexColor'); - LineShaderNormalDates.timeLoc = gl.getAttribLocation(LineShaderNormalDates._prog, 'aTime'); - LineShaderNormalDates.lineColorLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'lineColor'); - LineShaderNormalDates.projMatLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'uPMatrix'); - LineShaderNormalDates.mvMatLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'uMVMatrix'); - LineShaderNormalDates.jNowLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'jNow'); - LineShaderNormalDates.decayLoc = gl.getUniformLocation(LineShaderNormalDates._prog, 'decay'); - gl.enable(3042); - gl.blendFunc(770, 771); - LineShaderNormalDates.initialized = true; - }; - LineShaderNormalDates.use = function (renderContext, vertex, lineColor, zBuffer, jNow, decay) { - var gl = renderContext.gl; - if (gl != null) { - if (!LineShaderNormalDates.initialized) { - LineShaderNormalDates.init(renderContext); - } - gl.useProgram(LineShaderNormalDates._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(LineShaderNormalDates.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(LineShaderNormalDates.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform4f(LineShaderNormalDates.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, 1); - gl.uniform1f(LineShaderNormalDates.jNowLoc, jNow); - gl.uniform1f(LineShaderNormalDates.decayLoc, decay); - if (zBuffer) { - gl.enable(2929); - } - else { - gl.disable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.enableVertexAttribArray(LineShaderNormalDates.vertLoc); - gl.enableVertexAttribArray(LineShaderNormalDates.colorLoc); - gl.vertexAttribPointer(LineShaderNormalDates.vertLoc, 3, 5126, false, 36, 0); - gl.vertexAttribPointer(LineShaderNormalDates.colorLoc, 4, 5126, false, 36, 12); - gl.vertexAttribPointer(LineShaderNormalDates.timeLoc, 2, 5126, false, 36, 28); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var LineShaderNormalDates$ = { - - }; - - - // wwtlib.TimeSeriesPointSpriteShader - - function TimeSeriesPointSpriteShader() { - } - TimeSeriesPointSpriteShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' uniform vec4 lineColor; \n' + ' varying lowp vec4 vColor; \n' + ' uniform sampler2D uSampler; \n' + ' void main(void) \n' + ' { \n' + ' vec4 texColor; \n' + ' texColor = texture2D(uSampler, gl_PointCoord); \n' + ' \n' + ' \n' + ' gl_FragColor = lineColor * vColor * texColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec4 aVertexColor; \n' + ' attribute vec2 aTime; \n' + ' attribute float aPointSize; \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' uniform float jNow; \n' + ' uniform vec3 cameraPosition; \n' + ' uniform float decay; \n' + ' uniform float scale; \n' + ' uniform float minSize; \n' + ' uniform float sky; \n' + ' uniform float showFarSide; \n' + ' \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) \n' + ' { \n' + ' float dotCam = dot( normalize(cameraPosition-aVertexPosition), normalize(aVertexPosition)); \n' + ' float dist = distance(aVertexPosition, cameraPosition); \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' float dAlpha = 1.0; \n' + ' if ( decay > 0.0) \n' + ' { \n' + ' dAlpha = 1.0 - ((jNow - aTime.y) / decay); \n ' + ' if (dAlpha > 1.0 ) \n' + ' { \n' + ' dAlpha = 1.0; \n' + ' } \n' + ' } \n' + ' if ( showFarSide == 0.0 && (dotCam * sky) < 0.0 || (jNow < aTime.x && decay > 0.0)) \n' + ' { \n' + ' vColor = vec4(0.0, 0.0, 0.0, 0.0); \n' + ' } \n' + ' else \n' + ' { \n' + ' vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha); \n' + ' } \n' + ' float lSize = scale; \n' + ' if (scale < 0.0) \n' + ' { \n' + ' lSize = -scale; \n' + ' dist = 1.0; \n' + ' } \n' + ' gl_PointSize = max(minSize, (lSize * ( aPointSize ) / dist)); \n' + ' } \n' + ' \n'; - TimeSeriesPointSpriteShader._frag = gl.createShader(35632); - gl.shaderSource(TimeSeriesPointSpriteShader._frag, fragShaderText); - gl.compileShader(TimeSeriesPointSpriteShader._frag); - var stat = gl.getShaderParameter(TimeSeriesPointSpriteShader._frag, 35713); - TimeSeriesPointSpriteShader._vert = gl.createShader(35633); - gl.shaderSource(TimeSeriesPointSpriteShader._vert, vertexShaderText); - gl.compileShader(TimeSeriesPointSpriteShader._vert); - var stat1 = gl.getShaderParameter(TimeSeriesPointSpriteShader._vert, 35713); - var compilationLog = gl.getShaderInfoLog(TimeSeriesPointSpriteShader._vert); - TimeSeriesPointSpriteShader._prog = gl.createProgram(); - gl.attachShader(TimeSeriesPointSpriteShader._prog, TimeSeriesPointSpriteShader._vert); - gl.attachShader(TimeSeriesPointSpriteShader._prog, TimeSeriesPointSpriteShader._frag); - gl.linkProgram(TimeSeriesPointSpriteShader._prog); - var errcode = gl.getProgramParameter(TimeSeriesPointSpriteShader._prog, 35714); - gl.useProgram(TimeSeriesPointSpriteShader._prog); - TimeSeriesPointSpriteShader.vertLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aVertexPosition'); - TimeSeriesPointSpriteShader.colorLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aVertexColor'); - TimeSeriesPointSpriteShader.pointSizeLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aPointSize'); - TimeSeriesPointSpriteShader.timeLoc = gl.getAttribLocation(TimeSeriesPointSpriteShader._prog, 'aTime'); - TimeSeriesPointSpriteShader.projMatLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uPMatrix'); - TimeSeriesPointSpriteShader.mvMatLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uMVMatrix'); - TimeSeriesPointSpriteShader.sampLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'uSampler'); - TimeSeriesPointSpriteShader.jNowLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'jNow'); - TimeSeriesPointSpriteShader.decayLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'decay'); - TimeSeriesPointSpriteShader.lineColorLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'lineColor'); - TimeSeriesPointSpriteShader.cameraPosLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'cameraPosition'); - TimeSeriesPointSpriteShader.scaleLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'scale'); - TimeSeriesPointSpriteShader.skyLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'sky'); - TimeSeriesPointSpriteShader.showFarSideLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'showFarSide'); - TimeSeriesPointSpriteShader.minSizeLoc = gl.getUniformLocation(TimeSeriesPointSpriteShader._prog, 'minSize'); - gl.enable(3042); - TimeSeriesPointSpriteShader.initialized = true; - }; - TimeSeriesPointSpriteShader.use = function (renderContext, vertex, texture, lineColor, zBuffer, jNow, decay, camera, scale, minSize, showFarSide, sky) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!TimeSeriesPointSpriteShader.initialized) { - TimeSeriesPointSpriteShader.init(renderContext); - } - gl.useProgram(TimeSeriesPointSpriteShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(TimeSeriesPointSpriteShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(TimeSeriesPointSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(TimeSeriesPointSpriteShader.sampLoc, 0); - gl.uniform1f(TimeSeriesPointSpriteShader.jNowLoc, jNow); - gl.uniform1f(TimeSeriesPointSpriteShader.decayLoc, decay); - gl.uniform4f(TimeSeriesPointSpriteShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); - gl.uniform3f(TimeSeriesPointSpriteShader.cameraPosLoc, camera.x, camera.y, camera.z); - gl.uniform1f(TimeSeriesPointSpriteShader.scaleLoc, scale); - gl.uniform1f(TimeSeriesPointSpriteShader.minSizeLoc, minSize); - gl.uniform1f(TimeSeriesPointSpriteShader.showFarSideLoc, (showFarSide) ? 1 : 0); - gl.uniform1f(TimeSeriesPointSpriteShader.skyLoc, (sky) ? -1 : 1); - if (zBuffer) { - gl.enable(2929); - } - else { - gl.disable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.vertLoc); - gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.colorLoc); - gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.pointSizeLoc); - gl.enableVertexAttribArray(TimeSeriesPointSpriteShader.timeLoc); - gl.vertexAttribPointer(TimeSeriesPointSpriteShader.vertLoc, 3, 5126, false, 40, 0); - gl.vertexAttribPointer(TimeSeriesPointSpriteShader.colorLoc, 4, 5126, false, 40, 12); - gl.vertexAttribPointer(TimeSeriesPointSpriteShader.pointSizeLoc, 1, 5126, false, 40, 36); - gl.vertexAttribPointer(TimeSeriesPointSpriteShader.timeLoc, 2, 5126, false, 40, 28); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 1); - } - }; - var TimeSeriesPointSpriteShader$ = { - - }; - - - // wwtlib.KeplerPointSpriteShader - - function KeplerPointSpriteShader() { - } - KeplerPointSpriteShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' uniform vec4 lineColor; \n' + ' varying lowp vec4 vColor; \n' + ' uniform sampler2D uSampler; \n' + ' void main(void) \n' + ' { \n' + ' vec4 texColor; \n' + ' texColor = texture2D(uSampler, gl_PointCoord); \n' + ' \n' + ' \n' + ' gl_FragColor = lineColor * vColor * texColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 ABC; \n' + ' attribute vec3 abc; \n' + ' attribute float PointSize; \n' + ' attribute vec4 Color; \n' + ' attribute vec2 we; \n' + ' attribute vec2 nT; \n' + ' attribute vec2 az; \n' + ' attribute vec2 orbit; \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' uniform float jNow; \n' + ' uniform vec3 cameraPosition; \n' + ' uniform float MM; \n' + ' uniform float scaling; \n' + ' uniform float minSize; \n' + ' uniform float opacity; \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) \n' + ' { \n' + ' float M = nT.x * (jNow - nT.y) * 0.01745329251994; \n' + ' float e = we.y; \n' + ' float a = az.x; \n' + ' float PI = 3.1415926535897932384; \n' + ' float w = we.x* 0.01745329251994; \n' + ' float F = 1.0; \n' + ' if (M < 0.0) \n' + ' F = -1.0; \n' + ' M = abs(M) / (2.0 * PI); \n' + ' M = (M - float(int(M)))*2.0 *PI *F; \n' + ' if (MM != 0.0) \n' + ' { \n' + ' M = MM + (1.0- orbit.x) *2.0 *PI; \n' + ' if (M > (2.0*PI)) \n' + ' M = M - (2.0*PI); \n' + ' } \n' + ' \n' + ' if (M < 0.0) \n' + ' M += 2.0 *PI; \n' + ' F = 1.0; \n' + ' if (M > PI) \n' + ' F = -1.0; \n' + ' if (M > PI) \n' + ' M = 2.0 *PI - M; \n' + ' \n' + ' float E = PI / 2.0; \n' + ' float scale = PI / 4.0; \n' + ' for (int i =0; i<23; i++) \n' + ' { \n' + ' float R = E - e *sin(E); \n' + ' if (M > R) \n' + ' \tE += scale; \n' + ' else \n' + ' \tE -= scale; \n' + ' scale /= 2.0; \n' + ' } \n' + ' E = E * F; \n' + ' \n' + ' float v = 2.0 * atan(sqrt((1.0 + e) / (1.0 -e )) * tan(E/2.0)); \n' + ' float r = a * (1.0-e * cos(E)); \n' + ' \n' + ' vec4 pnt; \n' + ' pnt.x = r * abc.x * sin(ABC.x + w + v); \n' + ' pnt.z = r * abc.y * sin(ABC.y + w + v); \n' + ' pnt.y = r * abc.z * sin(ABC.z + w + v); \n' + ' pnt.w = 1.0; \n' + ' \n' + ' float dist = distance(pnt.xyz, cameraPosition.xyz); \n' + ' gl_Position = uPMatrix * uMVMatrix * pnt; \n' + ' vColor.a = opacity * (1.0-(orbit.x)); \n' + ' vColor.r = Color.r; \n' + ' vColor.g = Color.g; \n' + ' vColor.b = Color.b; \n' + ' gl_PointSize = max(minSize, scaling * (PointSize / dist)); \n' + ' } \n'; - KeplerPointSpriteShader._frag = gl.createShader(35632); - gl.shaderSource(KeplerPointSpriteShader._frag, fragShaderText); - gl.compileShader(KeplerPointSpriteShader._frag); - var stat = gl.getShaderParameter(KeplerPointSpriteShader._frag, 35713); - KeplerPointSpriteShader._vert = gl.createShader(35633); - gl.shaderSource(KeplerPointSpriteShader._vert, vertexShaderText); - gl.compileShader(KeplerPointSpriteShader._vert); - var stat1 = gl.getShaderParameter(KeplerPointSpriteShader._vert, 35713); - var compilationLog = gl.getShaderInfoLog(KeplerPointSpriteShader._vert); - KeplerPointSpriteShader._prog = gl.createProgram(); - gl.attachShader(KeplerPointSpriteShader._prog, KeplerPointSpriteShader._vert); - gl.attachShader(KeplerPointSpriteShader._prog, KeplerPointSpriteShader._frag); - gl.linkProgram(KeplerPointSpriteShader._prog); - var errcode = gl.getProgramParameter(KeplerPointSpriteShader._prog, 35714); - gl.useProgram(KeplerPointSpriteShader._prog); - KeplerPointSpriteShader.abcLoc1 = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'abc'); - KeplerPointSpriteShader.abcLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'ABC'); - KeplerPointSpriteShader.pointSizeLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'PointSize'); - KeplerPointSpriteShader.colorLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'Color'); - KeplerPointSpriteShader.weLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'we'); - KeplerPointSpriteShader.nTLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'nT'); - KeplerPointSpriteShader.azLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'az'); - KeplerPointSpriteShader.orbitLoc = gl.getAttribLocation(KeplerPointSpriteShader._prog, 'orbit'); - KeplerPointSpriteShader.projMatLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uPMatrix'); - KeplerPointSpriteShader.mvMatLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uMVMatrix'); - KeplerPointSpriteShader.jNowLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'jNow'); - KeplerPointSpriteShader.cameraPosLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'cameraPosition'); - KeplerPointSpriteShader.mmLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'MM'); - KeplerPointSpriteShader.scaleLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'scaling'); - KeplerPointSpriteShader.minSizeLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'minSize'); - KeplerPointSpriteShader.lineColorLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'lineColor'); - KeplerPointSpriteShader.opacityLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'opacity'); - KeplerPointSpriteShader.sampLoc = gl.getUniformLocation(KeplerPointSpriteShader._prog, 'uSampler'); - gl.enable(3042); - KeplerPointSpriteShader.initialized = true; - }; - KeplerPointSpriteShader.use = function (renderContext, worldView, vertex, texture, lineColor, opacity, zBuffer, jNow, MM, camera, scale, minSize) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!KeplerPointSpriteShader.initialized) { - KeplerPointSpriteShader.init(renderContext); - } - gl.useProgram(KeplerPointSpriteShader._prog); - gl.uniformMatrix4fv(KeplerPointSpriteShader.mvMatLoc, false, worldView.floatArray()); - gl.uniformMatrix4fv(KeplerPointSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(KeplerPointSpriteShader.sampLoc, 0); - gl.uniform1f(KeplerPointSpriteShader.jNowLoc, jNow); - gl.uniform1f(KeplerPointSpriteShader.mmLoc, MM); - gl.uniform4f(KeplerPointSpriteShader.lineColorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); - gl.uniform1f(KeplerPointSpriteShader.opacityLoc, opacity); - gl.uniform3f(KeplerPointSpriteShader.cameraPosLoc, camera.x, camera.y, camera.z); - gl.uniform1f(KeplerPointSpriteShader.scaleLoc, scale); - gl.uniform1f(KeplerPointSpriteShader.minSizeLoc, minSize); - if (zBuffer) { - gl.enable(2929); - } - else { - gl.disable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.bindBuffer(34963, null); - gl.enableVertexAttribArray(KeplerPointSpriteShader.abcLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.abcLoc1); - gl.enableVertexAttribArray(KeplerPointSpriteShader.colorLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.pointSizeLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.weLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.nTLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.azLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.orbitLoc); - gl.enableVertexAttribArray(KeplerPointSpriteShader.weLoc); - gl.vertexAttribPointer(KeplerPointSpriteShader.abcLoc, 3, 5126, false, 76, 0); - gl.vertexAttribPointer(KeplerPointSpriteShader.abcLoc1, 3, 5126, false, 76, 12); - gl.vertexAttribPointer(KeplerPointSpriteShader.pointSizeLoc, 1, 5126, false, 76, 24); - gl.vertexAttribPointer(KeplerPointSpriteShader.colorLoc, 4, 5126, false, 76, 28); - gl.vertexAttribPointer(KeplerPointSpriteShader.weLoc, 2, 5126, false, 76, 44); - gl.vertexAttribPointer(KeplerPointSpriteShader.nTLoc, 2, 5126, false, 76, 52); - gl.vertexAttribPointer(KeplerPointSpriteShader.azLoc, 2, 5126, false, 76, 60); - gl.vertexAttribPointer(KeplerPointSpriteShader.orbitLoc, 2, 5126, false, 76, 68); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 1); - } - }; - var KeplerPointSpriteShader$ = { - - }; - - - // wwtlib.EllipseShader - - function EllipseShader() { - } - EllipseShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' varying lowp vec4 vColor; \n' + ' void main(void) \n' + ' { \n' + ' gl_FragColor = vColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 Angle; \n' + ' uniform mat4 matWVP; \n' + ' uniform mat4 matPosition; \n' + ' uniform vec3 positionNow; \n' + ' uniform float semiMajorAxis; \n' + ' uniform float eccentricity; \n' + ' uniform vec4 color; \n' + ' uniform float eccentricAnomaly; \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) \n' + ' { \n' + ' float fade = (1.0 - Angle.x); \n' + ' float PI = 3.1415927; \n' + ' float E = eccentricAnomaly - Angle.x * 2.0 * PI; \n' + ' vec2 semiAxes = vec2(1.0, sqrt(1.0 - eccentricity * eccentricity)) * semiMajorAxis; \n' + ' vec2 planePos = semiAxes * vec2(cos(E) - eccentricity, sin(E)); \n' + ' if (Angle.x == 0.0) \n' + ' gl_Position = matPosition * vec4(positionNow, 1.0); \n' + ' else \n' + ' gl_Position = matWVP * vec4(planePos.x, planePos.y, 0.0, 1.0); \n' + ' vColor = vec4(color.rgb, fade * color.a); \n' + ' } \n'; - EllipseShader._frag = gl.createShader(35632); - gl.shaderSource(EllipseShader._frag, fragShaderText); - gl.compileShader(EllipseShader._frag); - var stat = gl.getShaderParameter(EllipseShader._frag, 35713); - EllipseShader._vert = gl.createShader(35633); - gl.shaderSource(EllipseShader._vert, vertexShaderText); - gl.compileShader(EllipseShader._vert); - var stat1 = gl.getShaderParameter(EllipseShader._vert, 35713); - var compilationLog = gl.getShaderInfoLog(EllipseShader._vert); - EllipseShader._prog = gl.createProgram(); - gl.attachShader(EllipseShader._prog, EllipseShader._vert); - gl.attachShader(EllipseShader._prog, EllipseShader._frag); - gl.linkProgram(EllipseShader._prog); - var errcode = gl.getProgramParameter(EllipseShader._prog, 35714); - gl.useProgram(EllipseShader._prog); - EllipseShader.angleLoc = gl.getAttribLocation(EllipseShader._prog, 'Angle'); - EllipseShader.matWVPLoc = gl.getUniformLocation(EllipseShader._prog, 'matWVP'); - EllipseShader.matPositionLoc = gl.getUniformLocation(EllipseShader._prog, 'matPosition'); - EllipseShader.positionNowLoc = gl.getUniformLocation(EllipseShader._prog, 'positionNow'); - EllipseShader.colorLoc = gl.getUniformLocation(EllipseShader._prog, 'color'); - EllipseShader.semiMajorAxisLoc = gl.getUniformLocation(EllipseShader._prog, 'semiMajorAxis'); - EllipseShader.eccentricityLoc = gl.getUniformLocation(EllipseShader._prog, 'eccentricity'); - EllipseShader.eccentricAnomalyLoc = gl.getUniformLocation(EllipseShader._prog, 'eccentricAnomaly'); - gl.enable(3042); - EllipseShader.initialized = true; - }; - EllipseShader.use = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, lineColor, opacity, world, positionNow) { - var gl = renderContext.gl; - if (gl != null) { - if (!EllipseShader.initialized) { - EllipseShader.init(renderContext); - } - gl.useProgram(EllipseShader._prog); - var WVPPos = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(world, renderContext.get_view()), renderContext.get_projection()); - var WVP = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()), renderContext.get_projection()); - gl.uniformMatrix4fv(EllipseShader.matWVPLoc, false, WVP.floatArray()); - gl.uniformMatrix4fv(EllipseShader.matPositionLoc, false, WVPPos.floatArray()); - gl.uniform3f(EllipseShader.positionNowLoc, positionNow.x, positionNow.y, positionNow.z); - gl.uniform4f(EllipseShader.colorLoc, lineColor.r / 255, lineColor.g / 255, lineColor.b / 255, lineColor.a / 255); - gl.uniform1f(EllipseShader.semiMajorAxisLoc, semiMajorAxis); - gl.uniform1f(EllipseShader.eccentricityLoc, eccentricity); - gl.uniform1f(EllipseShader.eccentricAnomalyLoc, eccentricAnomaly); - gl.disable(2929); - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.enableVertexAttribArray(EllipseShader.angleLoc); - gl.vertexAttribPointer(EllipseShader.angleLoc, 3, 5126, false, 0, 0); - gl.lineWidth(1); - gl.enable(3042); - gl.blendFunc(770, 1); - } - }; - var EllipseShader$ = { - - }; - - - // wwtlib.ModelShader - - function ModelShader() { - } - ModelShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' uniform float opacity; \n' + ' uniform vec3 uSunPosition; \n' + ' uniform float uMinBrightness; \n' + ' uniform vec3 uAtmosphereColor; \n' + ' \n' + ' void main(void) { \n' + ' vec3 normal = normalize(vNormal); \n' + ' vec3 camVN = normalize(vCamVector); \n' + ' vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n' + ' float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n' + ' float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n' + ' atm = (dt > uMinBrightness) ? atm : 0.0; \n' + ' if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n' + ' vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' gl_FragColor = col * opacity; \n' + ' gl_FragColor.rgb *= dt; \n' + ' gl_FragColor.rgb += atm * uAtmosphereColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec3 aNormal; \n' + ' attribute vec2 aTextureCoord; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); \n' + ' vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); \n' + ' vTextureCoord = aTextureCoord; \n' + ' vNormal = normalT; \n' + ' } \n' + ' \n'; - ModelShader._frag = gl.createShader(35632); - gl.shaderSource(ModelShader._frag, fragShaderText); - gl.compileShader(ModelShader._frag); - var stat = gl.getShaderParameter(ModelShader._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(ModelShader._frag); - } - ModelShader._vert = gl.createShader(35633); - gl.shaderSource(ModelShader._vert, vertexShaderText); - gl.compileShader(ModelShader._vert); - var stat1 = gl.getShaderParameter(ModelShader._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(ModelShader._vert); - } - ModelShader._prog = gl.createProgram(); - gl.attachShader(ModelShader._prog, ModelShader._vert); - gl.attachShader(ModelShader._prog, ModelShader._frag); - gl.linkProgram(ModelShader._prog); - var errcode = gl.getProgramParameter(ModelShader._prog, 35714); - gl.useProgram(ModelShader._prog); - ModelShader.vertLoc = gl.getAttribLocation(ModelShader._prog, 'aVertexPosition'); - ModelShader.normalLoc = gl.getAttribLocation(ModelShader._prog, 'aNormal'); - ModelShader.textureLoc = gl.getAttribLocation(ModelShader._prog, 'aTextureCoord'); - ModelShader.projMatLoc = gl.getUniformLocation(ModelShader._prog, 'uPMatrix'); - ModelShader.mvMatLoc = gl.getUniformLocation(ModelShader._prog, 'uMVMatrix'); - ModelShader.sampLoc = gl.getUniformLocation(ModelShader._prog, 'uSampler'); - ModelShader.sunLoc = gl.getUniformLocation(ModelShader._prog, 'uSunPosition'); - ModelShader.minBrightnessLoc = gl.getUniformLocation(ModelShader._prog, 'uMinBrightness'); - ModelShader.opacityLoc = gl.getUniformLocation(ModelShader._prog, 'opacity'); - ModelShader.atmosphereColorLoc = gl.getUniformLocation(ModelShader._prog, 'uAtmosphereColor'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - ModelShader.initialized = true; - }; - ModelShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, stride) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!ModelShader.initialized) { - ModelShader.init(renderContext); - } - gl.useProgram(ModelShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(ModelShader.opacityLoc, opacity); - gl.uniform1f(ModelShader.minBrightnessLoc, (renderContext.lighting) ? ModelShader.minLightingBrightness : 1); - if (renderContext.lighting) { - gl.uniform3f(ModelShader.atmosphereColorLoc, ModelShader.atmosphereColor.r / 255, ModelShader.atmosphereColor.g / 255, ModelShader.atmosphereColor.b / 255); - } - else { - gl.uniform3f(ModelShader.atmosphereColorLoc, 0, 0, 0); - } - gl.uniformMatrix4fv(ModelShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(ModelShader.projMatLoc, false, renderContext.get_projection().floatArray()); - ModelShader.sunPosition.normalize(); - var mvInv = renderContext.get_view().clone(); - mvInv.set_m41(0); - mvInv.set_m42(0); - mvInv.set_m43(0); - mvInv.set_m44(1); - var sp = Vector3d._transformCoordinate(ModelShader.sunPosition, mvInv); - sp.normalize(); - gl.uniform3f(ModelShader.sunLoc, sp.x, sp.y, sp.z); - gl.uniform1i(ModelShader.sampLoc, 0); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(ModelShader.vertLoc); - gl.enableVertexAttribArray(ModelShader.normalLoc); - gl.enableVertexAttribArray(ModelShader.textureLoc); - gl.vertexAttribPointer(ModelShader.vertLoc, 3, 5126, false, stride, 0); - gl.vertexAttribPointer(ModelShader.normalLoc, 3, 5126, false, stride, 12); - gl.vertexAttribPointer(ModelShader.textureLoc, 2, 5126, false, stride, stride - 8); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var ModelShader$ = { - - }; - - - // wwtlib.ModelShaderTan - - function ModelShaderTan() { - } - ModelShaderTan.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' uniform float opacity; \n' + ' uniform vec3 uSunPosition; \n' + ' uniform float uMinBrightness; \n' + ' uniform vec3 uAtmosphereColor; \n' + ' \n' + ' void main(void) { \n' + ' vec3 normal = normalize(vNormal); \n' + ' vec3 camVN = normalize(vCamVector); \n' + ' vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n' + ' float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n' + ' float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n' + ' atm = (dt > uMinBrightness) ? atm : 0.0; \n' + ' if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n' + ' vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' gl_FragColor = col * opacity; \n' + ' gl_FragColor.rgb *= dt; \n' + ' gl_FragColor.rgb += atm * uAtmosphereColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec3 aNormal; \n' + ' attribute vec2 aTextureCoord; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz); \n' + ' vec3 normalT = normalize(mat3(uMVMatrix) * aNormal); \n' + ' vTextureCoord = aTextureCoord; \n' + ' vNormal = normalT; \n' + ' } \n' + ' \n'; - ModelShaderTan._frag = gl.createShader(35632); - gl.shaderSource(ModelShaderTan._frag, fragShaderText); - gl.compileShader(ModelShaderTan._frag); - var stat = gl.getShaderParameter(ModelShaderTan._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(ModelShaderTan._frag); - } - ModelShaderTan._vert = gl.createShader(35633); - gl.shaderSource(ModelShaderTan._vert, vertexShaderText); - gl.compileShader(ModelShaderTan._vert); - var stat1 = gl.getShaderParameter(ModelShaderTan._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(ModelShaderTan._vert); - } - ModelShaderTan._prog = gl.createProgram(); - gl.attachShader(ModelShaderTan._prog, ModelShaderTan._vert); - gl.attachShader(ModelShaderTan._prog, ModelShaderTan._frag); - gl.linkProgram(ModelShaderTan._prog); - var errcode = gl.getProgramParameter(ModelShaderTan._prog, 35714); - gl.useProgram(ModelShaderTan._prog); - ModelShaderTan.vertLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aVertexPosition'); - ModelShaderTan.normalLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aNormal'); - ModelShaderTan.textureLoc = gl.getAttribLocation(ModelShaderTan._prog, 'aTextureCoord'); - ModelShaderTan.projMatLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uPMatrix'); - ModelShaderTan.mvMatLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uMVMatrix'); - ModelShaderTan.sampLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uSampler'); - ModelShaderTan.sunLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uSunPosition'); - ModelShaderTan.minBrightnessLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uMinBrightness'); - ModelShaderTan.opacityLoc = gl.getUniformLocation(ModelShaderTan._prog, 'opacity'); - ModelShaderTan.atmosphereColorLoc = gl.getUniformLocation(ModelShaderTan._prog, 'uAtmosphereColor'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - ModelShaderTan.initialized = true; - }; - ModelShaderTan.use = function (renderContext, vertex, index, texture, opacity, noDepth, stride) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!ModelShaderTan.initialized) { - ModelShaderTan.init(renderContext); - } - gl.useProgram(ModelShaderTan._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(ModelShaderTan.opacityLoc, opacity); - gl.uniform1f(ModelShaderTan.minBrightnessLoc, (renderContext.lighting) ? ModelShaderTan.minLightingBrightness : 1); - if (renderContext.lighting) { - gl.uniform3f(ModelShaderTan.atmosphereColorLoc, ModelShaderTan.atmosphereColor.r / 255, ModelShaderTan.atmosphereColor.g / 255, ModelShaderTan.atmosphereColor.b / 255); - } - else { - gl.uniform3f(ModelShaderTan.atmosphereColorLoc, 0, 0, 0); - } - gl.uniformMatrix4fv(ModelShaderTan.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(ModelShaderTan.projMatLoc, false, renderContext.get_projection().floatArray()); - ModelShaderTan.sunPosition.normalize(); - var mvInv = renderContext.get_view().clone(); - mvInv.set_m41(0); - mvInv.set_m42(0); - mvInv.set_m43(0); - mvInv.set_m44(1); - var sp = Vector3d._transformCoordinate(ModelShaderTan.sunPosition, mvInv); - sp.normalize(); - gl.uniform3f(ModelShaderTan.sunLoc, -sp.x, -sp.y, -sp.z); - gl.uniform1i(ModelShaderTan.sampLoc, 0); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(ModelShaderTan.vertLoc); - gl.enableVertexAttribArray(ModelShaderTan.normalLoc); - gl.enableVertexAttribArray(ModelShaderTan.textureLoc); - gl.vertexAttribPointer(ModelShaderTan.vertLoc, 3, 5126, false, stride, 0); - gl.vertexAttribPointer(ModelShaderTan.normalLoc, 3, 5126, false, stride, 12); - gl.vertexAttribPointer(ModelShaderTan.textureLoc, 2, 5126, false, stride, stride - 8); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var ModelShaderTan$ = { - - }; - - - // wwtlib.TileShader - - function TileShader() { - } - TileShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' uniform float opacity; \n' + ' uniform vec3 uSunPosition; \n' + ' uniform float uMinBrightness; \n' + ' uniform vec3 uAtmosphereColor; \n' + ' \n' + ' void main(void) { \n' + ' vec3 normal = normalize(vNormal); \n' + ' vec3 camVN = normalize(vCamVector); \n' + ' vec3 cam = normalize(vec3(0.0,0.0,-1.0)); \n' + ' float dt = uMinBrightness + pow(max(0.0,- dot(normal,uSunPosition)),0.5); \n' + ' float atm = max(0.0, 1.0 - 2.5 * dot(cam,camVN)) + 0.3 * dt; \n' + ' atm = (dt > uMinBrightness) ? atm : 0.0; \n' + ' if ( uMinBrightness == 1.0 ) { dt = 1.0; atm= 0.0; } \n' + ' vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' gl_FragColor = col * opacity; \n' + ' gl_FragColor.rgb *= dt; \n' + ' gl_FragColor.rgb += atm * uAtmosphereColor; \n' + ' } \n'; - var vertexShaderText = '\r\n attribute vec3 aVertexPosition;\r\n attribute vec2 aTextureCoord;\r\n \r\n uniform mat4 uMVMatrix;\r\n uniform mat4 uPMatrix;\r\n uniform vec3 uCenterScreen;\r\n uniform vec3 uCenterWorld;\r\n\r\n varying vec2 vTextureCoord;\r\n varying vec3 vNormal;\r\n varying vec3 vCamVector;\r\n \r\n void main(void) {\r\n vec3 normal;\r\n if(length(uCenterWorld) > 0.00001){\r\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0);\r\n vCamVector = normalize((mat3(uMVMatrix) * (aVertexPosition + uCenterWorld)).xyz);\r\n normal = normalize(aVertexPosition + uCenterWorld);\r\n } else {\r\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\r\n vCamVector = normalize((mat3(uMVMatrix) * aVertexPosition).xyz);\r\n normal = normalize(aVertexPosition);\r\n }\r\n vec3 normalT = normalize(mat3(uMVMatrix) * normal);\r\n vTextureCoord = aTextureCoord;\r\n vNormal = normalT;\r\n }'; - TileShader._frag = gl.createShader(35632); - gl.shaderSource(TileShader._frag, fragShaderText); - gl.compileShader(TileShader._frag); - var stat = gl.getShaderParameter(TileShader._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(TileShader._frag); - } - TileShader._vert = gl.createShader(35633); - gl.shaderSource(TileShader._vert, vertexShaderText); - gl.compileShader(TileShader._vert); - var stat1 = gl.getShaderParameter(TileShader._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(TileShader._vert); - } - TileShader._prog = gl.createProgram(); - gl.attachShader(TileShader._prog, TileShader._vert); - gl.attachShader(TileShader._prog, TileShader._frag); - gl.linkProgram(TileShader._prog); - var errcode = gl.getProgramParameter(TileShader._prog, 35714); - gl.useProgram(TileShader._prog); - TileShader.vertLoc = gl.getAttribLocation(TileShader._prog, 'aVertexPosition'); - TileShader.textureLoc = gl.getAttribLocation(TileShader._prog, 'aTextureCoord'); - TileShader.projMatLoc = gl.getUniformLocation(TileShader._prog, 'uPMatrix'); - TileShader.mvMatLoc = gl.getUniformLocation(TileShader._prog, 'uMVMatrix'); - TileShader.sampLoc = gl.getUniformLocation(TileShader._prog, 'uSampler'); - TileShader.centerScreenLoc = gl.getUniformLocation(TileShader._prog, 'uCenterScreen'); - TileShader.centerWorldLoc = gl.getUniformLocation(TileShader._prog, 'uCenterWorld'); - TileShader.sunLoc = gl.getUniformLocation(TileShader._prog, 'uSunPosition'); - TileShader.minBrightnessLoc = gl.getUniformLocation(TileShader._prog, 'uMinBrightness'); - TileShader.opacityLoc = gl.getUniformLocation(TileShader._prog, 'opacity'); - TileShader.atmosphereColorLoc = gl.getUniformLocation(TileShader._prog, 'uAtmosphereColor'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - TileShader.initialized = true; - }; - TileShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, centerWorld) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!TileShader.initialized) { - TileShader.init(renderContext); - } - gl.useProgram(TileShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(TileShader.opacityLoc, opacity); - gl.uniform1f(TileShader.minBrightnessLoc, (renderContext.lighting) ? TileShader.minLightingBrightness : 1); - if (renderContext.lighting) { - gl.uniform3f(TileShader.atmosphereColorLoc, TileShader.atmosphereColor.r / 255, TileShader.atmosphereColor.g / 255, TileShader.atmosphereColor.b / 255); - } - else { - gl.uniform3f(TileShader.atmosphereColorLoc, 0, 0, 0); - } - gl.uniform3f(TileShader.centerWorldLoc, centerWorld.x, centerWorld.y, centerWorld.z); - if (centerWorld.lengthSq() > 0.001) { - var wvp = Matrix3d.multiplyMatrix(mvMat, renderContext.get_projection()); - var centerScreen = wvp.transform(centerWorld); - gl.uniform3f(TileShader.centerScreenLoc, centerScreen.x, centerScreen.y, centerScreen.z); - } - else { - gl.uniform3f(TileShader.centerScreenLoc, 0, 0, 0); - } - gl.uniformMatrix4fv(TileShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(TileShader.projMatLoc, false, renderContext.get_projection().floatArray()); - TileShader.sunPosition.normalize(); - var mvInv = renderContext.get_view().clone(); - mvInv.set_m41(0); - mvInv.set_m42(0); - mvInv.set_m43(0); - mvInv.set_m44(1); - var sp = Vector3d._transformCoordinate(TileShader.sunPosition, mvInv); - sp.normalize(); - gl.uniform3f(TileShader.sunLoc, -sp.x, -sp.y, -sp.z); - gl.uniform1i(TileShader.sampLoc, 0); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(TileShader.vertLoc); - gl.enableVertexAttribArray(TileShader.textureLoc); - gl.vertexAttribPointer(TileShader.vertLoc, 3, 5126, false, 20, 0); - gl.vertexAttribPointer(TileShader.textureLoc, 2, 5126, false, 20, 12); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var TileShader$ = { - - }; - - - // wwtlib.FitsShader - - function FitsShader() { - } - FitsShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = '#version 300 es\r\n precision mediump float;\r\n in vec2 vTextureCoord;\r\n in vec3 vNormal;\r\n in vec3 vCamVector;\r\n out vec4 fragmentColor;\r\n\r\n uniform sampler2D uSampler;\r\n uniform sampler2D colorSampler;\r\n uniform float blank;\r\n uniform float bzero;\r\n uniform float bscale;\r\n uniform float min;\r\n uniform float max;\r\n uniform bool containsBlanks;\r\n uniform bool transparentBlack;\r\n uniform int scaleType;\r\n uniform float opacity;\r\n \r\n bool isNaN(float value) {\r\n // See https://stackoverflow.com/questions/9446888/best-way-to-detect-nans-in-opengl-shaders\r\n // PKGW also finds that we need `value != value` on his Dell laptop running\r\n // Chrome on Linux.\r\n return (value != value) || !(value < 0.0 || 0.0 < value || value == 0.0);\r\n }\r\n\r\n void main(void) {\r\n //FITS images are flipped on the y axis\r\n vec4 color = texture(uSampler, vec2(vTextureCoord.x, 1.0 - vTextureCoord.y));\r\n if(isNaN(color.r) || (containsBlanks && abs(blank - color.r) < 0.00000001)){\r\n fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\r\n } else {\r\n float physicalValue = (bzero + bscale * color.r - min) / (max - min);\r\n if(transparentBlack && physicalValue <= 0.0){\r\n fragmentColor = vec4(0.0, 0.0, 0.0, 0.0);\r\n return;\r\n }\r\n \r\n physicalValue = clamp(physicalValue, 0.0, 1.0);\r\n\r\n switch(scaleType){\r\n case 1:\r\n physicalValue = log(physicalValue * 255.0 + 1.0 ) / log(256.0);\r\n break;\r\n case 2:\r\n physicalValue = physicalValue * physicalValue;\r\n break;\r\n case 3:\r\n physicalValue = sqrt(physicalValue);\r\n break;\r\n }\r\n vec4 colorFromColorMapper = texture(colorSampler, vec2(physicalValue, 0.5));\r\n fragmentColor = vec4(colorFromColorMapper.rgb, opacity);\r\n }\r\n }\r\n '; - var vertexShaderText = '#version 300 es\r\n in vec3 aVertexPosition;\r\n in vec2 aTextureCoord;\r\n \r\n uniform mat4 uMVMatrix;\r\n uniform mat4 uPMatrix;\r\n uniform vec3 uCenterScreen;\r\n \r\n out vec2 vTextureCoord;\r\n \r\n void main(void) {\r\n if(length(uCenterScreen) > 0.0000001) {\r\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0) + vec4(uCenterScreen, 1.0);\r\n } else {\r\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\r\n }\r\n vTextureCoord = aTextureCoord;\r\n }\r\n '; - FitsShader._frag = gl.createShader(35632); - gl.shaderSource(FitsShader._frag, fragShaderText); - gl.compileShader(FitsShader._frag); - var stat = gl.getShaderParameter(FitsShader._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(FitsShader._frag); - console.log(errorF); - } - FitsShader._vert = gl.createShader(35633); - gl.shaderSource(FitsShader._vert, vertexShaderText); - gl.compileShader(FitsShader._vert); - var stat1 = gl.getShaderParameter(FitsShader._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(FitsShader._vert); - console.log(errorV); - } - FitsShader._prog = gl.createProgram(); - gl.attachShader(FitsShader._prog, FitsShader._vert); - gl.attachShader(FitsShader._prog, FitsShader._frag); - gl.linkProgram(FitsShader._prog); - var errcode = gl.getProgramParameter(FitsShader._prog, 35714); - gl.useProgram(FitsShader._prog); - FitsShader.vertLoc = gl.getAttribLocation(FitsShader._prog, 'aVertexPosition'); - FitsShader.textureLoc = gl.getAttribLocation(FitsShader._prog, 'aTextureCoord'); - FitsShader.projMatLoc = gl.getUniformLocation(FitsShader._prog, 'uPMatrix'); - FitsShader.mvMatLoc = gl.getUniformLocation(FitsShader._prog, 'uMVMatrix'); - FitsShader.sampLoc = gl.getUniformLocation(FitsShader._prog, 'uSampler'); - FitsShader.colorLoc = gl.getUniformLocation(FitsShader._prog, 'colorSampler'); - FitsShader.centerScreenLoc = gl.getUniformLocation(FitsShader._prog, 'uCenterScreen'); - FitsShader.blank = gl.getUniformLocation(FitsShader._prog, 'blank'); - FitsShader.bzero = gl.getUniformLocation(FitsShader._prog, 'bzero'); - FitsShader.bscale = gl.getUniformLocation(FitsShader._prog, 'bscale'); - FitsShader.minLoc = gl.getUniformLocation(FitsShader._prog, 'min'); - FitsShader.maxLoc = gl.getUniformLocation(FitsShader._prog, 'max'); - FitsShader.transparentBlackLoc = gl.getUniformLocation(FitsShader._prog, 'transparentBlack'); - FitsShader.containsBlanksLoc = gl.getUniformLocation(FitsShader._prog, 'containsBlanks'); - FitsShader.scalingLocation = gl.getUniformLocation(FitsShader._prog, 'scaleType'); - FitsShader.opacityLoc = gl.getUniformLocation(FitsShader._prog, 'opacity'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - FitsShader.initialized = true; - }; - FitsShader.use = function (renderContext, vertex, index, texture, opacity, noDepth, centerWorld) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!FitsShader.initialized) { - FitsShader.init(renderContext); - } - gl.useProgram(FitsShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(FitsShader.opacityLoc, opacity); - gl.uniformMatrix4fv(FitsShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(FitsShader.projMatLoc, false, renderContext.get_projection().floatArray()); - if (centerWorld.lengthSq() > 0.001) { - var wvp = Matrix3d.multiplyMatrix(mvMat, renderContext.get_projection()); - var centerScreen = wvp.transform(centerWorld); - gl.uniform3f(FitsShader.centerScreenLoc, centerScreen.x, centerScreen.y, centerScreen.z); - } - else { - gl.uniform3f(FitsShader.centerScreenLoc, 0, 0, 0); - } - gl.uniform1i(FitsShader.sampLoc, 0); - gl.uniform1i(FitsShader.colorLoc, 1); - gl.uniform1f(FitsShader.blank, FitsShader.blankValue); - gl.uniform1f(FitsShader.bzero, FitsShader.bZero); - gl.uniform1f(FitsShader.bscale, FitsShader.bScale); - gl.uniform1f(FitsShader.minLoc, FitsShader.min); - gl.uniform1f(FitsShader.maxLoc, FitsShader.max); - gl.uniform1i(FitsShader.transparentBlackLoc, FitsShader.transparentBlack); - gl.uniform1i(FitsShader.containsBlanksLoc, FitsShader.containsBlanks); - gl.uniform1i(FitsShader.scalingLocation, FitsShader.scaleType); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(FitsShader.vertLoc); - gl.enableVertexAttribArray(FitsShader.textureLoc); - gl.vertexAttribPointer(FitsShader.vertLoc, 3, 5126, false, 20, 0); - gl.vertexAttribPointer(FitsShader.textureLoc, 2, 5126, false, 20, 12); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var FitsShader$ = { - - }; - - - // wwtlib.ImageShader - - function ImageShader() { - } - ImageShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' uniform float opacity; \n' + ' \n' + ' void main(void) { \n' + ' vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' gl_FragColor = col * opacity; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec2 aTextureCoord; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vTextureCoord = aTextureCoord; \n' + ' } \n' + ' \n'; - ImageShader._frag = gl.createShader(35632); - gl.shaderSource(ImageShader._frag, fragShaderText); - gl.compileShader(ImageShader._frag); - var stat = gl.getShaderParameter(ImageShader._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(ImageShader._frag); - } - ImageShader._vert = gl.createShader(35633); - gl.shaderSource(ImageShader._vert, vertexShaderText); - gl.compileShader(ImageShader._vert); - var stat1 = gl.getShaderParameter(ImageShader._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(ImageShader._vert); - } - ImageShader._prog = gl.createProgram(); - gl.attachShader(ImageShader._prog, ImageShader._vert); - gl.attachShader(ImageShader._prog, ImageShader._frag); - gl.linkProgram(ImageShader._prog); - var errcode = gl.getProgramParameter(ImageShader._prog, 35714); - gl.useProgram(ImageShader._prog); - ImageShader.vertLoc = gl.getAttribLocation(ImageShader._prog, 'aVertexPosition'); - ImageShader.textureLoc = gl.getAttribLocation(ImageShader._prog, 'aTextureCoord'); - ImageShader.projMatLoc = gl.getUniformLocation(ImageShader._prog, 'uPMatrix'); - ImageShader.mvMatLoc = gl.getUniformLocation(ImageShader._prog, 'uMVMatrix'); - ImageShader.sampLoc = gl.getUniformLocation(ImageShader._prog, 'uSampler'); - ImageShader.opacityLoc = gl.getUniformLocation(ImageShader._prog, 'opacity'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - ImageShader.initialized = true; - }; - ImageShader.use = function (renderContext, vertex, index, texture, opacity, noDepth) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!ImageShader.initialized) { - ImageShader.init(renderContext); - } - gl.useProgram(ImageShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(ImageShader.opacityLoc, opacity); - gl.uniformMatrix4fv(ImageShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(ImageShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(ImageShader.sampLoc, 0); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(ImageShader.vertLoc); - gl.enableVertexAttribArray(ImageShader.textureLoc); - gl.vertexAttribPointer(ImageShader.vertLoc, 3, 5126, false, 20, 0); - gl.vertexAttribPointer(ImageShader.textureLoc, 2, 5126, false, 20, 12); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var ImageShader$ = { - - }; - - - // wwtlib.ImageShader2 - - function ImageShader2() { - } - ImageShader2.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' uniform float opacity; \n' + ' \n' + ' void main(void) { \n' + ' vec4 col = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' gl_FragColor = col * opacity; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec2 aTextureCoord; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec3 vNormal; \n' + ' varying vec3 vCamVector; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vTextureCoord = aTextureCoord; \n' + ' } \n' + ' \n'; - ImageShader2._frag = gl.createShader(35632); - gl.shaderSource(ImageShader2._frag, fragShaderText); - gl.compileShader(ImageShader2._frag); - var stat = gl.getShaderParameter(ImageShader2._frag, 35713); - if (!stat) { - var errorF = gl.getShaderInfoLog(ImageShader2._frag); - } - ImageShader2._vert = gl.createShader(35633); - gl.shaderSource(ImageShader2._vert, vertexShaderText); - gl.compileShader(ImageShader2._vert); - var stat1 = gl.getShaderParameter(ImageShader2._vert, 35713); - if (!stat1) { - var errorV = gl.getShaderInfoLog(ImageShader2._vert); - } - ImageShader2._prog = gl.createProgram(); - gl.attachShader(ImageShader2._prog, ImageShader2._vert); - gl.attachShader(ImageShader2._prog, ImageShader2._frag); - gl.linkProgram(ImageShader2._prog); - var errcode = gl.getProgramParameter(ImageShader2._prog, 35714); - gl.useProgram(ImageShader2._prog); - ImageShader2.vertLoc = gl.getAttribLocation(ImageShader2._prog, 'aVertexPosition'); - ImageShader2.textureLoc = gl.getAttribLocation(ImageShader2._prog, 'aTextureCoord'); - ImageShader2.projMatLoc = gl.getUniformLocation(ImageShader2._prog, 'uPMatrix'); - ImageShader2.mvMatLoc = gl.getUniformLocation(ImageShader2._prog, 'uMVMatrix'); - ImageShader2.sampLoc = gl.getUniformLocation(ImageShader2._prog, 'uSampler'); - ImageShader2.opacityLoc = gl.getUniformLocation(ImageShader2._prog, 'opacity'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - ImageShader2.initialized = true; - }; - ImageShader2.use = function (renderContext, vertex, index, texture, opacity, noDepth) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!ImageShader2.initialized) { - ImageShader2.init(renderContext); - } - gl.useProgram(ImageShader2._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniform1f(ImageShader2.opacityLoc, opacity); - gl.uniformMatrix4fv(ImageShader2.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(ImageShader2.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(ImageShader2.sampLoc, 0); - if (renderContext.space || noDepth) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(ImageShader2.vertLoc); - gl.enableVertexAttribArray(ImageShader2.textureLoc); - gl.vertexAttribPointer(ImageShader2.vertLoc, 3, 5126, false, 32, 0); - gl.vertexAttribPointer(ImageShader2.textureLoc, 2, 5126, false, 32, 24); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, index); - gl.enable(3042); - if (noDepth) { - gl.blendFunc(770, 1); - } - else { - gl.blendFunc(770, 771); - } - } - }; - var ImageShader2$ = { - - }; - - - // wwtlib.SpriteShader - - function SpriteShader() { - } - SpriteShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying lowp vec4 vColor; \n' + ' uniform sampler2D uSampler; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * vColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec2 aTextureCoord; \n' + ' attribute lowp vec4 aColor; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec4 vColor; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vTextureCoord = aTextureCoord; \n' + ' vColor = aColor; \n' + ' } \n' + ' \n'; - SpriteShader._frag = gl.createShader(35632); - gl.shaderSource(SpriteShader._frag, fragShaderText); - gl.compileShader(SpriteShader._frag); - var stat = gl.getShaderParameter(SpriteShader._frag, 35713); - SpriteShader._vert = gl.createShader(35633); - gl.shaderSource(SpriteShader._vert, vertexShaderText); - gl.compileShader(SpriteShader._vert); - var stat1 = gl.getShaderParameter(SpriteShader._vert, 35713); - SpriteShader._prog = gl.createProgram(); - gl.attachShader(SpriteShader._prog, SpriteShader._vert); - gl.attachShader(SpriteShader._prog, SpriteShader._frag); - gl.linkProgram(SpriteShader._prog); - var errcode = gl.getProgramParameter(SpriteShader._prog, 35714); - gl.useProgram(SpriteShader._prog); - SpriteShader.vertLoc = gl.getAttribLocation(SpriteShader._prog, 'aVertexPosition'); - SpriteShader.textureLoc = gl.getAttribLocation(SpriteShader._prog, 'aTextureCoord'); - SpriteShader.colorLoc = gl.getAttribLocation(SpriteShader._prog, 'aColor'); - SpriteShader.projMatLoc = gl.getUniformLocation(SpriteShader._prog, 'uPMatrix'); - SpriteShader.mvMatLoc = gl.getUniformLocation(SpriteShader._prog, 'uMVMatrix'); - SpriteShader.sampLoc = gl.getUniformLocation(SpriteShader._prog, 'uSampler'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - SpriteShader.initialized = true; - }; - SpriteShader.use = function (renderContext, vertex, texture) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!SpriteShader.initialized) { - SpriteShader.init(renderContext); - } - gl.useProgram(SpriteShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(SpriteShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(SpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(SpriteShader.sampLoc, 0); - gl.disable(2929); - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(SpriteShader.vertLoc); - gl.enableVertexAttribArray(SpriteShader.textureLoc); - gl.enableVertexAttribArray(SpriteShader.colorLoc); - gl.vertexAttribPointer(SpriteShader.vertLoc, 3, 5126, false, 36, 0); - gl.vertexAttribPointer(SpriteShader.colorLoc, 4, 5126, false, 36, 12); - gl.vertexAttribPointer(SpriteShader.textureLoc, 2, 5126, false, 36, 28); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.bindBuffer(34963, null); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var SpriteShader$ = { - - }; - - - // wwtlib.ShapeSpriteShader - - function ShapeSpriteShader() { - } - ShapeSpriteShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying lowp vec4 vColor; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = vColor; \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute lowp vec4 aColor; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' varying vec4 vColor; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vColor = aColor; \n' + ' } \n' + ' \n'; - ShapeSpriteShader._frag = gl.createShader(35632); - gl.shaderSource(ShapeSpriteShader._frag, fragShaderText); - gl.compileShader(ShapeSpriteShader._frag); - var stat = gl.getShaderParameter(ShapeSpriteShader._frag, 35713); - ShapeSpriteShader._vert = gl.createShader(35633); - gl.shaderSource(ShapeSpriteShader._vert, vertexShaderText); - gl.compileShader(ShapeSpriteShader._vert); - var stat1 = gl.getShaderParameter(ShapeSpriteShader._vert, 35713); - ShapeSpriteShader._prog = gl.createProgram(); - gl.attachShader(ShapeSpriteShader._prog, ShapeSpriteShader._vert); - gl.attachShader(ShapeSpriteShader._prog, ShapeSpriteShader._frag); - gl.linkProgram(ShapeSpriteShader._prog); - var errcode = gl.getProgramParameter(ShapeSpriteShader._prog, 35714); - gl.useProgram(ShapeSpriteShader._prog); - ShapeSpriteShader.vertLoc = gl.getAttribLocation(ShapeSpriteShader._prog, 'aVertexPosition'); - ShapeSpriteShader.colorLoc = gl.getAttribLocation(ShapeSpriteShader._prog, 'aColor'); - ShapeSpriteShader.projMatLoc = gl.getUniformLocation(ShapeSpriteShader._prog, 'uPMatrix'); - ShapeSpriteShader.mvMatLoc = gl.getUniformLocation(ShapeSpriteShader._prog, 'uMVMatrix'); - gl.disable(2929); - gl.enable(3042); - gl.blendFunc(770, 771); - ShapeSpriteShader.initialized = true; - }; - ShapeSpriteShader.use = function (renderContext, vertex) { - var gl = renderContext.gl; - if (gl != null) { - if (!ShapeSpriteShader.initialized) { - ShapeSpriteShader.init(renderContext); - } - gl.useProgram(ShapeSpriteShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(ShapeSpriteShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(ShapeSpriteShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(ShapeSpriteShader.sampLoc, 0); - gl.disable(2929); - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(ShapeSpriteShader.vertLoc); - gl.enableVertexAttribArray(ShapeSpriteShader.textureLoc); - gl.enableVertexAttribArray(ShapeSpriteShader.colorLoc); - gl.vertexAttribPointer(ShapeSpriteShader.vertLoc, 3, 5126, false, 36, 0); - gl.vertexAttribPointer(ShapeSpriteShader.colorLoc, 4, 5126, false, 36, 12); - gl.bindBuffer(34963, null); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var ShapeSpriteShader$ = { - - }; - - - // wwtlib.TextShader - - function TextShader() { - } - TextShader.init = function (renderContext) { - var gl = renderContext.gl; - var fragShaderText = ' precision mediump float; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' \n' + ' uniform sampler2D uSampler; \n' + ' \n' + ' void main(void) { \n' + ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n' + ' } \n'; - var vertexShaderText = ' attribute vec3 aVertexPosition; \n' + ' attribute vec2 aTextureCoord; \n' + ' \n' + ' uniform mat4 uMVMatrix; \n' + ' uniform mat4 uPMatrix; \n' + ' \n' + ' varying vec2 vTextureCoord; \n' + ' \n' + ' \n' + ' void main(void) { \n' + ' gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \n' + ' vTextureCoord = aTextureCoord; \n' + ' } \n' + ' \n'; - TextShader._frag = gl.createShader(35632); - gl.shaderSource(TextShader._frag, fragShaderText); - gl.compileShader(TextShader._frag); - var stat = gl.getShaderParameter(TextShader._frag, 35713); - TextShader._vert = gl.createShader(35633); - gl.shaderSource(TextShader._vert, vertexShaderText); - gl.compileShader(TextShader._vert); - var stat1 = gl.getShaderParameter(TextShader._vert, 35713); - TextShader._prog = gl.createProgram(); - gl.attachShader(TextShader._prog, TextShader._vert); - gl.attachShader(TextShader._prog, TextShader._frag); - gl.linkProgram(TextShader._prog); - var errcode = gl.getProgramParameter(TextShader._prog, 35714); - gl.useProgram(TextShader._prog); - TextShader.vertLoc = gl.getAttribLocation(TextShader._prog, 'aVertexPosition'); - TextShader.textureLoc = gl.getAttribLocation(TextShader._prog, 'aTextureCoord'); - TextShader.projMatLoc = gl.getUniformLocation(TextShader._prog, 'uPMatrix'); - TextShader.mvMatLoc = gl.getUniformLocation(TextShader._prog, 'uMVMatrix'); - TextShader.sampLoc = gl.getUniformLocation(TextShader._prog, 'uSampler'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - gl.enable(3042); - gl.blendFunc(770, 771); - TextShader.initialized = true; - }; - TextShader.use = function (renderContext, vertex, texture) { - if (texture == null) { - texture = Texture.getEmpty(); - } - var gl = renderContext.gl; - if (gl != null) { - if (!TextShader.initialized) { - TextShader.init(renderContext); - } - gl.useProgram(TextShader._prog); - var mvMat = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - gl.uniformMatrix4fv(TextShader.mvMatLoc, false, mvMat.floatArray()); - gl.uniformMatrix4fv(TextShader.projMatLoc, false, renderContext.get_projection().floatArray()); - gl.uniform1i(TextShader.sampLoc, 0); - if (renderContext.space) { - gl.disable(2929); - } - else { - gl.enable(2929); - } - gl.disableVertexAttribArray(0); - gl.disableVertexAttribArray(1); - gl.disableVertexAttribArray(2); - gl.disableVertexAttribArray(3); - gl.bindBuffer(34962, vertex); - gl.enableVertexAttribArray(TextShader.vertLoc); - gl.enableVertexAttribArray(TextShader.textureLoc); - gl.vertexAttribPointer(TextShader.vertLoc, 3, 5126, false, 20, 0); - gl.vertexAttribPointer(TextShader.textureLoc, 2, 5126, false, 20, 12); - gl.activeTexture(33984); - gl.bindTexture(3553, texture); - gl.enable(3042); - gl.blendFunc(770, 771); - } - }; - var TextShader$ = { - - }; - - - // wwtlib.Sprite2d - - function Sprite2d() { - this.vertCount = 0; - } - var Sprite2d$ = { - draw: function (renderContext, points, count, texture, triangleStrips, opacity) { - if (this.vertexBuffer == null) { - this.create(points); - } - else { - this.update(points); - } - if (texture == null) { - ShapeSpriteShader.use(renderContext, this.vertexBuffer); - renderContext.gl.drawArrays((triangleStrips) ? 5 : 4, 0, points.length); - } - else { - SpriteShader.use(renderContext, this.vertexBuffer, (texture != null) ? texture.texture2d : null); - renderContext.gl.drawArrays((triangleStrips) ? 5 : 4, 0, points.length); - } - }, - create: function (verts) { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(verts.length * 9); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(verts); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.color.r / 255; - buffer[index++] = pt.color.g / 255; - buffer[index++] = pt.color.b / 255; - buffer[index++] = pt.color.a / 255; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35048); - }, - update: function (verts) { - if (this.vertCount < verts.length) { - Tile.prepDevice.deleteBuffer(this.vertexBuffer); - this.create(verts); - return; - } - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(verts.length * 9); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(verts); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.color.r / 255; - buffer[index++] = pt.color.g / 255; - buffer[index++] = pt.color.b / 255; - buffer[index++] = pt.color.a / 255; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferSubData(34962, 0, f32array); - } - }; - - - // wwtlib.Tessellator - - function Tessellator() { - } - Tessellator.tesselateSimplePoly = function (inputList) { - var results = []; - var tess = new Tessellator(); - tess.process(inputList, results); - return results; - }; - var Tessellator$ = { - _isLeftOfHalfSpace: function (pntA, pntB, pntTest) { - pntA.normalize(); - pntB.normalize(); - var cross = Vector3d.cross(pntA, pntB); - var dot = Vector3d.dot(cross, pntTest); - return dot > 0; - }, - _insideTriangle: function (pntA, pntB, pntC, pntTest) { - if (!this._isLeftOfHalfSpace(pntA, pntB, pntTest)) { - return false; - } - if (!this._isLeftOfHalfSpace(pntB, pntC, pntTest)) { - return false; - } - if (!this._isLeftOfHalfSpace(pntC, pntA, pntTest)) { - return false; - } - return true; - }, - _canClipEar: function (poly, u, v, w, n, verts) { - var p; - var a = poly[verts[u]].copy(); - var b = poly[verts[v]].copy(); - var c = poly[verts[w]].copy(); - var P; - var d = Vector3d.subtractVectors(b, a); - d.normalize(); - var e = Vector3d.subtractVectors(b, c); - e.normalize(); - var g = Vector3d.cross(d, e); - var bn = b.copy(); - bn.normalize(); - if (Vector3d.dot(g, bn) > 0) { - return false; - } - for (p = 0; p < n; p++) { - if ((p === u) || (p === v) || (p === w)) { - continue; - } - P = poly[verts[p]].copy(); - if (this._insideTriangle(a, b, c, P)) { - return false; - } - } - return true; - }, - process: function (poly, result) { - var n = poly.length; - if (poly.length < 3) { - return false; - } - var verts = new Array(poly.length); - for (var i = 0; i < n; i++) { - verts[i] = i; - } - var nv = n; - var count = 2 * nv; - for (var m = 0, v = nv - 1; nv > 2;) { - if (0 >= (count--)) { - return false; - } - var u = v; - if (nv <= u) { - u = 0; - } - v = u + 1; - if (nv <= v) { - v = 0; - } - var w = v + 1; - if (nv <= w) { - w = 0; - } - if (this._canClipEar(poly, u, v, w, nv, verts)) { - var s, t; - result.push(verts[u]); - result.push(verts[v]); - result.push(verts[w]); - m++; - for (s = v, t = v + 1; t < nv; s++, t++) { - verts[s] = verts[t]; - } - nv--; - count = 2 * nv; - } - } - return true; - } - }; - - - // wwtlib.Texture - - function Texture() { - this.imageElement = null; - this.texture2d = null; - this._downloading = false; - this._ready = false; - this._errored = false; - this.URL = ''; - } - Texture.getEmpty = function () { - if (Texture.empty == null) { - Texture.empty = Tile.prepDevice.createTexture(); - Tile.prepDevice.bindTexture(3553, Texture.empty); - Tile.prepDevice.texImage2D(3553, 0, 6408, 1, 1, 0, 6408, 5121, new Uint8Array([0, 0, 0, 0])); - Tile.prepDevice.bindTexture(3553, null); - } - return Texture.empty; - }; - Texture.fromUrl = function (url) { - var tex = new Texture(); - tex.load(url); - return tex; - }; - Texture.isPowerOfTwo = function (val) { - return !(val & (val - 1)); - }; - Texture.fitPowerOfTwo = function (val) { - val--; - for (var i = 1; i < 32; i <<= 1) { - val = val | val >> i; - } - return val + 1; - }; - var Texture$ = { - cleanUp: function () { - this.imageElement = null; - Tile.prepDevice.deleteTexture(this.texture2d); - }, - dispose: function () { - this.cleanUp(); - }, - load: function (url) { - var $this = this; - - this.URL = url; - if (typeof document === "undefined") { return; }; - if (!this._downloading) { - this._downloading = true; - this.imageElement = document.createElement('img'); - var xdomimg = this.imageElement; - this.imageElement.addEventListener('load', function (e) { - $this._ready = true; - $this._downloading = false; - $this._errored = false; - $this.makeTexture(); - }, false); - this.imageElement.addEventListener('error', function (e) { - if (!$this.imageElement.hasAttribute('proxyattempt')) { - $this.imageElement.setAttribute('proxyattempt', true); - var new_url = URLHelpers.singleton.activateProxy($this.URL); - if (new_url != null) { - $this.imageElement.src = new_url; - return; - } - } - $this._downloading = false; - $this._ready = false; - $this._errored = true; - }, false); - xdomimg.crossOrigin = 'anonymous'; - this.imageElement.src = this.URL; - } - }, - makeTexture: function () { - if (Tile.prepDevice != null) { - try { - this.texture2d = Tile.prepDevice.createTexture(); - Tile.prepDevice.bindTexture(3553, this.texture2d); - var image = this.imageElement; - if ((!Texture.isPowerOfTwo(this.imageElement.height) | !Texture.isPowerOfTwo(this.imageElement.width)) === 1) { - var temp = document.createElement('canvas'); - temp.height = Texture.fitPowerOfTwo(image.height); - temp.width = Texture.fitPowerOfTwo(image.width); - var ctx = temp.getContext('2d'); - ctx.drawImage(image, 0, 0, temp.width, temp.height); - image = temp; - } - Tile.prepDevice.texParameteri(3553, 10242, 33071); - Tile.prepDevice.texParameteri(3553, 10243, 33071); - Tile.prepDevice.texImage2D(3553, 0, 6408, 6408, 5121, image); - Tile.prepDevice.texParameteri(3553, 10241, 9985); - Tile.prepDevice.generateMipmap(3553); - Tile.prepDevice.bindTexture(3553, null); - } - catch ($e1) { - this._errored = true; - } - } - } - }; - - - // wwtlib.Grids - - function Grids() { - } - Grids._createGalaxyImage = function (renderContext) { - if (Grids._milkyWayImage == null) { - Grids._milkyWayImage = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('milkywaybar.jpg')); - } - var subdivs = 50; - var lat, lng; - var index = 0; - var latMin = 64; - var latMax = -64; - var lngMin = -64; - var lngMax = 64; - Grids._galaxyImageVertexBuffer = new PositionTextureVertexBuffer((subdivs + 1) * (subdivs + 1)); - var verts = Grids._galaxyImageVertexBuffer.lock(); - var x1, y1; - var latDegrees = latMax - latMin; - var lngDegrees = lngMax - lngMin; - var scaleFactor = 60800000; - var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; - var point; - var textureStepX = 1 / subdivs; - var textureStepY = 1 / subdivs; - for (y1 = 0; y1 <= subdivs; y1++) { - if (y1 !== subdivs) { - lat = latMax - (textureStepY * latDegrees * y1); - } - else { - lat = latMin; - } - for (x1 = 0; x1 <= subdivs; x1++) { - if (x1 !== subdivs) { - lng = lngMin + (textureStepX * lngDegrees * x1); - } - else { - lng = lngMax; - } - index = y1 * (subdivs + 1) + x1; - point = Vector3d.create(lng * scaleFactor, 0, (lat - 28) * scaleFactor); - point.rotateY(213 / 180 * Math.PI); - point.rotateZ((-62.87175) / 180 * Math.PI); - point.rotateY((-192.8595083) / 180 * Math.PI); - point.rotateX(ecliptic); - verts[index] = PositionTexture.createPosRaw(point, (1 - x1 * textureStepX), (y1 * textureStepY)); - } - } - Grids._galaxyImageVertexBuffer.unlock(); - Grids._galaxyImageTriangleCount = subdivs * subdivs * 2; - var ui16array = new Uint16Array(subdivs * subdivs * 6); - var indexArray = ui16array; - for (y1 = 0; y1 < subdivs; y1++) { - for (x1 = 0; x1 < subdivs; x1++) { - index = (y1 * subdivs * 6) + 6 * x1; - indexArray[index] = (y1 * (subdivs + 1) + x1); - indexArray[index + 2] = ((y1 + 1) * (subdivs + 1) + x1); - indexArray[index + 1] = (y1 * (subdivs + 1) + (x1 + 1)); - indexArray[index + 3] = (y1 * (subdivs + 1) + (x1 + 1)); - indexArray[index + 5] = ((y1 + 1) * (subdivs + 1) + x1); - indexArray[index + 4] = ((y1 + 1) * (subdivs + 1) + (x1 + 1)); - } - } - Grids._galaxyImageIndexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, Grids._galaxyImageIndexBuffer); - Tile.prepDevice.bufferData(34963, ui16array, 35044); - }; - Grids.drawGalaxyImage = function (renderContext, opacity) { - if (Grids._galaxyImageIndexBuffer == null) { - Grids._createGalaxyImage(renderContext); - } - var zoom = renderContext.viewCamera.zoom; - var log = Math.log(Math.max(1, zoom)) / Math.log(4); - var distAlpha = (log - 14) * 128; - var alpha = (Math.min(255, Math.max(0, distAlpha)) * opacity); - ImageShader.use(renderContext, Grids._galaxyImageVertexBuffer.vertexBuffer, Grids._galaxyImageIndexBuffer, Grids._milkyWayImage.texture2d, opacity, true); - renderContext.gl.drawElements(4, Grids._galaxyImageTriangleCount * 3, 5123, 0); - }; - Grids.drawStars3D = function (renderContext, opacity) { - var zoom = renderContext.viewCamera.zoom; - var distAlpha = Math.max(Math.min(255, (Math.log(zoom) - 15.5) * 40.8), 0); - var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); - if (alpha > 254) { - return; - } - alpha = ((255 - alpha) * opacity); - if (Grids._starSprites == null) { - Grids.initStarVertexBuffer(renderContext); - } - if (Grids._starSprites != null) { - Grids._starSprites.draw(renderContext, alpha / 255, false); - } - }; - Grids.initStarVertexBuffer = function (renderContext) { - if (!Grids._starsDownloading && !WWTControl.singleton.freestandingMode) { - Grids.getStarFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=hipparcos')); - Grids._starsDownloading = true; - } - if (Grids._starSprites == null && Grids._starCount > 0) { - var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; - var count = Grids._stars.length; - Grids._starCount = count; - Grids._starSprites = new PointList(renderContext); - Grids._starSprites.depthBuffered = false; - Grids._starSprites.showFarSide = true; - var $enum1 = ss.enumerate(Grids._stars); - while ($enum1.moveNext()) { - var star = $enum1.current; - var pos = Coordinates.raDecTo3dAu(star.RA, star.dec, star.distance); - pos.rotateX(ecliptic); - star.position = pos; - var radDec = (1200000) / Math.pow(1.6, star.absoluteMagnitude); - Grids._starSprites.addPoint(pos, star.col, new Dates(0, 1), radDec * 100); - } - } - }; - Grids.initializeStarDB = function (text) { - if (Grids._stars == null) { - if (Grids._stars == null) { - Grids._stars = []; - var rows = text.split('\r\n'); - var star; - var $enum1 = ss.enumerate(rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - var line = row; - star = new Star(line); - if (star.magnitude < Grids._limitingMagnitude && star.par > 0.001) { - Grids._stars.push(star); - Grids._hipparcosIndex[star.id] = star; - } - } - Grids._starCount = Grids._stars.length; - } - } - }; - Grids.getStarFile = function (url) { - Grids._webFileStar = new WebFile(url); - Grids._webFileStar.onStateChange = Grids.starFileStateChange; - Grids._webFileStar.send(); - }; - Grids.starFileStateChange = function () { - if (Grids._webFileStar.get_state() === 2) { - alert(Grids._webFileStar.get_message()); - } - else if (Grids._webFileStar.get_state() === 1) { - Grids.initializeStarDB(Grids._webFileStar.getText()); - } - }; - Grids.getGalaxyFile = function (url) { - Grids._webFileGalaxy = new WebFile(url); - Grids._webFileGalaxy.responseType = 'blob'; - Grids._webFileGalaxy.onStateChange = Grids.galaxyFileStateChange; - Grids._webFileGalaxy.send(); - }; - Grids.galaxyFileStateChange = function () { - if (Grids._webFileGalaxy.get_state() === 2) { - alert(Grids._webFileGalaxy.get_message()); - } - else if (Grids._webFileGalaxy.get_state() === 1) { - var mainBlob = Grids._webFileGalaxy.getBlob(); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - var br = new BinaryReader(new Uint8Array(chunck.result)); - Grids.initializeCosmos(br); - }; - chunck.readAsArrayBuffer(mainBlob); - } - }; - Grids.drawCosmos3D = function (renderContext, opacity) { - var device = renderContext.gl; - var zoom = renderContext.viewCamera.zoom; - var distAlpha = ((Math.log(Math.max(1, zoom)) / Math.log(4)) - 15.5) * 90; - var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); - if (alpha < 3) { - return; - } - Grids.initCosmosVertexBuffer(); - if (Grids._galaxyTextures == null) { - if (Grids._largeSet) { - Grids._galaxyTextures = new Array(256); - for (var i = 0; i < 256; i++) { - var num = i.toString(); - while (num.length < 4) { - num = '0' + num; - } - var name = ss.format(URLHelpers.singleton.engineAssetUrl('galimg/gal_{0}.jpg'), num); - Grids._galaxyTextures[i] = Planets.loadPlanetTexture(name); - } - } - } - if (Grids._cosmosReady) { - var count = 256; - for (var i = 0; i < count; i++) { - Grids._cosmosSprites[i].drawTextured(renderContext, Grids._galaxyTextures[i].texture2d, (alpha * opacity) / 255); - } - } - }; - Grids.initCosmosVertexBuffer = function () { - if (Grids._cosmosSprites == null) { - Grids._downloadCosmosFile(); - } - }; - Grids._createCosmosVertexBuffer = function (renderContext) { - var device = Tile.prepDevice; - var bucketCount = 256; - if (Grids._cosmosSprites != null) { - for (var ij = 0; ij < bucketCount; ij++) { - if (Grids._cosmosSprites[ij] != null) { - Grids._cosmosSprites[ij] = null; - } - } - } - Grids._cosmosSprites = null; - var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; - Grids._cosmosSprites = new Array(bucketCount); - var indexList = new Array(bucketCount); - for (var i = 0; i < bucketCount; i++) { - var count = Grids._galaxyVertexCounts[i]; - Grids._cosmosSprites[i] = new PointList(renderContext); - Grids._cosmosSprites[i].depthBuffered = false; - Grids._cosmosSprites[i].showFarSide = true; - indexList[i] = 0; - } - var $enum1 = ss.enumerate(Grids._cosmos); - while ($enum1.moveNext()) { - var galaxy = $enum1.current; - var bucket = galaxy.eTypeBucket; - var index = indexList[bucket]; - var pos = Coordinates.raDecTo3dAu(galaxy.RA, galaxy.dec, (galaxy.distance * 206264.806 * 1000000) / 0.73); - pos.rotateX(ecliptic); - galaxy.position = pos; - Grids._cosmosSprites[bucket].addPoint(pos, Colors.get_white(), new Dates(0, 1), (1E+09 * galaxy.size * 100)); - indexList[bucket]++; - } - Grids._cosmosReady = true; - }; - Grids.initializeCosmos = function (br) { - var max = Math.pow(100, 2.849485002); - if (Grids._cosmos == null) { - Grids._galaxyVertexCounts = new Array((Grids._largeSet) ? 256 : 20); - if (Grids._cosmos == null) { - Grids._cosmos = []; - var galaxy; - try { - var count = 0; - while (br.get_position() < br.get_length()) { - galaxy = new Galaxy(br); - Grids._cosmos.push(galaxy); - Grids._galaxyVertexCounts[galaxy.eTypeBucket]++; - count++; - } - } - catch ($e1) { - } - br.close(); - } - Grids._createCosmosVertexBuffer(WWTControl.singleton.renderContext); - } - }; - Grids._downloadCosmosFile = function () { - if (!Grids._downloadingGalaxy && !WWTControl.singleton.freestandingMode) { - Grids.getGalaxyFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=cosmosnewbin')); - Grids._downloadingGalaxy = true; - } - return false; - }; - Grids.drawEquitorialGrid = function (renderContext, opacity, drawColor) { - if (Grids._equLineList == null) { - Grids._equLineList = new SimpleLineList(); - Grids._equLineList.set_depthBuffered(false); - for (var hour = 0; hour < 24; hour++) { - for (var dec = -80; dec < 80; dec += 2) { - Grids._equLineList.addLine(Coordinates.raDecTo3dAu(hour, dec, 1), Coordinates.raDecTo3dAu(hour, dec + 2, 1)); - } - } - for (var dec = -80; dec <= 80; dec += 10) { - for (var hour = 0; hour < 23.8; hour += 0.2) { - Grids._equLineList.addLine(Coordinates.raDecTo3dAu(hour, dec, 1), Coordinates.raDecTo3dAu(hour + 0.2, dec, 1)); - } - } - var counter = 0; - for (var ra = 0; ra < 24; ra += 0.25) { - var dec = 0.5; - switch (counter % 4) { - case 0: - counter++; - continue; - case 3: - case 1: - dec = 0.25; - break; - } - counter++; - Grids._equLineList.addLine(Coordinates.raDecTo3dAu(ra, dec, 1), Coordinates.raDecTo3dAu(ra, -dec, 1)); - } - counter = 0; - for (var ra = 0; ra < 24; ra += 3) { - counter = 0; - for (var dec = -80; dec <= 80; dec += 1) { - var width = 0.5 / 30; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - width = 0.5 / 15; - break; - } - counter++; - Grids._equLineList.addLine(Coordinates.raDecTo3dAu(ra + width, dec, 1), Coordinates.raDecTo3dAu(ra - width, dec, 1)); - } - } - } - Grids._equLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids.drawEquitorialGridText = function (renderContext, opacity, drawColor) { - Grids._makeEquitorialGridText(); - Grids._equTextBatch.draw(renderContext, opacity, drawColor); - return true; - }; - Grids._makeEquitorialGridText = function () { - if (Grids._equTextBatch == null) { - Grids._equTextBatch = new Text3dBatch(30); - var index = 0; - for (var ra = 0; ra < 24; ra++) { - var text = ra.toString() + ' hr'; - if (ra < 10) { - text = ' ' + ra.toString() + ' hr'; - } - Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra + 0.005, 0.4, 1), Coordinates.raDecTo3dAu(ra + 0.005, 0.5, 1), text, 45, 0.00018)); - } - index = 0; - for (var ra = 0; ra < 24; ra += 3) { - for (var dec = -80; dec <= 80; dec += 10) { - if (!dec) { - continue; - } - var text = dec.toString(); - if (dec > 0) { - text = ' +' + dec.toString(); - Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra, dec - 0.4, 1), Coordinates.raDecTo3dAu(ra, dec - 0.3, 1), text, 45, 0.00018)); - } - else { - text = ' - ' + text.substr(1); - Grids._equTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(ra, dec + 0.4, 1), Coordinates.raDecTo3dAu(ra, dec + 0.5, 1), text, 45, 0.00018)); - } - index++; - } - } - } - }; - Grids.drawEcliptic = function (renderContext, opacity, drawColor) { - var col = drawColor; - var year = SpaceTimeController.get_now().getUTCFullYear(); - if (Grids._eclipticOverviewLineList == null || year !== Grids._eclipticYear) { - if (Grids._eclipticOverviewLineList != null) { - Grids._eclipticOverviewLineList.clear(); - Grids._eclipticOverviewLineList = null; - } - Grids._eclipticYear = year; - var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); - var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); - var daysPerYear = 365.25; - if (DT.isLeap(year, true)) { - Grids._monthDays[1] = 29; - daysPerYear = 366; - } - else { - Grids._monthDays[1] = 28; - daysPerYear = 365; - } - var count = 2 * ss.truncate(daysPerYear); - Grids._eclipticCount = ss.truncate(daysPerYear); - var jYear = SpaceTimeController.utcToJulian(new Date(year, 0, 1, 12, 0, 0)); - var index = 0; - var d = 0; - Grids._eclipticOverviewLineList = new SimpleLineList(); - Grids._eclipticOverviewLineList.set_depthBuffered(false); - for (var m = 0; m < 12; m++) { - var daysThisMonth = ss.truncate(Grids._monthDays[m]); - for (var i = 0; i < daysThisMonth; i++) { - var sunRaDec = Planets.getPlanetLocationJD('Sun', jYear); - var sunEcliptic = CT.eq2Ec(sunRaDec.RA, sunRaDec.dec, obliquity); - d = sunEcliptic.x; - var width = 0.005; - if (!i) { - width = 0.01; - } - var dd = d; - Grids._eclipticOverviewLineList.addLine(Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), width, Math.sin((dd * Math.PI * 2) / 360)), mat), Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), -width, Math.sin((dd * Math.PI * 2) / 360)), mat)); - index++; - jYear += 1; - } - d += Grids._monthDays[m]; - } - } - Grids._eclipticOverviewLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids.drawEclipticText = function (renderContext, opacity, drawColor) { - Grids._makeEclipticText(); - Grids._eclipOvTextBatch.draw(renderContext, opacity, drawColor); - return true; - }; - Grids._makeEclipticText = function () { - var year = SpaceTimeController.get_now().getUTCFullYear(); - if (Grids._eclipOvTextBatch == null) { - Grids._eclipOvTextBatch = new Text3dBatch(80); - Grids._eclipticTextYear = year; - var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); - var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); - var daysPerYear = 365.25; - if (DT.isLeap(year, true)) { - Grids._monthDays[1] = 29; - daysPerYear = 366; - } - else { - Grids._monthDays[1] = 28; - daysPerYear = 365; - } - var count = 2 * ss.truncate(daysPerYear); - Grids._eclipticCount = ss.truncate(daysPerYear); - var jYear = SpaceTimeController.utcToJulian(new Date(year, 0, 1, 12, 0, 0)); - var index = 0; - var d = 0; - for (var m = 0; m < 12; m++) { - var daysThisMonth = ss.truncate(Grids._monthDays[m]); - for (var i = 0; i < daysThisMonth; i++) { - var sunRaDec = Planets.getPlanetLocationJD('Sun', jYear); - var sunEcliptic = CT.eq2Ec(sunRaDec.RA, sunRaDec.dec, obliquity); - d = sunEcliptic.x; - var dd = d; - if (i === Math.floor(daysThisMonth / 2)) { - var center = Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), 0.025, Math.sin((dd * Math.PI * 2) / 360)), mat); - var up = Vector3d._transformCoordinate(Vector3d.create(Math.cos((dd * Math.PI * 2) / 360), 0.045, Math.sin((dd * Math.PI * 2) / 360)), mat); - up.subtract(center); - up.normalize(); - Grids._eclipOvTextBatch.add(new Text3d(center, up, Grids._monthNames[m], 80, 0.000159375)); - } - index++; - index++; - jYear += 1; - } - d += Grids._monthDays[m]; - } - } - }; - Grids.drawPrecessionChart = function (renderContext, opacity, drawColor) { - Grids._makePrecessionChart(); - Grids._precTextBatch.draw(renderContext, opacity, drawColor); - Grids._precLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids._makePrecessionChart = function () { - var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); - var mat = Matrix3d._rotationX((obliquity / 360 * (Math.PI * 2))); - var col = Colors.get_white(); - if (Grids._precLineList == null) { - Grids._precLineList = new SimpleLineList(); - Grids._precLineList.set_depthBuffered(false); - for (var l = 0; l < 360; l++) { - var b = 90 - obliquity; - Grids._precLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + 1) / 15, b, 1), mat)); - } - for (var l = -12000; l < 13000; l += 2000) { - var b = 90 - obliquity; - var p = -((l - 2000) / 25772 * 24) - 6; - Grids._precLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b - 0.5, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b + 0.5, 1), mat)); - } - } - if (Grids._precTextBatch == null) { - Grids._precTextBatch = new Text3dBatch(50); - for (var l = -12000; l < 13000; l += 2000) { - var b = 90 - obliquity + 3; - var p = -((l - 2000) / 25772 * 24) - 6; - var text = l.toString(); - if (!l) { - b = 90 - obliquity + 2; - text = '1 CE'; - } - else if (l < 0) { - text = ' ' + Math.abs(l).toString() + ' BCE'; - } - else { - text = Math.abs(l).toString() + ' CE'; - } - if (text.length === 9) { - text = ' ' + text; - } - Grids._precTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(p + 0.01, b, 1), mat), text, 75, 0.00015)); - } - } - return; - }; - Grids.drawAltAzGrid = function (renderContext, opacity, drawColor) { - var zenithAltAz = new Coordinates(0, 0); - var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); - var raPart = -((zenith.get_RA() + 6) / 24 * (Math.PI * 2)); - var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); - var raText = Coordinates.formatDMS(zenith.get_RA()); - var mat = Matrix3d._rotationY(-raPart); - mat._multiply(Matrix3d._rotationX(decPart)); - mat.invert(); - if (Grids._altAzLineList == null) { - Grids._altAzLineList = new SimpleLineList(); - Grids._altAzLineList.set_depthBuffered(false); - for (var l = 0; l < 360; l += 10) { - for (var b = -80; b < 80; b += 2) { - Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu(l / 15, b + 2, 1)); - } - } - for (var b = -80; b <= 80; b += 10) { - for (var l = 0; l < 360; l += 5) { - Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu((l + 5) / 15, b, 1)); - } - } - var counter = 0; - for (var l = 0; l < 360; l += 1) { - var b = 0.25; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - b = 0.5; - break; - } - counter++; - Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu(l / 15, b, 1), Coordinates.raDecTo3dAu(l / 15, -b, 1)); - } - counter = 0; - for (var l = 0; l < 360; l += 90) { - counter = 0; - for (var b = -80; b <= 80; b += 1) { - var width = 0.5 / 2; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - width = 0.5; - break; - } - counter++; - Grids._altAzLineList.addLine(Coordinates.raDecTo3dAu((l + width) / 15, b, 1), Coordinates.raDecTo3dAu((l - width) / 15, b, 1)); - } - } - } - var matOldWorld = renderContext.get_world().clone(); - var matOldWorldBase = renderContext.get_worldBase().clone(); - renderContext.set_worldBase(Matrix3d.multiplyMatrix(mat, renderContext.get_world())); - renderContext.set_world(renderContext.get_worldBase().clone()); - renderContext.makeFrustum(); - Grids._altAzLineList.viewTransform = Matrix3d.invertMatrix(mat); - Grids._altAzLineList.drawLines(renderContext, opacity, drawColor); - renderContext.set_worldBase(matOldWorldBase); - renderContext.set_world(matOldWorld); - renderContext.makeFrustum(); - return true; - }; - Grids.drawAltAzGridText = function (renderContext, opacity, drawColor) { - var zenithAltAz = new Coordinates(0, 0); - var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); - var raPart = -((zenith.get_RA() - 6) / 24 * (Math.PI * 2)); - var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); - var raText = Coordinates.formatDMS(zenith.get_RA()); - var mat = Matrix3d._rotationY(-raPart - Math.PI); - mat._multiply(Matrix3d._rotationX(decPart)); - mat.invert(); - Grids._makeAltAzGridText(); - var matOldWorld = renderContext.get_world().clone(); - var matOldWorldBase = renderContext.get_worldBase().clone(); - renderContext.set_worldBase(Matrix3d.multiplyMatrix(mat, renderContext.get_world())); - renderContext.set_world(renderContext.get_worldBase().clone()); - renderContext.makeFrustum(); - Grids._altAzTextBatch.viewTransform = Matrix3d.invertMatrix(mat); - Grids._altAzTextBatch.draw(renderContext, opacity, drawColor); - renderContext.set_worldBase(matOldWorldBase); - renderContext.set_world(matOldWorld); - renderContext.makeFrustum(); - return true; - }; - Grids._makeAltAzGridText = function () { - var drawColor = Colors.get_white(); - var index = 0; - if (Grids._altAzTextBatch == null) { - Grids._altAzTextBatch = new Text3dBatch(30); - for (var l = 0; l < 360; l += 10) { - var text = ' ' + l.toString(); - if (l < 10) { - text = ' ' + l.toString(); - } - else if (l < 100) { - text = ' ' + l.toString(); - } - var lc = 360 - l; - Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(lc / 15 - 6, 0.4, 1), Coordinates.raDecTo3dAu(lc / 15 - 6, 0.5, 1), text, 75, 0.00018)); - } - index = 0; - for (var l = 0; l < 360; l += 90) { - for (var b = -80; b <= 80; b += 10) { - if (!b) { - continue; - } - var text = b.toString(); - if (b > 0) { - text = ' +' + b.toString(); - Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(l / 15, b - 0.4, 1), Coordinates.raDecTo3dAu(l / 15, b - 0.3, 1), text, 75, 0.00018)); - } - else { - text = ' - ' + text.substr(1); - Grids._altAzTextBatch.add(new Text3d(Coordinates.raDecTo3dAu(l / 15, b + 0.4, 1), Coordinates.raDecTo3dAu(l / 15, b + 0.5, 1), text, 75, 0.00018)); - } - index++; - } - } - } - return; - }; - Grids.drawEclipticGrid = function (renderContext, opacity, drawColor) { - if (Grids._eclipticLineList == null) { - Grids._eclipticLineList = new SimpleLineList(); - Grids._eclipticLineList.set_depthBuffered(false); - var obliquity = Coordinates.meanObliquityOfEcliptic(2451545); - var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); - for (var l = 0; l < 360; l += 10) { - for (var b = -80; b < 80; b += 2) { - Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 2, 1), mat)); - } - } - for (var b = -80; b <= 80; b += 10) { - for (var l = 0; l < 360; l += 5) { - Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + 5) / 15, b, 1), mat)); - } - } - var counter = 0; - for (var l = 0; l < 360; l += 1) { - var b = 0.25; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - b = 0.5; - break; - } - counter++; - Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, -b, 1), mat)); - } - counter = 0; - for (var l = 0; l < 360; l += 90) { - counter = 0; - for (var b = -80; b <= 80; b += 1) { - var width = 0.5 / 2; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - width = 0.5; - break; - } - counter++; - Grids._eclipticLineList.addLine(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l + width) / 15, b, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu((l - width) / 15, b, 1), mat)); - } - } - } - Grids._eclipticLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids.drawEclipticGridText = function (renderContext, opacity, drawColor) { - Grids._makeEclipticGridText(); - Grids._eclipticTextBatch.draw(renderContext, opacity, drawColor); - return true; - }; - Grids._makeEclipticGridText = function () { - var drawColor = Colors.get_white(); - var obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()); - var mat = Matrix3d._rotationX((-obliquity / 360 * (Math.PI * 2))); - if (Grids._eclipticTextBatch == null) { - Grids._eclipticTextBatch = new Text3dBatch(30); - for (var l = 0; l < 360; l += 10) { - var text = ' ' + l.toString(); - if (l < 10) { - text = ' ' + l.toString(); - } - else if (l < 100) { - text = ' ' + l.toString(); - } - Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, 0.5, 1), mat), text, 75, 0.00018)); - } - for (var l = 0; l < 360; l += 90) { - for (var b = -80; b <= 80; b += 10) { - if (!b) { - continue; - } - var text = b.toString(); - if (b > 0) { - text = ' +' + b.toString(); - Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b - 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b - 0.3, 1), mat), text, 75, 0.00018)); - } - else { - text = ' - ' + text.substr(1); - Grids._eclipticTextBatch.add(new Text3d(Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 0.4, 1), mat), Vector3d._transformCoordinate(Coordinates.raDecTo3dAu(l / 15, b + 0.5, 1), mat), text, 75, 0.00018)); - } - } - } - } - return; - }; - Grids.drawGalacticGrid = function (renderContext, opacity, drawColor) { - if (Grids._galLineList == null) { - Grids._galLineList = new SimpleLineList(); - Grids._galLineList.set_depthBuffered(false); - for (var l = 0; l < 360; l += 10) { - for (var b = -80; b < 80; b += 2) { - Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l, b + 2)); - } - } - for (var b = -80; b <= 80; b += 10) { - for (var l = 0; l < 360; l += 5) { - Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l + 5, b)); - } - } - var counter = 0; - for (var l = 0; l < 360; l += 1) { - var b = 0.25; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - b = 0.5; - break; - } - counter++; - Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l, b), Coordinates.galacticTo3dDouble(l, -b)); - } - counter = 0; - for (var l = 0; l < 360; l += 90) { - counter = 0; - for (var b = -80; b <= 80; b += 1) { - var width = 0.5 / 2; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - width = 0.5; - break; - } - counter++; - Grids._galLineList.addLine(Coordinates.galacticTo3dDouble(l + width, b), Coordinates.galacticTo3dDouble(l - width, b)); - } - } - } - Grids._galLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids.drawGalacticGridText = function (renderContext, opacity, drawColor) { - Grids._makeGalacticGridText(); - Grids._galTextBatch.draw(renderContext, opacity, drawColor); - return true; - }; - Grids._makeGalacticGridText = function () { - if (Grids._galTextBatch == null) { - Grids._galTextBatch = new Text3dBatch(30); - for (var l = 0; l < 360; l += 10) { - var text = ' ' + l.toString(); - if (l < 10) { - text = ' ' + l.toString(); - } - else if (l < 100) { - text = ' ' + l.toString(); - } - Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, 0.4), Coordinates.galacticTo3dDouble(l, 0.5), text, 75, 0.00018)); - } - for (var l = 0; l < 360; l += 90) { - for (var b = -80; b <= 80; b += 10) { - if (!b) { - continue; - } - var text = b.toString(); - if (b > 0) { - text = ' +' + b.toString(); - Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, b - 0.4), Coordinates.galacticTo3dDouble(l, b - 0.3), text, 75, 0.00018)); - } - else { - text = ' - ' + text.substr(1); - Grids._galTextBatch.add(new Text3d(Coordinates.galacticTo3dDouble(l, b + 0.4), Coordinates.galacticTo3dDouble(l, b + 0.5), text, 75, 0.00018)); - } - } - } - } - }; - Grids.drawPlanetGrid = function (renderContext, opacity, drawColor) { - if (Grids._planetLineList == null) { - Grids._planetLineList = new SimpleLineList(); - Grids._planetLineList.set_depthBuffered(true); - var col = drawColor; - for (var lng = 0; lng < 360; lng += 10) { - for (var lat = -80; lat < 80; lat += 2) { - Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, lng), Coordinates.geoTo3dDouble(lat + 2, lng)); - } - } - for (var lat = -80; lat <= 80; lat += 10) { - for (var l = 0; l < 360; l += 5) { - Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, l), Coordinates.geoTo3dDouble(lat, l + 5)); - } - } - var counter = 0; - for (var lng = 0; lng < 360; lng += 1) { - var lat = 0.25; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - lat = 0.5; - break; - } - counter++; - Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(lat, lng), Coordinates.geoTo3dDouble(-lat, lng)); - } - counter = 0; - for (var lng = 0; lng < 360; lng += 90) { - counter = 0; - for (var b = -80; b <= 80; b += 1) { - var width = 0.5 / 2; - switch (counter % 10) { - case 0: - counter++; - continue; - case 5: - width = 0.5; - break; - } - counter++; - Grids._planetLineList.addLine(Coordinates.geoTo3dDouble(b, lng + width), Coordinates.geoTo3dDouble(b, lng - width)); - } - } - } - Grids._planetLineList.aaFix = false; - Grids._planetLineList.set_depthBuffered(true); - Grids._planetLineList.sky = false; - Grids._planetLineList.drawLines(renderContext, opacity, drawColor); - return true; - }; - Grids.drawPlanetGridText = function (renderContext, opacity, drawColor) { - Grids._makePlanetGridText(); - Grids._planetTextBatch.draw(renderContext, opacity, drawColor); - return true; - }; - Grids._makePlanetGridText = function () { - if (Grids._planetTextBatch == null) { - Grids._planetTextBatch = new Text3dBatch(80); - for (var lng = -180; lng < 180; lng += 10) { - var text = ' ' + lng.toString(); - if (lng < 10) { - text = ' ' + lng.toString(); - } - else if (lng < 100) { - text = ' ' + lng.toString(); - } - Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(0.4, lng), Coordinates.geoTo3dDouble(0.5, lng), text, -80, 6E-05)); - } - for (var lng = 0; lng < 360; lng += 90) { - for (var lat = -80; lat <= 80; lat += 10) { - if (!lat) { - continue; - } - var text = lat.toString(); - if (lat > 0) { - text = ' +' + lat.toString(); - Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(lat - 0.4, lng), Coordinates.geoTo3dDouble(lat - 0.3, lng), text, -80, 6E-05)); - } - else { - text = ' - ' + text.substring(1); - Grids._planetTextBatch.add(new Text3d(Coordinates.geoTo3dDouble(lat + 0.4, lng), Coordinates.geoTo3dDouble(lat + 0.5, lng), text, -80, 6E-05)); - } - } - } - } - }; - var Grids$ = { - - }; - - - // wwtlib.Imageset - - function Imageset() { - this._projection = 0; - this._imageSetID = 0; - this._baseTileDegrees = 0; - this._widthFactor = 1; - this.demUrl = ''; - this._levels = 0; - this._mercator = false; - this._bottomsUp = false; - this._baseLevel = 1; - this._quadTreeTileMap = '0123'; - this._centerX = 0; - this._centerY = 0; - this._rotation = 0; - this._meanRadius = 0; - this._dataSetType = 0; - this._bandPass = 3; - this._altUrl = ''; - this._singleImage = false; - this._fitsProperties = new FitsProperties(); - this._matrixComputed = false; - this._name = ''; - this._sparse = false; - this._thumbnailUrl = ''; - this._generic = false; - this._defaultSet = false; - this._elevationModel = false; - this._offsetX = 0; - this._offsetY = 0; - } - Imageset.getTileKey = function (imageset, level, x, y, parent) { - if (imageset.get_projection() === 7 && parent != null) { - var ipix = (parent).ipix * 4 + y * 2 + x; - return imageset.get_imageSetID().toString() + '\\' + level.toString() + '\\' + ipix.toString(); - } - return imageset.get_imageSetID().toString() + '\\' + level.toString() + '\\' + y.toString() + '_' + x.toString(); - }; - Imageset.getNewTile = function (imageset, level, x, y, parent) { - switch (imageset.get_projection()) { - case 0: - var newTile = MercatorTile.create(level, x, y, imageset, parent); - return newTile; - case 1: - return EquirectangularTile.create(level, x, y, imageset, parent); - case 3: - default: - return ToastTile.create(level, x, y, imageset, parent); - case 5: - return new SkyImageTile(level, x, y, imageset, parent); - case 6: - return PlotTile.create(level, x, y, imageset, parent); - case 7: - if (imageset.get_hipsProperties() == null) { - imageset.set_hipsProperties(new HipsProperties(imageset)); - } - if (imageset.get_hipsProperties().get_downloadComplete()) { - return new HealpixTile(level, x, y, imageset, parent); - } - else { - return null; - } - case 2: - var newTile = new TangentTile(level, x, y, imageset, parent); - return newTile; - } - }; - Imageset.fromXMLNode = function (node) { - try { - var type = 2; - var projection = 2; - if (node.attributes.getNamedItem('DataSetType') != null) { - type = Enums.parse('ImageSetType', node.attributes.getNamedItem('DataSetType').nodeValue); - } - var bandPass = 3; - bandPass = Enums.parse('BandPass', node.attributes.getNamedItem('BandPass').nodeValue); - var wf = 1; - if (node.attributes.getNamedItem('WidthFactor') != null) { - wf = parseInt(node.attributes.getNamedItem('WidthFactor').nodeValue); - } - if (node.attributes.getNamedItem('Generic') == null || !ss.boolean(node.attributes.getNamedItem('Generic').nodeValue)) { - projection = Enums.parse('ProjectionType', node.attributes.getNamedItem('Projection').nodeValue); - var fileType = node.attributes.getNamedItem('FileType').nodeValue; - if (!ss.startsWith(fileType, '.')) { - fileType = '.' + fileType; - } - var thumbnailUrl = ''; - var thumbUrl = Util.selectSingleNode(node, 'ThumbnailUrl'); - if (thumbUrl != null) { - if (ss.emptyString(thumbUrl.text)) { - var cn = thumbUrl; - thumbnailUrl = cn.textContent; - } - else { - thumbnailUrl = thumbUrl.text; - } - } - var stockSet = false; - var elevationModel = false; - if (node.attributes.getNamedItem('StockSet') != null) { - stockSet = ss.boolean(node.attributes.getNamedItem('StockSet').nodeValue); - } - if (node.attributes.getNamedItem('ElevationModel') != null) { - elevationModel = ss.boolean(node.attributes.getNamedItem('ElevationModel').nodeValue); - } - var demUrl = ''; - if (node.attributes.getNamedItem('DemUrl') != null) { - demUrl = node.attributes.getNamedItem('DemUrl').nodeValue; - } - var alturl = ''; - if (node.attributes.getNamedItem('AltUrl') != null) { - alturl = node.attributes.getNamedItem('AltUrl').nodeValue; - } - var offsetX = 0; - if (node.attributes.getNamedItem('OffsetX') != null) { - offsetX = parseFloat(node.attributes.getNamedItem('OffsetX').nodeValue); - } - var offsetY = 0; - if (node.attributes.getNamedItem('OffsetY') != null) { - offsetY = parseFloat(node.attributes.getNamedItem('OffsetY').nodeValue); - } - var creditText = ''; - var credits = Util.selectSingleNode(node, 'Credits'); - if (credits != null) { - creditText = Util.getInnerText(credits); - } - var creditsUrl = ''; - credits = Util.selectSingleNode(node, 'CreditsUrl'); - if (credits != null) { - creditsUrl = Util.getInnerText(credits); - } - var meanRadius = 0; - if (node.attributes.getNamedItem('MeanRadius') != null) { - meanRadius = parseFloat(node.attributes.getNamedItem('MeanRadius').nodeValue); - } - var referenceFrame = null; - if (node.attributes.getNamedItem('ReferenceFrame') != null) { - referenceFrame = node.attributes.getNamedItem('ReferenceFrame').nodeValue; - } - var name = ''; - if (node.attributes.getNamedItem('Name') != null) { - name = node.attributes.getNamedItem('Name').nodeValue; - } - var url = ''; - if (node.attributes.getNamedItem('Url') != null) { - url = node.attributes.getNamedItem('Url').nodeValue; - } - var baseTileLevel = 0; - if (node.attributes.getNamedItem('BaseTileLevel') != null) { - baseTileLevel = parseInt(node.attributes.getNamedItem('BaseTileLevel').nodeValue); - } - var tileLevels = 0; - if (node.attributes.getNamedItem('TileLevels') != null) { - tileLevels = parseInt(node.attributes.getNamedItem('TileLevels').nodeValue); - } - var baseDegreesPerTile = 0; - if (node.attributes.getNamedItem('BaseDegreesPerTile') != null) { - baseDegreesPerTile = parseFloat(node.attributes.getNamedItem('BaseDegreesPerTile').nodeValue); - } - var bottomsUp = false; - if (node.attributes.getNamedItem('BottomsUp') != null) { - bottomsUp = ss.boolean(node.attributes.getNamedItem('BottomsUp').nodeValue); - } - var quadTreeMap = ''; - if (node.attributes.getNamedItem('QuadTreeMap') != null) { - quadTreeMap = node.attributes.getNamedItem('QuadTreeMap').nodeValue; - } - var centerX = 0; - if (node.attributes.getNamedItem('CenterX') != null) { - centerX = parseFloat(node.attributes.getNamedItem('CenterX').nodeValue); - } - var centerY = 0; - if (node.attributes.getNamedItem('CenterY') != null) { - centerY = parseFloat(node.attributes.getNamedItem('CenterY').nodeValue); - } - var rotation = 0; - if (node.attributes.getNamedItem('Rotation') != null) { - rotation = parseFloat(node.attributes.getNamedItem('Rotation').nodeValue); - } - var sparse = false; - if (node.attributes.getNamedItem('Sparse') != null) { - sparse = ss.boolean(node.attributes.getNamedItem('Sparse').nodeValue); - } - return Imageset.create(name, url, type, bandPass, projection, Math.abs(Util.getHashCode(url)), baseTileLevel, tileLevels, 256, baseDegreesPerTile, fileType, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, stockSet, elevationModel, wf, offsetX, offsetY, creditText, creditsUrl, demUrl, alturl, meanRadius, referenceFrame); - } - else { - return Imageset.createGeneric(type, bandPass); - } - } - catch ($e1) { - return null; - } - }; - Imageset.saveToXml = function (xmlWriter, imageset, alternateUrl) { - xmlWriter._writeStartElement('ImageSet'); - xmlWriter._writeAttributeString('Generic', imageset.get_generic().toString()); - xmlWriter._writeAttributeString('DataSetType', Enums.toXml('ImageSetType', imageset.get_dataSetType())); - xmlWriter._writeAttributeString('BandPass', Enums.toXml('BandPass', imageset.get_bandPass())); - if (!imageset.get_generic()) { - xmlWriter._writeAttributeString('Name', imageset.get_name()); - if (ss.emptyString(alternateUrl)) { - xmlWriter._writeAttributeString('Url', imageset.get_url()); - } - else { - xmlWriter._writeAttributeString('Url', alternateUrl); - } - xmlWriter._writeAttributeString('DemUrl', imageset.get_demUrl()); - xmlWriter._writeAttributeString('BaseTileLevel', imageset.get_baseLevel().toString()); - xmlWriter._writeAttributeString('TileLevels', imageset.get_levels().toString()); - xmlWriter._writeAttributeString('BaseDegreesPerTile', imageset.get_baseTileDegrees().toString()); - xmlWriter._writeAttributeString('FileType', imageset.get_extension()); - xmlWriter._writeAttributeString('BottomsUp', imageset.get_bottomsUp().toString()); - xmlWriter._writeAttributeString('Projection', Enums.toXml('ProjectionType', imageset.get_projection())); - xmlWriter._writeAttributeString('QuadTreeMap', imageset.get_quadTreeTileMap()); - xmlWriter._writeAttributeString('CenterX', imageset.get_centerX().toString()); - xmlWriter._writeAttributeString('CenterY', imageset.get_centerY().toString()); - xmlWriter._writeAttributeString('OffsetX', imageset.get_offsetX().toString()); - xmlWriter._writeAttributeString('OffsetY', imageset.get_offsetY().toString()); - xmlWriter._writeAttributeString('Rotation', imageset.get_rotation().toString()); - xmlWriter._writeAttributeString('Sparse', imageset.get_sparse().toString()); - xmlWriter._writeAttributeString('ElevationModel', imageset.get_elevationModel().toString()); - xmlWriter._writeAttributeString('StockSet', imageset.get_defaultSet().toString()); - xmlWriter._writeAttributeString('WidthFactor', imageset.get_widthFactor().toString()); - xmlWriter._writeAttributeString('MeanRadius', imageset.get_meanRadius().toString()); - xmlWriter._writeAttributeString('ReferenceFrame', imageset.get_referenceFrame()); - if (ss.emptyString(alternateUrl)) { - xmlWriter._writeElementString('ThumbnailUrl', imageset.get_thumbnailUrl()); - } - else { - xmlWriter._writeElementString('ThumbnailUrl', imageset.get_url()); - } - } - xmlWriter._writeEndElement(); - }; - Imageset.createGeneric = function (dataSetType, bandPass) { - var temp = new Imageset(); - temp._generic = true; - temp._name = 'Generic'; - temp._sparse = false; - temp._dataSetType = dataSetType; - temp._bandPass = bandPass; - temp._quadTreeTileMap = ''; - temp.url = ''; - temp._levels = 0; - temp._baseTileDegrees = 0; - temp._imageSetID = 0; - temp._extension = ''; - temp._projection = 1; - temp._bottomsUp = false; - temp._baseLevel = 0; - temp._mercator = (!temp._projection); - temp._centerX = 0; - temp._centerY = 0; - temp._rotation = 0; - temp._thumbnailUrl = ''; - temp._matrix = Matrix3d.get_identity(); - temp._matrix._multiply(Matrix3d._rotationX((temp.get_rotation() / 180 * Math.PI))); - temp._matrix._multiply(Matrix3d._rotationZ((temp.get_centerY() / 180 * Math.PI))); - temp._matrix._multiply(Matrix3d._rotationY((((360 - temp.get_centerX()) + 180) / 180 * Math.PI))); - return temp; - }; - Imageset.create = function (name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, tileSize, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame) { - var temp = new Imageset(); - temp.setInitialParameters(name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame); - return temp; - }; - var Imageset$ = { - get_wcsImage: function () { - return this._wcsImage; - }, - set_wcsImage: function (value) { - this._wcsImage = value; - return value; - }, - get_projection: function () { - return this._projection; - }, - set_projection: function (value) { - this._projection = value; - return value; - }, - get_referenceFrame: function () { - return this._referenceFrame; - }, - set_referenceFrame: function (value) { - this._referenceFrame = value; - return value; - }, - get_imageSetID: function () { - return this._imageSetID; - }, - set_imageSetID: function (value) { - this._imageSetID = value; - return value; - }, - get_baseTileDegrees: function () { - return this._baseTileDegrees; - }, - set_baseTileDegrees: function (value) { - this._baseTileDegrees = value; - return value; - }, - get_widthFactor: function () { - return this._widthFactor; - }, - set_widthFactor: function (value) { - this._widthFactor = value; - return value; - }, - getHashCode: function () { - return Util.getHashCode(this.get_url()); - }, - get_url: function () { - return this.url; - }, - set_url: function (value) { - this.url = value; - return value; - }, - get_demUrl: function () { - if (ss.emptyString(this.demUrl) && !this._projection && !WWTControl.singleton.freestandingMode) { - return URLHelpers.singleton.coreStaticUrl('wwtweb/BingDemTile.aspx?Q={0},{1},{2}'); - } - return this.demUrl; - }, - set_demUrl: function (value) { - this.demUrl = value; - return value; - }, - get_extension: function () { - return this._extension; - }, - set_extension: function (value) { - this._extension = value; - return value; - }, - get_levels: function () { - return this._levels; - }, - set_levels: function (value) { - this._levels = value; - return value; - }, - get_bottomsUp: function () { - return this._bottomsUp; - }, - set_bottomsUp: function (value) { - this._bottomsUp = value; - return value; - }, - get_mercator: function () { - return this._mercator; - }, - set_mercator: function (value) { - this._mercator = value; - return value; - }, - get_baseLevel: function () { - return this._baseLevel; - }, - set_baseLevel: function (value) { - this._baseLevel = value; - return value; - }, - get_quadTreeTileMap: function () { - return this._quadTreeTileMap; - }, - set_quadTreeTileMap: function (value) { - this._quadTreeTileMap = value; - return value; - }, - get_centerX: function () { - return this._centerX; - }, - set_centerX: function (value) { - if (this._centerX !== value) { - this._centerX = value; - this._computeMatrix(); - } - return value; - }, - get_centerY: function () { - return this._centerY; - }, - set_centerY: function (value) { - if (this._centerY !== value) { - this._centerY = value; - this._computeMatrix(); - } - return value; - }, - get_rotation: function () { - return this._rotation; - }, - set_rotation: function (value) { - if (this._rotation !== value) { - this._rotation = value; - this._computeMatrix(); - } - return value; - }, - get_meanRadius: function () { - return this._meanRadius; - }, - set_meanRadius: function (value) { - this._meanRadius = value; - return value; - }, - get_bandPass: function () { - return this._bandPass; - }, - set_bandPass: function (value) { - this._bandPass = value; - return value; - }, - get_dataSetType: function () { - return this._dataSetType; - }, - set_dataSetType: function (value) { - this._dataSetType = value; - return value; - }, - get_altUrl: function () { - return this._altUrl; - }, - set_altUrl: function (value) { - this._altUrl = value; - return value; - }, - get_singleImage: function () { - return this._singleImage; - }, - set_singleImage: function (value) { - this._singleImage = value; - return value; - }, - get_hipsProperties: function () { - return this._hipsProperties; - }, - set_hipsProperties: function (value) { - this._hipsProperties = value; - return value; - }, - get_fitsProperties: function () { - return this._fitsProperties; - }, - set_fitsProperties: function (value) { - this._fitsProperties = value; - return value; - }, - toString: function () { - if (this.get_defaultSet()) { - return this._name + ' *'; - } - else { - return this._name; - } - }, - get_stockImageSet: function () { - if (this._generic || !this._defaultSet) { - return this; - } - else { - return Imageset.createGeneric(this.get_dataSetType(), this.get_bandPass()); - } - }, - equals: function (obj) { - if (obj == null) { - return false; - } - if (!(ss.canCast(obj, Imageset))) { - return false; - } - var b = obj; - return (Util.getHashCode(b.get_url()) === Util.getHashCode(this.get_url()) && b.get_dataSetType() === this.get_dataSetType() && b.get_bandPass() === this.get_bandPass() && b.get_generic() === this.get_generic()); - }, - get_matrix: function () { - if (!this._matrixComputed) { - this._computeMatrix(); - } - return this._matrix; - }, - set_matrix: function (value) { - this._matrix = value; - return value; - }, - _computeMatrix: function () { - this._matrixComputed = true; - this._matrix = Matrix3d.get_identity(); - this._matrix._multiply(Matrix3d._rotationX((this.get_rotation() / 180 * Math.PI))); - this._matrix._multiply(Matrix3d._rotationZ((this.get_centerY() / 180 * Math.PI))); - this._matrix._multiply(Matrix3d._rotationY(((360 - this.get_centerX()) / 180 * Math.PI))); - }, - get_name: function () { - return this._name; - }, - set_name: function (value) { - this._name = value; - return value; - }, - get_sparse: function () { - return this._sparse; - }, - set_sparse: function (value) { - this._sparse = value; - return value; - }, - get_thumbnailUrl: function () { - return this._thumbnailUrl; - }, - set_thumbnailUrl: function (value) { - this._thumbnailUrl = value; - return value; - }, - get_generic: function () { - return this._generic; - }, - set_generic: function (value) { - this._generic = value; - return value; - }, - get_elevationModel: function () { - return this._elevationModel; - }, - set_elevationModel: function (value) { - this._elevationModel = value; - return value; - }, - get_defaultSet: function () { - return this._defaultSet; - }, - set_defaultSet: function (value) { - this._defaultSet = value; - return value; - }, - get_offsetX: function () { - return this._offsetX; - }, - set_offsetX: function (value) { - this._offsetX = value; - return value; - }, - get_offsetY: function () { - return this._offsetY; - }, - set_offsetY: function (value) { - this._offsetY = value; - return value; - }, - get_creditsText: function () { - return this._creditsText; - }, - set_creditsText: function (value) { - this._creditsText = value; - return value; - }, - get_creditsUrl: function () { - return this._creditsUrl; - }, - set_creditsUrl: function (value) { - this._creditsUrl = value; - return value; - }, - get_isMandelbrot: function () { - return false; - }, - _calcViewCenterCoordinate: function (isX) { - var rot = Coordinates.degreesToRadians(this._rotation); - var crot = Math.cos(rot); - var srot = Math.sin(rot); - var dx = 0, dy = 0; - if (this.get_levels() > 0) { - dx = -this._offsetX; - dy = this._offsetY; - } - else { - var effWidth = 800; - var effHeight = 800; - dx = (this._offsetX - effWidth / 2) * this._baseTileDegrees; - dy = (effHeight / 2 - this._offsetY) * this._baseTileDegrees; - } - if (this._bottomsUp) { - dx = -dx; - } - if (isX) { - return this._centerX + dx * crot + dy * srot; - } - else { - return this._centerY - dx * srot + dy * crot; - } - }, - get_viewCenterX: function () { - if (this.get_wcsImage() != null) { - return (this.get_wcsImage()).get_viewCenterX(); - } - else { - return this._calcViewCenterCoordinate(true); - } - }, - get_viewCenterY: function () { - if (this.get_wcsImage() != null) { - return (this.get_wcsImage()).get_viewCenterY(); - } - else { - return this._calcViewCenterCoordinate(false); - } - }, - setInitialParameters: function (name, url, dataSetType, bandPass, projection, imageSetID, baseLevel, levels, baseTileDegrees, extension, bottomsUp, quadTreeMap, centerX, centerY, rotation, sparse, thumbnailUrl, defaultSet, elevationModel, wf, offsetX, offsetY, credits, creditsUrl, demUrlIn, alturl, meanRadius, referenceFrame) { - this.set_referenceFrame(referenceFrame); - this.set_meanRadius(meanRadius); - this._altUrl = alturl; - this.demUrl = demUrlIn; - this._creditsText = credits; - this._creditsUrl = creditsUrl; - this._offsetY = offsetY; - this._offsetX = offsetX; - this._widthFactor = wf; - this._elevationModel = elevationModel; - this._defaultSet = defaultSet; - this._name = name; - this._sparse = sparse; - this._dataSetType = dataSetType; - this._bandPass = bandPass; - this._quadTreeTileMap = quadTreeMap; - this.url = url; - this._levels = levels; - this._baseTileDegrees = baseTileDegrees; - this._imageSetID = imageSetID; - this._extension = extension; - this._projection = projection; - this._bottomsUp = bottomsUp; - this._baseLevel = baseLevel; - this._mercator = (!projection); - this._centerX = centerX; - this._centerY = centerY; - this._rotation = rotation; - this._thumbnailUrl = thumbnailUrl; - this._computeMatrix(); - }, - _guessZoomSetting: function (currentZoom) { - var zoom = currentZoom; - var aswcs = ss.safeCast(this._wcsImage, FitsImage); - if (this.get_projection() === 5) { - if (aswcs != null) { - zoom = this.get_baseTileDegrees() * aswcs.get_sizeY() * 6 * 1.7; - } - } - else if (aswcs != null) { - zoom = aswcs.get_scaleY() * aswcs.get_sizeY() * 6 * 1.7; - } - else { - zoom = this.get_baseTileDegrees() * 6 * 1.7; - } - if (zoom > currentZoom) { - zoom = currentZoom; - } - return zoom; - }, - get_thumbnail: function () { - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - return value; - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_isImage: function () { - return true; - }, - get_isTour: function () { - return false; - }, - get_isFolder: function () { - return false; - }, - get_isCloudCommunityItem: function () { - return false; - }, - get_readOnly: function () { - return false; - }, - get_children: function () { - return []; - } - }; - - - // wwtlib.ViewMoverKenBurnsStyle - - function ViewMoverKenBurnsStyle(from, to, time, fromDateTime, toDateTime, type) { - this.interpolationType = 0; - this.fastDirectionMove = false; - this._toTargetTime = 0; - this._dateTimeSpan = 0; - this._complete = false; - this._midpointFired = false; - this.interpolationType = type; - if (Math.abs(from.lng - to.lng) > 180) { - if (from.lng > to.lng) { - from.lng -= 360; - } - else { - from.lng += 360; - } - } - this._fromDateTime = fromDateTime; - this._toDateTime = toDateTime; - this._dateTimeSpan = toDateTime - fromDateTime; - this._from = from.copy(); - this._to = to.copy(); - this._fromTime = SpaceTimeController.get_metaNow(); - this._toTargetTime = time; - } - var ViewMoverKenBurnsStyle$ = { - get_complete: function () { - return this._complete; - }, - get_currentPosition: function () { - var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; - var elapsedSeconds = (elapsed) / 1000; - var alpha = elapsedSeconds / this._toTargetTime; - if (!this._midpointFired && alpha >= 0.5) { - this._midpointFired = true; - if (this._midpoint != null) { - this._midpoint(); - } - } - if (alpha >= 1) { - alpha = 1; - this._complete = true; - return this._to.copy(); - } - if (Settings.get_active().get_galacticMode() && WWTControl.singleton.renderContext.space) { - return CameraParameters.interpolateGreatCircle(this._from, this._to, alpha, this.interpolationType, this.fastDirectionMove); - } - return CameraParameters.interpolate(this._from, this._to, alpha, this.interpolationType, this.fastDirectionMove); - }, - get_currentDateTime: function () { - var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; - var elapsedSeconds = (elapsed) / 1000; - var alpha = elapsedSeconds / this._toTargetTime; - var delta = this._dateTimeSpan * alpha; - var retDate = new Date(this._fromDateTime.getTime() + ss.truncate(delta)); - return retDate; - }, - get_midpoint: function () { - return this._midpoint; - }, - set_midpoint: function (value) { - this._midpoint = value; - return value; - }, - get_moveTime: function () { - return this._toTargetTime; - } - }; - - - // wwtlib.ViewMoverSlew - - function ViewMoverSlew() { - this._upTargetTime = 0; - this._downTargetTime = 0; - this._toTargetTime = 0; - this._upTimeFactor = 0.6; - this._downTimeFactor = 0.6; - this._travelTimeFactor = 7; - this._midpointFired = false; - this._complete = false; - } - ViewMoverSlew.create = function (from, to) { - var temp = new ViewMoverSlew(); - temp.init(from, to); - return temp; - }; - ViewMoverSlew.createUpDown = function (from, to, upDowFactor) { - var temp = new ViewMoverSlew(); - temp._upTimeFactor = temp._downTimeFactor = upDowFactor; - temp.init(from.copy(), to.copy()); - return temp; - }; - var ViewMoverSlew$ = { - init: function (from, to) { - if (Math.abs(from.lng - to.lng) > 180) { - if (from.lng > to.lng) { - from.lng -= 360; - } - else { - from.lng += 360; - } - } - if (to.zoom <= 0) { - to.zoom = 360; - } - if (from.zoom <= 0) { - from.zoom = 360; - } - this._from = from; - this._to = to; - this._fromTime = SpaceTimeController.get_metaNow(); - var zoomUpTarget = 360; - var travelTime; - var lngDist = Math.abs(from.lng - to.lng); - var latDist = Math.abs(from.lat - to.lat); - var distance = Math.sqrt(latDist * latDist + lngDist * lngDist); - zoomUpTarget = (distance / 3) * 20; - if (zoomUpTarget > 360) { - zoomUpTarget = 360; - } - if (zoomUpTarget < from.zoom) { - zoomUpTarget = from.zoom; - } - travelTime = (distance / 180) * (360 / zoomUpTarget) * this._travelTimeFactor; - var rotateTime = Math.max(Math.abs(from.angle - to.angle), Math.abs(from.rotation - to.rotation)); - var logDistUp = Math.max(Math.abs(Util.logN(zoomUpTarget, 2) - Util.logN(from.zoom, 2)), rotateTime); - this._upTargetTime = this._upTimeFactor * logDistUp; - this._downTargetTime = this._upTargetTime + travelTime; - var logDistDown = Math.abs(Util.logN(zoomUpTarget, 2) - Util.logN(to.zoom, 2)); - this._toTargetTime = this._downTargetTime + Math.max((this._downTimeFactor * logDistDown), rotateTime); - this._fromTop = from.copy(); - this._fromTop.zoom = zoomUpTarget; - this._fromTop.angle = (from.angle + to.angle) / 2; - this._fromTop.rotation = (from.rotation + to.rotation) / 2; - this._toTop = to.copy(); - this._toTop.zoom = this._fromTop.zoom; - this._toTop.angle = this._fromTop.angle; - this._toTop.rotation = this._fromTop.rotation; - }, - get_complete: function () { - return this._complete; - }, - get_currentPosition: function () { - var elapsed = SpaceTimeController.get_metaNow() - this._fromTime; - var elapsedSeconds = (elapsed) / 1000; - if (elapsedSeconds < this._upTargetTime) { - return CameraParameters.interpolate(this._from, this._fromTop, elapsedSeconds / this._upTargetTime, 3, false); - } - else if (elapsedSeconds < this._downTargetTime) { - elapsedSeconds -= this._upTargetTime; - if (Settings.get_active().get_galacticMode() && WWTControl.singleton.renderContext.space) { - return CameraParameters.interpolateGreatCircle(this._fromTop, this._toTop, elapsedSeconds / (this._downTargetTime - this._upTargetTime), 3, false); - } - return CameraParameters.interpolate(this._fromTop, this._toTop, elapsedSeconds / (this._downTargetTime - this._upTargetTime), 3, false); - } - else { - if (!this._midpointFired) { - this._midpointFired = true; - if (this._midpoint != null) { - this._midpoint(); - } - } - elapsedSeconds -= this._downTargetTime; - var alpha = elapsedSeconds / (this._toTargetTime - this._downTargetTime); - if (alpha > 1) { - alpha = 1; - this._complete = true; - return this._to.copy(); - } - return CameraParameters.interpolate(this._toTop, this._to, alpha, 3, false); - } - }, - get_currentDateTime: function () { - SpaceTimeController.updateClock(); - return SpaceTimeController.get_now(); - }, - get_midpoint: function () { - return this._midpoint; - }, - set_midpoint: function (value) { - this._midpoint = value; - return value; - }, - get_moveTime: function () { - return this._toTargetTime; - } - }; - - - // wwtlib.KeplerVertex - - function KeplerVertex() { - this.ABC = new Vector3d(); - this.abc1 = new Vector3d(); - this.pointSize = 0; - this.w = 0; - this.e = 0; - this.n = 0; - this.t = 0; - this.a = 0; - this.z = 0; - this.orbitPos = 0; - this.orbits = 0; - } - var KeplerVertex$ = { - fill: function (ee) { - var F = Math.cos(ee.omega * KeplerVertex._degrad); - var sinOmega = Math.sin(ee.omega * KeplerVertex._degrad); - var cosi = Math.cos(ee.i * KeplerVertex._degrad); - var sini = Math.sin(ee.i * KeplerVertex._degrad); - var G = sinOmega * KeplerVertex._cose; - var H = sinOmega * KeplerVertex._sine; - var P = -sinOmega * cosi; - var Q = (F * cosi * KeplerVertex._cose) - (sini * KeplerVertex._sine); - var R = (F * cosi * KeplerVertex._sine) + (sini * KeplerVertex._cose); - var checkA = (F * F) + (G * G) + (H * H); - var checkB = (P * P) + (Q * Q) + (R * R); - this.ABC.x = Math.atan2(F, P); - this.ABC.y = Math.atan2(G, Q); - this.ABC.z = Math.atan2(H, R); - this.abc1.x = Math.sqrt((F * F) + (P * P)); - this.abc1.y = Math.sqrt((G * G) + (Q * Q)); - this.abc1.z = Math.sqrt((H * H) + (R * R)); - this.pointSize = 0.1; - if (ee.a < 2.5) { - this.color = Colors.get_white(); - } - else if (ee.a < 2.83) { - this.color = Colors.get_red(); - } - else if (ee.a < 2.96) { - this.color = Colors.get_green(); - } - else if (ee.a < 3.3) { - this.color = Colors.get_magenta(); - } - else if (ee.a < 5) { - this.color = Colors.get_cyan(); - } - else if (ee.a < 10) { - this.color = Colors.get_yellow(); - this.pointSize = 0.9; - } - else { - this.color = Colors.get_white(); - this.pointSize = 8; - } - this.w = ee.w; - this.e = ee.e; - if (!ee.n) { - this.n = (0.9856076686 / (ee.a * Math.sqrt(ee.a))); - } - else { - this.n = ee.n; - } - this.t = (ee.t - KeplerVertex.baseDate); - this.a = ee.a; - this.z = 0; - this.orbitPos = 0; - this.orbits = 0; - } - }; - - - // wwtlib.ScaleMap - - function ScaleMap() { - } - var ScaleMap$ = { - - }; - - - // wwtlib.ColorMapContainer - - function ColorMapContainer() { - this.colors = []; - } - ColorMapContainer.fromArgbList = function (color_list) { - var temp = new ColorMapContainer(); - var $enum1 = ss.enumerate(color_list); - while ($enum1.moveNext()) { - var color = $enum1.current; - temp.colors.push(Color.fromArgb(color[0], color[1], color[2], color[3])); - } - return temp; - }; - ColorMapContainer.fromStringList = function (color_list) { - var temp = new ColorMapContainer(); - var $enum1 = ss.enumerate(color_list); - while ($enum1.moveNext()) { - var color = $enum1.current; - temp.colors.push(Color.load(color)); - } - return temp; - }; - ColorMapContainer.fromNamedColormap = function (name) { - if (name == null) { - return null; - } - switch (name.toLowerCase()) { - case 'viridis': - return ColorMapContainer.viridis; - case 'plasma': - return ColorMapContainer.plasma; - case 'inferno': - return ColorMapContainer.inferno; - case 'magma': - return ColorMapContainer.magma; - case 'cividis': - return ColorMapContainer.cividis; - case 'greys': - return ColorMapContainer.greys; - case 'gray': - return ColorMapContainer.gray; - case 'purples': - return ColorMapContainer.purples; - case 'blues': - return ColorMapContainer.blues; - case 'greens': - return ColorMapContainer.greens; - case 'oranges': - return ColorMapContainer.oranges; - case 'reds': - return ColorMapContainer.reds; - case 'rdylbu': - return ColorMapContainer.rdYlBu; - } - return null; - }; - ColorMapContainer._getTextureFromName = function (gl, name) { - var texture = ColorMapContainer.colorTextures[name]; - if (texture == null) { - var colorMapContainer = ColorMapContainer.fromNamedColormap(name); - if (colorMapContainer != null) { - texture = ColorMapContainer._initColorTexture(gl, colorMapContainer); - ColorMapContainer.colorTextures[name.toLowerCase()] = texture; - } - } - return texture; - }; - ColorMapContainer.bindColorMapTexture = function (gl, colorMapName) { - var texture = ColorMapContainer._getTextureFromName(gl, colorMapName); - if (texture == null) { - texture = ColorMapContainer._getTextureFromName(gl, 'gray'); - } - gl.activeTexture(33985); - gl.bindTexture(3553, texture); - }; - ColorMapContainer._initColorTexture = function (gl, colorMapContainer) { - var colorTexture = gl.createTexture(); - gl.activeTexture(33985); - gl.bindTexture(3553, colorTexture); - gl.texParameteri(3553, 10242, 33071); - gl.texParameteri(3553, 10243, 33071); - var colorBuffer = ColorMapContainer._extractColorArray(colorMapContainer.colors); - gl.texImage2D(3553, 0, 32849, colorBuffer.length / 3, 1, 0, 6407, 5121, colorBuffer); - gl.texParameteri(3553, 10241, 9728); - gl.texParameteri(3553, 10240, 9728); - return colorTexture; - }; - ColorMapContainer._extractColorArray = function (colors) { - var index = 0; - var colorBuffer = new Uint8Array(colors.length * 3); - var $enum1 = ss.enumerate(colors); - while ($enum1.moveNext()) { - var color = $enum1.current; - colorBuffer[index++] = color.r; - colorBuffer[index++] = color.g; - colorBuffer[index++] = color.b; - } - return colorBuffer; - }; - var ColorMapContainer$ = { - findClosestColor: function (value) { - var index; - if (value <= 0) { - return this.colors[0]; - } - else if (value >= 1) { - return this.colors[this.colors.length - 1]; - } - else { - index = ss.truncate((value * this.colors.length)); - return this.colors[index]; - } - } - }; - - - // wwtlib.Layer - - function Layer() { - this.id = Guid.newGuid(); - this.loadedFromTour = false; - this.tourDocument = null; - this.opacity = 1; - this.opened = false; - this._startTime = ss.date('01/01/1900'); - this._endTime = ss.date('01/01/2100'); - this._fadeSpan = 0; - this._fadeType = 4; - this.version = 0; - this.color = Colors.get_white(); - this.enabled = true; - this.astronomical = false; - } - Layer.fromXml = function (layerNode, someFlag) { - var layerClassName = layerNode.attributes.getNamedItem('Type').nodeValue; - var overLayType = ss.replaceString(layerClassName, 'TerraViewer.', ''); - if (overLayType == null) { - return null; - } - var newLayer = null; - switch (overLayType) { - case 'SpreadSheetLayer': - newLayer = new SpreadSheetLayer(); - break; - case 'GreatCirlceRouteLayer': - newLayer = new GreatCirlceRouteLayer(); - break; - case 'GridLayer': - newLayer = new GridLayer(); - break; - case 'ImageSetLayer': - newLayer = new ImageSetLayer(); - break; - case 'Object3dLayer': - newLayer = new Object3dLayer(); - break; - case 'OrbitLayer': - newLayer = new OrbitLayer(); - break; - case 'VoTableLayer': - newLayer = new VoTableLayer(); - break; - default: - return null; - } - newLayer.initFromXml(layerNode); - return newLayer; - }; - var Layer$ = { - getPrimaryUI: function () { - return null; - }, - getFileStreamUrl: function (filename) { - if (this.tourDocument != null) { - return this.tourDocument.getFileStream(filename); - } - return null; - }, - get_opacity: function () { - return this.opacity; - }, - set_opacity: function (value) { - if (this.opacity !== value) { - this.version++; - this.opacity = value; - } - return value; - }, - get_opened: function () { - return this.opened; - }, - set_opened: function (value) { - if (this.opened !== value) { - this.version++; - this.opened = value; - } - return value; - }, - get_startTime: function () { - return this._startTime; - }, - set_startTime: function (value) { - if (!ss.compareDates(this._startTime, value)) { - this.version++; - this._startTime = value; - } - return value; - }, - get_endTime: function () { - return this._endTime; - }, - set_endTime: function (value) { - if (!ss.compareDates(this._endTime, value)) { - this.version++; - this._endTime = value; - } - return value; - }, - get_fadeSpan: function () { - return this._fadeSpan; - }, - set_fadeSpan: function (value) { - this.version++; - this._fadeSpan = value; - return value; - }, - get_fadeType: function () { - return this._fadeType; - }, - set_fadeType: function (value) { - if (this._fadeType !== value) { - this.set_version(this.get_version() + 1) - 1; - this._fadeType = value; - } - return value; - }, - get_version: function () { - return this.version; - }, - set_version: function (value) { - this.version = value; - return value; - }, - findClosest: function (target, distance, closestPlace, astronomical) { - return closestPlace; - }, - hoverCheckScreenSpace: function (cursor) { - return false; - }, - clickCheckScreenSpace: function (cursor) { - return false; - }, - draw: function (renderContext, opacity, flat) { - return true; - }, - preDraw: function (renderContext, opacity) { - return true; - }, - updateData: function (data, purgeOld, purgeAll, hasHeader) { - return true; - }, - upadteData: function (data, purgeOld, purgeAll, hasHeader) { - return this.updateData(data, purgeOld, purgeAll, hasHeader); - }, - canCopyToClipboard: function () { - return false; - }, - copyToClipboard: function () { - return; - }, - getParams: function () { - var paramList = new Array(5); - paramList[0] = this.color.r / 255; - paramList[1] = this.color.g / 255; - paramList[2] = this.color.b / 255; - paramList[3] = this.color.a / 255; - paramList[4] = this.opacity; - return paramList; - }, - setParams: function (paramList) { - if (paramList.length === 5) { - this.opacity = paramList[4]; - this.color = Color.fromArgb((paramList[3] * 255), (paramList[0] * 255), (paramList[1] * 255), (paramList[2] * 255)); - } - }, - getParamNames: function () { - return ['Color.Red', 'Color.Green', 'Color.Blue', 'Color.Alpha', 'Opacity']; - }, - getEditUI: function () { - return ss.safeCast(this, IUiController); - }, - cleanUp: function () { - }, - get_name: function () { - return this._name; - }, - set_name: function (value) { - if (this._name !== value) { - this.version++; - this._name = value; - } - return value; - }, - toString: function () { - return this._name; - }, - get_referenceFrame: function () { - return this.referenceFrame; - }, - set_referenceFrame: function (value) { - this.referenceFrame = value; - return value; - }, - getProps: function () { - return ''; - }, - get_color: function () { - return this.color; - }, - set_color: function (value) { - if (this.color !== value) { - this.color = value; - this.version++; - } - return value; - }, - colorChanged: function () { - }, - get_colorValue: function () { - return this.get_color().toString(); - }, - set_colorValue: function (value) { - this.set_color(Color.fromName(value)); - return value; - }, - get_enabled: function () { - return this.enabled; - }, - set_enabled: function (value) { - this.enabled = value; - return value; - }, - get_astronomical: function () { - return this.astronomical; - }, - set_astronomical: function (value) { - if (this.astronomical !== value) { - this.version++; - this.astronomical = value; - } - return value; - }, - getTypeName: function () { - return 'TerraViewer.Layer'; - }, - saveToXml: function (xmlWriter) { - xmlWriter._writeStartElement('Layer'); - xmlWriter._writeAttributeString('Id', this.id.toString()); - xmlWriter._writeAttributeString('Type', this.getTypeName()); - xmlWriter._writeAttributeString('Name', this.get_name()); - xmlWriter._writeAttributeString('ReferenceFrame', this.referenceFrame); - xmlWriter._writeAttributeString('Color', this.color.save()); - xmlWriter._writeAttributeString('Opacity', this.opacity.toString()); - xmlWriter._writeAttributeString('StartTime', Util.xmlDate(this.get_startTime())); - xmlWriter._writeAttributeString('EndTime', Util.xmlDate(this.get_endTime())); - xmlWriter._writeAttributeString('FadeSpan', this.get_fadeSpan().toString()); - xmlWriter._writeAttributeString('FadeType', this.get_fadeType().toString()); - this.writeLayerProperties(xmlWriter); - xmlWriter._writeEndElement(); - }, - writeLayerProperties: function (xmlWriter) { - return; - }, - initializeFromXml: function (node) { - }, - initFromXml: function (node) { - this.id = Guid.fromString(node.attributes.getNamedItem('Id').nodeValue); - this.set_name(node.attributes.getNamedItem('Name').nodeValue); - this.referenceFrame = node.attributes.getNamedItem('ReferenceFrame').nodeValue; - this.color = Color.load(node.attributes.getNamedItem('Color').nodeValue); - this.opacity = parseFloat(node.attributes.getNamedItem('Opacity').nodeValue); - if (node.attributes.getNamedItem('StartTime') != null) { - this.set_startTime(new Date(node.attributes.getNamedItem('StartTime').nodeValue)); - } - if (node.attributes.getNamedItem('EndTime') != null) { - this.set_endTime(new Date(node.attributes.getNamedItem('EndTime').nodeValue)); - } - if (node.attributes.getNamedItem('FadeSpan') != null) { - this.set_fadeSpan(Util.parseTimeSpan(node.attributes.getNamedItem('FadeSpan').nodeValue)); - } - if (node.attributes.getNamedItem('FadeType') != null) { - switch (node.attributes.getNamedItem('FadeType').nodeValue) { - case 'In': - this.set_fadeType(1); - break; - case 'Out': - this.set_fadeType(2); - break; - case 'Both': - this.set_fadeType(3); - break; - case 'None': - this.set_fadeType(4); - break; - default: - break; - } - } - this.initializeFromXml(node); - }, - loadData: function (doc, filename) { - return; - }, - addFilesToCabinet: function (fc) { - return; - }, - getStringFromGzipBlob: function (blob, dataReady) { - var reader = new FileReader(); - reader.onloadend = function (e) { - var result = ''; - try { - result = pako.inflate(e.target.result, { to: 'string' }); - } - catch (err) { - var errString = err.toString(); - if (errString === 'incorrect header check' || errString === 'unknown compression method') { - try { - result = String.fromCharCode.apply(null, new Uint8Array(e.target.result)); - } - catch (error) { - throw error; - } - } - else { - throw err; - } - } - dataReady(result); - }; - reader.readAsArrayBuffer(blob); - } - }; - - - // wwtlib.DomainValue - - function DomainValue(text, markerIndex) { - this.markerIndex = 4; - this.customMarker = null; - this.text = text; - this.markerIndex = markerIndex; - } - var DomainValue$ = { - - }; - - - // wwtlib.LayerManager - - function LayerManager() { - } - LayerManager.get_version = function () { - return LayerManager._version; - }; - LayerManager.set_version = function (value) { - LayerManager._version = value; - return value; - }; - LayerManager.get_frameWizardDialog = function () { - return LayerManager._frameWizardDialog; - }; - LayerManager.get_dataVizWizardDialog = function () { - return LayerManager._dataVizWizardDialog; - }; - LayerManager.get_referenceFramePropsDialog = function () { - return LayerManager._referenceFramePropsDialog; - }; - LayerManager.get_greatCircleDlg = function () { - return LayerManager._greatCircleDialog; - }; - LayerManager.get_tourLayers = function () { - return LayerManager._tourLayers; - }; - LayerManager.set_tourLayers = function (value) { - if (LayerManager._tourLayers !== value && !value) { - LayerManager._clearLayers(); - LayerManager._tourLayers = value; - LayerManager.loadTree(); - } - else if (LayerManager._tourLayers !== value && !!value) { - LayerManager._tourLayers = value; - LayerManager.initLayers(); - } - return value; - }; - LayerManager.loadTree = function () { - if (WWTControl.scriptInterface != null) { - WWTControl.scriptInterface.refreshLayerManagerNow(); - } - }; - LayerManager.get_layerMaps = function () { - if (LayerManager.get_tourLayers()) { - return LayerManager._layerMapsTours; - } - else { - return LayerManager._layerMaps; - } - }; - LayerManager.set_layerMaps = function (value) { - if (LayerManager.get_tourLayers()) { - LayerManager._layerMapsTours = value; - } - else { - LayerManager._layerMaps = value; - } - return value; - }; - LayerManager.get_allMaps = function () { - if (LayerManager.get_tourLayers()) { - return LayerManager._allMapsTours; - } - else { - return LayerManager._allMaps; - } - }; - LayerManager.set_allMaps = function (value) { - if (LayerManager.get_tourLayers()) { - LayerManager._allMapsTours = value; - } - else { - LayerManager._allMaps = value; - } - return value; - }; - LayerManager.get_currentMap = function () { - return LayerManager._currentMap; - }; - LayerManager.set_currentMap = function (value) { - LayerManager._currentMap = value; - return value; - }; - LayerManager.get_layerList = function () { - if (LayerManager.get_tourLayers()) { - return LayerManager._layerListTours; - } - else { - return LayerManager._layerList; - } - }; - LayerManager.set_layerList = function (value) { - if (LayerManager.get_tourLayers()) { - LayerManager._layerListTours = value; - } - else { - LayerManager._layerList = value; - } - return value; - }; - LayerManager.oneTimeInitialization = function () { - if (LayerManager._webFileMoons == null) { - LayerManager.getMoonFile(URLHelpers.singleton.engineAssetUrl('moons.txt')); - } - PushPin.triggerLoadSprite(); - }; - LayerManager.initLayers = function () { - LayerManager._clearLayers(); - var iss = null; - var doISS = !LayerManager.get_tourLayers() && !WWTControl.singleton.freestandingMode; - if (doISS) { - iss = new LayerMap('ISS', 18); - iss.frame.epoch = SpaceTimeController._twoLineDateToJulian('10184.51609218'); - iss.frame.semiMajorAxis = 6728829.41; - iss.frame.referenceFrameType = 1; - iss.frame.inclination = 51.6442; - iss.frame.longitudeOfAscendingNode = 147.0262; - iss.frame.eccentricity = 0.0009909; - iss.frame.meanAnomolyAtEpoch = 325.5563; - iss.frame.meanDailyMotion = 360 * 15.72172655; - iss.frame.argumentOfPeriapsis = 286.4623; - iss.frame.scale = 1; - iss.frame.semiMajorAxisUnits = 1; - iss.frame.meanRadius = 130; - iss.frame.oblateness = 0; - iss.frame.showOrbitPath = true; - var isstle = new Array(0); - var url = URLHelpers.singleton.coreDynamicUrl('wwtweb/isstle.aspx'); - var webFile; - webFile = new WebFile(url); - webFile.onStateChange = function () { - if (webFile.get_state() === 1) { - var data = webFile.getText(); - isstle = data.split('\n'); - if (isstle.length > 1) { - iss.frame.fromTLE(isstle[0], isstle[1], 398600441800000); - } - } - }; - webFile.send(); - iss.enabled = true; - } - LayerManager.get_layerMaps()['Sun'] = new LayerMap('Sun', 3); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Mercury', 4)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Venus', 5)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Earth', 6)); - LayerManager.get_layerMaps()['Sun'].childMaps['Earth'].addChild(new LayerMap('Moon', 13)); - if (doISS) { - LayerManager.get_layerMaps()['Sun'].childMaps['Earth'].addChild(iss); - } - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Mars', 7)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Jupiter', 8)); - LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Io', 14)); - LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Europa', 15)); - LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Ganymede', 16)); - LayerManager.get_layerMaps()['Sun'].childMaps['Jupiter'].addChild(new LayerMap('Callisto', 17)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Saturn', 9)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Uranus', 10)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Neptune', 11)); - LayerManager.get_layerMaps()['Sun'].addChild(new LayerMap('Pluto', 12)); - LayerManager._addMoons(LayerManager._moonfile); - LayerManager.get_layerMaps()['Sky'] = new LayerMap('Sky', 0); - LayerManager.get_layerMaps()['Sun'].open = true; - LayerManager._allMaps = {}; - LayerManager._addAllMaps(LayerManager.get_layerMaps(), null); - if (doISS) { - LayerManager._addIss(); - } - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._addIss = function () { - var layer = new ISSLayer(); - layer.set_name(Language.getLocalizedText(1314, 'ISS Model (Toshiyuki Takahei)')); - layer.enabled = Settings.get_active().get_showISSModel(); - LayerManager.get_layerList()[layer.id] = layer; - layer.set_referenceFrame('ISS'); - LayerManager.get_allMaps()['ISS'].layers.push(layer); - LayerManager.get_allMaps()['ISS'].open = true; - }; - LayerManager._addAllMaps = function (maps, parent) { - var $enum1 = ss.enumerate(ss.keys(maps)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var map = maps[key]; - map.frame.parent = parent; - LayerManager.get_allMaps()[map.get_name()] = map; - LayerManager._addAllMaps(map.childMaps, map.get_name()); - } - }; - LayerManager._clearLayers = function () { - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var layer = LayerManager.get_layerList()[key]; - layer.cleanUp(); - } - ss.clearKeys(LayerManager.get_layerList()); - ss.clearKeys(LayerManager.get_layerMaps()); - }; - LayerManager.getMoonFile = function (url) { - LayerManager._webFileMoons = new WebFile(url); - LayerManager._webFileMoons.onStateChange = LayerManager.moonFileStateChange; - LayerManager._webFileMoons.send(); - }; - LayerManager.moonFileStateChange = function () { - if (LayerManager._webFileMoons.get_state() === 2) { - alert(LayerManager._webFileMoons.get_message()); - } - else if (LayerManager._webFileMoons.get_state() === 1) { - LayerManager._moonfile = LayerManager._webFileMoons.getText(); - LayerManager.initLayers(); - } - }; - LayerManager._addMoons = function (file) { - var data = file.split('\r\n'); - var first = true; - var $enum1 = ss.enumerate(data); - while ($enum1.moveNext()) { - var line = $enum1.current; - if (first) { - first = false; - continue; - } - var parts = line.split('\t'); - if (parts.length > 16) { - var planet = parts[0]; - var frame = new LayerMap(parts[2], 18); - frame.frame._systemGenerated = true; - frame.frame.epoch = parseFloat(parts[1]); - frame.frame.semiMajorAxis = parseFloat(parts[3]) * 1000; - frame.frame.referenceFrameType = 1; - frame.frame.inclination = parseFloat(parts[7]); - frame.frame.longitudeOfAscendingNode = parseFloat(parts[8]); - frame.frame.eccentricity = parseFloat(parts[4]); - frame.frame.meanAnomolyAtEpoch = parseFloat(parts[6]); - frame.frame.meanDailyMotion = parseFloat(parts[9]); - frame.frame.argumentOfPeriapsis = parseFloat(parts[5]); - frame.frame.scale = 1; - frame.frame.semiMajorAxisUnits = 1; - frame.frame.meanRadius = parseFloat(parts[16]) * 1000; - frame.frame.rotationalPeriod = parseFloat(parts[17]); - frame.frame.showAsPoint = false; - frame.frame.showOrbitPath = true; - frame.frame.set_representativeColor(Color.fromArgb(255, 175, 216, 230)); - frame.frame.oblateness = 0; - LayerManager.get_layerMaps()['Sun'].childMaps[planet].addChild(frame); - } - } - }; - LayerManager.addVoTableLayer = function (table, title) { - return LayerManager.addVoTableLayerWithPlotType(table, title, 2); - }; - LayerManager.addVoTableLayerWithPlotType = function (table, title, plotType) { - var layer = VoTableLayer.create(table, plotType); - layer.set_name(title); - layer.set_astronomical(true); - layer.set_referenceFrame('Sky'); - LayerManager.get_layerList()[layer.id] = layer; - LayerManager.get_allMaps()['Sky'].layers.push(layer); - LayerManager.get_allMaps()['Sky'].open = true; - layer.enabled = true; - LayerManager._version++; - LayerManager.loadTree(); - return layer; - }; - LayerManager.addImageSetLayer = function (imageset, title) { - var layer = ImageSetLayer.create(imageset); - return LayerManager.addFitsImageSetLayer(layer, title); - }; - LayerManager.addImageSetLayerCallback = function (imageset, title, callback) { - var layer = ImageSetLayer.create(imageset); - var isNonHipsTiledFits = imageset.get_extension() === '.fits' && layer.getFitsImage() == null && imageset.get_projection() !== 7; - if (isNonHipsTiledFits) { - imageset.get_fitsProperties().onMainImageLoaded = function (image) { - image.applyDisplaySettings(); - if (callback != null) { - callback(layer); - } - }; - } - LayerManager.addFitsImageSetLayer(layer, title); - if (callback != null && (!isNonHipsTiledFits || imageset.get_fitsProperties().mainImageLoadedEventHasFired)) { - callback(layer); - } - return layer; - }; - LayerManager.addFitsImageSetLayer = function (layer, title) { - layer.doneLoading(null); - layer.set_name(title); - layer.set_astronomical(true); - layer.set_referenceFrame('Sky'); - LayerManager.get_layerList()[layer.id] = layer; - LayerManager.get_allMaps()['Sky'].layers.push(layer); - LayerManager.get_allMaps()['Sky'].open = true; - layer.enabled = true; - LayerManager._version++; - LayerManager.loadTree(); - return layer; - }; - LayerManager.getNextFitsName = function () { - return LayerManager._getNextName('Fits Image'); - }; - LayerManager.getNextImageSetName = function () { - return LayerManager._getNextName('Image Set'); - }; - LayerManager._getNextName = function (type) { - var currentNumber = 0; - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var $enum2 = ss.enumerate(LayerManager.get_allMaps()[key].layers); - while ($enum2.moveNext()) { - var layer = $enum2.current; - if (ss.startsWith(layer.get_name(), type + ' ')) { - var number = ss.replaceString(layer.get_name(), type + ' ', ''); - try { - var num = parseInt(number); - if (num > currentNumber) { - currentNumber = num; - } - } - catch ($e3) { - } - } - } - } - return ss.format('{0} {1}', type, currentNumber + 1); - }; - LayerManager._closeAllTourLoadedLayers = function () { - var purgeTargets = []; - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var layer = LayerManager.get_layerList()[key]; - if (layer.loadedFromTour) { - purgeTargets.push(layer.id); - } - } - var $enum2 = ss.enumerate(purgeTargets); - while ($enum2.moveNext()) { - var guid = $enum2.current; - LayerManager.deleteLayerByID(guid, true, false); - } - var purgeMapsNames = []; - var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); - while ($enum3.moveNext()) { - var key = $enum3.current; - var map = LayerManager.get_allMaps()[key]; - if (map.loadedFromTour && !map.layers.length) { - purgeMapsNames.push(map.get_name()); - } - } - var $enum4 = ss.enumerate(purgeMapsNames); - while ($enum4.moveNext()) { - var name = $enum4.current; - LayerManager.purgeLayerMapDeep(LayerManager.get_allMaps()[name], true); - } - LayerManager.set_version(LayerManager.get_version() + 1) - 1; - LayerManager.loadTree(); - }; - LayerManager.purgeLayerMapDeep = function (target, topLevel) { - var $enum1 = ss.enumerate(target.layers); - while ($enum1.moveNext()) { - var layer = $enum1.current; - LayerManager.deleteLayerByID(layer.id, false, false); - } - target.layers.length = 0; - var $enum2 = ss.enumerate(ss.keys(target.childMaps)); - while ($enum2.moveNext()) { - var key = $enum2.current; - var map = target.childMaps[key]; - LayerManager.purgeLayerMapDeep(map, false); - } - ss.clearKeys(target.childMaps); - if (topLevel) { - if (!ss.emptyString(target.frame.parent)) { - if (ss.keyExists(LayerManager.get_allMaps(), target.frame.parent)) { - delete LayerManager.get_allMaps()[target.frame.parent].childMaps[target.get_name()]; - } - } - else { - if (ss.keyExists(LayerManager.get_layerMaps(), target.get_name())) { - delete LayerManager.get_layerMaps()[target.get_name()]; - } - } - } - delete LayerManager.get_allMaps()[target.get_name()]; - LayerManager._version++; - }; - LayerManager._cleanAllTourLoadedLayers = function () { - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var layer = LayerManager.get_layerList()[key]; - if (layer.loadedFromTour) { - layer.loadedFromTour = false; - } - } - }; - LayerManager.mergeToursLayers = function () { - LayerManager._tourLayers = false; - var OverWrite = false; - var CollisionChecked = false; - var $enum1 = ss.enumerate(ss.keys(LayerManager._allMapsTours)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var map = LayerManager._allMapsTours[key]; - if (!ss.keyExists(LayerManager._allMaps, map.get_name())) { - var newMap = new LayerMap(map.get_name(), 18); - newMap.frame = map.frame; - newMap.loadedFromTour = true; - LayerManager.get_allMaps()[newMap.get_name()] = newMap; - } - } - LayerManager.connectAllChildren(); - var $enum2 = ss.enumerate(ss.keys(LayerManager._layerListTours)); - while ($enum2.moveNext()) { - var key = $enum2.current; - var layer = LayerManager._layerListTours[key]; - if (ss.keyExists(LayerManager.get_layerList(), layer.id)) { - if (!CollisionChecked) { - OverWrite = true; - CollisionChecked = true; - } - if (OverWrite) { - LayerManager.deleteLayerByID(layer.id, true, false); - } - } - if (!ss.keyExists(LayerManager.get_layerList(), layer.id)) { - if (ss.keyExists(LayerManager.get_allMaps(), layer.get_referenceFrame())) { - LayerManager.get_layerList()[layer.id] = layer; - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); - } - } - else { - layer.cleanUp(); - } - } - ss.clearKeys(LayerManager._layerListTours); - ss.clearKeys(LayerManager._allMapsTours); - ss.clearKeys(LayerManager._layerMapsTours); - LayerManager.loadTree(); - }; - LayerManager.connectAllChildren = function () { - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var map = LayerManager.get_allMaps()[key]; - if (ss.emptyString(map.frame.parent) && !ss.keyExists(LayerManager.get_layerMaps(), map.frame.name)) { - LayerManager.get_layerMaps()[map.get_name()] = map; - } - else if (!ss.emptyString(map.frame.parent) && ss.keyExists(LayerManager.get_allMaps(), map.frame.parent)) { - if (!ss.keyExists(LayerManager.get_allMaps()[map.frame.parent].childMaps, map.frame.name)) { - LayerManager.get_allMaps()[map.frame.parent].childMaps[map.frame.name] = map; - map.parent = LayerManager.get_allMaps()[map.frame.parent]; - } - } - } - }; - LayerManager.deleteLayerByID = function (ID, removeFromParent, updateTree) { - if (ss.keyExists(LayerManager.get_layerList(), ID)) { - var layer = LayerManager.get_layerList()[ID]; - layer.cleanUp(); - if (removeFromParent) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - } - delete LayerManager.get_layerList()[ID]; - LayerManager._version++; - if (updateTree) { - LayerManager.loadTree(); - } - return true; - } - else { - return false; - } - }; - LayerManager._getFrameTarget = function (renderContext, TrackingFrame) { - var target = new FrameTarget(); - var targetPoint = Vector3d.get_empty(); - target.target = Vector3d.get_empty(); - target.matrix = Matrix3d.get_identity(); - if (!ss.keyExists(LayerManager.get_allMaps(), TrackingFrame)) { - return target; - } - var mapList = []; - var current = LayerManager.get_allMaps()[TrackingFrame]; - mapList.push(current); - while (current.frame.reference === 18) { - current = current.parent; - mapList.splice(0, 0, current); - } - var matOld = renderContext.get_world().clone(); - var matOldNonRotating = renderContext.get_worldBaseNonRotating(); - var matOldBase = renderContext.get_worldBase(); - var oldNominalRadius = renderContext.get_nominalRadius(); - var $enum1 = ss.enumerate(mapList); - while ($enum1.moveNext()) { - var map = $enum1.current; - if (map.frame.reference !== 18 && map.frame.reference !== 20) { - Planets.setupPlanetMatrix(renderContext, Enums.parse('SolarSystemObjects', map.frame.name), Vector3d.get_empty(), false); - } - else { - map.computeFrame(renderContext); - if (map.frame.useRotatingParentFrame()) { - renderContext.set_world(Matrix3d.multiplyMatrix(map.frame.worldMatrix, renderContext.get_world())); - } - else { - renderContext.set_world(Matrix3d.multiplyMatrix(map.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); - } - if (map.frame.referenceFrameType === 3) { - renderContext.set_worldBaseNonRotating(renderContext.get_world().clone()); - } - renderContext.set_nominalRadius(map.frame.meanRadius); - } - } - targetPoint = renderContext.get_world().transform(targetPoint); - var lookAt = renderContext.get_world().transform(Vector3d.create(0, 0, 1)); - var lookUp = Vector3d.subtractVectors(renderContext.get_world().transform(Vector3d.create(0, 1, 0)), targetPoint); - lookUp.normalize(); - target.matrix = Matrix3d.lookAtLH(new Vector3d(), Vector3d.subtractVectors(lookAt, targetPoint), lookUp); - renderContext.set_nominalRadius(oldNominalRadius); - renderContext.set_world(matOld); - renderContext.set_worldBaseNonRotating(matOldNonRotating); - renderContext.set_worldBase(matOldBase); - target.target = targetPoint; - return target; - }; - LayerManager._prepTourLayers = function () { - if (TourPlayer.get_playing()) { - var player = WWTControl.singleton.uiController; - if (player != null) { - var tour = player.get_tour(); - if (tour.get_currentTourStop() != null) { - player.updateTweenPosition(-1); - if (!tour.get_currentTourStop().get_keyFramed()) { - tour.get_currentTourStop()._updateLayerOpacity(); - var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var info = tour.get_currentTourStop().layers[key]; - if (ss.keyExists(LayerManager.get_layerList(), info.id)) { - LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); - LayerManager.get_layerList()[info.id].setParams(info.frameParams); - } - } - } - } - } - } - }; - LayerManager._draw = function (renderContext, opacity, astronomical, referenceFrame, nested, cosmos) { - if (!ss.keyExists(LayerManager.get_allMaps(), referenceFrame)) { - return; - } - var thisMap = LayerManager.get_allMaps()[referenceFrame]; - if (!thisMap.enabled || (!ss.keyCount(thisMap.childMaps) && !thisMap.layers.length && !(thisMap.frame.showAsPoint || thisMap.frame.showOrbitPath))) { - return; - } - if (TourPlayer.get_playing()) { - var player = WWTControl.singleton.uiController; - if (player != null) { - var tour = player.get_tour(); - if (tour.get_currentTourStop() != null) { - player.updateTweenPosition(-1); - tour.get_currentTourStop()._updateLayerOpacity(); - var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var info = tour.get_currentTourStop().layers[key]; - if (ss.keyExists(LayerManager.get_layerList(), info.id)) { - LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); - LayerManager.get_layerList()[info.id].setParams(info.frameParams); - } - } - } - } - } - var matOld = renderContext.get_world(); - var matOldNonRotating = renderContext.get_worldBaseNonRotating(); - var oldNominalRadius = renderContext.get_nominalRadius(); - if ((thisMap.frame.reference === 18 | thisMap.frame.reference === 18) === 1) { - thisMap.computeFrame(renderContext); - if (thisMap.frame.referenceFrameType !== 1 && thisMap.frame.referenceFrameType !== 2) { - renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_world())); - } - else { - renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); - } - renderContext.set_nominalRadius(thisMap.frame.meanRadius); - } - if (thisMap.frame.showAsPoint) { - } - for (var pass = 0; pass < 2; pass++) { - var $enum2 = ss.enumerate(LayerManager.get_allMaps()[referenceFrame].layers); - while ($enum2.moveNext()) { - var layer = $enum2.current; - if ((!pass && ss.canCast(layer, ImageSetLayer)) || (pass === 1 && !(ss.canCast(layer, ImageSetLayer)))) { - var skipLayer = false; - if (!pass) { - skipLayer = !astronomical && (layer).get_overrideDefaultLayer(); - } - if (layer.enabled && !skipLayer) { - var layerStart = SpaceTimeController.utcToJulian(layer.get_startTime()); - var layerEnd = SpaceTimeController.utcToJulian(layer.get_endTime()); - var fadeIn = SpaceTimeController.utcToJulian(layer.get_startTime()) - ((layer.get_fadeType() === 1 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); - var fadeOut = SpaceTimeController.utcToJulian(layer.get_endTime()) + ((layer.get_fadeType() === 2 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); - if (SpaceTimeController.get_jNow() > fadeIn && SpaceTimeController.get_jNow() < fadeOut) { - var fadeOpacity = 1; - if (SpaceTimeController.get_jNow() < layerStart) { - fadeOpacity = ((SpaceTimeController.get_jNow() - fadeIn) / (layer.get_fadeSpan() / 864000000)); - } - if (SpaceTimeController.get_jNow() > layerEnd) { - fadeOpacity = ((fadeOut - SpaceTimeController.get_jNow()) / (layer.get_fadeSpan() / 864000000)); - } - layer.set_astronomical(astronomical); - if (ss.canCast(layer, SpreadSheetLayer)) { - var tsl = ss.safeCast(layer, SpreadSheetLayer); - tsl.draw(renderContext, opacity * fadeOpacity, cosmos); - } - else { - layer.draw(renderContext, opacity * fadeOpacity, cosmos); - } - } - } - } - } - } - if (nested) { - var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps()[referenceFrame].childMaps)); - while ($enum3.moveNext()) { - var key = $enum3.current; - var map = LayerManager.get_allMaps()[referenceFrame].childMaps[key]; - if (!(ss.canCast(map, LayerMap))) { - continue; - } - if (map.enabled && map.frame.showOrbitPath && Settings.get_active().get_solarSystemOrbits() && Settings.get_active().get_solarSystemMinorOrbits()) { - if (map.frame.referenceFrameType === 1) { - if (map.frame.get_orbit() == null) { - map.frame.set_orbit(new Orbit(map.frame.get_elements(), 360, map.frame.get_representativeColor(), 1, map.parent.frame.meanRadius)); - } - var matSaved = renderContext.get_world(); - renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); - map.frame.get_orbit().draw3D(renderContext, 1 * 0.5, Vector3d.create(0, 0, 0)); - renderContext.set_world(matSaved); - } - else if (map.frame.referenceFrameType === 2) { - } - } - if ((map.frame.reference === 18 || map.frame.reference === 19)) { - LayerManager._draw(renderContext, opacity, astronomical, map.get_name(), nested, cosmos); - } - } - } - renderContext.set_nominalRadius(oldNominalRadius); - renderContext.set_world(matOld); - renderContext.set_worldBaseNonRotating(matOldNonRotating); - }; - LayerManager._getVisibleLayerList = function (previous) { - var list = {}; - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var layer = LayerManager.get_layerList()[key]; - if (layer.enabled) { - var info = new LayerInfo(); - info.startOpacity = info.endOpacity = layer.get_opacity(); - info.id = layer.id; - info.startParams = layer.getParams(); - if (ss.keyExists(previous, info.id)) { - info.endOpacity = previous[info.id].endOpacity; - info.endParams = previous[info.id].endParams; - } - else { - info.endParams = layer.getParams(); - } - list[layer.id] = info; - } - } - return list; - }; - LayerManager.setVisibleLayerList = function (list) { - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_layerList())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var layer = LayerManager.get_layerList()[key]; - layer.enabled = ss.keyExists(list, layer.id); - try { - if (layer.enabled) { - layer.set_opacity(list[layer.id].frameOpacity); - layer.setParams(list[layer.id].frameParams); - } - } - catch ($e2) { - } - } - }; - LayerManager._preDraw = function (renderContext, opacity, astronomical, referenceFrame, nested) { - if (!ss.keyExists(LayerManager.get_allMaps(), referenceFrame)) { - return; - } - var thisMap = LayerManager.get_allMaps()[referenceFrame]; - if (!ss.keyCount(thisMap.childMaps) && !thisMap.layers.length) { - return; - } - if (TourPlayer.get_playing()) { - var player = ss.safeCast(WWTControl.singleton.uiController, TourPlayer); - if (player != null) { - var tour = player.get_tour(); - if (tour.get_currentTourStop() != null) { - player.updateTweenPosition(-1); - tour.get_currentTourStop()._updateLayerOpacity(); - var $enum1 = ss.enumerate(ss.keys(tour.get_currentTourStop().layers)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var info = tour.get_currentTourStop().layers[key]; - if (ss.keyExists(LayerManager.get_layerList(), info.id)) { - LayerManager.get_layerList()[info.id].set_opacity(info.frameOpacity); - LayerManager.get_layerList()[info.id].setParams(info.frameParams); - } - } - } - } - } - var matOld = renderContext.get_world(); - var matOldNonRotating = renderContext.get_worldBaseNonRotating(); - var oldNominalRadius = renderContext.get_nominalRadius(); - if (thisMap.frame.reference === 18) { - thisMap.computeFrame(renderContext); - if (thisMap.frame.referenceFrameType !== 1) { - renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_world())); - } - else { - renderContext.set_world(Matrix3d.multiplyMatrix(thisMap.frame.worldMatrix, renderContext.get_worldBaseNonRotating())); - } - renderContext.set_nominalRadius(thisMap.frame.meanRadius); - } - for (var pass = 0; pass < 2; pass++) { - var $enum2 = ss.enumerate(LayerManager.get_allMaps()[referenceFrame].layers); - while ($enum2.moveNext()) { - var layer = $enum2.current; - if ((!pass && ss.canCast(layer, ImageSetLayer)) || (pass === 1 && !(ss.canCast(layer, ImageSetLayer)))) { - if (layer.enabled) { - var layerStart = SpaceTimeController.utcToJulian(layer.get_startTime()); - var layerEnd = SpaceTimeController.utcToJulian(layer.get_endTime()); - var fadeIn = SpaceTimeController.utcToJulian(layer.get_startTime()) - ((layer.get_fadeType() === 1 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); - var fadeOut = SpaceTimeController.utcToJulian(layer.get_endTime()) + ((layer.get_fadeType() === 2 || layer.get_fadeType() === 3) ? (layer.get_fadeSpan() / 864000000) : 0); - if (SpaceTimeController.get_jNow() > fadeIn && SpaceTimeController.get_jNow() < fadeOut) { - var fadeOpacity = 1; - if (SpaceTimeController.get_jNow() < layerStart) { - fadeOpacity = ((SpaceTimeController.get_jNow() - fadeIn) / (layer.get_fadeSpan() / 864000000)); - } - if (SpaceTimeController.get_jNow() > layerEnd) { - fadeOpacity = ((fadeOut - SpaceTimeController.get_jNow()) / (layer.get_fadeSpan() / 864000000)); - } - if (!thisMap.frame.reference) { - layer.set_astronomical(true); - } - layer.preDraw(renderContext, opacity * fadeOpacity); - } - } - } - } - } - if (nested) { - var $enum3 = ss.enumerate(ss.keys(LayerManager.get_allMaps()[referenceFrame].childMaps)); - while ($enum3.moveNext()) { - var key = $enum3.current; - var map = LayerManager.get_allMaps()[referenceFrame].childMaps[key]; - if ((map.frame.reference === 18 || map.frame.reference === 19)) { - LayerManager._preDraw(renderContext, opacity, astronomical, map.get_name(), nested); - } - } - } - renderContext.set_nominalRadius(oldNominalRadius); - renderContext.set_world(matOld); - renderContext.set_worldBaseNonRotating(matOldNonRotating); - }; - LayerManager.add = function (layer, updateTree) { - if (!ss.keyExists(LayerManager.get_layerList(), layer.id)) { - if (ss.keyExists(LayerManager.get_allMaps(), layer.get_referenceFrame())) { - LayerManager.get_layerList()[layer.id] = layer; - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); - LayerManager._version++; - if (updateTree) { - LayerManager.loadTree(); - } - } - } - }; - LayerManager.layerSelectionChanged = function (selected) { - LayerManager._selectedLayer = selected; - if (LayerManager._selectedLayer != null) { - if (ss.canCast(LayerManager._selectedLayer, LayerMap)) { - var map = ss.safeCast(LayerManager._selectedLayer, LayerMap); - if (map != null) { - LayerManager.set_currentMap(map.get_name()); - } - } - else { - var layer = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); - if (layer != null && ss.canCast(layer.get_imageSet().get_wcsImage(), FitsImage)) { - return; - } - } - } - WWTControl.scriptInterface.setTimeSlider('left', ''); - WWTControl.scriptInterface.setTimeSlider('right', ''); - WWTControl.scriptInterface.setTimeSlider('title', Language.getLocalizedText(667, 'Time Scrubber')); - }; - LayerManager.setTimeSliderValue = function (pos) { - var layer = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); - if (layer != null && ss.canCast(layer.get_imageSet().get_wcsImage(), FitsImage)) { - } - }; - LayerManager.showLayerMenu = function (selected, x, y) { - LayerManager._lastMenuClick = Vector2d.create(x, y); - LayerManager._selectedLayer = selected; - if (ss.canCast(selected, LayerMap)) { - LayerManager.set_currentMap((selected).get_name()); - } - else if (ss.canCast(selected, Layer)) { - LayerManager.set_currentMap((selected).get_referenceFrame()); - } - if (((ss.canCast(selected, Layer)) && !(ss.canCast(selected, SkyOverlays)))) { - var selectedLayer = selected; - LayerManager._contextMenu = new ContextMenuStrip(); - var renameMenu = ToolStripMenuItem.create(Language.getLocalizedText(225, 'Rename')); - var Expand = ToolStripMenuItem.create(Language.getLocalizedText(981, 'Expand')); - var Collapse = ToolStripMenuItem.create(Language.getLocalizedText(982, 'Collapse')); - var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); - var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); - var saveMenu = ToolStripMenuItem.create(Language.getLocalizedText(960, 'Save...')); - var publishMenu = ToolStripMenuItem.create(Language.getLocalizedText(983, 'Publish to Community...')); - var colorMenu = ToolStripMenuItem.create(Language.getLocalizedText(458, 'Color/Opacity')); - var opacityMenu = ToolStripMenuItem.create(Language.getLocalizedText(305, 'Opacity')); - var propertiesMenu = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); - var scaleMenu = ToolStripMenuItem.create(Language.getLocalizedText(1291, 'Scale/Histogram')); - var lifeTimeMenu = ToolStripMenuItem.create(Language.getLocalizedText(683, 'Lifetime')); - var spacer1 = new ToolStripSeparator(); - var top = ToolStripMenuItem.create(Language.getLocalizedText(684, 'Move to Top')); - var up = ToolStripMenuItem.create(Language.getLocalizedText(685, 'Move Up')); - var down = ToolStripMenuItem.create(Language.getLocalizedText(686, 'Move Down')); - var bottom = ToolStripMenuItem.create(Language.getLocalizedText(687, 'Move to Bottom')); - var showViewer = ToolStripMenuItem.create(Language.getLocalizedText(957, 'VO Table Viewer')); - var spacer2 = new ToolStripSeparator(); - var defaultImageset = ToolStripMenuItem.create(Language.getLocalizedText(1294, 'Background Image Set')); - top.click = LayerManager._top_Click; - up.click = LayerManager._up_Click; - down.click = LayerManager._down_Click; - bottom.click = LayerManager._bottom_Click; - saveMenu.click = LayerManager._saveMenu_Click; - publishMenu.click = LayerManager._publishMenu_Click; - Expand.click = LayerManager._expand_Click; - Collapse.click = LayerManager._collapse_Click; - copyMenu.click = LayerManager._copyMenu_Click; - colorMenu.click = LayerManager._colorMenu_Click; - deleteMenu.click = LayerManager._deleteMenu_Click; - renameMenu.click = LayerManager._renameMenu_Click; - propertiesMenu.click = LayerManager._propertiesMenu_Click; - scaleMenu.click = LayerManager.scaleMenu_click; - defaultImageset.click = LayerManager._defaultImageset_Click; - opacityMenu.click = LayerManager._opacityMenu_Click; - lifeTimeMenu.click = LayerManager._lifeTimeMenu_Click; - showViewer.click = LayerManager._showViewer_Click; - LayerManager._contextMenu.items.push(renameMenu); - if (!selectedLayer.get_opened() && selectedLayer.getPrimaryUI() != null && selectedLayer.getPrimaryUI().get_hasTreeViewNodes()) { - LayerManager._contextMenu.items.push(Expand); - } - if (selectedLayer.get_opened()) { - LayerManager._contextMenu.items.push(Collapse); - } - if (selectedLayer.canCopyToClipboard()) { - } - LayerManager._contextMenu.items.push(deleteMenu); - LayerManager._contextMenu.items.push(spacer2); - LayerManager._contextMenu.items.push(colorMenu); - if (ss.canCast(selected, ImageSetLayer)) { - LayerManager._contextMenu.items.push(defaultImageset); - var isl = ss.safeCast(selected, ImageSetLayer); - defaultImageset.checked = isl.get_overrideDefaultLayer(); - } - if (ss.canCast(selected, SpreadSheetLayer) || ss.canCast(selected, GreatCirlceRouteLayer)) { - LayerManager._contextMenu.items.push(propertiesMenu); - } - if (ss.canCast(selected, VoTableLayer)) { - LayerManager._contextMenu.items.push(showViewer); - } - if (ss.canCast(selected, ImageSetLayer)) { - var isl = ss.safeCast(selected, ImageSetLayer); - LayerManager._contextMenu.items.push(scaleMenu); - } - if (LayerManager.get_allMaps()[selectedLayer.get_referenceFrame()].layers.length > 1) { - LayerManager._contextMenu.items.push(spacer1); - LayerManager._contextMenu.items.push(top); - LayerManager._contextMenu.items.push(up); - LayerManager._contextMenu.items.push(down); - LayerManager._contextMenu.items.push(bottom); - } - LayerManager._contextMenu._show(Vector2d.create(x, y)); - } - else if (ss.canCast(selected, LayerMap)) { - var map = ss.safeCast(selected, LayerMap); - var sandbox = map.frame.reference.toString() === 'Sandbox'; - var Dome = map.frame.name === 'Dome'; - var Sky = map.frame.name === 'Sky'; - if (Dome) { - return; - } - LayerManager._contextMenu = new ContextMenuStrip(); - var trackFrame = ToolStripMenuItem.create(Language.getLocalizedText(1298, 'Track this frame')); - var goTo = ToolStripMenuItem.create(Language.getLocalizedText(1299, 'Fly Here')); - var showOrbit = ToolStripMenuItem.create('Show Orbit'); - var newMenu = ToolStripMenuItem.create(Language.getLocalizedText(674, 'New Reference Frame')); - var newLayerGroupMenu = ToolStripMenuItem.create(Language.getLocalizedText(675, 'New Layer Group')); - var addMenu = ToolStripMenuItem.create(Language.getLocalizedText(166, 'Add')); - var newLight = ToolStripMenuItem.create('Add Light'); - var addFeedMenu = ToolStripMenuItem.create(Language.getLocalizedText(956, 'Add OData/table feed as Layer')); - var addWmsLayer = ToolStripMenuItem.create(Language.getLocalizedText(987, 'New WMS Layer')); - var addGridLayer = ToolStripMenuItem.create(Language.getLocalizedText(1300, 'New Lat/Lng Grid')); - var addGreatCircle = ToolStripMenuItem.create(Language.getLocalizedText(988, 'New Great Circle')); - var importTLE = ToolStripMenuItem.create(Language.getLocalizedText(989, 'Import Orbital Elements')); - var addMpc = ToolStripMenuItem.create(Language.getLocalizedText(1301, 'Add Minor Planet')); - var deleteFrameMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); - var addToTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1290, 'Add to Timeline')); - var addKeyframe = ToolStripMenuItem.create(Language.getLocalizedText(1280, 'Add Keyframe')); - var popertiesMenu = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); - var saveMenu = ToolStripMenuItem.create(Language.getLocalizedText(990, 'Save Layers')); - var publishLayers = ToolStripMenuItem.create(Language.getLocalizedText(991, 'Publish Layers to Community')); - var spacer1 = new ToolStripSeparator(); - var spacer0 = new ToolStripSeparator(); - var spacer2 = new ToolStripSeparator(); - var asReferenceFrame = ToolStripMenuItem.create('As Reference Frame'); - var asOrbitalLines = ToolStripMenuItem.create('As Orbital Line'); - trackFrame.click = LayerManager._trackFrame_Click; - goTo.click = LayerManager._goTo_Click; - asReferenceFrame.click = LayerManager._addMpc_Click; - asOrbitalLines.click = LayerManager._asOrbitalLines_Click; - addMpc.dropDownItems.push(asReferenceFrame); - addMpc.dropDownItems.push(asOrbitalLines); - addMenu.click = LayerManager._addMenu_Click; - newLayerGroupMenu.click = LayerManager._newLayerGroupMenu_Click; - pasteMenu.click = LayerManager._pasteLayer_Click; - newMenu.click = LayerManager._newMenu_Click; - deleteFrameMenu.click = LayerManager._deleteFrameMenu_Click; - popertiesMenu.click = LayerManager._framePropertiesMenu_Click; - addGreatCircle.click = LayerManager._addGreatCircle_Click; - addGridLayer.click = LayerManager._addGirdLayer_Click; - var convertToOrbit = ToolStripMenuItem.create('Extract Orbit Layer'); - if (map.frame.reference !== 19) { - if ((WWTControl.singleton.get_solarSystemMode() | WWTControl.singleton.sandboxMode) === 1) { - var spacerNeeded = false; - if (map.frame.reference !== 18 && !WWTControl.singleton.sandboxMode) { - if (!Sky) { - } - try { - var name = map.frame.reference.toString(); - if (name !== 'Sandbox') { - var ssObj = Enums.parse('SolarSystemObjects', name); - var id = ssObj; - var bit = Math.pow(2, id); - showOrbit.checked = !!(Settings.get_active().get_planetOrbitsFilter() & bit); - showOrbit.click = LayerManager._showOrbitPlanet_Click; - showOrbit.tag = bit.toString(); - } - } - catch ($e1) { - } - } - else { - if (!sandbox && !Sky) { - LayerManager._contextMenu.items.push(trackFrame); - spacerNeeded = true; - } - showOrbit.checked = map.frame.showOrbitPath; - showOrbit.click = LayerManager._showOrbit_Click; - } - if (spacerNeeded) { - LayerManager._contextMenu.items.push(spacer2); - } - if (!Sky && !sandbox) { - LayerManager._contextMenu.items.push(showOrbit); - LayerManager._contextMenu.items.push(spacer0); - } - if (map.frame.reference.toString() === 'Sandbox') { - LayerManager._contextMenu.items.push(newLight); - } - } - if (!Sky) { - LayerManager._contextMenu.items.push(newMenu); - } - } - if (!Sky) { - LayerManager._contextMenu.items.push(addGreatCircle); - LayerManager._contextMenu.items.push(addGridLayer); - } - if ((map.frame.reference !== 19 && map.frame.name === 'Sun') || (map.frame.reference === 19 && map.parent != null && map.parent.frame.name === 'Sun')) { - LayerManager._contextMenu.items.push(addMpc); - } - if (map.frame.reference === 18 && map.frame.referenceFrameType === 1 && map.parent != null && map.parent.frame.name === 'Sun') { - } - if (!Sky) { - } - LayerManager._contextMenu.items.push(pasteMenu); - if (map.frame.reference === 19) { - LayerManager._contextMenu.items.push(deleteFrameMenu); - } - if (map.frame.reference === 18) { - LayerManager._contextMenu.items.push(deleteFrameMenu); - LayerManager._contextMenu.items.push(popertiesMenu); - } - LayerManager._contextMenu.items.push(spacer1); - LayerManager._contextMenu._show(Vector2d.create(x, y)); - } - }; - LayerManager._publishMenu_Click = function (sender, e) { - }; - LayerManager._addGirdLayer_Click = function (sender, e) { - var layer = new GridLayer(); - layer.enabled = true; - layer.set_name('Lat-Lng Grid'); - LayerManager.get_layerList()[layer.id] = layer; - layer.set_referenceFrame(LayerManager._currentMap); - LayerManager.get_allMaps()[LayerManager._currentMap].layers.push(layer); - LayerManager.get_allMaps()[LayerManager._currentMap].open = true; - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._trackFrame_Click = function (sender, e) { - var target = LayerManager._selectedLayer; - WWTControl.singleton.renderContext.set_solarSystemTrack(20); - WWTControl.singleton.renderContext.set_trackingFrame(target.get_name()); - WWTControl.singleton.renderContext.viewCamera.zoom = WWTControl.singleton.renderContext.targetCamera.zoom = 1E-09; - }; - LayerManager._goTo_Click = function (sender, e) { - }; - LayerManager._saveMenu_Click = function (sender, e) { - }; - LayerManager._expand_Click = function (sender, e) { - }; - LayerManager._collapse_Click = function (sender, e) { - }; - LayerManager._copyMenu_Click = function (sender, e) { - if (LayerManager._selectedLayer != null && ss.canCast(LayerManager._selectedLayer, Layer)) { - var node = LayerManager._selectedLayer; - node.copyToClipboard(); - } - }; - LayerManager._newLayerGroupMenu_Click = function (sender, e) { - }; - LayerManager._importTLEFile = function (filename) { - }; - LayerManager._makeLayerGroupNow = function (name) { - var target = LayerManager._selectedLayer; - LayerManager._makeLayerGroup(name, target); - }; - LayerManager._makeLayerGroup = function (name, target) { - var frame = new ReferenceFrame(); - frame.name = name; - frame.reference = 19; - var newMap = new LayerMap(frame.name, 19); - newMap.frame = frame; - newMap.frame._systemGenerated = false; - target.addChild(newMap); - newMap.frame.parent = target.get_name(); - LayerManager.get_allMaps()[frame.name] = newMap; - LayerManager._version++; - }; - LayerManager._lifeTimeMenu_Click = function (sender, e) { - }; - LayerManager._deleteFrameMenu_Click = function (sender, e) { - }; - LayerManager._framePropertiesMenu_Click = function (sender, e) { - var target = LayerManager._selectedLayer; - LayerManager.get_referenceFramePropsDialog().show(target.frame, e); - }; - LayerManager._newMenu_Click = function (sender, e) { - var frame = new ReferenceFrame(); - LayerManager.get_frameWizardDialog().show(frame, e); - }; - LayerManager.referenceFrameWizardFinished = function (frame) { - var target = LayerManager._selectedLayer; - var newMap = new LayerMap(frame.name, 18); - if (!ss.keyExists(LayerManager.get_allMaps(), frame.name)) { - newMap.frame = frame; - target.addChild(newMap); - newMap.frame.parent = target.get_name(); - LayerManager.get_allMaps()[frame.name] = newMap; - LayerManager._version++; - LayerManager.loadTree(); - } - }; - LayerManager.pasteFromTle = function (lines, frame) { - var line1 = ''; - var line2 = ''; - for (var i = 0; i < lines.length; i++) { - lines[i] = ss.trim(lines[i]); - if (lines[i].length === 69 && ReferenceFrame.isTLECheckSumGood(lines[i])) { - if (!line1.length && lines[i].substring(0, 1) === '1') { - line1 = lines[i]; - } - if (!line2.length && lines[i].substring(0, 1) === '2') { - line2 = lines[i]; - } - } - } - if (line1.length === 69 && line2.length === 69) { - frame.fromTLE(line1, line2, 398600441800000); - return true; - } - return false; - }; - LayerManager._opacityMenu_Click = function (sender, e) { - }; - LayerManager._defaultImageset_Click = function (sender, e) { - var isl = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); - isl.set_overrideDefaultLayer(!isl.get_overrideDefaultLayer()); - }; - LayerManager._propertiesMenu_Click = function (sender, e) { - if (ss.canCast(LayerManager._selectedLayer, SpreadSheetLayer)) { - var target = LayerManager._selectedLayer; - LayerManager.get_dataVizWizardDialog().show(target, e); - } - if (ss.canCast(LayerManager._selectedLayer, GreatCirlceRouteLayer)) { - LayerManager.get_greatCircleDlg().show(LayerManager._selectedLayer, new ss.EventArgs()); - } - }; - LayerManager._renameMenu_Click = function (sender, e) { - var layer = LayerManager._selectedLayer; - var input = new SimpleInput(Language.getLocalizedText(225, 'Rename'), Language.getLocalizedText(228, 'New Name'), layer.get_name(), 32); - input.show(LayerManager._lastMenuClick, function () { - if (!ss.emptyString(input.text)) { - layer.set_name(input.text); - LayerManager._version++; - LayerManager.loadTree(); - } - }); - }; - LayerManager._colorMenu_Click = function (sender, e) { - var layer = LayerManager._selectedLayer; - var picker = new ColorPicker(); - if (layer.get_color() != null) { - picker.color = layer.get_color(); - } - picker.callBack = function () { - layer.set_color(picker.color); - }; - picker.show(e); - }; - LayerManager._addMenu_Click = function (sender, e) { - }; - LayerManager._deleteMenu_Click = function (sender, e) { - LayerManager._deleteSelectedLayer(); - }; - LayerManager._deleteSelectedLayer = function () { - if (LayerManager._selectedLayer != null && ss.canCast(LayerManager._selectedLayer, Layer)) { - var node = LayerManager._selectedLayer; - delete LayerManager.get_layerList()[node.id]; - ss.remove(LayerManager.get_allMaps()[LayerManager.get_currentMap()].layers, node); - node.cleanUp(); - node.set_version(node.get_version() + 1) - 1; - LayerManager.loadTree(); - LayerManager._version++; - } - }; - LayerManager.scaleMenu_click = function (sender, e) { - var isl = ss.safeCast(LayerManager._selectedLayer, ImageSetLayer); - if (isl != null) { - var hist = new Histogram(); - hist.image = isl.getFitsImage(); - hist.layer = isl; - hist.show(Vector2d.create(200, 200)); - } - }; - LayerManager._showViewer_Click = function (sender, e) { - if (ss.canCast(LayerManager._selectedLayer, VoTableLayer)) { - var layer = ss.safeCast(LayerManager._selectedLayer, VoTableLayer); - WWTControl.scriptInterface.displayVoTableLayer(layer); - } - }; - LayerManager._bottom_Click = function (sender, e) { - var layer = ss.safeCast(LayerManager._selectedLayer, Layer); - if (layer != null) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.push(layer); - } - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._down_Click = function (sender, e) { - var layer = ss.safeCast(LayerManager._selectedLayer, Layer); - if (layer != null) { - var index = LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.lastIndexOf(layer); - if (index < (LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.length - 1)) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(index + 1, 0, layer); - } - } - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._up_Click = function (sender, e) { - var layer = ss.safeCast(LayerManager._selectedLayer, Layer); - if (layer != null) { - var index = LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.lastIndexOf(layer); - if (index > 0) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(index - 1, 0, layer); - } - } - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._top_Click = function (sender, e) { - var layer = ss.safeCast(LayerManager._selectedLayer, Layer); - if (layer != null) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(0, 0, layer); - } - LayerManager._version++; - LayerManager.loadTree(); - }; - LayerManager._pasteLayer_Click = function (sender, e) { - LayerManager.get_dataVizWizardDialog().show(LayerManager.get_currentMap(), e); - }; - LayerManager.createSpreadsheetLayer = function (frame, name, data) { - var layer = new SpreadSheetLayer(); - layer.loadFromString(data, false, false, false, true); - layer.set_name(name); - LayerManager.addSpreadsheetLayer(layer, frame); - return layer; - }; - LayerManager.addSpreadsheetLayer = function (layer, frame) { - layer.enabled = true; - layer.set_referenceFrame(frame); - LayerManager.add(layer, true); - }; - LayerManager._showOrbitPlanet_Click = function (sender, e) { - try { - var bit = parseInt((sender).tag.toString()); - if (!(Settings.get_globalSettings().get_planetOrbitsFilter() & bit)) { - Settings.get_globalSettings().set_planetOrbitsFilter(Settings.get_globalSettings().get_planetOrbitsFilter() | bit); - } - else { - Settings.get_globalSettings().set_planetOrbitsFilter(Settings.get_globalSettings().get_planetOrbitsFilter() & ~bit); - } - } - catch ($e1) { - } - }; - LayerManager._showOrbit_Click = function (sender, e) { - var map = ss.safeCast(LayerManager._selectedLayer, LayerMap); - map.frame.showOrbitPath = !map.frame.showOrbitPath; - }; - LayerManager._addGreatCircle_Click = function (sender, e) { - LayerManager._addGreatCircleLayer(); - }; - LayerManager._addMpc_Click = function (sender, e) { - var target = LayerManager._selectedLayer; - var input = new SimpleInput(Language.getLocalizedText(1302, 'Minor planet name or designation'), Language.getLocalizedText(238, 'Name'), '', 32); - var retry = false; - do { - if (input.showDialog() === 1) { - if (ss.keyExists(target.childMaps, input.text)) { - retry = true; - } - else { - try { - LayerManager._getMpc(input.text, target); - retry = false; - } - catch ($e1) { - retry = true; - } - } - } - else { - retry = false; - } - } while (retry); - return; - }; - LayerManager._asOrbitalLines_Click = function (sender, e) { - var target = LayerManager._selectedLayer; - var input = new SimpleInput(Language.getLocalizedText(1302, 'Minor planet name or designation'), Language.getLocalizedText(238, 'Name'), '', 32); - input.show(Cursor.get_position(), function () { - if (ss.keyExists(target.childMaps, input.text)) { - } - else { - LayerManager._getMpcAsTLE(input.text, target); - } - }); - }; - LayerManager._getMpcAsTLE = function (id, target) { - var file = new WebFile('https://www.minorplanetcenter.net/db_search/show_object?object_id=' + id); - file.onStateChange = function () { - if (file.get_state() !== 1) { - return; - } - var data = file.getText(); - var startform = data.indexOf('show-orbit-button'); - var lastForm = data.indexOf('/form', startform); - var formpart = data.substring(startform, lastForm); - var name = id; - var frame = new ReferenceFrame(); - frame.oblateness = 0; - frame.showOrbitPath = true; - frame.showAsPoint = true; - frame.epoch = SpaceTimeController.utcToJulian(ss.date(LayerManager._getValueByID(formpart, 'epoch').substring(0, 10))); - frame.semiMajorAxis = parseFloat(LayerManager._getValueByID(formpart, 'a')) * 149598000 * 1000; - frame.referenceFrameType = 1; - frame.inclination = parseFloat(LayerManager._getValueByID(formpart, 'incl')); - frame.longitudeOfAscendingNode = parseFloat(LayerManager._getValueByID(formpart, 'node')); - frame.eccentricity = parseFloat(LayerManager._getValueByID(formpart, 'e')); - frame.meanAnomolyAtEpoch = parseFloat(LayerManager._getValueByID(formpart, 'm')); - frame.meanDailyMotion = ELL.meanMotionFromSemiMajorAxis(parseFloat(LayerManager._getValueByID(formpart, 'a'))); - frame.argumentOfPeriapsis = parseFloat(LayerManager._getValueByID(formpart, 'peri')); - frame.scale = 1; - frame.semiMajorAxisUnits = 1; - frame.meanRadius = 10; - frame.oblateness = 0; - var TLE = name + '\n' + frame.toTLE(); - LayerManager._loadOrbitsFile(id, TLE, target.get_name()); - LayerManager.loadTree(); - }; - file.send(); - }; - LayerManager._getMpc = function (id, target) { - var file = new WebFile('https://www.minorplanetcenter.net/db_search/show_object?object_id=' + id); - file.onStateChange = function () { - var data = file.getText(); - var startform = data.indexOf('show-orbit-button'); - var lastForm = data.indexOf('/form', startform); - var formpart = data.substring(startform, lastForm); - var name = id; - var orbit = new LayerMap(ss.trim(name), 18); - orbit.frame.oblateness = 0; - orbit.frame.showOrbitPath = true; - orbit.frame.showAsPoint = true; - orbit.frame.epoch = SpaceTimeController.utcToJulian(ss.date(LayerManager._getValueByID(formpart, 'epoch').substring(0, 10))); - orbit.frame.semiMajorAxis = parseFloat(LayerManager._getValueByID(formpart, 'a')) * 149598000 * 1000; - orbit.frame.referenceFrameType = 1; - orbit.frame.inclination = parseFloat(LayerManager._getValueByID(formpart, 'incl')); - orbit.frame.longitudeOfAscendingNode = parseFloat(LayerManager._getValueByID(formpart, 'node')); - orbit.frame.eccentricity = parseFloat(LayerManager._getValueByID(formpart, 'e')); - orbit.frame.meanAnomolyAtEpoch = parseFloat(LayerManager._getValueByID(formpart, 'm')); - orbit.frame.meanDailyMotion = ELL.meanMotionFromSemiMajorAxis(parseFloat(LayerManager._getValueByID(formpart, 'a'))); - orbit.frame.argumentOfPeriapsis = parseFloat(LayerManager._getValueByID(formpart, 'peri')); - orbit.frame.scale = 1; - orbit.frame.semiMajorAxisUnits = 1; - orbit.frame.meanRadius = 10; - orbit.frame.oblateness = 0; - if (!ss.keyExists(LayerManager.get_allMaps()[target.get_name()].childMaps, ss.trim(name))) { - LayerManager.get_allMaps()[target.get_name()].addChild(orbit); - } - LayerManager.get_allMaps()[orbit.get_name()] = orbit; - orbit.frame.parent = target.get_name(); - LayerManager._makeLayerGroup('Minor Planet', orbit); - LayerManager.loadTree(); - }; - }; - LayerManager._getValueByID = function (data, id) { - var valStart = data.indexOf('id="' + id + '"'); - valStart = data.indexOf('value=', valStart) + 7; - var valEnd = data.indexOf('"', valStart); - return data.substr(valStart, valEnd - valStart); - }; - LayerManager._addGreatCircleLayer = function () { - var layer = new GreatCirlceRouteLayer(); - var camera = WWTControl.singleton.renderContext.viewCamera; - layer.set_latStart(camera.lat); - layer.set_latEnd(camera.lat - 5); - layer.set_lngStart(camera.lng); - layer.set_lngEnd(camera.lng + 5); - layer.set_width(4); - layer.enabled = true; - layer.set_name(Language.getLocalizedText(1144, 'Great Circle Route')); - LayerManager.get_layerList()[layer.id] = layer; - layer.set_referenceFrame(LayerManager._currentMap); - LayerManager.get_allMaps()[LayerManager._currentMap].layers.push(layer); - LayerManager.get_allMaps()[LayerManager._currentMap].open = true; - LayerManager._version++; - LayerManager.loadTree(); - LayerManager.get_greatCircleDlg().show(layer, new ss.EventArgs()); - }; - LayerManager._loadOrbitsFile = function (name, data, currentMap) { - var layer = new OrbitLayer(); - layer.loadString(data); - layer.enabled = true; - layer.set_name(name); - LayerManager.get_layerList()[layer.id] = layer; - layer.set_referenceFrame(currentMap); - LayerManager.get_allMaps()[currentMap].layers.push(layer); - LayerManager.get_allMaps()[currentMap].open = true; - LayerManager._version++; - LayerManager.loadTree(); - return layer; - }; - var LayerManager$ = { - - }; - - - // wwtlib.LayerMap - - function LayerMap(name, reference) { - this.childMaps = {}; - this.parent = null; - this.layers = []; - this.open = false; - this.enabled = true; - this.loadedFromTour = false; - this.frame = new ReferenceFrame(); - this.set_name(name); - this.frame.reference = reference; - var radius = 6371000; - switch (reference) { - case 0: - break; - case 1: - break; - case 2: - break; - case 3: - radius = 696000000; - break; - case 4: - radius = 2439700; - break; - case 5: - radius = 6051800; - break; - case 6: - radius = 6371000; - break; - case 7: - radius = 3390000; - break; - case 8: - radius = 69911000; - break; - case 9: - radius = 58232000; - break; - case 10: - radius = 25362000; - break; - case 11: - radius = 24622000; - break; - case 12: - radius = 1161000; - break; - case 13: - radius = 1737100; - break; - case 14: - radius = 1821500; - break; - case 15: - radius = 1561000; - break; - case 16: - radius = 2631200; - break; - case 17: - radius = 2410300; - break; - case 18: - break; - case 19: - break; - default: - break; - } - this.frame.meanRadius = radius; - } - var LayerMap$ = { - addChild: function (child) { - child.parent = this; - this.childMaps[child.get_name()] = child; - }, - get_name: function () { - return this.frame.name; - }, - set_name: function (value) { - this.frame.name = value; - return value; - }, - computeFrame: function (renderContext) { - if (this.frame.reference === 18) { - this.frame.computeFrame(renderContext); - } - }, - toString: function () { - return this.get_name(); - } - }; - - - // wwtlib.SkyOverlays - - function SkyOverlays() { - } - var SkyOverlays$ = { - - }; - - - // wwtlib.GroundOverlayLayer - - function GroundOverlayLayer() { - } - var GroundOverlayLayer$ = { - - }; - - - // wwtlib.FrameTarget - - function FrameTarget() { - } - var FrameTarget$ = { - - }; - - - // wwtlib.LayerUI - - function LayerUI() { - } - var LayerUI$ = { - get_hasTreeViewNodes: function () { - return false; - }, - getTreeNodes: function () { - return null; - }, - getNodeContextMenu: function (node) { - return null; - }, - setUICallbacks: function (callbacks) { - } - }; - - - // wwtlib.LayerUIMenuItem - - function LayerUIMenuItem() { - this._tag = null; - this._isChecked = false; - this._isEnabled = true; - this._subMenus = null; - } - var LayerUIMenuItem$ = { - get_name: function () { - return this._name; - }, - set_name: function (value) { - this._name = value; - return value; - }, - get_tag: function () { - return this._tag; - }, - set_tag: function (value) { - this._tag = value; - return value; - }, - get_checked: function () { - return this._isChecked; - }, - set_checked: function (value) { - this._isChecked = value; - return value; - }, - get_enabled: function () { - return this._isEnabled; - }, - set_enabled: function (value) { - this._isEnabled = value; - return value; - }, - add_menuItemSelected: function (value) { - this.__menuItemSelected = ss.bindAdd(this.__menuItemSelected, value); - }, - remove_menuItemSelected: function (value) { - this.__menuItemSelected = ss.bindSub(this.__menuItemSelected, value); - }, - fireMenuItemSelected: function () { - if (this.__menuItemSelected != null) { - this.__menuItemSelected(this); - } - }, - get_subMenus: function () { - if (this._subMenus == null) { - this._subMenus = []; - } - return this._subMenus; - } - }; - - - // wwtlib.LayerUITreeNode - - function LayerUITreeNode() { - this._parent = null; - this._level = 0; - this._open = false; - this._isChecked = false; - this._bold = false; - this._color = Colors.get_white(); - this._nodes = null; - } - var LayerUITreeNode$ = { - add_nodeChecked: function (value) { - this.__nodeChecked = ss.bindAdd(this.__nodeChecked, value); - }, - remove_nodeChecked: function (value) { - this.__nodeChecked = ss.bindSub(this.__nodeChecked, value); - }, - fireNodeChecked: function (newState) { - if (this.__nodeChecked != null) { - this.__nodeChecked(this, newState); - } - }, - add_nodeUpdated: function (value) { - this.__nodeUpdated = ss.bindAdd(this.__nodeUpdated, value); - }, - remove_nodeUpdated: function (value) { - this.__nodeUpdated = ss.bindSub(this.__nodeUpdated, value); - }, - fireNodeUpdated: function () { - if (this.__nodeUpdated != null) { - this.__nodeUpdated(this); - } - }, - add_nodeSelected: function (value) { - this.__nodeSelected = ss.bindAdd(this.__nodeSelected, value); - }, - remove_nodeSelected: function (value) { - this.__nodeSelected = ss.bindSub(this.__nodeSelected, value); - }, - fireNodeSelected: function () { - if (this.__nodeSelected != null) { - this.__nodeSelected(this); - } - }, - add_nodeActivated: function (value) { - this.__nodeActivated = ss.bindAdd(this.__nodeActivated, value); - }, - remove_nodeActivated: function (value) { - this.__nodeActivated = ss.bindSub(this.__nodeActivated, value); - }, - fireNodeActivated: function () { - if (this.__nodeActivated != null) { - this.__nodeActivated(this); - } - }, - get_name: function () { - return this._name; - }, - set_name: function (value) { - if (this._name !== value) { - this._name = value; - this.fireNodeUpdated(); - } - return value; - }, - get_parent: function () { - return this._parent; - }, - set_parent: function (value) { - this._parent = value; - return value; - }, - get_level: function () { - return this._level; - }, - set_level: function (value) { - this._level = value; - return value; - }, - get_tag: function () { - return this._tag; - }, - set_tag: function (value) { - this._tag = value; - return value; - }, - get_referenceTag: function () { - return this._referenceTag; - }, - set_referenceTag: function (value) { - this._referenceTag = value; - return value; - }, - get_opened: function () { - return this._open; - }, - set_opened: function (value) { - if (this._open !== value) { - this._open = value; - this.fireNodeUpdated(); - } - return value; - }, - get_checked: function () { - return this._isChecked; - }, - set_checked: function (value) { - if (this._isChecked !== value) { - this._isChecked = value; - this.fireNodeUpdated(); - } - return value; - }, - get_bold: function () { - return this._bold; - }, - set_bold: function (value) { - if (this._bold !== value) { - this._bold = value; - this.fireNodeUpdated(); - } - return value; - }, - get_color: function () { - return this._color; - }, - set_color: function (value) { - if (this._color !== value) { - this._color = value; - this.fireNodeUpdated(); - } - return value; - }, - add: function (name) { - var node = new LayerUITreeNode(); - node.set_name(name); - node.set_parent(this); - node.set_level(this.get_level() + 1); - this.get_nodes().push(node); - return node; - }, - get_nodes: function () { - if (this._nodes == null) { - this._nodes = []; - } - return this._nodes; - } - }; - - - // wwtlib.Group - - function Group() { - this.startIndex = 0; - this.indexCount = 0; - this.materialIndex = 0; - } - var Group$ = { - - }; - - - // wwtlib.Mesh - - function Mesh() { - this.boundingSphere = new SphereHull(); - } - Mesh.create = function (vertices, indices) { - var mesh = new Mesh(); - mesh.vertices = vertices; - mesh.indices = indices; - var points = new Array(vertices.length); - for (var i = 0; i < vertices.length; ++i) { - points[i] = vertices[i].get_position(); - } - mesh.boundingSphere = ConvexHull.findEnclosingSphereFast(points); - return mesh; - }; - Mesh.createTangent = function (vertices, indices) { - var mesh = new Mesh(); - mesh.tangentVertices = vertices; - mesh.indices = indices; - var points = new Array(mesh.tangentVertices.length); - for (var i = 0; i < mesh.tangentVertices.length; ++i) { - points[i] = mesh.tangentVertices[i].get_position(); - } - mesh.boundingSphere = ConvexHull.findEnclosingSphereFast(points); - return mesh; - }; - var Mesh$ = { - dispose: function () { - if (this.vertexBuffer != null) { - this.vertexBuffer.dispose(); - this.vertexBuffer = null; - } - if (this.tangentVertexBuffer != null) { - this.tangentVertexBuffer.dispose(); - this.tangentVertexBuffer = null; - } - if (this.indexBuffer != null) { - this.indexBuffer.dispose(); - this.indexBuffer = null; - } - }, - setObjects: function (objects) { - this._objects = objects; - }, - commitToDevice: function () { - if (this.vertices != null) { - this.vertexBuffer = PositionNormalTexturedVertexBuffer.create(this.vertices); - } - else if (this.tangentVertices != null) { - this.tangentVertexBuffer = PositionNormalTexturedTangentVertexBuffer.create(this.tangentVertices); - } - this.indexBuffer = new IndexBuffer(new Uint32Array(this.indices)); - }, - beginDrawing: function (renderContext) { - if (this.vertexBuffer != null) { - renderContext._setVertexBuffer(this.vertexBuffer); - } - else if (this.tangentVertexBuffer != null) { - renderContext._setVertexBuffer(this.tangentVertexBuffer); - } - if (this.indexBuffer != null) { - renderContext._setIndexBuffer(this.indexBuffer); - } - }, - drawSubset: function (renderContext, materialIndex) { - if (this.indexBuffer == null || this._objects == null) { - return; - } - this.drawHierarchy(this._objects, materialIndex, renderContext, 0); - }, - drawHierarchy: function (nodes, materialIndex, renderContext, depth) { - if (depth > 1212) { - return; - } - var $enum1 = ss.enumerate(nodes); - while ($enum1.moveNext()) { - var node = $enum1.current; - if (node.drawGroup != null && node.enabled) { - var $enum2 = ss.enumerate(node.drawGroup); - while ($enum2.moveNext()) { - var group = $enum2.current; - if (group.materialIndex === materialIndex) { - renderContext.gl.drawElements(4, group.indexCount, 5125, group.startIndex * 4); - } - } - } - this.drawHierarchy(node.children, materialIndex, renderContext, depth + 1); - } - }, - get_objects: function () { - return this._objects; - }, - set_objects: function (value) { - this._objects = value; - return value; - } - }; - - - // wwtlib.VertexPosition - - function VertexPosition() { - this.index = 0; - } - var VertexPosition$ = { - - }; - - - // wwtlib.Object3d - - function Object3d(tourDoc, filename, flipV, flipHandedness, smooth, color) { - this.flipHandedness = false; - this.flipV = true; - this.smooth = true; - this._mesh = null; - this._meshMaterials = []; - this._meshTextures = []; - this._meshSpecularTextures = []; - this._meshNormalMaps = []; - this.meshFilenames = []; - this.color = Colors.get_white(); - this._textureCache = {}; - this._matFiles = new Array(0); - this._matFileIndex = 0; - this.objects = []; - this._matLib = {}; - this._textureLib = {}; - this._tourDocument = null; - this.issLayer = false; - this._readyToRender = false; - this.useCurrentAmbient = false; - this._dirty = true; - this.color = color; - this.smooth = smooth; - this.flipV = flipV; - this.flipHandedness = flipHandedness; - this.filename = filename; - if (ss.endsWith(this.filename.toLowerCase(), '.obj')) { - this._loadMeshFromObj(tourDoc, this.filename); - } - else { - this._loadMeshFrom3ds(tourDoc, this.filename, 1); - } - } - Object3d._compareVector3 = function (v0, v1) { - if (v0.x < v1.x) { - return -1; - } - else if (v0.x > v1.x) { - return 1; - } - else if (v0.y < v1.y) { - return -1; - } - else if (v0.y > v1.y) { - return 1; - } - else if (v0.z < v1.z) { - return -1; - } - else if (v0.z > v1.z) { - return 1; - } - else { - return 0; - } - }; - Object3d._compareVector = function (v0, v1) { - if (v0.x < v1.x) { - return -1; - } - else if (v0.x > v1.x) { - return 1; - } - else if (v0.y < v1.y) { - return -1; - } - else if (v0.y > v1.y) { - return 1; - } - else { - return 0; - } - }; - Object3d._getMaterialID = function (material, materialNames) { - var index = 0; - var $enum1 = ss.enumerate(materialNames); - while ($enum1.moveNext()) { - var mat = $enum1.current; - if (mat === material) { - return index; - } - index++; - } - return -1; - }; - Object3d._disposeTextureList = function (textures) { - if (textures != null) { - for (var i = 0; i < textures.length; ++i) { - if (textures[i] != null) { - textures[i].dispose(); - textures[i] = null; - } - } - textures.length = 0; - } - }; - var Object3d$ = { - _reload: function () { - if (!this.issLayer) { - this.dispose(); - if (ss.endsWith(this.filename.toLowerCase(), '.obj')) { - this._loadMeshFromObj(this._tourDocument, this.filename); - } - else { - this._loadMeshFrom3ds(this._tourDocument, this.filename, 1); - } - } - }, - _calculateVertexNormalsMerged: function (vertexList, indexList, creaseAngleRad) { - if (!vertexList.length) { - return null; - } - var vertexCount = vertexList.length; - var triangleCount = Math.floor(indexList.length / 3); - var vertexPositions = []; - for (var vertexIndex = 0; vertexIndex < vertexList.length; ++vertexIndex) { - var vp = new VertexPosition(); - vp.position = vertexList[vertexIndex].get_position(); - vp.index = vertexIndex; - vertexPositions.push(vp); - } - vertexPositions.sort(function (v0, v1) { - return Object3d._compareVector3(v0.position, v1.position); - }); - var vertexMap = new Array(vertexPositions.length); - var uniqueVertexCount = 0; - for (var vertexIndex = 0; vertexIndex < vertexPositions.length; vertexIndex++) { - if (!vertexIndex || !!Object3d._compareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position)) { - ++uniqueVertexCount; - } - vertexMap[vertexPositions[vertexIndex].index] = uniqueVertexCount - 1; - } - var vertexInstanceCounts = new Array(uniqueVertexCount); - for (var i = 0; i < uniqueVertexCount; i++) { - vertexInstanceCounts[i] = 0; - } - var $enum1 = ss.enumerate(indexList); - while ($enum1.moveNext()) { - var vertexIndex = $enum1.current; - var uniqueIndex = vertexMap[vertexIndex]; - vertexInstanceCounts[uniqueIndex]++; - } - var vertexInstances = new Array(uniqueVertexCount); - for (var i = 0; i < uniqueVertexCount; ++i) { - var count = vertexInstanceCounts[i]; - if (count > 0) { - vertexInstances[i] = new Array(count); - for (var j = 0; j < count; j++) { - vertexInstances[i][j] = 0; - } - } - } - for (var i = 0; i < indexList.length; ++i) { - var faceIndex = Math.floor(i / 3); - var uniqueIndex = vertexMap[indexList[i]]; - vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; - } - var faceNormals = new Array(triangleCount); - for (var i = 0; i < triangleCount; ++i) { - var i0 = indexList[i * 3 + 0]; - var i1 = indexList[i * 3 + 1]; - var i2 = indexList[i * 3 + 2]; - var edge0 = Vector3d.subtractVectors(vertexList[i1].get_position(), vertexList[i0].get_position()); - var edge1 = Vector3d.subtractVectors(vertexList[i2].get_position(), vertexList[i1].get_position()); - faceNormals[i] = Vector3d.cross(edge0, edge1); - faceNormals[i].normalize(); - } - var newVertexCount = triangleCount * 3; - var vertexNormals = new Array(newVertexCount); - var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); - for (var i = 0; i < newVertexCount; ++i) { - var vertexIndex = indexList[i]; - var uniqueIndex = vertexMap[vertexIndex]; - var faceNormal = faceNormals[Math.floor(i / 3)]; - var sum = new Vector3d(); - var $enum2 = ss.enumerate(vertexInstances[uniqueIndex]); - while ($enum2.moveNext()) { - var faceIndex = $enum2.current; - var n = faceNormals[faceIndex]; - if (Vector3d.dot(faceNormal, n) > cosCreaseAngle) { - sum.add(n); - } - } - vertexNormals[i] = sum; - vertexNormals[i].normalize(); - } - return vertexNormals; - }, - _calculateVertexTangents: function (vertexList, indexList, creaseAngleRad) { - if (!vertexList.length) { - return null; - } - var vertexCount = vertexList.length; - var triangleCount = Math.floor(indexList.length / 3); - var vertexPositions = []; - for (var vertexIndex = 0; vertexIndex < vertexList.length; ++vertexIndex) { - var vp = new VertexPosition(); - vp.position = vertexList[vertexIndex].get_position(); - vp.index = vertexIndex; - vertexPositions.push(vp); - } - vertexPositions.sort(function (v0, v1) { - return Object3d._compareVector3(v0.position, v1.position); - }); - var vertexMap = new Array(vertexPositions.length); - var uniqueVertexCount = 0; - for (var vertexIndex = 0; vertexIndex < vertexPositions.length; vertexIndex++) { - if (!vertexIndex || !!Object3d._compareVector3(vertexPositions[vertexIndex].position, vertexPositions[vertexIndex - 1].position)) { - ++uniqueVertexCount; - } - vertexMap[vertexPositions[vertexIndex].index] = (uniqueVertexCount - 1); - } - var vertexInstanceCounts = new Array(uniqueVertexCount); - for (var i = 0; i < uniqueVertexCount; i++) { - vertexInstanceCounts[i] = 0; - } - var $enum1 = ss.enumerate(indexList); - while ($enum1.moveNext()) { - var vertexIndex = $enum1.current; - var uniqueIndex = vertexMap[vertexIndex]; - vertexInstanceCounts[uniqueIndex]++; - } - var vertexInstances = new Array(uniqueVertexCount); - for (var i = 0; i < uniqueVertexCount; ++i) { - var count = vertexInstanceCounts[i]; - if (count > 0) { - vertexInstances[i] = new Array(count); - for (var j = 0; j < count; j++) { - vertexInstances[i][j] = 0; - } - } - } - for (var i = 0; i < indexList.length; ++i) { - var faceIndex = Math.floor(i / 3); - var uniqueIndex = vertexMap[indexList[i]]; - vertexInstances[uniqueIndex][--vertexInstanceCounts[uniqueIndex]] = faceIndex; - } - var partials = new Array(triangleCount); - for (var i = 0; i < triangleCount; ++i) { - var v0 = vertexList[indexList[i * 3 + 0]]; - var v1 = vertexList[indexList[i * 3 + 1]]; - var v2 = vertexList[indexList[i * 3 + 2]]; - var edge0 = Vector3d.subtractVectors(v1.get_position(), v0.get_position()); - var edge1 = Vector3d.subtractVectors(v2.get_position(), v0.get_position()); - var m00 = v1.tu - v0.tu; - var m01 = v1.tv - v0.tv; - var m10 = v2.tu - v0.tu; - var m11 = v2.tv - v0.tv; - var determinant = m00 * m11 - m01 * m10; - if (Math.abs(determinant) < 1E-06) { - if (edge0.lengthSq() > 0) { - partials[i] = edge0; - partials[i].normalize(); - } - else { - partials[i] = Vector3d.create(1, 0, 0); - } - } - else { - var invDeterminant = 1 / determinant; - var n00 = m11 * invDeterminant; - var n01 = -m01 * invDeterminant; - var n10 = -m10 * invDeterminant; - var n11 = m00 * invDeterminant; - partials[i] = Vector3d.addVectors(Vector3d.multiplyScalar(edge0, n00), Vector3d.multiplyScalar(edge1, n01)); - partials[i].normalize(); - } - } - var newVertexCount = triangleCount * 3; - var tangents = new Array(newVertexCount); - var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); - for (var i = 0; i < newVertexCount; ++i) { - var vertexIndex = indexList[i]; - var uniqueIndex = vertexMap[vertexIndex]; - var du = partials[Math.floor(i / 3)]; - var sum = new Vector3d(); - var $enum2 = ss.enumerate(vertexInstances[uniqueIndex]); - while ($enum2.moveNext()) { - var faceIndex = $enum2.current; - var T = partials[faceIndex]; - if (Vector3d.dot(du, T) > cosCreaseAngle) { - sum.add(T); - } - } - var N = vertexList[vertexIndex].get_normal(); - tangents[i] = Vector3d.subtractVectors(sum, Vector3d.multiplyScalar(N, Vector3d.dot(N, sum))); - tangents[i].normalize(); - } - return tangents; - }, - _calculateVertexNormals: function (vertexList, indexList, creaseAngleRad) { - var vertexCount = vertexList.length; - var triangleCount = Math.floor(indexList.length / 3); - var vertexInstanceCounts = new Array(vertexCount); - var $enum1 = ss.enumerate(indexList); - while ($enum1.moveNext()) { - var vertexIndex = $enum1.current; - vertexInstanceCounts[vertexIndex]++; - } - var vertexInstances = new Array(vertexCount); - for (var i = 0; i < vertexCount; ++i) { - var count = vertexInstanceCounts[i]; - if (count > 0) { - vertexInstances[i] = new Array(count); - } - } - for (var i = 0; i < indexList.length; ++i) { - var faceIndex = Math.floor(i / 3); - var vertexIndex = indexList[i]; - vertexInstances[vertexIndex][--vertexInstanceCounts[vertexIndex]] = faceIndex; - } - var faceNormals = new Array(triangleCount); - for (var i = 0; i < triangleCount; ++i) { - var i0 = indexList[i * 3 + 0]; - var i1 = indexList[i * 3 + 1]; - var i2 = indexList[i * 3 + 2]; - var edge0 = Vector3d.subtractVectors(vertexList[i1].get_position(), vertexList[i0].get_position()); - var edge1 = Vector3d.subtractVectors(vertexList[i2].get_position(), vertexList[i1].get_position()); - faceNormals[i] = Vector3d.cross(edge0, edge1); - faceNormals[i].normalize(); - } - var newVertexCount = triangleCount * 3; - var vertexNormals = new Array(newVertexCount); - var cosCreaseAngle = Math.min(0.9999, Math.cos(creaseAngleRad)); - for (var i = 0; i < newVertexCount; ++i) { - var vertexIndex = indexList[i]; - var faceNormal = faceNormals[Math.floor(i / 3)]; - var sum = new Vector3d(); - var $enum2 = ss.enumerate(vertexInstances[vertexIndex]); - while ($enum2.moveNext()) { - var faceIndex = $enum2.current; - var n = faceNormals[faceIndex]; - if (Vector3d.dot(faceNormal, n) > cosCreaseAngle) { - sum.add(n); - } - } - vertexNormals[i] = sum; - vertexNormals[i].normalize(); - } - return vertexNormals; - }, - _addMaterial: function (material) { - this._meshMaterials.push(material); - while (this._meshTextures.length < this._meshMaterials.length) { - this._meshTextures.push(null); - } - while (this._meshSpecularTextures.length < this._meshMaterials.length) { - this._meshSpecularTextures.push(null); - } - while (this._meshNormalMaps.length < this._meshMaterials.length) { - this._meshNormalMaps.push(null); - } - }, - _loadColorChunk: function (br) { - var chunkID = br.readUInt16(); - var chunkLength = br.readUInt32(); - var color = Colors.get_black(); - if ((chunkID === 16 || chunkID === 19) && chunkLength === 18) { - var r = Math.max(0, Math.min(1, br.readSingle())); - var g = Math.max(0, Math.min(1, br.readSingle())); - var b = Math.max(0, Math.min(1, br.readSingle())); - color = Color.fromArgb(255, ss.truncate((255 * r)), ss.truncate((255 * g)), ss.truncate((255 * b))); - } - else if ((chunkID === 17 || chunkID === 18) && chunkLength === 9) { - color = Color.fromArgb(255, br.readByte(), br.readByte(), br.readByte()); - } - else { - br.readBytes(chunkLength - 6); - } - return color; - }, - _loadPercentageChunk: function (br) { - var chunkID = br.readUInt16(); - var chunkLength = br.readUInt32(); - var percentage = 0; - if (chunkID === 48 && chunkLength === 8) { - percentage = br.readUInt16(); - } - else if (chunkID === 49 && chunkLength === 10) { - percentage = br.readSingle(); - } - else { - br.readBytes(chunkLength - 6); - } - return percentage; - }, - _loadMeshFromObj: function (doc, filename) { - var $this = this; - - this.filename = filename; - this._tourDocument = doc; - var blob = doc.getFileBlob(filename); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - $this._matFiles = $this._readObjMaterialsFromBin(ss.safeCast(chunck.result, String)); - $this._matFileIndex = 0; - $this._loadMatLib(ss.safeCast(chunck.result, String)); - }; - chunck.readAsText(blob); - }, - _readObjMaterialsFromBin: function (data) { - var matFiles = []; - var lines = data.split('\n'); - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var lineraw = $enum1.current; - var line = ss.replaceString(lineraw, ' ', ' '); - var parts = ss.trim(line).split(' '); - if (parts.length > 0) { - switch (parts[0]) { - case 'mtllib': - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - var matFile = path + parts[1]; - matFiles.push(matFile); - break; - } - } - } - return matFiles; - }, - _readObjFromBin: function (data) { - var objectFound = false; - var objects = []; - var currentObject = new ObjectNode(); - currentObject.name = 'Default'; - var triangleCount = 0; - var vertexCount = 0; - var vertexList = []; - var vertList = []; - var normList = []; - var uvList = []; - vertList.push(new Vector3d()); - normList.push(new Vector3d()); - uvList.push(new Vector2d()); - var indexList = []; - var attribList = []; - var applyLists = []; - var applyListsIndex = []; - var materialNames = []; - var currentMaterialIndex = -1; - var currentMaterial = new Material(); - var currentGroup = new Group(); - var currentIndex = 0; - currentMaterial = new Material(); - currentMaterial.diffuse = this.color; - currentMaterial.ambient = this.color; - currentMaterial.specular = Colors.get_white(); - currentMaterial.specularSharpness = 30; - currentMaterial.opacity = 1; - currentMaterial.isDefault = true; - currentGroup.startIndex = 0; - currentGroup.indexCount = 0; - currentGroup.materialIndex = 0; - var lines = data.split('\n'); - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var lineraw = $enum1.current; - var line = ss.replaceString(lineraw, ' ', ' '); - var parts = ss.trim(line).split(' '); - if (parts.length > 0) { - switch (parts[0]) { - case 'mtllib': - break; - case 'usemtl': - var materialName = parts[1]; - if (ss.keyExists(this._matLib, materialName)) { - if (currentMaterialIndex === -1 && currentIndex > 0) { - this._addMaterial(currentMaterial); - currentMaterialIndex++; - } - if (currentMaterialIndex > -1) { - currentGroup.indexCount = currentIndex - currentGroup.startIndex; - currentObject.drawGroup.push(currentGroup); - } - currentMaterialIndex++; - if (ss.keyExists(this._matLib, materialName)) { - currentMaterial = this._matLib[materialName]; - if (ss.keyExists(this._textureLib, materialName)) { - try { - if (!ss.keyExists(this._textureCache, this._textureLib[materialName])) { - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - var tex = this._tourDocument.getCachedTexture2d(path + this._textureLib[materialName]); - if (tex != null) { - this.meshFilenames.push(this._textureLib[materialName]); - this._textureCache[this._textureLib[materialName]] = tex; - } - } - this._meshTextures.push(this._textureCache[this._textureLib[materialName]]); - } - catch ($e2) { - } - } - this._addMaterial(currentMaterial); - currentGroup = new Group(); - currentGroup.startIndex = currentIndex; - currentGroup.indexCount = 0; - currentGroup.materialIndex = currentMaterialIndex; - } - } - break; - case 'v': - vertexCount++; - if (this.flipHandedness) { - vertList.push(Vector3d.create(-parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); - } - else { - vertList.push(Vector3d.create(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); - } - break; - case 'vn': - if (this.flipHandedness) { - normList.push(Vector3d.create(-parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); - } - else { - normList.push(Vector3d.create(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]))); - } - break; - case 'vt': - uvList.push(Vector2d.create(parseFloat(parts[1]), (this.flipV) ? (1 - parseFloat(parts[2])) : parseFloat(parts[2]))); - break; - case 'g': - case 'o': - if (objectFound) { - if (currentMaterialIndex > -1) { - currentGroup.indexCount = currentIndex - currentGroup.startIndex; - currentObject.drawGroup.push(currentGroup); - currentGroup = new Group(); - currentGroup.startIndex = currentIndex; - currentGroup.indexCount = 0; - currentGroup.materialIndex = currentMaterialIndex; - } - currentObject = new ObjectNode(); - } - objectFound = true; - if (parts.length > 1) { - currentObject.name = parts[1]; - } - else { - currentObject.name = 'Unnamed'; - } - objects.push(currentObject); - break; - case 'f': - var indexiesA = this._getIndexies(parts[1]); - var indexiesB = this._getIndexies(parts[2]); - var indexiesC = this._getIndexies(parts[3]); - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); - if (this.flipHandedness) { - indexList.push(currentIndex); - indexList.push(currentIndex + 2); - indexList.push(currentIndex + 1); - } - else { - indexList.push(currentIndex); - indexList.push(currentIndex + 1); - indexList.push(currentIndex + 2); - } - triangleCount++; - currentIndex += 3; - if (parts.length > 4) { - var partIndex = 4; - while (partIndex < parts.length) { - if (this.flipHandedness) { - indexiesA = this._getIndexies(parts[1]); - indexiesC = this._getIndexies(parts[partIndex]); - indexiesB = this._getIndexies(parts[partIndex - 1]); - } - else { - indexiesA = this._getIndexies(parts[1]); - indexiesB = this._getIndexies(parts[partIndex - 1]); - indexiesC = this._getIndexies(parts[partIndex]); - } - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesA[0]], normList[indexiesA[2]], uvList[indexiesA[1]])); - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesB[0]], normList[indexiesB[2]], uvList[indexiesB[1]])); - vertexList.push(PositionNormalTextured.createUV(vertList[indexiesC[0]], normList[indexiesC[2]], uvList[indexiesC[1]])); - indexList.push(currentIndex); - indexList.push(currentIndex + 1); - indexList.push(currentIndex + 2); - triangleCount++; - currentIndex += 3; - partIndex++; - } - } - break; - } - } - } - if (!objectFound) { - objects.push(currentObject); - } - if (currentMaterialIndex === -1 && currentIndex > 0) { - this._addMaterial(currentMaterial); - currentMaterialIndex++; - } - if (currentMaterialIndex > -1) { - currentGroup.indexCount = (currentIndex - currentGroup.startIndex); - currentObject.drawGroup.push(currentGroup); - } - if (normList.length < 2) { - var degtorag = Math.PI / 180; - var creaseAngleRad = ((this.smooth) ? 170 * degtorag : 45 * degtorag); - var vertexNormals = this._calculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); - var newVertexList = []; - var newVertexCount = indexList.length; - for (var vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) { - var v = vertexList[indexList[vertexIndex]]; - v.set_normal(vertexNormals[vertexIndex]); - newVertexList.push(v); - } - vertexList = newVertexList; - } - this._mesh = Mesh.create(vertexList, indexList); - var rootDummy = new ObjectNode(); - rootDummy.name = 'Root'; - rootDummy.parent = null; - rootDummy.level = -1; - rootDummy.drawGroup = null; - rootDummy.children = objects; - this.objects = []; - this.objects.push(rootDummy); - this._mesh.setObjects(this.objects); - this._mesh.commitToDevice(); - this._dirty = false; - this._readyToRender = true; - }, - _loadMatLib: function (data) { - var $this = this; - - if (this._matFileIndex < this._matFiles.length) { - var filename = this._matFiles[this._matFileIndex++]; - var blob = this._tourDocument.getFileBlob(filename); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - $this._readMatLibFromBin(ss.safeCast(chunck.result, String)); - $this._loadMatLib(data); - }; - chunck.readAsText(blob); - } - else { - this._readObjFromBin(data); - } - }, - _readMatLibFromBin: function (data) { - try { - var currentMaterial = new Material(); - var materialName = ''; - this._matLib = {}; - this._textureLib = {}; - var lines = data.split('\n'); - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var lineraw = $enum1.current; - var line = lineraw; - var parts = ss.trim(line).split(' '); - if (parts.length > 0) { - switch (parts[0]) { - case 'newmtl': - if (!ss.emptyString(materialName)) { - this._matLib[materialName] = currentMaterial; - } - currentMaterial = new Material(); - currentMaterial.diffuse = Colors.get_white(); - currentMaterial.ambient = Colors.get_white(); - currentMaterial.specular = Colors.get_black(); - currentMaterial.specularSharpness = 30; - currentMaterial.opacity = 1; - materialName = parts[1]; - break; - case 'Ka': - currentMaterial.ambient = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); - break; - case 'map_Kd': - currentMaterial.diffuse = Colors.get_white(); - var textureFilename = parts[1]; - for (var i = 2; i < parts.length; i++) { - textureFilename += ' ' + parts[i]; - } - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - textureFilename = ss.replaceString(textureFilename, '/', '\\'); - if (textureFilename.indexOf('\\') !== -1) { - textureFilename = textureFilename.substring(textureFilename.lastIndexOf('\\') + 1); - } - this._textureLib[materialName] = textureFilename; - break; - case 'Kd': - currentMaterial.diffuse = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); - break; - case 'Ks': - currentMaterial.specular = Color.fromArgb(255, Math.min(parseFloat(parts[1]) * 255, 255), Math.min(parseFloat(parts[2]) * 255, 255), Math.min(parseFloat(parts[3]) * 255, 255)); - break; - case 'd': - currentMaterial.opacity = parseFloat(parts[1]); - break; - case 'Tr': - currentMaterial.opacity = 1 - parseFloat(parts[1]); - break; - case 'illum': - var illuminationMode = parseInt(parts[1]); - break; - case 'sharpness': - currentMaterial.specularSharpness = parseFloat(parts[1]); - break; - case 'Ns': - currentMaterial.specularSharpness = 1 + 2 * parseFloat(parts[1]); - currentMaterial.specularSharpness = Math.max(10, currentMaterial.specularSharpness); - break; - } - } - } - if (!ss.emptyString(materialName)) { - this._matLib[materialName] = currentMaterial; - } - } - catch ($e2) { - } - }, - _getIndexies: function (data) { - var parts = ss.trim(data).split('/'); - var indecies = new Array(3); - if (ss.emptyString(data)) { - return indecies; - } - if (parts.length > 0) { - indecies[0] = parseInt(parts[0]); - } - if (parts.length > 1) { - if (ss.emptyString(parts[1])) { - indecies[1] = 0; - } - else { - indecies[1] = parseInt(parts[1]); - } - } - if (parts.length > 2) { - indecies[2] = parseInt(parts[2]); - } - return indecies; - }, - _loadMeshFrom3ds: function (doc, filename, scale) { - var $this = this; - - this._tourDocument = doc; - var blob = doc.getFileBlob(filename); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - $this._read3dsFromBin(new BinaryReader(new Uint8Array(chunck.result)), scale); - }; - chunck.readAsArrayBuffer(blob); - }, - _read3dsFromBin: function (br, scale) { - var i; - var sectionID; - var sectionLength; - var name = ''; - var material = ''; - var triangleCount = 0; - var vertexCount = 0; - var vertexList = []; - var indexList = []; - var attribList = []; - var materialNames = []; - var currentMaterialIndex = -1; - var currentMaterial = new Material(); - var attributeID = 0; - var count = 0; - var lastID = 0; - var exit = false; - var normalMapFound = false; - var offsetX = 0; - var offsetY = 0; - var offsetZ = 0; - var objects = []; - var currentObject = null; - var objHierarchy = []; - var objNames = []; - var objectTable = {}; - var dummyCount = 0; - var length = br.get_length() - 1; - var startMapIndex = 0; - var startTriangleIndex = 0; - while (br.get_position() < length && !exit) { - sectionID = br.readUInt16(); - sectionLength = br.readUInt32(); - switch (sectionID) { - case 19789: - break; - case 15677: - break; - case 16384: - name = ''; - var b; - do { - b = br.readByte(); - if (b > 0) { - name += String.fromCharCode(b); - } - } while (!!b); - currentObject = new ObjectNode(); - currentObject.name = name; - objects.push(currentObject); - if (!ss.keyExists(objectTable, currentObject.name)) { - objectTable[currentObject.name] = currentObject; - } - break; - case 16640: - startMapIndex = vertexList.length; - startTriangleIndex = Math.floor(indexList.length / 3); - break; - case 16656: - vertexCount = br.readUInt16(); - for (i = 0; i < vertexCount; i++) { - var x = br.readSingle() - offsetX; - var y = br.readSingle() - offsetY; - var z = br.readSingle() - offsetZ; - var vert = PositionNormalTextured._create(x * scale, z * scale, y * scale, 0, 0, 0, 0, 0); - vertexList.push(vert); - } - break; - case 16672: - var triCount = br.readUInt16(); - triangleCount += triCount; - for (i = 0; i < triCount; i++) { - var aa = br.readUInt16() + startMapIndex; - var bb = br.readUInt16() + startMapIndex; - var cc = br.readUInt16() + startMapIndex; - indexList.push(cc); - indexList.push(bb); - indexList.push(aa); - var flags = br.readUInt16(); - } - break; - case 16688: - material = ''; - i = 0; - var b1; - do { - b1 = br.readByte(); - if (b1 > 0) { - material += String.fromCharCode(b1); - } - i++; - } while (!!b1); - var triCount = br.readUInt16(); - var applyList = new Array(triCount); - attributeID = Object3d._getMaterialID(material, materialNames); - for (i = 0; i < triCount; i++) { - applyList[i] = br.readUInt16() + startTriangleIndex; - } - currentObject.applyLists.push(applyList); - currentObject.applyListsIndex.push(attributeID); - break; - case 16704: - count = br.readUInt16(); - for (i = 0; i < count; i++) { - var vert = vertexList[startMapIndex + i]; - var texCoord = Vector2d.create(br.readSingle(), (this.flipV) ? (1 - br.readSingle()) : br.readSingle()); - vertexList[startMapIndex + i] = PositionNormalTextured.createUV(vert.get_position(), new Vector3d(), texCoord); - } - break; - case 16736: - var mat = new Array(12); - for (i = 0; i < 12; i++) { - mat[i] = br.readSingle(); - } - if (ss.keyExists(objectTable, name)) { - objectTable[name].localMat = Matrix3d.create(mat[0], mat[1], mat[2], 0, mat[3], mat[4], mat[5], 0, mat[6], mat[7], mat[8], 0, mat[9], mat[10], mat[11], 1); - objectTable[name].localMat.invert(); - } - break; - case 45055: - break; - case 40960: - var matName = ''; - i = 0; - var b2; - do { - b2 = br.readByte(); - if (b2 > 0) { - matName += String.fromCharCode(b2); - } - i++; - } while (!!b2); - materialNames.push(matName); - if (currentMaterialIndex > -1) { - this._addMaterial(currentMaterial); - } - currentMaterialIndex++; - currentMaterial = new Material(); - currentMaterial.diffuse = Colors.get_white(); - currentMaterial.ambient = Colors.get_white(); - currentMaterial.specular = Colors.get_black(); - currentMaterial.specularSharpness = 30; - currentMaterial.opacity = 1; - break; - case 40976: - currentMaterial.ambient = this._loadColorChunk(br); - break; - case 40992: - currentMaterial.diffuse = this._loadColorChunk(br); - break; - case 41008: - currentMaterial.specular = this._loadColorChunk(br); - break; - case 41024: - currentMaterial.specularSharpness = 1 + 2 * this._loadPercentageChunk(br); - currentMaterial.specularSharpness = Math.max(10, currentMaterial.specularSharpness); - break; - case 41472: - break; - case 41728: - var textureFilename = ''; - i = 0; - var b2; - do { - b2 = br.readByte(); - if (b2 > 0) { - textureFilename += String.fromCharCode(b2); - } - i++; - } while (!!b2); - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - try { - var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); - if (tex != null) { - this._meshTextures.push(tex); - this.meshFilenames.push(textureFilename); - currentMaterial.diffuse = Colors.get_white(); - } - else { - this._meshTextures.push(null); - } - } - catch ($e1) { - this._meshTextures.push(null); - } - break; - case 41520: - var percentage = this._loadPercentageChunk(br); - var nameId = br.readUInt16(); - var nameBlockLength = br.readUInt32(); - var textureFilename = ''; - i = 0; - var b2; - do { - b2 = br.readByte(); - if (b2 > 0) { - textureFilename += String.fromCharCode(b2); - } - i++; - } while (!!b2); - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - try { - var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); - if (tex != null) { - this._meshNormalMaps.push(tex); - this.meshFilenames.push(textureFilename); - normalMapFound = true; - } - else { - this._meshNormalMaps.push(null); - } - } - catch ($e2) { - this._meshNormalMaps.push(null); - } - break; - case 41476: - var strength = this._loadPercentageChunk(br); - var nameId = br.readUInt16(); - var nameBlockLength = br.readUInt32(); - var textureFilename = ''; - i = 0; - var b2; - do { - b2 = br.readByte(); - if (b2 > 0) { - textureFilename += String.fromCharCode(b2); - } - i++; - } while (!!b2); - var path = this.filename.substring(0, this.filename.lastIndexOf('\\') + 1); - try { - var tex = this._tourDocument.getCachedTexture2d(path + textureFilename); - if (tex != null) { - this._meshSpecularTextures.push(tex); - this.meshFilenames.push(textureFilename); - var gray = ss.truncate((255.99 * strength / 100)); - currentMaterial.specular = Color.fromArgb(255, gray, gray, gray); - } - else { - this._meshSpecularTextures.push(null); - } - } - catch ($e3) { - this._meshSpecularTextures.push(null); - } - break; - case 45056: - break; - case 45058: - break; - case 45072: - name = ''; - i = 0; - var b1; - do { - b1 = br.readByte(); - if (b1 > 0) { - name += String.fromCharCode(b1); - } - i++; - } while (!!b1); - var dum1 = br.readUInt16(); - var dum2 = br.readUInt16(); - var level = br.readUInt16(); - if (level === 65535) { - level = -1; - } - if (ss.startsWith(name, '$')) { - dummyCount++; - } - else { - objNames.push(name); - } - objHierarchy.push(level); - if (ss.keyExists(objectTable, name)) { - objectTable[name].level = level; - } - break; - case 45073: - name = ''; - i = 0; - var b1; - do { - b1 = br.readByte(); - if (b1 > 0) { - name += String.fromCharCode(b1); - } - i++; - } while (!!b1); - objNames.push('$$$' + name); - break; - case 45075: - var points = new Array(3); - for (i = 0; i < 3; i++) { - points[i] = br.readSingle(); - } - if (ss.keyExists(objectTable, name)) { - objectTable[name].pivotPoint = Vector3d.create(-points[0], -points[1], -points[2]); - } - break; - case 45088: - var pos = new Array(8); - for (i = 0; i < 8; i++) { - pos[i] = br.readSingle(); - } - break; - default: - br.seekRelative((sectionLength - 6)); - break; - } - lastID = sectionID; - } - br.close(); - if (currentMaterialIndex > -1) { - this._addMaterial(currentMaterial); - } - var degtorag = Math.PI / 180; - var creaseAngleRad = ((this.smooth) ? 70 * degtorag : 45 * degtorag); - var vertexNormals = this._calculateVertexNormalsMerged(vertexList, indexList, creaseAngleRad); - var newVertexList = []; - var newVertexCount = triangleCount * 3; - for (var vertexIndex = 0; vertexIndex < newVertexCount; ++vertexIndex) { - var v = vertexList[indexList[vertexIndex]]; - v.set_normal(vertexNormals[vertexIndex]); - newVertexList.push(v); - } - var newIndexList = []; - var $enum4 = ss.enumerate(objects); - while ($enum4.moveNext()) { - var node = $enum4.current; - var materialGroups = []; - for (i = 0; i < node.applyLists.length; i++) { - var matId = node.applyListsIndex[i]; - var startIndex = newIndexList.length; - var $enum5 = ss.enumerate(node.applyLists[i]); - while ($enum5.moveNext()) { - var triangleIndex = $enum5.current; - newIndexList.push((triangleIndex * 3)); - newIndexList.push((triangleIndex * 3 + 1)); - newIndexList.push((triangleIndex * 3 + 2)); - } - var group = new Group(); - group.startIndex = startIndex; - group.indexCount = node.applyLists[i].length * 3; - group.materialIndex = matId; - materialGroups.push(group); - } - node.drawGroup = materialGroups; - } - var nodeStack = new ss.Stack(); - var nodeTreeRoot = []; - var rootDummy = new ObjectNode(); - rootDummy.name = 'Root'; - rootDummy.parent = null; - rootDummy.level = -1; - rootDummy.drawGroup = null; - var currentLevel = -1; - nodeStack.push(rootDummy); - nodeTreeRoot.push(rootDummy); - for (i = 0; i < objHierarchy.length; i++) { - var level = objHierarchy[i]; - if (level <= currentLevel) { - while (level <= nodeStack.peek().level && nodeStack.count > 1) { - nodeStack.pop(); - } - currentLevel = level; - } - if (ss.startsWith(objNames[i], '$$$')) { - var dummy = new ObjectNode(); - dummy.name = ss.replaceString(objNames[i], '$$$', ''); - dummy.parent = nodeStack.peek(); - dummy.parent.children.push(dummy); - dummy.level = currentLevel = level; - dummy.drawGroup = null; - nodeStack.push(dummy); - } - else { - objectTable[objNames[i]].level = currentLevel = level; - objectTable[objNames[i]].parent = nodeStack.peek(); - objectTable[objNames[i]].parent.children.push(objectTable[objNames[i]]); - nodeStack.push(objectTable[objNames[i]]); - } - } - if (!objHierarchy.length) { - var $enum6 = ss.enumerate(objects); - while ($enum6.moveNext()) { - var node = $enum6.current; - rootDummy.children.push(node); - node.parent = rootDummy; - } - } - if (normalMapFound) { - var tangentIndexList = []; - for (var tangentIndex = 0; tangentIndex < newVertexCount; ++tangentIndex) { - tangentIndexList.push(tangentIndex); - } - var tangents = this._calculateVertexTangents(newVertexList, tangentIndexList, creaseAngleRad); - var vertices = new Array(newVertexList.length); - var vertexIndex = 0; - var $enum7 = ss.enumerate(newVertexList); - while ($enum7.moveNext()) { - var v = $enum7.current; - var tvertex = new PositionNormalTexturedTangent(v.get_position(), v.get_normal(), Vector2d.create(v.tu, v.tv), tangents[vertexIndex]); - vertices[vertexIndex] = tvertex; - ++vertexIndex; - } - this._mesh = Mesh.createTangent(vertices, newIndexList); - } - else { - this._mesh = Mesh.create(newVertexList, newIndexList); - } - this.objects = nodeTreeRoot; - this._mesh.setObjects(nodeTreeRoot); - this._mesh.commitToDevice(); - this._dirty = false; - this._readyToRender = true; - }, - _offsetObjects: function (vertList, objects, offsetMat, offsetPoint) { - var $enum1 = ss.enumerate(objects); - while ($enum1.moveNext()) { - var node = $enum1.current; - var matLoc = node.localMat; - this._offsetObjects(vertList, node.children, matLoc, Vector3d.addVectors(node.pivotPoint, offsetPoint)); - var $enum2 = ss.enumerate(node.drawGroup); - while ($enum2.moveNext()) { - var group = $enum2.current; - var end = group.startIndex + group.indexCount; - for (var i = group.startIndex; i < end; i++) { - var vert = vertList[i]; - vert.set_position(Vector3d.addVectors(vert.get_position(), Vector3d.addVectors(node.pivotPoint, offsetPoint))); - vertList[i] = vert; - } - } - } - }, - setupLighting: function (renderContext) { - var objPosition = Vector3d.create(renderContext.get_world().get_offsetX(), renderContext.get_world().get_offsetY(), renderContext.get_world().get_offsetZ()); - var objToLight = Vector3d.subtractVectors(objPosition, renderContext.get_reflectedLightPosition()); - var sunPosition = Vector3d.subtractVectors(renderContext.get_sunPosition(), renderContext.get_reflectedLightPosition()); - var cosPhaseAngle = (sunPosition.length() <= 0) ? 1 : Vector3d.dot(objToLight, sunPosition) / (objToLight.length() * sunPosition.length()); - var reflectedLightFactor = Math.max(0, cosPhaseAngle); - reflectedLightFactor = Math.sqrt(reflectedLightFactor); - var hemiLightFactor = 0; - var sunlightFactor = 1; - if (renderContext.get_occludingPlanetRadius() > 0) { - var objAltitude = Vector3d.subtractVectors(objPosition, renderContext.get_occludingPlanetPosition()).length() - renderContext.get_occludingPlanetRadius(); - hemiLightFactor = Math.max(0, Math.min(1, 1 - (objAltitude / renderContext.get_occludingPlanetRadius()) * 300)); - reflectedLightFactor *= (1 - hemiLightFactor); - var sunToPlanet = Vector3d.subtractVectors(renderContext.get_occludingPlanetPosition(), renderContext.get_sunPosition()); - var objToPlanet = Vector3d.subtractVectors(renderContext.get_occludingPlanetPosition(), objPosition); - var hemiLightDirection = Vector3d.create(-objToPlanet.x, -objToPlanet.y, -objToPlanet.z); - hemiLightDirection.normalize(); - renderContext.set_hemisphereLightUp(hemiLightDirection); - var objToSun = Vector3d.subtractVectors(renderContext.get_sunPosition(), objPosition); - var sunPlanetDistance = sunToPlanet.length(); - var t = -Vector3d.dot(objToSun, sunToPlanet) / (sunPlanetDistance * sunPlanetDistance); - if (t > 1) { - var shadowAxisPoint = Vector3d.addVectors(renderContext.get_sunPosition(), Vector3d.multiplyScalar(sunToPlanet, t)); - var d = Vector3d.subtractVectors(shadowAxisPoint, objPosition).length(); - var s = Vector3d.subtractVectors(shadowAxisPoint, renderContext.get_sunPosition()).length(); - var solarRadius = 0.004645784; - var penumbraRadius = renderContext.get_occludingPlanetRadius() + (t - 1) * (renderContext.get_occludingPlanetRadius() + solarRadius); - var umbraRadius = renderContext.get_occludingPlanetRadius() + (t - 1) * (renderContext.get_occludingPlanetRadius() - solarRadius); - if (d < penumbraRadius) { - var minimumShadow = 0; - if (umbraRadius < 0) { - var occlusion = Math.pow(1 / (1 - umbraRadius), 2); - umbraRadius = 0; - minimumShadow = 1 - occlusion; - } - var u = Math.max(0, umbraRadius); - sunlightFactor = Math.max(minimumShadow, (d - u) / (penumbraRadius - u)); - var gray = ss.truncate((255.99 * sunlightFactor)); - renderContext.set_sunlightColor(Color.fromArgb(255, gray, gray, gray)); - hemiLightFactor *= sunlightFactor; - } - } - } - renderContext.set_reflectedLightColor(Color.fromArgb(255, ss.truncate((renderContext.get_reflectedLightColor().r * reflectedLightFactor)), ss.truncate((renderContext.get_reflectedLightColor().g * reflectedLightFactor)), ss.truncate((renderContext.get_reflectedLightColor().b * reflectedLightFactor)))); - renderContext.set_hemisphereLightColor(Color.fromArgb(255, ss.truncate((renderContext.get_hemisphereLightColor().r * hemiLightFactor)), ss.truncate((renderContext.get_hemisphereLightColor().g * hemiLightFactor)), ss.truncate((renderContext.get_hemisphereLightColor().b * hemiLightFactor)))); - }, - render: function (renderContext, opacity) { - if (!this._readyToRender) { - return; - } - if (this._dirty && !this.issLayer) { - this._reload(); - } - var oldWorld = renderContext.get_world(); - var offset = this._mesh.boundingSphere.center; - var unitScale = 1; - if (this._mesh.boundingSphere.radius > 0) { - unitScale = 1 / this._mesh.boundingSphere.radius; - } - renderContext.set_world(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.translation(Vector3d.create(-offset.x, -offset.y, -offset.z)), Matrix3d._scaling(unitScale, unitScale, unitScale)), oldWorld)); - var worldView = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - var v = worldView.transform(Vector3d.get_empty()); - var scaleFactor = Math.sqrt(worldView.get_m11() * worldView.get_m11() + worldView.get_m22() * worldView.get_m22() + worldView.get_m33() * worldView.get_m33()) / unitScale; - var dist = v.length(); - var radius = scaleFactor; - var viewportHeight = ss.truncate(renderContext.height); - var p11 = renderContext.get_projection().get_m11(); - var p34 = renderContext.get_projection().get_m34(); - var p44 = renderContext.get_projection().get_m44(); - var w = Math.abs(p34) * dist + p44; - var pixelsPerUnit = (p11 / w) * viewportHeight; - var radiusInPixels = (radius * pixelsPerUnit); - if (radiusInPixels < 0.5) { - return; - } - var savedSunlightColor = renderContext.get_sunlightColor(); - var savedReflectedColor = renderContext.get_reflectedLightColor(); - var savedHemiColor = renderContext.get_hemisphereLightColor(); - if (Settings.get_current().get_solarSystemLighting()) { - this.setupLighting(renderContext); - if (!this.useCurrentAmbient) { - renderContext.set_ambientLightColor(Color.fromArgb(255, 11, 11, 11)); - } - } - else { - renderContext.set_sunlightColor(Colors.get_black()); - renderContext.set_reflectedLightColor(Colors.get_black()); - renderContext.set_hemisphereLightColor(Colors.get_black()); - renderContext.set_ambientLightColor(Colors.get_white()); - } - if (this._mesh == null) { - return; - } - ModelShader.minLightingBrightness = 0.1; - var count = this._meshMaterials.length; - this._mesh.beginDrawing(renderContext); - if (count > 0) { - for (var i = 0; i < this._meshMaterials.length; i++) { - if (this._meshMaterials[i].isDefault) { - var mat = this._meshMaterials[i]; - mat.diffuse = this.color; - mat.ambient = this.color; - this._meshMaterials[i] = mat; - } - renderContext.setMaterial(this._meshMaterials[i], this._meshTextures[i], this._meshSpecularTextures[i], this._meshNormalMaps[i], opacity); - if (this._mesh.vertexBuffer != null) { - ModelShader.use(renderContext, this._mesh.vertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 32); - } - else { - ModelShader.use(renderContext, this._mesh.tangentVertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 44); - } - renderContext.preDraw(); - this._mesh.drawSubset(renderContext, i); - } - } - else { - renderContext.preDraw(); - for (var i = 0; i < this._meshTextures.length; i++) { - if (this._meshTextures[i] != null) { - renderContext.set_mainTexture(this._meshTextures[i]); - if (this._mesh.vertexBuffer != null) { - ModelShader.use(renderContext, this._mesh.vertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 32); - } - else { - ModelShader.use(renderContext, this._mesh.tangentVertexBuffer.vertexBuffer, this._mesh.indexBuffer.buffer, (this._meshTextures[i] != null) ? this._meshTextures[i].texture2d : null, opacity, false, 44); - } - } - renderContext.preDraw(); - this._mesh.drawSubset(renderContext, i); - } - } - renderContext.set_world(oldWorld); - renderContext.set_sunlightColor(savedSunlightColor); - renderContext.set_reflectedLightColor(savedReflectedColor); - renderContext.set_hemisphereLightColor(savedHemiColor); - renderContext.set_ambientLightColor(Colors.get_black()); - }, - dispose: function () { - if (this._mesh != null) { - this._mesh.dispose(); - this._mesh = null; - } - var $enum1 = ss.enumerate(ss.keys(this._textureCache)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var tex = this._textureCache[key]; - if (tex != null) { - tex.dispose(); - } - } - ss.clearKeys(this._textureCache); - Object3d._disposeTextureList(this._meshTextures); - Object3d._disposeTextureList(this._meshSpecularTextures); - Object3d._disposeTextureList(this._meshNormalMaps); - this._meshMaterials.length = 0; - this._dirty = true; - } - }; - - - // wwtlib.ObjectNode - - function ObjectNode() { - this.level = -1; - this.children = []; - this.enabled = true; - this.drawGroup = []; - this.applyLists = []; - this.applyListsIndex = []; - } - var ObjectNode$ = { - - }; - - - // wwtlib.Orbit - - function Orbit(elements, segments, color, thickness, scale) { - this._elements = null; - this._orbitColor = Colors.get_white(); - this._scale = 0; - this._segmentCount = 0; - this._elements = elements; - this._segmentCount = segments; - this._orbitColor = color; - this._scale = scale; - } - var Orbit$ = { - cleanUp: function () { - }, - get_boundingRadius: function () { - if (this._elements != null) { - return (this._elements.a * (1 + this._elements.e)) / this._scale; - } - else { - return 0; - } - }, - draw3D: function (renderContext, opacity, centerPoint) { - var orbitalPlaneOrientation = Matrix3d.multiplyMatrix(Matrix3d._rotationZ(Coordinates.degreesToRadians(this._elements.w)), Matrix3d.multiplyMatrix(Matrix3d._rotationX(Coordinates.degreesToRadians(this._elements.i)), Matrix3d._rotationZ(Coordinates.degreesToRadians(this._elements.omega)))); - orbitalPlaneOrientation = Matrix3d.multiplyMatrix(orbitalPlaneOrientation, Orbit._orbitalToWwt); - var worldMatrix = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(orbitalPlaneOrientation, Matrix3d.translation(centerPoint)), renderContext.get_world()); - var M = this._elements.n * (SpaceTimeController.get_jNow() - this._elements.t); - var F = 1; - if (M < 0) { - F = -1; - } - M = Math.abs(M) / 360; - M = (M - ss.truncate(M)) * 360 * F; - var color = Color._fromArgbColor(ss.truncate((opacity * 255)), this._orbitColor); - M = Coordinates.degreesToRadians(M); - var E = M; - for (var i = 0; i < 5; i++) { - E += (M - E + this._elements.e * Math.sin(E)) / (1 - this._elements.e * Math.cos(E)); - } - EllipseRenderer.drawEllipse(renderContext, this._elements.a / this._scale, this._elements.e, E, color, worldMatrix); - } - }; - - - // wwtlib.EllipseRenderer - - function EllipseRenderer() { - } - EllipseRenderer.drawEllipseWithPosition = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, worldMatrix, positionNow) { - if (EllipseRenderer._ellipseShader == null) { - EllipseRenderer._ellipseShader = new EllipseShader(); - } - if (EllipseRenderer._ellipseVertexBuffer == null) { - EllipseRenderer._ellipseVertexBuffer = EllipseRenderer.createEllipseVertexBuffer(500); - } - var savedWorld = renderContext.get_world(); - renderContext.set_world(worldMatrix); - renderContext.gl.bindBuffer(34962, EllipseRenderer._ellipseVertexBuffer.vertexBuffer); - renderContext.gl.bindBuffer(34963, null); - EllipseShader.use(renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, 1, savedWorld, positionNow); - renderContext.gl.drawArrays(3, 0, EllipseRenderer._ellipseVertexBuffer.count); - renderContext.set_world(savedWorld); - }; - EllipseRenderer.drawEllipse = function (renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, worldMatrix) { - if (EllipseRenderer._ellipseShader == null) { - EllipseRenderer._ellipseShader = new EllipseShader(); - } - if (EllipseRenderer._ellipseWithoutStartPointVertexBuffer == null) { - EllipseRenderer._ellipseWithoutStartPointVertexBuffer = EllipseRenderer.createEllipseVertexBufferWithoutStartPoint(360); - } - var savedWorld = renderContext.get_world(); - renderContext.set_world(worldMatrix); - renderContext.gl.bindBuffer(34962, EllipseRenderer._ellipseWithoutStartPointVertexBuffer.vertexBuffer); - renderContext.gl.bindBuffer(34963, null); - EllipseShader.use(renderContext, semiMajorAxis, eccentricity, eccentricAnomaly, color, 1, savedWorld, Vector3d.create(0, 0, 0)); - renderContext.gl.drawArrays(3, 0, EllipseRenderer._ellipseWithoutStartPointVertexBuffer.count - 1); - renderContext.set_world(savedWorld); - }; - EllipseRenderer.createEllipseVertexBuffer = function (vertexCount) { - var vb = new PositionVertexBuffer(vertexCount); - var verts = vb.lock(); - var index = 0; - for (var i = 0; i < vertexCount / 2; ++i) { - verts[index++] = Vector3d.create(2 * i / vertexCount * 0.05, 0, 0); - } - for (var i = 0; i < vertexCount / 2; ++i) { - verts[index++] = Vector3d.create(2 * i / vertexCount * 0.95 + 0.05, 0, 0); - } - vb.unlock(); - return vb; - }; - EllipseRenderer.createEllipseVertexBufferWithoutStartPoint = function (vertexCount) { - var vb = new PositionVertexBuffer(vertexCount); - var verts = vb.lock(); - verts[0] = Vector3d.create(1E-06, 0, 0); - for (var i = 1; i < vertexCount; ++i) { - verts[i] = Vector3d.create(2 * i / vertexCount, 0, 0); - } - vb.unlock(); - return vb; - }; - var EllipseRenderer$ = { - - }; - - - // wwtlib.ReferenceFrame - - function ReferenceFrame() { - this._systemGenerated = false; - this.meanAnomoly = 0; - this.orbitalYears = 0; - this.observingLocation = false; - this.reference = 18; - this.parentsRoationalBase = false; - this.referenceFrameType = 0; - this.meanRadius = 6371000; - this.oblateness = 0.0033528; - this.heading = 0; - this.pitch = 0; - this.roll = 0; - this.scale = 1; - this.tilt = 0; - this.translation = new Vector3d(); - this.lat = 0; - this.lng = 0; - this.altitude = 0; - this.rotationalPeriod = 0; - this.zeroRotationDate = 0; - this.representativeColor = Colors.get_white(); - this.showAsPoint = false; - this.showOrbitPath = false; - this.stationKeeping = true; - this.semiMajorAxis = 0; - this.semiMajorAxisUnits = 1; - this.eccentricity = 0; - this.inclination = 0; - this.argumentOfPeriapsis = 0; - this.longitudeOfAscendingNode = 0; - this.meanAnomolyAtEpoch = 0; - this.meanDailyMotion = 0; - this.epoch = 0; - this._orbit = null; - this._elements = new EOE(); - this.worldMatrix = new Matrix3d(); - this.worldMatrix = Matrix3d.get_identity(); - } - ReferenceFrame.isTLECheckSumGood = function (line) { - if (line.length !== 69) { - return false; - } - var checksum = 0; - for (var i = 0; i < 68; i++) { - switch (line.substr(i, 1)) { - case '1': - checksum += 1; - break; - case '2': - checksum += 2; - break; - case '3': - checksum += 3; - break; - case '4': - checksum += 4; - break; - case '5': - checksum += 5; - break; - case '6': - checksum += 6; - break; - case '7': - checksum += 7; - break; - case '8': - checksum += 8; - break; - case '9': - checksum += 9; - break; - case '-': - checksum += 1; - break; - } - } - return (checksum % 10).toString() === line.charAt(68).toString(); - }; - ReferenceFrame.toTLEExponential = function (num, size) { - var exp = num.toExponential(size); - if (exp.length < size + 6) { - exp = exp.substring(0, size + 4) + '0' + exp.substr(size + 4, 1); - } - return exp; - }; - ReferenceFrame.tleNumberString = function (num, left, right) { - var formated = num.toFixed(right); - var point = formated.indexOf('.'); - if (point === -1) { - point = formated.length; - formated += '.0'; - } - var len = formated.length - point - 1; - var fill = '00000000'; - formated = fill.substr(0, left - point) + formated + fill.substr(0, right - len); - return formated; - }; - ReferenceFrame.computeTLECheckSum = function (line) { - if (line.length !== 68) { - return '0'; - } - var checksum = 0; - for (var i = 0; i < 68; i++) { - switch (line[i]) { - case '1': - checksum += 1; - break; - case '2': - checksum += 2; - break; - case '3': - checksum += 3; - break; - case '4': - checksum += 4; - break; - case '5': - checksum += 5; - break; - case '6': - checksum += 6; - break; - case '7': - checksum += 7; - break; - case '8': - checksum += 8; - break; - case '9': - checksum += 9; - break; - case '-': - checksum += 1; - break; - } - } - return ((checksum % 10)); - }; - var ReferenceFrame$ = { - get_representativeColor: function () { - return this.representativeColor; - }, - set_representativeColor: function (value) { - if (value !== this.representativeColor) { - this.representativeColor = value; - this._orbit = null; - } - return value; - }, - get_orbit: function () { - return this._orbit; - }, - set_orbit: function (value) { - this._orbit = value; - return value; - }, - getIndentifier: function () { - return this.name; - }, - importTrajectory: function (filename) { - }, - saveToXml: function (xmlWriter) { - xmlWriter._writeStartElement('ReferenceFrame'); - xmlWriter._writeAttributeString('Name', this.name); - xmlWriter._writeAttributeString('Parent', this.parent); - xmlWriter._writeAttributeString('ReferenceFrameType', Enums.toXml('ReferenceFrameTypes', this.referenceFrameType)); - xmlWriter._writeAttributeString('Reference', Enums.toXml('ReferenceFrames', this.reference)); - xmlWriter._writeAttributeString('ParentsRoationalBase', this.parentsRoationalBase.toString()); - xmlWriter._writeAttributeString('MeanRadius', this.meanRadius.toString()); - xmlWriter._writeAttributeString('Oblateness', this.oblateness.toString()); - xmlWriter._writeAttributeString('Heading', this.heading.toString()); - xmlWriter._writeAttributeString('Pitch', this.pitch.toString()); - xmlWriter._writeAttributeString('Roll', this.roll.toString()); - xmlWriter._writeAttributeString('Scale', this.scale.toString()); - xmlWriter._writeAttributeString('Tilt', this.tilt.toString()); - xmlWriter._writeAttributeString('Translation', this.translation.toString()); - if (!this.referenceFrameType) { - xmlWriter._writeAttributeString('Lat', this.lat.toString()); - xmlWriter._writeAttributeString('Lng', this.lng.toString()); - xmlWriter._writeAttributeString('Altitude', this.altitude.toString()); - } - xmlWriter._writeAttributeString('RotationalPeriod', this.rotationalPeriod.toString()); - xmlWriter._writeAttributeString('ZeroRotationDate', this.zeroRotationDate.toString()); - xmlWriter._writeAttributeString('RepresentativeColor', this.get_representativeColor().save()); - xmlWriter._writeAttributeString('ShowAsPoint', this.showAsPoint.toString()); - xmlWriter._writeAttributeString('ShowOrbitPath', this.showOrbitPath.toString()); - xmlWriter._writeAttributeString('StationKeeping', this.stationKeeping.toString()); - if (this.referenceFrameType === 1) { - xmlWriter._writeAttributeString('SemiMajorAxis', this.semiMajorAxis.toString()); - xmlWriter._writeAttributeString('SemiMajorAxisScale', Enums.toXml('AltUnits', this.semiMajorAxisUnits)); - xmlWriter._writeAttributeString('Eccentricity', this.eccentricity.toString()); - xmlWriter._writeAttributeString('Inclination', this.inclination.toString()); - xmlWriter._writeAttributeString('ArgumentOfPeriapsis', this.argumentOfPeriapsis.toString()); - xmlWriter._writeAttributeString('LongitudeOfAscendingNode', this.longitudeOfAscendingNode.toString()); - xmlWriter._writeAttributeString('MeanAnomolyAtEpoch', this.meanAnomolyAtEpoch.toString()); - xmlWriter._writeAttributeString('MeanDailyMotion', this.meanDailyMotion.toString()); - xmlWriter._writeAttributeString('Epoch', this.epoch.toString()); - } - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - this.name = node.attributes.getNamedItem('Name').nodeValue; - this.parent = node.attributes.getNamedItem('Parent').nodeValue; - this.referenceFrameType = Enums.parse('ReferenceFrameTypes', node.attributes.getNamedItem('ReferenceFrameType').nodeValue); - this.reference = Enums.parse('ReferenceFrames', node.attributes.getNamedItem('Reference').nodeValue); - this.parentsRoationalBase = ss.boolean(node.attributes.getNamedItem('ParentsRoationalBase').nodeValue); - this.meanRadius = parseFloat(node.attributes.getNamedItem('MeanRadius').nodeValue); - this.oblateness = parseFloat(node.attributes.getNamedItem('Oblateness').nodeValue); - this.heading = parseFloat(node.attributes.getNamedItem('Heading').nodeValue); - this.pitch = parseFloat(node.attributes.getNamedItem('Pitch').nodeValue); - this.roll = parseFloat(node.attributes.getNamedItem('Roll').nodeValue); - this.scale = parseFloat(node.attributes.getNamedItem('Scale').nodeValue); - this.tilt = parseFloat(node.attributes.getNamedItem('Tilt').nodeValue); - this.translation = Vector3d.parse(node.attributes.getNamedItem('Translation').nodeValue); - if (!this.referenceFrameType) { - this.lat = parseFloat(node.attributes.getNamedItem('Lat').nodeValue); - this.lng = parseFloat(node.attributes.getNamedItem('Lng').nodeValue); - this.altitude = parseFloat(node.attributes.getNamedItem('Altitude').nodeValue); - } - this.rotationalPeriod = parseFloat(node.attributes.getNamedItem('RotationalPeriod').nodeValue); - this.zeroRotationDate = parseFloat(node.attributes.getNamedItem('ZeroRotationDate').nodeValue); - this.set_representativeColor(Color.load(node.attributes.getNamedItem('RepresentativeColor').nodeValue)); - this.showAsPoint = ss.boolean(node.attributes.getNamedItem('ShowAsPoint').nodeValue); - if (node.attributes.getNamedItem('StationKeeping') != null) { - this.stationKeeping = ss.boolean(node.attributes.getNamedItem('StationKeeping').nodeValue); - } - if (this.referenceFrameType === 1) { - this.showOrbitPath = ss.boolean(node.attributes.getNamedItem('ShowOrbitPath').nodeValue); - this.semiMajorAxis = parseFloat(node.attributes.getNamedItem('SemiMajorAxis').nodeValue); - this.semiMajorAxisUnits = Enums.parse('AltUnits', node.attributes.getNamedItem('SemiMajorAxisScale').nodeValue); - this.eccentricity = parseFloat(node.attributes.getNamedItem('Eccentricity').nodeValue); - this.inclination = parseFloat(node.attributes.getNamedItem('Inclination').nodeValue); - this.argumentOfPeriapsis = parseFloat(node.attributes.getNamedItem('ArgumentOfPeriapsis').nodeValue); - this.longitudeOfAscendingNode = parseFloat(node.attributes.getNamedItem('LongitudeOfAscendingNode').nodeValue); - this.meanAnomolyAtEpoch = parseFloat(node.attributes.getNamedItem('MeanAnomolyAtEpoch').nodeValue); - this.meanDailyMotion = parseFloat(node.attributes.getNamedItem('MeanDailyMotion').nodeValue); - this.epoch = parseFloat(node.attributes.getNamedItem('Epoch').nodeValue); - } - }, - fromTLE: function (line1, line2, gravity) { - this.epoch = SpaceTimeController._twoLineDateToJulian(line1.substr(18, 14)); - this.eccentricity = parseFloat('0.' + line2.substr(26, 7)); - this.inclination = parseFloat(line2.substr(8, 8)); - this.longitudeOfAscendingNode = parseFloat(line2.substr(17, 8)); - this.argumentOfPeriapsis = parseFloat(line2.substr(34, 8)); - var revs = parseFloat(line2.substr(52, 11)); - this.meanAnomolyAtEpoch = parseFloat(line2.substr(43, 8)); - this.meanDailyMotion = revs * 360; - var part = (86400 / revs) / (Math.PI * 2); - this.semiMajorAxis = Math.pow((part * part) * gravity, 1 / 3); - this.semiMajorAxisUnits = 1; - }, - toTLE: function () { - var line1 = new ss.StringBuilder(); - line1.append('1 99999U 00111AAA '); - line1.append(SpaceTimeController.julianToTwoLineDate(this.epoch)); - line1.append(' '); - line1.append(this.semiMajorAxis.toExponential(4)); - line1.append(' 00000-0 '); - line1.append(ReferenceFrame.toTLEExponential(this.meanDailyMotion, 5)); - line1.append(' 001'); - line1.append(ReferenceFrame.computeTLECheckSum(line1.toString())); - line1.appendLine(''); - var line2 = new ss.StringBuilder(); - line2.append('2 99999 '); - line2.append(ReferenceFrame.tleNumberString(this.inclination, 3, 4) + ' '); - line2.append(ReferenceFrame.tleNumberString(this.longitudeOfAscendingNode, 3, 4) + ' '); - line2.append((ReferenceFrame.tleNumberString(this.eccentricity, 1, 7) + ' ').substring(2)); - line2.append(ReferenceFrame.tleNumberString(this.argumentOfPeriapsis, 3, 4) + ' '); - line2.append(ReferenceFrame.tleNumberString(this.meanAnomolyAtEpoch, 3, 4) + ' '); - line2.append(ReferenceFrame.toTLEExponential(this.meanDailyMotion / 207732, 5)); - line2.append('00001'); - line2.append(ReferenceFrame.computeTLECheckSum(line2.toString())); - line2.appendLine(''); - return line1.toString() + line2.toString(); - }, - get_elements: function () { - this._elements.a = this.semiMajorAxis; - this._elements.e = this.eccentricity; - this._elements.i = this.inclination; - this._elements.w = this.argumentOfPeriapsis; - this._elements.omega = this.longitudeOfAscendingNode; - this._elements.jdEquinox = this.epoch; - if (!this.meanDailyMotion) { - this._elements.n = ELL.meanMotionFromSemiMajorAxis(this._elements.a); - } - else { - this._elements.n = this.meanDailyMotion; - } - this._elements.t = this.epoch - (this.meanAnomolyAtEpoch / this._elements.n); - return this._elements; - }, - set_elements: function (value) { - this._elements = value; - return value; - }, - computeFrame: function (renderContext) { - switch (this.referenceFrameType) { - case 1: - this._computeOrbital(renderContext); - break; - case 0: - this._computeFixedSherical(renderContext); - break; - case 2: - this._computeFrameTrajectory(renderContext); - break; - default: - break; - } - }, - useRotatingParentFrame: function () { - switch (this.referenceFrameType) { - case 1: - case 2: - case 3: - return false; - default: - return true; - } - }, - _computeFixedRectangular: function (renderContext) { - }, - _computeFixedSherical: function (renderContext) { - if (this.observingLocation) { - this.lat = SpaceTimeController.get_location().get_lat(); - this.lng = SpaceTimeController.get_location().get_lng(); - this.altitude = SpaceTimeController.get_altitude(); - } - this.worldMatrix = Matrix3d.get_identity(); - this.worldMatrix.translate(this.translation); - var localScale = (1 / renderContext.get_nominalRadius()) * this.scale * this.meanRadius; - this.worldMatrix.scale(Vector3d.create(localScale, localScale, localScale)); - this.worldMatrix._multiply(Matrix3d.rotationYawPitchRoll((this.heading / 180 * Math.PI), (this.pitch / 180 * Math.PI), (this.roll / 180 * Math.PI))); - this.worldMatrix._multiply(Matrix3d._rotationZ(-90 / 180 * Math.PI)); - if (!!this.rotationalPeriod) { - var rotationCurrent = (((SpaceTimeController.get_jNow() - this.zeroRotationDate) / this.rotationalPeriod) * Math.PI * 2) % (Math.PI * 2); - this.worldMatrix._multiply(Matrix3d._rotationX(-rotationCurrent)); - } - this.worldMatrix.translate(Vector3d.create(1 + (this.altitude / renderContext.get_nominalRadius()), 0, 0)); - this.worldMatrix._multiply(Matrix3d._rotationZ(this.lat / 180 * Math.PI)); - this.worldMatrix._multiply(Matrix3d._rotationY(-(this.lng + 180) / 180 * Math.PI)); - }, - _computeFrameTrajectory: function (renderContext) { - }, - _computeOrbital: function (renderContext) { - var ee = this.get_elements(); - var point = ELL.calculateRectangularJD(SpaceTimeController.get_jNow(), ee); - this.meanAnomoly = ee.meanAnnomolyOut; - var pointInstantLater = ELL.calculateRectangular(ee, this.meanAnomoly + 0.001); - var direction = Vector3d.subtractVectors(point, pointInstantLater); - var up = point.copy(); - up.normalize(); - direction.normalize(); - var dist = point.length(); - var scaleFactor = 1; - switch (this.semiMajorAxisUnits) { - case 1: - scaleFactor = 1; - break; - case 2: - scaleFactor = 1 / 3.2808399; - break; - case 3: - scaleFactor = (1 / 3.2808399) / 12; - break; - case 4: - scaleFactor = 1609.344; - break; - case 5: - scaleFactor = 1000; - break; - case 6: - scaleFactor = 149598000 * 1000; - break; - case 7: - scaleFactor = 63239.6717 * 149598000 * 1000; - break; - case 8: - scaleFactor = 206264.806 * 149598000 * 1000; - break; - case 9: - scaleFactor = 206264.806 * 149598000 * 1000 * 1000000; - break; - case 10: - scaleFactor = 1; - break; - default: - break; - } - scaleFactor *= 1 / renderContext.get_nominalRadius(); - var look = Matrix3d.lookAtLH(Vector3d.create(0, 0, 0), direction, up); - look.invert(); - this.worldMatrix = Matrix3d.get_identity(); - this.worldMatrix.translate(this.translation); - var localScale = (1 / renderContext.get_nominalRadius()) * this.scale * this.meanRadius; - this.worldMatrix.scale(Vector3d.create(localScale, localScale, localScale)); - this.worldMatrix._multiply(Matrix3d.rotationYawPitchRoll((this.heading / 180 * Math.PI), (this.pitch / 180 * Math.PI), (this.roll / 180 * Math.PI))); - if (!!this.rotationalPeriod) { - var rotationCurrent = (((SpaceTimeController.get_jNow() - this.zeroRotationDate) / this.rotationalPeriod) * Math.PI * 2) % (Math.PI * 2); - this.worldMatrix._multiply(Matrix3d._rotationX(-rotationCurrent)); - } - point = Vector3d.scale(point, scaleFactor); - this.worldMatrix.translate(point); - if (this.stationKeeping) { - this.worldMatrix = Matrix3d.multiplyMatrix(look, this.worldMatrix); - } - } - }; - - - // wwtlib.KmlCoordinate - - function KmlCoordinate() { - this.lat = 0; - this.lng = 0; - this.alt = 0; - } - var KmlCoordinate$ = { - - }; - - - // wwtlib.KmlLineList - - function KmlLineList() { - this.extrude = false; - this.astronomical = false; - this.meanRadius = 6371000; - this.pointList = []; - } - var KmlLineList$ = { - parseWkt: function (geoText, option, alt, date) { - var parts = UiTools.split(geoText, '(,)'); - var $enum1 = ss.enumerate(parts); - while ($enum1.moveNext()) { - var part = $enum1.current; - var coordinates = ss.trim(part).split(' '); - if (coordinates.length > 1) { - var pnt = new KmlCoordinate(); - pnt.lng = parseFloat(coordinates[0]); - if (this.astronomical) { - pnt.lng -= 180; - } - pnt.lat = parseFloat(coordinates[1]); - if (coordinates.length > 2 && !alt) { - pnt.alt = parseFloat(coordinates[2]); - } - else { - pnt.alt = alt; - } - pnt.date = date; - this.pointList.push(pnt); - } - } - }, - getCenterPoint: function () { - var point = new KmlCoordinate(); - point.lat = 0; - point.lng = 0; - point.alt = 0; - var $enum1 = ss.enumerate(this.pointList); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - point.lat += pnt.lat; - point.lng += pnt.lng; - point.alt += pnt.alt; - } - point.lat /= this.pointList.length; - point.lng /= this.pointList.length; - point.alt /= this.pointList.length; - return point; - } - }; - - - // wwtlib.PushPin - - function PushPin() { - } - PushPin.triggerLoadSprite = function () { - if (PushPin._pins == null) { - PushPin._pins = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('pins.png')); - } - }; - PushPin.getPushPinTexture = function (pinId) { - var texture = null; - if (ss.keyExists(PushPin._pinTextureCache, pinId)) { - return PushPin._pinTextureCache[pinId]; - } - try { - texture = Tile.prepDevice.createTexture(); - Tile.prepDevice.bindTexture(3553, texture); - var row = Math.floor(pinId / 16); - var col = pinId % 16; - var temp = document.createElement('canvas'); - temp.height = 32; - temp.width = 32; - var ctx = temp.getContext('2d'); - ctx.drawImage(PushPin._pins.imageElement, (col * 32), (row * 32), 32, 32, 0, 0, 32, 32); - var image = temp; - Tile.prepDevice.texParameteri(3553, 10242, 33071); - Tile.prepDevice.texParameteri(3553, 10243, 33071); - Tile.prepDevice.texImage2D(3553, 0, 6408, 6408, 5121, image); - Tile.prepDevice.texParameteri(3553, 10241, 9985); - Tile.prepDevice.generateMipmap(3553); - Tile.prepDevice.bindTexture(3553, null); - PushPin._pinTextureCache[pinId] = texture; - } - catch ($e1) { - } - return texture; - }; - var PushPin$ = { - - }; - - - // wwtlib.Table - - function Table() { - this.guid = new Guid(); - this.header = []; - this.rows = []; - this.delimiter = '\t'; - this.locked = false; - } - var Table$ = { - lock: function () { - this.locked = true; - }, - unlock: function () { - this.locked = false; - }, - save: function () { - var data = ''; - var first = true; - var $enum1 = ss.enumerate(this.header); - while ($enum1.moveNext()) { - var col = $enum1.current; - if (!first) { - data += '\t'; - } - else { - first = false; - } - data += col; - } - data += '\r\n'; - var $enum2 = ss.enumerate(this.rows); - while ($enum2.moveNext()) { - var row = $enum2.current; - first = true; - var $enum3 = ss.enumerate(row); - while ($enum3.moveNext()) { - var col = $enum3.current; - if (!first) { - data += '\t'; - } - else { - first = false; - } - data += col; - } - data += '\r\n'; - } - return data; - }, - loadFromString: function (data, isUpdate, purge, hasHeader) { - var count = 0; - var lines = data.split('\r\n'); - if (!isUpdate || hasHeader) { - if (lines.length > 0) { - var headerLine = lines[0]; - count++; - if (headerLine.indexOf('\t') === -1 && headerLine.indexOf(',') > -1) { - this.delimiter = ','; - } - if (!isUpdate) { - this.rows.length = 0; - } - this.header = UiTools.splitString(headerLine, this.delimiter); - } - else { - this.header = []; - } - } - var temp = []; - if (!purge) { - temp = this.rows; - } - while (count < lines.length) { - var line = lines[count]; - var rowData = UiTools.splitString(line, this.delimiter); - if (rowData.length < 1) { - break; - } - temp.push(rowData); - count++; - } - if (purge) { - this.rows = temp; - } - }, - clone: function () { - var cloned_table = new Table(); - for (var i = 0; i < this.header.length; i++) { - cloned_table.header.push(this.header[i]); - } - for (var j = 0; j < this.rows.length; j++) { - cloned_table.rows.push([]); - for (var i = 0; i < this.rows[j].length; i++) { - cloned_table.rows[j].push(this.rows[j][i]); - } - } - return cloned_table; - }, - addColumn: function (name, data) { - this.header.push(name); - for (var i = 0; i < data.length; i++) { - this.rows[i].push(data[i]); - } - }, - removeColumn: function (name) { - var remove_index = this.header.indexOf(name); - if (remove_index > -1) { - this.header.splice(remove_index, 1); - for (var i = 0; i < this.rows.length; i++) { - this.rows[i].splice(remove_index, 1); - } - } - } - }; - - - // wwtlib.VoTable - - function VoTable() { - this.columns = {}; - this.column = []; - this.rows = []; - this.loadFilename = ''; - this.sampId = ''; - this.selectedRow = null; - this.error = false; - this.errorText = ''; - } - VoTable.loadFromUrl = function (url, complete) { - var temp = new VoTable(); - temp._onComplete = complete; - temp._webFile = new WebFile(URLHelpers.singleton.rewrite(url, 1)); - temp._webFile.onStateChange = ss.bind('_loadData', temp); - temp._webFile.send(); - return temp; - }; - VoTable.loadFromString = function (data) { - var xParser = new DOMParser(); - var doc = xParser.parseFromString(data, 'text/xml'); - var table = new VoTable(); - table.loadFromXML(doc); - return table; - }; - var VoTable$ = { - _loadData: function () { - if (this._webFile.get_state() === 2) { - alert(this._webFile.get_message()); - } - else if (this._webFile.get_state() === 1) { - this.loadFromXML(this._webFile.getXml()); - if (this._onComplete != null) { - this._onComplete(); - } - } - }, - loadFromXML: function (xml) { - var voTable = Util.selectSingleNode(xml, 'VOTABLE'); - if (voTable == null) { - return; - } - var index = 0; - try { - var table = Util.selectSingleNode(Util.selectSingleNode(voTable, 'RESOURCE'), 'TABLE'); - if (table != null) { - var $enum1 = ss.enumerate(table.childNodes); - while ($enum1.moveNext()) { - var node = $enum1.current; - if (node.nodeName === 'FIELD') { - var col = new VoColumn(node, index++); - this.columns[col.name] = col; - this.column.push(col); - } - } - } - } - catch ($e2) { - this.error = true; - this.errorText = Util.selectSingleNode(voTable, 'DESCRIPTION').text; - } - try { - var tableData = Util.selectSingleNode(Util.selectSingleNode(Util.selectSingleNode(Util.selectSingleNode(voTable, 'RESOURCE'), 'TABLE'), 'DATA'), 'TABLEDATA'); - if (tableData != null) { - var $enum3 = ss.enumerate(tableData.childNodes); - while ($enum3.moveNext()) { - var node = $enum3.current; - if (node.nodeName === 'TR') { - var row = new VoRow(this); - row.columnData = new Array(ss.keyCount(this.columns)); - index = 0; - var $enum4 = ss.enumerate(node.childNodes); - while ($enum4.moveNext()) { - var child = $enum4.current; - if (child.nodeName === 'TD') { - row.columnData[index++] = ss.trim(Util.getInnerText(child)); - } - } - this.rows.push(row); - } - } - } - } - catch ($e5) { - } - }, - save: function (filename) { - return true; - }, - getColumnByUcd: function (ucd) { - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (ss.replaceString(col.ucd, '_', '.').toLocaleLowerCase().indexOf(ucd.toLocaleLowerCase()) > -1) { - return col; - } - } - return null; - }, - getRAColumn: function () { - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (col.ucd.toLocaleLowerCase().indexOf('pos.eq.ra') > -1 || col.ucd.toLocaleLowerCase().indexOf('pos_eq_ra') > -1) { - return col; - } - } - var $enum2 = ss.enumerate(ss.keys(this.columns)); - while ($enum2.moveNext()) { - var key = $enum2.current; - var col = this.columns[key]; - if (col.name.toLocaleLowerCase().indexOf('ra') > -1) { - return col; - } - } - return null; - }, - getDecColumn: function () { - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (col.ucd.toLowerCase().indexOf('pos.eq.dec') > -1 || col.ucd.toLowerCase().indexOf('pos_eq_dec') > -1) { - return col; - } - } - var $enum2 = ss.enumerate(ss.keys(this.columns)); - while ($enum2.moveNext()) { - var key = $enum2.current; - var col = this.columns[key]; - if (col.name.toLowerCase().indexOf('dec') > -1) { - return col; - } - } - return null; - }, - getMagColumn: function () { - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (col.ucd.toLowerCase().indexOf('phot.mag') > -1 || col.ucd.toLowerCase().indexOf('phot_mag') > -1) { - return col; - } - } - return null; - }, - getDistanceColumn: function () { - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (col.ucd.toLowerCase().indexOf('pos.distance') > -1 || col.ucd.toLowerCase().indexOf('pos_distance') > -1) { - return col; - } - } - return null; - }, - toString: function () { - var sb = new ss.StringBuilder(); - var first = true; - var $enum1 = ss.enumerate(ss.keys(this.columns)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var col = this.columns[key]; - if (first) { - first = false; - } - else { - sb.append('\t'); - } - sb.append(col.name); - } - sb.appendLine(''); - var $enum2 = ss.enumerate(this.rows); - while ($enum2.moveNext()) { - var row = $enum2.current; - first = true; - var $enum3 = ss.enumerate(row.columnData); - while ($enum3.moveNext()) { - var col = $enum3.current; - if (first) { - first = false; - } - else { - sb.append('\t'); - } - sb.append(col.toString()); - } - sb.appendLine(''); - } - return sb.toString(); - } - }; - - - // wwtlib.VoRow - - function VoRow(owner) { - this.selected = false; - this.owner = owner; - } - var VoRow$ = { - getColumnData: function (key) { - if (this.owner.columns[key] != null) { - return this.columnData[this.owner.columns[key].index]; - } - return null; - }, - get_item: function (index) { - if (index < 0 || index >= this.columnData.length) { - return null; - } - return this.columnData[index]; - } - }; - - - // wwtlib.VoColumn - - function VoColumn(node, index) { - this.id = ''; - this.type = 0; - this.precision = 0; - this.dimentions = 0; - this.sizes = null; - this.ucd = ''; - this.unit = ''; - this.name = ''; - this.index = 0; - this.index = index; - if (node.attributes.getNamedItem('datatype') != null) { - this.type = VoColumn.getType(node.attributes.getNamedItem('datatype').nodeValue); - } - if (node.attributes.getNamedItem('ucd') != null) { - this.ucd = node.attributes.getNamedItem('ucd').nodeValue; - } - if (node.attributes.getNamedItem('precision') != null) { - try { - this.precision = parseInt(node.attributes.getNamedItem('precision').nodeValue); - } - catch ($e1) { - } - } - if (node.attributes.getNamedItem('ID') != null) { - this.id = node.attributes.getNamedItem('ID').nodeValue; - } - if (node.attributes.getNamedItem('name') != null) { - this.name = node.attributes.getNamedItem('name').nodeValue; - } - else { - this.name = this.id; - } - if (node.attributes.getNamedItem('unit') != null) { - this.unit = node.attributes.getNamedItem('unit').nodeValue; - } - if (node.attributes.getNamedItem('arraysize') != null) { - var split = node.attributes.getNamedItem('arraysize').nodeValue.split('x'); - this.dimentions = split.length; - this.sizes = new Array(split.length); - var indexer = 0; - var $enum2 = ss.enumerate(split); - while ($enum2.moveNext()) { - var dim = $enum2.current; - if (!(dim.indexOf('*') > -1)) { - this.sizes[indexer++] = parseInt(dim); - } - else { - var len = 9999; - var lenString = ss.replaceString(dim, '*', ''); - if (lenString.length > 0) { - len = parseInt(lenString); - } - this.sizes[indexer++] = len; - } - } - } - } - VoColumn.getType = function (type) { - var Type = 13; - switch (type) { - case 'boolean': - Type = 1; - break; - case 'bit': - Type = 2; - break; - case 'unsignedByte': - Type = 3; - break; - case 'short': - Type = 4; - break; - case 'int': - Type = 5; - break; - case 'long': - Type = 6; - break; - case 'char': - Type = 7; - break; - case 'unicodeChar': - Type = 8; - break; - case 'float': - Type = 9; - break; - case 'double': - Type = 10; - break; - case 'floatComplex': - Type = 11; - break; - case 'doubleComplex': - Type = 12; - break; - default: - Type = 13; - break; - } - return Type; - }; - var VoColumn$ = { - toString: function () { - return this.name; - } - }; - - - // wwtlib.WcsImage - - function WcsImage() { - this.copyright = ''; - this.creditsUrl = ''; - this._validWcs = false; - this.keywords = []; - this.description = ''; - this.scaleX = 0; - this.scaleY = 0; - this.centerX = 0; - this.centerY = 0; - this.rotation = 0; - this.referenceX = 0; - this.referenceY = 0; - this.sizeX = 0; - this.sizeY = 0; - this.cd1_1 = 0; - this.cd1_2 = 0; - this.cd2_1 = 0; - this.cd2_2 = 0; - this.hasRotation = false; - this.hasSize = false; - this.hasScale = false; - this.hasLocation = false; - this.hasPixel = false; - this.filename = ''; - this._colorCombine = false; - } - var WcsImage$ = { - get_copyright: function () { - return this.copyright; - }, - set_copyright: function (value) { - this.copyright = value; - return value; - }, - get_creditsUrl: function () { - return this.creditsUrl; - }, - set_creditsUrl: function (value) { - this.creditsUrl = value; - return value; - }, - get_validWcs: function () { - return this._validWcs; - }, - set_validWcs: function (value) { - this._validWcs = value; - return value; - }, - get_keywords: function () { - if (!this.keywords.length) { - this.keywords.push('Image File'); - } - return this.keywords; - }, - set_keywords: function (value) { - this.keywords = value; - return value; - }, - get_description: function () { - return this.description; - }, - set_description: function (value) { - this.description = value; - return value; - }, - get_scaleX: function () { - return this.scaleX; - }, - set_scaleX: function (value) { - this.scaleX = value; - return value; - }, - get_scaleY: function () { - return this.scaleY; - }, - set_scaleY: function (value) { - this.scaleY = value; - return value; - }, - get_centerX: function () { - return this.centerX; - }, - set_centerX: function (value) { - this.centerX = value; - return value; - }, - get_viewCenterX: function () { - return this.centerX + (this.get_sizeX() / 2 - this.get_referenceX()) * this.get_scaleX(); - }, - get_centerY: function () { - return this.centerY; - }, - set_centerY: function (value) { - this.centerY = value; - return value; - }, - get_viewCenterY: function () { - return this.centerY + (this.get_sizeY() / 2 - this.get_referenceY()) * this.get_scaleY(); - }, - get_rotation: function () { - return this.rotation; - }, - set_rotation: function (value) { - this.rotation = value; - return value; - }, - get_referenceX: function () { - return this.referenceX; - }, - set_referenceX: function (value) { - this.referenceX = value; - return value; - }, - get_referenceY: function () { - return this.referenceY; - }, - set_referenceY: function (value) { - this.referenceY = value; - return value; - }, - get_sizeX: function () { - return this.sizeX; - }, - set_sizeX: function (value) { - this.sizeX = value; - return value; - }, - get_sizeY: function () { - return this.sizeY; - }, - set_sizeY: function (value) { - this.sizeY = value; - return value; - }, - get_cd1_1: function () { - return this.cd1_1; - }, - set_cd1_1: function (value) { - this.cd1_1 = value; - return value; - }, - get_cd1_2: function () { - return this.cd1_2; - }, - set_cd1_2: function (value) { - this.cd1_2 = value; - return value; - }, - get_cd2_1: function () { - return this.cd2_1; - }, - set_cd2_1: function (value) { - this.cd2_1 = value; - return value; - }, - get_cd2_2: function () { - return this.cd2_2; - }, - set_cd2_2: function (value) { - this.cd2_2 = value; - return value; - }, - adjustScale: function (width, height) { - if (width !== this.sizeX) { - this.scaleX *= (this.sizeX / width); - this.referenceX /= (this.sizeX / width); - this.sizeX = width; - } - if (height !== this.sizeY) { - this.scaleY *= (this.sizeY / height); - this.referenceY /= (this.sizeY / height); - this.sizeY = height; - } - }, - calculateScaleFromCD: function () { - this.scaleX = (Math.sqrt(this.cd1_1 * this.cd1_1 + this.cd2_1 * this.cd2_1) * (this.cd1_1 * this.cd2_2 - this.cd1_2 * this.cd2_1) < 0) ? -1 : 1; - this.scaleY = Math.sqrt(this.cd1_2 * this.cd1_2 + this.cd2_2 * this.cd2_2); - }, - calculateRotationFromCD: function () { - var sign = ((this.cd1_1 * this.cd2_2 - this.cd1_2 * this.cd2_1) < 0) ? -1 : 1; - var rot2 = Math.atan2((-sign * this.cd1_2), this.cd2_2); - this.rotation = rot2 / Math.PI * 180; - }, - get_filename: function () { - return this.filename; - }, - set_filename: function (value) { - this.filename = value; - return value; - }, - get_colorCombine: function () { - return this._colorCombine; - }, - set_colorCombine: function (value) { - this._colorCombine = value; - return value; - }, - getBitmap: function () { - return null; - } - }; - - - // wwtlib.MainView - - function MainView() { - } - MainView._drawTest = function () { - var canvas = document.getElementById('canvas'); - var ctx = canvas.getContext('2d'); - ctx.fillStyle = 'rgb(80,0,0)'; - ctx.fillRect(120, 120, 165, 160); - ctx.fillStyle = 'rgba(0, 0, 160, 0.5)'; - ctx.fillRect(140, 140, 165, 160); - }; - - - // wwtlib.MinorPlanets - - function MinorPlanets() { - } - MinorPlanets.getMpcFile = function (url) { - MinorPlanets._webMpcFile = new WebFile(url); - MinorPlanets._webMpcFile.responseType = 'blob'; - MinorPlanets._webMpcFile.onStateChange = MinorPlanets.starFileStateChange; - MinorPlanets._webMpcFile.send(); - }; - MinorPlanets.starFileStateChange = function () { - if (MinorPlanets._webMpcFile.get_state() === 2) { - alert(MinorPlanets._webMpcFile.get_message()); - } - else if (MinorPlanets._webMpcFile.get_state() === 1) { - var mainBlob = MinorPlanets._webMpcFile.getBlob(); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - MinorPlanets._readFromBin(new BinaryReader(new Uint8Array(chunck.result))); - MinorPlanets.initMPCVertexBuffer(); - }; - chunck.readAsArrayBuffer(mainBlob); - } - }; - MinorPlanets._readFromBin = function (br) { - MinorPlanets.mpcList = []; - var len = br.get_length(); - var ee; - try { - while (br.get_position() < len) { - ee = EOE._create(br); - MinorPlanets.mpcList.push(ee); - } - } - catch ($e1) { - } - br.close(); - }; - MinorPlanets.drawMPC3D = function (renderContext, opacity, centerPoint) { - var zoom = renderContext.viewCamera.zoom; - var distAlpha = ((Math.log(Math.max(1, zoom)) / Math.log(4)) - 15.5) * 90; - var alpha = Math.min(255, Math.max(0, ss.truncate(distAlpha))); - if (alpha > 254) { - return; - } - if (MinorPlanets._mpcVertexBuffer == null) { - if (MinorPlanets.starTexture == null) { - MinorPlanets.starTexture = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png')); - } - for (var i = 0; i < 7; i++) { - MinorPlanets._mpcBlendStates[i] = BlendState.create(false, 1000); - } - if (!MinorPlanets._initBegun) { - MinorPlanets._startInit(); - MinorPlanets._initBegun = true; - } - return; - } - var offset = Matrix3d.translation(Vector3d.negate(centerPoint)); - var world = Matrix3d.multiplyMatrix(renderContext.get_world(), offset); - var matrixWV = Matrix3d.multiplyMatrix(world, renderContext.get_view()); - var cam = Vector3d._transformCoordinate(renderContext.cameraPosition, Matrix3d.invertMatrix(renderContext.get_world())); - if (MinorPlanets._mpcVertexBuffer != null) { - for (var i = 0; i < 7; i++) { - MinorPlanets._mpcBlendStates[i].set_targetState(true); - if (MinorPlanets._mpcBlendStates[i].get_state()) { - KeplerPointSpriteShader.use(renderContext, matrixWV, MinorPlanets._mpcVertexBuffer[i].vertexBuffer, MinorPlanets.starTexture.texture2d, Colors.get_white(), opacity * MinorPlanets._mpcBlendStates[i].get_opacity(), false, (SpaceTimeController.get_jNow() - KeplerVertex.baseDate), 0, renderContext.cameraPosition, 200, 0.1); - renderContext.gl.drawArrays(0, 0, MinorPlanets._mpcVertexBuffer[i].count); - } - } - } - }; - MinorPlanets._startInit = function () { - if (!WWTControl.singleton.freestandingMode) { - MinorPlanets.getMpcFile(URLHelpers.singleton.coreStaticUrl('wwtweb/catalog.aspx?Q=mpcbin')); - } - }; - MinorPlanets.initMPCVertexBuffer = function () { - try { - if (MinorPlanets._mpcVertexBuffer == null) { - var mpcVertexBufferTemp = new Array(7); - MinorPlanets._mpcCount = MinorPlanets.mpcList.length; - var lists = new Array(7); - for (var i = 0; i < 7; i++) { - lists[i] = []; - } - var $enum1 = ss.enumerate(MinorPlanets.mpcList); - while ($enum1.moveNext()) { - var ee = $enum1.current; - var listID = 0; - if (ee.a < 2.5) { - listID = 0; - } - else if (ee.a < 2.83) { - listID = 1; - } - else if (ee.a < 2.96) { - listID = 2; - } - else if (ee.a < 3.3) { - listID = 3; - } - else if (ee.a < 5) { - listID = 4; - } - else if (ee.a < 10) { - listID = 5; - } - else { - listID = 6; - } - var vert = new KeplerVertex(); - vert.fill(ee); - lists[listID].push(vert); - } - for (var i = 0; i < 7; i++) { - mpcVertexBufferTemp[i] = KeplerVertexBuffer.create(lists[i]); - mpcVertexBufferTemp[i].unlock(); - } - MinorPlanets._mpcVertexBuffer = mpcVertexBufferTemp; - } - } - finally { - } - }; - var MinorPlanets$ = { - - }; - - - // wwtlib.Place - - function Place() { - this._camParams = CameraParameters.create(0, 0, -1, 0, 0, 100); - this._location3d = Vector3d.create(0, 0, 0); - this.htmlDescription = ''; - this._constellation = ''; - this._classification = 1048576; - this._type = 2; - this._magnitude = 0; - this._distnace = 0; - this.angularSize = 60; - this.annotation = ''; - this._thumbNail = null; - this._studyImageset = null; - this._backgroundImageSet = null; - this._searchDistance = 0; - this._elevation = 50; - } - Place.create = function (name, lat, lng, classification, constellation, type, zoomFactor) { - var temp = new Place(); - temp.set_zoomLevel(zoomFactor); - temp._constellation = constellation; - temp._name = name; - if (type === 2 || type === 4) { - temp._camParams.set_RA(lng); - } - else { - temp.set_lng(lng); - } - temp.set_lat(lat); - temp.set_classification(classification); - temp.set_type(type); - return temp; - }; - Place.createCameraParams = function (name, camParams, classification, constellation, type, target) { - var temp = new Place(); - temp._constellation = constellation; - temp._name = name; - temp.set_classification(classification); - temp._camParams = camParams; - temp.set_type(type); - temp.set_target(target); - return temp; - }; - Place._fromXml = function (place) { - var newPlace = new Place(); - newPlace._name = place.attributes.getNamedItem('Name').nodeValue; - if (place.attributes.getNamedItem('MSRComponentId') != null && place.attributes.getNamedItem('Permission') != null && place.attributes.getNamedItem('Url') != null) { - newPlace.set_url(place.attributes.getNamedItem('Url').nodeValue); - newPlace.set_thumbnailUrl(place.attributes.getNamedItem('Thumbnail').nodeValue); - return newPlace; - } - if (place.attributes.getNamedItem('DataSetType') != null) { - newPlace._type = Enums.parse('ImageSetType', place.attributes.getNamedItem('DataSetType').nodeValue); - } - if (newPlace.get_type() === 2) { - newPlace._camParams.set_RA(parseFloat(place.attributes.getNamedItem('RA').nodeValue)); - newPlace._camParams.set_dec(parseFloat(place.attributes.getNamedItem('Dec').nodeValue)); - } - else { - newPlace.set_lat(parseFloat(place.attributes.getNamedItem('Lat').nodeValue)); - newPlace.set_lng(parseFloat(place.attributes.getNamedItem('Lng').nodeValue)); - } - if (place.attributes.getNamedItem('Constellation') != null) { - newPlace._constellation = place.attributes.getNamedItem('Constellation').nodeValue; - } - if (place.attributes.getNamedItem('Classification') != null) { - newPlace._classification = Enums.parse('Classification', place.attributes.getNamedItem('Classification').nodeValue); - } - if (place.attributes.getNamedItem('Magnitude') != null) { - newPlace._magnitude = parseFloat(place.attributes.getNamedItem('Magnitude').nodeValue); - } - if (place.attributes.getNamedItem('AngularSize') != null) { - newPlace.angularSize = parseFloat(place.attributes.getNamedItem('AngularSize').nodeValue); - } - if (place.attributes.getNamedItem('ZoomLevel') != null) { - newPlace.set_zoomLevel(parseFloat(place.attributes.getNamedItem('ZoomLevel').nodeValue)); - } - if (place.attributes.getNamedItem('Rotation') != null) { - newPlace._camParams.rotation = parseFloat(place.attributes.getNamedItem('Rotation').nodeValue); - } - if (place.attributes.getNamedItem('Annotation') != null) { - newPlace.annotation = place.attributes.getNamedItem('Annotation').nodeValue; - } - if (place.attributes.getNamedItem('Angle') != null) { - newPlace._camParams.angle = parseFloat(place.attributes.getNamedItem('Angle').nodeValue); - } - if (place.attributes.getNamedItem('Opacity') != null) { - newPlace._camParams.opacity = parseFloat(place.attributes.getNamedItem('Opacity').nodeValue); - } - else { - newPlace._camParams.opacity = 100; - } - newPlace.set_target(65536); - if (place.attributes.getNamedItem('Target') != null) { - newPlace.set_target(Enums.parse('SolarSystemObjects', place.attributes.getNamedItem('Target').nodeValue)); - } - if (place.attributes.getNamedItem('ViewTarget') != null) { - newPlace._camParams.viewTarget = Vector3d.parse(place.attributes.getNamedItem('ViewTarget').nodeValue); - } - if (place.attributes.getNamedItem('TargetReferenceFrame') != null) { - newPlace._camParams.targetReferenceFrame = place.attributes.getNamedItem('TargetReferenceFrame').nodeValue; - } - var descriptionNode = Util.selectSingleNode(place, 'Description'); - if (descriptionNode != null) { - newPlace.htmlDescription = Util.getInnerText(descriptionNode); - } - var backgroundImageSet = Util.selectSingleNode(place, 'BackgroundImageSet'); - if (backgroundImageSet != null) { - var imageSet = Util.selectSingleNode(backgroundImageSet, 'ImageSet'); - newPlace._backgroundImageSet = Imageset.fromXMLNode(imageSet); - } - var study = Util.selectSingleNode(place, 'ForegroundImageSet'); - if (study != null) { - var imageSet = Util.selectSingleNode(study, 'ImageSet'); - newPlace._studyImageset = Imageset.fromXMLNode(imageSet); - } - study = Util.selectSingleNode(place, 'ImageSet'); - if (study != null) { - newPlace._studyImageset = Imageset.fromXMLNode(study); - } - return newPlace; - }; - Place._properCaps = function (name) { - var list = name.split(' '); - var ProperName = ''; - var $enum1 = ss.enumerate(list); - while ($enum1.moveNext()) { - var part = $enum1.current; - ProperName = ProperName + part.substr(0, 1).toUpperCase() + ((part.length > 1) ? part.substr(1).toLowerCase() : '') + ' '; - } - return ss.trim(ProperName); - }; - var Place$ = { - get_tag: function () { - return this._tag; - }, - set_tag: function (value) { - this._tag = value; - return value; - }, - get_url: function () { - return this._url; - }, - set_url: function (value) { - this._url = value; - return value; - }, - get_thumbnail: function () { - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - return value; - }, - get_name: function () { - return this.get_names()[0]; - }, - get_names: function () { - if (ss.emptyString(this._name)) { - return ''.split(';'); - } - return this._name.split(';'); - }, - set_names: function (value) { - this._name = UiTools.getNamesStringFromArray(value); - return value; - }, - get_camParams: function () { - if (this.get_classification() === 536870912 && this._camParams.target !== 20) { - var raDec = Planets.getPlanetLocation(this.get_name()); - this._camParams.set_RA(raDec.RA); - this._camParams.set_dec(raDec.dec); - this._distnace = raDec.distance; - } - return this._camParams; - }, - set_camParams: function (value) { - this._camParams = value; - return value; - }, - updatePlanetLocation: function (jNow) { - this._camParams.viewTarget = Planets.getPlanet3dLocationJD(this.get_target(), jNow); - if (this.get_target() !== 65536 && this.get_target() !== 20) { - this._camParams.viewTarget = Planets.getPlanetTargetPoint(this.get_target(), this.get_lat(), this.get_lng(), jNow); - } - }, - get_location3d: function () { - if (this.get_classification() === 536870912 || (!this._location3d.x && !this._location3d.y && !this._location3d.z)) { - this._location3d = Coordinates.raDecTo3d(this.get_RA(), this.get_dec()); - } - return this._location3d; - }, - get_lat: function () { - return this.get_camParams().lat; - }, - set_lat: function (value) { - this._camParams.lat = value; - return value; - }, - get_lng: function () { - return this.get_camParams().lng; - }, - set_lng: function (value) { - this._camParams.lng = value; - return value; - }, - get_opacity: function () { - return this.get_camParams().opacity; - }, - set_opacity: function (value) { - this._camParams.opacity = value; - return value; - }, - get_constellation: function () { - return this._constellation; - }, - set_constellation: function (value) { - this._constellation = value; - return value; - }, - get_classification: function () { - return this._classification; - }, - set_classification: function (value) { - this._classification = value; - return value; - }, - get_type: function () { - return this._type; - }, - set_type: function (value) { - this._type = value; - return value; - }, - get_magnitude: function () { - return this._magnitude; - }, - set_magnitude: function (value) { - this._magnitude = value; - return value; - }, - get_distance: function () { - return this._distnace; - }, - set_distance: function (value) { - this._distnace = value; - return value; - }, - get_zoomLevel: function () { - return this.get_camParams().zoom; - }, - set_zoomLevel: function (value) { - this._camParams.zoom = value; - return value; - }, - get_annotation: function () { - return this.annotation; - }, - set_annotation: function (value) { - this.annotation = value; - return value; - }, - get_studyImageset: function () { - return this._studyImageset; - }, - set_studyImageset: function (value) { - this._studyImageset = value; - return value; - }, - get_backgroundImageset: function () { - return this._backgroundImageSet; - }, - set_backgroundImageset: function (value) { - if (value != null) { - this.set_type(value.get_dataSetType()); - } - this._backgroundImageSet = value; - return value; - }, - get_searchDistance: function () { - return this._searchDistance; - }, - set_searchDistance: function (value) { - this._searchDistance = value; - return value; - }, - get_elevation: function () { - return this._elevation; - }, - set_elevation: function (value) { - this._elevation = value; - return value; - }, - get_thumbnailUrl: function () { - if (ss.emptyString(this._thumbnailField)) { - if (this._studyImageset != null && !ss.emptyString(this._studyImageset.get_thumbnailUrl())) { - return this._studyImageset.get_thumbnailUrl(); - } - if (this._backgroundImageSet != null && !ss.emptyString(this._backgroundImageSet.get_thumbnailUrl())) { - return this._backgroundImageSet.get_thumbnailUrl(); - } - var name = this.get_name(); - if (name.indexOf(';') > -1) { - name = name.substr(0, name.indexOf(';')); - } - if (this.get_classification() === 1 || WWTControl.singleton.freestandingMode) { - return URLHelpers.singleton.engineAssetUrl('thumb_star.jpg'); - } - return URLHelpers.singleton.coreStaticUrl('wwtweb/thumbnail.aspx?name=' + name.toLowerCase()); - } - return this._thumbnailField; - }, - set_thumbnailUrl: function (value) { - this._thumbnailField = value; - return value; - }, - get_RA: function () { - return this.get_camParams().get_RA(); - }, - set_RA: function (value) { - this._camParams.set_RA(value); - return value; - }, - get_dec: function () { - return this.get_camParams().get_dec(); - }, - set_dec: function (value) { - this._camParams.set_dec(value); - return value; - }, - toString: function () { - return this._name; - }, - _saveToXml: function (xmlWriter, elementName) { - xmlWriter._writeStartElement(elementName); - xmlWriter._writeAttributeString('Name', this._name); - xmlWriter._writeAttributeString('DataSetType', Enums.toXml('ImageSetType', this._type)); - if (this.get_type() === 2) { - xmlWriter._writeAttributeString('RA', this._camParams.get_RA().toString()); - xmlWriter._writeAttributeString('Dec', this._camParams.get_dec().toString()); - } - else { - xmlWriter._writeAttributeString('Lat', this.get_lat().toString()); - xmlWriter._writeAttributeString('Lng', this.get_lng().toString()); - } - xmlWriter._writeAttributeString('Constellation', this._constellation); - xmlWriter._writeAttributeString('Classification', Enums.toXml('Classification', this._classification)); - xmlWriter._writeAttributeString('Magnitude', this._magnitude.toString()); - xmlWriter._writeAttributeString('Distance', this._distnace.toString()); - xmlWriter._writeAttributeString('AngularSize', this.angularSize.toString()); - xmlWriter._writeAttributeString('ZoomLevel', this.get_zoomLevel().toString()); - xmlWriter._writeAttributeString('Rotation', this._camParams.rotation.toString()); - xmlWriter._writeAttributeString('Angle', this._camParams.angle.toString()); - xmlWriter._writeAttributeString('Opacity', this._camParams.opacity.toString()); - xmlWriter._writeAttributeString('Target', Enums.toXml('SolarSystemObjects', this.get_target())); - xmlWriter._writeAttributeString('ViewTarget', this._camParams.viewTarget.toString()); - xmlWriter._writeAttributeString('TargetReferenceFrame', this._camParams.targetReferenceFrame); - xmlWriter._writeStartElement('Description'); - xmlWriter._writeCData(this.htmlDescription); - xmlWriter._writeEndElement(); - if (this._backgroundImageSet != null) { - xmlWriter._writeStartElement('BackgroundImageSet'); - Imageset.saveToXml(xmlWriter, this._backgroundImageSet, ''); - xmlWriter._writeEndElement(); - } - if (this._studyImageset != null) { - Imageset.saveToXml(xmlWriter, this._studyImageset, ''); - } - xmlWriter._writeEndElement(); - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_isImage: function () { - return this._studyImageset != null || this._backgroundImageSet != null; - }, - get_isTour: function () { - return false; - }, - get_isFolder: function () { - return false; - }, - get_children: function () { - return []; - }, - get_readOnly: function () { - return true; - }, - get_target: function () { - return this._camParams.target; - }, - set_target: function (value) { - this._camParams.target = value; - return value; - }, - get_isCloudCommunityItem: function () { - return false; - } - }; - - - // wwtlib.KeplerianElements - - function KeplerianElements() { - this.a = 0; - this.e = 0; - this.ea = 0; - } - var KeplerianElements$ = { - - }; - - - // wwtlib.BodyAngles - - function BodyAngles(poleRa, poleDec, primeMeridian, rotationRate) { - this.poleDec = 0; - this.poleRa = 0; - this.primeMeridian = 0; - this.rotationRate = 0; - this.poleDec = poleDec; - this.poleRa = poleRa; - this.primeMeridian = primeMeridian; - this.rotationRate = rotationRate; - } - var BodyAngles$ = { - - }; - - - // wwtlib.Planets - - function Planets() { - } - Planets.loadPlanetTexture = function (url) { - var texture = new Texture(); - texture.load(url); - return texture; - }; - Planets.getPlanet3dLocation = function (target) { - try { - if (target < 21) { - return Planets._planet3dLocations[target].copy(); - } - } - catch ($e1) { - } - return Vector3d.create(0, 0, 0); - }; - Planets.getPlanet3dSufaceAltitude = function (target) { - try { - if (target < 21) { - return Planets.getAdjustedPlanetRadius(target); - } - } - catch ($e1) { - } - return 0; - }; - Planets.getPlanetTargetPoint = function (target, lat, lng, jNow) { - var temp; - if (!jNow) { - temp = Planets.getPlanet3dLocation(target); - } - else { - temp = Planets.getPlanet3dLocationJD(target, jNow); - } - temp.add(Coordinates.raDecTo3dAu((lng / 15) + 6, lat, Planets.getPlanet3dSufaceAltitude(target))); - return temp; - }; - Planets.getPlanet3dLocationJD = function (target, jNow) { - try { - var result = new Vector3d(); - var centerRaDec = AstroCalc.getPlanet(jNow, 0, 0, 0, -6378149); - var center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); - if (target === 19) { - result = Vector3d.create(-center.x, -center.y, -center.z); - } - else { - var planet = AstroCalc.getPlanet(jNow, target, 0, 0, -6378149); - result = Coordinates.raDecTo3dAu(planet.RA, planet.dec, planet.distance); - result.subtract(center); - } - result.rotateX(Coordinates.meanObliquityOfEcliptic(jNow) * Planets.RC); - if (Settings.get_active().get_solarSystemScale() !== 1) { - switch (target) { - case 9: - var parent = Planets.getPlanet3dLocationJD(19, jNow); - result.subtract(parent); - result.multiply(Settings.get_active().get_solarSystemScale() / 2); - result.add(parent); - break; - case 10: - case 11: - case 12: - case 13: - var parent = Planets.getPlanet3dLocationJD(4, jNow); - result.subtract(parent); - result.multiply(Settings.get_active().get_solarSystemScale()); - result.add(parent); - break; - default: - break; - } - } - return result; - } - catch ($e1) { - return Vector3d.create(0, 0, 0); - } - }; - Planets.getPlanetLocation = function (name) { - var id = Planets.getPlanetIDFromName(name); - if (Planets._planetLocations != null) { - return Planets._planetLocations[id]; - } - else { - return AstroCalc.getPlanet(SpaceTimeController.get_jNow(), id, SpaceTimeController.get_location().get_lat(), SpaceTimeController.get_location().get_lng(), SpaceTimeController.get_altitude()); - } - }; - Planets.getPlanetLocationJD = function (name, jNow) { - var id = Planets.getPlanetIDFromName(name); - return AstroCalc.getPlanet(jNow, id, SpaceTimeController.get_location().get_lat(), SpaceTimeController.get_location().get_lng(), SpaceTimeController.get_altitude()); - }; - Planets.getPlanetIDFromName = function (planetName) { - switch (planetName) { - case 'Sun': - return 0; - case 'Mercury': - return 1; - case 'Venus': - return 2; - case 'Mars': - return 3; - case 'Jupiter': - return 4; - case 'Saturn': - return 5; - case 'Uranus': - return 6; - case 'Neptune': - return 7; - case 'Pluto': - return 8; - case 'Moon': - return 9; - case 'Io': - return 10; - case 'Europa': - return 11; - case 'Ganymede': - return 12; - case 'Callisto': - return 13; - case 'Earth': - return 19; - case 'IoShadow': - return 14; - case 'EuropaShadow': - return 15; - case 'GanymedeShadow': - return 16; - case 'CallistoShadow': - return 17; - case 'SunEclipsed': - return 18; - case 'Custom': - return 20; - case 'Undefined': - return 65536; - default: - return -1; - } - }; - Planets.getImageSetNameNameFrom3dId = function (id) { - switch (id) { - case 0: - return 'Sun'; - case 1: - return 'Mercury'; - case 2: - return 'Venus'; - case 3: - return 'Visible Imagery'; - case 4: - return 'Jupiter'; - case 5: - return 'Saturn'; - case 6: - return 'Uranus'; - case 7: - return 'Neptune'; - case 8: - return 'Pluto'; - case 9: - return 'Moon'; - case 10: - return 'Io (Jupiter)'; - case 11: - return 'Europa (Jupiter)'; - case 12: - return 'Ganymede (Jupiter)'; - case 13: - return 'Callisto (Jupiter)'; - case 19: - return 'Bing Maps Aerial'; - default: - return ''; - } - }; - Planets.getNameFrom3dId = function (id) { - switch (id) { - case 0: - return 'Sun'; - case 1: - return 'Mercury'; - case 2: - return 'Venus'; - case 3: - return 'Mars'; - case 4: - return 'Jupiter'; - case 5: - return 'Saturn'; - case 6: - return 'Uranus'; - case 7: - return 'Neptune'; - case 8: - return 'Pluto'; - case 9: - return 'Moon'; - case 10: - return 'Io'; - case 11: - return 'Europa'; - case 12: - return 'Ganymede'; - case 13: - return 'Callisto'; - case 19: - return 'Earth'; - default: - return ''; - } - }; - Planets.updatePlanetLocations = function (threeDee) { - Planets._jNow = SpaceTimeController.get_jNow(); - if (threeDee) { - Planets.updateOrbits(0); - } - if (Planets._planetDiameters == null) { - Planets._planetDiameters = new Array(20); - Planets._planetDiameters[0] = 0.009291568; - Planets._planetDiameters[1] = 3.25794793734425E-05; - Planets._planetDiameters[2] = 8.08669220531394E-05; - Planets._planetDiameters[3] = 4.53785605596396E-05; - Planets._planetDiameters[4] = 0.000954501; - Planets._planetDiameters[5] = 0.000802173; - Planets._planetDiameters[6] = 0.000339564; - Planets._planetDiameters[7] = 0.000324825; - Planets._planetDiameters[8] = 1.52007379777805E-05; - Planets._planetDiameters[9] = 2.32084653538149E-05; - Planets._planetDiameters[10] = 2.43519298386342E-05; - Planets._planetDiameters[11] = 2.08692629580609E-05; - Planets._planetDiameters[12] = 3.51742670356556E-05; - Planets._planetDiameters[13] = 3.22263666626559E-05; - Planets._planetDiameters[14] = 2.43519298386342E-05; - Planets._planetDiameters[15] = 2.08692629580609E-05; - Planets._planetDiameters[16] = 3.51742670356556E-05; - Planets._planetDiameters[17] = 3.22263666626559E-05; - Planets._planetDiameters[18] = 0.009291568 * 2; - Planets._planetDiameters[19] = 8.55626412117809E-05; - } - if (Planets.planetColors == null) { - var lightYellow = Color.fromArgb(255, 255, 255, 221); - var orangeRed = Color.fromArgb(255, 255, 68, 0); - Planets.planetColors = new Array(20); - Planets.planetColors[0] = Colors.get_yellow(); - Planets.planetColors[1] = Colors.get_white(); - Planets.planetColors[2] = lightYellow; - Planets.planetColors[3] = orangeRed; - Planets.planetColors[4] = Color.fromArgb(255, 255, 165, 0); - Planets.planetColors[5] = Color.fromArgb(255, 184, 134, 11); - Planets.planetColors[6] = Color.fromArgb(255, 173, 216, 230); - Planets.planetColors[7] = Colors.get_blue(); - Planets.planetColors[8] = Colors.get_white(); - Planets.planetColors[9] = Colors.get_white(); - Planets.planetColors[10] = Colors.get_white(); - Planets.planetColors[11] = Colors.get_white(); - Planets.planetColors[12] = Colors.get_white(); - Planets.planetColors[13] = Colors.get_white(); - Planets.planetColors[14] = Colors.get_black(); - Planets.planetColors[15] = Colors.get_black(); - Planets.planetColors[16] = Colors.get_black(); - Planets.planetColors[17] = Colors.get_black(); - Planets.planetColors[18] = Colors.get_white(); - Planets.planetColors[19] = Color.fromArgb(255, 173, 216, 230); - } - if (Planets._planetTilts == null) { - Planets._planetTilts = new Array(20); - Planets._planetTilts[0] = 0; - Planets._planetTilts[1] = 0.01; - Planets._planetTilts[2] = 177.4; - Planets._planetTilts[3] = 25.19; - Planets._planetTilts[4] = 3.13; - Planets._planetTilts[5] = 26.73; - Planets._planetTilts[6] = 97.77; - Planets._planetTilts[7] = 28.32; - Planets._planetTilts[8] = 119.61; - Planets._planetTilts[9] = 23.439; - Planets._planetTilts[10] = 2.21; - Planets._planetTilts[11] = 0; - Planets._planetTilts[12] = -0.33; - Planets._planetTilts[13] = 0; - Planets._planetTilts[14] = 0; - Planets._planetTilts[15] = 0; - Planets._planetTilts[16] = 0; - Planets._planetTilts[17] = 0; - Planets._planetTilts[18] = 0; - Planets._planetTilts[19] = 23.5; - } - Planets._planetTilts[19] = Planets._obliquity / Planets.RC; - if (Planets.planetRotationPeriod == null) { - Planets.planetRotationPeriod = new Array(20); - Planets.planetRotationPeriod[0] = 25.37995; - Planets.planetRotationPeriod[1] = 58.6462; - Planets.planetRotationPeriod[2] = -243.0187; - Planets.planetRotationPeriod[3] = 1.02595675; - Planets.planetRotationPeriod[4] = 0.41007; - Planets.planetRotationPeriod[5] = 0.426; - Planets.planetRotationPeriod[6] = -0.71833; - Planets.planetRotationPeriod[7] = 0.67125; - Planets.planetRotationPeriod[8] = -6.38718; - Planets.planetRotationPeriod[9] = 27.3; - Planets.planetRotationPeriod[10] = 1.769137786; - Planets.planetRotationPeriod[11] = 3.551; - Planets.planetRotationPeriod[12] = 7.155; - Planets.planetRotationPeriod[13] = 16.69; - Planets.planetRotationPeriod[14] = 0; - Planets.planetRotationPeriod[15] = 0; - Planets.planetRotationPeriod[16] = 0; - Planets.planetRotationPeriod[17] = 0; - Planets.planetRotationPeriod[18] = 0; - Planets.planetRotationPeriod[19] = 0.99726968; - } - if (Planets._planetScales == null) { - Planets._planetScales = new Array(20); - } - if (Planets._planet3dLocations == null) { - Planets._planet3dLocations = new Array(20); - } - if (Settings.get_active().get_actualPlanetScale()) { - Planets._planetScales[0] = 0.5; - Planets._planetScales[1] = 0.25; - Planets._planetScales[2] = 0.25; - Planets._planetScales[3] = 0.25; - Planets._planetScales[4] = 0.25; - Planets._planetScales[5] = 0.5; - Planets._planetScales[6] = 0.25; - Planets._planetScales[7] = 0.25; - Planets._planetScales[8] = 0.25; - Planets._planetScales[9] = 0.25; - Planets._planetScales[10] = 0.25; - Planets._planetScales[11] = 0.25; - Planets._planetScales[12] = 0.25; - Planets._planetScales[13] = 0.25; - Planets._planetScales[14] = 0.25; - Planets._planetScales[15] = 0.25; - Planets._planetScales[16] = 0.25; - Planets._planetScales[17] = 0.25; - Planets._planetScales[18] = 0.5; - Planets._planetScales[19] = 0.25; - } - else { - for (var i = 0; i < 20; i++) { - if (i < 10) { - Planets._planetScales[i] = 0.25; - } - else { - Planets._planetScales[i] = 0.1; - } - } - Planets._planetScales[0] = 0.5; - Planets._planetScales[5] = 0.5; - Planets._planetScales[18] = 0.5; - } - Planets._planetDrawOrder = {}; - Planets._planetLocations = new Array(20); - var center = new Vector3d(); - var planetCenter = 0; - if (planetCenter > -1) { - var centerRaDec = AstroCalc.getPlanet(Planets._jNow, planetCenter, (threeDee) ? 0 : SpaceTimeController.get_location().get_lat(), (threeDee) ? 0 : SpaceTimeController.get_location().get_lng(), (threeDee) ? -6378149 : SpaceTimeController.get_altitude()); - center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); - } - Planets._planet3dLocations[19] = Vector3d.create(-center.x, -center.y, -center.z); - Planets._planet3dLocations[19].rotateX(Planets._obliquity); - for (var i = 0; i < 18; i++) { - Planets._planetLocations[i] = AstroCalc.getPlanet(Planets._jNow, i, (threeDee) ? 0 : SpaceTimeController.get_location().get_lat(), (threeDee) ? 0 : SpaceTimeController.get_location().get_lng(), (threeDee) ? -6378149 : SpaceTimeController.get_altitude()); - Planets._planet3dLocations[i] = Coordinates.raDecTo3dAu(Planets._planetLocations[i].RA, Planets._planetLocations[i].dec, Planets._planetLocations[i].distance); - Planets._planet3dLocations[i].subtract(center); - Planets._planet3dLocations[i].rotateX(Planets._obliquity); - if (Settings.get_active().get_actualPlanetScale()) { - Planets._planetScales[i] = (2 * Math.atan(0.5 * (Planets._planetDiameters[i] / Planets._planetLocations[i].distance))) / Math.PI * 180; - } - if (Settings.get_active().get_solarSystemScale() !== 1) { - var id = i; - switch (id) { - case 9: - var parent = Planets._planet3dLocations[19]; - Planets._planet3dLocations[i].subtract(parent); - Planets._planet3dLocations[i].multiply(Settings.get_active().get_solarSystemScale() / 2); - Planets._planet3dLocations[i].add(parent); - break; - case 10: - case 11: - case 12: - case 13: - var parent = Planets._planet3dLocations[4]; - Planets._planet3dLocations[i].subtract(parent); - Planets._planet3dLocations[i].multiply(Settings.get_active().get_solarSystemScale()); - Planets._planet3dLocations[i].add(parent); - break; - default: - break; - } - } - var finalDistance = -Planets._planetLocations[i].distance; - while (ss.keyExists(Planets._planetDrawOrder, finalDistance)) { - finalDistance += 1E-10; - } - Planets._planetDrawOrder[finalDistance] = i; - } - Planets._planetLocations[18] = Planets._planetLocations[0]; - Planets._planetScales[0] *= 2; - Planets._planetScales[18] = Planets._planetScales[0]; - Planets._planetScales[5] = Planets._planetScales[5] * 2; - Planets._lastUpdate = SpaceTimeController.get_now(); - }; - Planets.planetsReady = function () { - }; - Planets.updateOrbits = function (planetCenter) { - try { - Planets._obliquity = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) * Planets.RC; - if (planetCenter !== Planets._lastPlanetCenterID) { - Planets._orbits = null; - } - Planets._lastPlanetCenterID = planetCenter; - if (Planets._orbits == null) { - if (planetCenter < 0) { - Planets._eclipticTilt = Matrix3d.get_identity(); - } - else { - Planets._eclipticTilt = Matrix3d.get_identity(); - Planets._eclipticTilt = Matrix3d._rotationX(Planets._obliquity); - } - if (Planets.planetOrbitalYears == null) { - Planets.planetOrbitalYears = new Array(20); - Planets.planetOrbitalYears[0] = 1; - Planets.planetOrbitalYears[1] = 0.241; - Planets.planetOrbitalYears[2] = 0.615; - Planets.planetOrbitalYears[3] = 1.881; - Planets.planetOrbitalYears[4] = 11.87; - Planets.planetOrbitalYears[5] = 29.45; - Planets.planetOrbitalYears[6] = 84.07; - Planets.planetOrbitalYears[7] = 164.9; - Planets.planetOrbitalYears[8] = 248.1; - Planets.planetOrbitalYears[9] = 27.3 / 365.25; - Planets.planetOrbitalYears[10] = 16.6890184 / 365.25; - Planets.planetOrbitalYears[11] = 3.551181 / 365.25; - Planets.planetOrbitalYears[12] = 7.15455296 / 365.25; - Planets.planetOrbitalYears[13] = 16.6890184 / 365.25; - Planets.planetOrbitalYears[19] = 1; - } - if (!Planets.readOrbits()) { - Planets._orbits = new Array(20); - for (var i = 1; i < 20; i++) { - Planets._orbits[i] = new Array(Planets._orbitalSampleRate); - if (i < 9 || i === 19) { - for (var j = 0; j < Planets._orbitalSampleRate; j++) { - var centerId = planetCenter; - var now = Planets._jNow + ((Planets.planetOrbitalYears[i] * 365.25 / Planets._orbitalSampleRate) * (j - (Planets._orbitalSampleRate / 2))); - var center = new Vector3d(); - if (i === 9) { - centerId = -1; - } - else if (i > 9 && i < 14) { - centerId = 4; - } - if (centerId > -1) { - var centerRaDec = AstroCalc.getPlanet(now, centerId, 0, 0, -6378149); - center = Coordinates.raDecTo3dAu(centerRaDec.RA, centerRaDec.dec, centerRaDec.distance); - } - if (i !== 19) { - var planetRaDec = AstroCalc.getPlanet(now, i, 0, 0, -6378149); - Planets._orbits[i][j] = Coordinates.raDecTo3dAu(planetRaDec.RA, planetRaDec.dec, planetRaDec.distance); - Planets._orbits[i][j].subtract(center); - } - else { - Planets._orbits[i][j] = Vector3d.create(-center.x, -center.y, -center.z); - } - Planets._orbits[i][j].rotateX(Planets._obliquity); - } - Planets._orbits[i][Planets._orbitalSampleRate - 1] = Planets._orbits[i][0]; - } - } - Planets.dumpOrbitsFile(); - } - } - } - finally { - } - }; - Planets.readOrbits = function () { - return false; - }; - Planets.dumpOrbitsFile = function () { - }; - Planets.drawPlanets = function (renderContext, opacity) { - if (Planets._planetTextures == null) { - Planets._loadPlanetTextures(); - } - var elong = Planets._geocentricElongation(Planets._planetLocations[9].RA, Planets._planetLocations[9].dec, Planets._planetLocations[0].RA, Planets._planetLocations[0].dec); - var raDif = Planets._planetLocations[9].RA - Planets._planetLocations[0].RA; - if (Planets._planetLocations[9].RA < Planets._planetLocations[0].RA) { - raDif += 24; - } - var phaseAngle = Planets._phaseAngle(elong, Planets._planetLocations[9].distance, Planets._planetLocations[0].distance); - var limbAngle = Planets._positionAngle(Planets._planetLocations[9].RA, Planets._planetLocations[9].dec, Planets._planetLocations[0].RA, Planets._planetLocations[0].dec); - if (raDif < 12) { - phaseAngle += 180; - } - var dista = (Math.abs(Planets._planetLocations[9].RA - Planets._planetLocations[0].RA) * 15) * Math.cos(Coordinates.degreesToRadians(Planets._planetLocations[0].dec)); - var distb = Math.abs(Planets._planetLocations[9].dec - Planets._planetLocations[0].dec); - var sunMoonDist = Math.sqrt(dista * dista + distb * distb); - var eclipse = false; - var coronaOpacity = 0; - var moonEffect = (Planets._planetScales[9] / 2 - sunMoonDist); - var darkLimb = Math.min(32, ss.truncate((sunMoonDist * 32))); - if (moonEffect > (Planets._planetScales[0] / 4)) { - eclipse = true; - coronaOpacity = Math.min(1, (moonEffect - (Planets._planetScales[0] / 2)) / 0.001); - Planets._drawPlanet(renderContext, 18, coronaOpacity); - } - var $enum1 = ss.enumerate(ss.keys(Planets._planetDrawOrder)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var planetId = Planets._planetDrawOrder[key]; - Planets._drawPlanet(renderContext, planetId, 1); - } - return true; - }; - Planets._loadPlanetTextures = function () { - var baseUrl = URLHelpers.singleton.engineAssetUrl(''); - Planets._planetTextures = new Array(20); - Planets._planetTextures[0] = Planets.loadPlanetTexture(baseUrl + 'sun.png'); - Planets._planetTextures[1] = Planets.loadPlanetTexture(baseUrl + 'mercury.png'); - Planets._planetTextures[2] = Planets.loadPlanetTexture(baseUrl + 'venus.png'); - Planets._planetTextures[3] = Planets.loadPlanetTexture(baseUrl + 'mars.png'); - Planets._planetTextures[4] = Planets.loadPlanetTexture(baseUrl + 'jupiter.png'); - Planets._planetTextures[5] = Planets.loadPlanetTexture(baseUrl + 'saturn.png'); - Planets._planetTextures[6] = Planets.loadPlanetTexture(baseUrl + 'uranus.png'); - Planets._planetTextures[7] = Planets.loadPlanetTexture(baseUrl + 'neptune.png'); - Planets._planetTextures[8] = Planets.loadPlanetTexture(baseUrl + 'pluto.png'); - Planets._planetTextures[9] = Planets.loadPlanetTexture(baseUrl + 'moon.png'); - Planets._planetTextures[10] = Planets.loadPlanetTexture(baseUrl + 'io.png'); - Planets._planetTextures[11] = Planets.loadPlanetTexture(baseUrl + 'europa.png'); - Planets._planetTextures[12] = Planets.loadPlanetTexture(baseUrl + 'ganymede.png'); - Planets._planetTextures[13] = Planets.loadPlanetTexture(baseUrl + 'callisto.png'); - Planets._planetTextures[14] = Planets.loadPlanetTexture(baseUrl + 'moonshadow.png'); - Planets._planetTextures[15] = Planets.loadPlanetTexture(baseUrl + 'moonshadow.png'); - Planets._planetTextures[16] = Planets.loadPlanetTexture(baseUrl + 'moonshadow.png'); - Planets._planetTextures[17] = Planets.loadPlanetTexture(baseUrl + 'moonshadow.png'); - Planets._planetTextures[18] = Planets.loadPlanetTexture(baseUrl + 'sunCorona.png'); - Planets._planetTextures[19] = Planets.loadPlanetTexture(baseUrl + 'earth.png'); - }; - Planets.drawPlanets3D = function (renderContext, opacity, centerPoint) { - Planets.initPlanetResources(renderContext); - var distss = UiTools.solarSystemToMeters(renderContext.get_solarSystemCameraDistance()); - var moonFade = Math.min(1, Math.max(Util.log10(distss) - 7.3, 0)); - var fade = Math.min(1, Math.max(Util.log10(distss) - 8.6, 0)); - if (Settings.get_active().get_solarSystemOrbits() && fade > 0) { - for (var ii = 1; ii < 10; ii++) { - var id = ii; - if (ii === 9) { - id = 19; - } - var angle = Math.atan2(Planets._planet3dLocations[id].z, Planets._planet3dLocations[id].x); - Planets._drawSingleOrbit(renderContext, Planets.planetColors[id], id, centerPoint, angle, Planets._planet3dLocations[id], fade); - } - var mid = 9; - Planets._drawSingleOrbit(renderContext, Planets.planetColors[mid], mid, centerPoint, 0, Planets._planet3dLocations[mid], fade); - } - ss.clearKeys(Planets._drawOrder); - var camera = renderContext.cameraPosition.copy(); - for (var planetId = 0; planetId < 14; planetId++) { - if (!(Settings.get_active().get_solarSystemLighting() && Planets._planetLocations[planetId].eclipsed)) { - var distVector = Vector3d.subtractVectors(camera, Vector3d.subtractVectors(Planets._planet3dLocations[planetId], centerPoint)); - if (!ss.keyExists(Planets._drawOrder, distVector.length())) { - Planets._drawOrder[distVector.length()] = planetId; - } - } - } - var distVectorEarth = Vector3d.subtractVectors(camera, Vector3d.subtractVectors(Planets._planet3dLocations[19], centerPoint)); - if (!ss.keyExists(Planets._drawOrder, distVectorEarth.length())) { - Planets._drawOrder[distVectorEarth.length()] = 19; - } - var $enum1 = ss.enumerate(ss.keys(Planets._drawOrder)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var planetId = Planets._drawOrder[key]; - Planets._drawPlanet3d(renderContext, planetId, centerPoint); - } - return true; - }; - Planets.getPlanetOrientationAtEpoch = function (planetID) { - var m = Matrix3d.get_identity(); - var obliquityOfEcliptic = 23.4392794; - if (planetID === 19) { - m._multiply(Matrix3d._rotationX(obliquityOfEcliptic * Planets.RC)); - } - else { - m._multiply(Matrix3d._rotationX(-90 * Planets.RC)); - m._multiply(Matrix3d._rotationZ((180 + Planets._planetAngles[planetID].primeMeridian) * Planets.RC)); - m._multiply(Matrix3d._rotationX((90 - Planets._planetAngles[planetID].poleDec) * Planets.RC)); - m._multiply(Matrix3d._rotationZ((Planets._planetAngles[planetID].poleRa - 90) * Planets.RC)); - m._multiply(Matrix3d._rotationX(obliquityOfEcliptic * Planets.RC)); - m._multiply(Matrix3d._rotationX(90 * Planets.RC)); - } - return m; - }; - Planets.setupPlanetMatrix = function (renderContext, planetID, centerPoint, makeFrustum) { - var matNonRotating = renderContext.get_world().clone(); - Planets._setupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, makeFrustum); - if (planetID === 0) { - var radius = Planets.getAdjustedPlanetRadius(planetID); - matNonRotating.scale(Vector3d.create(radius, radius, radius)); - var translation = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); - matNonRotating._multiply(Matrix3d.translation(translation)); - renderContext.set_worldBaseNonRotating(matNonRotating); - } - }; - Planets._setupMatrixForPlanetGeometry = function (renderContext, planetID, centerPoint, makeFrustum) { - var radius = Planets.getAdjustedPlanetRadius(planetID); - var rotationCurrent = 0; - if (planetID === 19) { - rotationCurrent = Math.PI + Coordinates.mstFromUTC2(SpaceTimeController.get_now(), 0) / 180 * Math.PI; - } - else { - rotationCurrent = Math.PI + (((Planets._jNow - 2451545) / Planets.planetRotationPeriod[planetID]) * Math.PI * 2) % (Math.PI * 2); - } - if (planetID === 9) { - rotationCurrent -= Math.PI / 2; - } - var matLocal = renderContext.get_world().clone(); - var matNonRotating = renderContext.get_world().clone(); - var translation = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); - var orientationAtEpoch = Planets.getPlanetOrientationAtEpoch(planetID); - matLocal.scale(Vector3d.create(radius, radius, radius)); - matLocal._multiply(Matrix3d._rotationY(-rotationCurrent)); - matLocal._multiply(orientationAtEpoch); - if (planetID === renderContext.viewCamera.target) { - Planets.earthMatrix = Matrix3d.get_identity(); - Planets.earthMatrix._multiply(Matrix3d._rotationY(-rotationCurrent)); - Planets.earthMatrix._multiply(orientationAtEpoch); - Planets.earthMatrixInv = Planets.earthMatrix.clone(); - Planets.earthMatrixInv.invert(); - } - matLocal._multiply(Matrix3d.translation(translation)); - renderContext.set_world(matLocal); - renderContext.set_worldBase(renderContext.get_world().clone()); - renderContext.set_nominalRadius(Planets.getPlanetRadiusInMeters(planetID)); - if (makeFrustum) { - renderContext.makeFrustum(); - } - matNonRotating.scale(Vector3d.create(radius, radius, radius)); - matNonRotating._multiply(orientationAtEpoch); - matNonRotating._multiply(Matrix3d.translation(translation)); - renderContext.set_worldBaseNonRotating(matNonRotating); - return rotationCurrent; - }; - Planets.initPlanetResources = function (renderContext) { - }; - Planets._drawSingleOrbit = function (renderContext, eclipticColor, id, centerPoint, startAngle, planetNow, opacity) { - if (opacity < 0.01) { - return; - } - if (renderContext.gl == null) { - var count = Planets._orbitalSampleRate; - var planetDropped = false; - var viewPoint = renderContext.get_viewPoint(); - var ctx = renderContext.device; - ctx.save(); - ctx.strokeStyle = eclipticColor.toString(); - ctx.lineWidth = 2; - ctx.globalAlpha = 1; - var point = new Vector3d(); - var pointTest = new Vector3d(); - var lastPoint = new Vector3d(); - var firstPoint = true; - var translate = Matrix3d.translation(Vector3d.negate(centerPoint)); - var mat = Matrix3d.multiplyMatrix(translate, renderContext.WVP); - var matWV = Matrix3d.multiplyMatrix(translate, renderContext.WV); - for (var i = 0; i < count; i++) { - var pnt = Planets._orbits[id][i]; - var angle = (Math.atan2(Planets._orbits[id][i].z, Planets._orbits[id][i].x) + Math.PI * 2 - startAngle) % (Math.PI * 2); - var alpha = ss.truncate((angle / (Math.PI * 2) * 255)); - var alphaD = alpha / 255; - if (alpha < 2 && !planetDropped) { - pnt = planetNow; - alphaD = 1; - } - pointTest = matWV.transform(pnt); - point = mat.transform(pnt); - if (pointTest.z > 0) { - if (firstPoint) { - firstPoint = false; - } - else { - ctx.beginPath(); - ctx.globalAlpha = alphaD * opacity; - ctx.moveTo(lastPoint.x, lastPoint.y); - ctx.lineTo(point.x, point.y); - ctx.stroke(); - } - } - lastPoint = point; - } - ctx.restore(); - } - else { - if (id !== 9) { - var count = Planets._orbitalSampleRate; - var planetDropped = false; - var viewPoint = renderContext.get_viewPoint(); - var point = new Vector3d(); - var pointTest = new Vector3d(); - var lastPoint = new Vector3d(); - var lastColor = new Color(); - var firstPoint = true; - var list = new OrbitLineList(); - for (var i = 0; i < count; i++) { - var pnt = Planets._orbits[id][i].copy(); - var angle = (Math.atan2(pnt.z, pnt.x) + Math.PI * 2 - startAngle) % (Math.PI * 2); - var alpha = ss.truncate((angle / (Math.PI * 2) * 255)); - var alphaD = alpha / 255; - var color = Color.fromArgb(alpha, eclipticColor.r, eclipticColor.g, eclipticColor.b); - if (alpha < 2 && !planetDropped && !firstPoint) { - pnt = Vector3d.subtractVectors(planetNow, centerPoint); - alphaD = 1; - alpha = 255; - color.a = 255; - lastColor.a = 255; - list.addLine(lastPoint, pnt.copy(), lastColor._clone(), color._clone()); - lastColor.a = 0; - color.a = 0; - pnt = Planets._orbits[id][i].copy(); - planetDropped = true; - } - pnt = Vector3d.subtractVectors(pnt, centerPoint); - if (firstPoint) { - firstPoint = false; - } - else { - list.addLine(lastPoint, pnt, lastColor, color); - } - lastPoint = pnt; - lastColor = color._clone(); - } - list.drawLines(renderContext, 1, Colors.get_white()); - list.clear(); - } - else { - var mu = 0; - switch (id) { - case 9: - mu = 398600.44189 + 4902.7779; - break; - case 10: - case 11: - case 12: - case 13: - mu = 126686534; - break; - default: - mu = 132712440018.8; - break; - } - var deltaT = 1 / 1440 * 0.1; - var r0 = Planets.getPlanetPositionDirect(id, Planets._jNow); - var r1 = Planets.getPlanetPositionDirect(id, Planets._jNow - deltaT); - var v = Vector3d.scale(Vector3d.subtractVectors(r0, r1), 1 / deltaT); - var elements = Planets._stateVectorToKeplerian(r0, v, mu); - Planets._drawSingleOrbitElements(renderContext, eclipticColor, id, centerPoint, startAngle, planetNow, elements); - } - } - }; - Planets.getPlanetPositionDirect = function (id, jd) { - var L = 0; - var B = 0; - var R = 0; - switch (id) { - case 1: - L = CAAMercury.eclipticLongitude(jd); - B = CAAMercury.eclipticLatitude(jd); - R = CAAMercury.radiusVector(jd); - break; - case 2: - L = CAAVenus.eclipticLongitude(jd); - B = CAAVenus.eclipticLatitude(jd); - R = CAAVenus.radiusVector(jd); - break; - case 19: - L = CAAEarth.eclipticLongitude(jd); - B = CAAEarth.eclipticLatitude(jd); - R = CAAEarth.radiusVector(jd); - break; - case 3: - L = CAAMars.eclipticLongitude(jd); - B = CAAMars.eclipticLatitude(jd); - R = CAAMars.radiusVector(jd); - break; - case 4: - L = CAAJupiter.eclipticLongitude(jd); - B = CAAJupiter.eclipticLatitude(jd); - R = CAAJupiter.radiusVector(jd); - break; - case 5: - L = CAASaturn.eclipticLongitude(jd); - B = CAASaturn.eclipticLatitude(jd); - R = CAASaturn.radiusVector(jd); - break; - case 6: - L = CAAUranus.eclipticLongitude(jd); - B = CAAUranus.eclipticLatitude(jd); - R = CAAUranus.radiusVector(jd); - break; - case 7: - L = CAANeptune.eclipticLongitude(jd); - B = CAANeptune.eclipticLatitude(jd); - R = CAANeptune.radiusVector(jd); - break; - case 8: - L = CAAPluto.eclipticLongitude(jd); - B = CAAPluto.eclipticLatitude(jd); - R = CAAPluto.radiusVector(jd); - break; - case 9: - L = CAAMoon.eclipticLongitude(jd); - B = CAAMoon.eclipticLatitude(jd); - R = CAAMoon.radiusVector(jd) / 149598000; - break; - case 10: - var galileanInfo = GM.calculate(jd); - var position = galileanInfo.satellite1.eclipticRectangularCoordinates; - return Vector3d.create(position.x, position.z, position.y); - case 11: - var galileanInfo = GM.calculate(jd); - var position = galileanInfo.satellite2.eclipticRectangularCoordinates; - return Vector3d.create(position.x, position.z, position.y); - case 12: - var galileanInfo = GM.calculate(jd); - var position = galileanInfo.satellite3.eclipticRectangularCoordinates; - return Vector3d.create(position.x, position.z, position.y); - case 13: - var galileanInfo = GM.calculate(jd); - var position = galileanInfo.satellite4.eclipticRectangularCoordinates; - return Vector3d.create(position.x, position.z, position.y); - } - L = Coordinates.degreesToRadians(L); - B = Coordinates.degreesToRadians(B); - var eclPos = Vector3d.create(Math.cos(L) * Math.cos(B) * R, Math.sin(L) * Math.cos(B) * R, Math.sin(B) * R); - var eclipticOfDateRotation = (Coordinates.meanObliquityOfEcliptic(jd) - Coordinates.meanObliquityOfEcliptic(2451545)) * Planets.RC; - eclPos.rotateX(eclipticOfDateRotation); - return Vector3d.create(eclPos.x, eclPos.z, eclPos.y); - }; - Planets._stateVectorToKeplerian = function (position, velocity, mu) { - var r = Vector3d.scale(position, 149598000); - var v = Vector3d.scale(Vector3d.scale(velocity, 1 / 86400), 149598000); - var rmag = r.length(); - var vmag = v.length(); - var sma = 1 / (2 / rmag - vmag * vmag / mu); - var h = Vector3d.cross(r, v); - var ecc = Vector3d.subtractVectors(Vector3d.scale(Vector3d.cross(v, h), 1 / mu), Vector3d.scale(r, 1 / rmag)); - var e = ecc.length(); - h.normalize(); - ecc.normalize(); - var s = Vector3d.cross(h, ecc); - r.normalize(); - var cosNu = Vector3d.dot(ecc, r); - var sinNu = Vector3d.dot(s, r); - var E = Math.atan2(Math.sqrt(1 - e * e) * sinNu, e + cosNu); - var elements = new KeplerianElements(); - elements.orientation = Matrix3d.create(ecc.x, ecc.y, ecc.z, 0, s.x, s.y, s.z, 0, h.x, h.y, h.z, 0, 0, 0, 0, 1); - elements.a = sma; - elements.e = e; - elements.ea = E; - return elements; - }; - Planets._drawSingleOrbitElements = function (renderContext, eclipticColor, id, centerPoint, xstartAngle, planetNow, el) { - var scaleFactor; - switch (id) { - case 9: - if (Settings.get_active().get_solarSystemScale() > 1) { - scaleFactor = Settings.get_active().get_solarSystemScale() / 2; - } - else { - scaleFactor = 1; - } - break; - case 10: - case 11: - case 12: - case 13: - scaleFactor = Settings.get_active().get_solarSystemScale(); - break; - default: - scaleFactor = 1; - break; - } - var translation = Vector3d.negate(centerPoint); - if (id === 9) { - translation.add(Planets._planet3dLocations[19]); - } - else if (id === 10 || id === 11 || id === 12 || id === 13) { - translation.add(Planets._planet3dLocations[4]); - } - var currentPosition = Vector3d.subtractVectors(planetNow, centerPoint); - var worldMatrix = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(el.orientation, Matrix3d.translation(translation)), renderContext.get_world()); - EllipseRenderer.drawEllipseWithPosition(renderContext, el.a / 149598000 * scaleFactor, el.e, el.ea, eclipticColor, worldMatrix, currentPosition); - }; - Planets.isPlanetInFrustum = function (renderContext, rad) { - var frustum = renderContext.get_frustum(); - var center = Vector3d.create(0, 0, 0); - var centerV4 = new Vector4d(0, 0, 0, 1); - for (var i = 0; i < 6; i++) { - if (frustum[i].dot(centerV4) + rad < 0) { - return false; - } - } - return true; - }; - Planets._drawPlanet3d = function (renderContext, planetID, centerPoint) { - if (planetID === 0) { - TileShader.minLightingBrightness = 1; - } - else { - TileShader.minLightingBrightness = 0.025; - if (planetID === 19) { - TileShader.atmosphereColor = Color.fromArgb(255, 65, 157, 217); - } - else { - TileShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); - } - } - var matOld = renderContext.get_world(); - var matOldBase = renderContext.get_worldBase(); - var matOldNonRotating = renderContext.get_worldBaseNonRotating(); - var radius = Planets.getAdjustedPlanetRadius(planetID); - Planets.setupPlanetMatrix(renderContext, planetID, centerPoint, true); - var planetWidth = 1; - if (planetID === 5) { - planetWidth = 3; - } - if (Planets.isPlanetInFrustum(renderContext, planetWidth)) { - var matOld2 = renderContext.get_world(); - var matOldBase2 = renderContext.get_worldBase(); - var matOldNonRotating2 = renderContext.get_worldBaseNonRotating(); - var sun = Planets._planet3dLocations[0].copy(); - var planet = Planets._planet3dLocations[planetID].copy(); - sun = matOld.transform(sun); - planet = matOld.transform(planet); - renderContext.set_world(matOld); - renderContext.set_worldBase(matOldBase); - renderContext.set_worldBaseNonRotating(matOldNonRotating); - Planets._setupMatrixForPlanetGeometry(renderContext, planetID, centerPoint, true); - var sunPosition = Vector3d.subtractVectors(sun, planet); - sunPosition.normalize(); - renderContext.set_sunPosition(sunPosition); - TileShader.sunPosition = Vector3d.subtractVectors(Planets._planet3dLocations[0], planet); - var loc = Vector3d.subtractVectors(Planets._planet3dLocations[planetID], centerPoint); - loc.subtract(renderContext.cameraPosition); - var dist = loc.length(); - var sizeIndexParam = (2 * Math.atan(0.5 * (radius / dist))) / Math.PI * 180; - var sizeIndex = 0; - if (sizeIndexParam > 10.5) { - sizeIndex = 0; - } - else if (sizeIndexParam > 3.9) { - sizeIndex = 1; - } - else if (sizeIndexParam > 0.72) { - sizeIndex = 2; - } - else if (sizeIndexParam > 0.05) { - sizeIndex = 3; - } - else { - sizeIndex = 4; - } - if (planetID === 19 && sizeIndex < 2) { - var width = Settings.get_active().get_solarSystemScale() * 1E-05; - } - if (sizeIndex < 4) { - var oldLighting = renderContext.lighting; - if (planetID === 5) { - if (renderContext.gl == null) { - renderContext.lighting = false; - Planets.drawSaturnsRings(renderContext, false, dist); - renderContext.lighting = oldLighting; - } - } - if (!planetID) { - renderContext.lighting = false; - } - Planets._drawSphere(renderContext, planetID); - if (planetID === 5) { - if (renderContext.gl == null) { - renderContext.lighting = false; - Planets.drawSaturnsRings(renderContext, true, dist); - } - else { - renderContext.lighting = false; - Planets._drawRings(renderContext); - renderContext.lighting = oldLighting; - } - } - renderContext.lighting = oldLighting; - } - else { - if (!planetID) { - Planets.drawPointPlanet(renderContext, new Vector3d(), (10 * Planets._planetDiameters[planetID]), Planets.planetColors[planetID], true); - } - else if (planetID < 9 || planetID === 19) { - var size = (800 * Planets._planetDiameters[planetID]); - Planets.drawPointPlanet(renderContext, new Vector3d(), Math.max(0.05, Math.min(0.1, size)), Planets.planetColors[planetID], true); - } - else if (sizeIndexParam > 0.002) { - var size = (800 * Planets._planetDiameters[planetID]); - Planets.drawPointPlanet(renderContext, new Vector3d(), Math.max(0.05, Math.min(0.1, size)), Planets.planetColors[planetID], true); - } - } - } - LayerManager._draw(renderContext, 1, false, Planets.getNameFrom3dId(planetID), true, false); - renderContext.set_world(matOld); - renderContext.set_worldBase(matOldBase); - renderContext.set_worldBaseNonRotating(matOldNonRotating); - }; - Planets.drawSaturnsRings = function (renderContext, front, distance) { - if (Planets._ringsTriangleLists[0] == null) { - Planets._ringImage = document.createElement('img'); - var xdomimg = Planets._ringImage; - xdomimg.crossOrigin = 'anonymous'; - Planets._ringImage.src = URLHelpers.singleton.engineAssetUrl('saturnringsshadow.png'); - Planets._ringsTriangleLists[0] = []; - Planets._ringsTriangleLists[1] = []; - var ringSize = 2.25; - var TopLeft = Vector3d.create(-ringSize, 0, -ringSize); - var TopRight = Vector3d.create(ringSize, 0, -ringSize); - var BottomLeft = Vector3d.create(-ringSize, 0, ringSize); - var BottomRight = Vector3d.create(ringSize, 0, ringSize); - var center = Vector3d.create(0, 0, 0); - var leftCenter = Vector3d.create(-ringSize, 0, 0); - var topCenter = Vector3d.create(0, 0, -ringSize); - var bottomCenter = Vector3d.create(0, 0, ringSize); - var rightCenter = Vector3d.create(ringSize, 0, 0); - var level = 6; - var vertexList; - vertexList = []; - var Width = 1024; - var Height = 1024; - vertexList.push(PositionTexture.createPosSize(TopLeft, 0, 0, Width, Height)); - vertexList.push(PositionTexture.createPosSize(TopRight, 1, 0, Width, Height)); - vertexList.push(PositionTexture.createPosSize(BottomLeft, 0, 1, Width, Height)); - vertexList.push(PositionTexture.createPosSize(BottomRight, 1, 1, Width, Height)); - var childTriangleList = []; - childTriangleList.push(Triangle.create(0, 2, 1)); - childTriangleList.push(Triangle.create(2, 3, 1)); - var count = 5; - while (count-- > 1) { - var newList = []; - var $enum1 = ss.enumerate(childTriangleList); - while ($enum1.moveNext()) { - var tri = $enum1.current; - tri.subDivideNoNormalize(newList, vertexList); - } - childTriangleList = newList; - } - var miter = 0.6 / (Width / 256); - var $enum2 = ss.enumerate(childTriangleList); - while ($enum2.moveNext()) { - var tri = $enum2.current; - var p1 = vertexList[tri.a]; - var p2 = vertexList[tri.b]; - var p3 = vertexList[tri.c]; - Planets._ringsTriangleLists[0].push(RenderTriangle.createWithMiter(p1, p2, p3, Planets._ringImage, level, miter)); - } - } - if (renderContext.gl == null) { - var cam = renderContext.cameraPosition; - var test = new Vector3d(); - var worldLocal = Matrix3d.multiplyMatrix(Matrix3d._rotationY(Math.atan2(renderContext.get_sunPosition().x, renderContext.get_sunPosition().z)), renderContext.get_worldBaseNonRotating()); - var wv = Matrix3d.multiplyMatrix(worldLocal, renderContext.get_view()); - var wvp = Matrix3d.multiplyMatrix(wv, renderContext.get_projection()); - var Width = renderContext.width; - var Height = renderContext.height; - wvp.scale(Vector3d.create(Width / 2, -Height / 2, 1)); - wvp.translate(Vector3d.create(Width / 2, Height / 2, 0)); - var td = 0; - for (var i = 0; i < 2; i++) { - var $enum3 = ss.enumerate(Planets._ringsTriangleLists[0]); - while ($enum3.moveNext()) { - var tri = $enum3.current; - test = wv.transform(tri.a.position); - td = test.length(); - var draw = td > distance; - if (front) { - draw = !draw; - } - if (draw) { - tri.opacity = 1; - tri.draw(renderContext.device, wvp); - } - } - RenderTriangle.cullInside = !RenderTriangle.cullInside; - } - } - else { - } - }; - Planets._drawRings = function (renderContext) { - Planets._initRings(); - TileShader.use(renderContext, Planets._ringsVertexBuffer.vertexBuffer, null, Planets._ringsTexture.texture2d, 1, false, Vector3d.zero); - renderContext.gl.drawArrays(5, 0, Planets._triangleCountRings); - }; - Planets._initRings = function () { - if (Planets._ringsVertexBuffer != null) { - return; - } - Planets._ringsTexture = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('saturnringsstrip.png')); - var inner = 1.113; - var outer = 2.25; - Planets._ringsVertexBuffer = new PositionTextureVertexBuffer(((192 + 1) * 2)); - Planets._triangleCountRings = (192 + 1) * 2; - var verts = Planets._ringsVertexBuffer.lock(); - var radStep = Math.PI * 2 / 192; - var index = 0; - for (var x = 0; x <= 192; x += 2) { - var rads1 = x * radStep; - var rads2 = (x + 1) * radStep; - verts[index] = new PositionTexture(); - verts[index].position = Vector3d.create((Math.cos(rads1) * inner), 0, (Math.sin(rads1) * inner)); - verts[index].tu = 1; - verts[index].tv = 0; - index++; - verts[index] = new PositionTexture(); - verts[index].position = Vector3d.create((Math.cos(rads1) * outer), 0, (Math.sin(rads1) * outer)); - verts[index].tu = 0; - verts[index].tv = 0; - index++; - verts[index] = new PositionTexture(); - verts[index].position = Vector3d.create((Math.cos(rads2) * inner), 0, (Math.sin(rads2) * inner)); - verts[index].tu = 1; - verts[index].tv = 1; - index++; - verts[index] = new PositionTexture(); - verts[index].position = Vector3d.create((Math.cos(rads2) * outer), 0, (Math.sin(rads2) * outer)); - verts[index].tu = 0; - verts[index].tv = 1; - index++; - } - Planets._ringsVertexBuffer.unlock(); - }; - Planets.drawPointPlanet = function (renderContext, location, size, color, zOrder) { - var center = location; - var rad = size / 2; - if (renderContext.gl != null) { - var ppList = new PointList(renderContext); - ppList.minSize = 20; - ppList.addPoint(location.copy(), color._clone(), new Dates(0, 1), size / 100); - ppList.depthBuffered = true; - ppList.draw(renderContext, 1, false); - } - else { - var screenSpacePnt = renderContext.WVP.transform(center); - if (screenSpacePnt.z < 0) { - return; - } - if (!zOrder) { - if (Vector3d.dot(renderContext.get_viewPoint(), center) < 0.55) { - return; - } - } - var ctx = renderContext.device; - ctx.save(); - ctx.beginPath(); - ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); - ctx.lineWidth = 1; - ctx.fillStyle = color.toString(); - if (true) { - ctx.fill(); - } - ctx.globalAlpha = 1; - ctx.strokeStyle = color.toString(); - ctx.stroke(); - ctx.restore(); - } - }; - Planets.getAdjustedPlanetRadius = function (planetID) { - if (planetID > Planets._planetDiameters.length - 1) { - planetID = 19; - } - var diameter = Planets._planetDiameters[planetID]; - var radius = (diameter / 2); - if (!!planetID) { - radius = radius * (1 + (3 * (Settings.get_active().get_solarSystemScale() - 1))); - } - else { - radius = radius * (1 + (0.3 * (Settings.get_active().get_solarSystemScale() - 1))); - } - return radius; - }; - Planets.getPlanetRadiusInMeters = function (planetID) { - if (planetID > Planets._planetDiameters.length - 1) { - planetID = 19; - } - var diameter = Planets._planetDiameters[planetID]; - return (diameter / 2) * 149598000 * 1000; - }; - Planets._drawPlanet = function (renderContext, planetID, opacity) { - var planetPosition = Planets._planetLocations[planetID]; - if (((planetID < 14) && Planets._planetScales[planetID] < (renderContext.viewCamera.zoom / 6) / 400)) { - if (planetID < 10 || ((planetID < 14) && Planets._planetScales[planetID] > (renderContext.viewCamera.zoom / 6) / 6400)) { - var point = Coordinates.raDecTo3d(planetPosition.RA, planetPosition.dec); - Planets.drawPointPlanet(renderContext, point, 3, Planets.planetColors[planetID], false); - } - return; - } - var brush = null; - if (planetID < 10 || planetID === 18) { - brush = Planets._planetTextures[planetID]; - } - else if (planetID < 14) { - if (Planets._planetLocations[planetID].eclipsed) { - brush = Planets._planetTextures[15]; - } - else { - if (Settings.get_active().get_showMoonsAsPointSource()) { - brush = Planets._planetTextures[14]; - } - else { - brush = Planets._planetTextures[planetID]; - } - } - } - else { - if (!Planets._planetLocations[planetID].shadow) { - return; - } - brush = Planets._planetTextures[15]; - } - if (renderContext.gl != null) { - if (Planets._planetPoints == null) { - Planets._planetPoints = new Array(4); - for (var i = 0; i < 4; i++) { - Planets._planetPoints[i] = new PositionColoredTextured(); - } - } - var radius = (Planets._planetScales[planetID] / 2); - var raRadius = (radius / Math.cos(planetPosition.dec / 180 * Math.PI)); - Planets._planetPoints[0].position = Coordinates.raDecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.dec + radius, 1); - Planets._planetPoints[0].tu = 0; - Planets._planetPoints[0].tv = 1; - Planets._planetPoints[0].color = Colors.get_white(); - Planets._planetPoints[1].position = Coordinates.raDecTo3dAu((planetPosition.RA - (raRadius / 15)), planetPosition.dec - radius, 1); - Planets._planetPoints[1].tu = 0; - Planets._planetPoints[1].tv = 0; - Planets._planetPoints[1].color = Colors.get_white(); - Planets._planetPoints[2].position = Coordinates.raDecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.dec + radius, 1); - Planets._planetPoints[2].tu = 1; - Planets._planetPoints[2].tv = 1; - Planets._planetPoints[2].color = Colors.get_white(); - Planets._planetPoints[3].position = Coordinates.raDecTo3dAu((planetPosition.RA + (raRadius / 15)), planetPosition.dec - radius, 1); - Planets._planetPoints[3].tu = 1; - Planets._planetPoints[3].tv = 0; - Planets._planetPoints[3].color = Colors.get_white(); - Planets._planetSprite.draw(renderContext, Planets._planetPoints, 4, brush, true, 1); - } - else { - var center = Coordinates.raDecTo3d(planetPosition.RA, planetPosition.dec); - var rad = Planets._planetScales[planetID] / (renderContext.get_fovScale() / 3600) / 2; - var screenSpacePnt = renderContext.WVP.transform(center); - if (screenSpacePnt.z < 0) { - return; - } - if (Vector3d.dot(renderContext.get_viewPoint(), center) < 0.55) { - return; - } - var ctx = renderContext.device; - ctx.save(); - ctx.globalAlpha = opacity; - ctx.beginPath(); - ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); - ctx.lineWidth = 0; - ctx.closePath(); - ctx.clip(); - ctx.drawImage(brush.imageElement, screenSpacePnt.x - rad, screenSpacePnt.y - rad, rad * 2, rad * 2); - ctx.globalAlpha = 1; - ctx.restore(); - } - }; - Planets._drawPlanetPhase = function (renderContext, planetID, phase, angle, dark) { - }; - Planets._geocentricElongation = function (ObjectAlpha, ObjectDelta, SunAlpha, SunDelta) { - ObjectAlpha = Coordinates.degreesToRadians(ObjectAlpha * 15); - SunAlpha = Coordinates.degreesToRadians(SunAlpha * 15); - ObjectDelta = Coordinates.degreesToRadians(ObjectDelta); - SunDelta = Coordinates.degreesToRadians(SunDelta); - return Coordinates.radiansToDegrees(Math.acos(Math.sin(SunDelta) * Math.sin(ObjectDelta) + Math.cos(SunDelta) * Math.cos(ObjectDelta) * Math.cos(SunAlpha - ObjectAlpha))); - }; - Planets._phaseAngle = function (GeocentricElongation, EarthObjectDistance, EarthSunDistance) { - GeocentricElongation = Coordinates.degreesToRadians(GeocentricElongation); - return Coordinates.mapTo0To360Range(Coordinates.radiansToDegrees(Math.atan2(EarthSunDistance * Math.sin(GeocentricElongation), EarthObjectDistance - EarthSunDistance * Math.cos(GeocentricElongation)))); - }; - Planets._positionAngle = function (Alpha0, Delta0, Alpha, Delta) { - Alpha0 = Coordinates.hoursToRadians(Alpha0); - Alpha = Coordinates.hoursToRadians(Alpha); - Delta0 = Coordinates.degreesToRadians(Delta0); - Delta = Coordinates.degreesToRadians(Delta); - return Coordinates.mapTo0To360Range(Coordinates.radiansToDegrees(Math.atan2(Math.cos(Delta0) * Math.sin(Alpha0 - Alpha), Math.sin(Delta0) * Math.cos(Delta) - Math.cos(Delta0) * Math.sin(Delta) * Math.cos(Alpha0 - Alpha)))); - }; - Planets._drawSphere = function (renderContext, planetID) { - var planetName = Planets.getImageSetNameNameFrom3dId(planetID); - var planet = WWTControl.singleton.getImagesetByName(planetName); - if (planet == null) { - planet = WWTControl.singleton.getImagesetByName('Bing Maps Aerial'); - } - if (planet != null) { - renderContext.drawImageSet(planet, 100); - if (planetID === 19) { - } - return; - } - }; - var Planets$ = { - - }; - - - // wwtlib.Material - - function Material() { - this.specularSharpness = 0; - this.opacity = 0; - this.isDefault = false; - } - var Material$ = { - - }; - - - // wwtlib.InViewReturnMessage - - function InViewReturnMessage() { - this.aborted = false; - } - var InViewReturnMessage$ = { - - }; - - - // wwtlib.RenderContext - - function RenderContext() { - this.height = 0; - this.width = 0; - this.lighting = false; - this._viewPoint = new Vector3d(); - this.space = false; - this._fovAngle = 0; - this._fovScale = 0; - this._nominalRadius = 6378137; - this._mainTexture = null; - this.viewMover = null; - this.viewCamera = new CameraParameters(); - this.targetCamera = new CameraParameters(); - this.alt = 0; - this.az = 0; - this.targetAlt = 0; - this.targetAz = 0; - this._backgroundImageset = null; - this._foregroundImageset = null; - this._activeCatalogHipsImagesets = []; - this._targetHeight = 1; - this.targetAltitude = 0; - this._galactic = true; - this._galacticMatrix = Matrix3d.create(-0.4838350155, -0.0548755604, -0.8734370902, 0, 0.7469822445, 0.4941094279, -0.44482963, 0, 0.4559837762, -0.867666149, -0.1980763734, 0, 0, 0, 0, 1); - this._firstTimeInit = false; - this._useSolarSystemTilt = true; - this.customTrackingParams = new CameraParameters(); - this._cameraOffset = new Vector3d(); - this._fovLocal = (Math.PI / 4); - this.perspectiveFov = Math.PI / 4; - this.nearPlane = 0; - this._frustumDirty = true; - this._frustum = new Array(6); - this._ambientLightColor = Colors.get_black(); - this._hemiLightColor = Colors.get_black(); - this._hemiLightUp = new Vector3d(); - this._sunlightColor = Colors.get_white(); - this._sunPosition = new Vector3d(); - this._reflectedLightColor = Colors.get_black(); - this._reflectedLightPosition = new Vector3d(); - this._occludingPlanetRadius = 0; - this._occludingPlanetPosition = new Vector3d(); - this._lightingStateDirty = true; - this._twoSidedLighting = false; - this.cameraPosition = new Vector3d(); - this._skyColor = 'Blue'; - for (var i = 0; i < 6; i++) { - this._frustum[i] = new PlaneD(0, 0, 0, 0); - } - } - RenderContext.create = function (device) { - var temp = new RenderContext(); - temp.device = device; - temp.viewCamera.zoom = 700; - temp.viewCamera.target = 65536; - return temp; - }; - RenderContext.getTilesYForLevel = function (layer, level) { - var maxY = 1; - switch (layer.get_projection()) { - case 0: - maxY = Math.pow(2, level); - break; - case 1: - maxY = (Math.pow(2, level) * (180 / layer.get_baseTileDegrees())); - break; - case 2: - maxY = Math.pow(2, level); - break; - case 4: - maxY = 1; - break; - case 7: - maxY = 4 * Math.pow(2, level); - break; - default: - maxY = Math.pow(2, level); - break; - } - if (maxY === Number.POSITIVE_INFINITY) { - maxY = 1; - } - return maxY; - }; - RenderContext.getTilesXForLevel = function (layer, level) { - var maxX = 1; - switch (layer.get_projection()) { - case 6: - case 3: - maxX = Math.pow(2, level); - break; - case 0: - maxX = Math.pow(2, level) * ss.truncate((layer.get_baseTileDegrees() / 360)); - break; - case 1: - maxX = Math.pow(2, level) * ss.truncate((360 / layer.get_baseTileDegrees())); - break; - case 2: - if (layer.get_widthFactor() === 1) { - maxX = Math.pow(2, level) * 2; - } - else { - maxX = Math.pow(2, level); - } - break; - case 5: - maxX = 1; - break; - case 4: - maxX = 1; - break; - case 7: - maxX = Math.pow(2, level) * 3; - break; - default: - maxX = Math.pow(2, level) * 2; - break; - } - return maxX; - }; - var RenderContext$ = { - save: function () { - if (this.gl != null) { - } - else { - this.device.save(); - } - }, - restore: function () { - if (this.gl != null) { - } - else { - this.device.restore(); - } - }, - clear: function () { - if (this.gl != null) { - this.gl.viewport(0, 0, ss.truncate(this.width), ss.truncate(this.height)); - this.gl.clear(16384 | 256); - } - else { - this.device.save(); - this.device.fillStyle = 'black'; - this.device.fillRect(0, 0, this.width, this.height); - this.device.restore(); - } - }, - get_viewPoint: function () { - return this._viewPoint; - }, - get_RA: function () { - return ((((180 - (this.viewCamera.lng - 180)) / 15) % 24) + 48) % 24; - }, - rAtoViewLng: function (ra) { - return 180 - (ra / 24 * 360) - 180; - }, - get_dec: function () { - return this.viewCamera.lat; - }, - get_fovAngle: function () { - return this._fovAngle; - }, - get_fovScale: function () { - return this._fovScale; - }, - set_fovScale: function (value) { - this._fovScale = value; - return value; - }, - get_view: function () { - return this._view; - }, - set_view: function (value) { - this._view = value; - this._frustumDirty = true; - return value; - }, - get_viewBase: function () { - return this._viewBase; - }, - set_viewBase: function (value) { - this._viewBase = value; - return value; - }, - get_projection: function () { - return this._projection; - }, - set_projection: function (value) { - this._projection = value; - this._frustumDirty = true; - return value; - }, - get_world: function () { - return this._world; - }, - set_world: function (value) { - this._world = value; - this._frustumDirty = true; - return value; - }, - _getScreenTexture: function () { - var tex = null; - return tex; - }, - get_worldBase: function () { - return this._worldBase; - }, - set_worldBase: function (value) { - this._worldBase = value; - return value; - }, - get_worldBaseNonRotating: function () { - return this._worldBaseNonRotating; - }, - set_worldBaseNonRotating: function (value) { - this._worldBaseNonRotating = value; - return value; - }, - get_nominalRadius: function () { - return this._nominalRadius; - }, - set_nominalRadius: function (value) { - this._nominalRadius = value; - return value; - }, - get_mainTexture: function () { - return this._mainTexture; - }, - set_mainTexture: function (value) { - if (value != null) { - this._mainTexture = value; - this.gl.bindTexture(3553, this._mainTexture.texture2d); - } - return value; - }, - onTarget: function (place) { - return ((Math.abs(this.viewCamera.lat - this.targetCamera.lat) < 1E-12 && Math.abs(this.viewCamera.lng - this.targetCamera.lng) < 1E-12 && Math.abs(this.viewCamera.zoom - this.targetCamera.zoom) < 1E-12) && this.viewMover == null); - }, - setTexture: function (texture) { - }, - get_backgroundImageset: function () { - return this._backgroundImageset; - }, - set_backgroundImageset: function (value) { - var viewModeChanged = this._backgroundImageset != null && value != null && (this._backgroundImageset.get_dataSetType() !== value.get_dataSetType()); - this._backgroundImageset = value; - if (viewModeChanged) { - WWTControl.singleton._freezeView(); - WWTControl.singleton.clampZooms(this); - } - return value; - }, - get_foregroundImageset: function () { - return this._foregroundImageset; - }, - set_foregroundImageset: function (value) { - this._foregroundImageset = value; - return value; - }, - get_catalogHipsImagesets: function () { - return this._activeCatalogHipsImagesets; - }, - getCatalogHipsDataInView: function (imageset, limit, onComplete) { - var $this = this; - - var layer = new CatalogSpreadSheetLayer(); - var onHeaderInfoLoad = function () { - layer.useHeadersFromVoTable(imageset.get_hipsProperties().get_catalogColumnInfo()); - $this._tryGetAllDataInView(imageset, limit, layer, onComplete, 0); - }; - if (imageset.get_hipsProperties() == null) { - imageset.set_hipsProperties(new HipsProperties(imageset)); - imageset.get_hipsProperties().setDownloadCompleteListener(onHeaderInfoLoad); - } - else if (imageset.get_hipsProperties() != null && imageset.get_hipsProperties().get_downloadComplete()) { - onHeaderInfoLoad(); - } - else { - imageset.get_hipsProperties().setDownloadCompleteListener(onHeaderInfoLoad); - } - }, - _tryGetAllDataInView: function (imageset, limit, catalogSpreadSheetLayer, onComplete, i) { - var $this = this; - - var maxX = RenderContext.getTilesXForLevel(imageset, imageset.get_baseLevel()); - var maxY = RenderContext.getTilesYForLevel(imageset, imageset.get_baseLevel()); - var anyTileStillDownloading = false; - for (var x = 0; x < maxX; x++) { - for (var y = 0; y < maxY; y++) { - var tile = TileCache.getTile(imageset.get_baseLevel(), x, y, imageset, null); - if (tile != null) { - var tileAndChildrenReady = (tile).getDataInView(this, limit, catalogSpreadSheetLayer); - anyTileStillDownloading = anyTileStillDownloading || !tileAndChildrenReady; - } - else { - anyTileStillDownloading = true; - } - } - } - if (anyTileStillDownloading) { - var count = catalogSpreadSheetLayer.get__table().rows.length; - if ((count > 10000 || i > 100 * 60 * 5) && limit) { - console.log('Too Many results - Aborting'); - console.log(count); - var returnMessage = new InViewReturnMessage(); - returnMessage.aborted = true; - returnMessage.table = catalogSpreadSheetLayer.getTableDataInView(); - onComplete(returnMessage); - catalogSpreadSheetLayer.cleanUp(); - } - else { - setTimeout(function () { - $this._tryGetAllDataInView(imageset, limit, catalogSpreadSheetLayer, onComplete, i); - }, 10); - if (!(i % 200)) { - console.log('Waiting for more tiles to load'); - console.log(count); - } - i++; - } - } - else { - var count = catalogSpreadSheetLayer.get__table().rows.length; - console.log('Done!'); - console.log(count); - var returnMessage = new InViewReturnMessage(); - returnMessage.aborted = false; - returnMessage.table = catalogSpreadSheetLayer.getTableDataInView(); - onComplete(returnMessage); - catalogSpreadSheetLayer.cleanUp(); - } - }, - addCatalogHips: function (imageset, onLoad) { - if (!(this._activeCatalogHipsImagesets.indexOf(imageset) >= 0)) { - this._activeCatalogHipsImagesets.push(imageset); - } - if (imageset.get_hipsProperties() == null) { - imageset.set_hipsProperties(new HipsProperties(imageset)); - imageset.get_hipsProperties().setDownloadCompleteListener(onLoad); - } - else if (imageset.get_hipsProperties() != null && imageset.get_hipsProperties().get_downloadComplete()) { - LayerManager.addSpreadsheetLayer(imageset.get_hipsProperties().get_catalogSpreadSheetLayer(), 'Sky'); - if (onLoad != null) { - onLoad(); - } - } - }, - removeCatalogHips: function (imageset) { - ss.remove(this._activeCatalogHipsImagesets, imageset); - if (imageset.get_hipsProperties() != null) { - LayerManager.deleteLayerByID(imageset.get_hipsProperties().get_catalogSpreadSheetLayer().id, true, true); - } - }, - getCatalogHipsByName: function (name) { - var $enum1 = ss.enumerate(this._activeCatalogHipsImagesets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_name() === name) { - return imageset; - } - } - return null; - }, - getAltitudeForLatLongForPlanet: function (planetID, viewLat, viewLong) { - var layer = WWTControl.singleton.getImagesetByName(Planets.getNameFrom3dId(planetID)); - if (layer == null) { - return 0; - } - var maxX = RenderContext.getTilesXForLevel(layer, layer.get_baseLevel()); - var maxY = RenderContext.getTilesYForLevel(layer, layer.get_baseLevel()); - for (var x = 0; x < maxX; x++) { - for (var y = 0; y < maxY; y++) { - var tile = TileCache.getTile(layer.get_baseLevel(), x, y, layer, null); - if (tile != null) { - if (tile.isPointInTile(viewLat, viewLong)) { - return tile.getSurfacePointAltitude(viewLat, viewLong, true); - } - } - } - } - return 0; - }, - getEarthAltitude: function (ViewLat, ViewLong, meters) { - if (WWTControl.singleton.get_solarSystemMode()) { - var pnt = Coordinates.geoTo3dDouble(ViewLat, ViewLong + 90); - var EarthMat = Planets.earthMatrixInv; - pnt = Vector3d._transformCoordinate(pnt, EarthMat); - pnt.normalize(); - var point = Coordinates.cartesianToLatLng(pnt); - return this.getAltitudeForLatLongForPlanet(this.viewCamera.target, point.y, point.x); - } - else if (!this.get_backgroundImageset().get_dataSetType()) { - return (meters) ? this.getMetersAltitudeForLatLong(ViewLat, ViewLong) : this.getScaledAltitudeForLatLong(ViewLat, ViewLong); - } - else { - return 0; - } - }, - drawImageSet: function (imageset, opacity) { - var maxX = RenderContext.getTilesXForLevel(imageset, imageset.get_baseLevel()); - var maxY = RenderContext.getTilesYForLevel(imageset, imageset.get_baseLevel()); - for (var x = 0; x < maxX; x++) { - for (var y = 0; y < maxY; y++) { - var tile = TileCache.getTile(imageset.get_baseLevel(), x, y, imageset, null); - if (tile != null) { - tile.draw3D(this, opacity); - } - } - } - }, - _getTileAtLatLong: function (viewLat, viewLong) { - var layer = this.get_backgroundImageset(); - if (layer == null) { - return null; - } - var maxX = RenderContext.getTilesXForLevel(layer, layer.get_baseLevel()); - var maxY = RenderContext.getTilesYForLevel(layer, layer.get_baseLevel()); - for (var x = 0; x < maxX; x++) { - for (var y = 0; y < maxY; y++) { - var tile = TileCache.getTile(layer.get_baseLevel(), x, y, layer, null); - if (tile != null) { - if (tile.isPointInTile(viewLat, viewLong)) { - return tile; - } - } - } - } - return null; - }, - getScaledAltitudeForLatLong: function (viewLat, viewLong) { - var tile = this._getTileAtLatLong(viewLat, viewLong); - if (tile != null) { - return tile.getSurfacePointAltitude(viewLat, viewLong, false); - } - return 0; - }, - getMetersAltitudeForLatLong: function (viewLat, viewLong) { - var tile = this._getTileAtLatLong(viewLat, viewLong); - if (tile != null) { - return tile.getSurfacePointAltitude(viewLat, viewLong, true); - } - return 0; - }, - _setupMatricesLand3d: function () { - this.lighting = false; - this.space = false; - RenderTriangle.cullInside = false; - var WorldMatrix = Matrix3d._rotationY(((this.viewCamera.lng - 90) / 180 * Math.PI)); - WorldMatrix._multiply(Matrix3d._rotationX(((-this.viewCamera.lat) / 180 * Math.PI))); - this.set_world(WorldMatrix); - this.set_worldBase(WorldMatrix.clone()); - this._viewPoint = Coordinates.geoTo3d(this.viewCamera.lat, this.viewCamera.lng); - var distance = 0; - if (this._backgroundImageset.get_isMandelbrot()) { - distance = (4 * (this.viewCamera.zoom / 180)) + 1E-41; - } - else { - distance = (4 * (this.viewCamera.zoom / 180)) + 1E-06; - } - this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; - this._fovScale = (this._fovAngle / this.height) * 3600; - if (this.gl != null) { - this.targetAltitude = this.getScaledAltitudeForLatLong(this.viewCamera.lat, this.viewCamera.lng); - var heightNow = 1 + this.targetAltitude; - this.targetAltitude *= this.get_nominalRadius(); - if (this._targetHeight < heightNow) { - this._targetHeight = (((this._targetHeight * 2) + heightNow) / 3); - } - else { - this._targetHeight = (((this._targetHeight * 9) + heightNow) / 10); - } - } - else { - this.targetAltitude = 0; - this._targetHeight = 1; - } - var rotLocal = this.viewCamera.rotation; - this.cameraPosition = Vector3d.create((Math.sin(rotLocal) * Math.sin(this.viewCamera.angle) * distance), (Math.cos(rotLocal) * Math.sin(this.viewCamera.angle) * distance), (-this._targetHeight - (Math.cos(this.viewCamera.angle) * distance))); - var cameraTarget = Vector3d.create(0, 0, -this._targetHeight); - var camHeight = this.cameraPosition.length(); - var lookUp = Vector3d.create(Math.sin(rotLocal) * Math.cos(this.viewCamera.angle), Math.cos(rotLocal) * Math.cos(this.viewCamera.angle), Math.sin(this.viewCamera.angle)); - this.set_view(Matrix3d.lookAtLH(this.cameraPosition, cameraTarget, lookUp)); - this.set_viewBase(this.get_view()); - var back = Math.sqrt((distance + 1) * (distance + 1) - 1); - back = Math.max(0.5, back); - var m_nearPlane = distance * 0.05; - m_nearPlane = distance * 0.05; - this.set_projection(Matrix3d.perspectiveFovLH((Math.PI / 4), this.width / this.height, m_nearPlane, back)); - this._setMatrixes(); - this.makeFrustum(); - }, - setupMatricesSpace3d: function (canvasWidth, canvasHeight) { - this.lighting = false; - if (!this._firstTimeInit) { - this._galacticMatrix = Matrix3d.get_identity(); - this._galacticMatrix._multiply(Matrix3d._rotationY(-(270 - (17.7603329867975 * 15)) / 180 * Math.PI)); - this._galacticMatrix._multiply(Matrix3d._rotationX(-(-28.9361739586894) / 180 * Math.PI)); - this._galacticMatrix._multiply(Matrix3d._rotationZ(((31.422052860102) - 90) / 180 * Math.PI)); - this._firstTimeInit = true; - } - this.space = true; - RenderTriangle.cullInside = true; - var WorldMatrix = Matrix3d.get_identity(); - if (Settings.get_active().get_galacticMode()) { - WorldMatrix._multiply(this._galacticMatrix); - WorldMatrix._multiply(Matrix3d._rotationY(this.az / 180 * Math.PI)); - WorldMatrix._multiply(Matrix3d._rotationX(-this.alt / 180 * Math.PI)); - var gPoint = Coordinates.galactictoJ2000(this.az, this.alt); - this._viewPoint = Coordinates.raDecTo3dAu(gPoint[0] / 15, gPoint[1], 1); - this.targetCamera.lng = this.rAtoViewLng(gPoint[0] / 15); - this.targetCamera.lat = gPoint[1]; - this.viewCamera.lat = this.targetCamera.lat; - this.viewCamera.lng = this.targetCamera.lng; - } - else { - WorldMatrix._multiply(Matrix3d._rotationY(-(this.viewCamera.lng - 90) / 180 * Math.PI)); - WorldMatrix._multiply(Matrix3d._rotationX(-this.viewCamera.lat / 180 * Math.PI)); - this._viewPoint = Coordinates.raDecTo3dAu(this.get_RA(), this.get_dec(), 1); - } - var camLocal = this.viewCamera.rotation; - this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; - this._fovScale = (this._fovAngle / canvasHeight) * 3600; - if (Settings.get_active().get_localHorizonMode() && this._backgroundImageset.get_dataSetType() === 2) { - var zenithAltAz = new Coordinates(0, 0); - zenithAltAz.set_az(0); - zenithAltAz.set_alt(0); - var zenith = Coordinates.horizonToEquitorial(zenithAltAz, SpaceTimeController.get_location(), SpaceTimeController.get_now()); - var raPart = -((zenith.get_RA() - 6) / 24 * (Math.PI * 2)); - var decPart = -(zenith.get_dec() / 360 * (Math.PI * 2)); - var raText = Coordinates.formatDMS(zenith.get_RA()); - WorldMatrix = Matrix3d._rotationY(-raPart - Math.PI); - WorldMatrix._multiply(Matrix3d._rotationX(decPart)); - if (SpaceTimeController.get_location().get_lat() < 0) { - WorldMatrix._multiply(Matrix3d._rotationY((this.az / 180 * Math.PI))); - WorldMatrix._multiply(Matrix3d._rotationX((this.alt / 180 * Math.PI))); - camLocal += Math.PI; - } - else { - WorldMatrix._multiply(Matrix3d._rotationY(((-this.az) / 180 * Math.PI))); - WorldMatrix._multiply(Matrix3d._rotationX(((-this.alt) / 180 * Math.PI))); - } - var currentRaDec = Coordinates.horizonToEquitorial(Coordinates.fromLatLng(this.alt, this.az), SpaceTimeController.get_location(), SpaceTimeController.get_now()); - this.viewCamera.lat = this.targetCamera.lat = currentRaDec.get_dec(); - this.viewCamera.lng = this.targetCamera.lng = this.rAtoViewLng(currentRaDec.get_RA()); - } - this.set_world(WorldMatrix); - this.set_worldBase(WorldMatrix.clone()); - var localZoomFactor = this.viewCamera.zoom; - var FovAngle = (localZoomFactor / 343.774) / Math.PI * 180; - this.cameraPosition = Vector3d.create(0, 0, 0); - this.set_view(Matrix3d.lookAtLH(this.cameraPosition, Vector3d.create(0, 0, -1), Vector3d.create(Math.sin(camLocal), Math.cos(camLocal), 0))); - this.set_viewBase(this.get_view().clone()); - var m_nearPlane = 0.1; - this.nearPlane = 0.1; - this.set_projection(Matrix3d.perspectiveFovLH(localZoomFactor / 343.774, canvasWidth / canvasHeight, 0.1, -2)); - this._setMatrixes(); - this.makeFrustum(); - }, - get_solarSystemTrack: function () { - return this.viewCamera.target; - }, - set_solarSystemTrack: function (value) { - this.viewCamera.target = value; - return value; - }, - get_solarSystemCameraDistance: function () { - return (4 * (this.viewCamera.zoom / 9)) + 1E-06; - }, - get_sandboxMode: function () { - if (this._backgroundImageset == null) { - return false; - } - return this._backgroundImageset.get_dataSetType() === 5; - }, - get_trackingFrame: function () { - return this.viewCamera.targetReferenceFrame; - }, - set_trackingFrame: function (value) { - this.viewCamera.targetReferenceFrame = value; - return value; - }, - get_fovLocal: function () { - return this._fovLocal; - }, - set_fovLocal: function (value) { - this._fovLocal = value; - return value; - }, - setupMatricesOverlays: function () { - this.set_world(Matrix3d.get_identity()); - var lookAtAdjust = Matrix3d.get_identity(); - var lookFrom = Vector3d.create(0, 0, 0); - var lookAt = Vector3d.create(0, 0, 1); - var lookUp = Vector3d.create(0, 1, 0); - var view; - view = Matrix3d.lookAtLH(lookFrom, lookAt, lookUp); - view._multiply(Matrix3d._scaling(1, -1, 1)); - this.set_view(view); - var back = 10000; - this.nearPlane = 0.1; - this.set_projection(Matrix3d.perspectiveFovLH(this._fovLocal, this.width / this.height, this.nearPlane, back)); - }, - setupMatricesSolarSystem: function (forStars) { - this.lighting = Settings.get_active().get_solarSystemLighting(); - this.space = false; - if (this.get_solarSystemTrack() !== 20 && this.get_solarSystemTrack() !== 65536) { - this.viewCamera.viewTarget = Planets.getPlanetTargetPoint(this.get_solarSystemTrack(), this.viewCamera.lat, this.viewCamera.lng, 0); - } - RenderTriangle.cullInside = false; - var cameraDistance = this.get_solarSystemCameraDistance(); - var trackingMatrix = Matrix3d.get_identity(); - cameraDistance -= 1E-06; - var activeTrackingFrame = false; - if (this.get_solarSystemTrack() === 20 && !ss.emptyString(this.get_trackingFrame())) { - activeTrackingFrame = true; - var target = LayerManager._getFrameTarget(this, this.get_trackingFrame()); - this.viewCamera.viewTarget = target.target; - trackingMatrix = target.matrix; - } - else if (!ss.emptyString(this.get_trackingFrame())) { - this.set_trackingFrame(''); - } - var center = this.viewCamera.viewTarget; - var localZoom = this.viewCamera.zoom * 20; - var lookAt = new Vector3d(); - var viewAdjust = Matrix3d.get_identity(); - viewAdjust._multiply(Matrix3d._rotationX(((-this.viewCamera.lat) / 180 * Math.PI))); - viewAdjust._multiply(Matrix3d._rotationY(((-this.viewCamera.lng) / 180 * Math.PI))); - var lookAtAdjust = Matrix3d.get_identity(); - var dome = false; - var lookUp; - if (this._useSolarSystemTilt && !this.get_sandboxMode()) { - var angle = this.viewCamera.angle; - if (cameraDistance > 0.0008) { - angle = 0; - } - else if (cameraDistance > 1E-05) { - var val = Math.min(1.903089987, Util.log10(cameraDistance) + 5) / 1.903089987; - angle = angle * Math.max(0, 1 - val); - } - this.cameraPosition = Vector3d.create((Math.sin(-this.viewCamera.rotation) * Math.sin(angle) * cameraDistance), (Math.cos(-this.viewCamera.rotation) * Math.sin(angle) * cameraDistance), (Math.cos(angle) * cameraDistance)); - lookUp = Vector3d.create(Math.sin(-this.viewCamera.rotation), Math.cos(-this.viewCamera.rotation), 1E-05); - } - else { - this.cameraPosition = Vector3d.create(0, 0, cameraDistance); - lookUp = Vector3d.create(Math.sin(-this.viewCamera.rotation), Math.cos(-this.viewCamera.rotation), 0.0001); - } - this.cameraPosition = viewAdjust.transform(this.cameraPosition); - this._cameraOffset = this.cameraPosition.copy(); - var tmp = trackingMatrix.clone(); - tmp.invert(); - this._cameraOffset = Vector3d._transformCoordinate(this._cameraOffset, tmp); - lookUp = viewAdjust.transform(lookUp); - this.set_world(Matrix3d.get_identity()); - this.set_worldBase(Matrix3d.get_identity()); - this.set_worldBaseNonRotating(Matrix3d.get_identity()); - this.set_view(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(trackingMatrix, Matrix3d.lookAtLH(this.cameraPosition, lookAt, lookUp)), lookAtAdjust)); - this.set_viewBase(this.get_view().clone()); - var temp = Vector3d.subtractVectors(lookAt, this.cameraPosition); - temp.normalize(); - temp = Vector3d._transformCoordinate(temp, trackingMatrix); - temp.normalize(); - this._viewPoint = temp; - var radius = Planets.getAdjustedPlanetRadius(this.get_solarSystemTrack()); - if (cameraDistance < radius * 2 && !forStars) { - this.nearPlane = cameraDistance * 0.03; - this.nearPlane = Math.max(this.nearPlane, 1E-11); - RenderContext.back = 1900; - } - else { - if (forStars) { - RenderContext.back = 900056; - RenderContext.back = (cameraDistance > 900056) ? cameraDistance * 3 : 900056; - this.nearPlane = 3E-05; - } - else { - RenderContext.back = (cameraDistance > 1900) ? cameraDistance + 200 : 1900; - if (Settings.get_active().get_solarSystemScale() < 13) { - this.nearPlane = Math.min(cameraDistance * 0.03, 0.01); - } - else { - this.nearPlane = 0.001; - } - } - } - this.set_projection(Matrix3d.perspectiveFovLH(this._fovLocal, this.width / this.height, this.nearPlane, RenderContext.back)); - this.perspectiveFov = this._fovLocal; - this._fovAngle = (this.viewCamera.zoom / 343.774) / Math.PI * 180; - this._fovScale = (this._fovAngle / this.height) * 3600; - this._setMatrixes(); - this.makeFrustum(); - }, - _setMatrixes: function () { - }, - get_frustum: function () { - return this._frustum; - }, - get_ambientLightColor: function () { - return this._ambientLightColor; - }, - set_ambientLightColor: function (value) { - this._ambientLightColor = value; - this._lightingStateDirty = true; - return value; - }, - get_hemisphereLightColor: function () { - return this._hemiLightColor; - }, - set_hemisphereLightColor: function (value) { - this._hemiLightColor = value; - this._lightingStateDirty = true; - return value; - }, - get_hemisphereLightUp: function () { - return this._hemiLightUp; - }, - set_hemisphereLightUp: function (value) { - this._hemiLightUp = value; - this._lightingStateDirty = true; - return value; - }, - get_sunlightColor: function () { - return this._sunlightColor; - }, - set_sunlightColor: function (value) { - this._sunlightColor = value; - this._lightingStateDirty = true; - return value; - }, - get_sunPosition: function () { - return this._sunPosition; - }, - set_sunPosition: function (value) { - this._sunPosition = value; - this._lightingStateDirty = true; - return value; - }, - get_reflectedLightColor: function () { - return this._reflectedLightColor; - }, - set_reflectedLightColor: function (value) { - if (this._reflectedLightColor !== value) { - this._reflectedLightColor = value; - this._lightingStateDirty = true; - } - return value; - }, - get_reflectedLightPosition: function () { - return this._reflectedLightPosition; - }, - set_reflectedLightPosition: function (value) { - this._reflectedLightPosition = value; - this._lightingStateDirty = true; - return value; - }, - get_occludingPlanetRadius: function () { - return this._occludingPlanetRadius; - }, - set_occludingPlanetRadius: function (value) { - this._occludingPlanetRadius = value; - return value; - }, - get_occludingPlanetPosition: function () { - return this._occludingPlanetPosition; - }, - set_occludingPlanetPosition: function (value) { - this._occludingPlanetPosition = value; - return value; - }, - get_twoSidedLighting: function () { - return this._twoSidedLighting; - }, - set_twoSidedLighting: function (value) { - if (value !== this._twoSidedLighting) { - this._twoSidedLighting = value; - this._lightingStateDirty = true; - } - return value; - }, - makeFrustum: function () { - this.WV = Matrix3d.multiplyMatrix(this.get_world(), this.get_view()); - var viewProjection = Matrix3d.multiplyMatrix(this.WV, this.get_projection()); - this.WVP = viewProjection.clone(); - var inverseWorld = this.get_world().clone(); - inverseWorld.invert(); - this._frustum[0].a = viewProjection.get_m14() + viewProjection.get_m11(); - this._frustum[0].b = viewProjection.get_m24() + viewProjection.get_m21(); - this._frustum[0].c = viewProjection.get_m34() + viewProjection.get_m31(); - this._frustum[0].d = viewProjection.get_m44() + viewProjection.get_m41(); - this._frustum[1].a = viewProjection.get_m14() - viewProjection.get_m11(); - this._frustum[1].b = viewProjection.get_m24() - viewProjection.get_m21(); - this._frustum[1].c = viewProjection.get_m34() - viewProjection.get_m31(); - this._frustum[1].d = viewProjection.get_m44() - viewProjection.get_m41(); - this._frustum[2].a = viewProjection.get_m14() - viewProjection.get_m12(); - this._frustum[2].b = viewProjection.get_m24() - viewProjection.get_m22(); - this._frustum[2].c = viewProjection.get_m34() - viewProjection.get_m32(); - this._frustum[2].d = viewProjection.get_m44() - viewProjection.get_m42(); - this._frustum[3].a = viewProjection.get_m14() + viewProjection.get_m12(); - this._frustum[3].b = viewProjection.get_m24() + viewProjection.get_m22(); - this._frustum[3].c = viewProjection.get_m34() + viewProjection.get_m32(); - this._frustum[3].d = viewProjection.get_m44() + viewProjection.get_m42(); - this._frustum[4].a = viewProjection.get_m13(); - this._frustum[4].b = viewProjection.get_m23(); - this._frustum[4].c = viewProjection.get_m33(); - this._frustum[4].d = viewProjection.get_m43(); - this._frustum[5].a = viewProjection.get_m14() - viewProjection.get_m13(); - this._frustum[5].b = viewProjection.get_m24() - viewProjection.get_m23(); - this._frustum[5].c = viewProjection.get_m34() - viewProjection.get_m33(); - this._frustum[5].d = viewProjection.get_m44() - viewProjection.get_m43(); - for (var i = 0; i < 6; i++) { - this._frustum[i].normalize(); - } - this._frustumDirty = false; - this.WVP.scale(Vector3d.create(this.width / 2, -this.height / 2, 1)); - this.WVP.translate(Vector3d.create(this.width / 2, this.height / 2, 0)); - this._setMatrixes(); - }, - _initGL: function () { - if (this.gl == null) { - return; - } - var uints_for_indices = this.gl.getExtension('OES_element_index_uint'); - Tile.uvMultiple = 1; - Tile.demEnabled = true; - TileShader.init(this); - }, - freezeView: function () { - this.targetAlt = this.alt; - this.targetAz = this.az; - this.targetCamera = this.viewCamera.copy(); - }, - _setVertexBuffer: function (vertexBuffer) { - }, - _setIndexBuffer: function (indexBuffer) { - }, - setMaterial: function (material, diffuseTex, specularTex, normalMap, opacity) { - this.set_mainTexture(diffuseTex); - }, - preDraw: function () { - } - }; - - - // wwtlib.RenderTriangle - - function RenderTriangle() { - this.a = new PositionTexture(); - this.b = new PositionTexture(); - this.c = new PositionTexture(); - this.normal = new Vector3d(); - this.opacity = 1; - this.expansionInPixels = 0.6; - this.tileLevel = 0; - this._ta = new Vector3d(); - this._tb = new Vector3d(); - this._tc = new Vector3d(); - this._expandedS0 = new Vector2d(); - this._expandedS1 = new Vector2d(); - this._expandedS2 = new Vector2d(); - this.lighting = 1; - } - RenderTriangle.create = function (a, b, c, img, level) { - var temp = new RenderTriangle(); - temp.a = a.copy(); - temp.b = b.copy(); - temp.c = c.copy(); - temp._texture = img; - temp.tileLevel = level; - temp.makeNormal(); - return temp; - }; - RenderTriangle.createWithMiter = function (a, b, c, img, level, expansion) { - var temp = new RenderTriangle(); - temp.expansionInPixels = expansion; - temp.a = a.copy(); - temp.b = b.copy(); - temp.c = c.copy(); - temp._texture = img; - temp.tileLevel = level; - temp.makeNormal(); - return temp; - }; - RenderTriangle._getMiterPoint = function (p1, p2, p3, edgeOffset) { - var edge1 = Vector2d.subtract(p2, p1); - var edge2 = Vector2d.subtract(p3, p1); - edge1.normalize(); - edge2.normalize(); - var dir = Vector2d.create(edge1.x + edge2.x, edge1.y + edge2.y); - dir.normalize(); - var delta = Vector2d.create(edge1.x - edge2.x, edge1.y - edge2.y); - var sineHalfAngle = delta.get_length() / 2; - var net = Math.min(2, edgeOffset / sineHalfAngle); - dir.extend(net); - return Vector2d.create(p1.x - dir.x, p1.y - dir.y); - }; - RenderTriangle._miterPoint = function (p1x, p1y, p2x, p2y, p3x, p3y, ExpansionInPixels) { - var e1x = p2x - p1x; - var e1y = p2y - p1y; - var e2x = p3x - p1x; - var e2y = p3y - p1y; - var length = Math.sqrt(e1x * e1x + e1y * e1y); - if (!!length) { - e1x /= length; - e1y /= length; - } - length = Math.sqrt(e2x * e2x + e2y * e2y); - if (!!length) { - e2x /= length; - e2y /= length; - } - var dx = e1x + e2x; - var dy = e1y + e2y; - length = Math.sqrt(dx * dx + dy * dy); - if (!!length) { - dx /= length; - dy /= length; - } - var deltax = e1x - e2x; - var deltay = e1y - e2y; - length = Math.sqrt(deltax * deltax + deltay * deltay); - var sineHalfAngle = length / 2; - var net = Math.min(2, ExpansionInPixels / sineHalfAngle); - dx *= net; - dy *= net; - return Vector2d.create(p1x - dx, p1y - dy); - }; - RenderTriangle._miterPointOut = function (pntOut, p1x, p1y, p2x, p2y, p3x, p3y, ExpansionInPixels) { - var e1x = p2x - p1x; - var e1y = p2y - p1y; - var e2x = p3x - p1x; - var e2y = p3y - p1y; - var length = Math.sqrt(e1x * e1x + e1y * e1y); - if (!!length) { - e1x /= length; - e1y /= length; - } - length = Math.sqrt(e2x * e2x + e2y * e2y); - if (!!length) { - e2x /= length; - e2y /= length; - } - var dx = e1x + e2x; - var dy = e1y + e2y; - length = Math.sqrt(dx * dx + dy * dy); - if (!!length) { - dx /= length; - dy /= length; - } - var deltax = e1x - e2x; - var deltay = e1y - e2y; - length = Math.sqrt(deltax * deltax + deltay * deltay); - var sineHalfAngle = length / 2; - var net = Math.min(2, ExpansionInPixels / sineHalfAngle); - dx *= net; - dy *= net; - pntOut.x = p1x - dx; - pntOut.y = p1y - dy; - }; - var RenderTriangle$ = { - makeNormal: function () { - var a = this.a.position.copy(); - var b = this.b.position.copy(); - var c = this.c.position.copy(); - a.normalize(); - b.normalize(); - c.normalize(); - var x = a.x + b.x + c.x; - var y = a.y + b.y + c.y; - var z = a.z + b.z + c.z; - this.normal = Vector3d.create(x / 3, y / 3, z / 3); - this.normal.normalize(); - }, - _checkBackface: function () { - var ab = Vector3d.subtractVectors(this._ta, this._tb); - var ac = Vector3d.subtractVectors(this._ta, this._tc); - var cp = Vector3d.cross(ab, ac); - cp.normalize(); - return cp.z >= 0; - }, - draw: function (ctx, wvp) { - if (ctx == null) { - return; - } - wvp._transformTo(this.a.position, this._ta); - wvp._transformTo(this.b.position, this._tb); - wvp._transformTo(this.c.position, this._tc); - if (this._checkBackface() === RenderTriangle.cullInside) { - RenderTriangle.trianglesCulled++; - return; - } - this._drawTriangle(ctx, this._texture, this._ta.x, this._ta.y, this._tb.x, this._tb.y, this._tc.x, this._tc.y, this.a.tu, this.a.tv, this.b.tu, this.b.tv, this.c.tu, this.c.tv); - }, - _drawTriangle: function (ctx, im, x0, y0, x1, y1, x2, y2, sx0, sy0, sx1, sy1, sx2, sy2) { - if (!this.intersects(0, RenderTriangle.width, 0, RenderTriangle.height, x0, y0, x1, y1, x2, y2)) { - return false; - } - RenderTriangle._miterPointOut(this._expandedS0, x0, y0, x1, y1, x2, y2, this.expansionInPixels); - RenderTriangle._miterPointOut(this._expandedS1, x1, y1, x0, y0, x2, y2, this.expansionInPixels); - RenderTriangle._miterPointOut(this._expandedS2, x2, y2, x1, y1, x0, y0, this.expansionInPixels); - x0 = this._expandedS0.x; - y0 = this._expandedS0.y; - x1 = this._expandedS1.x; - y1 = this._expandedS1.y; - x2 = this._expandedS2.x; - y2 = this._expandedS2.y; - ctx.save(); - if (RenderTriangle.renderingOn) { - ctx.beginPath(); - ctx.moveTo(x0, y0); - ctx.lineTo(x1, y1); - ctx.lineTo(x2, y2); - ctx.closePath(); - ctx.clip(); - } - var denom = sx0 * (sy2 - sy1) - sx1 * sy2 + sx2 * sy1 + (sx1 - sx2) * sy0; - var m11 = -(sy0 * (x2 - x1) - sy1 * x2 + sy2 * x1 + (sy1 - sy2) * x0) / denom; - var m12 = (sy1 * y2 + sy0 * (y1 - y2) - sy2 * y1 + (sy2 - sy1) * y0) / denom; - var m21 = (sx0 * (x2 - x1) - sx1 * x2 + sx2 * x1 + (sx1 - sx2) * x0) / denom; - var m22 = -(sx1 * y2 + sx0 * (y1 - y2) - sx2 * y1 + (sx2 - sx1) * y0) / denom; - var dx = (sx0 * (sy2 * x1 - sy1 * x2) + sy0 * (sx1 * x2 - sx2 * x1) + (sx2 * sy1 - sx1 * sy2) * x0) / denom; - var dy = (sx0 * (sy2 * y1 - sy1 * y2) + sy0 * (sx1 * y2 - sx2 * y1) + (sx2 * sy1 - sx1 * sy2) * y0) / denom; - ctx.transform(m11, m12, m21, m22, dx, dy); - if (RenderTriangle.renderingOn) { - ctx.globalAlpha = this.opacity; - if (this.lighting < 1) { - ctx.globalAlpha = 1; - ctx.fillStyle = 'Black'; - ctx.fillRect(0, 0, RenderTriangle.width, RenderTriangle.height); - ctx.globalAlpha = this.lighting * this.opacity; - } - ctx.drawImage(im, 0, 0); - } - ctx.restore(); - return true; - }, - intersects: function (l, r, t, b, x0, y0, x1, y1, x2, y2) { - if (x0 > l && x0 < r && y0 > t && y0 < b) { - return true; - } - if (x1 > l && x1 < r && y1 > t && y1 < b) { - return true; - } - if (x2 > l && x2 < r && y2 > t && y2 < b) { - return true; - } - var h4 = RenderTriangle.height * 4; - if (this.tileLevel < 4 && ((Math.abs(x0 - x1) > h4) || (Math.abs(y0 - y1) > h4) || (Math.abs(x2 - x1) > h4) || (Math.abs(y2 - y1) > h4) || (Math.abs(x0 - x2) > h4) || (Math.abs(y0 - y2) > h4))) { - return false; - } - return this.lineRectangleIntersect(l, r, t, b, x0, y0, x1, y1) || this.lineRectangleIntersect(l, r, t, b, x1, y1, x2, y2) || this.lineRectangleIntersect(l, r, t, b, x2, y2, x0, y0); - }, - lineRectangleIntersect: function (l, r, t, b, x0, y0, x1, y1) { - var top_intersection; - var bottom_intersection; - var toptrianglepoint; - var bottomtrianglepoint; - var m; - var c; - m = (y1 - y0) / (x1 - x0); - c = y0 - (m * x0); - if (m > 0) { - top_intersection = (m * l + c); - bottom_intersection = (m * r + c); - } - else { - top_intersection = (m * r + c); - bottom_intersection = (m * l + c); - } - if (y0 < y1) { - toptrianglepoint = y0; - bottomtrianglepoint = y1; - } - else { - toptrianglepoint = y1; - bottomtrianglepoint = y0; - } - var topoverlap; - var botoverlap; - topoverlap = (top_intersection > toptrianglepoint) ? top_intersection : toptrianglepoint; - botoverlap = (bottom_intersection < bottomtrianglepoint) ? bottom_intersection : bottomtrianglepoint; - return (topoverlap < botoverlap) && (!((botoverlap < t) || (topoverlap > b))); - } - }; - - - // wwtlib.ScriptInterface - - function ScriptInterface() { - this._missedReady = false; - this.hideTourFeedback = false; - this._smoothAnimation = false; - this._showCaptions = true; - } - ScriptInterface._containsFitsLikeExtentsion = function (url) { - var lowerCaseUrl = url.toLowerCase(); - return (ss.endsWith(lowerCaseUrl, 'fits') || ss.endsWith(lowerCaseUrl, 'ftz') || ss.endsWith(lowerCaseUrl, 'fit') || ss.endsWith(lowerCaseUrl, 'fts')); - }; - ScriptInterface._addImageSet = function (name, gotoTarget, loaded, imageset) { - if (ss.whitespace(name)) { - name = LayerManager.getNextImageSetName(); - } - var imagesetLayer = LayerManager.addImageSetLayerCallback(imageset, name, loaded); - if (gotoTarget) { - var zoom = imageset._guessZoomSetting(WWTControl.singleton.renderContext.viewCamera.zoom); - WWTControl.singleton.gotoRADecZoom(imageset.get_viewCenterX() / 15, imageset.get_viewCenterY(), zoom, false, null); - } - return imagesetLayer; - }; - ScriptInterface._addFitsLayer = function (url, name, gotoTarget, loaded) { - if (ss.whitespace(name)) { - name = LayerManager.getNextFitsName(); - } - var imagesetLayer = new ImageSetLayer(); - var imageset = new Imageset(); - var wcsLoaded = function (wcsImage) { - if ((wcsImage).errored) { - return; - } - var width = ss.truncate(wcsImage.get_sizeX()); - var height = ss.truncate(wcsImage.get_sizeY()); - imageset.setInitialParameters(wcsImage.get_description(), wcsImage.get_filename(), 2, 3, 5, Util.getHashCode(wcsImage.get_filename()), 0, 0, wcsImage.get_scaleY(), '.fits', wcsImage.get_scaleX() > 0, '', wcsImage.get_centerX(), wcsImage.get_centerY(), wcsImage.get_rotation(), false, '', false, false, 1, wcsImage.get_referenceX(), wcsImage.get_referenceY(), wcsImage.get_copyright(), wcsImage.get_creditsUrl(), '', '', 0, ''); - imageset.set_wcsImage(wcsImage); - imagesetLayer.set_imageSet(imageset); - LayerManager.addFitsImageSetLayer(imagesetLayer, name); - if (gotoTarget) { - var zoom = imageset._guessZoomSetting(WWTControl.singleton.renderContext.viewCamera.zoom); - WWTControl.singleton.gotoRADecZoom(wcsImage.get_viewCenterX() / 15, wcsImage.get_viewCenterY(), zoom, false, null); - } - if (loaded != null) { - loaded(imagesetLayer); - } - }; - if (ss.whitespace(name)) { - name = LayerManager.getNextFitsName(); - } - if (RenderContext.useGlVersion2) { - new FitsImage(imageset, url, null, wcsLoaded); - } - else { - new FitsImageJs(imageset, url, null, wcsLoaded); - } - return imagesetLayer; - }; - var ScriptInterface$ = { - add_ready: function (value) { - this.__ready = ss.bindAdd(this.__ready, value); - }, - remove_ready: function (value) { - this.__ready = ss.bindSub(this.__ready, value); - }, - _fireReady: function () { - if (this.__ready != null) { - this.__ready(this, new ss.EventArgs()); - } - else { - this._missedReady = true; - } - }, - add_collectionLoaded: function (value) { - this.__collectionLoaded = ss.bindAdd(this.__collectionLoaded, value); - }, - remove_collectionLoaded: function (value) { - this.__collectionLoaded = ss.bindSub(this.__collectionLoaded, value); - }, - _fireCollectionLoaded: function (url) { - if (this.__collectionLoaded != null) { - this.__collectionLoaded(this, new CollectionLoadedEventArgs(url)); - } - }, - add_colorPickerDisplay: function (value) { - this.__colorPickerDisplay = ss.bindAdd(this.__colorPickerDisplay, value); - }, - remove_colorPickerDisplay: function (value) { - this.__colorPickerDisplay = ss.bindSub(this.__colorPickerDisplay, value); - }, - add_voTableDisplay: function (value) { - this.__voTableDisplay = ss.bindAdd(this.__voTableDisplay, value); - }, - remove_voTableDisplay: function (value) { - this.__voTableDisplay = ss.bindSub(this.__voTableDisplay, value); - }, - add_refreshLayerManager: function (value) { - this.__refreshLayerManager = ss.bindAdd(this.__refreshLayerManager, value); - }, - remove_refreshLayerManager: function (value) { - this.__refreshLayerManager = ss.bindSub(this.__refreshLayerManager, value); - }, - add_arrived: function (value) { - this.__arrived = ss.bindAdd(this.__arrived, value); - }, - remove_arrived: function (value) { - this.__arrived = ss.bindSub(this.__arrived, value); - }, - add_clicked: function (value) { - this.__clicked = ss.bindAdd(this.__clicked, value); - }, - remove_clicked: function (value) { - this.__clicked = ss.bindSub(this.__clicked, value); - }, - add_annotationClicked: function (value) { - this.__annotationClicked = ss.bindAdd(this.__annotationClicked, value); - }, - remove_annotationClicked: function (value) { - this.__annotationClicked = ss.bindSub(this.__annotationClicked, value); - }, - add_imageryLoaded: function (value) { - this.__imageryLoaded = ss.bindAdd(this.__imageryLoaded, value); - }, - remove_imageryLoaded: function (value) { - this.__imageryLoaded = ss.bindSub(this.__imageryLoaded, value); - }, - add_tourReady: function (value) { - this.__tourReady = ss.bindAdd(this.__tourReady, value); - }, - remove_tourReady: function (value) { - this.__tourReady = ss.bindSub(this.__tourReady, value); - }, - add_tourError: function (value) { - this.__tourError = ss.bindAdd(this.__tourError, value); - }, - remove_tourError: function (value) { - this.__tourError = ss.bindSub(this.__tourError, value); - }, - add_tourPaused: function (value) { - this.__tourPaused = ss.bindAdd(this.__tourPaused, value); - }, - remove_tourPaused: function (value) { - this.__tourPaused = ss.bindSub(this.__tourPaused, value); - }, - add_tourResumed: function (value) { - this.__tourResumed = ss.bindAdd(this.__tourResumed, value); - }, - remove_tourResumed: function (value) { - this.__tourResumed = ss.bindSub(this.__tourResumed, value); - }, - add_tourEnded: function (value) { - this.__tourEnded = ss.bindAdd(this.__tourEnded, value); - }, - remove_tourEnded: function (value) { - this.__tourEnded = ss.bindSub(this.__tourEnded, value); - }, - add_slideChanged: function (value) { - this.__slideChanged = ss.bindAdd(this.__slideChanged, value); - }, - remove_slideChanged: function (value) { - this.__slideChanged = ss.bindSub(this.__slideChanged, value); - }, - add_timeScrubberHook: function (value) { - this.__timeScrubberHook = ss.bindAdd(this.__timeScrubberHook, value); - }, - remove_timeScrubberHook: function (value) { - this.__timeScrubberHook = ss.bindSub(this.__timeScrubberHook, value); - }, - setTimeScrubberPosition: function (posLeft) { - LayerManager.setTimeSliderValue(posLeft); - }, - setTimeSlider: function (name, value) { - this.__timeScrubberHook(name, value); - }, - showColorPicker: function (pickerInstance, e) { - if (this.__colorPickerDisplay != null) { - this.__colorPickerDisplay(pickerInstance, e); - } - }, - displayVoTableLayer: function (layer) { - if (this.__voTableDisplay != null) { - this.__voTableDisplay(layer, new ss.EventArgs()); - } - }, - refreshLayerManagerNow: function () { - if (this.__refreshLayerManager != null) { - this.__refreshLayerManager(null, new ss.EventArgs()); - } - }, - _fireTourReady: function () { - if (this.__tourReady != null) { - this.__tourReady(this, new ss.EventArgs()); - } - }, - _fireTourError: function (ex) { - if (this.__tourError != null) { - this.__tourError(ex, new ss.EventArgs()); - } - }, - _fireTourPaused: function () { - if (this.__tourPaused != null) { - this.__tourPaused(this, new ss.EventArgs()); - } - }, - _fireTourResume: function () { - if (this.__tourResumed != null) { - this.__tourResumed(this, new ss.EventArgs()); - } - }, - _fireTourEnded: function () { - if (this.__tourEnded != null) { - this.__tourEnded(this, new ss.EventArgs()); - } - }, - _fireImageryLoaded: function () { - if (this.__imageryLoaded != null) { - this.__imageryLoaded(this, new ss.EventArgs()); - } - }, - _fireClick: function (ra, dec) { - if (this.__clicked != null) { - this.__clicked(this, new ArrivedEventArgs(ra, dec, WWTControl.singleton.renderContext.viewCamera.zoom)); - } - }, - _fireArrived: function (ra, dec, zoom) { - if (this.__arrived != null) { - this.__arrived(this, new ArrivedEventArgs(ra, dec, zoom)); - } - }, - _fireAnnotationclicked: function (RA, Dec, id) { - try { - if (this.__annotationClicked != null) { - this.__annotationClicked(this, new AnnotationClickEventArgs(RA, Dec, id)); - } - } - catch ($e1) { - } - }, - _fireSlideChanged: function (caption) { - try { - if (this.__slideChanged != null) { - this.__slideChanged(this, new SlideChangedEventArgs(caption)); - } - } - catch ($e1) { - } - }, - endInit: function () { - if (this._missedReady) { - this._fireReady(); - } - }, - gotoRaDecZoom: function (ra, dec, zoom, instant, roll) { - if (WWTControl.singleton != null) { - WWTControl.singleton.gotoRADecZoom(ra / 15, dec, zoom * 6, instant, roll); - } - }, - setBackgroundImageByName: function (name) { - if (WWTControl.singleton != null) { - WWTControl.singleton.setBackgroundImageByName(name); - } - }, - addVoTableLayer: function (table) { - return LayerManager.addVoTableLayer(table, 'Vo Table'); - }, - getLayers: function () { - return LayerManager.get_layerList(); - }, - setForegroundImageByName: function (name) { - if (WWTControl.singleton != null) { - WWTControl.singleton.setForegroundImageByName(name); - WWTControl.singleton.renderContext.viewCamera.opacity = 100; - } - }, - setForegroundOpacity: function (opacity) { - if (WWTControl.singleton != null) { - WWTControl.singleton.renderContext.viewCamera.opacity = opacity; - } - }, - addCatalogHipsByName: function (name) { - if (WWTControl.singleton != null) { - WWTControl.singleton.addCatalogHipsByName(name); - } - }, - addCatalogHipsByNameWithCallback: function (name, onLoad) { - if (WWTControl.singleton != null) { - WWTControl.singleton.addCatalogHipsByNameWithCallback(name, onLoad); - } - }, - removeCatalogHipsByName: function (name) { - if (WWTControl.singleton != null) { - WWTControl.singleton.removeCatalogHipsByName(name); - } - }, - getCatalogHipsDataInView: function (name, limit, onComplete) { - if (WWTControl.singleton != null) { - WWTControl.singleton.getCatalogHipsDataInView(name, limit, onComplete); - } - }, - setCutsForFits: function (imagesetName, min, max) { - if (WWTControl.singleton != null) { - WWTControl.singleton.setCutsForFits(imagesetName, min, max); - } - }, - setColorMapForFits: function (imagesetName, colorMapName) { - if (WWTControl.singleton != null) { - WWTControl.singleton.setColorMapForFits(imagesetName, colorMapName); - } - }, - setScaleTypeForFits: function (imagesetName, scaleType) { - if (WWTControl.singleton != null) { - WWTControl.singleton.setScaleTypeForFits(imagesetName, scaleType); - } - }, - hideUI: function (hide) { - }, - loadTour: function (url) { - if (WWTControl.singleton != null) { - WWTControl.singleton.playTour(url); - } - }, - loadFits: function (url) { - return this.loadFitsLayer(url, '', true, null); - }, - loadFitsLayer: function (url, name, gotoTarget, loaded) { - return this.addImageSetLayer(url, 'fits', name, gotoTarget, loaded); - }, - addImageSetLayer: function (url, mode, name, gotoTarget, loaded) { - if (mode != null && mode.toLowerCase() === 'fits') { - return ScriptInterface._addFitsLayer(url, name, gotoTarget, loaded); - } - else if (mode != null && mode.toLowerCase() === 'preloaded') { - var imageset = WWTControl.singleton.getImageSetByUrl(url); - if (imageset != null) { - return ScriptInterface._addImageSet(name, gotoTarget, loaded, imageset); - } - } - else { - var imageset = WWTControl.singleton.getImageSetByUrl(url); - if (imageset != null) { - return ScriptInterface._addImageSet(name, gotoTarget, loaded, imageset); - } - else if (ScriptInterface._containsFitsLikeExtentsion(url)) { - return ScriptInterface._addFitsLayer(url, name, gotoTarget, loaded); - } - } - return null; - }, - setImageSetLayerOrder: function (id, order) { - var layer = LayerManager.get_layerList()[id]; - if (ss.canCast(layer, ImageSetLayer) && order >= 0) { - ss.remove(LayerManager.get_allMaps()[layer.get_referenceFrame()].layers, layer); - LayerManager.get_allMaps()[layer.get_referenceFrame()].layers.splice(order, 0, layer); - } - }, - isUsingWebGl2: function () { - return RenderContext.useGlVersion2; - }, - get_hideTourFeedback: function () { - return this.hideTourFeedback; - }, - set_hideTourFeedback: function (value) { - this.hideTourFeedback = value; - return value; - }, - playTour: function () { - if (WWTControl.singleton != null) { - WWTControl.singleton.playCurrentTour(); - } - }, - stopTour: function () { - if (WWTControl.singleton != null) { - WWTControl.singleton.stopCurrentTour(); - } - }, - loadImageCollection: function (url, loadChildFolders) { - var $this = this; - - this._imageUrl = url; - Wtml.getWtmlFile(url, function () { - $this._fireCollectionLoaded(url); - }, loadChildFolders); - }, - _imageFileLoaded: function () { - this._fireCollectionLoaded(this._imageUrl); - }, - zoom: function (factor) { - if (WWTControl.singleton != null) { - WWTControl.singleton.zoom(factor); - } - return; - }, - getRA: function () { - if (WWTControl.singleton != null) { - return WWTControl.singleton.renderContext.get_RA(); - } - return 0; - }, - getDec: function () { - if (WWTControl.singleton != null) { - return WWTControl.singleton.renderContext.get_dec(); - } - return 0; - }, - createFolder: function () { - var folder = new Folder(); - return folder; - }, - createPolygon: function (fill) { - var p = new Poly(); - p.set_fill(fill); - return p; - }, - createPolyLine: function (fill) { - return new PolyLine(); - }, - createCircle: function (fill) { - var c = new Circle(); - c.set_fill(fill); - return c; - }, - addAnnotation: function (annotation) { - if (annotation != null && ss.canCast(annotation, Annotation)) { - if (WWTControl.singleton != null) { - WWTControl.singleton._addAnnotation(annotation); - } - } - }, - removeAnnotation: function (annotation) { - if (annotation != null) { - if (WWTControl.singleton != null) { - WWTControl.singleton._removeAnnotation(annotation); - } - } - }, - clearAnnotations: function () { - if (WWTControl.singleton != null) { - WWTControl.singleton._clearAnnotations(); - } - }, - get_smoothAnimation: function () { - return this._smoothAnimation; - }, - set_smoothAnimation: function (value) { - this._smoothAnimation = value; - return value; - }, - get_showCaptions: function () { - return this._showCaptions; - }, - set_showCaptions: function (value) { - this._showCaptions = value; - return value; - }, - loadVOTable: function (url, useCurrentView) { - }, - get_fov: function () { - if (WWTControl.singleton != null) { - return WWTControl.singleton.renderContext.viewCamera.zoom / 6; - } - return 60; - } - }; - - - // wwtlib.Settings - - function Settings() { - this.autoRepeatTour = false; - this._localHorizonMode = false; - this._galacticMode = false; - this._constellationBoundryColor = 'blue'; - this._constellationSelectionColor = 'yellow'; - this._constellationFigureColor = 'red'; - this._showConstellationFigures = true; - this._showConstellationBoundries = true; - this._showConstellationSelection = true; - this._showCrosshairs = true; - this._crosshairsColor = 'white'; - this._showEcliptic = false; - this._locationLat = 47.717; - this._locationLng = -122.0858; - this._locationAltitude = 100; - this._showFiledOfView = false; - this._actualPlanetScale = true; - this._fovCamera = 0; - this._fovEyepiece = 0; - this._fovTelescope = 0; - this._showClouds = false; - this._showGrid = false; - this._showHorizon = true; - this._showHorizonPanorama = false; - this._showMoonsAsPointSource = true; - this._showSolarSystem = true; - this._solarSystemStars = true; - this._solarSystemMilkyWay = true; - this._solarSystemCosmos = true; - this._solarSystemOrbits = true; - this._solarSystemOverlays = true; - this._solarSystemLighting = true; - this._solarSystemMultiRes = true; - this._solarSystemScale = 1; - this._smoothPan = true; - this._showElevationModel = true; - this._showEquatorialGridText = false; - this._showGalacticGrid = false; - this._showGalacticGridText = false; - this._showEclipticGrid = false; - this._showEclipticGridText = false; - this._showEclipticOverviewText = false; - this._showAltAzGrid = false; - this._eclipticGridColor = Colors.get_green(); - this._galacticGridColor = Colors.get_cyan(); - this._altAzGridColor = Colors.get_magenta(); - this._precessionChartColor = Colors.get_orange(); - this._eclipticColor = Colors.get_blue(); - this._equatorialGridColor = Colors.get_white(); - this._showAltAzGridText = false; - this._showPrecessionChart = false; - this._showConstellationPictures = false; - this._showConstellationLabels = false; - this._constellationLabelsHeight = 80; - this._solarSystemCMB = true; - this._solarSystemMinorPlanets = false; - this._solarSystemPlanets = true; - this._showEarthSky = true; - this._solarSystemMinorOrbits = false; - this._constellationsEnabled = ''; - this._constellationFiguresFilter = new ConstellationFilter(); - this._constellationBoundariesFilter = new ConstellationFilter(); - this._constellationNamesFilter = new ConstellationFilter(); - this._constellationArtFilter = new ConstellationFilter(); - this._showSkyOverlays = true; - this._showConstellations = true; - this._showSkyNode = true; - this._showSkyGrids = true; - this._showSkyOverlaysIn3d = true; - this._earthCutawayView = false; - this._showISSModel = false; - this._milkyWayModel = false; - this._minorPlanetsFilter = 255; - this._planetOrbitsFilter = 2147483647; - this._constellations = true; - } - Settings.get_current = function () { - if (Settings._active == null) { - Settings._active = new Settings(); - } - return Settings._active; - }; - Settings.get_globalSettings = function () { - if (Settings._active == null) { - Settings._active = new Settings(); - } - return Settings._active; - }; - Settings.get_active = function () { - if (Settings._active == null) { - Settings._active = new Settings(); - } - if (Settings.tourSettings != null) { - return Settings.tourSettings; - } - return Settings._active; - }; - var Settings$ = { - get_constellationFigureColor: function () { - return this._constellationFigureColor; - }, - set_constellationFigureColor: function (value) { - this._constellationFigureColor = value; - return value; - }, - get_constellationBoundryColor: function () { - return this._constellationBoundryColor; - }, - set_constellationBoundryColor: function (value) { - this._constellationBoundryColor = value; - return value; - }, - get_constellationSelectionColor: function () { - return this._constellationSelectionColor; - }, - set_constellationSelectionColor: function (value) { - this._constellationSelectionColor = value; - return value; - }, - get_showCrosshairs: function () { - return this._showCrosshairs; - }, - set_showCrosshairs: function (value) { - this._showCrosshairs = value; - return value; - }, - get_smoothPan: function () { - return this._smoothPan; - }, - set_smoothPan: function (value) { - this._smoothPan = value; - return value; - }, - get_crosshairsColor: function () { - return this._crosshairsColor; - }, - set_crosshairsColor: function (value) { - this._crosshairsColor = value; - return value; - }, - get_actualPlanetScale: function () { - return this._actualPlanetScale; - }, - set_actualPlanetScale: function (value) { - this._actualPlanetScale = value; - return value; - }, - get_fovCamera: function () { - return this._fovCamera; - }, - get_fovEyepiece: function () { - return this._fovEyepiece; - }, - get_fovTelescope: function () { - return this._fovTelescope; - }, - get_locationAltitude: function () { - return this._locationAltitude; - }, - set_locationAltitude: function (value) { - this._locationAltitude = value; - return value; - }, - get_locationLat: function () { - return this._locationLat; - }, - set_locationLat: function (value) { - this._locationLat = value; - return value; - }, - get_locationLng: function () { - return this._locationLng; - }, - set_locationLng: function (value) { - this._locationLng = value; - return value; - }, - get_showClouds: function () { - return this._showClouds; - }, - get_showConstellationBoundries: function () { - return this._showConstellationBoundries; - }, - set_showConstellationBoundries: function (value) { - this._showConstellationBoundries = value; - return value; - }, - get_showConstellationFigures: function () { - return this._showConstellationFigures; - }, - set_showConstellationFigures: function (value) { - this._showConstellationFigures = value; - return value; - }, - get_showConstellationSelection: function () { - return this._showConstellationSelection; - }, - set_showConstellationSelection: function (value) { - this._showConstellationSelection = value; - return value; - }, - get_showEcliptic: function () { - return this._showEcliptic; - }, - set_showEcliptic: function (value) { - this._showEcliptic = value; - return value; - }, - get_showElevationModel: function () { - return this._showElevationModel; - }, - set_showElevationModel: function (value) { - this._showElevationModel = value; - return value; - }, - get_showFieldOfView: function () { - return this._showFiledOfView; - }, - get_showGrid: function () { - return this._showGrid; - }, - set_showGrid: function (value) { - this._showGrid = value; - return value; - }, - get_showHorizon: function () { - return this._showHorizon; - }, - set_showHorizon: function (value) { - this._showHorizon = value; - return value; - }, - get_showHorizonPanorama: function () { - return this._showHorizonPanorama; - }, - get_showMoonsAsPointSource: function () { - return this._showMoonsAsPointSource; - }, - get_showSolarSystem: function () { - return this._showSolarSystem; - }, - set_showSolarSystem: function (value) { - this._showSolarSystem = value; - return value; - }, - get_localHorizonMode: function () { - return this._localHorizonMode; - }, - set_localHorizonMode: function (value) { - this._localHorizonMode = value; - return value; - }, - get_galacticMode: function () { - return this._galacticMode; - }, - set_galacticMode: function (value) { - this._galacticMode = value; - return value; - }, - get_solarSystemStars: function () { - return this._solarSystemStars; - }, - set_solarSystemStars: function (value) { - this._solarSystemStars = value; - return value; - }, - get_solarSystemMilkyWay: function () { - return this._solarSystemMilkyWay; - }, - set_solarSystemMilkyWay: function (value) { - this._solarSystemMilkyWay = value; - return value; - }, - get_solarSystemCosmos: function () { - return this._solarSystemCosmos; - }, - set_solarSystemCosmos: function (value) { - this._solarSystemCosmos = value; - return value; - }, - get_solarSystemOrbits: function () { - return this._solarSystemOrbits; - }, - set_solarSystemOrbits: function (value) { - this._solarSystemOrbits = value; - return value; - }, - get_solarSystemOverlays: function () { - return this._solarSystemOverlays; - }, - set_solarSystemOverlays: function (value) { - this._solarSystemOverlays = value; - return value; - }, - get_solarSystemLighting: function () { - return this._solarSystemLighting; - }, - set_solarSystemLighting: function (value) { - this._solarSystemLighting = value; - return value; - }, - get_solarSystemMultiRes: function () { - return true; - }, - set_solarSystemMultiRes: function (value) { - this._solarSystemMultiRes = value; - return value; - }, - get_solarSystemScale: function () { - return this._solarSystemScale; - }, - set_solarSystemScale: function (value) { - this._solarSystemScale = value; - return value; - }, - get_showEquatorialGridText: function () { - return this._showEquatorialGridText; - }, - set_showEquatorialGridText: function (value) { - this._showEquatorialGridText = value; - return value; - }, - get_showGalacticGrid: function () { - return this._showGalacticGrid; - }, - set_showGalacticGrid: function (value) { - this._showGalacticGrid = value; - return value; - }, - get_showGalacticGridText: function () { - return this._showGalacticGridText; - }, - set_showGalacticGridText: function (value) { - this._showGalacticGridText = value; - return value; - }, - get_showEclipticGrid: function () { - return this._showEclipticGrid; - }, - set_showEclipticGrid: function (value) { - this._showEclipticGrid = value; - return value; - }, - get_showEclipticGridText: function () { - return this._showEclipticGridText; - }, - set_showEclipticGridText: function (value) { - this._showEclipticGridText = value; - return value; - }, - get_showEclipticOverviewText: function () { - return this._showEclipticOverviewText; - }, - set_showEclipticOverviewText: function (value) { - this._showEclipticOverviewText = value; - return value; - }, - get_showAltAzGrid: function () { - return this._showAltAzGrid; - }, - set_showAltAzGrid: function (value) { - this._showAltAzGrid = value; - return value; - }, - get_eclipticGridColor: function () { - return this._eclipticGridColor; - }, - set_eclipticGridColor: function (value) { - this._eclipticGridColor = value; - return value; - }, - get_galacticGridColor: function () { - return this._galacticGridColor; - }, - set_galacticGridColor: function (value) { - this._galacticGridColor = value; - return value; - }, - get_altAzGridColor: function () { - return this._altAzGridColor; - }, - set_altAzGridColor: function (value) { - this._altAzGridColor = value; - return value; - }, - get_precessionChartColor: function () { - return this._precessionChartColor; - }, - set_precessionChartColor: function (value) { - this._precessionChartColor = value; - return value; - }, - get_eclipticColor: function () { - return this._eclipticColor; - }, - set_eclipticColor: function (value) { - this._eclipticColor = value; - return value; - }, - get_equatorialGridColor: function () { - return this._equatorialGridColor; - }, - set_equatorialGridColor: function (value) { - this._equatorialGridColor = value; - return value; - }, - get_showAltAzGridText: function () { - return this._showAltAzGridText; - }, - set_showAltAzGridText: function (value) { - this._showAltAzGridText = value; - return value; - }, - get_showPrecessionChart: function () { - return this._showPrecessionChart; - }, - set_showPrecessionChart: function (value) { - this._showPrecessionChart = value; - return value; - }, - get_showConstellationPictures: function () { - return this._showConstellationPictures; - }, - set_showConstellationPictures: function (value) { - this._showConstellationPictures = value; - return value; - }, - get_showConstellationLabels: function () { - return this._showConstellationLabels; - }, - set_showConstellationLabels: function (value) { - this._showConstellationLabels = value; - return value; - }, - get_constellationLabelsHeight: function () { - return this._constellationLabelsHeight; - }, - set_constellationLabelsHeight: function (value) { - this._constellationLabelsHeight = value; - return value; - }, - get_solarSystemCMB: function () { - return this._solarSystemCMB; - }, - set_solarSystemCMB: function (value) { - this._solarSystemCMB = value; - return value; - }, - get_solarSystemMinorPlanets: function () { - return this._solarSystemMinorPlanets; - }, - set_solarSystemMinorPlanets: function (value) { - this._solarSystemMinorPlanets = value; - return value; - }, - get_solarSystemPlanets: function () { - return this._solarSystemPlanets; - }, - set_solarSystemPlanets: function (value) { - this._solarSystemPlanets = value; - return value; - }, - get_showEarthSky: function () { - return this._showEarthSky; - }, - set_showEarthSky: function (value) { - this._showEarthSky = value; - return value; - }, - get_solarSystemMinorOrbits: function () { - return this._solarSystemMinorOrbits; - }, - set_solarSystemMinorOrbits: function (value) { - this._solarSystemMinorOrbits = value; - return value; - }, - get_constellationsEnabled: function () { - return this._constellationsEnabled; - }, - set_constellationsEnabled: function (value) { - this._constellationsEnabled = value; - return value; - }, - get_constellationFiguresFilter: function () { - return this._constellationFiguresFilter; - }, - set_constellationFiguresFilter: function (value) { - this._constellationFiguresFilter = value; - return value; - }, - get_constellationBoundariesFilter: function () { - return this._constellationBoundariesFilter; - }, - set_constellationBoundariesFilter: function (value) { - this._constellationBoundariesFilter = value; - return value; - }, - get_constellationNamesFilter: function () { - return this._constellationNamesFilter; - }, - set_constellationNamesFilter: function (value) { - this._constellationNamesFilter = value; - return value; - }, - get_constellationArtFilter: function () { - return this._constellationArtFilter; - }, - set_constellationArtFilter: function (value) { - this._constellationArtFilter = value; - return value; - }, - get_showSkyOverlays: function () { - return this._showSkyOverlays; - }, - set_showSkyOverlays: function (value) { - this._showSkyOverlays = value; - return value; - }, - get_showConstellations: function () { - return this._showConstellations; - }, - set_showConstellations: function (value) { - this._showConstellations = value; - return value; - }, - get_showSkyNode: function () { - return this._showSkyNode; - }, - set_showSkyNode: function (value) { - this._showSkyNode = value; - return value; - }, - get_showSkyGrids: function () { - return this._showSkyGrids; - }, - set_showSkyGrids: function (value) { - this._showSkyGrids = value; - return value; - }, - get_showSkyOverlaysIn3d: function () { - return this._showSkyOverlaysIn3d; - }, - set_showSkyOverlaysIn3d: function (value) { - this._showSkyOverlaysIn3d = value; - return value; - }, - get_earthCutawayView: function () { - return this._earthCutawayView; - }, - set_earthCutawayView: function (value) { - this._earthCutawayView = value; - return value; - }, - get_showISSModel: function () { - return this._showISSModel; - }, - set_showISSModel: function (value) { - this._showISSModel = value; - return value; - }, - get_milkyWayModel: function () { - return this._milkyWayModel; - }, - set_milkyWayModel: function (value) { - this._milkyWayModel = value; - return value; - }, - get_minorPlanetsFilter: function () { - return this._minorPlanetsFilter; - }, - set_minorPlanetsFilter: function (value) { - this._minorPlanetsFilter = value; - return value; - }, - get_planetOrbitsFilter: function () { - return this._planetOrbitsFilter; - }, - set_planetOrbitsFilter: function (value) { - this._planetOrbitsFilter = value; - return value; - }, - get_constellations: function () { - return this._constellations; - }, - set_constellations: function (value) { - this._constellations = value; - return value; - }, - getSetting: function (type) { - if (type === 17) { - return new SettingParameter(true, 0, !!0, null); - } - return new SettingParameter(false, 1, false, null); - } - }; - - - // wwtlib.Text3dBatch - - function Text3dBatch(height) { - this.height = 128; - this.items = []; - this._glyphVersion = -1; - this.viewTransform = Matrix3d.get_identity(); - this._textObject = new TextObject(); - this._vertCount = 0; - this.height = (height * 3); - } - var Text3dBatch$ = { - add: function (newItem) { - this.items.push(newItem); - }, - draw: function (renderContext, opacity, color) { - if (renderContext.gl == null) { - var viewPoint = Vector3d._transformCoordinate(renderContext.get_viewPoint(), this.viewTransform); - var drawHeight = (this.height / renderContext.get_fovAngle()) * renderContext.height / 180; - var $enum1 = ss.enumerate(this.items); - while ($enum1.moveNext()) { - var t3d = $enum1.current; - var screenSpacePnt = renderContext.WVP.transform(t3d.center); - if (screenSpacePnt.z < 0) { - continue; - } - if (Vector3d.dot(viewPoint, t3d.center) < 0.55) { - continue; - } - var screenSpaceTop = renderContext.WVP.transform(t3d.top); - var rotation = Math.atan2(screenSpacePnt.x - screenSpaceTop.x, screenSpacePnt.y - screenSpaceTop.y); - var ctx = renderContext.device; - ctx.save(); - ctx.translate(screenSpacePnt.x, screenSpacePnt.y); - ctx.rotate(-rotation); - ctx.globalAlpha = opacity; - ctx.fillStyle = color.toString(); - ctx.font = 'normal' + ' ' + ((false) ? 'bold' : 'normal') + ' ' + Math.round(drawHeight * 1.2).toString() + 'px ' + 'Arial'; - ctx.textBaseline = 'top'; - var tm = ctx.measureText(t3d.text); - ctx.fillText(t3d.text, -tm.width / 2, -drawHeight / 2); - ctx.restore(); - } - } - else { - if (this._glyphCache == null || this._glyphCache.get_version() > this._glyphVersion) { - this.prepareBatch(); - } - if (!this._glyphCache.ready) { - return; - } - TextShader.use(renderContext, this._vertexBuffer.vertexBuffer, this._glyphCache.get_texture().texture2d); - renderContext.gl.drawArrays(4, 0, this._vertexBuffer.count); - } - }, - prepareBatch: function () { - if (this._glyphCache == null) { - this._glyphCache = GlyphCache.getCache(this.height); - } - if (!this._glyphCache.ready) { - return; - } - this._textObject.text = ''; - this._textObject.fontSize = this.height * 0.5; - var verts = []; - var $enum1 = ss.enumerate(this.items); - while ($enum1.moveNext()) { - var t3d = $enum1.current; - var text = t3d.text; - var left = 0; - var top = 0; - var fntAdjust = this._textObject.fontSize / 128; - var factor = 0.6666; - var width = 0; - var height = 0; - for (var i = 0; i < text.length; i++) { - var item = this._glyphCache.getGlyphItem(text.substr(i, 1)); - if (item != null) { - width += item.extents.x; - height = Math.max(item.extents.y, height); - } - } - var size = Vector2d.create(width, height); - t3d.width = size.x * t3d.scale * factor * fntAdjust; - t3d.height = size.y * t3d.scale * factor * fntAdjust; - var charsLeft = text.length; - for (var i = 0; i < charsLeft; i++) { - var item = this._glyphCache.getGlyphItem(text.substr(i, 1)); - if (item != null) { - var position = Rectangle.create(left * t3d.scale * factor, 0 * t3d.scale * factor, item.extents.x * fntAdjust * t3d.scale * factor, item.extents.y * fntAdjust * t3d.scale * factor); - left += (item.extents.x * fntAdjust); - t3d.addGlyphPoints(verts, item.size, position, item.uvRect); - } - } - } - this._vertCount = verts.length; - this._vertexBuffer = new PositionTextureVertexBuffer(this._vertCount); - var vertBuf = this._vertexBuffer.lock(); - for (var i = 0; i < this._vertCount; i++) { - vertBuf[i] = verts[i]; - } - this._vertexBuffer.unlock(); - this._glyphVersion = this._glyphCache.get_version(); - }, - cleanUp: function () { - if (this._vertexBuffer != null) { - this._vertexBuffer = null; - } - this.items.length = 0; - } - }; - - - // wwtlib.GlyphItem - - function GlyphItem(glyph) { - this.referenceCount = 0; - this.glyph = glyph; - this.uvRect = new Rectangle(); - this.size = new Vector2d(); - this.referenceCount = 1; - } - GlyphItem.create = function (glyph, uv, size, extents) { - var temp = new GlyphItem(glyph); - temp.glyph = glyph; - temp.uvRect = uv; - temp.size = size; - temp.extents = extents; - temp.referenceCount = 1; - return temp; - }; - GlyphItem._fromXML = function (node) { - var glyph = node.attributes.getNamedItem('Glyph').nodeValue; - var item = new GlyphItem(glyph); - item.uvRect = Rectangle.create(parseFloat(node.attributes.getNamedItem('UVLeft').nodeValue), parseFloat(node.attributes.getNamedItem('UVTop').nodeValue), parseFloat(node.attributes.getNamedItem('UVWidth').nodeValue), parseFloat(node.attributes.getNamedItem('UVHeight').nodeValue)); - item.size = Vector2d.create(parseFloat(node.attributes.getNamedItem('SizeWidth').nodeValue), parseFloat(node.attributes.getNamedItem('SizeHeight').nodeValue)); - item.extents = Vector2d.create(parseFloat(node.attributes.getNamedItem('ExtentsWidth').nodeValue), parseFloat(node.attributes.getNamedItem('ExtentsHeight').nodeValue)); - return item; - }; - var GlyphItem$ = { - addRef: function () { - this.referenceCount++; - }, - release: function () { - this.referenceCount--; - } - }; - - - // wwtlib.GlyphCache - - function GlyphCache(height) { - this._cellHeight = 128; - this._gridSize = 8; - this.ready = false; - this._glyphItems = {}; - this.textObject = new TextObject(); - this._dirty = true; - this._textureDirty = true; - this._version = 0; - this._cellHeight = height; - this._texture = Planets.loadPlanetTexture(URLHelpers.singleton.engineAssetUrl('glyphs1.png')); - this._webFile = new WebFile(URLHelpers.singleton.engineAssetUrl('glyphs1.xml')); - this._webFile.onStateChange = ss.bind('_glyphXmlReady', this); - this._webFile.send(); - } - GlyphCache.getCache = function (height) { - if (!ss.keyExists(GlyphCache._caches, height)) { - GlyphCache._caches[height] = new GlyphCache(height); - } - return GlyphCache._caches[height]; - }; - GlyphCache.cleanUpAll = function () { - ss.clearKeys(GlyphCache._caches); - }; - var GlyphCache$ = { - get_height: function () { - return this._cellHeight; - }, - _glyphXmlReady: function () { - if (this._webFile.get_state() === 2) { - alert(this._webFile.get_message()); - } - else if (this._webFile.get_state() === 1) { - this._loadXmlGlyph(this._webFile.getXml()); - } - }, - _loadXmlGlyph: function (xml) { - var nodes = Util.selectSingleNode(xml, 'GlyphItems'); - var $enum1 = ss.enumerate(nodes.childNodes); - while ($enum1.moveNext()) { - var glyphItem = $enum1.current; - if (glyphItem.nodeName === 'GlyphItem') { - var item = GlyphItem._fromXML(glyphItem); - this._glyphItems[item.glyph] = item; - GlyphCache._allGlyphs = GlyphCache._allGlyphs + item.glyph; - } - } - this.ready = true; - }, - get_texture: function () { - return this._texture; - }, - _makeTexture: function () { - this._calcOrMake(true); - }, - getGlyphItem: function (glyph) { - if (this._dirty) { - this._calculateGlyphDetails(); - } - return this._glyphItems[glyph]; - }, - _calculateGlyphDetails: function () { - this._calcOrMake(false); - }, - _calcOrMake: function (makeTexture) { - }, - get_version: function () { - return this._version; - }, - set_version: function (value) { - this._version = value; - return value; - }, - addGlyph: function (glyph) { - if (!ss.keyExists(this._glyphItems, glyph)) { - var item = new GlyphItem(glyph); - this._glyphItems[glyph] = item; - this._dirty = true; - this._textureDirty = true; - this._version++; - GlyphCache._allGlyphs = GlyphCache._allGlyphs + glyph; - } - else { - this._glyphItems[glyph].addRef(); - } - }, - cleanUp: function () { - this._dirty = true; - this._texture = null; - }, - dispose: function () { - this.cleanUp(); - }, - get_dirty: function () { - return this._dirty; - }, - set_dirty: function (value) { - this._dirty = value; - return value; - } - }; - - - // wwtlib.Text3d - - function Text3d(center, up, text, fontsize, scale) { - this.rotation = 0; - this.tilt = 0; - this.bank = 0; - this._matInit = false; - this.color = Colors.get_white(); - this.sky = true; - this.scale = 0; - this.opacity = 1; - this.text = ''; - this.width = 1; - this.height = 1; - this.alignment = 0; - this.text = text; - this.up = up; - this.center = center; - this.scale = scale; - this.top = Vector3d.addVectors(center, Vector3d.scale(up, scale)); - if (fontsize < 0) { - this.sky = false; - } - } - var Text3d$ = { - addGlyphPoints: function (pointList, size, position, uv) { - var points = new Array(6); - for (var i = 0; i < 6; i++) { - points[i] = new PositionTexture(); - } - var left = Vector3d.cross(this.center, this.up); - var right = Vector3d.cross(this.up, this.center); - left.normalize(); - right.normalize(); - this.up.normalize(); - var upTan = Vector3d.cross(this.center, right); - upTan.normalize(); - if (!this.alignment) { - left.multiply(this.width - position.get_left() * 2); - right.multiply(this.width - ((this.width * 2) - position.get_right() * 2)); - } - else if (this.alignment === 1) { - left.multiply(-position.get_left() * 2); - right.multiply(position.get_right() * 2); - } - var top = upTan.copy(); - var bottom = Vector3d.subtractVectors(Vector3d.get_empty(), upTan); - top.multiply(this.height - position.get_top() * 2); - bottom.multiply(this.height - ((this.height * 2) - position.get_bottom() * 2)); - var ul = this.center.copy(); - ul.add(top); - if (this.sky) { - ul.add(left); - } - else { - ul.subtract(left); - } - var ur = this.center.copy(); - ur.add(top); - if (this.sky) { - ur.add(right); - } - else { - ur.subtract(right); - } - var ll = this.center.copy(); - if (this.sky) { - ll.add(left); - } - else { - ll.subtract(left); - } - ll.add(bottom); - var lr = this.center.copy(); - if (this.sky) { - lr.add(right); - } - else { - lr.subtract(right); - } - lr.add(bottom); - points[0].position = ul.copy(); - points[0].tu = uv.get_left(); - points[0].tv = uv.get_top(); - points[2].tu = uv.get_left(); - points[2].tv = uv.get_bottom(); - points[2].position = ll.copy(); - points[1].tu = uv.get_right(); - points[1].tv = uv.get_top(); - points[1].position = ur.copy(); - points[3].tu = uv.get_right(); - points[3].tv = uv.get_bottom(); - points[3].position = lr.copy(); - points[5].tu = uv.get_right(); - points[5].tv = uv.get_top(); - points[5].position = ur.copy(); - points[4].tu = uv.get_left(); - points[4].tv = uv.get_bottom(); - points[4].position = ll.copy(); - if (!!this.rotation || !!this.tilt || !!this.bank) { - if (!this._matInit) { - var lookAt = Matrix3d.lookAtLH(this.center, new Vector3d(), this.up); - var lookAtInv = lookAt.clone(); - lookAtInv.invert(); - this._rtbMat = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(lookAt, Matrix3d._rotationZ(-this.rotation / 180 * Math.PI)), Matrix3d._rotationX(-this.tilt / 180 * Math.PI)), Matrix3d._rotationY(-this.bank / 180 * Math.PI)), lookAtInv); - this._matInit = true; - } - for (var i = 0; i < 6; i++) { - points[i].position = Vector3d._transformCoordinate(points[i].position, this._rtbMat); - } - } - var $enum1 = ss.enumerate(points); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - pointList.push(pnt); - } - } - }; - - - // wwtlib.SpaceTimeController - - function SpaceTimeController() { - } - SpaceTimeController.updateClock = function () { - if (SpaceTimeController._syncToClock) { - var justNow = SpaceTimeController.get_metaNow(); - if (SpaceTimeController._timeRate !== 1) { - var ts = justNow.getTime() - SpaceTimeController.last.getTime(); - var ticks = (ts * SpaceTimeController._timeRate); - SpaceTimeController._offset += ticks; - } - SpaceTimeController.last = justNow; - try { - SpaceTimeController._now = new Date(justNow.getTime() + SpaceTimeController._offset); - } - catch ($e1) { - SpaceTimeController._now = new Date(1, 12, 25, 23, 59, 59); - SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); - } - if (SpaceTimeController._now.getFullYear() > 4000) { - SpaceTimeController._now = new Date(4000, 12, 31, 23, 59, 59); - SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); - } - if (SpaceTimeController._now.getFullYear() < 1) { - SpaceTimeController._now = new Date(0, 12, 25, 23, 59, 59); - SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); - } - } - }; - SpaceTimeController.getTimeForFutureTime = function (delta) { - try { - if (SpaceTimeController._syncToClock) { - var future = new Date((SpaceTimeController.get_now().getTime() + (delta * 1000) * SpaceTimeController._timeRate)); - return future; - } - else { - return SpaceTimeController.get_now(); - } - } - catch ($e1) { - return SpaceTimeController.get_now(); - } - }; - SpaceTimeController.getJNowForFutureTime = function (delta) { - try { - if (SpaceTimeController._syncToClock) { - var future = new Date(SpaceTimeController.get_now().getTime() + ss.truncate((delta * 1000 * SpaceTimeController._timeRate))); - return SpaceTimeController.utcToJulian(future); - } - else { - return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); - } - } - catch ($e1) { - return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); - } - }; - SpaceTimeController.get_now = function () { - return SpaceTimeController._now; - }; - SpaceTimeController.set_now = function (value) { - SpaceTimeController._now = value; - SpaceTimeController._offset = SpaceTimeController._now - SpaceTimeController.get_metaNow(); - SpaceTimeController.last = SpaceTimeController.get_metaNow(); - return value; - }; - SpaceTimeController.get_metaNow = function () { - return SpaceTimeController._metaNow; - }; - SpaceTimeController.set_metaNow = function (value) { - if (!SpaceTimeController.frameDumping) { - SpaceTimeController._metaNow = value; - } - return value; - }; - SpaceTimeController.nextFrame = function () { - SpaceTimeController._metaNow.setMilliseconds(SpaceTimeController._metaNow.getMilliseconds() + Math.round(1000 / SpaceTimeController.framesPerSecond)); - SpaceTimeController.currentFrameNumber += 1; - }; - SpaceTimeController.get_doneDumping = function () { - return !SpaceTimeController.frameDumping || SpaceTimeController.cancelFrameDump || (SpaceTimeController.currentFrameNumber >= SpaceTimeController.totalFrames); - }; - SpaceTimeController.syncTime = function () { - SpaceTimeController._offset = 0; - SpaceTimeController._now = ss.now(); - SpaceTimeController._syncToClock = true; - }; - SpaceTimeController.get_jNow = function () { - return SpaceTimeController.utcToJulian(SpaceTimeController.get_now()); - }; - SpaceTimeController.get_syncToClock = function () { - return SpaceTimeController._syncToClock; - }; - SpaceTimeController.set_syncToClock = function (value) { - if (SpaceTimeController._syncToClock !== value) { - SpaceTimeController._syncToClock = value; - if (value) { - SpaceTimeController.last = ss.now(); - SpaceTimeController._offset = SpaceTimeController._now - ss.now(); - } - else { - SpaceTimeController._now = new Date(ss.now().getTime() + SpaceTimeController._offset); - } - } - return value; - }; - SpaceTimeController.get_timeRate = function () { - return SpaceTimeController._timeRate; - }; - SpaceTimeController.set_timeRate = function (value) { - SpaceTimeController._timeRate = value; - return value; - }; - SpaceTimeController.get_altitude = function () { - return SpaceTimeController._altitude; - }; - SpaceTimeController.set_altitude = function (value) { - SpaceTimeController._altitude = value; - return value; - }; - SpaceTimeController.get_location = function () { - SpaceTimeController._location = Coordinates.fromLatLng(Settings.get_active().get_locationLat(), Settings.get_active().get_locationLng()); - SpaceTimeController._altitude = Settings.get_active().get_locationAltitude(); - return SpaceTimeController._location; - }; - SpaceTimeController.set_location = function (value) { - if (Settings.get_globalSettings().get_locationLat() !== value.get_lat()) { - Settings.get_globalSettings().set_locationLat(value.get_lat()); - } - if (Settings.get_globalSettings().get_locationLng() !== value.get_lng()) { - Settings.get_globalSettings().set_locationLng(value.get_lng()); - } - SpaceTimeController._location = value; - return value; - }; - SpaceTimeController.julianToUtc = function (jDate) { - var date = new DT(); - date.setJD(jDate, true); - var ms = (date.second() - ss.truncate(date.second())) * 1000; - return new Date(date.year(), date.month() - 1, date.day(), date.hour(), date.minute(), ss.truncate(date.second()), ss.truncate(ms)); - }; - SpaceTimeController._twoLineDateToJulian = function (p) { - var pre1950 = parseInt(p.substring(0, 1)) < 6; - var year = parseInt(((pre1950) ? ' 20' : '19') + p.substring(0, 2)); - var days = parseFloat(p.substring(2, 3)); - var fraction = parseFloat(p.substr(5)); - var date = new Date(year, 0, 1, 0, 0); - return SpaceTimeController.utcToJulian(date) + (days - 1 + fraction); - }; - SpaceTimeController.julianToTwoLineDate = function (jDate) { - return SpaceTimeController.dateToTwoLineDate(SpaceTimeController.julianToUtc(jDate)); - }; - SpaceTimeController.dateToTwoLineDate = function (date) { - var sb = new ss.StringBuilder(); - sb.append(date.getFullYear() % 100); - var fullYear = new Date(date.getFullYear(), 0, 1, 0, 0); - var dayofyear = Math.floor((date - fullYear) / (60 * 60 * 24 * 1000)) + 2; - var day = dayofyear + date.getHours() / 24 + date.getMinutes() / 60 / 24 + date.getSeconds() / 60 / 60 / 24 + date.getMilliseconds() / 1000 / 60 / 60 / 24; - var sDay = SpaceTimeController.tleDayString(day); - sb.append(sDay); - return sb.toString(); - }; - SpaceTimeController.tleDayString = function (day) { - var formated = day.toString(); - var point = formated.indexOf('.'); - if (point === -1) { - point = formated.length; - formated += '.0'; - } - var len = formated.length - point - 1; - var fill = '00000000'; - formated = fill.substr(0, 3 - point) + formated + fill.substr(0, 8 - len); - return formated; - }; - SpaceTimeController.utcToJulian = function (utc) { - var year = utc.getUTCFullYear(); - var month = utc.getUTCMonth() + 1; - var day = utc.getUTCDate(); - var hour = utc.getUTCHours(); - var minute = utc.getUTCMinutes(); - var second = utc.getUTCSeconds() + utc.getUTCMilliseconds() / 1000; - var dblDay = day + (hour / 24) + (minute / 1440) + (second / 86400); - return AstroCalc.getJulianDay(year, month, dblDay); - }; - SpaceTimeController.dateToJD = function (Year, Month, Day, bGregorianCalendar) { - var Y = Year; - var M = Month; - if (M < 3) { - Y = Y - 1; - M = M + 12; - } - var A = 0; - var B = 0; - if (bGregorianCalendar) { - A = ss.truncate((Y / 100)); - B = 2 - A + ss.truncate((A / 4)); - } - return ss.truncate((365.25 * (Y + 4716))) + ss.truncate((30.6001 * (M + 1))) + Day + B - 1524.5; - }; - var SpaceTimeController$ = { - - }; - - - // wwtlib.Star - - function Star(input) { - this.magnitude = 0; - this.RA = 0; - this.dec = 0; - this.BMV = 0; - this.id = 0; - this.absoluteMagnitude = 0; - this.par = 0; - this.distance = 0; - var sa = input.split('\t'); - this.id = parseInt(ss.replaceString(sa[0], 'HIP', '')); - this.dec = parseFloat(sa[3]); - this.RA = parseFloat(sa[2]) / 15; - if (sa.length > 4) { - try { - if (sa[4].toUpperCase() !== 'NULL' && !!sa[4]) { - this.magnitude = parseFloat(sa[4]); - } - } - catch ($e1) { - } - } - if (sa.length > 5) { - try { - this.BMV = parseFloat(sa[5]); - this._makeColor(this.BMV); - } - catch ($e2) { - } - } - if (sa.length > 6) { - this.par = parseFloat(sa[6]); - this._makeDistanceAndMagnitude(); - } - } - var Star$ = { - get_name: function () { - return 'HIP' + this.id.toString(); - }, - get_coordinates: function () { - return Coordinates.fromRaDec(this.RA, this.dec); - }, - get_asPlace: function () { - var place = Place.create(this.get_name(), this.dec, this.RA, 1, Constellations.containment.findConstellationForPoint(this.RA, this.dec), 4, -1); - place.set_magnitude(this.magnitude); - place.set_distance(this.distance); - return place; - }, - stars: function (input, newish) { - var sa = input.split('\t'); - this.id = parseInt(sa[0]); - this.RA = parseFloat(sa[1]) / 15; - this.dec = parseFloat(sa[2]); - if (sa.length > 3) { - try { - this.magnitude = parseFloat(sa[3]); - } - catch ($e1) { - } - } - if (sa.length > 4) { - try { - this.col = Color.load(sa[4]); - } - catch ($e2) { - } - } - }, - _makeDistanceAndMagnitude: function () { - this.distance = 1 / (this.par / 1000); - this.absoluteMagnitude = this.magnitude - 5 * (Util.logN(this.distance, 10) - 1); - this.distance *= 206264.806; - }, - _makeColor: function (bmv) { - var c = 4294967295; - if (bmv <= -0.32) { - c = 4288854271; - } - else if (bmv <= -0.31) { - c = 4288919807; - } - else if (bmv <= -0.3) { - c = 4288985855; - } - else if (bmv <= -0.3) { - c = 4289051391; - } - else if (bmv <= -0.28) { - c = 4289182975; - } - else if (bmv <= -0.26) { - c = 4289314303; - } - else if (bmv <= -0.24) { - c = 4289445887; - } - else if (bmv <= -0.2) { - c = 4289708799; - } - else if (bmv <= -0.16) { - c = 4290037503; - } - else if (bmv <= -0.14) { - c = 4290169087; - } - else if (bmv <= -0.12) { - c = 4290366207; - } - else if (bmv <= -0.09) { - c = 4290563583; - } - else if (bmv <= -0.06) { - c = 4290892031; - } - else if (bmv <= 0) { - c = 4291483391; - } - else if (bmv <= 0.06) { - c = 4292009215; - } - else if (bmv <= 0.14) { - c = 4292732159; - } - else if (bmv <= 0.19) { - c = 4293126399; - } - else if (bmv <= 0.31) { - c = 4294111999; - } - else if (bmv <= 0.36) { - c = 4294571775; - } - else if (bmv <= 0.43) { - c = 4294965756; - } - else if (bmv <= 0.54) { - c = 4294964979; - } - else if (bmv <= 0.59) { - c = 4294964203; - } - else if (bmv <= 0.63) { - c = 4294963687; - } - else if (bmv <= 0.66) { - c = 4294963169; - } - else if (bmv <= 0.74) { - c = 4294962909; - } - else if (bmv <= 0.82) { - c = 4294961877; - } - else if (bmv <= 0.92) { - c = 4294960324; - } - else if (bmv <= 1.15) { - c = 4294959032; - } - else if (bmv <= 1.3) { - c = 4294958516; - } - else if (bmv <= 1.41) { - c = 4294955933; - } - else if (bmv <= 1.48) { - c = 4294954385; - } - else if (bmv <= 1.52) { - c = 4294953351; - } - else if (bmv <= 1.55) { - c = 4294952319; - } - else if (bmv <= 1.56) { - c = 4294951287; - } - else if (bmv <= 1.61) { - c = 4294950257; - } - else if (bmv <= 1.72) { - c = 4294948966; - } - else if (bmv <= 1.84) { - c = 4294947419; - } - else if (bmv <= 2) { - c = 4294946129; - } - this.col = Color.fromInt(c); - } - }; - - - // wwtlib.Galaxy - - function Galaxy(br) { - this.RA = 0; - this.dec = 0; - this.distance = 0; - this.type = 0; - this.eTypeBucket = 0; - this.size = 5; - this.sdssID = 0; - this.sdssID = br.readInt64(); - this.RA = br.readSingle(); - this.dec = br.readSingle(); - this.distance = br.readSingle(); - this.eTypeBucket = br.readByte(); - this.size = br.readSingle(); - } - Galaxy.getEType = function (value) { - var a = 0; - var b = Galaxy._eTypeBuckets.length - 1; - while (b - a > 1) { - var m = (a + b) / 2; - if (value > Galaxy._eTypeBuckets[m]) { - a = m; - } - else { - b = m; - } - } - return a; - }; - var Galaxy$ = { - - }; - - - // wwtlib.LatLngEdges - - function LatLngEdges() { - this.latMin = 0; - this.latMax = 0; - this.lngMin = 0; - this.lngMax = 0; - } - var LatLngEdges$ = { - - }; - - - // wwtlib.Tile - - function Tile() { - this._renderTriangleLists = new Array(4); - this._indexBuffers = new Array(4); - this.level = 0; - this.tileX = 0; - this.tileY = 0; - this.texture = null; - this.texture2d = null; - this.isCatalogTile = false; - this.readyToRender = false; - this.inViewFrustum = true; - this.globalCenter = Vector3d.zero; - this.children = [null, null, null, null]; - this.parent = null; - this.localCenter = new Vector3d(); - this.renderedAtOrBelowGeneration = 0; - this._demScaleFactor = 6371000; - this.demIndex = 0; - this.demAverage = 0; - this.demReady = false; - this.texReady = false; - this.demTile = false; - this.demDownloading = false; - this.renderedGeneration = 0; - this.accomidation = 0; - this.accessCount = 0; - this.downloading = false; - this.geometryCreated = false; - this._isHdTile = false; - this.demSize = 33 * 33; - this._topLeftScreen = new Vector3d(); - this._bottomRightScreen = new Vector3d(); - this._topRightScreen = new Vector3d(); - this._bottomLeftScreen = new Vector3d(); - this.sphereRadius = 0; - this.sphereCenter = new Vector3d(); - this.radius = 1; - this.triangleCount = 0; - this.requestHits = 0; - this.requestPending = false; - this.errored = false; - this._key = null; - this._tileId = null; - this._vertexCount = 0; - this.renderChildPart = null; - this.renderChildPart = new Array(4); - for (var i = 0; i < 4; i++) { - this.renderChildPart[i] = BlendState.create(false, 500); - } - } - Tile.getFrustumList = function () { - try { - return Tile.frustumList; - } - catch ($e1) { - return null; - } - }; - Tile.get_subDivisions = function () { - return 32; - }; - var Tile$ = { - getIndexBuffer: function (index, accomidation) { - return this._indexBuffers[index]; - }, - isPointInTile: function (lat, lng) { - return false; - }, - getSurfacePointAltitude: function (lat, lng, meters) { - return 0; - }, - makeTexture: function () { - if (Tile.prepDevice != null) { - try { - this.texture2d = Tile.prepDevice.createTexture(); - Tile.prepDevice.bindTexture(3553, this.texture2d); - Tile.prepDevice.texParameteri(3553, 10242, 33071); - Tile.prepDevice.texParameteri(3553, 10243, 33071); - if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1 && RenderContext.useGlVersion2) { - Tile.prepDevice.texImage2D(3553, 0, 33326, ss.truncate(this.fitsImage.get_sizeX()), ss.truncate(this.fitsImage.get_sizeY()), 0, 6403, 5126, this.fitsImage.dataUnit); - Tile.prepDevice.texParameteri(3553, 10241, 9728); - Tile.prepDevice.texParameteri(3553, 10240, 9728); - } - else { - var image = this.texture; - if ((!Texture.isPowerOfTwo(this.texture.height) | !Texture.isPowerOfTwo(this.texture.width)) === 1) { - var temp = document.createElement('canvas'); - temp.height = Texture.fitPowerOfTwo(image.height); - temp.width = Texture.fitPowerOfTwo(image.width); - var ctx = temp.getContext('2d'); - ctx.drawImage(image, 0, 0, temp.width, temp.height); - image = temp; - } - Tile.prepDevice.texImage2D(3553, 0, 6408, 6408, 5121, image); - Tile.prepDevice.texParameteri(3553, 10241, 9985); - Tile.prepDevice.generateMipmap(3553); - } - Tile.prepDevice.bindTexture(3553, null); - } - catch ($e1) { - this.errored = true; - } - } - }, - addVertex: function (buffer, index, p) { - buffer[index++] = p.position.x; - buffer[index++] = p.position.y; - buffer[index++] = p.position.z; - buffer[index++] = p.tu; - buffer[index++] = p.tv; - return index; - }, - geoTo3dWithAlt: function (lat, lng, useLocalCenter, rev) { - lat = Math.max(Math.min(90, lat), -90); - lng = Math.max(Math.min(180, lng), -180); - if (!Tile.demEnabled || this.demData == null) { - return this.geoTo3d(lat, lng, useLocalCenter); - } - if (rev) { - lng -= 180; - } - var altitude = this.demData[this.demIndex]; - var retVal = this.geoTo3dWithAltitude(lat, lng, altitude, useLocalCenter); - return retVal; - }, - geoTo3dWithAltitude: function (lat, lng, altitude, useLocalCenter) { - var radius = 1 + (altitude / this.get__demScaleFactor()); - var retVal = Vector3d.create((Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * radius), (Math.sin(lat * Tile.RC) * radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * radius)); - if (useLocalCenter) { - retVal.subtract(this.localCenter); - } - return retVal; - }, - get__demScaleFactor: function () { - return this._demScaleFactor; - }, - set__demScaleFactor: function (value) { - this._demScaleFactor = value; - return value; - }, - requestImage: function () { - var $this = this; - - if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1) { - if (!this.downloading && !this.readyToRender) { - this.downloading = true; - if (RenderContext.useGlVersion2) { - this.fitsImage = new FitsImageTile(this.dataset, this.get_URL(), function (wcsImage) { - $this.downloading = false; - $this.errored = $this.fitsImage.errored; - TileCache.removeFromQueue($this.get_key(), true); - if (!$this.fitsImage.errored) { - if (!$this.level) { - $this.dataset.get_fitsProperties()._fireMainImageLoaded($this.fitsImage); - $this.fitsImage.applyDisplaySettings(); - } - $this.texReady = true; - $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); - $this.requestPending = false; - $this.makeTexture(); - } - }); - } - else { - this.fitsImage = FitsImageJs.createTiledFits(this.dataset, this.get_URL(), function (wcsImage) { - if (!$this.level) { - $this.dataset.get_fitsProperties()._fireMainImageLoaded($this.fitsImage); - } - $this.texReady = true; - $this.downloading = false; - $this.errored = $this.fitsImage.errored; - $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); - $this.requestPending = false; - TileCache.removeFromQueue($this.get_key(), true); - $this.texture2d = wcsImage.getBitmap().getTexture(); - }); - } - } - } - else { - if (this.get_dataset().get_wcsImage() != null) { - this.texReady = true; - this.downloading = false; - this.errored = false; - this.readyToRender = true; - this.requestPending = false; - TileCache.removeFromQueue(this.get_key(), true); - return; - } - if (!this.downloading && !this.readyToRender) { - this.downloading = true; - this.texture = document.createElement('img'); - var xdomimg = this.texture; - this.texture.addEventListener('load', function (e) { - $this.texReady = true; - $this.downloading = false; - $this.errored = false; - $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); - $this.requestPending = false; - TileCache.removeFromQueue($this.get_key(), true); - $this.makeTexture(); - }, false); - this.texture.addEventListener('error', function (e) { - if (!$this.texture.hasAttribute('proxyattempt')) { - $this.texture.setAttribute('proxyattempt', true); - var new_url = URLHelpers.singleton.activateProxy($this.texture.src); - if (new_url != null) { - $this.texture.src = new_url; - return; - } - } - $this.downloading = false; - $this.readyToRender = false; - $this.errored = true; - $this.requestPending = false; - TileCache.removeFromQueue($this.get_key(), true); - }, false); - xdomimg.crossOrigin = 'anonymous'; - this.texture.src = this.get_URL(); - } - } - }, - createDemFromParent: function () { - return false; - }, - _loadDemData: function () { - if (this.demFile == null) { - return this.createDemFromParent(); - } - this.demData = this.demFile; - if (this.demFile.length !== 1089 && this.demFile.length !== 513) { - return this.createDemFromParent(); - } - var total = 0; - var $enum1 = ss.enumerate(this.demData); - while ($enum1.moveNext()) { - var fv = $enum1.current; - total += fv; - } - this.demAverage /= this.demData.length; - return true; - }, - requestDem: function () { - var $this = this; - - if (!this.readyToRender && !this.demDownloading) { - this.demTile = true; - this.demDownloading = true; - Tile.callCount++; - var xhr = new XMLHttpRequest(); - xhr.addEventListener('load', function (e) { - $this.demReady = true; - $this.demDownloading = false; - $this.readyToRender = $this.texReady && ($this.demReady || !$this.demTile); - $this.requestPending = false; - try { - $this.demFile = new Float32Array(xhr.response); - } - catch ($e1) { - } - TileCache.removeFromQueue($this.get_key(), true); - }, false); - xhr.addEventListener('error', function (e) { - $this.demDownloading = false; - $this.demReady = false; - $this.readyToRender = false; - $this.errored = true; - $this.requestPending = false; - TileCache.removeFromQueue($this.get_key(), true); - }, false); - xhr.open('GET', this.get_demURL(), true); - xhr.responseType = 'arraybuffer'; - xhr.send(); - } - }, - draw3D: function (renderContext, opacity) { - this.renderedGeneration = Tile.currentRenderGeneration; - Tile.tilesTouched++; - this.accessCount = TileCache.accessID++; - if (this.errored) { - return false; - } - var xMax = 2; - this.inViewFrustum = true; - if (!this.readyToRender) { - TileCache.addTileToQueue(this); - return false; - } - var transitioning = false; - var childIndex = 0; - var yOffset = 0; - if (this.dataset.get_mercator() || this.dataset.get_bottomsUp()) { - yOffset = 1; - } - var xOffset = 0; - var anythingToRender = false; - var childRendered = false; - for (var y1 = 0; y1 < 2; y1++) { - for (var x1 = 0; x1 < xMax; x1++) { - if (this.level < this.dataset.get_levels()) { - if (this.children[childIndex] == null) { - this.children[childIndex] = TileCache.getTile(this.level + 1, this.tileX * 2 + ((x1 + xOffset) % 2), this.tileY * 2 + ((y1 + yOffset) % 2), this.dataset, this); - } - if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { - this.inViewFrustum = true; - if (this.children[childIndex].isTileBigEnough(renderContext)) { - this.renderChildPart[childIndex].set_targetState(!this.children[childIndex].draw3D(renderContext, opacity)); - if (this.renderChildPart[childIndex].get_targetState()) { - childRendered = true; - } - } - else { - this.renderChildPart[childIndex].set_targetState(true); - } - } - else { - this.renderChildPart[childIndex].set_targetState(this.renderChildPart[childIndex].set_state(false)); - } - if (this.renderChildPart[childIndex].get_targetState() !== this.renderChildPart[childIndex].get_state()) { - transitioning = true; - } - } - else { - this.renderChildPart[childIndex].set_state(true); - } - if (!!this.renderChildPart[childIndex].get_state()) { - anythingToRender = true; - } - childIndex++; - } - } - if (childRendered || anythingToRender) { - this.renderedAtOrBelowGeneration = Tile.currentRenderGeneration; - if (this.parent != null) { - this.parent.renderedAtOrBelowGeneration = this.renderedAtOrBelowGeneration; - } - } - if (!anythingToRender) { - return true; - } - if (!this.createGeometry(renderContext)) { - return false; - } - Tile.tilesInView++; - this.accomidation = this._computeAccomidation(); - for (var i = 0; i < 4; i++) { - if (this.renderChildPart[i].get_targetState()) { - this.renderPart(renderContext, i, (opacity / 100), false); - } - } - return true; - }, - _computeAccomidation: function () { - var accVal = 0; - if (!Tile.useAccomidation) { - return 0; - } - var top = TileCache.getCachedTile(this.level, this.tileX, this.tileY + 1, this.dataset, this); - if (top == null || top.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { - accVal += 1; - } - var right = TileCache.getCachedTile(this.level, this.tileX + 1, this.tileY, this.dataset, this); - if (right == null || right.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { - accVal += 2; - } - var bottom = TileCache.getCachedTile(this.level, this.tileX, this.tileY - 1, this.dataset, this); - if (bottom == null || bottom.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { - accVal += 4; - } - var left = TileCache.getCachedTile(this.level, this.tileX - 1, this.tileY, this.dataset, this); - if (left == null || left.renderedAtOrBelowGeneration < Tile.currentRenderGeneration - 2) { - accVal += 8; - } - return accVal; - }, - renderPart: function (renderContext, part, opacity, combine) { - if (Tile.prepDevice == null) { - var lighting = renderContext.lighting && renderContext.get_sunPosition() != null; - var $enum1 = ss.enumerate(this._renderTriangleLists[part]); - while ($enum1.moveNext()) { - var tri = $enum1.current; - tri.opacity = opacity; - if (lighting) { - var norm = tri.normal.copy(); - renderContext.get_world().multiplyVector(norm); - norm.normalize(); - var light = Vector3d.dot(norm, renderContext.get_sunPosition()); - if (light < 0) { - light = 0; - } - else { - light = Math.min(1, (light * 1)); - } - tri.lighting = light; - } - else { - tri.lighting = 1; - } - tri.draw(renderContext.device, renderContext.WVP); - } - } - else { - if (RenderContext.useGlVersion2 && this.fitsImage != null) { - ColorMapContainer.bindColorMapTexture(Tile.prepDevice, this.dataset.get_fitsProperties().colorMapName); - FitsShader.min = this.dataset.get_fitsProperties().lowerCut; - FitsShader.max = this.dataset.get_fitsProperties().upperCut; - FitsShader.containsBlanks = this.dataset.get_fitsProperties().containsBlanks; - FitsShader.blankValue = this.dataset.get_fitsProperties().blankValue; - FitsShader.bZero = this.dataset.get_fitsProperties().bZero; - FitsShader.bScale = this.dataset.get_fitsProperties().bScale; - FitsShader.scaleType = this.dataset.get_fitsProperties().scaleType; - FitsShader.transparentBlack = this.dataset.get_fitsProperties().transparentBlack; - FitsShader.use(renderContext, this._vertexBuffer, this.getIndexBuffer(part, this.accomidation), this.texture2d, opacity, false, this.globalCenter); - } - else { - TileShader.use(renderContext, this._vertexBuffer, this.getIndexBuffer(part, this.accomidation), this.texture2d, opacity, false, this.globalCenter); - } - renderContext.gl.drawElements(4, this.triangleCount * 3, 5123, 0); - } - }, - cleanUp: function (removeFromParent) { - this.readyToRender = false; - this.demData = null; - this.demFile = null; - this.demDownloading = false; - this.texReady = false; - this.demReady = false; - this.errored = false; - if (this.texture != null) { - this.texture = null; - } - this._renderTriangleLists = new Array(4); - this.geometryCreated = false; - if (removeFromParent && this.parent != null) { - this.parent.removeChild(this); - this.parent = null; - } - if (Tile.prepDevice != null) { - var $enum1 = ss.enumerate(this._indexBuffers); - while ($enum1.moveNext()) { - var buf = $enum1.current; - Tile.prepDevice.deleteBuffer(buf); - } - this._indexBuffers = new Array(4); - if (this._vertexBuffer != null) { - Tile.prepDevice.deleteBuffer(this._vertexBuffer); - this._vertexBuffer = null; - } - if (this.texture2d != null) { - Tile.prepDevice.deleteTexture(this.texture2d); - this.texture2d = null; - } - } - }, - removeChild: function (child) { - for (var i = 0; i < 4; i++) { - if (this.children[i] === child) { - this.children[i] = null; - return; - } - } - }, - createGeometry: function (renderContext) { - if (Tile.demEnabled && this.demReady && this.demData == null) { - if (!this._loadDemData()) { - return false; - } - } - if (Tile.demEnabled && this.demData == null) { - return false; - } - this.readyToRender = true; - return true; - }, - calcSphere: function () { - var corners = new Array(4); - corners[0] = this.topLeft; - corners[1] = this.bottomRight; - corners[2] = this.topRight; - corners[3] = this.bottomLeft; - var result = ConvexHull.findEnclosingSphere(corners); - this.sphereCenter = result.center; - this.sphereRadius = result.radius; - }, - isTileBigEnough: function (renderContext) { - if (this.level > 1) { - var wvp = renderContext.WVP; - wvp._transformTo(this.topLeft, this._topLeftScreen); - wvp._transformTo(this.bottomRight, this._bottomRightScreen); - wvp._transformTo(this.topRight, this._topRightScreen); - wvp._transformTo(this.bottomLeft, this._bottomLeftScreen); - var top = this._topLeftScreen; - top.subtract(this._topRightScreen); - var topLength = top.length(); - var bottom = this._bottomLeftScreen; - bottom.subtract(this._bottomRightScreen); - var bottomLength = bottom.length(); - var left = this._bottomLeftScreen; - left.subtract(this._topLeftScreen); - var leftLength = left.length(); - var right = this._bottomRightScreen; - right.subtract(this._topRightScreen); - var rightLength = right.length(); - var lengthMax = Math.max(Math.max(rightLength, leftLength), Math.max(bottomLength, topLength)); - if (lengthMax < 300) { - return false; - } - else { - Tile.deepestLevel = (this.level > Tile.deepestLevel) ? this.level : Tile.deepestLevel; - } - } - return true; - }, - isTileInFrustum: function (frustum) { - if (this.level < 2 && (!this.dataset.get_projection() || this.dataset.get_projection() === 3)) { - } - this.inViewFrustum = false; - var centerV4 = new Vector4d(this.sphereCenter.x, this.sphereCenter.y, this.sphereCenter.z, 1); - for (var i = 0; i < 6; i++) { - if (frustum[i].dot(centerV4) < -this.sphereRadius) { - return false; - } - } - this.inViewFrustum = true; - return true; - }, - get_sphereRadius: function () { - return this.sphereRadius; - }, - get_sphereCenter: function () { - return this.sphereCenter; - }, - geoTo3d: function (lat, lng, useLocalCenter) { - if (this.dataset.get_dataSetType() === 3) { - var retVal = Vector3d.create(-(Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius), (Math.sin(lat * Tile.RC) * this.radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius)); - return retVal; - } - else { - lng -= 180; - var retVal = Vector3d.create((Math.cos(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius), (Math.sin(lat * Tile.RC) * this.radius), (Math.sin(lng * Tile.RC) * Math.cos(lat * Tile.RC) * this.radius)); - return retVal; - } - }, - onCreateVertexBuffer: function (sender, e) { - }, - get_dataset: function () { - return this.dataset; - }, - set_dataset: function (value) { - this.dataset = value; - return value; - }, - get_key: function () { - if (this._key == null) { - this._key = Imageset.getTileKey(this.dataset, this.level, this.tileX, this.tileY, this.parent); - } - return this._key; - }, - get_URL: function () { - var rewritten_url = URLHelpers.singleton.rewrite(this.dataset.get_url(), 0); - var returnUrl = rewritten_url; - if (rewritten_url.indexOf('{1}') > -1) { - if (!this.dataset.get_projection() && !ss.emptyString(this.dataset.get_quadTreeTileMap())) { - returnUrl = ss.format(rewritten_url, this.getServerID(), this.getTileID()); - if (returnUrl.indexOf('virtualearth.net') > -1) { - returnUrl += '&n=z'; - } - return returnUrl; - } - else { - return ss.format(rewritten_url, this.dataset.get_imageSetID(), this.level, this.tileX, this.tileY); - } - } - returnUrl = ss.replaceString(returnUrl, '{X}', this.tileX.toString()); - returnUrl = ss.replaceString(returnUrl, '{Y}', this.tileY.toString()); - returnUrl = ss.replaceString(returnUrl, '{L}', this.level.toString()); - var hash = 0; - if (returnUrl.indexOf('{S:0}') > -1) { - hash = 0; - returnUrl = ss.replaceString(returnUrl, '{S:0}', '{S}'); - } - if (returnUrl.indexOf('{S:1}') > -1) { - hash = 1; - returnUrl = ss.replaceString(returnUrl, '{S:1}', '{S}'); - } - if (returnUrl.indexOf('{S:2}') > -1) { - hash = 2; - returnUrl = ss.replaceString(returnUrl, '{S:2}', '{S}'); - } - if (returnUrl.indexOf('{S:3}') > -1) { - hash = 3; - returnUrl = ss.replaceString(returnUrl, '{S:3}', '{S}'); - } - if (returnUrl.indexOf('a{S}') > -1) { - returnUrl = ss.replaceString(returnUrl, 'a{S}', 'r{S}'); - } - if (returnUrl.indexOf('h{S}') > -1) { - returnUrl = ss.replaceString(returnUrl, 'h{S}', 'r{S}'); - } - if (returnUrl.indexOf('//r{S}.ortho.tiles.virtualearth.net') > -1) { - returnUrl = ss.replaceString(returnUrl, '//r{S}.ortho.tiles.virtualearth.net', '//ecn.t{S}.tiles.virtualearth.net'); - } - var id = this.getTileID(); - var server = ''; - if (!id.length) { - server = hash.toString(); - } - else { - server = id.substr(id.length - 1, 1); - } - returnUrl = ss.replaceString(returnUrl, '{Q}', id); - returnUrl = ss.replaceString(returnUrl, '{S}', server); - if (returnUrl.indexOf('virtualearth.net') > -1) { - returnUrl += '&n=z'; - } - return returnUrl; - }, - get_demURL: function () { - var rewritten_url = URLHelpers.singleton.rewrite(this.dataset.get_demUrl(), 0); - if (!this.dataset.get_projection() && !WWTControl.singleton.freestandingMode) { - var baseUrl = URLHelpers.singleton.coreStaticUrl('wwtweb/demtile.aspx?q={0},{1},{2},M'); - if (!ss.emptyString(rewritten_url)) { - baseUrl = rewritten_url; - } - } - if (rewritten_url.indexOf('{1}') > -1) { - return ss.format(rewritten_url + '&new', this.level, this.tileX, this.tileY); - } - var returnUrl = rewritten_url; - returnUrl = ss.replaceString(returnUrl, '{X}', this.tileX.toString()); - returnUrl = ss.replaceString(returnUrl, '{Y}', this.tileY.toString()); - returnUrl = ss.replaceString(returnUrl, '{L}', this.level.toString()); - var hash = 0; - if (returnUrl.indexOf('{S:0}') > -1) { - hash = 0; - returnUrl = ss.replaceString(returnUrl, '{S:0}', '{S}'); - } - if (returnUrl.indexOf('{S:1}') > -1) { - hash = 1; - returnUrl = ss.replaceString(returnUrl, '{S:1}', '{S}'); - } - if (returnUrl.indexOf('{S:2}') > -1) { - hash = 2; - returnUrl = ss.replaceString(returnUrl, '{S:2}', '{S}'); - } - if (returnUrl.indexOf('{S:3}') > -1) { - hash = 3; - returnUrl = ss.replaceString(returnUrl, '{S:3}', '{S}'); - } - var id = this.getTileID(); - var server = ''; - if (!id.length) { - server = hash.toString(); - } - else { - server = id.substr(id.length - 1, 1); - } - returnUrl = ss.replaceString(returnUrl, '{Q}', id); - returnUrl = ss.replaceString(returnUrl, '{S}', server); - return returnUrl; - }, - getServerID: function () { - var server = (this.tileX & 1) + ((this.tileY & 1) << 1); - return server; - }, - getTileID: function () { - if (this._tileId != null) { - return this._tileId; - } - var netLevel = this.level; - var netX = this.tileX; - var netY = this.tileY; - if (this.dataset.get_projection() === 1) { - netLevel++; - } - var tileMap = this.dataset.get_quadTreeTileMap(); - if (!ss.emptyString(tileMap)) { - var sb = new ss.StringBuilder(); - for (var i = netLevel; i > 0; --i) { - var mask = 1 << (i - 1); - var val = 0; - if (!!(netX & mask)) { - val = 1; - } - if (!!(netY & mask)) { - val += 2; - } - sb.append(tileMap.substr(val, 1)); - } - this._tileId = sb.toString(); - return this._tileId; - } - else { - this._tileId = '0'; - return this._tileId; - } - }, - get_vertexCount: function () { - return this._vertexCount; - }, - set_vertexCount: function (value) { - this._vertexCount = value; - return value; - } - }; - - - // wwtlib.TileCache - - function TileCache() { - } - TileCache.get_queueCount = function () { - return ss.keyCount(TileCache._queue); - }; - TileCache.getTile = function (level, x, y, dataset, parent) { - var retTile = null; - var tileKey = Imageset.getTileKey(dataset, level, x, y, parent); - if (!ss.keyExists(TileCache._tiles, tileKey)) { - retTile = Imageset.getNewTile(dataset, level, x, y, parent); - if (retTile != null) { - TileCache._tiles[tileKey] = retTile; - } - } - else { - retTile = TileCache._tiles[tileKey]; - } - var p = 0; - return retTile; - }; - TileCache.getCachedTile = function (level, x, y, dataset, parent) { - if (level < dataset.get_baseLevel()) { - return null; - } - var retTile = null; - var tileKey = Imageset.getTileKey(dataset, level, x, y, parent); - try { - if (!ss.keyExists(TileCache._tiles, tileKey)) { - return null; - } - else { - retTile = TileCache._tiles[tileKey]; - } - } - catch ($e1) { - } - return retTile; - }; - TileCache.getReadyToRenderTileCount = function () { - var notReadyCullList = []; - var readyCullList = []; - try { - try { - var $enum1 = ss.enumerate(ss.keys(TileCache._tiles)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var tile = TileCache._tiles[key]; - if (tile.renderedGeneration < (Tile.currentRenderGeneration - 10) && !(tile.requestPending || tile.downloading)) { - if (tile.readyToRender) { - readyCullList.push(tile); - } - else { - notReadyCullList.push(tile); - } - } - } - } - catch ($e2) { - } - return readyCullList.length; - } - catch ($e3) { - return -1; - } - }; - TileCache.processQueue = function (renderContext) { - while (ss.keyCount(TileCache._queue) > 0 && TileCache.openThreads > 0) { - var minDistance = 100000; - var overlayTile = false; - var maxKey = null; - var level = 1000; - var $enum1 = ss.enumerate(ss.keys(TileCache._queue)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var t = TileCache._queue[key]; - if (!t.requestPending && t.inViewFrustum) { - var vectTemp = Vector3d.makeCopy(t.get_sphereCenter()); - vectTemp._transformByMatrics(renderContext.get_world()); - if (renderContext.space) { - vectTemp.subtract(Vector3d.create(0, 0, -1)); - } - else { - vectTemp.subtract(renderContext.cameraPosition); - } - var distTemp = Math.max(0, vectTemp.length() - t.get_sphereRadius()); - var thisIsOverlay = (t.get_dataset().get_projection() === 2) || (t.get_dataset().get_projection() === 5); - if (distTemp < minDistance && (!overlayTile || thisIsOverlay)) { - minDistance = distTemp; - maxKey = t.get_key(); - level = t.level; - overlayTile = thisIsOverlay; - } - } - } - if (maxKey != null) { - var workTile = TileCache._queue[maxKey]; - workTile.requestPending = true; - TileCache.openThreads--; - if (TileCache.openThreads < 0) { - TileCache.openThreads = 0; - } - workTile.requestImage(); - if (workTile.get_dataset().get_elevationModel()) { - workTile.requestDem(); - } - } - else { - return; - } - } - }; - TileCache.addTileToQueue = function (tile) { - var hitValue; - hitValue = 256; - if (!tile.downloading && !tile.readyToRender) { - if (ss.keyExists(TileCache._queue, tile.get_key())) { - TileCache._queue[tile.get_key()].requestHits += hitValue; - } - else { - tile.requestHits = hitValue; - TileCache._queue[tile.get_key()] = tile; - } - } - return true; - }; - TileCache.removeFromQueue = function (key, complete) { - if (complete) { - var workTile = TileCache._queue[key]; - if (workTile != null) { - workTile.requestPending = false; - delete TileCache._queue[workTile.get_key()]; - } - TileCache.openThreads++; - } - delete TileCache._queue[key]; - }; - TileCache.clearCache = function () { - ss.clearKeys(TileCache._tiles); - }; - TileCache.purgeQueue = function () { - ss.clearKeys(TileCache._queue); - }; - TileCache.purgeLRU = function () { - if (ss.keyCount(TileCache._tiles) < TileCache.maxReadyToRenderSize) { - return; - } - var notReadyCullList = []; - var readyCullList = []; - try { - try { - var $enum1 = ss.enumerate(ss.keys(TileCache._tiles)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var tile = TileCache._tiles[key]; - if (tile.renderedGeneration < (Tile.currentRenderGeneration - 10) && !(tile.requestPending || tile.downloading)) { - if (tile.readyToRender) { - readyCullList.push(tile); - } - else { - notReadyCullList.push(tile); - } - } - } - } - catch ($e2) { - } - TileCache.readyToRenderCount = readyCullList.length; - if (readyCullList.length > TileCache.maxReadyToRenderSize) { - readyCullList.sort(function (t1, t2) { - return (t2.accessCount < t1.accessCount) ? 1 : ((t2.accessCount === t1.accessCount) ? 0 : -1); - }); - var totalToPurge = readyCullList.length - TileCache.maxReadyToRenderSize; - var $enum3 = ss.enumerate(readyCullList); - while ($enum3.moveNext()) { - var tile = $enum3.current; - if (totalToPurge < 1) { - break; - } - tile.cleanUp(false); - totalToPurge--; - } - } - if (ss.keyCount(TileCache._tiles) < TileCache.maxTileCacheSize) { - return; - } - if (notReadyCullList.length > TileCache.maxTileCacheSize) { - notReadyCullList.sort(function (t1, t2) { - return (t2.accessCount < t1.accessCount) ? 1 : ((t2.accessCount === t1.accessCount) ? 0 : -1); - }); - var totalToPurge = notReadyCullList.length - TileCache.maxTileCacheSize; - if (totalToPurge > 20) { - totalToPurge = 20; - } - var $enum4 = ss.enumerate(notReadyCullList); - while ($enum4.moveNext()) { - var tile = $enum4.current; - if (totalToPurge < 1) { - break; - } - tile.cleanUp(true); - delete TileCache._tiles[tile.get_key()]; - totalToPurge--; - } - } - } - catch ($e5) { - } - finally { - } - return; - }; - TileCache.decimateQueue = function () { - var list = []; - var $enum1 = ss.enumerate(ss.keys(TileCache._queue)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var t = TileCache._queue[key]; - if (!t.requestPending) { - t.requestHits = t.requestHits / 2; - try { - if (t.requestHits < 2) { - list.push(t); - } - else if (!t.inViewFrustum) { - list.push(t); - } - } - catch ($e2) { - } - } - } - var $enum3 = ss.enumerate(list); - while ($enum3.moveNext()) { - var t = $enum3.current; - delete TileCache._queue[t.get_key()]; - } - }; - var TileCache$ = { - - }; - - - // wwtlib.DistanceCalc - - function DistanceCalc() { - } - DistanceCalc.lineToPoint = function (l0, l1, p) { - var v = Vector3d.subtractVectors(l1, l0); - var w = Vector3d.subtractVectors(p, l0); - var dist = Vector3d.cross(w, v).length() / v.length(); - return dist; - }; - DistanceCalc.getUVFromInnerPoint = function (ul, ur, ll, lr, pnt) { - ul.normalize(); - ur.normalize(); - ll.normalize(); - lr.normalize(); - pnt.normalize(); - var dUpper = DistanceCalc.lineToPoint(ul, ur, pnt); - var dLower = DistanceCalc.lineToPoint(ll, lr, pnt); - var dVert = dUpper + dLower; - var dRight = DistanceCalc.lineToPoint(ur, lr, pnt); - var dLeft = DistanceCalc.lineToPoint(ul, ll, pnt); - var dHoriz = dRight + dLeft; - return Vector2d.create(dLeft / dHoriz, dUpper / dVert); - }; - var DistanceCalc$ = { - - }; - - - // wwtlib.Tour - - function Tour() { - this.userLevel = 0; - this.classification = 0; - this.averageRating = 0; - this.lengthInSecs = 0; - this._thumbnailUrlField = ''; - } - Tour._fromXml = function (child) { - var temp = new Tour(); - if (child.attributes.getNamedItem('ID') != null) { - temp.id = child.attributes.getNamedItem('ID').nodeValue; - } - if (child.attributes.getNamedItem('TourUrl') != null) { - temp._tourUrl = child.attributes.getNamedItem('TourUrl').nodeValue; - } - if (child.attributes.getNamedItem('Title') != null) { - temp.title = child.attributes.getNamedItem('Title').nodeValue; - } - if (child.attributes.getNamedItem('Description') != null) { - temp.description = child.attributes.getNamedItem('Description').nodeValue; - } - if (child.attributes.getNamedItem('Classification') != null) { - temp.classification = Enums.parse('Classification', child.attributes.getNamedItem('Classification').nodeValue); - } - if (child.attributes.getNamedItem('AuthorEmail') != null) { - temp.authorEmail = child.attributes.getNamedItem('AuthorEmail').nodeValue; - } - if (child.attributes.getNamedItem('Author') != null) { - temp.author = child.attributes.getNamedItem('Author').nodeValue; - } - if (child.attributes.getNamedItem('AuthorURL') != null) { - temp.authorURL = child.attributes.getNamedItem('AuthorURL').nodeValue; - } - if (child.attributes.getNamedItem('AuthorImageUrl') != null) { - temp.authorImageUrl = child.attributes.getNamedItem('AuthorImageUrl').nodeValue; - } - if (child.attributes.getNamedItem('AverageRating') != null) { - temp.averageRating = parseFloat(child.attributes.getNamedItem('AverageRating').nodeValue); - } - if (child.attributes.getNamedItem('LengthInSecs') != null) { - temp.lengthInSecs = parseFloat(child.attributes.getNamedItem('LengthInSecs').nodeValue); - } - if (child.attributes.getNamedItem('OrganizationUrl') != null) { - temp.organizationUrl = child.attributes.getNamedItem('OrganizationUrl').nodeValue; - } - if (child.attributes.getNamedItem('OrganizationName') != null) { - temp.organizationName = child.attributes.getNamedItem('OrganizationName').nodeValue; - } - if (child.attributes.getNamedItem('RelatedTours') != null) { - temp.relatedTours = child.attributes.getNamedItem('RelatedTours').nodeValue; - } - if (child.attributes.getNamedItem('Keywords') != null) { - temp.keywords = child.attributes.getNamedItem('Keywords').nodeValue; - } - if (child.attributes.getNamedItem('ThumbnailUrl') != null) { - temp.set_thumbnailUrl(child.attributes.getNamedItem('ThumbnailUrl').nodeValue); - } - return temp; - }; - var Tour$ = { - get_name: function () { - return this.title; - }, - get_thumbnail: function () { - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - return value; - }, - get_thumbnailUrl: function () { - if (!ss.emptyString(this._thumbnailUrlField)) { - return this._thumbnailUrlField; - } - else if (WWTControl.singleton.freestandingMode) { - return URLHelpers.singleton.engineAssetUrl('thumb_star.jpg'); - } - return ss.format(URLHelpers.singleton.coreStaticUrl('wwtweb/GetTourThumbnail.aspx?GUID={0}'), this.id); - }, - set_thumbnailUrl: function (value) { - this._thumbnailUrlField = value; - return value; - }, - get_tourUrl: function () { - if (ss.emptyString(this._tourUrl) && !WWTControl.singleton.freestandingMode) { - return ss.format(URLHelpers.singleton.coreStaticUrl('wwtweb/GetTour.aspx?GUID={0}'), this.id); - } - else { - return this._tourUrl; - } - }, - set_tourUrl: function (value) { - this._tourUrl = value; - return value; - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_isImage: function () { - return false; - }, - get_isTour: function () { - return true; - }, - get_isFolder: function () { - return false; - }, - get_isCloudCommunityItem: function () { - return false; - }, - get_readOnly: function () { - return false; - }, - get_children: function () { - return []; - } - }; - - - // wwtlib.FileEntry - - function FileEntry(filename, size) { - this.size = 0; - this.offset = 0; - this.filename = filename; - this.size = size; - } - var FileEntry$ = { - toString: function () { - return this.filename; - } - }; - - - // wwtlib.FileCabinet - - function FileCabinet() { - this.tempDirectory = ''; - this._currentOffset = 0; - this._packageID = ''; - this.url = ''; - this.clearFileList(); - } - FileCabinet.fromUrl = function (url, callMe) { - var temp = new FileCabinet(); - temp.url = url; - temp._callMe = callMe; - temp._webFile = new WebFile(url); - temp._webFile.responseType = 'blob'; - temp._webFile.onStateChange = ss.bind('_loadCabinet', temp); - temp._webFile.send(); - return temp; - }; - var FileCabinet$ = { - get_packageID: function () { - return this._packageID; - }, - set_packageID: function (value) { - this._packageID = value; - return value; - }, - addFile: function (filename, data) { - if (data == null) { - return; - } - if (!ss.keyExists(this._fileDirectory, filename)) { - var fe = new FileEntry(filename, data.size); - fe.offset = this._currentOffset; - fe.blob = data; - this.fileList.push(fe); - this._fileDirectory[filename] = fe; - this._currentOffset += fe.size; - } - }, - clearFileList: function () { - if (this.fileList == null) { - this.fileList = []; - } - if (this._fileDirectory == null) { - this._fileDirectory = {}; - } - this.fileList.length = 0; - ss.clearKeys(this._fileDirectory); - this._currentOffset = 0; - }, - packageFiles: function () { - var xmlWriter = new XmlTextWriter(); - xmlWriter.formatting = 1; - xmlWriter._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - xmlWriter._writeStartElement('FileCabinet'); - xmlWriter._writeAttributeString('HeaderSize', '0x0BADFOOD'); - xmlWriter._writeStartElement('Files'); - var $enum1 = ss.enumerate(this.fileList); - while ($enum1.moveNext()) { - var entry = $enum1.current; - xmlWriter._writeStartElement('File'); - xmlWriter._writeAttributeString('Name', entry.filename); - xmlWriter._writeAttributeString('Size', entry.size.toString()); - xmlWriter._writeAttributeString('Offset', entry.offset.toString()); - xmlWriter._writeEndElement(); - } - xmlWriter._writeEndElement(); - xmlWriter._writeFullEndElement(); - xmlWriter._close(); - var data = xmlWriter.body; - var blob = new Blob([data]); - var sizeText = ss.format('0x{0:x8}', blob.size); - data = ss.replaceString(data, '0x0BADFOOD', sizeText); - blob = new Blob([data]); - var blobs = []; - blobs.push(blob); - var $enum2 = ss.enumerate(this.fileList); - while ($enum2.moveNext()) { - var entry = $enum2.current; - blobs.push(entry.blob); - } - var cabBlob = new Blob(blobs, { type: 'application/x-wtt' });; - return cabBlob; - }, - _loadCabinet: function () { - var $this = this; - - if (this._webFile.get_state() === 2) { - alert(this._webFile.get_message()); - } - else if (this._webFile.get_state() === 1) { - this._mainBlob = this._webFile.getBlob(); - var chunck = new FileReader(); - chunck.onloadend = function (e) { - var offset = $this._getSize(chunck.result); - var header = new FileReader(); - header.onloadend = function (ee) { - var data = ss.safeCast(header.result, String); - var xParser = new DOMParser(); - $this.extract(xParser.parseFromString(data, 'text/xml'), offset); - $this._callMe(); - }; - header.readAsText($this._mainBlob.slice(0, offset)); - }; - chunck.readAsText(this._mainBlob.slice(0, 255)); - } - }, - _getSize: function (data) { - var start = data.indexOf('0x'); - if (start === -1) { - return 0; - } - return parseInt(data.substring(start, start + 10), 16); - }, - extract: function (doc, offset) { - try { - var cab = Util.selectSingleNode(doc, 'FileCabinet'); - var files = Util.selectSingleNode(cab, 'Files'); - this.fileList.length = 0; - var $enum1 = ss.enumerate(files.childNodes); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child.nodeName === 'File') { - var fe = new FileEntry(child.attributes.getNamedItem('Name').nodeValue, parseInt(child.attributes.getNamedItem('Size').nodeValue)); - fe.offset = offset; - offset += fe.size; - this.fileList.push(fe); - } - } - } - catch ($e2) { - } - }, - getFileBlob: function (filename) { - var fe = this.getFileEntry(filename); - if (fe != null) { - var ext = filename.substr(filename.lastIndexOf('.')).toLowerCase(); - var type = null; - switch (ext) { - case '.png': - type = 'image/png'; - break; - case '.jpg': - case '.jpeg': - type = 'image/jpeg'; - break; - case '.mp3': - type = 'audio/mpeg3'; - break; - case '.txt': - type = 'text/plain'; - break; - case '.fit': - case '.fits': - type = 'application/octet-stream'; - break; - } - return this._mainBlob.slice(fe.offset, fe.offset + fe.size, type); - } - return null; - }, - getFileEntry: function (filename) { - var $enum1 = ss.enumerate(this.fileList); - while ($enum1.moveNext()) { - var entry = $enum1.current; - if (entry.filename === filename) { - return entry; - } - } - return null; - }, - get_masterFile: function () { - if (this.fileList.length > 0) { - return this.fileList[0].filename; - } - else { - return null; - } - }, - clearTempFiles: function () { - var $enum1 = ss.enumerate(this.fileList); - while ($enum1.moveNext()) { - var entry = $enum1.current; - } - } - }; - - - // wwtlib.SettingParameter - - function SettingParameter(edgeTrigger, opacity, targetState, filter) { - this.targetState = false; - this.edgeTrigger = false; - this.opacity = 0; - this.edgeTrigger = edgeTrigger; - this.opacity = opacity; - this.targetState = targetState; - this.filter = filter; - } - var SettingParameter$ = { - - }; - - - // wwtlib.Overlay - - function Overlay() { - this.isDynamic = false; - this.isDesignTimeOnly = false; - this._name = ''; - this.id = (Overlay.nextId++).toString(); - this._owner = null; - this._url = ''; - this._linkID = ''; - this._domeMatrix = Matrix3d.get_identity(); - this._domeMatX = 0; - this._domeMatY = 0; - this._domeAngle = 0; - this.points = null; - this._animate = false; - this._tweenFactor = 0; - this._endX = 0; - this._endY = 0; - this._endOpacity = 0; - this._endColor = new Color(); - this._endWidth = 0; - this._endHeight = 0; - this._endRotationAngle = 0; - this._anchor = 1; - this._x = 0; - this._y = 0; - this._width = 0; - this._height = 0; - this._color = Colors.get_white(); - this._opacity = 0.5; - this._rotationAngle = 0; - this.currentRotation = 0; - this.texture = null; - this.texture2d = null; - this._interpolationType = 5; - } - Overlay._fromXml = function (owner, overlay) { - if (overlay.attributes == null) { - return null; - } - if (overlay.attributes.getNamedItem('Type') == null) { - return null; - } - var overlayClassName = overlay.attributes.getNamedItem('Type').nodeValue; - var overLayType = ss.replaceString(overlayClassName, 'TerraViewer.', ''); - var newOverlay = null; - switch (overLayType) { - case 'AudioOverlay': - newOverlay = new AudioOverlay(); - break; - case 'BitmapOverlay': - newOverlay = new BitmapOverlay(); - break; - case 'FlipBookOverlay': - newOverlay = new FlipbookOverlay(); - break; - case 'ShapeOverlay': - newOverlay = new ShapeOverlay(); - break; - case 'TextOverlay': - newOverlay = new TextOverlay(); - break; - default: - return null; - } - newOverlay._owner = owner; - newOverlay._initOverlayFromXml(overlay); - return newOverlay; - }; - var Overlay$ = { - get_name: function () { - return this._name; - }, - set_name: function (value) { - this._name = value; - return value; - }, - get_owner: function () { - return this._owner; - }, - set_owner: function (value) { - this._owner = value; - return value; - }, - get_zOrder: function () { - var index = 0; - var $enum1 = ss.enumerate(this._owner.get_overlays()); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (item === this) { - break; - } - index++; - } - return index; - }, - get_url: function () { - return this._url; - }, - set_url: function (value) { - this._url = value; - return value; - }, - get_linkID: function () { - return this._linkID; - }, - set_linkID: function (value) { - this._linkID = value; - return value; - }, - play: function () { - }, - pause: function () { - }, - stop: function () { - }, - seek: function (time) { - }, - makePosition: function (centerX, centerY, offsetX, offsetY, angle) { - centerX -= 960; - centerY -= 558; - var point = Vector3d.create(centerX + offsetX, centerY + offsetY, 1347); - if (!!this._domeMatX || !!this._domeMatY || this._domeAngle !== angle) { - this._domeMatX = centerX; - this._domeMatY = centerY; - this._domeMatrix = Matrix3d.translation(Vector3d.create(-centerX, -centerY, 0)); - this._domeMatrix._multiply(Matrix3d._rotationZ((angle / 180 * Math.PI))); - this._domeMatrix._multiply(Matrix3d.translation(Vector3d.create(centerX, centerY, 0))); - } - point = Vector3d._transformCoordinate(point, this._domeMatrix); - return point; - }, - draw3D: function (renderContext, designTime) { - if (RenderContext.useGl) { - if (this.texture == null || this.isDynamic) { - this.initializeTexture(); - } - if (!this.isDesignTimeOnly || designTime) { - this.initializeGeometry(); - this.updateRotation(); - } - } - else { - } - }, - cleanUp: function () { - if (this.texture != null) { - this.texture = null; - } - this.texture2d = null; - }, - initializeTexture: function () { - }, - prepMultimedia: function () { - }, - cleanUpGeometry: function () { - this.currentRotation = 0; - this.points = null; - }, - initializeGeometry: function () { - if (this.points == null) { - this.currentRotation = 0; - this.points = new Array(4); - this.points[0] = new PositionColoredTextured(); - this.points[0].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, -this.get_height() / 2, this.get_rotationAngle()); - this.points[0].tu = 0; - this.points[0].tv = 0; - this.points[0].color = this.get_color(); - this.points[1] = new PositionColoredTextured(); - this.points[1].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, -this.get_height() / 2, this.get_rotationAngle()); - this.points[1].tu = 1; - this.points[1].tv = 0; - this.points[1].color = this.get_color(); - this.points[2] = new PositionColoredTextured(); - this.points[2].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 2, this.get_rotationAngle()); - this.points[2].tu = 0; - this.points[2].tv = 1; - this.points[2].color = this.get_color(); - this.points[3] = new PositionColoredTextured(); - this.points[3].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, this.get_height() / 2, this.get_rotationAngle()); - this.points[3].tu = 1; - this.points[3].tv = 1; - this.points[3].color = this.get_color(); - } - }, - updateRotation: function () { - }, - get_animate: function () { - return this._animate; - }, - set_animate: function (value) { - if (this._animate !== value) { - this._animate = value; - if (this._animate) { - this._endX = this._x; - this._endY = this._y; - this._endRotationAngle = this._rotationAngle; - this._endColor = this._color; - this._endWidth = this._width; - this._endHeight = this._height; - this.cleanUpGeometry(); - } - else { - this._endX = this._x = this.get_x(); - this._endY = this._y = this.get_y(); - this._endRotationAngle = this._rotationAngle = this.get_rotationAngle(); - this._endColor = this._color = this.get_color(); - this._endWidth = this._width = this.get_width(); - this._endHeight = this._height = this.get_height(); - this.cleanUpGeometry(); - this._tweenFactor = 0; - } - } - return value; - }, - get_tweenFactor: function () { - return this._tweenFactor; - }, - set_tweenFactor: function (value) { - if (!this._animate) { - this._tweenFactor = 0; - } - else { - if (this._tweenFactor !== value) { - this._tweenFactor = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_anchor: function () { - return this._anchor; - }, - set_anchor: function (value) { - this._anchor = value; - return value; - }, - get_position: function () { - return Vector2d.create(this.get_x(), this.get_y()); - }, - set_position: function (value) { - this.set_x(value.x); - this.set_y(value.y); - return value; - }, - get_x: function () { - return (this._x * (1 - this._tweenFactor)) + (this._endX * this._tweenFactor); - }, - set_x: function (value) { - if (this._tweenFactor < 0.5) { - if (this._x !== value) { - this._x = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endX !== value) { - this._endX = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_y: function () { - return (this._y * (1 - this._tweenFactor)) + (this._endY * this._tweenFactor); - }, - set_y: function (value) { - if (this._tweenFactor < 0.5) { - if (this._y !== value) { - this._y = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endY !== value) { - this._endY = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_width: function () { - return (this._width * (1 - this._tweenFactor)) + (this._endWidth * this._tweenFactor); - }, - set_width: function (value) { - if (value < 5 && !!value) { - value = 5; - } - if (this._tweenFactor < 0.5) { - if (this._width !== value) { - this._width = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endWidth !== value) { - this._endWidth = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_height: function () { - return (this._height * (1 - this._tweenFactor)) + (this._endHeight * this._tweenFactor); - }, - set_height: function (value) { - if (value < 5 && !!value) { - value = 5; - } - if (this._tweenFactor < 0.5) { - if (this._height !== value) { - this._height = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endHeight !== value) { - this._endHeight = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_color: function () { - var red = ss.truncate(((this._color.r * (1 - this._tweenFactor)) + (this._endColor.r * this._tweenFactor))); - var green = ss.truncate(((this._color.g * (1 - this._tweenFactor)) + (this._endColor.g * this._tweenFactor))); - var blue = ss.truncate(((this._color.b * (1 - this._tweenFactor)) + (this._endColor.b * this._tweenFactor))); - var alpha = ss.truncate(((this._color.a * (1 - this._tweenFactor)) + (this._endColor.a * this._tweenFactor))); - return Color.fromArgb(Math.max(0, Math.min(255, alpha)), Math.max(0, Math.min(255, red)), Math.max(0, Math.min(255, green)), Math.max(0, Math.min(255, blue))); - }, - set_color: function (value) { - if (this._tweenFactor < 0.5) { - if (this._color !== value) { - this._color = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endColor !== value) { - this._endColor = value; - this.cleanUpGeometry(); - } - } - return value; - }, - get_opacity: function () { - return this.get_color().a / 255; - }, - set_opacity: function (value) { - var col = this.get_color(); - this.set_color(Color.fromArgb(Math.min(255, ss.truncate((value * 255))), col.r, col.g, col.b)); - this._opacity = value; - return value; - }, - get_rotationAngle: function () { - return (this._rotationAngle * (1 - this._tweenFactor)) + (this._endRotationAngle * this._tweenFactor); - }, - set_rotationAngle: function (value) { - if (this._tweenFactor < 0.5) { - if (this._rotationAngle !== value) { - this._rotationAngle = value; - this.cleanUpGeometry(); - } - } - else { - if (this._endRotationAngle !== value) { - this._endRotationAngle = value; - this.cleanUpGeometry(); - } - } - return value; - }, - hitTest: function (pntTest) { - var tempPoints = new Array(1); - tempPoints[0] = Vector2d.create(pntTest.x, pntTest.y); - var mat = Matrix2d.rotateAt(-this.get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.get_x(), this.get_y())); - mat._transformPoints(tempPoints); - var rect = Rectangle.create((this.get_x() - (this.get_width() / 2)), (this.get_y() - (this.get_height() / 2)), this.get_width(), this.get_height()); - return rect.contains(tempPoints[0]); - }, - get_bounds: function () { - return this._bounds; - }, - set_bounds: function (value) { - this._bounds = value; - return value; - }, - get_interpolationType: function () { - return this._interpolationType; - }, - set_interpolationType: function (value) { - this._interpolationType = value; - return value; - }, - saveToXml: function (xmlWriter, saveKeys) { - xmlWriter._writeStartElement('Overlay'); - xmlWriter._writeAttributeString('Id', this.id); - xmlWriter._writeAttributeString('Type', this.getTypeName()); - xmlWriter._writeAttributeString('Name', this.get_name()); - xmlWriter._writeAttributeString('X', this._x.toString()); - xmlWriter._writeAttributeString('Y', this._y.toString()); - xmlWriter._writeAttributeString('Width', this._width.toString()); - xmlWriter._writeAttributeString('Height', this._height.toString()); - xmlWriter._writeAttributeString('Rotation', this._rotationAngle.toString()); - xmlWriter._writeAttributeString('Color', this._color.save()); - xmlWriter._writeAttributeString('Url', this._url); - xmlWriter._writeAttributeString('LinkID', this._linkID); - xmlWriter._writeAttributeString('Animate', this._animate.toString()); - if (this._animate) { - xmlWriter._writeAttributeString('EndX', this._endX.toString()); - xmlWriter._writeAttributeString('EndY', this._endY.toString()); - xmlWriter._writeAttributeString('EndWidth', this._endWidth.toString()); - xmlWriter._writeAttributeString('EndHeight', this._endHeight.toString()); - xmlWriter._writeAttributeString('EndRotation', this._endRotationAngle.toString()); - xmlWriter._writeAttributeString('EndColor', this._endColor.save()); - xmlWriter._writeAttributeString('InterpolationType', Enums.toXml('InterpolationType', this._interpolationType)); - } - xmlWriter._writeAttributeString('Anchor', Enums.toXml('OverlayAnchor', this._anchor)); - this.writeOverlayProperties(xmlWriter); - xmlWriter._writeEndElement(); - }, - getTypeName: function () { - return 'TerraViewer.Overlay'; - }, - addFilesToCabinet: function (fc) { - }, - writeOverlayProperties: function (xmlWriter) { - }, - _initOverlayFromXml: function (node) { - this.id = node.attributes.getNamedItem('Id').nodeValue; - this.set_name(node.attributes.getNamedItem('Name').nodeValue); - this._x = parseFloat(node.attributes.getNamedItem('X').nodeValue); - this._y = parseFloat(node.attributes.getNamedItem('Y').nodeValue); - this._width = parseFloat(node.attributes.getNamedItem('Width').nodeValue); - this._height = parseFloat(node.attributes.getNamedItem('Height').nodeValue); - this._rotationAngle = parseFloat(node.attributes.getNamedItem('Rotation').nodeValue); - this._color = Color.load(node.attributes.getNamedItem('Color').nodeValue); - if (node.attributes.getNamedItem('Url') != null) { - this.set_url(node.attributes.getNamedItem('Url').nodeValue); - } - if (node.attributes.getNamedItem('LinkID') != null) { - this.set_linkID(node.attributes.getNamedItem('LinkID').nodeValue); - } - if (node.attributes.getNamedItem('Animate') != null) { - this._animate = ss.boolean(node.attributes.getNamedItem('Animate').nodeValue); - if (this._animate) { - this._endX = parseFloat(node.attributes.getNamedItem('EndX').nodeValue); - this._endY = parseFloat(node.attributes.getNamedItem('EndY').nodeValue); - this._endColor = Color.load(node.attributes.getNamedItem('EndColor').nodeValue); - this._endWidth = parseFloat(node.attributes.getNamedItem('EndWidth').nodeValue); - this._endHeight = parseFloat(node.attributes.getNamedItem('EndHeight').nodeValue); - this._endRotationAngle = parseFloat(node.attributes.getNamedItem('EndRotation').nodeValue); - if (node.attributes.getNamedItem('InterpolationType') != null) { - this.set_interpolationType(Enums.parse('InterpolationType', node.attributes.getNamedItem('InterpolationType').nodeValue)); - } - } - } - this.initializeFromXml(node); - }, - initializeFromXml: function (node) { - }, - toString: function () { - return this.get_name(); - } - }; - - - // wwtlib.Selection - - function Selection() { - this._singleSelectHandles = null; - this._multiSelectHandles = null; - this._focusHandles = null; - this.selectionSet = []; - this._focus = null; - this._ratio = 1; - this._sprite = new Sprite2d(); - this._centerX = 0; - this._centerY = 0; - } - var Selection$ = { - clearSelection: function () { - this.selectionSet.length = 0; - }, - addSelection: function (overlay) { - if (overlay != null) { - if (!(this.selectionSet.indexOf(overlay) >= 0)) { - this.selectionSet.push(overlay); - } - } - }, - addSelectionRange: function (overlays) { - var $enum1 = ss.enumerate(overlays); - while ($enum1.moveNext()) { - var ov = $enum1.current; - this.selectionSet.push(ov); - } - }, - isOverlaySelected: function (overlay) { - return (this.selectionSet.indexOf(overlay) >= 0); - }, - setSelection: function (overlay) { - this.selectionSet.length = 0; - if (overlay != null) { - this.selectionSet.push(overlay); - } - }, - get_multiSelect: function () { - return this.selectionSet.length > 1; - }, - setSelectionRange: function (overlays) { - this.selectionSet.length = 0; - var $enum1 = ss.enumerate(overlays); - while ($enum1.moveNext()) { - var ov = $enum1.current; - this.selectionSet.push(ov); - } - }, - get_focus: function () { - return this._focus; - }, - set_focus: function (value) { - this._focus = value; - return value; - }, - draw3D: function (renderContext, transparancy) { - this._ratio = 1116 / renderContext.height; - if (this._singleSelectHandles == null) { - this._singleSelectHandles = Texture.fromUrl('images/Selhand.bmp'); - } - if (this._multiSelectHandles == null) { - this._multiSelectHandles = Texture.fromUrl('images/multiSelhand.bmp'); - } - if (this._focusHandles == null) { - this._focusHandles = Texture.fromUrl('images/FocusHandles.png'); - } - if (this.selectionSet.length > 1) { - var $enum1 = ss.enumerate(this.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (overlay === this._focus) { - this._drawSelectionHandles(renderContext, overlay, this._focusHandles); - } - else { - this._drawSelectionHandles(renderContext, overlay, this._multiSelectHandles); - } - } - } - else { - var $enum2 = ss.enumerate(this.selectionSet); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - this._drawSelectionHandles(renderContext, overlay, this._singleSelectHandles); - } - } - }, - _drawSelectionHandles: function (renderContext, overlay, handleTexture) { - var handles = this.makeHandles(overlay); - var angle = overlay.get_rotationAngle(); - var i = 0; - var j = 0; - var $enum1 = ss.enumerate(handles); - while ($enum1.moveNext()) { - var handle = $enum1.current; - Selection._points[i + 0] = new PositionColoredTextured(); - Selection._points[i + 0].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_top() - this._centerY, angle); - Selection._points[i + 0].tu = j * (1 / 9); - Selection._points[i + 0].tv = 0; - Selection._points[i + 0].color = Colors.get_white(); - Selection._points[i + 1] = new PositionColoredTextured(); - Selection._points[i + 1].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_top() - this._centerY, angle); - Selection._points[i + 1].tu = (j + 1) * (1 / 9); - Selection._points[i + 1].tv = 0; - Selection._points[i + 1].color = Colors.get_white(); - Selection._points[i + 2] = new PositionColoredTextured(); - Selection._points[i + 2].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_bottom() - this._centerY, angle); - Selection._points[i + 2].tu = j * (1 / 9); - Selection._points[i + 2].tv = 1; - Selection._points[i + 2].color = Colors.get_white(); - Selection._points[i + 3] = new PositionColoredTextured(); - Selection._points[i + 3].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_top() - this._centerY, angle); - Selection._points[i + 3].tu = (j + 1) * (1 / 9); - Selection._points[i + 3].tv = 0; - Selection._points[i + 3].color = Colors.get_white(); - Selection._points[i + 4] = new PositionColoredTextured(); - Selection._points[i + 4].position = overlay.makePosition(this._centerX, this._centerY, handle.get_right() - this._centerX, handle.get_bottom() - this._centerY, angle); - Selection._points[i + 4].tu = (j + 1) * (1 / 9); - Selection._points[i + 4].tv = 1; - Selection._points[i + 4].color = Colors.get_white(); - Selection._points[i + 5] = new PositionColoredTextured(); - Selection._points[i + 5].position = overlay.makePosition(this._centerX, this._centerY, handle.get_left() - this._centerX, handle.get_bottom() - this._centerY, angle); - Selection._points[i + 5].tu = j * (1 / 9); - Selection._points[i + 5].tv = 1; - Selection._points[i + 5].color = Colors.get_white(); - i += 6; - j++; - } - if (this.get_multiSelect()) { - this._sprite.draw(renderContext, Selection._points, Selection._points.length - 6, handleTexture, false, 1); - } - else { - this._sprite.draw(renderContext, Selection._points, Selection._points.length, handleTexture, false, 1); - } - }, - pointToSelectionSpace: function (pntIn) { - var tempPoints = new Array(1); - tempPoints[0] = Vector2d.create(pntIn.x, pntIn.y); - var mat = Matrix2d.rotateAt(-this.selectionSet[0].get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.selectionSet[0].get_x(), this.selectionSet[0].get_y())); - mat._transformPoints(tempPoints); - return tempPoints[0]; - }, - pointToScreenSpace: function (pntIn) { - var tempPoints = new Array(1); - tempPoints[0] = Vector2d.create(pntIn.x, pntIn.y); - var mat = Matrix2d.rotateAt(this.selectionSet[0].get_rotationAngle() / 180 * Math.PI, Vector2d.create(this.selectionSet[0].get_x(), this.selectionSet[0].get_y())); - mat._transformPoints(tempPoints); - return tempPoints[0]; - }, - hitTest: function (position) { - if (this.selectionSet.length === 1) { - var $enum1 = ss.enumerate(this.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - var handles = this.makeHandles(overlay); - var index = 0; - var testPoint = this.pointToSelectionSpace(position); - var $enum2 = ss.enumerate(handles); - while ($enum2.moveNext()) { - var rectf = $enum2.current; - if (rectf.contains(testPoint)) { - return index; - } - index++; - } - } - } - return 11; - }, - makeHandles: function (overlay) { - var x = ss.truncate((overlay.get_x() - (overlay.get_width() / 2))) + 0.5; - var y = (ss.truncate(overlay.get_y()) - (overlay.get_height() / 2)) + 0.5; - this._centerX = overlay.get_x(); - this._centerY = overlay.get_y(); - var width = overlay.get_width(); - var height = overlay.get_height(); - var handleSize = 12 * this._ratio; - var handles = new Array(9); - handles[0] = Rectangle.create(x - handleSize, y - handleSize, handleSize, handleSize); - handles[1] = Rectangle.create((x + (width / 2)) - (handleSize / 2), y - handleSize, handleSize, handleSize); - handles[2] = Rectangle.create(x + width, y - handleSize, handleSize, handleSize); - handles[3] = Rectangle.create(x + width, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); - handles[4] = Rectangle.create(x + width, (y + height), handleSize, handleSize); - handles[5] = Rectangle.create((x + (width / 2)) - (handleSize / 2), (y + height), handleSize, handleSize); - handles[6] = Rectangle.create(x - handleSize, (y + height), handleSize, handleSize); - handles[7] = Rectangle.create(x - handleSize, (y + (height / 2)) - (handleSize / 2), handleSize, handleSize); - handles[8] = Rectangle.create((x + (width / 2)) - (handleSize / 2), y - 30 * this._ratio, handleSize, handleSize); - return handles; - } - }; - - - // wwtlib.TextObject - - function TextObject() { - this.bold = false; - this.italic = false; - this.underline = false; - this.fontSize = 0; - this.borderStyle = 0; - } - TextObject.create = function (text, bold, italic, underline, fontSize, fontName, forgroundColor, backgroundColor, borderStyle) { - var temp = new TextObject(); - temp.text = text; - temp.bold = bold; - temp.italic = italic; - temp.underline = underline; - temp.fontSize = fontSize; - temp.fontName = fontName; - temp.foregroundColor = forgroundColor; - temp.backgroundColor = backgroundColor; - temp.borderStyle = borderStyle; - return temp; - }; - TextObject._fromXml = function (node) { - var newTextObject = new TextObject(); - newTextObject.text = Util.getInnerText(node); - newTextObject.borderStyle = 0; - newTextObject.bold = ss.boolean(node.attributes.getNamedItem('Bold').nodeValue); - newTextObject.italic = ss.boolean(node.attributes.getNamedItem('Italic').nodeValue); - newTextObject.underline = ss.boolean(node.attributes.getNamedItem('Underline').nodeValue); - newTextObject.fontSize = parseFloat(node.attributes.getNamedItem('FontSize').nodeValue); - newTextObject.fontName = node.attributes.getNamedItem('FontName').nodeValue; - newTextObject.foregroundColor = Color.load(node.attributes.getNamedItem('ForgroundColor').nodeValue); - newTextObject.backgroundColor = Color.load(node.attributes.getNamedItem('BackgroundColor').nodeValue); - if (node.attributes.getNamedItem('BorderStyle') != null) { - newTextObject.borderStyle = Enums.parse('TextBorderStyle', node.attributes.getNamedItem('BorderStyle').nodeValue); - } - return newTextObject; - }; - var TextObject$ = { - toString: function () { - return this.text; - }, - _saveToXml: function (xmlWriter) { - xmlWriter._writeStartElement('TextObject'); - xmlWriter._writeAttributeString('Bold', this.bold.toString()); - xmlWriter._writeAttributeString('Italic', this.italic.toString()); - xmlWriter._writeAttributeString('Underline', this.underline.toString()); - xmlWriter._writeAttributeString('FontSize', this.fontSize.toString()); - xmlWriter._writeAttributeString('FontName', this.fontName); - xmlWriter._writeAttributeString('ForgroundColor', this.foregroundColor.save()); - xmlWriter._writeAttributeString('BackgroundColor', this.backgroundColor.save()); - xmlWriter._writeAttributeString('BorderStyle', Enums.toXml('TextBorderStyle', this.borderStyle)); - xmlWriter._writeString(this.text); - xmlWriter._writeEndElement(); - } - }; - - - // wwtlib.TourDocument - - function TourDocument() { - this._tourDirty = 0; - this._workingDirectory = ''; - this.url = ''; - this._tagId = ''; - this._representativeThumbnailTourstop = 0; - this._id = ''; - this._title = ''; - this._runTime = 0; - this._lastDirtyCheck = 0; - this._description = ''; - this._attributesAndCredits = ''; - this._authorEmailOther = ''; - this._authorEmail = ''; - this._authorUrl = ''; - this._authorPhone = ''; - this._authorContactText = ''; - this._orgName = 'None'; - this._orgUrl = ''; - this._author = ''; - this._authorImageUrl = ''; - this._authorImage = null; - this._organizationUrl = ''; - this._filename = ''; - this._level = 0; - this._type = 268435456; - this._taxonomy = ''; - this._keywords = ''; - this._objects = ''; - this._editMode = false; - this.explicitTourLinks = []; - this.implicitTourLinks = []; - this._tourStops = []; - this._currentTourstopIndex = -1; - this._textureList = {}; - this._textureList2d = {}; - this._fileCache = {}; - this.dontCleanUpTempFiles = false; - this._id = Guid.newGuid().toString(); - } - TourDocument.get_baseWorkingDirectory = function () { - return ''; - }; - TourDocument.fromUrl = function (url, callMe) { - var temp = new TourDocument(); - temp.url = url; - temp._callMe = callMe; - temp._cabinet = FileCabinet.fromUrl(url, ss.bind('_loadXmlDocument', temp)); - return temp; - }; - TourDocument.fromUrlRaw = function (url, callMe) { - var temp = new TourDocument(); - temp.url = url; - temp._callMe = callMe; - temp._cabinet = FileCabinet.fromUrl(url, callMe); - return temp; - }; - var TourDocument$ = { - get_tourDirty: function () { - return this._tourDirty > 0; - }, - set_tourDirty: function (value) { - if (value) { - this._tourDirty++; - } - else { - this._tourDirty = 0; - } - return value; - }, - get_workingDirectory: function () { - if (ss.emptyString(this._workingDirectory)) { - this._workingDirectory = TourDocument.get_baseWorkingDirectory() + this._id + '\\'; - } - return this._workingDirectory; - }, - set_workingDirectory: function (value) { - this._workingDirectory = value; - return value; - }, - _loadXmlDocument: function () { - var $this = this; - - try { - var master = this._cabinet.get_masterFile(); - var doc = new FileReader(); - doc.onloadend = function (ee) { - var data = ss.safeCast(doc.result, String); - var xParser = new DOMParser(); - $this.fromXml(xParser.parseFromString(data, 'text/xml')); - $this._callMe(); - }; - doc.readAsText(this._cabinet.getFileBlob(master)); - } - catch (ex) { - WWTControl.scriptInterface._fireTourError(ex); - } - }, - fromXml: function (doc) { - var root = Util.selectSingleNode(doc, 'Tour'); - this._id = root.attributes.getNamedItem('ID').nodeValue; - this.set_title(root.attributes.getNamedItem('Title').nodeValue); - this.set_author(root.attributes.getNamedItem('Author').nodeValue); - if (root.attributes.getNamedItem('Descirption') != null) { - this.set_description(root.attributes.getNamedItem('Descirption').nodeValue); - } - if (root.attributes.getNamedItem('AuthorEmail') != null) { - this._authorEmail = root.attributes.getNamedItem('AuthorEmail').nodeValue; - } - if (root.attributes.getNamedItem('Keywords') != null) { - this.set_keywords(root.attributes.getNamedItem('Keywords').nodeValue); - } - if (root.attributes.getNamedItem('OrganizationName') != null) { - this.set_orgName(root.attributes.getNamedItem('OrganizationName').nodeValue); - } - this._organizationUrl = root.attributes.getNamedItem('OrganizationUrl').nodeValue; - this._level = Enums.parse('UserLevel', root.attributes.getNamedItem('UserLevel').nodeValue); - this._type = Enums.parse('Classification', root.attributes.getNamedItem('Classification').nodeValue); - this._taxonomy = root.attributes.getNamedItem('Taxonomy').nodeValue; - var TourStops = Util.selectSingleNode(root, 'TourStops'); - var $enum1 = ss.enumerate(TourStops.childNodes); - while ($enum1.moveNext()) { - var tourStop = $enum1.current; - if (tourStop.nodeName === 'TourStop') { - this.addTourStop(TourStop._fromXml(this, tourStop)); - } - } - var Frames = Util.selectSingleNode(root, 'ReferenceFrames'); - if (Frames != null) { - var $enum2 = ss.enumerate(Frames.childNodes); - while ($enum2.moveNext()) { - var frame = $enum2.current; - if (frame.nodeName === 'ReferenceFrame') { - var newFrame = new ReferenceFrame(); - newFrame.initializeFromXml(frame); - if (!ss.keyExists(LayerManager.get_allMaps(), newFrame.name)) { - var map = new LayerMap(newFrame.name, 18); - map.frame = newFrame; - map.loadedFromTour = true; - LayerManager.get_allMaps()[newFrame.name] = map; - } - } - } - LayerManager.connectAllChildren(); - LayerManager.loadTree(); - } - var Layers = Util.selectSingleNode(root, 'Layers'); - if (Layers != null) { - var $enum3 = ss.enumerate(Layers.childNodes); - while ($enum3.moveNext()) { - var layer = $enum3.current; - if (layer.nodeName === 'Layer') { - var newLayer = Layer.fromXml(layer, true); - if (newLayer != null) { - if (ss.canCast(newLayer, ImageSetLayer)) { - var imageSetLayer = newLayer; - var imageset = imageSetLayer.get_imageSet(); - if (imageset.get_projection() === 7 && imageset.get_extension() === '.tsv') { - WWTControl.singleton.addCatalogHips(imageset); - continue; - } - } - var fileName = ss.format('{0}.txt', newLayer.id.toString()); - if (ss.keyExists(LayerManager.get_layerList(), newLayer.id)) { - LayerManager.deleteLayerByID(newLayer.id, true, false); - } - try { - newLayer.loadedFromTour = true; - newLayer.loadData(this, fileName); - LayerManager.add(newLayer, false); - } - catch ($e4) { - } - } - } - } - LayerManager.loadTree(); - } - this._tourDirty = 0; - }, - saveToDataUrl: function () { - return URL.createObjectURL(this.saveToBlob());; - }, - saveToBlob: function () { - var excludeAudio = false; - this.cleanUp(); - var tourXml = this.getTourXML(); - var fc = new FileCabinet(); - fc.set_packageID(this.get_id()); - fc.addFile('Tour.wwtxml', new Blob([tourXml])); - if (this._authorImage != null) { - } - var $enum1 = ss.enumerate(this.get_tourStops()); - while ($enum1.moveNext()) { - var stop = $enum1.current; - stop._addFilesToCabinet(fc, excludeAudio); - } - var masterList = this._createLayerMasterList(); - var $enum2 = ss.enumerate(masterList); - while ($enum2.moveNext()) { - var id = $enum2.current; - if (ss.keyExists(LayerManager.get_layerList(), id)) { - LayerManager.get_layerList()[id].addFilesToCabinet(fc); - } - } - this.set_tourDirty(false); - return fc.packageFiles(); - }, - getTourXML: function () { - var xmlWriter = new XmlTextWriter(); - xmlWriter.formatting = 1; - xmlWriter._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - xmlWriter._writeStartElement('Tour'); - xmlWriter._writeAttributeString('ID', this._id); - xmlWriter._writeAttributeString('Title', this._title); - xmlWriter._writeAttributeString('Descirption', this.get_description()); - xmlWriter._writeAttributeString('Description', this.get_description()); - xmlWriter._writeAttributeString('RunTime', (this.get_runTime() / 1000).toString()); - xmlWriter._writeAttributeString('Author', this._author); - xmlWriter._writeAttributeString('AuthorEmail', this._authorEmail); - xmlWriter._writeAttributeString('OrganizationUrl', this._organizationUrl); - xmlWriter._writeAttributeString('OrganizationName', this.get_orgName()); - xmlWriter._writeAttributeString('Keywords', this.get_keywords()); - xmlWriter._writeAttributeString('UserLevel', Enums.toXml('UserLevel', this._level)); - xmlWriter._writeAttributeString('Classification', Enums.toXml('Classification', this._type)); - xmlWriter._writeAttributeString('Taxonomy', this._taxonomy); - var timeLineTour = this._isTimelineTour(); - xmlWriter._writeAttributeString('TimeLineTour', timeLineTour.toString()); - xmlWriter._writeStartElement('TourStops'); - var $enum1 = ss.enumerate(this.get_tourStops()); - while ($enum1.moveNext()) { - var stop = $enum1.current; - stop._saveToXml(xmlWriter, true); - } - xmlWriter._writeEndElement(); - var masterList = this._createLayerMasterList(); - var referencedFrames = this._getReferenceFrameList(); - xmlWriter._writeStartElement('ReferenceFrames'); - var $enum2 = ss.enumerate(referencedFrames); - while ($enum2.moveNext()) { - var item = $enum2.current; - item.saveToXml(xmlWriter); - } - xmlWriter._writeEndElement(); - xmlWriter._writeStartElement('Layers'); - var $enum3 = ss.enumerate(masterList); - while ($enum3.moveNext()) { - var id = $enum3.current; - if (ss.keyExists(LayerManager.get_layerList(), id)) { - var layer = LayerManager.get_layerList()[id]; - var name = layer.get_name(); - var imageset = WWTControl.singleton.renderContext.getCatalogHipsByName(name); - if (imageset != null) { - var imageSetLayer = ImageSetLayer.create(imageset); - imageSetLayer.id = id; - imageSetLayer.set_name(name); - imageSetLayer.set_referenceFrame('Sky'); - imageSetLayer.saveToXml(xmlWriter); - } - else { - LayerManager.get_layerList()[id].saveToXml(xmlWriter); - } - } - } - xmlWriter._writeEndElement(); - xmlWriter._writeFullEndElement(); - xmlWriter._close(); - return xmlWriter.body; - }, - _getReferenceFrameList: function () { - var list = []; - var $enum1 = ss.enumerate(ss.keys(LayerManager.get_allMaps())); - while ($enum1.moveNext()) { - var key = $enum1.current; - var lm = LayerManager.get_allMaps()[key]; - if ((lm.frame.reference === 18 || lm.frame.reference === 19) && !(list.indexOf(lm.frame) >= 0) && !lm.frame._systemGenerated) { - list.push(lm.frame); - } - } - return list; - }, - _createLayerMasterList: function () { - var masterList = []; - var $enum1 = ss.enumerate(this.get_tourStops()); - while ($enum1.moveNext()) { - var stop = $enum1.current; - var $enum2 = ss.enumerate(ss.keys(stop.layers)); - while ($enum2.moveNext()) { - var id = $enum2.current; - if (!(masterList.indexOf(id) >= 0)) { - if (ss.keyExists(LayerManager.get_layerList(), id)) { - masterList.push(id); - } - } - } - } - return masterList; - }, - _isTimelineTour: function () { - return false; - }, - get_tagId: function () { - return this._tagId; - }, - set_tagId: function (value) { - this._tagId = value; - return value; - }, - get_authorThumbnailFilename: function () { - return 'Author.Png'; - }, - get_tourThumbnailFilename: function () { - if (this._representativeThumbnailTourstop < this._tourStops.length) { - return this._tourStops[this._representativeThumbnailTourstop].get_tourStopThumbnailFilename(); - } - else { - return null; - } - }, - get_id: function () { - return this._id; - }, - set_id: function (value) { - this._id = value; - return value; - }, - get_title: function () { - return this._title; - }, - set_title: function (value) { - this._title = value; - this.set_tourDirty(true); - return value; - }, - get_runTime: function () { - if (!this._runTime || this._lastDirtyCheck !== this._tourDirty) { - this._runTime = this._calculateRunTime(); - this._lastDirtyCheck = this._tourDirty; - } - return this._runTime; - }, - get_description: function () { - return this._description; - }, - set_description: function (value) { - this._description = value; - this.set_tourDirty(true); - return value; - }, - get_attributesAndCredits: function () { - return this._attributesAndCredits; - }, - set_attributesAndCredits: function (value) { - this._attributesAndCredits = value; - this.set_tourDirty(true); - return value; - }, - get_authorEmailOther: function () { - return this._authorEmailOther; - }, - set_authorEmailOther: function (value) { - this._authorEmailOther = value; - this.set_tourDirty(true); - return value; - }, - get_authorEmail: function () { - return this._authorEmail; - }, - set_authorEmail: function (value) { - this._authorEmail = value; - this.set_tourDirty(true); - return value; - }, - get_authorUrl: function () { - return this._authorUrl; - }, - set_authorUrl: function (value) { - this._authorUrl = value; - this.set_tourDirty(true); - return value; - }, - get_authorPhone: function () { - return this._authorPhone; - }, - set_authorPhone: function (value) { - this._authorPhone = value; - this.set_tourDirty(true); - return value; - }, - get_authorContactText: function () { - return this._authorContactText; - }, - set_authorContactText: function (value) { - this._authorContactText = value; - this.set_tourDirty(true); - return value; - }, - get_orgName: function () { - return this._orgName; - }, - set_orgName: function (value) { - this._orgName = value; - this.set_tourDirty(true); - return value; - }, - get_orgUrl: function () { - return this._orgUrl; - }, - set_orgUrl: function (value) { - this._orgUrl = value; - this.set_tourDirty(true); - return value; - }, - get_author: function () { - return this._author; - }, - set_author: function (value) { - this._author = value; - this.set_tourDirty(true); - return value; - }, - get_authorImageUrl: function () { - return this._authorImageUrl; - }, - set_authorImageUrl: function (value) { - this._authorImageUrl = value; - this.set_tourDirty(true); - return value; - }, - get_authorImage: function () { - return this._authorImage; - }, - set_authorImage: function (value) { - this._authorImage = value; - this.set_tourDirty(true); - return value; - }, - get_organizationUrl: function () { - return this._organizationUrl; - }, - set_organizationUrl: function (value) { - this._organizationUrl = value; - this.set_tourDirty(true); - return value; - }, - get_fileName: function () { - return this._filename; - }, - set_fileName: function (value) { - this._filename = value; - return value; - }, - get_level: function () { - return this._level; - }, - set_level: function (value) { - this._level = value; - this.set_tourDirty(true); - return value; - }, - get_type: function () { - return this._type; - }, - set_type: function (value) { - this._type = value; - this.set_tourDirty(true); - return value; - }, - get_taxonomy: function () { - return this._taxonomy; - }, - set_taxonomy: function (value) { - this._taxonomy = value; - this.set_tourDirty(true); - return value; - }, - get_keywords: function () { - return this._keywords; - }, - set_keywords: function (value) { - this._keywords = value; - this.set_tourDirty(true); - return value; - }, - get_objects: function () { - return this._objects; - }, - set_objects: function (value) { - this._objects = value; - this.set_tourDirty(true); - return value; - }, - get_editMode: function () { - return this._editMode; - }, - set_editMode: function (value) { - this._editMode = value; - return value; - }, - get_tourStops: function () { - return this._tourStops; - }, - set_tourStops: function (value) { - this._tourStops = value; - return value; - }, - get_currentTourstopIndex: function () { - return this._currentTourstopIndex; - }, - set_currentTourstopIndex: function (value) { - this._currentTourstopIndex = value; - return value; - }, - addTourStop: function (ts) { - ts.set_owner(this); - this.get_tourStops().push(ts); - this._currentTourstopIndex = this._tourStops.length - 1; - this.set_tourDirty(true); - }, - insertTourStop: function (ts) { - ts.set_owner(this); - if (this._currentTourstopIndex > -1) { - this.get_tourStops().splice(this._currentTourstopIndex, 0, ts); - } - else { - this.get_tourStops().push(ts); - this._currentTourstopIndex = this._tourStops.length - 1; - } - this.set_tourDirty(true); - }, - insertAfterTourStop: function (ts) { - ts.set_owner(this); - if (this._currentTourstopIndex > -1 || this._currentTourstopIndex < this.get_tourStops().length) { - this.get_tourStops().splice(this._currentTourstopIndex + 1, 0, ts); - } - else { - this.get_tourStops().push(ts); - this._currentTourstopIndex = this._tourStops.length - 1; - } - this.set_tourDirty(true); - }, - removeTourStop: function (ts) { - ss.remove(this._tourStops, ts); - if (this._currentTourstopIndex > this._tourStops.length - 1) { - this._currentTourstopIndex--; - } - this.set_tourDirty(true); - }, - _calculateRunTime: function () { - var totalTime = 0; - for (var i = 0; i < this._tourStops.length; i++) { - totalTime += this._tourStops[i].get_duration(); - if (i > 0) { - switch (this._tourStops[i].get__transition()) { - case 0: - if (this._tourStops[i].get_target().get_backgroundImageset() == null || (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() !== 4) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target())))) { - var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); - var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); - totalTime += slew.get_moveTime() * 1000; - } - break; - case 2: - break; - case 1: - break; - case 5: - break; - default: - break; - } - } - } - return ss.truncate(totalTime); - }, - elapsedTimeTillTourstop: function (index) { - if (!index && index >= this._tourStops.length) { - return 0; - } - var totalTime = 0; - for (var i = 0; i < index; i++) { - totalTime += this._tourStops[i].get_duration(); - if (i > 0) { - switch (this._tourStops[i].get__transition()) { - case 0: - var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); - if (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() !== 4) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target()))) { - var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); - totalTime += slew.get_moveTime() * 1000; - } - break; - case 2: - break; - case 1: - break; - case 5: - break; - default: - break; - } - } - } - return totalTime / 1000; - }, - elapsedTimeSinceLastMaster: function (index) { - var masterOut = null; - if (!index && index >= this._tourStops.length) { - return null; - } - var totalTime = 0; - for (var i = 0; i < index; i++) { - if (this._tourStops[i].get_masterSlide()) { - totalTime = 0; - masterOut = this._tourStops[i]; - } - totalTime += this._tourStops[i].get_duration(); - if (i > 0) { - switch (this._tourStops[i].get__transition()) { - case 0: - var start = (this._tourStops[i - 1].get_endTarget() == null) ? this._tourStops[i - 1].get_target().get_camParams() : this._tourStops[i - 1].get_endTarget().get_camParams(); - if (this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() === this._tourStops[i].get_target().get_backgroundImageset().get_dataSetType() && ((this._tourStops[i - 1].get_target().get_backgroundImageset().get_dataSetType() !== 4) || (this._tourStops[i - 1].get_target().get_target() === this._tourStops[i].get_target().get_target()))) { - var slew = ViewMoverSlew.create(start, this._tourStops[i].get_target().get_camParams()); - totalTime += slew.get_moveTime() * 1000; - } - break; - case 2: - break; - case 1: - break; - case 5: - break; - default: - break; - } - } - } - return new MasterTime(masterOut, totalTime / 1000); - }, - getMasterSlideForIndex: function (index) { - var master = -1; - for (var i = 0; i < index; i++) { - if (this._tourStops[i].get_masterSlide()) { - master = i; - } - } - if (master === -1) { - return null; - } - return this._tourStops[master]; - }, - getTourStopIndexByID: function (id) { - if (!id || id === 'Next') { - return this._currentTourstopIndex++; - } - var index = 0; - var $enum1 = ss.enumerate(this._tourStops); - while ($enum1.moveNext()) { - var stop = $enum1.current; - if (stop.get_id() === id) { - return index; - } - index++; - } - return -1; - }, - cleanUp: function () { - }, - getCachedTexture: function (filename, callMe) { - if (this._textureList == null) { - this._textureList = {}; - } - if (ss.keyExists(this._textureList, filename)) { - callMe(); - return this._textureList[filename]; - } - var url = this.getFileStream(filename); - if (!ss.whitespace(url)) { - var texture = document.createElement('img'); - texture.src = this.getFileStream(filename); - texture.addEventListener('load', function () { - callMe(); - }, false); - this._textureList[filename] = texture; - return texture; - } - else { - return null; - } - }, - getCachedTexture2d: function (filename) { - if (this._textureList2d == null) { - this._textureList2d = {}; - } - if (ss.keyExists(this._textureList2d, filename)) { - return this._textureList2d[filename]; - } - var texture = new Texture(); - texture.load(this.getFileStream(filename)); - this._textureList2d[filename] = texture; - return texture; - }, - addCachedFile: function (filename, file) { - this._fileCache[filename] = file; - if (ss.keyExists(this._textureList2d, filename)) { - delete this._textureList2d[filename]; - } - if (ss.keyExists(this._textureList, filename)) { - delete this._textureList[filename]; - } - }, - getFileStream: function (filename) { - var blob = this.getFileBlob(filename); - if (blob == null) { - return null; - } - return URL.createObjectURL(blob);; - }, - getFileBlob: function (filename) { - if (ss.keyExists(this._fileCache, filename)) { - return this._fileCache[filename]; - } - else if (this._cabinet != null) { - return this._cabinet.getFileBlob(this.get_workingDirectory() + filename); - } - else { - return null; - } - }, - get_currentTourStop: function () { - if (this._currentTourstopIndex > -1) { - return this.get_tourStops()[this._currentTourstopIndex]; - } - else { - return null; - } - }, - set_currentTourStop: function (value) { - var i = 0; - var $enum1 = ss.enumerate(this.get_tourStops()); - while ($enum1.moveNext()) { - var stop = $enum1.current; - if (stop === value) { - if (this._currentTourstopIndex > -1) { - } - this._currentTourstopIndex = i; - break; - } - i++; - } - return value; - }, - clearTempFiles: function () { - } - }; - - - // wwtlib.TourEditTab - - function TourEditTab() { - this.musicTrack = new SoundEditor(); - this.voiceTrack = new SoundEditor(); - this._tour = null; - this.tourStopList = new TourStopList(); - this.tourEditorUI = new TourEditor(); - this._contextMenu = new ContextMenuStrip(); - this.nextSlideCallback = null; - this.playing = false; - this._player = null; - this._defultColor = Colors.get_white(); - } - var TourEditTab$ = { - setUiStrings: function () { - }, - get_tour: function () { - return this._tour; - }, - set_tour: function (value) { - this._tour = value; - this.tourEditorUI.set_tour(this._tour); - this.tourStopList.tour = this._tour; - Overlay.defaultAnchor = 1; - if (this._tour.get_tourStops().length > 0) { - WWTControl.singleton.gotoTarget(this._tour.get_tourStops()[0].get_target(), false, true, false); - this._tour.set_currentTourstopIndex(0); - this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); - this.musicTrack.target = this._tour.get_currentTourStop(); - this.voiceTrack.target = this._tour.get_currentTourStop(); - LayerManager.setVisibleLayerList(this._tour.get_currentTourStop().layers); - } - this.setEditMode(this._tour.get_editMode()); - return value; - }, - tour_CurrentTourstopChanged: function () { - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); - if (this.tourEditorUI != null) { - this.tourEditorUI.clearSelection(); - } - this.tourStopList.refresh(); - }, - setFocusedChild: function () { - }, - selectCurrent: function () { - this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); - this.tourStopList.refresh(); - }, - tourEdit_Load: function (sender, e) { - }, - playNow: function (fromStart) { - this.playing = true; - if (this.get_tour().get_editMode() || fromStart) { - this.get_tour().set_currentTourstopIndex(-1); - } - this.setPlayPauseMode(); - }, - _tourPlayer_TourEnded: function (sender, e) { - }, - _endTour_CloseTour: function (sender, e) { - }, - _endTour_LaunchTour: function (sender, e) { - this.playNow(true); - }, - setEditMode: function (visible) { - }, - tourStopList_ItemClicked: function (sender, e) { - if (this._tour.get_currentTourStop() !== e) { - this._tour.set_currentTourStop(e); - if (e != null) { - this.musicTrack.target = this._tour.get_currentTourStop(); - this.voiceTrack.target = this._tour.get_currentTourStop(); - } - else { - this.musicTrack.target = null; - this.voiceTrack.target = null; - } - this.tourEditorUI.clearSelection(); - } - if (this.playing) { - this._playFromHere_Click(sender, new ss.EventArgs()); - } - }, - tourStopList_ItemDoubleClicked: function (sender, e) { - this.showSlideStartPosition(e); - }, - showSlideStartPosition: function (ts) { - this._tour.set_currentTourStop(ts); - if (ts != null) { - this.musicTrack.target = this._tour.get_currentTourStop(); - this.voiceTrack.target = this._tour.get_currentTourStop(); - } - else { - this.musicTrack.target = null; - this.voiceTrack.target = null; - } - this.tourEditorUI.clearSelection(); - if (this._tour.get_currentTourStop() != null) { - this._tour.get_currentTourStop().syncSettings(); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - WWTControl.singleton.gotoTarget(ts.get_target(), false, true, false); - this._tour.get_currentTourStop().set_tweenPosition(0); - this._tour.get_currentTourStop()._updateLayerOpacity(); - LayerManager.setVisibleLayerList(this._tour.get_currentTourStop().layers); - } - }, - tourStopList_MouseClick: function (sender, e) { - if (!this._tour.get_editMode()) { - } - if (this.tourStopList.multipleSelection) { - if (this._contextMenu != null) { - this._contextMenu._dispose(); - } - this._contextMenu = new ContextMenuStrip(); - var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); - var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); - var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(429, 'Paste')); - var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); - cutMenu.click = ss.bind('_cutMenu_Click', this); - copyMenu.click = ss.bind('_copyMenu_Click', this); - pasteMenu.click = ss.bind('_pasteMenu_Click', this); - deleteMenu.click = ss.bind('_deleteMenu_Click', this); - selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); - var sep1 = new ToolStripSeparator(); - this._contextMenu.items.push(selectAllMenu); - this._contextMenu.items.push(sep1); - this._contextMenu.items.push(cutMenu); - this._contextMenu.items.push(copyMenu); - pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; - this._contextMenu.items.push(pasteMenu); - this._contextMenu.items.push(deleteMenu); - this._contextMenu._show(Cursor.get_position()); - } - else if (this._tour.get_currentTourStop() == null) { - if (this._contextMenu != null) { - this._contextMenu._dispose(); - } - this._contextMenu = new ContextMenuStrip(); - var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); - var sep1 = new ToolStripSeparator(); - var sep2 = new ToolStripSeparator(); - var insertSlide = ToolStripMenuItem.create(Language.getLocalizedText(426, 'Add New Slide')); - pasteMenu.click = ss.bind('_pasteMenu_Click', this); - selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); - insertSlide.click = ss.bind('_addNewSlide_Click', this); - pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; - this._contextMenu.items.push(selectAllMenu); - this._contextMenu.items.push(sep1); - this._contextMenu.items.push(pasteMenu); - this._contextMenu.items.push(sep2); - this._contextMenu.items.push(insertSlide); - this._contextMenu._show(Cursor.get_position()); - } - else { - if (this._contextMenu != null) { - this._contextMenu._dispose(); - } - this._contextMenu = new ContextMenuStrip(); - var selectAllMenu = ToolStripMenuItem.create(Language.getLocalizedText(1345, 'Select All')); - var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); - var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(429, 'Paste')); - var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); - var sep1 = new ToolStripSeparator(); - var sep3 = new ToolStripSeparator(); - var sep4 = new ToolStripSeparator(); - var sep5 = new ToolStripSeparator(); - var sep6 = new ToolStripSeparator(); - var sep7 = new ToolStripSeparator(); - var insertSlide = ToolStripMenuItem.create(Language.getLocalizedText(431, 'Insert New Slide')); - var insertDuplicate = ToolStripMenuItem.create(Language.getLocalizedText(627, 'Duplicate Slide at End Position')); - var insertSlideshow = ToolStripMenuItem.create(Language.getLocalizedText(628, 'Merge Tour after slide...')); - var playFromHere = ToolStripMenuItem.create(Language.getLocalizedText(432, 'Preview Tour From Here')); - var sep2 = new ToolStripSeparator(); - var captureThumbnail = ToolStripMenuItem.create(Language.getLocalizedText(433, 'Capture New Thumbnail')); - var setSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(434, 'Set Start Camera Position')); - var setEndSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(435, 'Set End Camera Position')); - var showSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(436, 'Show Start Camera Position')); - var showEndSkyPosition = ToolStripMenuItem.create(Language.getLocalizedText(437, 'Show End Camera Position')); - var masterSlide = ToolStripMenuItem.create(Language.getLocalizedText(438, 'Master Slide')); - var makeTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1346, 'Create Timeline')); - var showTimeline = ToolStripMenuItem.create(Language.getLocalizedText(1347, 'Show Timeline')); - var linkString = this._tour.get_currentTourStop().get_nextSlide(); - switch (linkString) { - case '': - case null: - case 'Next': - linkString = ' (' + Language.getLocalizedText(610, 'Next Slide') + ')'; - break; - case 'Return': - linkString = ' (' + Language.getLocalizedText(602, 'Return to Caller') + ')'; - break; - default: - var index = this.get_tour().getTourStopIndexByID(linkString); - if (index > -1) { - if (ss.emptyString(this._tour.get_tourStops()[index].get_description())) { - linkString = ss.format(' (Slide {0})', index); - } - else { - linkString = ' (' + this._tour.get_tourStops()[index].get_description() + ')'; - } - } - break; - } - var setNextSlide = ToolStripMenuItem.create(Language.getLocalizedText(590, 'Set Next Slide') + linkString); - var trackSpaceTime = ToolStripMenuItem.create(Language.getLocalizedText(439, 'Track Date/Time/Location')); - var fadeInOverlays = ToolStripMenuItem.create(Language.getLocalizedText(629, 'Fade In Slide Elements')); - var properties = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); - var interpolation = ToolStripMenuItem.create(Language.getLocalizedText(1029, 'Animation Tween Type')); - var Linear = ToolStripMenuItem.create(Language.getLocalizedText(1030, 'Linear')); - var Ease = ToolStripMenuItem.create(Language.getLocalizedText(1031, 'Ease In/Out')); - var EaseIn = ToolStripMenuItem.create(Language.getLocalizedText(1032, 'Ease In')); - var EaseOut = ToolStripMenuItem.create(Language.getLocalizedText(1033, 'Ease Out')); - var Exponential = ToolStripMenuItem.create(Language.getLocalizedText(1034, 'Exponential')); - Linear.tag = 0; - Ease.tag = 3; - EaseIn.tag = 1; - EaseOut.tag = 2; - Exponential.tag = 4; - Linear.click = ss.bind('_interpolation_Click', this); - Ease.click = ss.bind('_interpolation_Click', this); - EaseIn.click = ss.bind('_interpolation_Click', this); - EaseOut.click = ss.bind('_interpolation_Click', this); - Exponential.click = ss.bind('_interpolation_Click', this); - switch (this._tour.get_currentTourStop().get_interpolationType()) { - case 0: - Linear.checked = true; - break; - case 1: - EaseIn.checked = true; - break; - case 2: - EaseOut.checked = true; - break; - case 3: - Ease.checked = true; - break; - case 4: - Exponential.checked = true; - break; - default: - break; - } - interpolation.dropDownItems.push(Linear); - interpolation.dropDownItems.push(Ease); - interpolation.dropDownItems.push(EaseIn); - interpolation.dropDownItems.push(EaseOut); - interpolation.dropDownItems.push(Exponential); - selectAllMenu.click = ss.bind('_selectAllMenu_Click', this); - insertDuplicate.click = ss.bind('_insertDuplicate_Click', this); - cutMenu.click = ss.bind('_cutMenu_Click', this); - copyMenu.click = ss.bind('_copyMenu_Click', this); - pasteMenu.click = ss.bind('_pasteMenu_Click', this); - deleteMenu.click = ss.bind('_deleteMenu_Click', this); - insertSlide.click = ss.bind('_insertNewSlide_Click', this); - properties.click = ss.bind('_properties_Click', this); - captureThumbnail.click = ss.bind('_captureThumbnail_Click', this); - setSkyPosition.click = ss.bind('_setSkyPosition_Click', this); - setEndSkyPosition.click = ss.bind('_setEndSkyPosition_Click', this); - showEndSkyPosition.click = ss.bind('_showEndSkyPosition_Click', this); - showSkyPosition.click = ss.bind('_showSkyPosition_Click', this); - playFromHere.click = ss.bind('_playFromHere_Click', this); - masterSlide.click = ss.bind('_masterSlide_Click', this); - setNextSlide.click = ss.bind('_setNextSlide_Click', this); - trackSpaceTime.click = ss.bind('_trackSpaceTime_Click', this); - insertSlideshow.click = ss.bind('_insertSlideshow_Click', this); - fadeInOverlays.click = ss.bind('_fadeInOverlays_Click', this); - if (this._tour.get_currentTourStop().get_masterSlide()) { - masterSlide.checked = true; - } - if (this._tour.get_currentTourStop().get_hasTime()) { - trackSpaceTime.checked = true; - } - fadeInOverlays.checked = this._tour.get_currentTourStop().get_fadeInOverlays(); - this._contextMenu.items.push(selectAllMenu); - this._contextMenu.items.push(sep7); - this._contextMenu.items.push(cutMenu); - this._contextMenu.items.push(copyMenu); - pasteMenu.enabled = this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide'; - this._contextMenu.items.push(pasteMenu); - this._contextMenu.items.push(deleteMenu); - this._contextMenu.items.push(sep1); - this._contextMenu.items.push(insertSlide); - this._contextMenu.items.push(insertDuplicate); - this._contextMenu.items.push(insertSlideshow); - this._contextMenu.items.push(sep2); - this._contextMenu.items.push(playFromHere); - this._contextMenu.items.push(sep3); - this._contextMenu.items.push(setSkyPosition); - this._contextMenu.items.push(setEndSkyPosition); - this._contextMenu.items.push(sep4); - this._contextMenu.items.push(showSkyPosition); - this._contextMenu.items.push(showEndSkyPosition); - this._contextMenu.items.push(sep5); - this._contextMenu.items.push(captureThumbnail); - this._contextMenu.items.push(sep6); - this._contextMenu.items.push(masterSlide); - this._contextMenu.items.push(setNextSlide); - this._contextMenu.items.push(fadeInOverlays); - this._contextMenu.items.push(trackSpaceTime); - this._contextMenu.items.push(interpolation); - this._contextMenu._show(Vector2d.create(e.clientX, e.clientY)); - } - }, - _selectAllMenu_Click: function (sender, e) { - this.tourStopList.selectAll(); - }, - _interpolation_Click: function (sender, e) { - var item = sender; - this._tour.get_currentTourStop().set_interpolationType(item.tag); - }, - _nextSlideChosen: function () { - if (this._selectDialog.get_OK()) { - this._tour.get_currentTourStop().set_nextSlide(this._selectDialog.get_id()); - } - }, - _setNextSlide_Click: function (sender, e) { - this._selectDialog = new SelectLink(null); - this.nextSlideCallback(this._selectDialog, ss.bind('_nextSlideChosen', this)); - }, - _insertDuplicate_Click: function (sender, e) { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(530, 'Duplicate Slide at End Position'), this._tour)); - var ts = this._tour.get_currentTourStop().copy(); - if (ts == null) { - return; - } - if (ts.get_endTarget() != null) { - ts.get_endTarget().set_backgroundImageset(ts.get_target().get_backgroundImageset()); - ts.get_endTarget().set_studyImageset(ts.get_target().get_studyImageset()); - ts.set_target(ts.get_endTarget()); - ts.set_startTime(ts.get_endTime()); - ts.set_endTarget(null); - } - var $enum1 = ss.enumerate(ts.get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_tweenFactor(1); - overlay.set_animate(!overlay.get_animate()); - overlay.set_animate(!overlay.get_animate()); - } - ts.set_tweenPosition(0); - ts.set_fadeInOverlays(false); - this._tour.insertAfterTourStop(ts); - this.tourStopList.refresh(); - }, - _fadeInOverlays_Click: function (sender, e) { - this._tour.get_currentTourStop().set_fadeInOverlays(!this._tour.get_currentTourStop().get_fadeInOverlays()); - }, - _insertSlideshow_Click: function (sender, e) { - }, - _trackSpaceTime_Click: function (sender, e) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(532, 'Track Time Edit'), this._tour)); - this._tour.get_currentTourStop().set_hasTime(!this._tour.get_currentTourStop().get_hasTime()); - }, - _masterSlide_Click: function (sender, e) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(533, 'Master Slide State Edit'), this._tour)); - this._tour.get_currentTourStop().set_masterSlide(!this._tour.get_currentTourStop().get_masterSlide()); - this.tourStopList.refresh(); - }, - _playFromHere_Click: function (sender, e) { - this.playFromCurrentTourstop(); - }, - playFromCurrentTourstop: function () { - this.playing = true; - WWTControl.singleton.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - this.setPlayPauseMode(); - }, - playFromTourstop: function (ts) { - this._tour.set_currentTourStop(ts); - this.playFromCurrentTourstop(); - }, - _showSkyPosition_Click: function (sender, e) { - if (this._tour.get_currentTourStop() != null) { - WWTControl.singleton.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); - this._tour.get_currentTourStop().syncSettings(); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - this._tour.get_currentTourStop().set_tweenPosition(0); - LayerManager.setVisibleLayerList(this._tour.get_currentTourStop().layers); - this.tourStopList.refresh(); - } - }, - _showEndSkyPosition_Click: function (sender, e) { - this._tour.get_currentTourStop().set_tweenPosition(1); - this._tour.get_currentTourStop()._updateLayerOpacity(); - if (this._tour.get_currentTourStop() != null && this._tour.get_currentTourStop().get_endTarget() != null) { - WWTControl.singleton.gotoTargetFull(false, true, this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_target().get_studyImageset(), this._tour.get_currentTourStop().get_target().get_backgroundImageset()); - WWTControl.singleton.renderContext.set_solarSystemTrack(this._tour.get_currentTourStop().get_endTarget().get_target()); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_endTime()); - this._tour.get_currentTourStop().syncSettings(); - LayerManager.setVisibleLayerList(this._tour.get_currentTourStop().layers); - SpaceTimeController.set_syncToClock(false); - this.tourStopList.refresh(); - this.tourEditorUI.clearSelection(); - } - }, - _setEndSkyPosition_Click: function (sender, e) { - if (this._tour.get_currentTourStop() != null) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(435, 'Set End Camera Position'), this._tour)); - var newPlace = Place.createCameraParams('End Place', WWTControl.singleton.renderContext.viewCamera.copy(), 268435456, WWTControl.singleton.constellation, WWTControl.singleton.renderContext.get_backgroundImageset().get_dataSetType(), WWTControl.singleton.renderContext.get_solarSystemTrack()); - this._tour.get_currentTourStop().set_endTarget(newPlace); - this._tour.get_currentTourStop().get_endTarget().set_constellation(WWTControl.singleton.constellation); - this._tour.get_currentTourStop().set_endTime(SpaceTimeController.get_now()); - this._tour.get_currentTourStop().set_tweenPosition(1); - var $enum1 = ss.enumerate(ss.keys(this._tour.get_currentTourStop().layers)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var info = this._tour.get_currentTourStop().layers[key]; - if (ss.keyExists(LayerManager.get_layerList(), info.id)) { - info.endOpacity = LayerManager.get_layerList()[info.id].get_opacity(); - info.endParams = LayerManager.get_layerList()[info.id].getParams(); - } - } - this._tour.get_currentTourStop()._updateLayerOpacity(); - this.tourStopList.refresh(); - TimeLine.refreshUi(); - this.tourEditorUI.clearSelection(); - } - }, - _setSkyPosition_Click: function (sender, e) { - if (this._tour.get_currentTourStop() != null) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(434, 'Set Start Camera Position'), this._tour)); - this._tour.get_currentTourStop().get_target().set_target(WWTControl.singleton.renderContext.get_solarSystemTrack()); - this._tour.get_currentTourStop().get_target().set_type(WWTControl.singleton.renderContext.get_backgroundImageset().get_dataSetType()); - this._tour.get_currentTourStop().get_target().set_camParams(WWTControl.singleton.renderContext.viewCamera.copy()); - this._tour.get_currentTourStop().get_target().set_constellation(WWTControl.singleton.constellation); - this._tour.get_currentTourStop().get_target().set_studyImageset(WWTControl.singleton.renderContext.get_foregroundImageset()); - this._tour.get_currentTourStop().get_target().set_type(WWTControl.singleton.renderContext.get_backgroundImageset().get_dataSetType()); - this._tour.get_currentTourStop().get_target().set_backgroundImageset(WWTControl.singleton.renderContext.get_backgroundImageset().get_stockImageSet()); - this._tour.get_currentTourStop().captureSettings(); - this._tour.get_currentTourStop().layers = LayerManager._getVisibleLayerList(this._tour.get_currentTourStop().layers); - this._tour.get_currentTourStop().set_tweenPosition(0); - this.tourStopList.refresh(); - TimeLine.refreshUi(); - this.tourEditorUI.clearSelection(); - } - }, - _captureThumbnail_Click: function (sender, e) { - if (this._tour.get_currentTourStop() != null) { - this._captureThumbnail(this._tour.get_currentTourStop()); - } - }, - _captureThumbnail: function (tourStop) { - var $this = this; - - WWTControl.singleton.captureThumbnail(function (blob) { - var filename = ss.format('{0}.thumb.png', tourStop.get_id()); - $this._tour.addCachedFile(filename, blob); - tourStop.set_thumbnail($this._tour.getCachedTexture(filename, function () { - $this.tourStopList.refresh(); - })); - }); - }, - _properties_Click: function (sender, e) { - throw new Error('The method or operation is not implemented.'); - }, - tourStopList_AddNewSlide: function (sender, e) { - this.addSlide(false); - this.tourStopList.ensureAddVisible(); - }, - _addNewSlide_Click: function (sender, e) { - this.addSlide(false); - this.tourStopList.ensureAddVisible(); - }, - _insertNewSlide_Click: function (sender, e) { - this.addSlide(true); - }, - addSlide: function (insert) { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(426, 'Add New Slide'), this._tour)); - Cursor.set_current(Cursors.get_waitCursor()); - var placeName = 'Current Screen'; - var newPlace = Place.createCameraParams(placeName, WWTControl.singleton.renderContext.viewCamera.copy(), 268435456, WWTControl.singleton.constellation, WWTControl.singleton.renderContext.get_backgroundImageset().get_dataSetType(), WWTControl.singleton.renderContext.get_solarSystemTrack()); - newPlace.set_studyImageset(WWTControl.singleton.renderContext.get_foregroundImageset()); - newPlace.set_backgroundImageset(WWTControl.singleton.renderContext.get_backgroundImageset().get_stockImageSet()); - var newTourStop = TourStop.create(newPlace); - if (insert) { - this._tour.insertTourStop(newTourStop); - } - else { - this._tour.addTourStop(newTourStop); - } - if (this._tour.get_currentTourStop() != null) { - this.musicTrack.target = this._tour.get_currentTourStop(); - this.voiceTrack.target = this._tour.get_currentTourStop(); - } - else { - this.musicTrack.target = null; - this.voiceTrack.target = null; - } - this._tour.get_currentTourStop().layers = LayerManager._getVisibleLayerList(this._tour.get_currentTourStop().layers); - this._captureThumbnail(newTourStop); - this.tourStopList.selectedItem = this.tourStopList.findItem(newTourStop); - this.tourStopList.refresh(); - this.tourEditorUI.clearSelection(); - Cursor.set_current(Cursors.get_defaultV()); - TimeLine.refreshUi(); - }, - _deleteMenu_Click: function (sender, e) { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(534, 'Delete Slide'), this._tour)); - var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var item = this.tourStopList.selectedItems[key]; - this._tour.removeTourStop(item); - } - ss.clearKeys(this.tourStopList.selectedItems); - this.tourStopList.selectedItem = -1; - this._tour.set_currentTourStop(null); - this.musicTrack.target = null; - this.voiceTrack.target = null; - this.tourStopList.refresh(); - this.tourEditorUI.clearSelection(); - }, - _pasteMenu_Click: function (sender, e) { - if (this.tourEditorUI.clipboardType === 'WorldWideTelescope.Slide') { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(535, 'Paste Slide'), this._tour)); - var xParser = new DOMParser(); - var doc = xParser.parseFromString(this.tourEditorUI.clipboardData, 'text/xml'); - var node = Util.selectSingleNode(doc, 'TourStops'); - var pasteStack = new ss.Stack(); - var $enum1 = ss.enumerate(node.childNodes); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child.nodeName === 'TourStop') { - var ts = TourStop._fromXml(this._tour, child); - ts.set_id(Guid.newGuid().toString()); - pasteStack.push(ts); - } - } - ss.clearKeys(this.tourStopList.selectedItems); - var curIndex = this.tourStopList.selectedItem + pasteStack.count - 1; - while (pasteStack.count > 0) { - var ts = pasteStack.pop(); - this._tour.insertTourStop(ts); - this.tourStopList.selectedItems[curIndex--] = ts; - } - this.tourStopList.refresh(); - this.tourEditorUI.clearSelection(); - } - }, - _copyMenu_Click: function (sender, e) { - var writer = new XmlTextWriter(); - writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - writer._writeStartElement('TourStops'); - var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var item = this.tourStopList.selectedItems[key]; - item._saveToXml(writer, true); - } - writer._writeEndElement(); - this.tourEditorUI.clipboardType = 'WorldWideTelescope.Slide'; - this.tourEditorUI.clipboardData = writer.body; - }, - _cutMenu_Click: function (sender, e) { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(536, 'Cut Slide'), this._tour)); - this._copyMenu_Click(sender, e); - var $enum1 = ss.enumerate(ss.keys(this.tourStopList.selectedItems)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var item = this.tourStopList.selectedItems[key]; - this._tour.removeTourStop(item); - } - ss.clearKeys(this.tourStopList.selectedItems); - this.tourStopList.refresh(); - this.tourEditorUI.clearSelection(); - }, - pauseTour: function () { - if (this.playing) { - this.playing = false; - } - this.setPlayPauseMode(); - }, - preview_Click: function (sender, e) { - this.playing = !this.playing; - if (this.playing && this._tour.get_editMode()) { - this.get_tour().set_currentTourstopIndex(-1); - } - this.setPlayPauseMode(); - }, - setPlayPauseMode: function () { - if (this._tour.get_editMode()) { - if (this.playing) { - if (this._player == null) { - this._player = new TourPlayer(); - } - this._player.set_tour(this._tour); - WWTControl.singleton.uiController = this._player; - this._player.play(); - this.tourStopList.showAddButton = false; - } - else { - WWTControl.singleton.uiController = this.tourEditorUI; - if (this._player != null) { - this._player.stop(false); - } - this._player = null; - WWTControl.singleton.set__mover(null); - this.tourStopList.showAddButton = this._tour.get_editMode(); - } - } - else { - if (this.playing) { - if (this._player == null) { - this._player = new TourPlayer(); - } - this._player.set_tour(this._tour); - WWTControl.singleton.uiController = this._player; - this._player.play(); - this.tourStopList.showAddButton = false; - } - else { - WWTControl.singleton.uiController = null; - WWTControl.singleton.renderContext.freezeView(); - if (this._player != null) { - this._player.stop(false); - } - this._player = null; - WWTControl.singleton.uiController = null; - WWTControl.singleton.set__mover(null); - this.tourStopList.showAddButton = this._tour.get_editMode(); - } - } - this.tourStopList.refresh(); - }, - playerTimer_Tick: function (sender, e) { - if (this.playing) { - if (this._player != null) { - if (!TourPlayer.get_playing()) { - this.playing = false; - this.setPlayPauseMode(); - } - else { - if (this.tourStopList.selectedItem !== this._tour.get_currentTourstopIndex()) { - this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); - } - } - } - } - }, - insertShapeCircle_Click: function (sender, e) { - this.tourEditorUI.addShape('', 0); - }, - insertShapeRectangle_Click: function (sender, e) { - this.tourEditorUI.addShape('', 1); - }, - insertShapeLine_Click: function (sender, e) { - this.tourEditorUI.addShape('', 5); - }, - insertDonut_Click: function (sender, e) { - this.tourEditorUI.addShape('', 3); - }, - _addArrow_Click: function (sender, e) { - this.tourEditorUI.addShape('', 4); - }, - insertVideo_Click: function (sender, e) { - }, - insertAudio_Click: function (sender, e) { - }, - insertHyperlink_Click: function (sender, e) { - }, - colorPicker_Click: function (sender, e) { - }, - tourEditTab_Leave: function (sender, e) { - }, - editTourProperties_Click: function (sender, e) { - }, - saveTour_Click: function (sender, e) { - this.save(false); - }, - save: function (saveAs) { - return true; - }, - addVideo_Click: function (sender, e) { - }, - addPicture_Click: function (sender, e) { - }, - addShape_Click: function (sender, e) { - }, - _addOpenRectangle_Click: function (sender, e) { - this.tourEditorUI.addShape('', 6); - }, - _addStar_Click: function (sender, e) { - this.tourEditorUI.addShape('', 2); - }, - addText_Click: function (sender, e) { - }, - preview_EnabledChanged: function (sender, e) { - if (this.playing) { - } - else { - } - }, - preview_MouseEnter: function (sender, e) { - }, - preview_MouseLeave: function (sender, e) { - }, - preview_MouseUp: function (sender, e) { - }, - preview_MouseDown: function (sender, e) { - }, - tourStopList_ItemHover: function (sender, e) { - }, - refresh: function () { - }, - undoStep: function () { - if (Undo.peekAction()) { - Undo.stepBack(); - this.tourStopList.refresh(); - this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); - this.showSlideStartPosition(this._tour.get_currentTourStop()); - this.refresh(); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); - } - }, - redoStep: function () { - if (Undo.peekRedoAction()) { - Undo.stepForward(); - this.tourStopList.refresh(); - this.tourStopList.selectedItem = this._tour.get_currentTourstopIndex(); - this.showSlideStartPosition(this._tour.get_currentTourStop()); - this.refresh(); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.tourEditorUI.selection); - } - }, - tourStopList_ShowEndPosition: function (sender, e) { - this._showEndSkyPosition_Click(this, new ss.EventArgs()); - }, - tourStopList_ShowStartPosition: function (sender, e) { - this.showSlideStartPosition(this.get_tour().get_currentTourStop()); - this.tourEditorUI.clearSelection(); - }, - tourStopList_KeyDown: function (sender, e) { - if (e.ctrlKey) { - switch (e.keyCode) { - case 67: - this._copyMenu_Click(null, new ss.EventArgs()); - break; - case 86: - this._pasteMenu_Click(null, new ss.EventArgs()); - break; - case 88: - this._cutMenu_Click(null, new ss.EventArgs()); - break; - case 90: - if (Undo.peekAction()) { - TourEdit._undoStep(); - } - else { - UiTools._beep(); - } - break; - case 89: - if (Undo.peekRedoAction()) { - TourEdit._redoStep(); - } - else { - UiTools._beep(); - } - break; - } - } - if (e.keyCode === 46) { - this._deleteMenu_Click(null, new ss.EventArgs()); - } - }, - _ensureSelectedVisible: function () { - this.tourStopList.ensureSelectedVisible(); - } - }; - - - // wwtlib.TourEditor - - function TourEditor() { - this.selection = new Selection(); - this._contextMenu = new ContextMenuStrip(); - this._tour = null; - this._mouseDown = false; - this._selectionAction = 11; - this._needUndoFrame = false; - this._contextPoint = new Vector2d(); - this._dragCopying = false; - this._brokeThreshold = false; - this.nextSlideCallback = null; - this.clipboardData = ''; - this.clipboardType = ''; - this.editTextCallback = null; - this._defaultColor = Colors.get_white(); - } - var TourEditor$ = { - render: function (renderContext) { - renderContext.setupMatricesOverlays(); - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (overlay.get_animate() && this.get_tour().get_currentTourStop().get_keyFramed()) { - overlay.set_tweenFactor(this._tour.get_currentTourStop().get_tweenPosition()); - } - else if (!this.get_tour().get_currentTourStop().get_keyFramed()) { - overlay.set_tweenFactor((this._tour.get_currentTourStop().get_tweenPosition() < 0.5) ? 0 : 1); - } - overlay.draw3D(renderContext, true); - } - this.selection.draw3D(renderContext, 1); - if (TourEditor.currentEditor != null) { - TourEditor.currentEditor.render(renderContext); - } - Settings.tourSettings = null; - }, - get_tour: function () { - return this._tour; - }, - set_tour: function (value) { - this._tour = value; - return value; - }, - close: function () { - if (this._tour != null) { - this._tour = null; - this.set_focus(null); - } - }, - clearSelection: function () { - this.selection.clearSelection(); - OverlayList._updateOverlayListSelection(this.selection); - this.set_focus(null); - }, - get_focus: function () { - return this.selection.get_focus(); - }, - set_focus: function (value) { - this.selection.set_focus(value); - return value; - }, - pointToView: function (pnt) { - var clientHeight = WWTControl.singleton.renderContext.height; - var clientWidth = WWTControl.singleton.renderContext.width; - var viewWidth = (WWTControl.singleton.renderContext.width / WWTControl.singleton.renderContext.height) * 1116; - var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - var y = (pnt.y) / clientHeight * 1116; - return Vector2d.create(x, y); - }, - mouseDown: function (sender, e) { - this._brokeThreshold = false; - this._needUndoFrame = true; - var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - if (this._tour == null || this._tour.get_currentTourStop() == null) { - this._needUndoFrame = false; - return false; - } - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.mouseDown(sender, e)) { - return true; - } - } - if (this.get_focus() != null) { - if (this.selection.get_multiSelect()) { - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (overlay.hitTest(location)) { - this._selectionAction = 9; - this._mouseDown = true; - this._pointDown = location; - this.set_focus(overlay); - if (e.ctrlKey) { - this._dragCopying = true; - } - return true; - } - } - } - else { - if (this.get_focus().hitTest(location)) { - this._selectionAction = 9; - this._mouseDown = true; - this._pointDown = location; - if (e.ctrlKey) { - this._dragCopying = true; - } - return true; - } - } - var hit = this.selection.hitTest(location); - if (hit !== 11) { - this._selectionAction = hit; - this._mouseDown = true; - if (hit === 8) { - this._pointDown = location; - } - else { - this._pointDown = this.selection.pointToSelectionSpace(location); - } - return true; - } - } - for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { - if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location)) { - this._selectionAction = 9; - this.set_focus(this._tour.get_currentTourStop().get_overlays()[i]); - if (e.ctrlKey || e.shiftKey) { - this.selection.addSelection(this.get_focus()); - } - else { - this.selection.setSelection(this.get_focus()); - } - OverlayList._updateOverlayListSelection(this.selection); - this._mouseDown = true; - this._pointDown = location; - return true; - } - } - this.set_focus(null); - this.clearSelection(); - this._needUndoFrame = false; - return false; - }, - mouseUp: function (sender, e) { - this._brokeThreshold = false; - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.mouseUp(sender, e)) { - return true; - } - } - this._contextPoint = Vector2d.create(e.offsetX, e.offsetY); - if (this._mouseDown) { - this._mouseDown = false; - if (e.button === 2) { - if (this.get_focus() != null) { - this.showSelectionContextMenu(Vector2d.create(e.offsetX, e.offsetY)); - } - } - return true; - } - if (e.button === 2) { - if (this.get_focus() == null) { - this._showNoSelectionContextMenu(Vector2d.create(e.offsetX, e.offsetY)); - } - return true; - } - return false; - }, - mouseMove: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.mouseMove(sender, e)) { - return true; - } - } - var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - if (this._mouseDown && this.get_focus() != null) { - var undoFrame = null; - var actionText = Language.getLocalizedText(502, 'Edit'); - if (this._needUndoFrame) { - undoFrame = new UndoTourStopChange(Language.getLocalizedText(502, 'Edit'), this._tour); - } - var moveX; - var moveY; - if (this._selectionAction !== 9 && this._selectionAction !== 8) { - var newPoint = this.selection.pointToSelectionSpace(location); - moveX = newPoint.x - this._pointDown.x; - moveY = newPoint.y - this._pointDown.y; - this._pointDown = newPoint; - } - else { - moveX = location.x - this._pointDown.x; - moveY = location.y - this._pointDown.y; - if (this._selectionAction === 9 && !this._brokeThreshold) { - if (Math.abs(moveX) > 3 || Math.abs(moveY) > 3) { - this._brokeThreshold = true; - } - else { - return true; - } - } - this._pointDown = location; - } - if (this._dragCopying) { - if (this.selection.get_multiSelect()) { - var set = this.selection.selectionSet; - this.clearSelection(); - var $enum1 = ss.enumerate(set); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - var newOverlay = this.addOverlay(overlay); - newOverlay.set_x(overlay.get_x()); - newOverlay.set_y(overlay.get_y()); - this.set_focus(newOverlay); - this.selection.addSelection(this.get_focus()); - } - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - this._dragCopying = false; - } - else { - var newOverlay = this.addOverlay(this.get_focus()); - newOverlay.set_x(this.get_focus().get_x()); - newOverlay.set_y(this.get_focus().get_y()); - this.set_focus(newOverlay); - this.selection.setSelection(this.get_focus()); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - this._dragCopying = false; - } - } - var aspect = this.get_focus().get_width() / this.get_focus().get_height(); - var center = Vector2d.create(this.get_focus().get_x(), this.get_focus().get_y()); - if (e.ctrlKey) { - actionText = Language.getLocalizedText(537, 'Resize'); - switch (this._selectionAction) { - case 0: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - (moveX / aspect) * 2)); - break; - case 1: - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - moveY * 2)); - break; - case 2: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + (moveX / aspect) * 2)); - break; - case 3: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); - break; - case 4: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() + moveX * 2)); - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + (moveX / aspect) * 2)); - break; - case 5: - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() + moveY * 2)); - break; - case 6: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); - this.get_focus().set_height(Math.max(2, this.get_focus().get_height() - (moveX / aspect) * 2)); - break; - case 7: - this.get_focus().set_width(Math.max(2, this.get_focus().get_width() - moveX * 2)); - break; - case 8: - actionText = Language.getLocalizedText(538, 'Rotate'); - this.get_focus().set_rotationAngle(this.get_focus().get_rotationAngle() + moveX / 10); - break; - case 9: - actionText = Language.getLocalizedText(539, 'Drag Copy'); - center.x += moveX; - center.y += moveY; - break; - case 10: - break; - case 11: - break; - default: - break; - } - } - else { - if (this._selectionAction !== 8 && this._selectionAction !== 9) { - if (moveX > (this.get_focus().get_width() - 2)) { - moveX = 0; - } - if (moveY > (this.get_focus().get_height() - 2)) { - moveY = 0; - } - } - actionText = Language.getLocalizedText(537, 'Resize'); - switch (this._selectionAction) { - case 0: - this.get_focus().set_width(this.get_focus().get_width() - moveX); - this.get_focus().set_height(this.get_focus().get_height() - (moveX / aspect)); - center.x += (moveX / 2); - center.y += ((moveX / aspect) / 2); - break; - case 1: - this.get_focus().set_height(this.get_focus().get_height() - moveY); - center.y += (moveY / 2); - break; - case 2: - this.get_focus().set_width(this.get_focus().get_width() + moveX); - this.get_focus().set_height(this.get_focus().get_height() + (moveX / aspect)); - center.x += (moveX / 2); - center.y -= ((moveX / aspect) / 2); - break; - case 3: - this.get_focus().set_width(this.get_focus().get_width() + moveX); - center.x += (moveX / 2); - break; - case 4: - this.get_focus().set_width(this.get_focus().get_width() + moveX); - this.get_focus().set_height(this.get_focus().get_height() + (moveX / aspect)); - center.x += (moveX / 2); - center.y += ((moveX / aspect) / 2); - break; - case 5: - this.get_focus().set_height(this.get_focus().get_height() + moveY); - center.y += (moveY / 2); - break; - case 6: - this.get_focus().set_width(this.get_focus().get_width() - moveX); - this.get_focus().set_height(this.get_focus().get_height() - (moveX / aspect)); - center.x += (moveX / 2); - center.y -= ((moveX / aspect) / 2); - break; - case 7: - this.get_focus().set_width(this.get_focus().get_width() - moveX); - center.x += (moveX / 2); - break; - case 8: - actionText = Language.getLocalizedText(538, 'Rotate'); - this.get_focus().set_rotationAngle(this.get_focus().get_rotationAngle() + moveX); - break; - case 9: - actionText = Language.getLocalizedText(540, 'Move'); - center.x += moveX; - center.y += moveY; - break; - case 10: - break; - case 11: - break; - default: - break; - } - } - if (this._selectionAction !== 9 && this._selectionAction !== 8) { - center = this.selection.pointToScreenSpace(center); - } - if (this.selection.get_multiSelect()) { - var $enum2 = ss.enumerate(this.selection.selectionSet); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - overlay.set_x(overlay.get_x() + moveX); - overlay.set_y(overlay.get_y() + moveY); - } - } - else { - this.get_focus().set_x(center.x); - this.get_focus().set_y(center.y); - } - if (this._needUndoFrame) { - this._needUndoFrame = false; - undoFrame.set_actionText(actionText); - Undo.push(undoFrame); - } - } - else { - if (this.get_focus() != null) { - if (this.get_focus().hitTest(location)) { - Cursor.set_current(Cursors.get_sizeAll()); - return false; - } - var hit = this.selection.hitTest(location); - if (hit === 11) { - return false; - } - switch (hit) { - case 0: - Cursor.set_current(Cursors.get_sizeNWSE()); - break; - case 1: - Cursor.set_current(Cursors.get_sizeNS()); - break; - case 2: - Cursor.set_current(Cursors.get_sizeNESW()); - break; - case 3: - Cursor.set_current(Cursors.get_sizeWE()); - break; - case 4: - Cursor.set_current(Cursors.get_sizeNWSE()); - break; - case 5: - Cursor.set_current(Cursors.get_sizeNS()); - break; - case 6: - Cursor.set_current(Cursors.get_sizeNESW()); - break; - case 7: - Cursor.set_current(Cursors.get_sizeWE()); - break; - case 8: - Cursor.set_current(Cursors.get_sizeWE()); - break; - case 10: - break; - case 11: - break; - default: - break; - } - } - } - return false; - }, - _showNoSelectionContextMenu: function (position) { - if (this._contextMenu != null) { - this._contextMenu._dispose(); - } - if (this._tour.get_currentTourStop() == null) { - return; - } - this._contextMenu = new ContextMenuStrip(); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); - pasteMenu.enabled = this.clipboardType === 'WorldWideTelescope.Overlay'; - pasteMenu.click = ss.bind('_pasteMenu_Click', this); - this._contextMenu.items.push(pasteMenu); - this._contextMenu._show(position); - }, - _addOpenRectangle_Click: function (sender, e) { - this.addShape('', 6); - }, - _addStar_Click: function (sender, e) { - this.addShape('', 2); - }, - _insertShapeCircle_Click: function (sender, e) { - this.addShape('', 0); - }, - _insertShapeRectangle_Click: function (sender, e) { - this.addShape('', 1); - }, - _insertShapeLine_Click: function (sender, e) { - this.addShape('', 5); - }, - _insertDonut_Click: function (sender, e) { - this.addShape('', 3); - }, - _addArrow_Click: function (sender, e) { - this.addShape('', 4); - }, - showSelectionContextMenu: function (position) { - if (this.get_focus() == null) { - return; - } - var multiSelect = this.selection.get_multiSelect(); - if (this._contextMenu != null) { - this._contextMenu._dispose(); - } - this._contextMenu = new ContextMenuStrip(); - var cutMenu = ToolStripMenuItem.create(Language.getLocalizedText(427, 'Cut')); - var copyMenu = ToolStripMenuItem.create(Language.getLocalizedText(428, 'Copy')); - var pasteMenu = ToolStripMenuItem.create(Language.getLocalizedText(425, 'Paste')); - var deleteMenu = ToolStripMenuItem.create(Language.getLocalizedText(167, 'Delete')); - var sep1 = new ToolStripSeparator(); - var sep2 = new ToolStripSeparator(); - var sep3 = new ToolStripSeparator(); - var bringToFront = ToolStripMenuItem.create(Language.getLocalizedText(452, 'Bring to Front')); - var sendToBack = ToolStripMenuItem.create(Language.getLocalizedText(453, 'Send to Back')); - var bringForward = ToolStripMenuItem.create(Language.getLocalizedText(454, 'Bring Forward')); - var sendBackward = ToolStripMenuItem.create(Language.getLocalizedText(455, 'Send Backward')); - var properties = ToolStripMenuItem.create(Language.getLocalizedText(20, 'Properties')); - var editText = ToolStripMenuItem.create(Language.getLocalizedText(502, 'Edit')); - var url = ToolStripMenuItem.create(Language.getLocalizedText(587, 'Hyperlink')); - var linkString = this.get_focus().get_linkID(); - switch (this.get_focus().get_linkID()) { - case '': - case null: - linkString = ' (' + Language.getLocalizedText(609, 'No Link') + ')'; - break; - case 'Next': - linkString = ' (' + Language.getLocalizedText(610, 'Next Slide') + ')'; - break; - case 'Return': - linkString = ' (' + Language.getLocalizedText(602, 'Return to Caller') + ')'; - break; - default: - var index = this.get_tour().getTourStopIndexByID(this.get_focus().get_linkID()); - if (index > -1) { - if (ss.emptyString(this._tour.get_tourStops()[index].get_description())) { - linkString = ss.format(' (' + Language.getLocalizedText(1340, 'Slide') + ' {0})', index); - } - else { - linkString = ' (' + this._tour.get_tourStops()[index].get_description() + ')'; - } - } - break; - } - var animateMenu = ToolStripMenuItem.create(Language.getLocalizedText(588, 'Animate')); - var linkID = ToolStripMenuItem.create(Language.getLocalizedText(589, 'Link to Slide') + linkString); - var pickColor = ToolStripMenuItem.create(Language.getLocalizedText(458, 'Color/Opacity')); - var flipbookProperties = ToolStripMenuItem.create(Language.getLocalizedText(630, 'Flipbook Properties')); - var interpolateMenu = ToolStripMenuItem.create(Language.getLocalizedText(1029, 'Animation Tween Type')); - var Linear = ToolStripMenuItem.create(Language.getLocalizedText(1030, 'Linear')); - var Ease = ToolStripMenuItem.create(Language.getLocalizedText(1031, 'Ease In/Out')); - var EaseIn = ToolStripMenuItem.create(Language.getLocalizedText(1032, 'Ease In')); - var EaseOut = ToolStripMenuItem.create(Language.getLocalizedText(1033, 'Ease Out')); - var Exponential = ToolStripMenuItem.create(Language.getLocalizedText(1034, 'Exponential')); - var Default = ToolStripMenuItem.create(Language.getLocalizedText(1035, 'Slide Default')); - var Align = ToolStripMenuItem.create(Language.getLocalizedText(790, 'Align')); - var AlignTop = ToolStripMenuItem.create(Language.getLocalizedText(1333, 'Top')); - var AlignBottom = ToolStripMenuItem.create(Language.getLocalizedText(1334, 'Bottom')); - var AlignLeft = ToolStripMenuItem.create(Language.getLocalizedText(1335, 'Left')); - var AlignRight = ToolStripMenuItem.create(Language.getLocalizedText(1336, 'Right')); - var AlignHorizon = ToolStripMenuItem.create(Language.getLocalizedText(1337, 'Horizontal')); - var AlignVertical = ToolStripMenuItem.create(Language.getLocalizedText(1338, 'Vertical')); - var AlignCenter = ToolStripMenuItem.create(Language.getLocalizedText(1339, 'Centered')); - Align.dropDownItems.push(AlignTop); - Align.dropDownItems.push(AlignBottom); - Align.dropDownItems.push(AlignLeft); - Align.dropDownItems.push(AlignRight); - Align.dropDownItems.push(AlignHorizon); - Align.dropDownItems.push(AlignVertical); - Align.dropDownItems.push(AlignCenter); - Linear.tag = 0; - Ease.tag = 3; - EaseIn.tag = 1; - EaseOut.tag = 2; - Exponential.tag = 4; - Default.tag = 5; - Linear.click = ss.bind('_interpolation_Click', this); - Ease.click = ss.bind('_interpolation_Click', this); - EaseIn.click = ss.bind('_interpolation_Click', this); - EaseOut.click = ss.bind('_interpolation_Click', this); - Exponential.click = ss.bind('_interpolation_Click', this); - Default.click = ss.bind('_interpolation_Click', this); - switch (this.get_focus().get_interpolationType()) { - case 0: - Linear.checked = true; - break; - case 1: - EaseIn.checked = true; - break; - case 2: - EaseOut.checked = true; - break; - case 3: - Ease.checked = true; - break; - case 4: - Exponential.checked = true; - break; - case 5: - Default.checked = true; - break; - default: - break; - } - interpolateMenu.dropDownItems.push(Default); - interpolateMenu.dropDownItems.push(Linear); - interpolateMenu.dropDownItems.push(Ease); - interpolateMenu.dropDownItems.push(EaseIn); - interpolateMenu.dropDownItems.push(EaseOut); - interpolateMenu.dropDownItems.push(Exponential); - cutMenu.click = ss.bind('_cutMenu_Click', this); - copyMenu.click = ss.bind('_copyMenu_Click', this); - deleteMenu.click = ss.bind('_deleteMenu_Click', this); - bringToFront.click = ss.bind('_bringToFront_Click', this); - sendToBack.click = ss.bind('_sendToBack_Click', this); - sendBackward.click = ss.bind('_sendBackward_Click', this); - bringForward.click = ss.bind('_bringForward_Click', this); - properties.click = ss.bind('_properties_Click', this); - editText.click = ss.bind('_editText_Click', this); - url.click = ss.bind('_url_Click', this); - pickColor.click = ss.bind('_pickColor_Click', this); - pasteMenu.click = ss.bind('_pasteMenu_Click', this); - animateMenu.click = ss.bind('_animateMenu_Click', this); - flipbookProperties.click = ss.bind('_flipbookProperties_Click', this); - linkID.click = ss.bind('_linkID_Click', this); - AlignTop.click = ss.bind('_alignTop_Click', this); - AlignBottom.click = ss.bind('_alignBottom_Click', this); - AlignLeft.click = ss.bind('_alignLeft_Click', this); - AlignRight.click = ss.bind('_alignRight_Click', this); - AlignHorizon.click = ss.bind('_alignHorizon_Click', this); - AlignVertical.click = ss.bind('_alignVertical_Click', this); - AlignCenter.click = ss.bind('_alignCenter_Click', this); - this._contextMenu.items.push(cutMenu); - this._contextMenu.items.push(copyMenu); - this._contextMenu.items.push(pasteMenu); - this._contextMenu.items.push(deleteMenu); - this._contextMenu.items.push(sep1); - this._contextMenu.items.push(bringToFront); - this._contextMenu.items.push(sendToBack); - this._contextMenu.items.push(bringForward); - this._contextMenu.items.push(sendBackward); - this._contextMenu.items.push(Align); - this._contextMenu.items.push(sep2); - pasteMenu.enabled = false; - this._contextMenu.items.push(pickColor); - this._contextMenu.items.push(url); - this._contextMenu.items.push(linkID); - this._contextMenu.items.push(animateMenu); - this._contextMenu.items.push(sep3); - this._contextMenu.items.push(flipbookProperties); - animateMenu.checked = this.get_focus().get_animate(); - this._contextMenu.items.push(interpolateMenu); - interpolateMenu.enabled = this.get_focus().get_animate(); - flipbookProperties.visible = (ss.canCast(this.get_focus(), FlipbookOverlay)); - sep3.visible = (ss.canCast(this.get_focus(), FlipbookOverlay)); - if (multiSelect) { - url.visible = false; - linkID.visible = false; - properties.visible = false; - flipbookProperties.visible = false; - bringForward.visible = false; - sendBackward.visible = false; - } - else { - Align.visible = false; - } - this._contextMenu.items.push(properties); - if (this.get_focus() != null) { - if (ss.typeOf(this.get_focus()) === TextOverlay) { - this._contextMenu.items.push(editText); - } - } - this._contextMenu._show(position); - }, - _editText_Click: function (sender, e) { - if (this.get_focus() != null) { - if (ss.typeOf(this.get_focus()) === TextOverlay) { - this._editText(); - } - } - }, - _alignVertical_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1036, 'Vertical Align'), this._tour)); - var xCenter = this.get_focus().get_x(); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_x(xCenter); - } - }, - _alignHorizon_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1037, 'Horizontal Align'), this._tour)); - var yCenter = this.get_focus().get_y(); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_y(yCenter); - } - }, - _alignCenter_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1038, 'Align Centers'), this._tour)); - var yCenter = this.get_focus().get_y(); - var xCenter = this.get_focus().get_x(); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_y(yCenter); - overlay.set_x(xCenter); - } - }, - _alignRight_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1040, 'Align Right'), this._tour)); - var left = this.get_focus().get_x() + this.get_focus().get_width() / 2; - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_x(left - overlay.get_width() / 2); - } - }, - _alignLeft_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1041, 'Align Left'), this._tour)); - var right = this.get_focus().get_x() - this.get_focus().get_width() / 2; - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_x(right + overlay.get_width() / 2); - } - }, - _alignBottom_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1042, 'Align Bottoms'), this._tour)); - var top = this.get_focus().get_y() + this.get_focus().get_height() / 2; - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_y(top - overlay.get_height() / 2); - } - }, - _alignTop_Click: function (sender, e) { - if (this.get_focus() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(1039, 'Align Tops'), this._tour)); - var top = this.get_focus().get_y() - this.get_focus().get_height() / 2; - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_y(top + overlay.get_height() / 2); - } - }, - _interpolation_Click: function (sender, e) { - var item = sender; - if (this.get_focus() != null) { - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_interpolationType(item.tag); - } - } - }, - _linkSlideChosen: function () { - if (this.selectDialog.get_OK()) { - this.get_focus().set_linkID(this.selectDialog.get_id()); - } - }, - _linkID_Click: function (sender, e) { - this.selectDialog = new SelectLink(this.get_focus().get_linkID()); - this.nextSlideCallback(this.selectDialog, ss.bind('_linkSlideChosen', this)); - }, - _flipbookProperties_Click: function (sender, e) { - }, - _animateMenu_Click: function (sender, e) { - if (this.get_focus() != null) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(588, 'Animate'), this._tour)); - var animate = !this.get_focus().get_animate(); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_animate(animate); - } - } - }, - _url_Click: function (sender, e) { - var $this = this; - - if (this.get_focus() != null) { - var input = new SimpleInput(Language.getLocalizedText(541, 'Edit Hyperlink'), Language.getLocalizedText(542, 'Url'), this.get_focus().get_url(), 2048); - input.show(Cursor.get_position(), function () { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(541, 'Edit Hyperlink'), $this._tour)); - $this.get_focus().set_url(input.text); - }); - } - }, - _pickColor_Click: function (sender, e) { - var $this = this; - - var picker = new ColorPicker(); - picker.color = this.get_focus().get_color(); - picker.callBack = function () { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(543, 'Edit Color'), $this._tour)); - var $enum1 = ss.enumerate($this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.set_color(picker.color); - } - }; - picker.show(e); - }, - _volume_Click: function (sender, e) { - var vol = new PopupVolume(); - vol.volume = (this.get_focus()).get_volume(); - vol.showDialog(); - (this.get_focus()).set_volume(vol.volume); - }, - _deleteMenu_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(167, 'Delete'), this._tour)); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().removeOverlay(overlay); - } - this.set_focus(null); - this.clearSelection(); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _properties_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(549, 'Properties Edit'), this._tour)); - var props = new OverlayProperties(); - props.overlay = this.get_focus(); - props.showDialog(); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _bringForward_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(454, 'Bring Forward'), this._tour)); - var $enum1 = ss.enumerate(this._getSortedSelection(false)); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().bringForward(overlay); - } - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _sendBackward_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(455, 'Send Backward'), this._tour)); - var $enum1 = ss.enumerate(this._getSortedSelection(true)); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().sendBackward(overlay); - } - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _sendToBack_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(453, 'Send to Back'), this._tour)); - var $enum1 = ss.enumerate(this._getSortedSelection(true)); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().sendToBack(overlay); - } - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _bringToFront_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(452, 'Bring to Front'), this._tour)); - var $enum1 = ss.enumerate(this._getSortedSelection(false)); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().bringToFront(overlay); - } - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _getSortedSelection: function (reverse) { - var sorted = []; - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var ov = $enum1.current; - sorted.push(ov); - } - if (reverse) { - sorted.sort(function (p1, p2) { - return -Util.compare(p1.get_zOrder(), p2.get_zOrder()); - }); - } - else { - sorted.sort(function (p1, p2) { - return Util.compare(p1.get_zOrder(), p2.get_zOrder()); - }); - } - return sorted; - }, - _copyMenu_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - var writer = new XmlTextWriter(); - writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - writer._writeStartElement('Overlays'); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.saveToXml(writer, true); - } - writer._writeEndElement(); - this.clipboardData = writer.body; - this.clipboardType = 'WorldWideTelescope.Overlay'; - }, - _cutMenu_Click: function (sender, e) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(427, 'Cut'), this._tour)); - this._copyMenu_Click(sender, e); - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - this._tour.get_currentTourStop().removeOverlay(overlay); - } - this.set_focus(null); - this.clearSelection(); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _pasteMenu_Click: function (sender, e) { - Undo.push(new UndoTourSlidelistChange(Language.getLocalizedText(544, 'Paste Object'), this._tour)); - if (this.clipboardType === 'WorldWideTelescope.Overlay') { - var xParser = new DOMParser(); - var doc = xParser.parseFromString(this.clipboardData, 'text/xml'); - this.clearSelection(); - var parent = Util.selectSingleNode(doc, 'Overlays'); - var $enum1 = ss.enumerate(parent.childNodes); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child.nodeName === 'Overlay') { - var copy = Overlay._fromXml(this._tour.get_currentTourStop(), child); - var found = false; - var maxX = 0; - var maxY = 0; - var $enum2 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum2.moveNext()) { - var item = $enum2.current; - if (item.id === copy.id && ss.typeOf(item) === ss.typeOf(copy)) { - found = true; - if (maxY < item.get_y() || maxX < item.get_x()) { - maxX = item.get_x(); - maxY = item.get_y(); - } - } - } - if (found) { - copy.set_x(maxX + 20); - copy.set_y(maxY + 20); - } - this._tour.get_currentTourStop().addOverlay(copy); - this.set_focus(copy); - this.selection.addSelection(this.get_focus()); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - } - } - } - }, - mouseClick: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.mouseClick(sender, e)) { - return true; - } - } - return false; - }, - click: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.click(sender, e)) { - return true; - } - } - return false; - }, - mouseDoubleClick: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.mouseDoubleClick(sender, e)) { - return true; - } - } - if (this.get_focus() != null) { - if (ss.typeOf(this.get_focus()) === TextOverlay) { - this._editText(); - return true; - } - } - return true; - }, - _doneEditing: function () { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(545, 'Text Edit'), this._tour)); - (this.get_focus()).set_width(0); - (this.get_focus()).set_height(0); - this.get_focus().set_color((this.get_focus()).textObject.foregroundColor); - this.get_focus().cleanUp(); - }, - _editText: function () { - var textObj = (this.get_focus()).textObject; - this.editTextCallback(textObj, ss.bind('_doneEditing', this)); - }, - keyDown: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.keyDown(sender, e)) { - return true; - } - } - var increment = 1; - if (e.ctrlKey) { - increment = 10; - } - switch (e.keyCode) { - case 65: - if (e.ctrlKey) { - this.clearSelection(); - this.selection.addSelectionRange(this._tour.get_currentTourStop().get_overlays()); - OverlayList._updateOverlayListSelection(this.selection); - if (this._tour.get_currentTourStop().get_overlays().length > 0) { - this.set_focus(this._tour.get_currentTourStop().get_overlays()[0]); - } - } - break; - case 90: - if (e.ctrlKey) { - if (Undo.peekAction()) { - TourEdit._undoStep(); - } - else { - UiTools._beep(); - } - } - break; - case 89: - if (e.ctrlKey) { - if (Undo.peekRedoAction()) { - TourEdit._redoStep(); - } - else { - UiTools._beep(); - } - } - break; - case 67: - if (e.ctrlKey) { - this._copyMenu_Click(this, new ss.EventArgs()); - } - break; - case 86: - if (e.ctrlKey) { - this._pasteMenu_Click(this, new ss.EventArgs()); - } - break; - case 88: - if (e.ctrlKey) { - this._cutMenu_Click(this, new ss.EventArgs()); - } - break; - case 46: - this._deleteMenu_Click(null, null); - return true; - case 9: - if (e.shiftKey) { - this._selectLast(); - } - else { - this._selectNext(); - } - return true; - case 37: - if (this.get_focus() != null) { - var $enum1 = ss.enumerate(this.selection.selectionSet); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (e.shiftKey) { - if (e.altKey) { - if (overlay.get_width() > increment) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - overlay.set_width(overlay.get_width() - increment); - } - } - else { - var aspect = overlay.get_width() / overlay.get_height(); - if (overlay.get_width() > increment && overlay.get_height() > (increment * aspect)) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - overlay.set_width(overlay.get_width() - increment); - overlay.set_height(overlay.get_height() - increment * aspect); - } - } - } - else if (e.altKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(538, 'Rotate'), this._tour)); - overlay.set_rotationAngle(overlay.get_rotationAngle() - increment); - } - else { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); - overlay.set_x(overlay.get_x() - increment); - } - } - return true; - } - break; - case 39: - if (this.get_focus() != null) { - var $enum2 = ss.enumerate(this.selection.selectionSet); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - if (e.shiftKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - if (e.altKey) { - overlay.set_width(overlay.get_width() + increment); - } - else { - var aspect = overlay.get_width() / overlay.get_height(); - overlay.set_width(overlay.get_width() + increment); - overlay.set_height(overlay.get_height() + increment * aspect); - } - } - else if (e.altKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(538, 'Rotate'), this._tour)); - overlay.set_rotationAngle(overlay.get_rotationAngle() + increment); - } - else { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); - overlay.set_x(overlay.get_x() + increment); - } - } - return true; - } - break; - case 38: - if (this.get_focus() != null) { - var $enum3 = ss.enumerate(this.selection.selectionSet); - while ($enum3.moveNext()) { - var overlay = $enum3.current; - if (e.shiftKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - if (e.altKey) { - overlay.set_height(overlay.get_height() + increment); - } - else { - var aspect = overlay.get_width() / overlay.get_height(); - overlay.set_width(overlay.get_width() + increment); - overlay.set_height(overlay.get_height() + increment * aspect); - } - } - else if (!e.altKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); - overlay.set_y(overlay.get_y() - increment); - } - } - return true; - } - break; - case 40: - if (this.get_focus() != null) { - var $enum4 = ss.enumerate(this.selection.selectionSet); - while ($enum4.moveNext()) { - var overlay = $enum4.current; - if (e.shiftKey) { - if (e.altKey) { - if (overlay.get_height() > increment) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - overlay.set_height(overlay.get_height() - increment); - } - } - else { - var aspect = overlay.get_width() / overlay.get_height(); - if (overlay.get_width() > increment && overlay.get_height() > (increment * aspect)) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(537, 'Resize'), this._tour)); - overlay.set_width(overlay.get_width() - increment); - overlay.set_height(overlay.get_height() - increment * aspect); - } - } - } - else if (!e.altKey) { - Undo.push(new UndoTourStopChange(Language.getLocalizedText(540, 'Move'), this._tour)); - overlay.set_y(overlay.get_y() + increment); - } - } - return true; - } - break; - case 34: - if (e.altKey) { - if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { - this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; - TourEdit._selectCurrent(); - TourEdit._ensureSelectedVisible(); - } - return true; - } - break; - case 33: - if (e.altKey) { - if (this._tour.get_currentTourstopIndex() > 0) { - this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() - 1) + 1; - TourEdit._selectCurrent(); - TourEdit._ensureSelectedVisible(); - } - return true; - } - break; - } - return false; - }, - _selectNext: function () { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - this.set_focus(this._tour.get_currentTourStop().getNextOverlay(this.get_focus())); - this.selection.setSelection(this.get_focus()); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - _selectLast: function () { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - this.set_focus(this._tour.get_currentTourStop().getPerviousOverlay(this.get_focus())); - this.selection.setSelection(this.get_focus()); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - }, - keyUp: function (sender, e) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.keyUp(sender, e)) { - return true; - } - } - return false; - }, - addPicture: function (file) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(546, 'Insert Picture'), this._tour)); - var bmp = BitmapOverlay.create(this._tour.get_currentTourStop(), file); - bmp.set_x(960); - bmp.set_y(600); - this._tour.get_currentTourStop().addOverlay(bmp); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - return true; - }, - addFlipbook: function (filename) { - return false; - }, - addAudio: function (file, music) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - var audio = AudioOverlay.create(this._tour.get_currentTourStop(), file); - audio.set_x(900); - audio.set_y(600); - if (music) { - this._tour.get_currentTourStop().set_musicTrack(audio); - } - else { - this._tour.get_currentTourStop().set_voiceTrack(audio); - } - return true; - }, - addVideo: function (filename) { - return true; - }, - addText: function (p, textObject) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - var text = TextOverlay.create(textObject); - text.set_color(textObject.foregroundColor); - text.set_x(960); - text.set_y(600); - Undo.push(new UndoTourStopChange(Language.getLocalizedText(547, 'Insert Text'), this._tour)); - this._tour.get_currentTourStop().addOverlay(text); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - return true; - }, - addOverlay: function (ol) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return null; - } - if (ss.typeOf(ol) === ShapeOverlay) { - var srcShapeOverlay = ol; - if (srcShapeOverlay != null) { - var shape = ShapeOverlay._create(this._tour.get_currentTourStop(), srcShapeOverlay.get_shapeType()); - shape.set_width(srcShapeOverlay.get_width()); - shape.set_height(srcShapeOverlay.get_height()); - shape.set_x(this._contextPoint.x); - shape.set_y(this._contextPoint.y); - shape.set_color(srcShapeOverlay.get_color()); - shape.set_rotationAngle(srcShapeOverlay.get_rotationAngle()); - this._tour.get_currentTourStop().addOverlay(shape); - return shape; - } - } - else if (ss.typeOf(ol) === TextOverlay) { - var srcTxtOverlay = ol; - if (srcTxtOverlay != null) { - var text = TextOverlay.create(srcTxtOverlay.textObject); - text.set_x(this._contextPoint.x); - text.set_y(this._contextPoint.y); - text.set_color(srcTxtOverlay.get_color()); - this._tour.get_currentTourStop().addOverlay(text); - return text; - } - } - else if (ss.typeOf(ol) === BitmapOverlay) { - var srcBmpOverlay = ol; - if (srcBmpOverlay != null) { - var bitmap = srcBmpOverlay.copy(this._tour.get_currentTourStop()); - bitmap.set_x(this._contextPoint.x); - bitmap.set_y(this._contextPoint.y); - this._tour.get_currentTourStop().addOverlay(bitmap); - return bitmap; - } - } - else if (ss.typeOf(ol) === FlipbookOverlay) { - var srcFlipbookOverlay = ol; - if (srcFlipbookOverlay != null) { - var bitmap = srcFlipbookOverlay.copy(this._tour.get_currentTourStop()); - bitmap.set_x(this._contextPoint.x); - bitmap.set_y(this._contextPoint.y); - this._tour.get_currentTourStop().addOverlay(bitmap); - return bitmap; - } - } - return null; - }, - addShape: function (p, shapeType) { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - Undo.push(new UndoTourStopChange(Language.getLocalizedText(548, 'Insert Shape'), this._tour)); - var shape = ShapeOverlay._create(this._tour.get_currentTourStop(), shapeType); - shape.set_width(200); - shape.set_height(200); - if (shapeType === 4) { - shape.set_height(shape.get_height() / 2); - } - if (shapeType === 5) { - shape.set_height(12); - } - shape.set_x(960); - shape.set_y(600); - this._tour.get_currentTourStop().addOverlay(shape); - this.set_focus(shape); - this.selection.setSelection(this.get_focus()); - OverlayList._updateOverlayList(this._tour.get_currentTourStop(), this.selection); - return true; - }, - getCurrentColor: function () { - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return this._defaultColor; - } - if (this.get_focus() != null) { - return this.get_focus().get_color(); - } - else { - return this._defaultColor; - } - }, - setCurrentColor: function (color) { - this._defaultColor = color; - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return; - } - if (this.get_focus() != null) { - this.get_focus().set_color(color); - } - }, - dispose: function () { - if (this._contextMenu != null) { - this._contextMenu._dispose(); - this._contextMenu = null; - } - }, - hover: function (pnt) { - if (TourEditor.currentEditor != null) { - if (TourEditor.currentEditor.hover(pnt)) { - return true; - } - } - return true; - } - }; - - - // wwtlib.OverlayList - - function OverlayList() { - } - OverlayList._updateOverlayList = function (currentTourStop, selection) { - }; - OverlayList._updateOverlayListSelection = function (selection) { - }; - var OverlayList$ = { - - }; - - - // wwtlib.TourEdit - - function TourEdit() { - } - TourEdit._ensureSelectedVisible = function () { - }; - TourEdit._selectCurrent = function () { - }; - TourEdit._undoStep = function () { - if (Undo.peekAction()) { - Undo.stepBack(); - } - }; - TourEdit._redoStep = function () { - if (Undo.peekRedoAction()) { - Undo.stepForward(); - } - }; - var TourEdit$ = { - - }; - - - // wwtlib.SoundEditor - - function SoundEditor() { - this.target = null; - } - var SoundEditor$ = { - - }; - - - // wwtlib.TourStopList - - function TourStopList() { - this.tour = null; - this.showAddButton = false; - this.selectedItems = null; - this.selectedItem = -1; - this.refreshCallback = null; - this.multipleSelection = false; - this.hitType = false; - } - var TourStopList$ = { - selectAll: function () { - this.selectedItems = {}; - for (var i = 0; i < this.tour.get_tourStops().length; i++) { - this.selectedItems[i] = this.tour.get_tourStops()[i]; - } - }, - refresh: function () { - if (this.refreshCallback != null) { - this.refreshCallback(); - } - }, - findItem: function (ts) { - return -1; - }, - ensureSelectedVisible: function () { - }, - ensureAddVisible: function () { - } - }; - - - // wwtlib.TimeLine - - function TimeLine() { - } - TimeLine.refreshUi = function () { - }; - var TimeLine$ = { - - }; - - - // wwtlib.TourPlayer - - function TourPlayer() { - this._overlayBlend = BlendState.create(false, 1000); - this._tour = null; - this._onTarget = false; - this._currentMasterSlide = null; - this._callStack = new ss.Stack(); - this._leaveSettingsWhenStopped = false; - } - TourPlayer.get_playing = function () { - return TourPlayer._playing; - }; - TourPlayer.set_playing = function (value) { - TourPlayer._playing = value; - return value; - }; - TourPlayer.add_tourEnded = function (value) { - TourPlayer.__tourEnded = ss.bindAdd(TourPlayer.__tourEnded, value); - }; - TourPlayer.remove_tourEnded = function (value) { - TourPlayer.__tourEnded = ss.bindSub(TourPlayer.__tourEnded, value); - }; - var TourPlayer$ = { - render: function (renderContext) { - if (this._tour == null || this._tour.get_currentTourStop() == null || !TourPlayer._playing) { - return; - } - renderContext.save(); - this.updateSlideStates(); - if (!this._onTarget) { - this._slideStartTime = ss.now(); - if (renderContext.onTarget(this.get_tour().get_currentTourStop().get_target())) { - this._onTarget = true; - this._overlayBlend.set_state(!this.get_tour().get_currentTourStop().get_fadeInOverlays()); - this._overlayBlend.set_targetState(true); - if (this._tour.get_currentTourStop().get_musicTrack() != null) { - this._tour.get_currentTourStop().get_musicTrack().seek(0); - this._tour.get_currentTourStop().get_musicTrack().play(); - } - if (this._tour.get_currentTourStop().get_voiceTrack() != null) { - this._tour.get_currentTourStop().get_voiceTrack().seek(0); - this._tour.get_currentTourStop().get_voiceTrack().play(); - } - var caption = ''; - var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (overlay.get_name().toLowerCase() === 'caption') { - var text = ss.safeCast(overlay, TextOverlay); - if (text != null) { - caption = text.textObject.text; - } - } - overlay.play(); - } - LayerManager.setVisibleLayerList(this._tour.get_currentTourStop().layers); - if (this._tour.get_currentTourStop().get_endTarget() != null && this._tour.get_currentTourStop().get_endTarget().get_zoomLevel() !== -1) { - if (this._tour.get_currentTourStop().get_target().get_type() === 4) { - } - renderContext.viewMover = new ViewMoverKenBurnsStyle(this._tour.get_currentTourStop().get_target().get_camParams(), this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_duration() / 1000, this._tour.get_currentTourStop().get_startTime(), this._tour.get_currentTourStop().get_endTime(), this._tour.get_currentTourStop().get_interpolationType()); - } - Settings.tourSettings = this._tour.get_currentTourStop(); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - WWTControl.scriptInterface._fireSlideChanged(caption); - } - } - if (renderContext.gl != null) { - renderContext.setupMatricesOverlays(); - if (this._currentMasterSlide != null) { - var $enum2 = ss.enumerate(this._currentMasterSlide.get_overlays()); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - overlay.set_tweenFactor(1); - overlay.draw3D(renderContext, false); - } - } - if (this._onTarget) { - var $enum3 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum3.moveNext()) { - var overlay = $enum3.current; - if (overlay.get_name().toLowerCase() !== 'caption' || WWTControl.scriptInterface.get_showCaptions()) { - overlay.set_tweenFactor(CameraParameters.easeCurve(this._tour.get_currentTourStop().get_tweenPosition(), (overlay.get_interpolationType() === 5) ? this._tour.get_currentTourStop().get_interpolationType() : overlay.get_interpolationType())); - overlay.draw3D(renderContext, false); - } - } - } - renderContext.restore(); - } - else { - renderContext.device.scale(renderContext.height / 1116, renderContext.height / 1116); - var aspectOrig = 1920 / 1116; - var aspectNow = renderContext.width / renderContext.height; - renderContext.device.translate(-((1920 - (aspectNow * 1116)) / 2), 0); - if (this._currentMasterSlide != null) { - var $enum4 = ss.enumerate(this._currentMasterSlide.get_overlays()); - while ($enum4.moveNext()) { - var overlay = $enum4.current; - overlay.set_tweenFactor(1); - overlay.draw3D(renderContext, false); - } - } - if (this._onTarget) { - var $enum5 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum5.moveNext()) { - var overlay = $enum5.current; - if (overlay.get_name().toLowerCase() !== 'caption' || WWTControl.scriptInterface.get_showCaptions()) { - overlay.set_tweenFactor(CameraParameters.easeCurve(this._tour.get_currentTourStop().get_tweenPosition(), (overlay.get_interpolationType() === 5) ? this._tour.get_currentTourStop().get_interpolationType() : overlay.get_interpolationType())); - overlay.draw3D(renderContext, false); - } - } - } - else { - var i = 0; - } - renderContext.restore(); - } - }, - get_tour: function () { - return this._tour; - }, - set_tour: function (value) { - this._tour = value; - return value; - }, - nextSlide: function () { - if (this._tour.get_currentTourStop() != null) { - if (!this._tour.get_currentTourStop().get_masterSlide()) { - if (this._tour.get_currentTourStop().get_musicTrack() != null) { - this._tour.get_currentTourStop().get_musicTrack().stop(); - } - if (this._tour.get_currentTourStop().get_voiceTrack() != null) { - this._tour.get_currentTourStop().get_voiceTrack().stop(); - } - var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.stop(); - } - } - else { - this._currentMasterSlide = this._tour.get_currentTourStop(); - } - } - if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1) || this._tour.get_currentTourStop().get_isLinked()) { - if (this._tour.get_currentTourStop().get_endTarget() != null) { - WWTControl.singleton.gotoTargetFull(false, true, this._tour.get_currentTourStop().get_endTarget().get_camParams(), this._tour.get_currentTourStop().get_target().get_studyImageset(), this._tour.get_currentTourStop().get_target().get_backgroundImageset()); - WWTControl.singleton.set__mover(null); - } - this._onTarget = false; - if (this._tour.get_currentTourStop().get_isLinked()) { - try { - switch (this._tour.get_currentTourStop().get_nextSlide()) { - case 'Return': - if (this._callStack.count > 0) { - this.playFromTourstop(this._tour.get_tourStops()[this._callStack.pop()]); - } - else { - this._tour.set_currentTourstopIndex(this._tour.get_tourStops().length - 1); - } - break; - default: - this.playFromTourstop(this._tour.get_tourStops()[this._tour.getTourStopIndexByID(this._tour.get_currentTourStop().get_nextSlide())]); - break; - } - } - catch ($e2) { - if (this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { - this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; - } - } - } - else { - this._tour.set_currentTourstopIndex(this._tour.get_currentTourstopIndex() + 1) - 1; - } - if (this._currentMasterSlide != null && this._tour.get_currentTourStop().get_masterSlide()) { - this._stopCurrentMaster(); - } - var instant = false; - switch (this._tour.get_currentTourStop().get__transition()) { - case 0: - break; - case 1: - instant = true; - break; - case 2: - instant = true; - break; - case 3: - instant = true; - break; - case 5: - instant = true; - break; - case 4: - instant = true; - break; - default: - break; - } - WWTControl.singleton.gotoTarget(this._tour.get_currentTourStop().get_target(), false, instant, false); - this._slideStartTime = ss.now(); - Settings.tourSettings = this._tour.get_currentTourStop(); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - } - else { - this._stopCurrentMaster(); - TourPlayer._playing = false; - if (Settings.get_current().autoRepeatTour) { - this._tour.set_currentTourstopIndex(-1); - this.play(); - } - else { - WWTControl.singleton._freezeView(); - if (TourPlayer.__tourEnded != null) { - TourPlayer.__tourEnded(this, new ss.EventArgs()); - } - WWTControl.singleton._hideUI(false); - WWTControl.scriptInterface._fireTourEnded(); - } - } - }, - _stopCurrentMaster: function () { - if (this._currentMasterSlide != null) { - if (this._currentMasterSlide.get_musicTrack() != null) { - this._currentMasterSlide.get_musicTrack().stop(); - } - if (this._currentMasterSlide.get_voiceTrack() != null) { - this._currentMasterSlide.get_voiceTrack().stop(); - } - var $enum1 = ss.enumerate(this._currentMasterSlide.get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.stop(); - } - this._currentMasterSlide = null; - } - }, - get_leaveSettingsWhenStopped: function () { - return this._leaveSettingsWhenStopped; - }, - set_leaveSettingsWhenStopped: function (value) { - this._leaveSettingsWhenStopped = value; - return value; - }, - play: function () { - if (this._tour == null) { - return; - } - if (TourPlayer._playing) { - this.stop(true); - } - else { - TourPlayer._playing = true; - } - WWTControl.singleton._hideUI(true); - TourPlayer._playing = true; - if (this._tour.get_tourStops().length > 0) { - this._onTarget = false; - if (this._tour.get_currentTourstopIndex() === -1) { - this._tour.set_currentTourStop(this._tour.get_tourStops()[0]); - } - var $enum1 = ss.enumerate(this._tour.get_tourStops()); - while ($enum1.moveNext()) { - var stop = $enum1.current; - if (stop.get_musicTrack() != null) { - stop.get_musicTrack().prepMultimedia(); - } - if (stop.get_voiceTrack() != null) { - stop.get_voiceTrack().prepMultimedia(); - } - var $enum2 = ss.enumerate(stop.get_overlays()); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - overlay.prepMultimedia(); - } - } - if (this._tour.get_currentTourstopIndex() > 0) { - this._playMasterForCurrent(); - } - WWTControl.singleton.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); - } - this._slideStartTime = ss.now(); - TourPlayer._playing = true; - }, - _playMasterForCurrent: function () { - if (!this._tour.get_currentTourStop().get_masterSlide()) { - var currentMaster = this._tour.elapsedTimeSinceLastMaster(this._tour.get_currentTourstopIndex()); - if (currentMaster != null) { - var elapsed = currentMaster.duration; - this._currentMasterSlide = currentMaster.master; - if (this._currentMasterSlide.get_musicTrack() != null) { - this._currentMasterSlide.get_musicTrack().seek(elapsed); - this._currentMasterSlide.get_musicTrack().play(); - } - if (this._currentMasterSlide.get_voiceTrack() != null) { - this._currentMasterSlide.get_voiceTrack().seek(elapsed); - this._currentMasterSlide.get_voiceTrack().play(); - } - var $enum1 = ss.enumerate(this._currentMasterSlide.get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.seek(elapsed); - overlay.play(); - } - } - } - }, - stop: function (noSwitchBackFullScreen) { - if (TourPlayer._switchedToFullScreen && !noSwitchBackFullScreen) { - } - if (!this._leaveSettingsWhenStopped) { - Settings.tourSettings = null; - } - TourPlayer._playing = false; - if (this._tour.get_currentTourStop() != null) { - if (this._tour.get_currentTourStop().get_musicTrack() != null) { - this._tour.get_currentTourStop().get_musicTrack().stop(); - } - if (this._tour.get_currentTourStop().get_voiceTrack() != null) { - this._tour.get_currentTourStop().get_voiceTrack().stop(); - } - var $enum1 = ss.enumerate(this._tour.get_currentTourStop().get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.stop(); - } - } - if (this._currentMasterSlide != null) { - if (this._currentMasterSlide.get_musicTrack() != null) { - this._currentMasterSlide.get_musicTrack().stop(); - } - if (this._currentMasterSlide.get_voiceTrack() != null) { - this._currentMasterSlide.get_voiceTrack().stop(); - } - var $enum2 = ss.enumerate(this._currentMasterSlide.get_overlays()); - while ($enum2.moveNext()) { - var overlay = $enum2.current; - overlay.stop(); - } - } - WWTControl.singleton._hideUI(TourPlayer.noRestoreUIOnStop); - WWTControl.scriptInterface._fireTourEnded(); - }, - updateSlideStates: function () { - var slideChanging = false; - var slideElapsedTime = ss.now() - this._slideStartTime; - if (slideElapsedTime > this._tour.get_currentTourStop().get_duration() && TourPlayer._playing) { - this.nextSlide(); - slideChanging = true; - } - slideElapsedTime = ss.now() - this._slideStartTime; - if (this._tour.get_currentTourStop() != null) { - this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, (slideElapsedTime / this._tour.get_currentTourStop().get_duration()))); - this._tour.get_currentTourStop().faderOpacity = 0; - var elapsedSeconds = this._tour.get_currentTourStop().get_tweenPosition() * this._tour.get_currentTourStop().get_duration() / 1000; - if (slideChanging) { - WWTControl.singleton.set_crossFadeFrame(false); - } - switch (this._tour.get_currentTourStop().get__transition()) { - case 0: - this._tour.get_currentTourStop().faderOpacity = 0; - WWTControl.singleton.set_crossFadeFrame(false); - break; - case 2: - if (slideChanging) { - } - if (elapsedSeconds < (elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime())) { - WWTControl.singleton.set_crossFadeFrame(true); - this._tour.get_currentTourStop().faderOpacity = 1; - } - else { - this._tour.get_currentTourStop().faderOpacity = 0; - WWTControl.singleton.set_crossFadeFrame(false); - } - break; - case 1: - WWTControl.singleton.set_crossFadeFrame(true); - var opacity = Math.max(0, 1 - Math.min(1, (elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime()) / this._tour.get_currentTourStop().get__transitionTime())); - this._tour.get_currentTourStop().faderOpacity = opacity; - if (slideChanging) { - } - break; - case 3: - case 4: - WWTControl.singleton.set_crossFadeFrame(false); - var opacity = Math.max(0, 1 - Math.max(0, elapsedSeconds - this._tour.get_currentTourStop().get__transitionHoldTime()) / this._tour.get_currentTourStop().get__transitionTime()); - this._tour.get_currentTourStop().faderOpacity = opacity; - break; - case 5: - WWTControl.singleton.set_crossFadeFrame(false); - break; - default: - break; - } - if (!this._tour.get_currentTourStop().get_isLinked() && this._tour.get_currentTourstopIndex() < (this._tour.get_tourStops().length - 1)) { - var nextTrans = this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1].get__transition(); - var nextTransTime = this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1].get__transitionOutTime(); - switch (nextTrans) { - case 5: - case 3: - if (!this._tour.get_currentTourStop().faderOpacity) { - WWTControl.singleton.set_crossFadeFrame(false); - var opacity = Math.max(0, 1 - Math.min(1, ((this._tour.get_currentTourStop().get_duration() / 1000) - elapsedSeconds) / nextTransTime)); - this._tour.get_currentTourStop().faderOpacity = opacity; - } - break; - default: - break; - } - } - } - }, - updateTweenPosition: function (tween) { - var slideElapsedTime = ss.now() - this._slideStartTime; - if (tween > -1) { - return this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, tween)); - } - else { - return this._tour.get_currentTourStop().set_tweenPosition(Math.min(1, (slideElapsedTime / this._tour.get_currentTourStop().get_duration()))); - } - }, - close: function () { - if (this._tour != null) { - if (TourPlayer.get_playing()) { - this.stop(TourPlayer._switchedToFullScreen); - } - this._tour = null; - } - }, - mouseDown: function (sender, e) { - var location; - location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { - if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location)) { - if (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_url())) { - var linkItem = this._tour.get_currentTourStop().get_overlays()[i]; - Util._openUrl(linkItem.get_url()); - return true; - } - if (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_linkID())) { - this._callStack.push(this._tour.get_currentTourstopIndex()); - this.playFromTourstop(this._tour.get_tourStops()[this._tour.getTourStopIndexByID(this._tour.get_currentTourStop().get_overlays()[i].get_linkID())]); - return true; - } - } - } - return false; - }, - mouseUp: function (sender, e) { - return false; - }, - mouseMove: function (sender, e) { - var location; - try { - location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - } - catch ($e1) { - return false; - } - if (this._tour == null || this._tour.get_currentTourStop() == null) { - return false; - } - for (var i = this._tour.get_currentTourStop().get_overlays().length - 1; i >= 0; i--) { - if (this._tour.get_currentTourStop().get_overlays()[i].hitTest(location) && (!ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_url()) || !ss.emptyString(this._tour.get_currentTourStop().get_overlays()[i].get_linkID()))) { - return true; - } - } - return false; - }, - mouseClick: function (sender, e) { - return false; - }, - click: function (sender, e) { - return false; - }, - mouseDoubleClick: function (sender, e) { - return false; - }, - keyDown: function (sender, e) { - switch (e.keyCode) { - case 27: - this.stop(TourPlayer._switchedToFullScreen); - WWTControl.singleton._closeTour(); - return true; - case 32: - this.pauseTour(); - return true; - case 39: - this._playNextSlide(); - return true; - case 37: - this._playPreviousSlide(); - return true; - case 35: - if (this._tour.get_tourStops().length > 0) { - this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_tourStops().length - 1]); - } - return true; - case 36: - if (this._tour.get_tourStops().length > 0) { - this.playFromTourstop(this._tour.get_tourStops()[0]); - } - return true; - } - return false; - }, - _playNextSlide: function () { - if ((this._tour.get_currentTourstopIndex() < this._tour.get_tourStops().length - 1) && this._tour.get_tourStops().length > 0) { - this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() + 1]); - } - }, - _playPreviousSlide: function () { - if (this._tour.get_currentTourstopIndex() > 0) { - this.playFromTourstop(this._tour.get_tourStops()[this._tour.get_currentTourstopIndex() - 1]); - } - }, - playFromTourstop: function (tourStop) { - this.stop(true); - this._tour.set_currentTourStop(tourStop); - WWTControl.singleton.gotoTarget(this._tour.get_currentTourStop().get_target(), false, true, false); - SpaceTimeController.set_now(this._tour.get_currentTourStop().get_startTime()); - SpaceTimeController.set_syncToClock(false); - this.play(); - }, - pauseTour: function () { - if (TourPlayer._playing) { - this.stop(TourPlayer._switchedToFullScreen); - WWTControl.singleton._freezeView(); - WWTControl.scriptInterface._fireTourPaused(); - } - else { - this.play(); - WWTControl.scriptInterface._fireTourResume(); - } - }, - keyUp: function (sender, e) { - return false; - }, - hover: function (pnt) { - if (TourPlayer._playing) { - return true; - } - return false; - }, - pointToView: function (pnt) { - var clientHeight = WWTControl.singleton.canvas.height; - var clientWidth = WWTControl.singleton.canvas.width; - var viewWidth = (clientWidth / clientHeight) * 1116; - var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - var y = (pnt.y) / clientHeight * 1116; - return Vector2d.create(x, y); - } - }; - - - // wwtlib.MasterTime - - function MasterTime(master, duration) { - this.duration = 0; - this.master = master; - this.duration = duration; - } - var MasterTime$ = { - - }; - - - // wwtlib.TourStop - - function TourStop() { - this._tourStopType = 0; - this._keyFramed = false; - this._tweenPosition = 0; - this.faderOpacity = 0; - this._owner = null; - this._transition = 0; - this._transitionTime = 2; - this._transitionHoldTime = 4; - this._transitionOutTime = 2; - this._nextSlide = 'Next'; - this._fadeInOverlays = false; - this._masterSlide = false; - this._id = ''; - this._description = ''; - this._name = ''; - this._duration = 10000; - this._interpolationType = 0; - this._hasLocation = true; - this._hasTime = true; - this._startTime = SpaceTimeController.get_now(); - this._endTime = SpaceTimeController.get_now(); - this._actualPlanetScale = Settings.get_current().get_actualPlanetScale(); - this._locationAltitude = Settings.get_current().get_locationAltitude(); - this._locationLat = Settings.get_current().get_locationLat(); - this._locationLng = Settings.get_current().get_locationLng(); - this._showClouds = Settings.get_current().get_showClouds(); - this._showConstellationBoundries = Settings.get_current().get_showConstellationBoundries(); - this._showConstellationFigures = Settings.get_current().get_showConstellationFigures(); - this._showConstellationSelection = Settings.get_current().get_showConstellationSelection(); - this._showEcliptic = Settings.get_current().get_showEcliptic(); - this._showElevationModel = Settings.get_current().get_showElevationModel(); - this._showFieldOfView = Settings.get_current().get_showFieldOfView(); - this._showGrid = Settings.get_current().get_showGrid(); - this._showHorizon = Settings.get_current().get_showHorizon(); - this._showHorizonPanorama = Settings.get_current().get_showHorizonPanorama(); - this._showMoonsAsPointSource = Settings.get_current().get_showMoonsAsPointSource(); - this._showSolarSystem = Settings.get_current().get_showSolarSystem(); - this._fovTelescope = Settings.get_current().get_fovTelescope(); - this._fovEyepiece = Settings.get_current().get_fovEyepiece(); - this._fovCamera = Settings.get_current().get_fovCamera(); - this._localHorizonMode = Settings.get_current().get_localHorizonMode(); - this._galacticMode = Settings.get_current().get_galacticMode(); - this._solarSystemStars = Settings.get_current().get_solarSystemStars(); - this._solarSystemMilkyWay = Settings.get_current().get_solarSystemMilkyWay(); - this._solarSystemCosmos = Settings.get_current().get_solarSystemCosmos(); - this._solarSystemOrbits = Settings.get_current().get_solarSystemOrbits(); - this._solarSystemOverlays = Settings.get_current().get_solarSystemOverlays(); - this._solarSystemLighting = Settings.get_current().get_solarSystemLighting(); - this._solarSystemScale = Settings.get_current().get_solarSystemScale(); - this._solarSystemMultiRes = Settings.get_current().get_solarSystemMultiRes(); - this._showEquatorialGridText = Settings.get_current().get_showEquatorialGridText(); - this._showGalacticGrid = Settings.get_current().get_showGalacticGrid(); - this._showGalacticGridText = Settings.get_current().get_showGalacticGridText(); - this._showEclipticGrid = Settings.get_current().get_showEclipticGrid(); - this._showEclipticGridText = Settings.get_current().get_showEclipticGridText(); - this._showEclipticOverviewText = Settings.get_current().get_showEclipticOverviewText(); - this._showAltAzGrid = Settings.get_current().get_showAltAzGrid(); - this._showAltAzGridText = Settings.get_current().get_showAltAzGridText(); - this._showPrecessionChart = Settings.get_current().get_showPrecessionChart(); - this._showConstellationPictures = Settings.get_current().get_showConstellationPictures(); - this._showConstellationLabels = Settings.get_current().get_showConstellationLabels(); - this._solarSystemCMB = Settings.get_current().get_solarSystemCMB(); - this._solarSystemMinorPlanets = Settings.get_current().get_solarSystemMinorPlanets(); - this._solarSystemPlanets = Settings.get_current().get_solarSystemPlanets(); - this._showEarthSky = Settings.get_current().get_showEarthSky(); - this._solarSystemMinorOrbits = Settings.get_current().get_solarSystemMinorOrbits(); - this._constellationsEnabled = ''; - this._constellationFiguresFilter = Settings.get_current().get_constellationFiguresFilter().clone(); - this._constellationBoundariesFilter = Settings.get_current().get_constellationBoundariesFilter().clone(); - this._constellationNamesFilter = Settings.get_current().get_constellationNamesFilter().clone(); - this._constellationArtFilter = Settings.get_current().get_constellationArtFilter().clone(); - this._showSkyOverlays = Settings.get_current().get_showSkyOverlays(); - this._showConstellations = Settings.get_current().get_showConstellations(); - this._showSkyNode = Settings.get_current().get_showSkyNode(); - this._showSkyGrids = Settings.get_current().get_showSkyGrids(); - this._showSkyOverlaysIn3d = Settings.get_current().get_showSkyOverlaysIn3d(); - this._earthCutawayView = Settings.get_current().get_earthCutawayView(); - this._showISSModel = Settings.get_current().get_showISSModel(); - this._milkyWayModel = Settings.get_current().get_milkyWayModel(); - this._minorPlanetsFilter = Settings.get_current().get_minorPlanetsFilter(); - this._planetOrbitsFilter = Settings.get_current().get_planetOrbitsFilter(); - this._thumbnailString = ''; - this._thumbnail = null; - this.layers = {}; - this._overlays = []; - this._musicTrack = null; - this._voiceTrack = null; - this._eclipticGridColor = Colors.get_green(); - this._galacticGridColor = Colors.get_cyan(); - this._altAzGridColor = Colors.get_magenta(); - this._precessionChartColor = Colors.get_orange(); - this._eclipticColor = Colors.get_blue(); - this._equatorialGridColor = Colors.get_white(); - this._constellationLabelsHeight = 80; - this._id = Guid.newGuid().toString(); - } - TourStop.create = function (target) { - var ts = new TourStop(); - ts._target = target; - return ts; - }; - TourStop.getXmlText = function (ts) { - var writer = new XmlTextWriter(); - writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - ts._saveToXml(writer, true); - writer._close(); - return writer.body; - }; - TourStop._fromXml = function (owner, tourStop) { - try { - var newTourStop = new TourStop(); - newTourStop._owner = owner; - newTourStop.set_id(tourStop.attributes.getNamedItem('Id').nodeValue); - newTourStop.set_name(tourStop.attributes.getNamedItem('Name').nodeValue); - newTourStop.set_description(tourStop.attributes.getNamedItem('Description').nodeValue); - newTourStop._thumbnailString = tourStop.attributes.getNamedItem('Thumbnail').nodeValue; - newTourStop._duration = Util.parseTimeSpan(tourStop.attributes.getNamedItem('Duration').nodeValue); - if (tourStop.attributes.getNamedItem('Master') != null) { - newTourStop._masterSlide = ss.boolean(tourStop.attributes.getNamedItem('Master').nodeValue); - } - if (tourStop.attributes.getNamedItem('NextSlide') != null) { - newTourStop._nextSlide = tourStop.attributes.getNamedItem('NextSlide').nodeValue; - } - if (tourStop.attributes.getNamedItem('InterpolationType') != null) { - newTourStop.set_interpolationType(Enums.parse('InterpolationType', tourStop.attributes.getNamedItem('InterpolationType').nodeValue)); - } - newTourStop._fadeInOverlays = true; - if (tourStop.attributes.getNamedItem('FadeInOverlays') != null) { - newTourStop._fadeInOverlays = ss.boolean(tourStop.attributes.getNamedItem('FadeInOverlays').nodeValue); - } - if (tourStop.attributes.getNamedItem('Transition') != null) { - newTourStop._transition = Enums.parse('TransitionType', tourStop.attributes.getNamedItem('Transition').nodeValue); - } - if (tourStop.attributes.getNamedItem('HasLocation') != null) { - newTourStop._hasLocation = ss.boolean(tourStop.attributes.getNamedItem('HasLocation').nodeValue); - } - if (newTourStop._hasLocation) { - if (tourStop.attributes.getNamedItem('LocationAltitude') != null) { - newTourStop._locationAltitude = parseFloat(tourStop.attributes.getNamedItem('LocationAltitude').nodeValue); - } - if (tourStop.attributes.getNamedItem('LocationLat') != null) { - newTourStop._locationLat = parseFloat(tourStop.attributes.getNamedItem('LocationLat').nodeValue); - } - if (tourStop.attributes.getNamedItem('LocationLng') != null) { - newTourStop._locationLng = parseFloat(tourStop.attributes.getNamedItem('LocationLng').nodeValue); - } - } - if (tourStop.attributes.getNamedItem('HasTime') != null) { - newTourStop._hasTime = ss.boolean(tourStop.attributes.getNamedItem('HasTime').nodeValue); - if (newTourStop._hasTime) { - if (tourStop.attributes.getNamedItem('StartTime') != null) { - newTourStop._startTime = ss.date(tourStop.attributes.getNamedItem('StartTime').nodeValue + ' UTC'); - } - if (tourStop.attributes.getNamedItem('EndTime') != null) { - newTourStop._endTime = ss.date(tourStop.attributes.getNamedItem('EndTime').nodeValue + ' UTC'); - } - } - } - if (tourStop.attributes.getNamedItem('ActualPlanetScale') != null) { - newTourStop._actualPlanetScale = ss.boolean(tourStop.attributes.getNamedItem('ActualPlanetScale').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowClouds') != null) { - newTourStop._showClouds = ss.boolean(tourStop.attributes.getNamedItem('ShowClouds').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowConstellationBoundries') != null) { - newTourStop._showConstellationBoundries = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationBoundries').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowConstellationFigures') != null) { - newTourStop._showConstellationFigures = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationFigures').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowConstellationSelection') != null) { - newTourStop._showConstellationSelection = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationSelection').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEcliptic') != null) { - newTourStop._showEcliptic = ss.boolean(tourStop.attributes.getNamedItem('ShowEcliptic').nodeValue); - } - if (tourStop.attributes.getNamedItem('EclipticColor') != null) { - newTourStop._eclipticColor = Color.load(tourStop.attributes.getNamedItem('EclipticColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowElevationModel') != null) { - newTourStop._showElevationModel = ss.boolean(tourStop.attributes.getNamedItem('ShowElevationModel').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowFieldOfView') != null) { - newTourStop._showFieldOfView = ss.boolean(tourStop.attributes.getNamedItem('ShowFieldOfView').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowGrid') != null) { - newTourStop._showGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowGrid').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowHorizon') != null) { - newTourStop._showHorizon = ss.boolean(tourStop.attributes.getNamedItem('ShowHorizon').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowHorizonPanorama') != null) { - newTourStop._showHorizonPanorama = ss.boolean(tourStop.attributes.getNamedItem('ShowHorizonPanorama').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowMoonsAsPointSource') != null) { - newTourStop._showMoonsAsPointSource = ss.boolean(tourStop.attributes.getNamedItem('ShowMoonsAsPointSource').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowSolarSystem') != null) { - newTourStop._showSolarSystem = ss.boolean(tourStop.attributes.getNamedItem('ShowSolarSystem').nodeValue); - } - if (tourStop.attributes.getNamedItem('FovTelescope') != null) { - newTourStop._fovTelescope = parseInt(tourStop.attributes.getNamedItem('FovTelescope').nodeValue); - } - if (tourStop.attributes.getNamedItem('FovEyepiece') != null) { - newTourStop._fovEyepiece = parseInt(tourStop.attributes.getNamedItem('FovEyepiece').nodeValue); - } - if (tourStop.attributes.getNamedItem('FovCamera') != null) { - newTourStop._fovCamera = parseInt(tourStop.attributes.getNamedItem('FovCamera').nodeValue); - } - if (tourStop.attributes.getNamedItem('LocalHorizonMode') != null) { - newTourStop._localHorizonMode = ss.boolean(tourStop.attributes.getNamedItem('LocalHorizonMode').nodeValue); - } - if (tourStop.attributes.getNamedItem('GalacticMode') != null) { - newTourStop._galacticMode = ss.boolean(tourStop.attributes.getNamedItem('GalacticMode').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemStars') != null) { - newTourStop._solarSystemStars = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemStars').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemMilkyWay') != null) { - newTourStop._solarSystemMilkyWay = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMilkyWay').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemCosmos') != null) { - newTourStop._solarSystemCosmos = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemCosmos').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemOrbits') != null) { - newTourStop._solarSystemOrbits = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemOrbits').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemOverlays') != null) { - newTourStop._solarSystemOverlays = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemOverlays').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemLighting') != null) { - newTourStop._solarSystemLighting = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemLighting').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemScale') != null) { - newTourStop._solarSystemScale = parseInt(tourStop.attributes.getNamedItem('SolarSystemScale').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemMultiRes') != null) { - newTourStop._solarSystemMultiRes = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMultiRes').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEquatorialGridText') != null) { - newTourStop._showEquatorialGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowEquatorialGridText').nodeValue); - } - if (tourStop.attributes.getNamedItem('EquatorialGridColor') != null) { - newTourStop._equatorialGridColor = Color.load(tourStop.attributes.getNamedItem('EquatorialGridColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowGalacticGrid') != null) { - newTourStop._showGalacticGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowGalacticGrid').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowGalacticGridText') != null) { - newTourStop._showGalacticGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowGalacticGridText').nodeValue); - } - if (tourStop.attributes.getNamedItem('GalacticGridColor') != null) { - newTourStop._galacticGridColor = Color.load(tourStop.attributes.getNamedItem('GalacticGridColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEclipticGrid') != null) { - newTourStop._showEclipticGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticGrid').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEclipticGridText') != null) { - newTourStop._showEclipticGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticGridText').nodeValue); - } - if (tourStop.attributes.getNamedItem('EclipticGridColor') != null) { - newTourStop._eclipticGridColor = Color.load(tourStop.attributes.getNamedItem('EclipticGridColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEclipticOverviewText') != null) { - newTourStop._showEclipticOverviewText = ss.boolean(tourStop.attributes.getNamedItem('ShowEclipticOverviewText').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowAltAzGrid') != null) { - newTourStop._showAltAzGrid = ss.boolean(tourStop.attributes.getNamedItem('ShowAltAzGrid').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowAltAzGridText') != null) { - newTourStop._showAltAzGridText = ss.boolean(tourStop.attributes.getNamedItem('ShowAltAzGridText').nodeValue); - } - if (tourStop.attributes.getNamedItem('AltAzGridColor') != null) { - newTourStop._altAzGridColor = Color.load(tourStop.attributes.getNamedItem('AltAzGridColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowPrecessionChart') != null) { - newTourStop._showPrecessionChart = ss.boolean(tourStop.attributes.getNamedItem('ShowPrecessionChart').nodeValue); - } - if (tourStop.attributes.getNamedItem('PrecessionChartColor') != null) { - newTourStop._precessionChartColor = Color.load(tourStop.attributes.getNamedItem('PrecessionChartColor').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowConstellationPictures') != null) { - newTourStop._showConstellationPictures = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationPictures').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowConstellationLabels') != null) { - newTourStop._showConstellationLabels = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellationLabels').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemCMB') != null) { - newTourStop._solarSystemCMB = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemCMB').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemMinorPlanets') != null) { - newTourStop._solarSystemMinorPlanets = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMinorPlanets').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemPlanets') != null) { - newTourStop._solarSystemPlanets = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemPlanets').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowEarthSky') != null) { - newTourStop._showEarthSky = ss.boolean(tourStop.attributes.getNamedItem('ShowEarthSky').nodeValue); - } - if (tourStop.attributes.getNamedItem('SolarSystemMinorOrbits') != null) { - newTourStop._solarSystemMinorOrbits = ss.boolean(tourStop.attributes.getNamedItem('SolarSystemMinorOrbits').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowSkyOverlays') != null) { - newTourStop._showSkyOverlays = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyOverlays').nodeValue); - } - else { - newTourStop._showSkyOverlays = true; - } - if (tourStop.attributes.getNamedItem('ShowConstellations') != null) { - newTourStop._showConstellations = ss.boolean(tourStop.attributes.getNamedItem('ShowConstellations').nodeValue); - } - else { - newTourStop._showConstellations = true; - } - if (tourStop.attributes.getNamedItem('ShowSkyNode') != null) { - newTourStop._showSkyNode = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyNode').nodeValue); - } - else { - newTourStop._showSkyNode = true; - } - if (tourStop.attributes.getNamedItem('ShowSkyGrids') != null) { - newTourStop._showSkyGrids = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyGrids').nodeValue); - } - else { - newTourStop._showSkyGrids = true; - } - if (tourStop.attributes.getNamedItem('ShowSkyOverlaysIn3d') != null) { - newTourStop._showSkyOverlaysIn3d = ss.boolean(tourStop.attributes.getNamedItem('ShowSkyOverlaysIn3d').nodeValue); - } - if (tourStop.attributes.getNamedItem('EarthCutawayView') != null) { - newTourStop._earthCutawayView = ss.boolean(tourStop.attributes.getNamedItem('EarthCutawayView').nodeValue); - } - if (tourStop.attributes.getNamedItem('ShowISSModel') != null) { - newTourStop._showISSModel = ss.boolean(tourStop.attributes.getNamedItem('ShowISSModel').nodeValue); - } - if (tourStop.attributes.getNamedItem('MilkyWayModel') != null) { - newTourStop._milkyWayModel = ss.boolean(tourStop.attributes.getNamedItem('MilkyWayModel').nodeValue); - } - if (tourStop.attributes.getNamedItem('ConstellationBoundariesFilter') != null) { - newTourStop._constellationBoundariesFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationBoundariesFilter').nodeValue); - } - else { - newTourStop._constellationBoundariesFilter = ConstellationFilter.get_allConstellation(); - } - if (tourStop.attributes.getNamedItem('ConstellationBoundariesFilter') != null) { - newTourStop._constellationFiguresFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationBoundariesFilter').nodeValue); - } - else { - newTourStop._constellationFiguresFilter = new ConstellationFilter(); - } - if (tourStop.attributes.getNamedItem('ConstellationNamesFilter') != null) { - newTourStop._constellationNamesFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationNamesFilter').nodeValue); - } - else { - newTourStop._constellationNamesFilter = new ConstellationFilter(); - } - if (tourStop.attributes.getNamedItem('ConstellationArtFilter') != null) { - newTourStop._constellationArtFilter = ConstellationFilter.parse(tourStop.attributes.getNamedItem('ConstellationArtFilter').nodeValue); - } - else { - newTourStop._constellationArtFilter = new ConstellationFilter(); - } - if (tourStop.attributes.getNamedItem('MinorPlanetsFilter') != null) { - newTourStop._minorPlanetsFilter = parseInt(tourStop.attributes.getNamedItem('MinorPlanetsFilter').nodeValue); - } - if (tourStop.attributes.getNamedItem('PlanetOrbitsFilter') != null) { - newTourStop._planetOrbitsFilter = parseInt(tourStop.attributes.getNamedItem('PlanetOrbitsFilter').nodeValue); - } - var place = Util.selectSingleNode(tourStop, 'Place'); - newTourStop._target = Place._fromXml(place); - var endTarget = Util.selectSingleNode(tourStop, 'EndTarget'); - if (endTarget != null) { - newTourStop._endTarget = Place._fromXml(endTarget); - } - var overlays = Util.selectSingleNode(tourStop, 'Overlays'); - var $enum1 = ss.enumerate(overlays.childNodes); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (overlay.nodeName === 'Overlay') { - newTourStop.addOverlay(Overlay._fromXml(newTourStop, overlay)); - } - } - var musicNode = Util.selectSingleNode(tourStop, 'MusicTrack'); - if (musicNode != null) { - newTourStop._musicTrack = Overlay._fromXml(newTourStop, Util.selectSingleNode(musicNode, 'Overlay')); - } - var voiceNode = Util.selectSingleNode(tourStop, 'VoiceTrack'); - if (voiceNode != null) { - newTourStop._voiceTrack = Overlay._fromXml(newTourStop, Util.selectSingleNode(voiceNode, 'Overlay')); - } - var layerNode = Util.selectSingleNode(tourStop, 'VisibleLayers'); - if (layerNode != null) { - newTourStop._loadLayerList(layerNode); - } - newTourStop._thumbnail = owner.getCachedTexture(ss.format('{0}.thumb.png', newTourStop._id), function () { - var c = 0; - }); - return newTourStop; - } - catch (ex) { - WWTControl.scriptInterface._fireTourError(ex); - return null; - } - }; - var TourStop$ = { - get_keyFramed: function () { - return this._keyFramed; - }, - get_tourStopType: function () { - if (this._target.get_backgroundImageset() != null) { - return this._target.get_backgroundImageset().get_dataSetType(); - } - else { - return this._tourStopType; - } - }, - set_tourStopType: function (value) { - if (this._target.get_backgroundImageset() != null) { - if (this._target.get_backgroundImageset().get_dataSetType() !== value) { - this._target.set_backgroundImageset(null); - } - } - this._tourStopType = value; - return value; - }, - get_tweenPosition: function () { - return this._tweenPosition; - }, - set_tweenPosition: function (value) { - if (this._tweenPosition !== value) { - this._tweenPosition = Math.max(0, Math.min(1, value)); - this.updateTweenPosition(); - } - return value; - }, - updateTweenPosition: function () { - if (this.get_keyFramed()) { - } - }, - copy: function () { - var writer = new XmlTextWriter(); - writer._writeProcessingInstruction('xml', "version='1.0' encoding='UTF-8'"); - this._saveToXml(writer, true); - try { - var xParser = new DOMParser(); - var doc = xParser.parseFromString(writer.body, 'text/xml'); - var node = Util.selectSingleNode(doc, 'TourStop'); - var ts = TourStop._fromXml(this.get_owner(), node); - ts.set_id(Guid.newGuid().toString()); - return ts; - } - catch ($e1) { - } - return null; - }, - get_owner: function () { - return this._owner; - }, - set_owner: function (value) { - this._owner = value; - return value; - }, - get__transition: function () { - return this._transition; - }, - set__transition: function (value) { - if (this._transition !== value) { - this._transition = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get__transitionTime: function () { - return this._transitionTime; - }, - set__transitionTime: function (value) { - if (this._transitionTime !== value) { - this._transitionTime = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get__transitionHoldTime: function () { - return this._transitionHoldTime; - }, - set__transitionHoldTime: function (value) { - if (this._transitionHoldTime !== value) { - this._transitionHoldTime = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get__transitionOutTime: function () { - return this._transitionOutTime; - }, - set__transitionOutTime: function (value) { - if (this._transitionOutTime !== value) { - this._transitionOutTime = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_nextSlide: function () { - return this._nextSlide; - }, - set_nextSlide: function (value) { - this._nextSlide = value; - return value; - }, - get_isLinked: function () { - if (this._nextSlide == null || this._nextSlide === 'Next' || !this._nextSlide) { - return false; - } - return true; - }, - get_fadeInOverlays: function () { - return this._fadeInOverlays; - }, - set_fadeInOverlays: function (value) { - this._fadeInOverlays = value; - return value; - }, - get_masterSlide: function () { - return this._masterSlide; - }, - set_masterSlide: function (value) { - if (this._masterSlide !== value) { - this._masterSlide = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_id: function () { - return this._id; - }, - set_id: function (value) { - this._id = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - return value; - }, - toString: function () { - if (this._target != null) { - return this.get_target().get_name(); - } - else { - return this._description; - } - }, - get_description: function () { - return this._description; - }, - set_description: function (value) { - if (this._description !== value) { - this._description = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_name: function () { - if (this._target != null) { - return this._target.get_name(); - } - return this._name; - }, - set_name: function (value) { - if (this._name !== value) { - this._name = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_duration: function () { - return this._duration; - }, - set_duration: function (value) { - if (this._duration !== value) { - this._duration = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_target: function () { - return this._target; - }, - set_target: function (value) { - if (this._target !== value) { - this._target = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_endTarget: function () { - return this._endTarget; - }, - set_endTarget: function (value) { - if (this._endTarget !== value) { - this._endTarget = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_interpolationType: function () { - return this._interpolationType; - }, - set_interpolationType: function (value) { - this._interpolationType = value; - return value; - }, - get_hasLocation: function () { - return this._hasTime; - }, - set_hasLocation: function (value) { - if (this._hasLocation !== value) { - this._hasLocation = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_hasTime: function () { - return this._hasTime; - }, - set_hasTime: function (value) { - if (this._hasTime !== value) { - this._hasTime = this._hasLocation = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_startTime: function () { - return this._startTime; - }, - set_startTime: function (value) { - this._startTime = value; - if (!ss.compareDates(this._startTime, value)) { - this._startTime = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_endTime: function () { - return this._endTime; - }, - set_endTime: function (value) { - if (!ss.compareDates(this._endTime, value)) { - this._endTime = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - captureSettings: function () { - this._startTime = SpaceTimeController.get_now(); - this._actualPlanetScale = Settings.get_current().get_actualPlanetScale(); - this._locationAltitude = Settings.get_current().get_locationAltitude(); - this._locationLat = Settings.get_current().get_locationLat(); - this._locationLng = Settings.get_current().get_locationLng(); - this._showClouds = Settings.get_current().get_showClouds(); - this._showConstellationBoundries = Settings.get_current().get_showConstellationBoundries(); - this._showConstellationFigures = Settings.get_current().get_showConstellationFigures(); - this._showConstellationSelection = Settings.get_current().get_showConstellationSelection(); - this._showEcliptic = Settings.get_current().get_showEcliptic(); - this._showElevationModel = Settings.get_current().get_showElevationModel(); - this._showFieldOfView = Settings.get_current().get_showFieldOfView(); - this._showGrid = Settings.get_current().get_showGrid(); - this._showHorizon = Settings.get_current().get_showHorizon(); - this._showHorizonPanorama = Settings.get_current().get_showHorizonPanorama(); - this._showMoonsAsPointSource = Settings.get_current().get_showMoonsAsPointSource(); - this._showSolarSystem = Settings.get_current().get_showSolarSystem(); - this._fovTelescope = Settings.get_current().get_fovTelescope(); - this._fovEyepiece = Settings.get_current().get_fovEyepiece(); - this._fovCamera = Settings.get_current().get_fovCamera(); - this._localHorizonMode = Settings.get_current().get_localHorizonMode(); - this._galacticMode = Settings.get_current().get_galacticMode(); - this._solarSystemStars = Settings.get_current().get_solarSystemStars(); - this._solarSystemMilkyWay = Settings.get_current().get_solarSystemMilkyWay(); - this._solarSystemCosmos = Settings.get_current().get_solarSystemCosmos(); - this._solarSystemOrbits = Settings.get_current().get_solarSystemOrbits(); - this._solarSystemOverlays = Settings.get_current().get_solarSystemOverlays(); - this._solarSystemLighting = Settings.get_current().get_solarSystemLighting(); - this._solarSystemScale = Settings.get_current().get_solarSystemScale(); - this._solarSystemMultiRes = Settings.get_current().get_solarSystemMultiRes(); - this._showEquatorialGridText = Settings.get_current().get_showEquatorialGridText(); - this._showGalacticGrid = Settings.get_current().get_showGalacticGrid(); - this._showGalacticGridText = Settings.get_current().get_showGalacticGridText(); - this._showEclipticGrid = Settings.get_current().get_showEclipticGrid(); - this._showEclipticGridText = Settings.get_current().get_showEclipticGridText(); - this._showEclipticOverviewText = Settings.get_current().get_showEclipticOverviewText(); - this._showAltAzGrid = Settings.get_current().get_showAltAzGrid(); - this._showAltAzGridText = Settings.get_current().get_showAltAzGridText(); - this._showPrecessionChart = Settings.get_current().get_showPrecessionChart(); - this._showConstellationPictures = Settings.get_current().get_showConstellationPictures(); - this._showConstellationLabels = Settings.get_current().get_showConstellationLabels(); - this._solarSystemCMB = Settings.get_current().get_solarSystemCMB(); - this._solarSystemMinorPlanets = Settings.get_current().get_solarSystemMinorPlanets(); - this._solarSystemPlanets = Settings.get_current().get_solarSystemPlanets(); - this._showEarthSky = Settings.get_current().get_showEarthSky(); - this._solarSystemMinorOrbits = Settings.get_current().get_solarSystemMinorOrbits(); - this._constellationFiguresFilter = Settings.get_current().get_constellationFiguresFilter().clone(); - this._constellationBoundariesFilter = Settings.get_current().get_constellationBoundariesFilter().clone(); - this._constellationNamesFilter = Settings.get_current().get_constellationNamesFilter().clone(); - this._constellationArtFilter = Settings.get_current().get_constellationArtFilter().clone(); - this._showSkyOverlays = Settings.get_current().get_showSkyOverlays(); - this._showConstellations = Settings.get_current().get_showConstellations(); - this._showSkyNode = Settings.get_current().get_showSkyNode(); - this._showSkyGrids = Settings.get_current().get_showSkyGrids(); - this._showSkyOverlaysIn3d = Settings.get_current().get_showSkyOverlaysIn3d(); - this._earthCutawayView = Settings.get_current().get_earthCutawayView(); - this._showISSModel = Settings.get_current().get_showISSModel(); - this._milkyWayModel = Settings.get_current().get_milkyWayModel(); - this._minorPlanetsFilter = Settings.get_current().get_minorPlanetsFilter(); - this._planetOrbitsFilter = Settings.get_current().get_planetOrbitsFilter(); - }, - syncSettings: function () { - Settings.get_globalSettings().set_actualPlanetScale(this._actualPlanetScale); - Settings.get_globalSettings().set_locationAltitude(this._locationAltitude); - Settings.get_globalSettings().set_locationLat(this._locationLat); - Settings.get_globalSettings().set_locationLng(this._locationLng); - Settings.get_globalSettings().set_earthCutawayView(this._earthCutawayView); - Settings.get_globalSettings().set_showConstellationBoundries(this._showConstellationBoundries); - Settings.get_globalSettings().set_showConstellationFigures(this._showConstellationFigures); - Settings.get_globalSettings().set_showConstellationSelection(this._showConstellationSelection); - Settings.get_globalSettings().set_showEcliptic(this._showEcliptic); - Settings.get_globalSettings().set_showElevationModel(this._showElevationModel); - Settings.get_globalSettings().set_showGrid(this._showGrid); - Settings.get_globalSettings().set_showHorizon(this._showHorizon); - Settings.get_globalSettings().set_showSolarSystem(this._showSolarSystem); - Settings.get_globalSettings().set_localHorizonMode(this._localHorizonMode); - Settings.get_globalSettings().set_galacticMode(this._galacticMode); - Settings.get_globalSettings().set_solarSystemStars(this._solarSystemStars); - Settings.get_globalSettings().set_solarSystemMilkyWay(this._solarSystemMilkyWay); - Settings.get_globalSettings().set_solarSystemCosmos(this._solarSystemCosmos); - Settings.get_globalSettings().set_solarSystemCMB(this._solarSystemCMB); - Settings.get_globalSettings().set_solarSystemOrbits(this._solarSystemOrbits); - Settings.get_globalSettings().set_solarSystemMinorOrbits(this._solarSystemMinorOrbits); - Settings.get_globalSettings().set_solarSystemMinorPlanets(this._solarSystemMinorPlanets); - Settings.get_globalSettings().set_solarSystemOverlays(this._solarSystemOverlays); - Settings.get_globalSettings().set_solarSystemLighting(this._solarSystemLighting); - Settings.get_globalSettings().set_showISSModel(this._showISSModel); - Settings.get_globalSettings().set_solarSystemScale(this._solarSystemScale); - Settings.get_globalSettings().set_solarSystemMultiRes(this._solarSystemMultiRes); - Settings.get_globalSettings().set_showEarthSky(this._showEarthSky); - Settings.get_globalSettings().set_minorPlanetsFilter(this._minorPlanetsFilter); - Settings.get_globalSettings().set_planetOrbitsFilter(this._planetOrbitsFilter); - Settings.get_globalSettings().set_showEquatorialGridText(this._showEquatorialGridText); - Settings.get_globalSettings().set_showGalacticGrid(this._showGalacticGrid); - Settings.get_globalSettings().set_showGalacticGridText(this._showGalacticGridText); - Settings.get_globalSettings().set_showEclipticGrid(this._showEclipticGrid); - Settings.get_globalSettings().set_showEclipticGridText(this._showEclipticGridText); - Settings.get_globalSettings().set_showEclipticOverviewText(this._showEclipticOverviewText); - Settings.get_globalSettings().set_showAltAzGrid(this._showAltAzGrid); - Settings.get_globalSettings().set_showAltAzGridText(this._showAltAzGridText); - Settings.get_globalSettings().set_showPrecessionChart(this._showPrecessionChart); - Settings.get_globalSettings().set_showConstellationPictures(this._showConstellationPictures); - Settings.get_globalSettings().set_constellationsEnabled(this._constellationsEnabled); - Settings.get_globalSettings().set_showSkyOverlays(this._showSkyOverlays); - Settings.get_globalSettings().set_constellations(this._showConstellations); - Settings.get_globalSettings().set_showSkyNode(this._showSkyNode); - Settings.get_globalSettings().set_showSkyGrids(this._showSkyGrids); - Settings.get_globalSettings().set_constellationFiguresFilter(this._constellationFiguresFilter.clone()); - Settings.get_globalSettings().set_constellationBoundariesFilter(this._constellationBoundariesFilter.clone()); - Settings.get_globalSettings().set_constellationNamesFilter(this._constellationNamesFilter.clone()); - Settings.get_globalSettings().set_constellationArtFilter(this._constellationArtFilter.clone()); - }, - get_solarSystemStars: function () { - return this._solarSystemStars; - }, - get_solarSystemMultiRes: function () { - return this._solarSystemMultiRes; - }, - get_solarSystemMilkyWay: function () { - return this._solarSystemMilkyWay; - }, - get_solarSystemCosmos: function () { - return this._solarSystemCosmos; - }, - get_solarSystemOrbits: function () { - return this._solarSystemOrbits; - }, - get_solarSystemOverlays: function () { - return this._solarSystemOverlays; - }, - get_solarSystemLighting: function () { - return this._solarSystemLighting; - }, - get_solarSystemScale: function () { - return this._solarSystemScale; - }, - get_actualPlanetScale: function () { - return this._actualPlanetScale; - }, - get_fovCamera: function () { - return this._fovCamera; - }, - get_fovEyepiece: function () { - return this._fovEyepiece; - }, - get_fovTelescope: function () { - return this._fovTelescope; - }, - get_locationAltitude: function () { - if (this._hasLocation) { - return this._locationAltitude; - } - else { - return Settings.get_current().get_locationAltitude(); - } - }, - get_locationLat: function () { - if (this._hasLocation) { - return this._locationLat; - } - else { - return Settings.get_current().get_locationLat(); - } - }, - get_locationLng: function () { - if (this._hasLocation) { - return this._locationLng; - } - else { - return Settings.get_current().get_locationLng(); - } - }, - get_showClouds: function () { - return this._showClouds; - }, - get_showConstellationBoundries: function () { - return this._showConstellationBoundries; - }, - get_showConstellationFigures: function () { - return this._showConstellationFigures; - }, - get_showConstellationSelection: function () { - return this._showConstellationSelection; - }, - get_showEcliptic: function () { - return this._showEcliptic; - }, - get_showElevationModel: function () { - return this._showElevationModel; - }, - get_showFieldOfView: function () { - return this._showFieldOfView; - }, - get_showGrid: function () { - return this._showGrid; - }, - get_showHorizon: function () { - return this._showHorizon; - }, - get_showHorizonPanorama: function () { - return this._showHorizonPanorama; - }, - get_showMoonsAsPointSource: function () { - return this._showMoonsAsPointSource; - }, - get_showSolarSystem: function () { - return this._showSolarSystem; - }, - get_localHorizonMode: function () { - return this._localHorizonMode; - }, - get_galacticMode: function () { - return this._galacticMode; - }, - get_thumbnail: function () { - if (this._target != null && this._thumbnail == null) { - return null; - } - return this._thumbnail; - }, - set_thumbnail: function (value) { - this._thumbnail = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - return value; - }, - get_overlays: function () { - return this._overlays; - }, - get_musicTrack: function () { - return this._musicTrack; - }, - set_musicTrack: function (value) { - if (this._musicTrack !== value) { - this._musicTrack = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - get_voiceTrack: function () { - return this._voiceTrack; - }, - set_voiceTrack: function (value) { - if (this._voiceTrack !== value) { - this._voiceTrack = value; - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - } - return value; - }, - addOverlay: function (overlay) { - if (overlay == null) { - return; - } - overlay.set_owner(this); - this._overlays.push(overlay); - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - removeOverlay: function (overlay) { - ss.remove(this._overlays, overlay); - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - cleanUp: function () { - var $enum1 = ss.enumerate(this.get_overlays()); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.cleanUp(); - } - if (this._voiceTrack != null) { - this._voiceTrack.cleanUp(); - } - if (this._musicTrack != null) { - this._musicTrack.cleanUp(); - } - }, - sendToBack: function (target) { - ss.remove(this._overlays, target); - this._overlays.splice(0, 0, target); - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - bringToFront: function (target) { - ss.remove(this._overlays, target); - this._overlays.push(target); - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - bringForward: function (target) { - var index = this._overlays.indexOf(target); - if (index < this._overlays.length - 1) { - ss.remove(this._overlays, target); - this._overlays.splice(index + 1, 0, target); - } - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - sendBackward: function (target) { - var index = this._overlays.indexOf(target); - if (index > 0) { - ss.remove(this._overlays, target); - this._overlays.splice(index - 1, 0, target); - } - if (this._owner != null) { - this._owner.set_tourDirty(true); - } - }, - getNextOverlay: function (current) { - if (current == null) { - if (this._overlays.length > 0) { - return this._overlays[0]; - } - else { - return null; - } - } - var index = this._overlays.indexOf(current); - if (index < this._overlays.length - 1) { - return this._overlays[index + 1]; - } - else { - return this._overlays[0]; - } - }, - getPerviousOverlay: function (current) { - if (current == null) { - if (this._overlays.length > 0) { - return this._overlays[0]; - } - else { - return null; - } - } - var index = this._overlays.indexOf(current); - if (index > 0) { - return this._overlays[index - 1]; - } - else { - return this._overlays[this._overlays.length - 1]; - } - }, - getOverlayById: function (id) { - var $enum1 = ss.enumerate(this._overlays); - while ($enum1.moveNext()) { - var ol = $enum1.current; - if (ol.id === id) { - return ol; - } - } - return null; - }, - get_tourStopThumbnailFilename: function () { - return ss.format('{0}.thumb.png', this._id); - }, - _saveToXml: function (xmlWriter, saveContent) { - if (saveContent) { - if (this._thumbnail != null) { - } - } - xmlWriter._writeStartElement('TourStop'); - xmlWriter._writeAttributeString('Id', this._id); - xmlWriter._writeAttributeString('Name', this._name); - xmlWriter._writeAttributeString('Description', this._description); - xmlWriter._writeAttributeString('Thumbnail', this._thumbnailString); - xmlWriter._writeAttributeString('Duration', Util.xmlDuration(this._duration)); - xmlWriter._writeAttributeString('Master', this._masterSlide.toString()); - xmlWriter._writeAttributeString('TransitionType', Enums.toXml('TransitionType', this._transition)); - xmlWriter._writeAttributeString('TransitionTime', this._transitionTime.toString()); - xmlWriter._writeAttributeString('TransitionOutTime', this._transitionOutTime.toString()); - xmlWriter._writeAttributeString('TransitionHoldTime', this._transitionHoldTime.toString()); - xmlWriter._writeAttributeString('NextSlide', this._nextSlide); - xmlWriter._writeAttributeString('InterpolationType', Enums.toXml('InterpolationType', this._interpolationType)); - xmlWriter._writeAttributeString('HasLocation', this._hasLocation.toString()); - if (this._hasLocation) { - xmlWriter._writeAttributeString('LocationAltitude', this._locationAltitude.toString()); - xmlWriter._writeAttributeString('LocationLat', this._locationLat.toString()); - xmlWriter._writeAttributeString('LocationLng', this._locationLng.toString()); - } - xmlWriter._writeAttributeString('HasTime', this._hasTime.toString()); - if (this._hasTime) { - xmlWriter._writeAttributeString('StartTime', Util.xmlDate(this._startTime)); - xmlWriter._writeAttributeString('EndTime', Util.xmlDate(this._endTime)); - } - xmlWriter._writeAttributeString('ActualPlanetScale', this._actualPlanetScale.toString()); - xmlWriter._writeAttributeString('ShowClouds', this._showClouds.toString()); - xmlWriter._writeAttributeString('EarthCutawayView', this._earthCutawayView.toString()); - xmlWriter._writeAttributeString('ShowConstellationBoundries', this._showConstellationBoundries.toString()); - xmlWriter._writeAttributeString('ShowConstellationFigures', this._showConstellationFigures.toString()); - xmlWriter._writeAttributeString('ShowConstellationSelection', this._showConstellationSelection.toString()); - xmlWriter._writeAttributeString('ShowEcliptic', this._showEcliptic.toString()); - xmlWriter._writeAttributeString('EclipticColor', this._eclipticColor.save()); - xmlWriter._writeAttributeString('ShowElevationModel', this._showElevationModel.toString()); - this._showFieldOfView = false; - xmlWriter._writeAttributeString('ShowFieldOfView', this._showFieldOfView.toString()); - xmlWriter._writeAttributeString('ShowGrid', this._showGrid.toString()); - xmlWriter._writeAttributeString('ShowHorizon', this._showHorizon.toString()); - xmlWriter._writeAttributeString('ShowHorizonPanorama', this._showHorizonPanorama.toString()); - xmlWriter._writeAttributeString('ShowMoonsAsPointSource', this._showMoonsAsPointSource.toString()); - xmlWriter._writeAttributeString('ShowSolarSystem', this._showSolarSystem.toString()); - xmlWriter._writeAttributeString('FovTelescope', this._fovTelescope.toString()); - xmlWriter._writeAttributeString('FovEyepiece', this._fovEyepiece.toString()); - xmlWriter._writeAttributeString('FovCamera', this._fovCamera.toString()); - xmlWriter._writeAttributeString('LocalHorizonMode', this._localHorizonMode.toString()); - xmlWriter._writeAttributeString('GalacticMode', this._galacticMode.toString()); - xmlWriter._writeAttributeString('FadeInOverlays', this._fadeInOverlays.toString()); - xmlWriter._writeAttributeString('SolarSystemStars', this._solarSystemStars.toString()); - xmlWriter._writeAttributeString('SolarSystemMilkyWay', this._solarSystemMilkyWay.toString()); - xmlWriter._writeAttributeString('SolarSystemCosmos', this._solarSystemCosmos.toString()); - xmlWriter._writeAttributeString('SolarSystemCMB', this._solarSystemCMB.toString()); - xmlWriter._writeAttributeString('SolarSystemOrbits', this._solarSystemOrbits.toString()); - xmlWriter._writeAttributeString('SolarSystemMinorOrbits', this._solarSystemMinorOrbits.toString()); - xmlWriter._writeAttributeString('SolarSystemOverlays', this._solarSystemOverlays.toString()); - xmlWriter._writeAttributeString('SolarSystemLighting', this._solarSystemLighting.toString()); - xmlWriter._writeAttributeString('ShowISSModel', this._showISSModel.toString()); - xmlWriter._writeAttributeString('SolarSystemScale', this._solarSystemScale.toString()); - xmlWriter._writeAttributeString('MinorPlanetsFilter', this._minorPlanetsFilter.toString()); - xmlWriter._writeAttributeString('PlanetOrbitsFilter', this._planetOrbitsFilter.toString()); - xmlWriter._writeAttributeString('SolarSystemMultiRes', this._solarSystemMultiRes.toString()); - xmlWriter._writeAttributeString('SolarSystemMinorPlanets', this._solarSystemMinorPlanets.toString()); - xmlWriter._writeAttributeString('SolarSystemPlanets', this._solarSystemPlanets.toString()); - xmlWriter._writeAttributeString('ShowEarthSky', this._showEarthSky.toString()); - xmlWriter._writeAttributeString('ShowEquatorialGridText', this.get_showEquatorialGridText().toString()); - xmlWriter._writeAttributeString('EquatorialGridColor', this.get_equatorialGridColor().save()); - xmlWriter._writeAttributeString('ShowGalacticGrid', this.get_showGalacticGrid().toString()); - xmlWriter._writeAttributeString('ShowGalacticGridText', this.get_showGalacticGridText().toString()); - xmlWriter._writeAttributeString('GalacticGridColor', this.get_galacticGridColor().save()); - xmlWriter._writeAttributeString('ShowEclipticGrid', this.get_showEclipticGrid().toString()); - xmlWriter._writeAttributeString('ShowEclipticGridText', this.get_showEclipticGridText().toString()); - xmlWriter._writeAttributeString('EclipticGridColor', this.get_eclipticGridColor().save()); - xmlWriter._writeAttributeString('ShowEclipticOverviewText', this.get_showEclipticOverviewText().toString()); - xmlWriter._writeAttributeString('ShowAltAzGrid', this.get_showAltAzGrid().toString()); - xmlWriter._writeAttributeString('ShowAltAzGridText', this.get_showAltAzGridText().toString()); - xmlWriter._writeAttributeString('AltAzGridColor', this.get_altAzGridColor().save()); - xmlWriter._writeAttributeString('ShowPrecessionChart', this.get_showPrecessionChart().toString()); - xmlWriter._writeAttributeString('PrecessionChartColor', this.get_precessionChartColor().save()); - xmlWriter._writeAttributeString('ConstellationPictures', this.get_showConstellationPictures().toString()); - xmlWriter._writeAttributeString('ConstellationsEnabled', this.get_constellationsEnabled()); - xmlWriter._writeAttributeString('ShowConstellationLabels', this.get_showConstellationLabels().toString()); - xmlWriter._writeAttributeString('ShowSkyOverlays', this.get_showSkyOverlays().toString()); - xmlWriter._writeAttributeString('ShowConstellations', this.get_showConstellations().toString()); - xmlWriter._writeAttributeString('ShowSkyNode', this.get_showSkyNode().toString()); - xmlWriter._writeAttributeString('ShowSkyGrids', this.get_showSkyGrids().toString()); - xmlWriter._writeAttributeString('SkyOverlaysIn3d', this.get_showSkyOverlaysIn3d().toString()); - xmlWriter._writeAttributeString('ConstellationFiguresFilter', this._constellationFiguresFilter.toString()); - xmlWriter._writeAttributeString('ConstellationBoundariesFilter', this._constellationBoundariesFilter.toString()); - xmlWriter._writeAttributeString('ConstellationNamesFilter', this._constellationNamesFilter.toString()); - xmlWriter._writeAttributeString('ConstellationArtFilter', this._constellationArtFilter.toString()); - this._target._saveToXml(xmlWriter, 'Place'); - if (this._endTarget != null) { - this._endTarget._saveToXml(xmlWriter, 'EndTarget'); - } - xmlWriter._writeStartElement('Overlays'); - var $enum1 = ss.enumerate(this._overlays); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.saveToXml(xmlWriter, false); - } - xmlWriter._writeEndElement(); - if (this._musicTrack != null) { - xmlWriter._writeStartElement('MusicTrack'); - this._musicTrack.saveToXml(xmlWriter, false); - xmlWriter._writeEndElement(); - } - if (this._voiceTrack != null) { - xmlWriter._writeStartElement('VoiceTrack'); - this._voiceTrack.saveToXml(xmlWriter, false); - xmlWriter._writeEndElement(); - } - this._writeLayerList(xmlWriter); - xmlWriter._writeEndElement(); - }, - _writeLayerList: function (xmlWriter) { - if (ss.keyCount(this.layers) > 0) { - xmlWriter._writeStartElement('VisibleLayers'); - var $enum1 = ss.enumerate(ss.keys(this.layers)); - while ($enum1.moveNext()) { - var key = $enum1.current; - var info = this.layers[key]; - xmlWriter._writeStartElement('Layer'); - xmlWriter._writeAttributeString('StartOpacity', info.startOpacity.toString()); - xmlWriter._writeAttributeString('EndOpacity', info.endOpacity.toString()); - var len = info.startParams.length; - xmlWriter._writeAttributeString('ParamCount', len.toString()); - for (var i = 0; i < len; i++) { - xmlWriter._writeAttributeString(ss.format('StartParam{0}', i), info.startParams[i].toString()); - xmlWriter._writeAttributeString(ss.format('EndParam{0}', i), info.endParams[i].toString()); - } - xmlWriter._writeValue(info.id.toString()); - xmlWriter._writeEndElement(); - } - xmlWriter._writeEndElement(); - } - }, - _addFilesToCabinet: function (fc, excludeAudio) { - if (this._thumbnail != null) { - var filename = ss.format('{0}.thumb.png', this._id); - var blob = this._owner.getFileBlob(filename); - fc.addFile(this._owner.get_workingDirectory() + filename, blob); - } - if (!excludeAudio) { - if (this._musicTrack != null) { - this._musicTrack.addFilesToCabinet(fc); - } - if (this._voiceTrack != null) { - this._voiceTrack.addFilesToCabinet(fc); - } - } - var $enum1 = ss.enumerate(this._overlays); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - overlay.addFilesToCabinet(fc); - } - }, - getNextDefaultName: function (baseName) { - var suffixId = 1; - var $enum1 = ss.enumerate(this._overlays); - while ($enum1.moveNext()) { - var overlay = $enum1.current; - if (ss.startsWith(overlay.get_name(), baseName)) { - var id = 0; - try { - id = parseInt(overlay.get_name().substr(baseName.length)); - } - catch ($e2) { - } - if (id >= suffixId) { - suffixId = id + 1; - } - } - } - return ss.format('{0} {1}', baseName, suffixId); - }, - _loadLayerList: function (layersNode) { - var $enum1 = ss.enumerate(layersNode.childNodes); - while ($enum1.moveNext()) { - var layer = $enum1.current; - if (layer.nodeName === 'Layer') { - var info = new LayerInfo(); - var id = layer.innerHTML; - info.id = Guid.fromString(id); - info.startOpacity = parseFloat(layer.attributes.getNamedItem('StartOpacity').nodeValue); - info.endOpacity = parseFloat(layer.attributes.getNamedItem('EndOpacity').nodeValue); - var len = 0; - if (layer.attributes.getNamedItem('ParamCount') != null) { - len = parseInt(layer.attributes.getNamedItem('ParamCount').nodeValue); - } - info.startParams = new Array(len); - info.endParams = new Array(len); - info.frameParams = new Array(len); - for (var i = 0; i < len; i++) { - info.startParams[i] = parseFloat(layer.attributes.getNamedItem(ss.format('StartParam{0}', i)).nodeValue); - info.endParams[i] = parseFloat(layer.attributes.getNamedItem(ss.format('EndParam{0}', i)).nodeValue); - info.frameParams[i] = info.startParams[i]; - } - this.layers[info.id] = info; - } - } - }, - _updateLayerOpacity: function () { - if (!this.get_keyFramed()) { - } - else { - this.updateTweenPosition(); - } - }, - get_showEquatorialGridText: function () { - return this._showEquatorialGridText; - }, - set_showEquatorialGridText: function (value) { - this._showEquatorialGridText = value; - return value; - }, - get_showGalacticGrid: function () { - return this._showGalacticGrid; - }, - set_showGalacticGrid: function (value) { - this._showGalacticGrid = value; - return value; - }, - get_showGalacticGridText: function () { - return this._showGalacticGridText; - }, - set_showGalacticGridText: function (value) { - this._showGalacticGridText = value; - return value; - }, - get_showEclipticGrid: function () { - return this._showEclipticGrid; - }, - set_showEclipticGrid: function (value) { - this._showEclipticGrid = value; - return value; - }, - get_showEclipticGridText: function () { - return this._showEclipticGridText; - }, - set_showEclipticGridText: function (value) { - this._showEclipticGridText = value; - return value; - }, - get_showEclipticOverviewText: function () { - return this._showEclipticOverviewText; - }, - set_showEclipticOverviewText: function (value) { - this._showEclipticOverviewText = value; - return value; - }, - get_showAltAzGrid: function () { - return this._showAltAzGrid; - }, - set_showAltAzGrid: function (value) { - this._showAltAzGrid = value; - return value; - }, - get_showAltAzGridText: function () { - return this._showAltAzGridText; - }, - set_showAltAzGridText: function (value) { - this._showAltAzGridText = value; - return value; - }, - get_showPrecessionChart: function () { - return this._showPrecessionChart; - }, - set_showPrecessionChart: function (value) { - this._showPrecessionChart = value; - return value; - }, - get_showConstellationPictures: function () { - return this._showConstellationPictures; - }, - set_showConstellationPictures: function (value) { - this._showConstellationPictures = value; - return value; - }, - get_showConstellationLabels: function () { - return this._showConstellationLabels; - }, - set_showConstellationLabels: function (value) { - this._showConstellationLabels = value; - return value; - }, - get_solarSystemCMB: function () { - return this._solarSystemCMB; - }, - set_solarSystemCMB: function (value) { - this._solarSystemCMB = value; - return value; - }, - get_solarSystemMinorPlanets: function () { - return this._solarSystemMinorPlanets; - }, - set_solarSystemMinorPlanets: function (value) { - this._solarSystemMinorPlanets = value; - return value; - }, - get_solarSystemPlanets: function () { - return this._solarSystemPlanets; - }, - set_solarSystemPlanets: function (value) { - this._solarSystemPlanets = value; - return value; - }, - get_showEarthSky: function () { - return this._showEarthSky; - }, - set_showEarthSky: function (value) { - this._showEarthSky = value; - return value; - }, - get_solarSystemMinorOrbits: function () { - return this._solarSystemMinorOrbits; - }, - set_solarSystemMinorOrbits: function (value) { - this._solarSystemMinorOrbits = value; - return value; - }, - get_constellationsEnabled: function () { - return this._constellationsEnabled; - }, - set_constellationsEnabled: function (value) { - this._constellationsEnabled = value; - return value; - }, - get_constellationFiguresFilter: function () { - return this._constellationFiguresFilter; - }, - set_constellationFiguresFilter: function (value) { - this._constellationFiguresFilter = value; - return value; - }, - get_constellationBoundariesFilter: function () { - return this._constellationBoundariesFilter; - }, - set_constellationBoundariesFilter: function (value) { - this._constellationBoundariesFilter = value; - return value; - }, - get_constellationNamesFilter: function () { - return this._constellationNamesFilter; - }, - set_constellationNamesFilter: function (value) { - this._constellationNamesFilter = value; - return value; - }, - get_constellationArtFilter: function () { - return this._constellationArtFilter; - }, - set_constellationArtFilter: function (value) { - this._constellationArtFilter = value; - return value; - }, - get_showSkyOverlays: function () { - return this._showSkyOverlays; - }, - set_showSkyOverlays: function (value) { - this._showSkyOverlays = value; - return value; - }, - get_showConstellations: function () { - return this._showConstellations; - }, - set_showConstellations: function (value) { - this._showConstellations = value; - return value; - }, - get_showSkyNode: function () { - return this._showSkyNode; - }, - set_showSkyNode: function (value) { - this._showSkyNode = value; - return value; - }, - get_showSkyGrids: function () { - return this._showSkyGrids; - }, - set_showSkyGrids: function (value) { - this._showSkyGrids = value; - return value; - }, - get_showSkyOverlaysIn3d: function () { - return this._showSkyOverlaysIn3d; - }, - set_showSkyOverlaysIn3d: function (value) { - this._showSkyOverlaysIn3d = value; - return value; - }, - get_earthCutawayView: function () { - return this._earthCutawayView; - }, - set_earthCutawayView: function (value) { - this._earthCutawayView = value; - return value; - }, - get_showISSModel: function () { - return this._showISSModel; - }, - set_showISSModel: function (value) { - this._showISSModel = value; - return value; - }, - get_milkyWayModel: function () { - return this._milkyWayModel; - }, - set_milkyWayModel: function (value) { - this._milkyWayModel = value; - return value; - }, - get_minorPlanetsFilter: function () { - return this._minorPlanetsFilter; - }, - set_minorPlanetsFilter: function (value) { - this._minorPlanetsFilter = value; - return value; - }, - get_planetOrbitsFilter: function () { - return this._planetOrbitsFilter; - }, - set_planetOrbitsFilter: function (value) { - this._planetOrbitsFilter = value; - return value; - }, - getSetting: function (type) { - if (type === 17) { - return new SettingParameter(true, this.faderOpacity, !!this.faderOpacity, null); - } - return new SettingParameter(false, 1, false, null); - }, - get_eclipticGridColor: function () { - return this._eclipticGridColor; - }, - set_eclipticGridColor: function (value) { - this._eclipticGridColor = value; - return value; - }, - get_galacticGridColor: function () { - return this._galacticGridColor; - }, - set_galacticGridColor: function (value) { - this._galacticGridColor = value; - return value; - }, - get_altAzGridColor: function () { - return this._altAzGridColor; - }, - set_altAzGridColor: function (value) { - this._altAzGridColor = value; - return value; - }, - get_precessionChartColor: function () { - return this._precessionChartColor; - }, - set_precessionChartColor: function (value) { - this._precessionChartColor = value; - return value; - }, - get_eclipticColor: function () { - return this._eclipticColor; - }, - set_eclipticColor: function (value) { - this._eclipticColor = value; - return value; - }, - get_equatorialGridColor: function () { - return this._equatorialGridColor; - }, - set_equatorialGridColor: function (value) { - this._equatorialGridColor = value; - return value; - }, - get_constellationLabelsHeight: function () { - return this._constellationLabelsHeight; - }, - set_constellationLabelsHeight: function (value) { - this._constellationLabelsHeight = value; - return value; - } - }; - - - // wwtlib.LayerInfo - - function LayerInfo() { - this.id = Guid.newGuid(); - this.startOpacity = 1; - this.endOpacity = 1; - this.frameOpacity = 1; - this.startParams = new Array(0); - this.endParams = new Array(0); - this.frameParams = new Array(0); - } - var LayerInfo$ = { - - }; - - - // wwtlib.UndoTourStopChange - - function UndoTourStopChange(text, tour) { - this._undoXml = ''; - this._redoXml = ''; - this._currentIndex = 0; - this._actionText = ''; - this._targetTour = null; - this._currentIndex = tour.get_currentTourstopIndex(); - this._actionText = text; - this._targetTour = tour; - this._undoXml = TourStop.getXmlText(tour.get_currentTourStop()); - this._targetTour.set_tourDirty(true); - } - var UndoTourStopChange$ = { - get_actionText: function () { - return this._actionText; - }, - set_actionText: function (value) { - this._actionText = value; - return value; - }, - undo: function () { - var tsRedo = this._targetTour.get_tourStops()[this._currentIndex]; - var parser = new DOMParser(); - var doc = parser.parseFromString(this._undoXml, 'text/xml'); - var node = Util.selectSingleNode(doc, 'TourStop'); - this._targetTour.get_tourStops()[this._currentIndex] = TourStop._fromXml(this._targetTour, node); - this._targetTour.set_currentTourstopIndex(this._currentIndex); - if (ss.emptyString(this._redoXml)) { - this._redoXml = TourStop.getXmlText(tsRedo); - } - this._targetTour.set_tourDirty(true); - }, - redo: function () { - var parser = new DOMParser(); - var doc = parser.parseFromString(this._redoXml, 'text/xml'); - var node = Util.selectSingleNode(doc, 'TourStop'); - this._targetTour.get_tourStops()[this._currentIndex] = TourStop._fromXml(this._targetTour, node); - this._targetTour.set_currentTourstopIndex(this._currentIndex); - this._targetTour.set_tourDirty(true); - }, - toString: function () { - return this._actionText; - } - }; - - - // wwtlib.Undo - - function Undo() { - } - Undo.clear = function () { - Undo._undoStack = new ss.Stack(); - Undo._redoStack = new ss.Stack(); - }; - Undo.push = function (step) { - Undo._undoStack.push(step); - Undo._redoStack = new ss.Stack(); - }; - Undo.peekActionString = function () { - if (Undo._undoStack.count > 0) { - return Undo._undoStack.peek().toString(); - } - else { - return Language.getLocalizedText(551, 'Nothing to Undo'); - } - }; - Undo.peekRedoActionString = function () { - if (Undo._redoStack.count > 0) { - return Undo._redoStack.peek().toString(); - } - else { - return ''; - } - }; - Undo.peekAction = function () { - return (Undo._undoStack.count > 0); - }; - Undo.peekRedoAction = function () { - return (Undo._redoStack.count > 0); - }; - Undo.stepBack = function () { - var step = Undo._undoStack.pop(); - step.undo(); - Undo._redoStack.push(step); - }; - Undo.stepForward = function () { - var step = Undo._redoStack.pop(); - step.redo(); - Undo._undoStack.push(step); - }; - var Undo$ = { - - }; - - - // wwtlib.UndoStep - - function UndoStep() { - } - var UndoStep$ = { - undo: function () { - }, - redo: function () { - }, - toString: function () { - return Language.getLocalizedText(551, 'Nothing to Undo'); - } - }; - - - // wwtlib.UndoTourSlidelistChange - - function UndoTourSlidelistChange(text, tour) { - this._currentIndex = 0; - this._actionText = ''; - this._targetTour = null; - this._undoList = []; - for (var i = 0; i < tour.get_tourStops().length; i++) { - this._undoList.push(tour.get_tourStops()[i]); - } - this._currentIndex = tour.get_currentTourstopIndex(); - this._actionText = text; - this._targetTour = tour; - this._targetTour.set_tourDirty(true); - } - var UndoTourSlidelistChange$ = { - get_actionText: function () { - return this._actionText; - }, - set_actionText: function (value) { - this._actionText = value; - return value; - }, - undo: function () { - this._redoList = this._targetTour.get_tourStops(); - this._targetTour.set_tourStops(this._undoList); - this._targetTour.set_currentTourstopIndex(this._currentIndex); - this._targetTour.set_tourDirty(true); - }, - redo: function () { - this._undoList = this._targetTour.get_tourStops(); - this._targetTour.set_tourStops(this._redoList); - this._targetTour.set_currentTourstopIndex(this._currentIndex); - this._targetTour.set_tourDirty(true); - }, - toString: function () { - return this._actionText; - } - }; - - - // wwtlib.UndoTourPropertiesChange - - function UndoTourPropertiesChange(text, tour) { - this._actionText = ''; - this._targetTour = null; - this._undoDomeMode = false; - this._undoLevel = 0; - this._redoDomeMode = false; - this._redoLevel = 0; - this._undoTitle = tour.get_title(); - this._undoAuthor = tour.get_author(); - this._undoAuthorEmail = tour.get_authorEmail(); - this._undoDescription = tour.get_description(); - this._undoAuthorImage = tour.get_authorImage(); - this._undoOrganizationUrl = tour.get_organizationUrl(); - this._undoOrgName = tour.get_orgName(); - this._undoKeywords = tour.get_keywords(); - this._undoTaxonomy = tour.get_taxonomy(); - this._undoLevel = tour.get_level(); - this._actionText = text; - this._targetTour = tour; - this._targetTour.set_tourDirty(true); - } - var UndoTourPropertiesChange$ = { - get_actionText: function () { - return this._actionText; - }, - set_actionText: function (value) { - this._actionText = value; - return value; - }, - undo: function () { - this._redoTitle = this._targetTour.get_title(); - this._redoAuthor = this._targetTour.get_author(); - this._redoAuthorEmail = this._targetTour.get_authorEmail(); - this._redoDescription = this._targetTour.get_description(); - this._redoAuthorImage = this._targetTour.get_authorImage(); - this._redoOrganizationUrl = this._targetTour.get_organizationUrl(); - this._redoOrgName = this._targetTour.get_orgName(); - this._redoKeywords = this._targetTour.get_keywords(); - this._redoTaxonomy = this._targetTour.get_taxonomy(); - this._redoLevel = this._targetTour.get_level(); - this._targetTour.set_title(this._undoTitle); - this._targetTour.set_author(this._undoAuthor); - this._targetTour.set_authorEmail(this._undoAuthorEmail); - this._targetTour.set_description(this._undoDescription); - this._targetTour.set_authorImage(this._undoAuthorImage); - this._targetTour.set_organizationUrl(this._undoOrganizationUrl); - this._targetTour.set_orgName(this._undoOrgName); - this._targetTour.set_keywords(this._undoKeywords); - this._targetTour.set_taxonomy(this._undoTaxonomy); - this._targetTour.set_level(this._undoLevel); - this._targetTour.set_tourDirty(true); - }, - redo: function () { - this._targetTour.set_title(this._redoTitle); - this._targetTour.set_author(this._redoAuthor); - this._targetTour.set_authorEmail(this._redoAuthorEmail); - this._targetTour.set_description(this._redoDescription); - this._targetTour.set_authorImage(this._redoAuthorImage); - this._targetTour.set_organizationUrl(this._redoOrganizationUrl); - this._targetTour.set_orgName(this._redoOrgName); - this._targetTour.set_keywords(this._redoKeywords); - this._targetTour.set_taxonomy(this._redoTaxonomy); - this._targetTour.set_level(this._redoLevel); - this._targetTour.set_tourDirty(true); - }, - toString: function () { - return this._actionText; - } - }; - - - // wwtlib.Triangle - - function Triangle() { - this.a = 0; - this.b = 0; - this.c = 0; - this.a = -1; - this.b = -1; - this.c = -1; - } - Triangle.create = function (a, b, c) { - var temp = new Triangle(); - temp.a = a; - temp.b = b; - temp.c = c; - return temp; - }; - var Triangle$ = { - subDivide: function (triList, vertexList) { - var a1 = Vector3d.lerp(vertexList[this.b].position, vertexList[this.c].position, 0.5); - var b1 = Vector3d.lerp(vertexList[this.c].position, vertexList[this.a].position, 0.5); - var c1 = Vector3d.lerp(vertexList[this.a].position, vertexList[this.b].position, 0.5); - var a1uv = Vector2d.lerp(Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), 0.5); - var b1uv = Vector2d.lerp(Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), 0.5); - var c1uv = Vector2d.lerp(Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), 0.5); - a1.normalize(); - b1.normalize(); - c1.normalize(); - var aIndex = vertexList.length; - var bIndex = vertexList.length + 1; - var cIndex = vertexList.length + 2; - vertexList.push(PositionTexture.createPosRaw(a1, a1uv.x, a1uv.y)); - vertexList.push(PositionTexture.createPosRaw(b1, b1uv.x, b1uv.y)); - vertexList.push(PositionTexture.createPosRaw(c1, c1uv.x, c1uv.y)); - triList.push(Triangle.create(this.a, cIndex, bIndex)); - triList.push(Triangle.create(this.b, aIndex, cIndex)); - triList.push(Triangle.create(this.c, bIndex, aIndex)); - triList.push(Triangle.create(aIndex, bIndex, cIndex)); - }, - subDivideNoNormalize: function (triList, vertexList) { - var a1 = Vector3d.lerp(vertexList[this.b].position, vertexList[this.c].position, 0.5); - var b1 = Vector3d.lerp(vertexList[this.c].position, vertexList[this.a].position, 0.5); - var c1 = Vector3d.lerp(vertexList[this.a].position, vertexList[this.b].position, 0.5); - var a1uv = Vector2d.lerp(Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), 0.5); - var b1uv = Vector2d.lerp(Vector2d.create(vertexList[this.c].tu, vertexList[this.c].tv), Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), 0.5); - var c1uv = Vector2d.lerp(Vector2d.create(vertexList[this.a].tu, vertexList[this.a].tv), Vector2d.create(vertexList[this.b].tu, vertexList[this.b].tv), 0.5); - var aIndex = vertexList.length; - var bIndex = vertexList.length + 1; - var cIndex = vertexList.length + 2; - vertexList.push(PositionTexture.createPosRaw(a1, a1uv.x, a1uv.y)); - vertexList.push(PositionTexture.createPosRaw(b1, b1uv.x, b1uv.y)); - vertexList.push(PositionTexture.createPosRaw(c1, c1uv.x, c1uv.y)); - triList.push(Triangle.create(this.a, cIndex, bIndex)); - triList.push(Triangle.create(this.b, aIndex, cIndex)); - triList.push(Triangle.create(this.c, bIndex, aIndex)); - triList.push(Triangle.create(aIndex, bIndex, cIndex)); - } - }; - - - // wwtlib.UiTools - - function UiTools() { - } - UiTools.gamma = function (val, gamma) { - return Math.min(255, ss.truncate(((255 * Math.pow(val / 255, 1 / gamma)) + 0.5))); - }; - UiTools.getNamesStringFromArray = function (array) { - var names = ''; - var delim = ''; - var $enum1 = ss.enumerate(array); - while ($enum1.moveNext()) { - var name = $enum1.current; - names += delim; - names += name; - delim = ';'; - } - return names; - }; - UiTools.solarSystemToMeters = function (SolarSystemCameraDistance) { - return SolarSystemCameraDistance * 149598000 * 370; - }; - UiTools.metersToSolarSystemDistance = function (meters) { - return meters / 370 * 149598000; - }; - UiTools.metersToZoom = function (meters) { - return ((meters / 1000 / 370) - 1E-06) / 4 * 9; - }; - UiTools.formatDistance = function (distance) { - if (distance < 0.1) { - var km = (distance * 149598000); - if (km < 10) { - var m = ss.truncate((km * 1000)); - return ss.format('{0} m', m); - } - else { - km = ss.truncate(km); - return ss.format('{0} km', km); - } - } - else if (distance < (10)) { - var au = ss.truncate((distance * 10)) / 10; - return ss.format('{0} au', au); - } - else if (distance < (63239.6717 / 10)) { - var au = ss.truncate(distance); - return ss.format('{0} au', au); - } - else if (distance < (63239.6717 * 10)) { - var ly = ss.truncate(((distance * 10) / 63239.6717)) / 10; - return ss.format('{0} ly', ly); - } - else if (distance < (63239.6717 * 1000000)) { - var ly = ss.truncate((distance / 63239.6717)); - return ss.format('{0} ly', ly); - } - else if (distance < (206264.806 * 10000000)) { - var mpc = ss.truncate(((distance * 10) / (206264.806 * 1000000))) / 10; - return ss.format('{0} Mpc', mpc); - } - else if (distance < (206264.806 * 1000000000)) { - var mpc = ss.truncate((distance / (206264.806 * 1000000))); - return ss.format('{0} Mpc', mpc); - } - else { - var mpc = ss.truncate(((distance * 10) / (206264.806 * 1000000000))) / 10; - return ss.format('{0} Gpc', mpc); - } - }; - UiTools.formatDecimalHours = function (dayFraction) { - var today = ss.now(); - var ts = today.getTimezoneOffset() / 60; - ts = 0; - var day = (dayFraction - ts) + 0.0083333334; - while (day > 24) { - day -= 24; - } - while (day < 0) { - day += 24; - } - var hours = ss.truncate(day); - var minutes = ss.truncate(((day * 60) - (hours * 60))); - var seconds = ss.truncate(((day * 3600) - ((hours * 3600) + (minutes * 60)))); - return ss.format('{0}:{1}', hours, minutes, seconds); - }; - UiTools.splitString = function (data, delimiter) { - var output = []; - var nestingLevel = 0; - var current = 0; - var count = 0; - var start = 0; - while (current < data.length) { - if (data.substr(current, 1) === '(') { - nestingLevel++; - } - if (data.substr(current, 1) === ')') { - nestingLevel--; - } - if (current === (data.length - 1)) { - if (data.substr(current, 1) === delimiter) { - output.push(data.substr(start, count)); - output.push(''); - return output; - } - else { - count++; - } - } - if (current === (data.length - 1) || (data.substr(current, 1) === delimiter && delimiter === '\t') || (!nestingLevel && data.substr(current, 1) === delimiter)) { - output.push(data.substr(start, count)); - start = current + 1; - count = 0; - } - else { - count++; - } - current++; - } - return output; - }; - UiTools.split = function (data, delimiters) { - var output = []; - var nestingLevel = 0; - var current = 0; - var count = 0; - var start = 0; - while (current < data.length) { - if (current === (data.length - 1)) { - count++; - } - if (current === (data.length - 1) || delimiters.indexOf(data.substr(current, 1)) > -1) { - output.push(data.substr(start, count)); - start = current + 1; - count = 0; - } - else { - count++; - } - current++; - } - return output; - }; - UiTools._beep = function () { - }; - var UiTools$ = { - - }; - - - // wwtlib.Util - - function Util() { - } - Util.splitString = function (target, split) { - var parts = []; - var start = 0; - var end = 0; - for (var i = 0; i < target.length; i++) { - var found = false; - for (var j = 0; j < split.length; j++) { - if (target[i] === split[j]) { - parts.push(target.substring(start, end - start)); - found = true; - continue; - } - start = i + 1; - end = i + 1; - } - if (!found) { - end++; - } - } - if (end > start) { - parts.push(target.substring(start, end - start)); - } - return parts; - }; - Util.stringContains = function (target, chars) { - for (var i = 0; i < chars.length; i++) { - if (target.indexOf(chars[i]) > -1) { - return true; - } - } - return false; - }; - Util.getHashCode = function (target) { - var hash = 0; - if (!target.length) { - return hash; - } - for (var i = 0; i < target.length; i++) { - var c = target.charCodeAt(i); - hash = ((hash << 5) - hash) + c; - } - return hash; - }; - Util.compare = function (l, r) { - if (l === r) { - return 0; - } - if (l > r) { - return 1; - } - return -1; - }; - Util.logN = function (num, b) { - return Math.log(num) / Math.log(b); - }; - Util.parseTimeSpan = function (timespan) { - var val = 0; - var parts = timespan.split(':'); - if (parts.length === 3) { - val += parseInt(parts[0]) * 3600000; - val += parseInt(parts[1]) * 60000; - val += ss.truncate((parseFloat(parts[2]) * 1000)); - } - return val; - }; - Util.xmlDuration = function (duration) { - var s = duration / 1000; - var hours = Math.floor(s / 3600); - var min = Math.floor(s / 60) - (hours * 60); - var sec = s - ((hours * 3600) + min * 60); - return ss.format('{0}:{1}:{2}', hours, min, sec); - }; - Util.xmlDate = function (d) { - var hours = d.getHours(); - var amPm = 'AM'; - if (hours > 12) { - hours -= 12; - amPm = 'PM'; - } - return (d.getMonth() + 1).toString() + '/' + d.getDate().toString() + '/' + d.getFullYear().toString() + ' ' + hours.toString() + ':' + d.getMinutes().toString() + ':' + d.getSeconds().toString() + ' ' + amPm; - }; - Util.selectSingleNode = function (parent, name) { - var node = null; - var $enum1 = ss.enumerate(parent.childNodes); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child.nodeName === name) { - node = child; - break; - } - } - return node; - }; - Util.getInnerText = function (node) { - if (ss.emptyString(node.text)) { - var cn = node; - return cn.textContent; - } - else { - return node.text; - } - }; - Util.getWrappedText = function (ctx, text, width) { - var lines = []; - lines.push(text); - return lines; - }; - Util.toHex = function (number) { - var num = Math.max(0, Math.min(ss.truncate(number), 255)); - return '0123456789ABCDEF'.substr((num - num % 16) / 16, 1) + '0123456789ABCDEF'.substr(num % 16, 1); - }; - Util.fromHex = function (data) { - var val = 0; - switch (data.substr(1, 1).toUpperCase()) { - case 'A': - val += 10; - break; - case 'B': - val += 11; - break; - case 'C': - val += 12; - break; - case 'D': - val += 13; - break; - case 'E': - val += 14; - break; - case 'F': - val += 15; - break; - default: - val += parseInt(data.substr(1, 1)); - break; - } - switch (data.substr(0, 1).toUpperCase()) { - case 'A': - val += 10 * 16; - break; - case 'B': - val += 11 * 16; - break; - case 'C': - val += 12 * 16; - break; - case 'D': - val += 13 * 16; - break; - case 'E': - val += 14 * 16; - break; - case 'F': - val += 15 * 16; - break; - default: - val += parseInt(data.substr(0, 1)) * 16; - break; - } - return val; - }; - Util._openUrl = function (url) { - window.open(url); - }; - Util.log10 = function (num) { - return Math.log(num) / 2.30258509299405; - }; - Util.sign = function (num) { - if (num < 0) { - return -1; - } - return 1; - }; - var Util$ = { - - }; - - - // wwtlib.Rectangle - - function Rectangle() { - this.x = 0; - this.y = 0; - this.width = 0; - this.height = 0; - } - Rectangle.create = function (x, y, width, height) { - var temp = new Rectangle(); - temp.x = x; - temp.y = y; - temp.width = width; - temp.height = height; - return temp; - }; - var Rectangle$ = { - get_left: function () { - return this.x; - }, - get_right: function () { - return this.x + this.width; - }, - get_top: function () { - return this.y; - }, - get_bottom: function () { - return this.y + this.height; - }, - contains: function (point) { - return (this._between(point.x, this.x, this.x + this.width) && this._between(point.y, this.y, this.y + this.height)); - }, - _between: function (n, n1, n2) { - if (n1 > n2) { - return !(n > n1) && !(n < n2); - } - else { - return !(n < n1) && !(n > n2); - } - }, - copy: function () { - var temp = new Rectangle(); - temp.x = this.x; - temp.y = this.y; - temp.width = this.width; - temp.height = this.height; - return temp; - } - }; - - - // wwtlib.Guid - - function Guid() { - this._guid = Guid.create(); - } - Guid.newGuid = function () { - return new Guid(); - }; - Guid.fromString = function (id) { - var temp = new Guid(); - temp._guid = ss.trim(id); - return temp; - }; - Guid.create = function () { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });; - }; - Guid.createFrom = function (value) { - var str = uuid.v5(value, '1420736a-a637-40a7-813a-ba692e72204e'); - return Guid.fromString(str); - }; - var Guid$ = { - toString: function () { - return this._guid; - } - }; - - - // wwtlib.Enums - - function Enums() { - } - Enums.parse = function (enumType, value) { - if (value === 'Default') { - value = 'DefaultV'; - } - if (value === '0') { - return 0; - } - var val = value.substr(0, 1).toLowerCase() + value.substr(1); - return this._wwtlib[enumType][val]; - }; - Enums.toXml = function (enumType, value) { - var x = "0"; var p = Object.keys(this._wwtlib[enumType]); for (var i in p) { - if (this._wwtlib[enumType][p[i]] == value) { - x = p[i]; break; - } - }; - var val = x; - var enumString = val.substr(0, 1).toUpperCase() + val.substr(1); - if (enumString === 'DefaultV') { - enumString = 'Default'; - } - return enumString; - }; - var Enums$ = { - - }; - - - // wwtlib.Mouse - - function Mouse() { - } - Mouse.offsetX = function (canvas, e) { - var x = 0; - var element = canvas; - var me = e; - if (element.offsetParent != null) { - do { - x += element.offsetLeft; - } while ((element = element.offsetParent) != null); - } - return me.pageX - x; - }; - Mouse.offsetY = function (canvas, e) { - var y = 0; - var element = canvas; - var me = e; - if (element.offsetParent != null) { - do { - y += element.offsetTop; - } while ((element = element.offsetParent) != null); - } - return me.pageY - y; - }; - - - // wwtlib.Language - - function Language() { - } - Language.getLocalizedText = function (id, text) { - return text; - }; - var Language$ = { - - }; - - - // wwtlib.Cursor - - function Cursor() { - } - Cursor.get_position = function () { - return new Vector2d(); - }; - Cursor.get_current = function () { - return document.body.style.cursor; - }; - Cursor.set_current = function (value) { - document.body.style.cursor = value; - return value; - }; - var Cursor$ = { - - }; - - - // wwtlib.Cursors - - function Cursors() { - } - Cursors.get_arrow = function () { - return 'default'; - }; - Cursors.get_cross = function () { - return 'crosshair'; - }; - Cursors.get_defaultV = function () { - return 'default'; - }; - Cursors.get_hand = function () { - return 'grab'; - }; - Cursors.get_help = function () { - return 'help'; - }; - Cursors.get_hSplit = function () { - return 'row-resize'; - }; - Cursors.get_iBeam = function () { - return 'text'; - }; - Cursors.get_no = function () { - return 'not-allowed'; - }; - Cursors.get_sizeAll = function () { - return 'help'; - }; - Cursors.get_sizeNESW = function () { - return 'nwse-resize'; - }; - Cursors.get_sizeNS = function () { - return 'ns-resize'; - }; - Cursors.get_sizeNWSE = function () { - return 'nwse-resize'; - }; - Cursors.get_sizeWE = function () { - return 'ew-resize'; - }; - Cursors.get_upArrow = function () { - return 'help'; - }; - Cursors.get_vSplit = function () { - return 'col-resize'; - }; - Cursors.get_waitCursor = function () { - return 'wait'; - }; - var Cursors$ = { - - }; - - - // wwtlib.SelectLink - - function SelectLink(id) { - this._return = false; - this._next = true; - this._linkSlide = false; - this._slide = null; - this._ok = false; - if (id != null) { - this.set_id(id); - } - else { - this.set_next(true); - } - } - var SelectLink$ = { - get_returnCaller: function () { - return this._return; - }, - set_returnCaller: function (value) { - if (value) { - this._slide = 'Return'; - } - this._return = value; - return value; - }, - get_next: function () { - return this._next; - }, - set_next: function (value) { - if (value) { - this._slide = 'Next'; - } - this._next = value; - return value; - }, - get_linkToSlide: function () { - return this._linkSlide; - }, - set_linkToSlide: function (value) { - if (value) { - this._slide = 'Next'; - } - this._linkSlide = value; - return value; - }, - get_id: function () { - return this._slide; - }, - set_id: function (value) { - this._return = false; - this._next = false; - this._linkSlide = true; - this._slide = value; - return value; - }, - get_OK: function () { - return this._ok; - }, - set_OK: function (value) { - this._ok = value; - return value; - } - }; - - - // wwtlib.PopupVolume - - function PopupVolume() { - this.volume = 0; - } - var PopupVolume$ = { - showDialog: function () { - return 1; - } - }; - - - // wwtlib.PopupColorPicker - - function PopupColorPicker() { - this.volume = 0; - this.location = new Vector2d(); - this.color = new Color(); - } - var PopupColorPicker$ = { - showDialog: function () { - return 1; - } - }; - - - // wwtlib.OverlayProperties - - function OverlayProperties() { - this.volume = 0; - this.location = new Vector2d(); - this.overlay = null; - } - var OverlayProperties$ = { - showDialog: function () { - return 1; - } - }; - - - // wwtlib.BinaryReader - - function BinaryReader(arraybuf) { - this.position = 0; - this._data = null; - this._data = arraybuf; - } - var BinaryReader$ = { - get_position: function () { - return this.position; - }, - seek: function (pos) { - this.position = pos; - }, - seekRelative: function (pos) { - this.position += pos; - }, - get_length: function () { - return this._data.length; - }, - get_endOfStream: function () { - return this.position >= this.get_length(); - }, - readByte: function () { - var result; - result = this._data[this.position]; - this.position += 1; - return result; - }, - readSByte: function () { - var result; - result = this._data[this.position]; - this.position += 1; - return result; - }, - readBytes: function (count) { - var buf = new Array(count); - for (var i = 0; i < count; i++) { - buf[i] = this._data[this.position + i]; - } - this.position += count; - return buf; - }, - readRemainingI16: function (i16Remaining) { - var data = new Float32Array(i16Remaining); - for (var i = 0; i < i16Remaining; i++) { - data[i] = this.readInt16(true); - } - return data; - }, - readByteString: function (count) { - var data = ''; - for (var i = 0; i < count; i++) { - data += String.fromCharCode(this._data[this.position + i]); - } - this.position += count; - return data; - }, - readSingle: function () { - var tmp = new Uint8Array(4); - tmp[0] = this._data[this.position]; - tmp[1] = this._data[this.position + 1]; - tmp[2] = this._data[this.position + 2]; - tmp[3] = this._data[this.position + 3]; - var result = new Float32Array(tmp.buffer, 0, 1)[0]; - this.position += 4; - return result; - }, - readUInt32: function () { - var result = (this._data[this.position] + (this._data[this.position + 1] << 8) + (this._data[this.position + 2] << 16) + (this._data[this.position + 3] << 24)); - this.position += 4; - return result; - }, - readUInt16: function () { - var result = (this._data[this.position] + (this._data[this.position + 1] << 8)); - this.position += 2; - return result; - }, - readUInt16LittleEndian: function () { - var result = ((this._data[this.position] << 8) + this._data[this.position + 1]); - this.position += 2; - return result; - }, - readInt16: function (littleEndian) { - var result = (littleEndian) ? this.readUInt16LittleEndian() : this.readUInt16(); - if (!!(result & 32768)) { - return (-((result - 1) ^ 65535)); - } - return result; - }, - readInt32: function () { - var result = this.readUInt32(); - if (!!(result & 2147483648)) { - return (-((result - 1) ^ 4294967295)); - } - return result; - }, - readInt64: function () { - this.position += 8; - return BinaryReader.id++; - }, - close: function () { - } - }; - - - // wwtlib.Bitmap - - function Bitmap() { - this.width = 0; - this.height = 0; - } - Bitmap.create = function (width, height) { - height = Texture.fitPowerOfTwo(height); - width = Texture.fitPowerOfTwo(width); - var bmp = new Bitmap(); - bmp.height = height; - bmp.width = width; - bmp._buffer = new Uint8Array(width * height * 4); - return bmp; - }; - var Bitmap$ = { - setPixel: function (x, y, r, g, b, a) { - var index = (x + y * this.width) * 4; - this._buffer[index++] = r; - this._buffer[index++] = g; - this._buffer[index++] = b; - this._buffer[index++] = a; - }, - getTexture: function () { - var tex = Tile.prepDevice.createTexture(); - Tile.prepDevice.bindTexture(3553, tex); - Tile.prepDevice.texParameteri(3553, 10242, 33071); - Tile.prepDevice.texParameteri(3553, 10243, 33071); - Tile.prepDevice.texImage2D(3553, 0, 6408, this.width, this.height, 0, 6408, 5121, this._buffer); - Tile.prepDevice.texParameteri(3553, 10241, 9985); - Tile.prepDevice.generateMipmap(3553); - Tile.prepDevice.bindTexture(3553, null); - return tex; - } - }; - - - // wwtlib.ColorPicker - - function ColorPicker() { - this.callBack = null; - this.color = Colors.get_white(); - } - var ColorPicker$ = { - nonMenuClick: function (e) { - }, - show: function (e) { - WWTControl.scriptInterface.showColorPicker(this, e); - }, - getColorFromClick: function (e) { - var image = document.getElementById('colorhex'); - var canvas = document.createElement('canvas'); - canvas.width = image.width; - canvas.height = image.height; - var ctx = canvas.getContext('2d'); - ctx.drawImage(image, 0, 0); - var pixels = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data; - this.color = Color.fromArgb(pixels[3], pixels[0], pixels[1], pixels[2]); - return this.color; - }, - pickColor: function (e) { - this.callBack(this.color); - } - }; - - - // wwtlib.ContextMenuStrip - - function ContextMenuStrip() { - this.items = []; - } - var ContextMenuStrip$ = { - _dispose: function () { - }, - _nonMenuClick: function (e) { - var menu = document.getElementById('contextmenu'); - menu.style.display = 'none'; - window.removeEventListener('click', ss.bind('_nonMenuClick', this), false); - var popup = document.getElementById('popoutmenu'); - while (popup.firstChild != null) { - popup.removeChild(popup.firstChild); - } - popup.style.display = 'none'; - }, - _menuItemClicked: function (e) { - var me = e.currentTarget; - me.itemTag.click(me.itemTag, new ss.EventArgs()); - }, - _show: function (position) { - var menu = document.getElementById('contextmenu'); - while (menu.firstChild != null) { - menu.removeChild(menu.firstChild); - } - menu.className = 'contextmenu'; - menu.style.display = 'block'; - menu.style.left = position.x.toString() + 'px'; - menu.style.top = position.y.toString() + 'px'; - window.addEventListener('click', ss.bind('_nonMenuClick', this), true); - var $enum1 = ss.enumerate(this.items); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (item.visible) { - var md = document.createElement('div'); - if (item.dropDownItems.length > 0) { - md.className = 'contextmenuitem submenu'; - } - else { - if (item.checked) { - md.className = 'contextmenuitem checkedmenu'; - } - else { - md.className = 'contextmenuitem'; - } - } - md.innerText = item.name; - var it = md; - it.itemTag = item; - md.addEventListener('mouseover', ss.bind('_openSubMenu', this), false); - if (item.click != null) { - md.addEventListener('click', ss.bind('_menuItemClicked', this), false); - } - menu.appendChild(md); - } - } - }, - _openSubMenu: function (e) { - var me = e.currentTarget; - var child = me.itemTag; - var menu = document.getElementById('popoutmenu'); - while (menu.firstChild != null) { - menu.removeChild(menu.firstChild); - } - menu.style.display = 'none'; - if (!child.dropDownItems.length) { - return; - } - var position = new Vector2d(); - position.x = e.currentTarget.parentNode.offsetLeft + e.currentTarget.parentNode.clientWidth; - position.y = e.currentTarget.parentNode.offsetTop + e.currentTarget.offsetTop; - menu.className = 'contextmenu'; - menu.style.display = 'block'; - menu.style.left = position.x.toString() + 'px'; - menu.style.top = position.y.toString() + 'px'; - window.addEventListener('click', ss.bind('_nonMenuClick', this), true); - var $enum1 = ss.enumerate(child.dropDownItems); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (item.visible) { - var md = document.createElement('div'); - md.className = (item.checked) ? 'contextmenuitem checkedmenu' : 'contextmenuitem'; - md.innerText = item.name; - var it = md; - it.itemTag = item; - md.addEventListener('click', ss.bind('_menuItemClicked', this), false); - menu.appendChild(md); - } - } - } - }; - - - // wwtlib.ToolStripMenuItem - - function ToolStripMenuItem() { - this.tag = null; - this.dropDownItems = []; - this.checked = false; - this.enabled = true; - this.visible = true; - } - ToolStripMenuItem.create = function (name) { - var tsmi = new ToolStripMenuItem(); - tsmi.name = name; - return tsmi; - }; - var ToolStripMenuItem$ = { - - }; - - - // wwtlib.TagMe - - function TagMe() { - } - var TagMe$ = { - - }; - - - // wwtlib.Dialog - - function Dialog() { - } - var Dialog$ = { - add_showDialogHook: function (value) { - this.__showDialogHook = ss.bindAdd(this.__showDialogHook, value); - }, - remove_showDialogHook: function (value) { - this.__showDialogHook = ss.bindSub(this.__showDialogHook, value); - }, - show: function (dialogArgs, e) { - if (this.__showDialogHook != null) { - this.__showDialogHook(dialogArgs, e); - } - } - }; - - - // wwtlib.Histogram - - function Histogram() { - this.image = null; - this.layer = null; - this.tile = null; - this._dropDown = null; - this._downPosition = 0; - this._lowPosition = 0; - this._highPosition = 255; - this._center = 127; - this._ignoreNextClick = false; - this._dragType = 4; - this._updated = false; - this.selectedCurveStyle = 0; - } - Histogram.updateImage = function (isl, z) { - if (!RenderContext.useGlVersion2) { - var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); - var Tile = TileCache.getTile(0, 0, 0, isl.get_imageSet(), null); - Tile.texture2d = image.getBitmap().getTexture(); - } - }; - Histogram.updateScale = function (isl, scale, low, hi) { - isl.get_imageSet().get_fitsProperties().scaleType = scale; - isl.get_imageSet().get_fitsProperties().lowerCut = low; - isl.get_imageSet().get_fitsProperties().upperCut = hi; - if (!RenderContext.useGlVersion2) { - var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); - var Tile = TileCache.getTile(0, 0, 0, isl.get_imageSet(), null); - Tile.texture2d = image.getBitmap().getTexture(); - } - }; - Histogram.updateColorMapper = function (isl, colorMapperName) { - isl.get_imageSet().get_fitsProperties().colorMapName = colorMapperName; - if (!RenderContext.useGlVersion2) { - var image = ss.safeCast(isl.get_imageSet().get_wcsImage(), FitsImageJs); - var Tile = TileCache.getTile(0, 0, 0, isl.get_imageSet(), null); - Tile.texture2d = image.getBitmap().getTexture(); - } - }; - var Histogram$ = { - close: function (e) { - var menu = document.getElementById('histogram'); - var closeBtn = document.getElementById('histogramClose'); - menu.style.display = 'none'; - window.removeEventListener('click', ss.bind('close', this), true); - var image = document.getElementById('graph'); - image.removeEventListener('mousedown', ss.bind('onPointerDown', this), false); - image.removeEventListener('mousemove', ss.bind('onPointerMove', this), false); - image.removeEventListener('mouseup', ss.bind('onPointerUp', this), false); - this._dropDown.removeEventListener('change', ss.bind('curveStyleSelected', this), false); - this._dropDown.removeEventListener('click', ss.bind('ignoreMe', this), true); - }, - show: function (position) { - this.tile = TileCache.getTile(0, 0, 0, this.layer.get_imageSet(), null); - var picker = document.getElementById('histogram'); - var closeBtn = document.getElementById('histogramClose'); - picker.style.display = 'block'; - picker.style.left = position.x.toString() + 'px'; - picker.style.top = position.y.toString() + 'px'; - this.selectedCurveStyle = this.layer.get_imageSet().get_fitsProperties().scaleType; - this._dropDown = document.getElementById('ScaleTypePicker'); - this._dropDown.addEventListener('change', ss.bind('curveStyleSelected', this), false); - this._dropDown.addEventListener('click', ss.bind('ignoreMe', this), true); - var canvas = document.getElementById('graph'); - canvas.addEventListener('pointerdown', ss.bind('onPointerDown', this), false); - canvas.addEventListener('pointermove', ss.bind('onPointerMove', this), false); - canvas.addEventListener('pointerup', ss.bind('onPointerUp', this), false); - closeBtn.addEventListener('click', ss.bind('close', this), true); - this.draw(); - }, - ignoreMe: function (e) { - this._ignoreNextClick = true; - }, - curveStyleSelected: function (e) { - this.selectedCurveStyle = this._dropDown.selectedIndex; - this.setUpdateTimer(); - this.layer.get_imageSet().get_fitsProperties().scaleType = this.selectedCurveStyle; - this.draw(); - this._ignoreNextClick = true; - }, - onPointerDown: function (e) { - var canvas = document.getElementById('graph'); - var x = Mouse.offsetX(canvas, e); - var y = Mouse.offsetY(canvas, e); - canvas.setPointerCapture(e.pointerId); - if ((Math.abs(x - this._center) < 10) && Math.abs(y - 75) < 10) { - this._dragType = 3; - } - else if (Math.abs(x - this._lowPosition) < 10) { - this._dragType = 0; - } - else if (Math.abs(x - this._highPosition) < 10) { - this._dragType = 1; - } - else { - this._dragType = 2; - this._downPosition = Math.min(255, Math.max(0, x)); - this.draw(); - } - e.cancelBubble = true; - }, - onPointerMove: function (e) { - var canvas = document.getElementById('graph'); - var x = Mouse.offsetX(canvas, e); - var y = Mouse.offsetY(canvas, e); - switch (this._dragType) { - case 0: - this._lowPosition = Math.min(255, Math.max(0, x)); - break; - case 1: - this._highPosition = Math.min(255, Math.max(0, x)); - break; - case 2: - this._lowPosition = this._downPosition; - this._highPosition = Math.min(255, Math.max(0, x)); - break; - case 3: - var hWidth = Math.abs(this._highPosition - this._lowPosition) / 2; - var adCenter = Math.min(255 - hWidth, Math.max(hWidth, x)); - var moved = this._center - adCenter; - this._lowPosition -= moved; - this._highPosition -= moved; - break; - case 4: - return; - default: - break; - } - this._center = (this._lowPosition + this._highPosition) / 2; - this.draw(); - var factor = (this.layer.get_imageSet().get_fitsProperties().maxVal - this.layer.get_imageSet().get_fitsProperties().minVal) / 256; - var low = this.layer.get_imageSet().get_fitsProperties().minVal + (this._lowPosition * factor); - var hi = this.layer.get_imageSet().get_fitsProperties().minVal + (this._highPosition * factor); - this.setUpdateTimer(); - this.layer.get_imageSet().get_fitsProperties().upperCut = hi; - this.layer.get_imageSet().get_fitsProperties().lowerCut = low; - this.layer.get_imageSet().get_fitsProperties().scaleType = this.selectedCurveStyle; - e.cancelBubble = true; - }, - onPointerUp: function (e) { - e.srcElement.releasePointerCapture(e.pointerId); - if (this._dragType !== 4) { - this._dragType = 4; - this.setUpdateTimer(); - this._ignoreNextClick = true; - } - e.cancelBubble = true; - }, - setUpdateTimer: function () { - var $this = this; - - if (!RenderContext.useGlVersion2) { - setTimeout(function () { - $this.update(); - }, 500); - this._updated = false; - } - }, - update: function () { - if (this._updated) { - return; - } - if (ss.canCast(this.image, FitsImageJs)) { - var factor = (this.layer.get_imageSet().get_fitsProperties().maxVal - this.layer.get_imageSet().get_fitsProperties().minVal) / 256; - var low = this.layer.get_imageSet().get_fitsProperties().minVal + (this._lowPosition * factor); - var hi = this.layer.get_imageSet().get_fitsProperties().minVal + (this._highPosition * factor); - this.tile.texture2d = (this.image).getScaledBitmap(low, hi, this.selectedCurveStyle, 0, null).getTexture(); - } - this._updated = true; - }, - draw: function () { - var canvas = document.getElementById('graph'); - var ctx = canvas.getContext('2d'); - if (this.image != null) { - this.image.drawHistogram(ctx); - } - var red = 'rgba(255,0,0,255)'; - var green = 'rgba(0,255,0,255)'; - var blue = 'rgba(0,0,255,255)'; - ctx.strokeStyle = red; - ctx.beginPath(); - ctx.moveTo(this._lowPosition, 0); - ctx.lineTo(this._lowPosition, 150); - ctx.stroke(); - ctx.strokeStyle = green; - ctx.beginPath(); - ctx.moveTo(this._highPosition, 0); - ctx.lineTo(this._highPosition, 150); - ctx.stroke(); - ctx.strokeStyle = blue; - ctx.beginPath(); - ctx.arc(this._center, 75, 10, 0, Math.PI * 2, false); - ctx.closePath(); - ctx.stroke(); - var Curve = []; - switch (this.selectedCurveStyle) { - case 0: - Curve.length = 0; - Curve.push(Vector2d.create(this._lowPosition, 150)); - Curve.push(Vector2d.create(this._highPosition, 0)); - break; - case 1: - Curve.length = 0; - var factor = 150 / Math.log(255); - var diff = (this._highPosition - this._lowPosition); - var jump = (diff < 0) ? -1 : 1; - var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); - var val = 1E-06; - for (var i = this._lowPosition; i !== this._highPosition; i += jump) { - Curve.push(Vector2d.create(i, (150 - (Math.log(val) * factor)))); - val += step; - } - break; - case 2: - Curve.length = 0; - var factor = 150 / Math.pow(255, 2); - var diff = (this._highPosition - this._lowPosition); - var jump = (diff < 0) ? -1 : 1; - var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); - var val = 1E-06; - for (var i = this._lowPosition; i !== this._highPosition; i += jump) { - Curve.push(Vector2d.create(i, (150 - (Math.pow(val, 2) * factor)))); - val += step; - } - break; - case 3: - Curve.length = 0; - var factor = 150 / Math.sqrt(255); - var diff = (this._highPosition - this._lowPosition); - var jump = (diff < 0) ? -1 : 1; - var step = Math.abs(256 / ((!diff) ? 1E-06 : diff)); - var val = 1E-06; - for (var i = this._lowPosition; i !== this._highPosition; i += jump) { - Curve.push(Vector2d.create(i, (150 - (Math.sqrt(val) * factor)))); - val += step; - } - break; - } - if (Curve.length > 1) { - ctx.beginPath(); - ctx.strokeStyle = blue; - ctx.moveTo(Curve[0].x, Curve[0].y); - for (var i = 1; i < Curve.length; i++) { - ctx.lineTo(Curve[i].x, Curve[i].y); - } - ctx.stroke(); - } - } - }; - - - // wwtlib.SimpleInput - - function SimpleInput(title, label, text, v3) { - this.title = 'Tile'; - this.label = 'Enter Text Below'; - this.text = ''; - this._textElement = null; - this._ignoreNextClick = false; - this.title = title; - this.label = label; - this.text = text; - } - var SimpleInput$ = { - showDialog: function () { - return 1; - }, - nonMenuClick: function (e) { - if (!this._ignoreNextClick) { - this._close(); - } - this._ignoreNextClick = false; - }, - show: function (position, callback) { - var simpleInputElement = document.getElementById('simpleinput'); - var modalElement = document.getElementById('simplemodal'); - modalElement.style.display = 'block'; - simpleInputElement.style.display = 'block'; - simpleInputElement.style.marginLeft = position.x.toString() + 'px'; - simpleInputElement.style.marginTop = position.y.toString() + 'px'; - this._textElement = document.getElementById('inputtext'); - this._textElement.value = this.text; - var titleDiv = document.getElementById('simpletitle'); - var labelDiv = document.getElementById('inputlabel'); - titleDiv.innerText = this.title; - labelDiv.innerText = this.label; - this._textElement.addEventListener('change', ss.bind('textChanged', this), false); - this._textElement.addEventListener('click', ss.bind('ignoreMe', this), true); - var okButton = document.getElementById('simpleinputok'); - var cancelButton = document.getElementById('simpleinputcancel'); - okButton.addEventListener('click', ss.bind('okClicked', this), false); - cancelButton.addEventListener('click', ss.bind('cancelClicked', this), false); - this._okCallback = callback; - }, - okClicked: function (e) { - this._close(); - if (this._okCallback != null) { - this._okCallback(); - } - }, - cancelClicked: function (e) { - this._close(); - }, - _close: function () { - var simpleInputElement = document.getElementById('simplemodal'); - simpleInputElement.style.display = 'none'; - this._textElement.removeEventListener('change', ss.bind('textChanged', this), false); - var okButton = document.getElementById('simpleinputok'); - var cancelButton = document.getElementById('simpleinputcancel'); - okButton.removeEventListener('click', ss.bind('okClicked', this), false); - cancelButton.removeEventListener('click', ss.bind('cancelClicked', this), false); - }, - ignoreMe: function (e) { - this._ignoreNextClick = true; - }, - textChanged: function (e) { - this.text = this._textElement.value; - this._ignoreNextClick = true; - } - }; - - - // wwtlib.XmlTextWriter - - function XmlTextWriter() { - this.body = "\r\n"; - this.formatting = 1; - this._elementStack = new ss.Stack(); - this._pending = false; - this._currentName = ''; - this._attributes = {}; - this._value = ''; - } - var XmlTextWriter$ = { - _pushNewElement: function (name) { - this._writePending(false); - this._elementStack.push(name); - this._pending = true; - this._currentName = name; - }, - _writePending: function (fullClose) { - var closed = true; - if (this._pending) { - for (var i = 1; i < this._elementStack.count; i++) { - this.body += ' '; - } - this.body += '<' + this._currentName; - if (ss.keyCount(this._attributes) > 0) { - var $enum1 = ss.enumerate(ss.keys(this._attributes)); - while ($enum1.moveNext()) { - var key = $enum1.current; - this.body += ss.format(' {0}="{1}"', key, this._attributes[key]); - } - } - if (!ss.emptyString(this._value)) { - this.body += '>'; - closed = false; - if (!ss.emptyString(this._value)) { - this.body += this._value; - } - } - else { - if (fullClose) { - this.body += ' />\r\n'; - closed = true; - } - else { - this.body += '>\r\n'; - } - } - this._pending = false; - this._currentName = ''; - this._value = ''; - this._attributes = {}; - return closed; - } - return false; - }, - _writeProcessingInstruction: function (v1, v2) { - }, - _writeStartElement: function (name) { - this._pushNewElement(name); - }, - _writeAttributeString: function (key, value) { - if (value != null) { - this._attributes[key] = ss.replaceString(value.toString(), '&', '&'); - } - else { - this._attributes[key] = ''; - } - }, - _writeEndElement: function () { - if (!this._writePending(true)) { - for (var i = 1; i < this._elementStack.count; i++) { - this.body += ' '; - } - this.body += ss.format('\r\n', this._elementStack.pop()); - } - else { - this._elementStack.pop(); - } - }, - _writeString: function (text) { - this._value = ss.replaceString(text, '&', '&'); - }, - _writeFullEndElement: function () { - this._writePending(false); - for (var i = 1; i < this._elementStack.count; i++) { - this.body += ' '; - } - this.body += ss.format('\r\n', this._elementStack.pop()); - }, - _close: function () { - }, - _writeElementString: function (name, value) { - this._writeStartElement(name); - this._writeValue(ss.replaceString(value, '&', '&')); - this._writeEndElement(); - }, - _writeValue: function (val) { - this._value = ss.replaceString(val, '&', '&'); - }, - _writeCData: function (htmlDescription) { - this._value = ss.format('', htmlDescription); - } - }; - - - // wwtlib.VizLayer - - function VizLayer() { - this.table = []; - this.items = []; - this._imageReady = false; - this._dateColumn = 0; - this._latColumn = 1; - this._lngColumn = 2; - this._depthColumn = 3; - this._magColumn = 4; - } - var VizLayer$ = { - load: function (data) { - var $this = this; - - var lines = data.split('\r\n'); - this._starProfile = document.createElement('img'); - this._starProfile.addEventListener('load', function (e) { - $this._imageReady = true; - }, false); - this._starProfile.src = URLHelpers.singleton.engineAssetUrl('StarProfileAlpha.png'); - var gotHeader = false; - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var line = $enum1.current; - if (gotHeader) { - this.table.push(line.split('\t')); - } - else { - this.header = line.split('\t'); - gotHeader = true; - } - } - }, - prepare: function () { - this._worldList = new Array(this.table.length); - this._transformedList = new Array(this.table.length); - var index = 0; - var $enum1 = ss.enumerate(this.table); - while ($enum1.moveNext()) { - var row = $enum1.current; - var item = new DataItem(); - item.eventTime = ss.date(row[this._dateColumn]); - var radius = (6371000 - parseFloat(row[this._depthColumn]) * 1000) / 6371000; - item.location = Coordinates.geoTo3dRad(parseFloat(row[this._latColumn]), parseFloat(row[this._lngColumn]) + 180, radius); - item.tranformed = new Vector3d(); - item.size = Math.pow(2, parseFloat(row[this._magColumn])) / 50; - this._worldList[index] = item.location; - this._transformedList[index] = item.tranformed; - this.items.push(item); - index++; - } - }, - draw: function (renderContext) { - if (!this._imageReady) { - return; - } - renderContext.device.save(); - renderContext.WVP.projectArrayToScreen(this._worldList, this._transformedList); - var ctx = renderContext.device; - ctx.globalAlpha = 0.4; - var width = renderContext.width; - var height = renderContext.height; - var viewPoint = Vector3d.makeCopy(renderContext.get_viewPoint()); - var scaleFactor = renderContext.get_fovScale() / 100; - var $enum1 = ss.enumerate(this.items); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (item.tranformed.z < 1) { - var x = item.tranformed.x; - var y = item.tranformed.y; - var size = 4 * item.size / scaleFactor; - var half = size / 2; - if (x > -half && x < width + half && y > -half && y < height + half) { - ctx.drawImage(this._starProfile, x - size / 2, y - size / 2, size, size); - } - } - } - renderContext.device.restore(); - } - }; - - - // wwtlib.DataItem - - function DataItem() { - this.size = 0; - } - var DataItem$ = { - getColor: function () { - return 'Red'; - } - }; - - - // wwtlib.WebFile - - function WebFile(url) { - this._state = 0; - this.responseType = ''; - this._triedOnce = false; - this._url = url; - } - var WebFile$ = { - send: function () { - if (typeof navigator === "undefined") { return; }; - var version = navigator.appVersion; - if (version.indexOf('MSIE 8') > -1 || version.indexOf('MSIE 9') > -1) { - this._ieCrossDomain(); - } - else { - this._CORS(); - } - this.set_state(0); - }, - get_message: function () { - return this._message; - }, - get_state: function () { - return this._state; - }, - set_state: function (value) { - this._state = value; - if (this.onStateChange != null) { - this.onStateChange(); - } - return value; - }, - _loadData: function (textReceived) { - this._data = textReceived; - this.set_state(1); - }, - _loadBlob: function (blob) { - this._blobdata = blob; - this.set_state(1); - }, - _error: function () { - this._message = ss.format('Error encountered loading {0}', this._url); - this.set_state(2); - }, - _timeOut: function () { - this._message = ss.format('Timeout encountered loading {0}', this._url); - this.set_state(2); - }, - _ieCrossDomain: function () { - var $this = this; - - this._xdr = new XDomainRequest(); - this._xdr.onload = function () { - $this._loadData($this._xdr.responseText); - }; - this._xdr.onTimeout = ss.bind('_error', this); - this._xdr.onError = ss.bind('_timeOut', this); - this._xdr.open('get', this._url); - this._xdr.send(); - }, - _CORS: function () { - var $this = this; - - this._xhr = new XMLHttpRequest(); - try { - this._xhr.open('GET', this._url); - if (this.responseType != null) { - this._xhr.responseType = this.responseType; - } - this._xhr.onreadystatechange = function () { - if ($this._xhr.readyState === 4) { - if (!$this._xhr.status) { - if (!$this._triedOnce) { - $this._triedOnce = true; - $this._xhr.onreadystatechange = null; - var new_url = URLHelpers.singleton.activateProxy($this._url); - if (new_url != null) { - $this._url = new_url; - $this._CORS(); - } - else { - $this._message = $this._xhr.statusText; - $this.set_state(2); - } - } - } - else { - if ($this._xhr.status >= 400) { - $this._message = $this._xhr.statusText; - $this.set_state(2); - } - else { - if (!$this.responseType) { - $this._loadData($this._xhr.responseText); - } - else { - $this._loadBlob($this._xhr.response); - } - } - } - } - }; - this._xhr.send(); - } - catch (err) { - this._message = err.message; - this.set_state(2); - throw err; - } - }, - getText: function () { - return this._data; - }, - getBlob: function () { - return this._blobdata; - }, - getXml: function () { - var xParser = new DOMParser(); - return xParser.parseFromString(this._data, 'text/xml'); - } - }; - - - // wwtlib.FolderDownloadAction - - function FolderDownloadAction(action, loadChildFolders) { - this.loadChildFolders = false; - this._numLoadingFolders = 0; - this._onComplete = action; - this.loadChildFolders = loadChildFolders; - } - var FolderDownloadAction$ = { - _folderLoaded: function () { - this._numLoadingFolders--; - if (!this._numLoadingFolders) { - this._onComplete(); - } - }, - startingNewFolderLoad: function (folder) { - var $this = this; - - this._numLoadingFolders++; - folder.childLoadCallback(function () { - Wtml.loadImagesets(folder, $this); - $this._folderLoaded(); - }); - } - }; - - - // wwtlib.Wtml - - function Wtml() { - } - Wtml.getWtmlFile = function (url, complete, loadChildFolders) { - if (loadChildFolders == null) { - loadChildFolders = false; - } - var folder = new Folder(); - folder.set_url(url); - var folderDownloadAction = new FolderDownloadAction(complete, loadChildFolders); - folderDownloadAction.startingNewFolderLoad(folder); - return folder; - }; - Wtml.loadImagesets = function (folder, folderDownloadAction) { - var children = folder.get_children(); - var $enum1 = ss.enumerate(children); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (ss.canCast(child, Imageset)) { - var imageSet = child; - WWTControl.addImageSetToRepository(imageSet); - } - if (ss.canCast(child, Place)) { - var place = child; - if (place.get_studyImageset() != null) { - WWTControl.addImageSetToRepository(place.get_studyImageset()); - } - if (place.get_backgroundImageset() != null) { - WWTControl.addImageSetToRepository(place.get_backgroundImageset()); - } - } - if (ss.canCast(child, Folder) && folderDownloadAction.loadChildFolders) { - folderDownloadAction.startingNewFolderLoad((child)); - } - } - if (!ss.emptyString(WWTControl.imageSetName)) { - var name = WWTControl.imageSetName.toLowerCase(); - var $enum2 = ss.enumerate(WWTControl.getImageSets()); - while ($enum2.moveNext()) { - var imageset = $enum2.current; - if (imageset.get_name().toLowerCase() === name) { - WWTControl.singleton.renderContext.set_backgroundImageset(imageset); - } - } - } - }; - var Wtml$ = { - - }; - - - // wwtlib.WWTControl - - function WWTControl() { - this.freestandingMode = false; - this.uiController = null; - this._annotations = []; - this._hoverText = ''; - this._hoverTextPoint = new Vector2d(); - this._lastMouseMove = new Date(1900, 1, 0, 0, 0, 0, 0); - this.layers = []; - this._frameCount = 0; - this._zoomMax = 360; - this._zoomMaxSolarSystem = 10000000000000000; - this._zoomMin = 0.001373291015625; - this._zoomMinSolarSystem = 1E-08; - this.constellation = 'UMA'; - this._fadePoints = null; - this.fader = BlendState.create(true, 2000); - this._crossFadeFrame = false; - this._crossFadeTexture = null; - this._sprite = new Sprite2d(); - this.renderType = 2; - this._milkyWayBackground = null; - this.capturingVideo = false; - this._videoBlobReady = null; - this.dumpFrameParams = null; - this._videoBlobQueue = {}; - this._videoQueueIndex = 0; - this._emptyFrames = []; - this._beginZoom = 1; - this._dragging = false; - this._mouseDown = false; - this._hasTwoTouches = false; - this._lastX = 0; - this._lastY = 0; - this._pointerIds = new Array(2); - this._pinchingZoomRect = new Array(2); - this._moved = false; - this._foregroundCanvas = null; - this._fgDevice = null; - this._tracking = false; - this._trackingObject = null; - this.sandboxMode = false; - this._solarSystemTrack = 65536; - this._moving = false; - this._targetStudyImageset = null; - this._targetBackgroundImageset = null; - this.tour = null; - this.tourEdit = null; - this._crossHairs = null; - } - WWTControl.addImageSetToRepository = function (imagesetToAdd) { - var $enum1 = ss.enumerate(WWTControl.imageSets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_imageSetID() === imagesetToAdd.get_imageSetID()) { - return imageset; - } - } - WWTControl.imageSets.push(imagesetToAdd); - return imagesetToAdd; - }; - WWTControl.getImageSets = function () { - return WWTControl.imageSets; - }; - WWTControl.get_renderNeeded = function () { - return WWTControl._renderNeeded; - }; - WWTControl.set_renderNeeded = function (value) { - WWTControl._renderNeeded = true; - return value; - }; - WWTControl.initControl = function (DivId) { - return WWTControl.initControl2(DivId, true); - }; - WWTControl.initControlParam = function (DivId, webgl_ignored) { - return WWTControl.initControl2(DivId, true); - }; - WWTControl.initControl2 = function (DivId, startRenderLoop) { - return WWTControl.initControl6(DivId, startRenderLoop, 0, 0, 360, 'Sky'); - }; - WWTControl.initControl6 = function (DivId, startRenderLoop, startLat, startLng, startZoom, startMode) { - if (WWTControl.singleton.renderContext.device == null) { - WWTControl.scriptInterface = new ScriptInterface(); - WWTControl.scriptInterface.settings = Settings.get_current(); - var canvas = WWTControl._createCanvasElement(DivId); - var gl = canvas.getContext('webgl2'); - if (gl != null) { - RenderContext.useGlVersion2 = true; - } - else { - console.warn('This browser does not support WebGL 2.0. Some features will work suboptimally. To get the full AAS WWT experience, consider using the latest version of Chrome, Firefox or Edge. In case you would like to use Safari, we recommend that you enable WebGL 2.0'); - gl = canvas.getContext('webgl'); - } - if (gl == null) { - gl = canvas.getContext('experimental-webgl'); - } - if (gl == null) { - var ctx = canvas.getContext('2d'); - WWTControl.singleton.renderContext.device = ctx; - } - else { - Tile.prepDevice = gl; - WWTControl.singleton.renderContext.gl = gl; - RenderContext.useGl = true; - } - WWTControl.singleton.canvas = canvas; - WWTControl.singleton.renderContext.width = canvas.width; - WWTControl.singleton.renderContext.height = canvas.height; - WWTControl.singleton.setup(canvas, startLat, startLng, startZoom); - Constellations.initializeConstellations(); - LayerManager.oneTimeInitialization(); - if (startMode === 'earth') { - WWTControl.singleton.renderContext.set_backgroundImageset(Imageset.create('Blue Marble', URLHelpers.singleton.coreStaticUrl('wwtweb/tiles.aspx?q={1},{2},{3},bm200407'), 0, 3, 3, 101, 0, 7, 256, 180, '.png', false, '', 0, 0, 0, false, URLHelpers.singleton.coreStaticUrl('wwtweb/thumbnail.aspx?name=bm200407'), true, false, 0, 0, 0, '', '', '', '', 6371000, 'Earth')); - } - else if (startMode === 'black') { - WWTControl.singleton.renderContext.set_backgroundImageset(Imageset.create('Black Sky Background', '', 2, 3, 3, 102, 0, 0, 256, 180, '.png', false, '0123', 0, 0, 0, false, '', false, false, 2, 0, 0, '', '', '', '', 1, 'Sky')); - } - else { - WWTControl.singleton.renderContext.set_backgroundImageset(Imageset.create('DSS', URLHelpers.singleton.coreStaticUrl('wwtweb/dss.aspx?q={1},{2},{3}'), 2, 3, 3, 100, 0, 12, 256, 180, '.png', false, '', 0, 0, 0, false, URLHelpers.singleton.coreStaticUrl('thumbnails/DSS.png'), true, false, 0, 0, 0, '', '', '', '', 1, 'Sky')); - } - } - WWTControl.singleton.renderContext.viewCamera.lng += 0; - WWTControl.singleton.renderContext._initGL(); - if (startRenderLoop) { - WWTControl.singleton.render(); - } - return WWTControl.scriptInterface; - }; - WWTControl._createCanvasElement = function (DivId) { - var div = document.getElementById(DivId); - var canvas = document.createElement('canvas'); - canvas.height = div.clientHeight; - canvas.width = div.clientWidth; - div.appendChild(canvas); - return canvas; - }; - WWTControl.useUserLocation = function () { - navigator.geolocation.getCurrentPosition(WWTControl._getLocation, WWTControl._getLocationError); - }; - WWTControl._getLocation = function (pos) { - if (!!pos.coords.latitude) { - Settings.get_globalSettings().set_locationLat(pos.coords.latitude); - } - if (!!pos.coords.longitude) { - Settings.get_globalSettings().set_locationLng(pos.coords.longitude); - } - if (!!pos.coords.altitude) { - Settings.get_globalSettings().set_locationAltitude(pos.coords.altitude); - } - }; - WWTControl._getLocationError = function (pos) { - if (pos != null && pos.coords != null) { - var lat = pos.coords.latitude; - var lng = pos.coords.longitude; - } - }; - WWTControl.setBackgroundImageName = function (name) { - WWTControl.imageSetName = name; - }; - WWTControl.setForegroundImageName = function (name) { - WWTControl.imageSetName = name; - }; - WWTControl.showLayers = function (show) { - WWTControl.showDataLayers = show; - }; - var WWTControl$ = { - _addAnnotation: function (annotation) { - this._annotations.push(annotation); - Annotation.batchDirty = true; - }, - _removeAnnotation: function (annotation) { - ss.remove(this._annotations, annotation); - Annotation.batchDirty = true; - }, - _clearAnnotations: function () { - this._annotations.length = 0; - Annotation.batchDirty = true; - }, - _annotationclicked: function (ra, dec, x, y) { - if (this._annotations != null && this._annotations.length > 0) { - var index = 0; - var $enum1 = ss.enumerate(this._annotations); - while ($enum1.moveNext()) { - var note = $enum1.current; - if (note.hitTest(this.renderContext, ra, dec, x, y)) { - WWTControl.scriptInterface._fireAnnotationclicked(ra, dec, note.get_id()); - return true; - } - index++; - } - } - return false; - }, - _annotationHover: function (ra, dec, x, y) { - if (this._annotations != null && this._annotations.length > 0) { - var index = 0; - var $enum1 = ss.enumerate(this._annotations); - while ($enum1.moveNext()) { - var note = $enum1.current; - if (note.hitTest(this.renderContext, ra, dec, x, y)) { - this._hoverText = note.get_label(); - this._hoverTextPoint = Vector2d.create(x, y); - return true; - } - index++; - } - } - return false; - }, - get_zoomMax: function () { - if (this.renderContext.get_backgroundImageset() != null && this.renderContext.get_backgroundImageset().get_dataSetType() === 4) { - return this._zoomMaxSolarSystem; - } - else { - return this._zoomMax; - } - }, - set_zoomMax: function (value) { - this._zoomMax = value; - return value; - }, - setSolarSystemMaxZoom: function (value) { - this._zoomMaxSolarSystem = value; - }, - get_zoomMin: function () { - if (this.renderContext.get_backgroundImageset() != null && this.renderContext.get_backgroundImageset().get_dataSetType() === 4) { - return this._zoomMinSolarSystem; - } - else { - return this._zoomMin; - } - }, - set_zoomMin: function (value) { - this._zoomMin = value; - return value; - }, - setSolarSystemMinZoom: function (value) { - this._zoomMinSolarSystem = value; - }, - _notifyMoveComplete: function () { - }, - get_crossFadeFrame: function () { - return this._crossFadeFrame; - }, - set_crossFadeFrame: function (value) { - if (value && this._crossFadeFrame !== value) { - if (this._crossFadeTexture != null) { - } - this._crossFadeTexture = this.renderContext._getScreenTexture(); - } - this._crossFadeFrame = value; - if (!value) { - if (this._crossFadeTexture != null) { - this._crossFadeTexture = null; - } - } - return value; - }, - _fadeFrame: function () { - if (this.renderContext.gl != null) { - var sp = Settings.get_active().getSetting(17); - if ((sp.opacity > 0)) { - var color = Color._fromArgbColor(255 - UiTools.gamma(255 - ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_black()); - if (!(sp.opacity > 0)) { - color = Color._fromArgbColor(255 - UiTools.gamma(255 - ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_black()); - } - if (this._crossFadeFrame) { - color = Color._fromArgbColor(UiTools.gamma(ss.truncate((sp.opacity * 255)), 1 / 2.2), Colors.get_white()); - } - else { - if (this._crossFadeTexture != null) { - this._crossFadeTexture = null; - } - } - if (this._fadePoints == null) { - this._fadePoints = new Array(4); - for (var i = 0; i < 4; i++) { - this._fadePoints[i] = new PositionColoredTextured(); - } - } - this._fadePoints[0].position.x = -this.renderContext.width / 2; - this._fadePoints[0].position.y = this.renderContext.height / 2; - this._fadePoints[0].position.z = 1347; - this._fadePoints[0].tu = 0; - this._fadePoints[0].tv = 1; - this._fadePoints[0].color = color; - this._fadePoints[1].position.x = -this.renderContext.width / 2; - this._fadePoints[1].position.y = -this.renderContext.height / 2; - this._fadePoints[1].position.z = 1347; - this._fadePoints[1].tu = 0; - this._fadePoints[1].tv = 0; - this._fadePoints[1].color = color; - this._fadePoints[2].position.x = this.renderContext.width / 2; - this._fadePoints[2].position.y = this.renderContext.height / 2; - this._fadePoints[2].position.z = 1347; - this._fadePoints[2].tu = 1; - this._fadePoints[2].tv = 1; - this._fadePoints[2].color = color; - this._fadePoints[3].position.x = this.renderContext.width / 2; - this._fadePoints[3].position.y = -this.renderContext.height / 2; - this._fadePoints[3].position.z = 1347; - this._fadePoints[3].tu = 1; - this._fadePoints[3].tv = 0; - this._fadePoints[3].color = color; - this._sprite.draw(this.renderContext, this._fadePoints, 4, this._crossFadeTexture, true, 1); - } - } - }, - captureVideo: function (VideoBlobReady, Width, Height, FramesPerSecond, TotalFrames, Format) { - this.capturingVideo = true; - this._videoBlobReady = VideoBlobReady; - ss.clearKeys(this._videoBlobQueue); - this._videoQueueIndex = 0; - this._emptyFrames.length = 0; - this.dumpFrameParams = new VideoOutputType(Width, Height, FramesPerSecond, Format, true); - SpaceTimeController.frameDumping = true; - SpaceTimeController.framesPerSecond = FramesPerSecond; - SpaceTimeController.totalFrames = TotalFrames; - SpaceTimeController.currentFrameNumber = 0; - }, - render: function () { - var $this = this; - - this.renderOneFrame(); - setTimeout(function () { - $this.render(); - }, 10); - }, - renderOneFrame: function () { - if (this.renderContext.get_backgroundImageset() != null) { - this.renderType = this.renderContext.get_backgroundImageset().get_dataSetType(); - } - else { - this.renderType = 2; - } - var sizeChange = false; - if (this.canvas.width !== this.canvas.parentNode.clientWidth) { - this.canvas.width = this.canvas.parentNode.clientWidth; - sizeChange = true; - } - if (this.canvas.height !== this.canvas.parentNode.clientHeight) { - this.canvas.height = this.canvas.parentNode.clientHeight; - sizeChange = true; - } - if (sizeChange && this.explorer != null) { - this.explorer.refresh(); - } - if (this.canvas.width < 1 || this.canvas.height < 1) { - return; - } - if (sizeChange) { - this._crossHairs = null; - } - Tile.lastDeepestLevel = Tile.deepestLevel; - RenderTriangle.width = this.renderContext.width = this.canvas.width; - RenderTriangle.height = this.renderContext.height = this.canvas.height; - Tile.tilesInView = 0; - Tile.tilesTouched = 0; - Tile.deepestLevel = 0; - SpaceTimeController.set_metaNow(ss.now()); - if (this.get__mover() != null) { - SpaceTimeController.set_now(this.get__mover().get_currentDateTime()); - Planets.updatePlanetLocations(this.get_solarSystemMode()); - if (this.get__mover() != null) { - var newCam = this.get__mover().get_currentPosition(); - this.renderContext.targetCamera = newCam.copy(); - this.renderContext.viewCamera = newCam.copy(); - if (this.renderContext.space && Settings.get_active().get_galacticMode()) { - var gPoint = Coordinates.j2000toGalactic(newCam.get_RA() * 15, newCam.get_dec()); - this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; - this.renderContext.targetAz = this.renderContext.az = gPoint[0]; - } - else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { - var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(newCam.get_RA(), newCam.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); - this.renderContext.targetAlt = this.renderContext.alt = currentAltAz.get_alt(); - this.renderContext.targetAz = this.renderContext.az = currentAltAz.get_az(); - } - if (this.get__mover().get_complete()) { - WWTControl.scriptInterface._fireArrived(this.get__mover().get_currentPosition().get_RA(), this.get__mover().get_currentPosition().get_dec(), WWTControl.singleton.renderContext.viewCamera.zoom); - this.set__mover(null); - this._notifyMoveComplete(); - } - } - } - else { - SpaceTimeController.updateClock(); - Planets.updatePlanetLocations(this.get_solarSystemMode()); - this._updateViewParameters(); - } - this.renderContext.clear(); - if (this.renderType === 4) { - if (this._solarSystemTrack < 20) { - var radius = Planets.getAdjustedPlanetRadius(this._solarSystemTrack); - var distance = this.renderContext.get_solarSystemCameraDistance(); - var camAngle = this.renderContext.get_fovLocal(); - } - if (this._trackingObject == null) { - } - this.renderContext.setupMatricesSolarSystem(true); - var zoom = this.renderContext.viewCamera.zoom; - var milkyWayBlend = Math.min(1, Math.max(0, (Math.log(zoom) - 8.4)) / 4.2); - var milkyWayBlendIn = Math.min(1, Math.max(0, (Math.log(zoom) - 17.9)) / 2.3); - var matOldMW = this.renderContext.get_world(); - var matLocalMW = this.renderContext.get_world().clone(); - matLocalMW._multiply(Matrix3d._scaling(100000, 100000, 100000)); - matLocalMW._multiply(Matrix3d._rotationX(23.5 / 180 * Math.PI)); - matLocalMW._multiply(Matrix3d.translation(this.renderContext.cameraPosition)); - this.renderContext.set_world(matLocalMW); - this.renderContext.set_worldBase(matLocalMW); - this.renderContext.space = true; - this.renderContext.makeFrustum(); - var lighting = this.renderContext.lighting; - this.renderContext.lighting = false; - if (Settings.get_active().get_solarSystemMilkyWay()) { - if (milkyWayBlend < 1) { - if (this._milkyWayBackground == null) { - this._milkyWayBackground = this.getImagesetByName('Digitized Sky Survey (Color)'); - } - if (this._milkyWayBackground != null) { - RenderTriangle.cullInside = true; - var c = (1 - milkyWayBlend) / 2; - this.renderContext.drawImageSet(this._milkyWayBackground, c * 100); - RenderTriangle.cullInside = false; - } - } - } - this._drawSkyOverlays(); - this.renderContext.lighting = lighting; - this.renderContext.space = false; - this.renderContext.set_world(matOldMW); - this.renderContext.set_worldBase(matOldMW); - this.renderContext.makeFrustum(); - var oldCamera = this.renderContext.cameraPosition; - var matOld = this.renderContext.get_world(); - var matLocal = this.renderContext.get_world(); - matLocal._multiply(Matrix3d.translation(this.renderContext.viewCamera.viewTarget)); - this.renderContext.cameraPosition = Vector3d.subtractVectors(this.renderContext.cameraPosition, this.renderContext.viewCamera.viewTarget); - this.renderContext.set_world(matLocal); - this.renderContext.makeFrustum(); - if (Settings.get_active().get_solarSystemCosmos()) { - Grids.drawCosmos3D(this.renderContext, 1); - } - if (Settings.get_active().get_solarSystemMilkyWay() && milkyWayBlendIn > 0) { - Grids.drawGalaxyImage(this.renderContext, milkyWayBlendIn); - } - if (Settings.get_active().get_solarSystemStars()) { - Grids.drawStars3D(this.renderContext, 1); - } - matLocal = matOld; - var pnt = this.renderContext.viewCamera.viewTarget; - var vt = Vector3d.create(-pnt.x, -pnt.y, -pnt.z); - this.renderContext.cameraPosition = oldCamera; - matLocal._multiply(Matrix3d.translation(vt)); - this.renderContext.set_world(matLocal); - this.renderContext.makeFrustum(); - LayerManager._draw(this.renderContext, 1, true, 'Sky', true, false); - this.renderContext.set_world(matOld); - this.renderContext.makeFrustum(); - if (this.renderContext.get_solarSystemCameraDistance() < 15000) { - this.renderContext.setupMatricesSolarSystem(false); - if (Settings.get_active().get_solarSystemMinorPlanets()) { - MinorPlanets.drawMPC3D(this.renderContext, 1, this.renderContext.viewCamera.viewTarget); - } - if (Settings.get_active().get_solarSystemPlanets()) { - Planets.drawPlanets3D(this.renderContext, 1, this.renderContext.viewCamera.viewTarget); - } - } - } - else { - if (!this.renderType || this.renderType === 1) { - this.renderContext._setupMatricesLand3d(); - } - else { - this.renderContext.setupMatricesSpace3d(this.renderContext.width, this.renderContext.height); - } - this.renderContext.drawImageSet(this.renderContext.get_backgroundImageset(), 100); - if (this.renderContext.get_foregroundImageset() != null) { - if (this.renderContext.get_foregroundImageset().get_dataSetType() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { - this.renderContext.set_foregroundImageset(null); - } - else { - if (this.renderContext.viewCamera.opacity !== 100 && this.renderContext.gl == null) { - if (this._foregroundCanvas.width !== this.renderContext.width || this._foregroundCanvas.height !== this.renderContext.height) { - this._foregroundCanvas.width = ss.truncate(this.renderContext.width); - this._foregroundCanvas.height = ss.truncate(this.renderContext.height); - } - var saveDevice = this.renderContext.device; - this._fgDevice.clearRect(0, 0, this.renderContext.width, this.renderContext.height); - this.renderContext.device = this._fgDevice; - this.renderContext.drawImageSet(this.renderContext.get_foregroundImageset(), 100); - this.renderContext.device = saveDevice; - this.renderContext.device.save(); - this.renderContext.device.globalAlpha = this.renderContext.viewCamera.opacity / 100; - this.renderContext.device.drawImage(this._foregroundCanvas, 0, 0); - this.renderContext.device.restore(); - } - else { - this.renderContext.drawImageSet(this.renderContext.get_foregroundImageset(), this.renderContext.viewCamera.opacity); - } - } - } - if (this.renderType === 2) { - var $enum1 = ss.enumerate(this.renderContext.get_catalogHipsImagesets()); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_hipsProperties().get_catalogSpreadSheetLayer().enabled && imageset.get_hipsProperties().get_catalogSpreadSheetLayer().lastVersion === imageset.get_hipsProperties().get_catalogSpreadSheetLayer().get_version()) { - this.renderContext.drawImageSet(imageset, 100); - } - } - } - if (this.renderType === 2 && Settings.get_active().get_showSolarSystem()) { - Planets.drawPlanets(this.renderContext, 1); - this.constellation = Constellations.containment.findConstellationForPoint(this.renderContext.viewCamera.get_RA(), this.renderContext.viewCamera.get_dec()); - this._drawSkyOverlays(); - } - if (this.get_planetLike() || this.get_space()) { - if (!this.get_space()) { - var angle = Coordinates.mstFromUTC2(SpaceTimeController.get_now(), 0) / 180 * Math.PI; - this.renderContext.set_worldBaseNonRotating(Matrix3d.multiplyMatrix(Matrix3d._rotationY(angle), this.renderContext.get_worldBase())); - if (this._targetBackgroundImageset != null) { - this.renderContext.set_nominalRadius(this._targetBackgroundImageset.get_meanRadius()); - } - } - else { - this.renderContext.set_worldBaseNonRotating(this.renderContext.get_world()); - if (this._targetBackgroundImageset != null) { - this.renderContext.set_nominalRadius(this._targetBackgroundImageset.get_meanRadius()); - } - } - var referenceFrame = this.getCurrentReferenceFrame(); - LayerManager._draw(this.renderContext, 1, this.get_space(), referenceFrame, true, this.get_space()); - } - } - var worldSave = this.renderContext.get_world(); - var viewSave = this.renderContext.get_view(); - var projSave = this.renderContext.get_projection(); - if (Settings.get_current().get_showCrosshairs()) { - this._drawCrosshairs(this.renderContext); - } - if (this.uiController != null) { - this.uiController.render(this.renderContext); - } - else { - var index = 0; - Annotation.prepBatch(this.renderContext); - var $enum2 = ss.enumerate(this._annotations); - while ($enum2.moveNext()) { - var item = $enum2.current; - item.draw(this.renderContext); - index++; - } - Annotation.drawBatch(this.renderContext); - if ((ss.now() - this._lastMouseMove) > 400) { - var raDecDown = this.getCoordinatesForScreenPoint(this._hoverTextPoint.x, this._hoverTextPoint.y); - this._annotationHover(raDecDown.x, raDecDown.y, this._hoverTextPoint.x, this._hoverTextPoint.y); - this._lastMouseMove = new Date(2100, 1, 1); - } - if (!ss.emptyString(this._hoverText)) { - this._drawHoverText(this.renderContext); - } - } - var tilesAllLoaded = !TileCache.get_queueCount(); - this.renderContext.setupMatricesOverlays(); - this._fadeFrame(); - this._frameCount++; - TileCache.decimateQueue(); - TileCache.processQueue(this.renderContext); - Tile.currentRenderGeneration++; - if (!TourPlayer.get_playing()) { - this.set_crossFadeFrame(false); - } - this.renderContext.set_world(worldSave); - this.renderContext.set_view(viewSave); - this.renderContext.set_projection(projSave); - var now = ss.now(); - var ms = now - this._lastUpdate; - if (ms > 1000) { - this._lastUpdate = now; - this._frameCount = 0; - RenderTriangle.trianglesRendered = 0; - RenderTriangle.trianglesCulled = 0; - } - if (this.capturingVideo) { - if ((this.dumpFrameParams != null) && (!this.dumpFrameParams.waitDownload || tilesAllLoaded)) { - this.captureFrameForVideo(this._videoBlobReady, this.dumpFrameParams.width, this.dumpFrameParams.height, this.dumpFrameParams.format); - SpaceTimeController.nextFrame(); - } - if (SpaceTimeController.get_doneDumping()) { - SpaceTimeController.frameDumping = false; - SpaceTimeController.cancelFrameDump = false; - this.capturingVideo = false; - } - } - }, - getCurrentReferenceFrame: function () { - if (this.renderContext.get_backgroundImageset() == null) { - return 'Sun'; - } - if (!ss.emptyString(this.renderContext.get_backgroundImageset().get_referenceFrame())) { - return this.renderContext.get_backgroundImageset().get_referenceFrame(); - } - if (!this.renderContext.get_backgroundImageset().get_dataSetType()) { - return 'Earth'; - } - if (this.renderContext.get_backgroundImageset().get_name() === 'Visible Imagery' && this.renderContext.get_backgroundImageset().get_url().toLowerCase().indexOf('mars') > -1) { - this.renderContext.get_backgroundImageset().set_referenceFrame('Mars'); - return this.renderContext.get_backgroundImageset().get_referenceFrame(); - } - if (this.renderContext.get_backgroundImageset().get_dataSetType() === 1) { - var $enum1 = ss.enumerate(WWTControl.solarSystemObjectsNames); - while ($enum1.moveNext()) { - var name = $enum1.current; - if (this.renderContext.get_backgroundImageset().get_name().toLowerCase().indexOf(name.toLowerCase()) > -1) { - this.renderContext.get_backgroundImageset().set_referenceFrame(name); - return name; - } - } - } - if (this.renderContext.get_backgroundImageset().get_dataSetType() === 2) { - return 'Sky'; - } - return ''; - }, - get_planetLike: function () { - if (this.renderContext.get_backgroundImageset() != null) { - return !this.renderContext.get_backgroundImageset().get_dataSetType() || this.renderContext.get_backgroundImageset().get_dataSetType() === 1; - } - else { - return true; - } - }, - get_space: function () { - if (this.renderContext.get_backgroundImageset() != null) { - return this.renderContext.get_backgroundImageset().get_dataSetType() === 2; - } - else { - return true; - } - }, - _drawSkyOverlays: function () { - if (Settings.get_active().get_showConstellationPictures() && !this.freestandingMode) { - Constellations.drawArtwork(this.renderContext); - } - if (Settings.get_active().get_showConstellationFigures()) { - if (WWTControl.constellationsFigures == null) { - WWTControl.constellationsFigures = Constellations.create('Constellations', URLHelpers.singleton.engineAssetUrl('figures.txt'), false, false, false); - } - WWTControl.constellationsFigures.draw(this.renderContext, false, 'UMA', false); - } - if (Settings.get_active().get_showEclipticGrid()) { - Grids.drawEclipticGrid(this.renderContext, 1, Settings.get_active().get_eclipticGridColor()); - if (Settings.get_active().get_showEclipticGridText()) { - Grids.drawEclipticGridText(this.renderContext, 1, Settings.get_active().get_eclipticGridColor()); - } - } - if (Settings.get_active().get_showGalacticGrid()) { - Grids.drawGalacticGrid(this.renderContext, 1, Settings.get_active().get_galacticGridColor()); - if (Settings.get_active().get_showGalacticGridText()) { - Grids.drawGalacticGridText(this.renderContext, 1, Settings.get_active().get_galacticGridColor()); - } - } - if (Settings.get_active().get_showAltAzGrid()) { - Grids.drawAltAzGrid(this.renderContext, 1, Settings.get_active().get_altAzGridColor()); - if (Settings.get_active().get_showAltAzGridText()) { - Grids.drawAltAzGridText(this.renderContext, 1, Settings.get_active().get_altAzGridColor()); - } - } - if (Settings.get_active().get_showPrecessionChart()) { - Grids.drawPrecessionChart(this.renderContext, 1, Settings.get_active().get_precessionChartColor()); - } - if (Settings.get_active().get_showEcliptic()) { - Grids.drawEcliptic(this.renderContext, 1, Settings.get_active().get_eclipticColor()); - if (Settings.get_active().get_showEclipticOverviewText()) { - Grids.drawEclipticText(this.renderContext, 1, Settings.get_active().get_eclipticColor()); - } - } - if (Settings.get_active().get_showGrid()) { - Grids.drawEquitorialGrid(this.renderContext, 1, Settings.get_active().get_equatorialGridColor()); - if (Settings.get_active().get_showEquatorialGridText()) { - Grids.drawEquitorialGridText(this.renderContext, 1, Settings.get_active().get_equatorialGridColor()); - } - } - if (Settings.get_active().get_showConstellationBoundries()) { - if (WWTControl.constellationsBoundries == null) { - WWTControl.constellationsBoundries = Constellations.create('Constellations', URLHelpers.singleton.engineAssetUrl('constellations.txt'), true, false, false); - } - WWTControl.constellationsBoundries.draw(this.renderContext, Settings.get_active().get_showConstellationSelection(), this.constellation, false); - } - if (Settings.get_active().get_showConstellationLabels()) { - Constellations.drawConstellationNames(this.renderContext, 1, Colors.get_yellow()); - } - }, - _drawHoverText: function (RenderContext) { - if (RenderContext.gl == null) { - var ctx = RenderContext.device; - ctx.save(); - ctx.fillStyle = 'White'; - ctx.font = '15px Arial'; - ctx.fillText(this._hoverText, this._hoverTextPoint.x, this._hoverTextPoint.y); - ctx.restore(); - } - }, - rAtoViewLng: function (ra) { - return (((180 - (ra / 24 * 360) - 180) + 540) % 360) - 180; - }, - _updateViewParameters: function () { - if (this.renderContext.space && this._tracking && this._trackingObject != null) { - if (Settings.get_active().get_galacticMode() && this.renderContext.space) { - var gPoint = Coordinates.j2000toGalactic(this._trackingObject.get_RA() * 15, this._trackingObject.get_dec()); - this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; - this.renderContext.targetAz = this.renderContext.az = gPoint[0]; - } - else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { - var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(this._trackingObject.get_RA(), this._trackingObject.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); - this.renderContext.targetAlt = currentAltAz.get_alt(); - this.renderContext.targetAz = currentAltAz.get_az(); - } - else { - this.renderContext.viewCamera.lng = this.renderContext.targetCamera.lng = this.rAtoViewLng(this._trackingObject.get_RA()); - this.renderContext.viewCamera.lat = this.renderContext.targetCamera.lat = this._trackingObject.get_dec(); - } - } - else if (!this.get_solarSystemMode()) { - this._tracking = false; - this._trackingObject = null; - } - var oneMinusDragCoefficient = 1 - 0.8; - var dc = 0.8; - if (!this._tracking) { - var minDelta = (this.renderContext.viewCamera.zoom / 4000); - if (this.renderContext.viewCamera.zoom > 360) { - minDelta = (360 / 40000); - } - if (this.renderContext.space && (Settings.get_active().get_localHorizonMode() || Settings.get_active().get_galacticMode())) { - if ((((Math.abs(this.renderContext.targetAlt - this.renderContext.alt) >= minDelta) | (Math.abs(this.renderContext.targetAz - this.renderContext.az) >= minDelta)) === 1)) { - this.renderContext.alt += (this.renderContext.targetAlt - this.renderContext.alt) / 10; - if (Math.abs(this.renderContext.targetAz - this.renderContext.az) > 170) { - if (this.renderContext.targetAz > this.renderContext.az) { - this.renderContext.az += (this.renderContext.targetAz - (360 + this.renderContext.az)) / 10; - } - else { - this.renderContext.az += ((360 + this.renderContext.targetAz) - this.renderContext.az) / 10; - } - } - else { - this.renderContext.az += (this.renderContext.targetAz - this.renderContext.az) / 10; - } - this.renderContext.az = ((this.renderContext.az + 720) % 360); - } - } - else { - if ((((Math.abs(this.renderContext.targetCamera.lat - this.renderContext.viewCamera.lat) >= minDelta) | (Math.abs(this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) >= minDelta)) === 1)) { - this.renderContext.viewCamera.lat += (this.renderContext.targetCamera.lat - this.renderContext.viewCamera.lat) / 10; - if (Math.abs(this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) > 170) { - if (this.renderContext.targetCamera.lng > this.renderContext.viewCamera.lng) { - this.renderContext.viewCamera.lng += (this.renderContext.targetCamera.lng - (360 + this.renderContext.viewCamera.lng)) / 10; - } - else { - this.renderContext.viewCamera.lng += ((360 + this.renderContext.targetCamera.lng) - this.renderContext.viewCamera.lng) / 10; - } - } - else { - this.renderContext.viewCamera.lng += (this.renderContext.targetCamera.lng - this.renderContext.viewCamera.lng) / 10; - } - this.renderContext.viewCamera.lng = ((this.renderContext.viewCamera.lng + 720) % 360); - } - else { - if (this.renderContext.viewCamera.lat !== this.renderContext.targetCamera.lat || this.renderContext.viewCamera.lng !== this.renderContext.targetCamera.lng) { - this.renderContext.viewCamera.lat = this.renderContext.targetCamera.lat; - this.renderContext.viewCamera.lng = this.renderContext.targetCamera.lng; - } - } - } - } - this.renderContext.viewCamera.zoom = dc * this.renderContext.viewCamera.zoom + oneMinusDragCoefficient * this.renderContext.targetCamera.zoom; - this.renderContext.viewCamera.rotation = dc * this.renderContext.viewCamera.rotation + oneMinusDragCoefficient * this.renderContext.targetCamera.rotation; - this.renderContext.viewCamera.angle = dc * this.renderContext.viewCamera.angle + oneMinusDragCoefficient * this.renderContext.targetCamera.angle; - }, - move: function (x, y) { - var angle = Math.atan2(y, x); - var distance = Math.sqrt(x * x + y * y); - if (this.get_solarSystemMode() || this.get_planetLike()) { - x = Math.cos(angle + this.renderContext.viewCamera.rotation) * distance; - y = Math.sin(angle + this.renderContext.viewCamera.rotation) * distance; - } - else { - x = Math.cos(angle - this.renderContext.viewCamera.rotation) * distance; - y = Math.sin(angle - this.renderContext.viewCamera.rotation) * distance; - } - var scaleY = this.renderContext.get_fovScale() / 3600; - if (this.renderContext.get_backgroundImageset().get_dataSetType() === 4) { - scaleY = 0.06; - } - var scaleX = scaleY / Math.max(0.2, Math.cos(this.renderContext.viewCamera.lat / 180 * Math.PI)); - if (!this.renderContext.get_backgroundImageset().get_dataSetType() || this.renderContext.get_backgroundImageset().get_dataSetType() === 1 || this.renderContext.get_backgroundImageset().get_dataSetType() === 4) { - scaleX *= 6.3; - scaleY *= 6.3; - } - if (this.renderContext.space && (Settings.get_active().get_galacticMode() || Settings.get_active().get_localHorizonMode())) { - x = (Settings.get_active().get_localHorizonMode()) ? -x : x; - this.renderContext.targetAz += x * scaleX; - this.renderContext.targetAz = ((this.renderContext.targetAz + 720) % 360); - this.renderContext.targetAlt += y * scaleY; - if (this.renderContext.targetAlt > 90) { - this.renderContext.targetAlt = 90; - } - if (this.renderContext.targetAlt < -90) { - this.renderContext.targetAlt = -90; - } - } - else { - this.renderContext.targetCamera.lng -= x * scaleX; - this.renderContext.targetCamera.lng = ((this.renderContext.targetCamera.lng + 720) % 360); - this.renderContext.targetCamera.lat += y * scaleY; - if (this.renderContext.targetCamera.lat > 90) { - this.renderContext.targetCamera.lat = 90; - } - if (this.renderContext.targetCamera.lat < -90) { - this.renderContext.targetCamera.lat = -90; - } - } - if (!Settings.get_globalSettings().get_smoothPan()) { - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - } - if (!!x && !!y) { - this._tracking = false; - this._trackingObject = null; - } - }, - zoom: function (factor) { - this.renderContext.targetCamera.zoom *= factor; - if (this.renderContext.targetCamera.zoom > this.get_zoomMax()) { - this.renderContext.targetCamera.zoom = this.get_zoomMax(); - } - if (!Settings.get_globalSettings().get_smoothPan()) { - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - } - }, - roll: function (angle) { - this.renderContext.targetCamera.rotation += angle; - }, - onGestureStart: function (e) { - this._mouseDown = false; - this._beginZoom = this.renderContext.viewCamera.zoom; - }, - onGestureChange: function (e) { - var g = e; - this._mouseDown = false; - this.renderContext.targetCamera.zoom = this.renderContext.viewCamera.zoom = Math.min(360, this._beginZoom * (1 / g.scale)); - }, - onGestureEnd: function (e) { - var g = e; - this._mouseDown = false; - }, - onTouchStart: function (e) { - var ev = e; - ev.preventDefault(); - ev.stopPropagation(); - this._lastX = ev.targetTouches[0].pageX; - this._lastY = ev.targetTouches[0].pageY; - if (ev.targetTouches.length === 2) { - this._hasTwoTouches = true; - return; - } - if (this.uiController != null) { - var ee = new WWTElementEvent(this._lastX, this._lastY); - if (this.uiController.mouseDown(this, ee)) { - this._mouseDown = false; - this._dragging = false; - return; - } - } - this._mouseDown = true; - }, - onTouchMove: function (e) { - var ev = e; - if (this._hasTwoTouches) { - var t0 = ev.touches[0]; - var t1 = ev.touches[1]; - var newRect = new Array(2); - newRect[0] = Vector2d.create(t0.pageX, t0.pageY); - newRect[1] = Vector2d.create(t1.pageX, t1.pageY); - if (this._pinchingZoomRect[0] != null && this._pinchingZoomRect[1] != null) { - var centerPoint = Vector2d.create(this.renderContext.width / 2, this.renderContext.height / 2); - var delta1 = Vector2d.subtract(newRect[0], this._pinchingZoomRect[0]); - var delta2 = Vector2d.subtract(newRect[1], this._pinchingZoomRect[1]); - var radialDirection1 = Vector2d.subtract(this._pinchingZoomRect[0], centerPoint); - var radialDirection2 = Vector2d.subtract(this._pinchingZoomRect[1], centerPoint); - radialDirection1.normalize(); - radialDirection2.normalize(); - var radialDot1 = delta1.x * radialDirection1.x + delta1.y * radialDirection1.y; - var radialDot2 = delta2.x * radialDirection2.x + delta2.y * radialDirection2.y; - var radialComponent1 = Vector2d.create(radialDot1 * radialDirection1.x, radialDot1 * radialDirection1.y); - var radialComponent2 = Vector2d.create(radialDot2 * radialDirection2.x, radialDot2 * radialDirection2.y); - var angularComponent1 = Vector2d.subtract(delta1, radialComponent1); - var angularComponent2 = Vector2d.subtract(delta2, radialComponent2); - var radialMagnitude = radialComponent1.get_length() + radialComponent2.get_length(); - var angularMagnitude = angularComponent1.get_length() + angularComponent2.get_length(); - if (radialMagnitude >= angularMagnitude) { - var oldDist = this.getDistance(this._pinchingZoomRect[0], this._pinchingZoomRect[1]); - var newDist = this.getDistance(newRect[0], newRect[1]); - var ratio = oldDist / newDist; - this.zoom(ratio); - } - else { - var oldCenterDelta1 = Vector2d.subtract(this._pinchingZoomRect[0], centerPoint); - var oldCenterDelta2 = Vector2d.subtract(this._pinchingZoomRect[1], centerPoint); - var newCenterDelta1 = Vector2d.subtract(newRect[0], centerPoint); - var newCenterDelta2 = Vector2d.subtract(newRect[1], centerPoint); - var cross1 = this.crossProductZ(oldCenterDelta1, newCenterDelta1); - var cross2 = this.crossProductZ(oldCenterDelta2, newCenterDelta2); - var angle1 = Math.asin(cross1 / (oldCenterDelta1.get_length() * newCenterDelta1.get_length())); - var angle2 = Math.asin(cross2 / (oldCenterDelta2.get_length() * newCenterDelta2.get_length())); - if (angle1 * angle2 >= 0) { - var angle = angle1 + angle2; - if (this.get_planetLike() || this.get_solarSystemMode()) { - angle *= -1; - } - this.roll(angle); - } - } - } - this._pinchingZoomRect = newRect; - ev.stopPropagation(); - ev.preventDefault(); - return; - } - ev.preventDefault(); - ev.stopPropagation(); - if (this._mouseDown) { - this._dragging = true; - var curX = ev.targetTouches[0].pageX - this._lastX; - var curY = ev.targetTouches[0].pageY - this._lastY; - this.move(curX, curY); - this._lastX = ev.targetTouches[0].pageX; - this._lastY = ev.targetTouches[0].pageY; - } - else { - if (this.uiController != null) { - if (this.uiController.mouseMove(this, e)) { - e.preventDefault(); - e.stopPropagation(); - return; - } - } - } - }, - onTouchEnd: function (e) { - var ev = e; - ev.preventDefault(); - ev.stopPropagation(); - this._pinchingZoomRect[0] = null; - this._pinchingZoomRect[1] = null; - if (this._hasTwoTouches) { - if (ev.touches.length < 2) { - this._hasTwoTouches = false; - } - return; - } - if (this.uiController != null) { - var ee = new WWTElementEvent(this._lastX, this._lastY); - if (this.uiController.mouseUp(this, ee)) { - this._mouseDown = false; - this._dragging = false; - return; - } - } - this._mouseDown = false; - this._dragging = false; - }, - onPointerDown: function (e) { - var pe = e; - var index = 0; - var evt = arguments[0], cnv = arguments[0].target; if (cnv.setPointerCapture) { cnv.setPointerCapture(evt.pointerId); } else if (cnv.msSetPointerCapture) { cnv.msSetPointerCapture(evt.pointerId); }; - if (this._pointerIds[0] === pe.pointerId) { - index = 0; - } - else if (this._pointerIds[1] === pe.pointerId) { - index = 1; - } - else if (!this._pointerIds[0]) { - index = 0; - } - else if (!this._pointerIds[1]) { - index = 1; - } - else { - return; - } - this._pointerIds[index] = pe.pointerId; - this._pinchingZoomRect[index] = Vector2d.create(e.offsetX, e.offsetY); - }, - onPointerMove: function (e) { - var pe = e; - var index = 0; - if (this._pointerIds[0] === pe.pointerId) { - index = 0; - } - else if (this._pointerIds[1] === pe.pointerId) { - index = 1; - } - else { - return; - } - if (this._pinchingZoomRect[0] != null && this._pinchingZoomRect[1] != null) { - var oldDist = this.getDistance(this._pinchingZoomRect[0], this._pinchingZoomRect[1]); - var newRect = Vector2d.create(e.offsetX, e.offsetY); - var newDist0 = this.getDistance(newRect, this._pinchingZoomRect[0]); - var ratio0 = oldDist / newDist0; - var abslog0 = Math.abs(Math.log(ratio0)); - if (!isFinite(abslog0)) { - abslog0 = 1000; - } - var newDist1 = this.getDistance(newRect, this._pinchingZoomRect[1]); - var ratio1 = oldDist / newDist1; - var abslog1 = Math.abs(Math.log(ratio1)); - if (!isFinite(abslog1)) { - abslog1 = 1000; - } - if (abslog1 < abslog0) { - this._pinchingZoomRect[0] = newRect; - this.zoom(ratio1); - } - else { - this._pinchingZoomRect[1] = newRect; - this.zoom(ratio0); - } - } - else { - this._pinchingZoomRect[index] = Vector2d.create(e.offsetX, e.offsetY); - } - e.stopPropagation(); - e.preventDefault(); - }, - onPointerUp: function (e) { - var pe = e; - if (this._pointerIds[0] === pe.pointerId) { - this._pointerIds[0] = -2; - this._pinchingZoomRect[0] = null; - } - if (this._pointerIds[1] === pe.pointerId) { - this._pointerIds[1] = -2; - this._pinchingZoomRect[1] = null; - } - }, - onMouseDown: function (e) { - document.addEventListener('mousemove', ss.bind('onMouseMove', this), false); - document.addEventListener('mouseup', ss.bind('onMouseUp', this), false); - if (this.uiController != null) { - if (this.uiController.mouseDown(this, e)) { - return; - } - } - this._mouseDown = true; - this._lastX = Mouse.offsetX(this.canvas, e); - this._lastY = Mouse.offsetY(this.canvas, e); - }, - onMouseMove: function (e) { - this._lastMouseMove = ss.now(); - this._hoverTextPoint = Vector2d.create(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e)); - this._hoverText = ''; - if (this._mouseDown) { - e.preventDefault(); - e.stopPropagation(); - this._moved = true; - if (e.ctrlKey) { - this._tilt(Mouse.offsetX(this.canvas, e) - this._lastX, Mouse.offsetY(this.canvas, e) - this._lastY); - } - else { - this.move(Mouse.offsetX(this.canvas, e) - this._lastX, Mouse.offsetY(this.canvas, e) - this._lastY); - } - this._lastX = Mouse.offsetX(this.canvas, e); - this._lastY = Mouse.offsetY(this.canvas, e); - } - else { - if (this.uiController != null) { - if (this.uiController.mouseMove(this, e)) { - e.preventDefault(); - e.stopPropagation(); - return; - } - } - } - }, - onMouseUp: function (e) { - document.removeEventListener('mousemove', ss.bind('onMouseMove', this), false); - document.removeEventListener('mouseup', ss.bind('onMouseUp', this), false); - if (this.uiController != null) { - if (this.uiController.mouseUp(this, e)) { - this._mouseDown = false; - e.preventDefault(); - return; - } - } - if (this._mouseDown && !this._moved) { - var raDecDown = this.getCoordinatesForScreenPoint(Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e)); - if (!this._annotationclicked(raDecDown.x, raDecDown.y, Mouse.offsetX(this.canvas, e), Mouse.offsetY(this.canvas, e))) { - WWTControl.scriptInterface._fireClick(raDecDown.x, raDecDown.y); - } - } - this._mouseDown = false; - this._moved = false; - }, - onMouseWheel: function (e) { - var ev = e; - var delta; - if (!!ev.deltaY) { - delta = -ev.deltaY; - } - else if (!!ev.detail) { - delta = ev.detail * -1; - } - else { - delta = ev.wheelDelta; - } - if (delta > 0) { - this.zoom(0.9); - } - else { - this.zoom(1.1); - } - e.stopPropagation(); - e.preventDefault(); - }, - onDoubleClick: function (e) { - WWTControl.showDataLayers = true; - }, - onKeyDown: function (e) { - if (this.uiController != null) { - this.uiController.keyDown(this, e); - } - }, - getDistance: function (a, b) { - var x; - var y; - x = a.x - b.x; - y = a.y - b.y; - return Math.sqrt(x * x + y * y); - }, - crossProductZ: function (a, b) { - return a.x * b.y - a.y * b.x; - }, - onContextMenu: function (e) { - e.preventDefault(); - e.stopPropagation(); - }, - _tilt: function (x, y) { - this.renderContext.targetCamera.rotation += x * 0.001; - this.renderContext.targetCamera.angle += y * 0.001; - if (this.renderContext.targetCamera.angle < -1.52) { - this.renderContext.targetCamera.angle = -1.52; - } - if (this.renderContext.targetCamera.angle > 0) { - this.renderContext.targetCamera.angle = 0; - } - }, - getCoordinatesForScreenPoint: function (x, y) { - var pt = Vector2d.create(x, y); - var PickRayDir = this.transformPickPointToWorldSpace(pt, this.renderContext.width, this.renderContext.height); - return Coordinates.cartesianToSphericalSky(PickRayDir); - }, - transformPickPointToWorldSpace: function (ptCursor, backBufferWidth, backBufferHeight) { - var vPickRayDir = new Vector3d(); - if (this.renderContext.get_projection() != null) { - var v = new Vector3d(); - v.x = (((2 * ptCursor.x) / backBufferWidth) - 1) / this.renderContext.get_projection().get_m11(); - v.y = (((2 * ptCursor.y) / backBufferHeight) - 1) / this.renderContext.get_projection().get_m22(); - v.z = 1; - var m = Matrix3d.multiplyMatrix(this.renderContext.get_view(), this.renderContext.get_world()); - m.invert(); - vPickRayDir.x = v.x * m.get_m11() + v.y * m.get_m21() + v.z * m.get_m31(); - vPickRayDir.y = v.x * m.get_m12() + v.y * m.get_m22() + v.z * m.get_m32(); - vPickRayDir.z = v.x * m.get_m13() + v.y * m.get_m23() + v.z * m.get_m33(); - vPickRayDir.normalize(); - } - return vPickRayDir; - }, - transformWorldPointToPickSpace: function (worldPoint, backBufferWidth, backBufferHeight) { - var m = Matrix3d.multiplyMatrix(this.renderContext.get_view(), this.renderContext.get_world()); - m.invert(); - var p = new Vector2d(); - var vz = worldPoint.x * m.get_m31() + worldPoint.y * m.get_m32() + worldPoint.z * m.get_m33(); - var vx = (worldPoint.x * m.get_m11() + worldPoint.y * m.get_m12() + worldPoint.z * m.get_m13()) / vz; - var vy = (worldPoint.x * m.get_m21() + worldPoint.y * m.get_m22() + worldPoint.z * m.get_m23()) / vz; - p.x = Math.round((1 + this.renderContext.get_projection().get_m11() * vx) * (backBufferWidth / 2)); - p.y = Math.round((1 + this.renderContext.get_projection().get_m22() * vy) * (backBufferHeight / 2)); - return p; - }, - getScreenPointForCoordinates: function (ra, dec) { - var pt = Vector2d.create(ra, dec); - var cartesian = Coordinates.sphericalSkyToCartesian(pt); - var result = this.transformWorldPointToPickSpace(cartesian, this.renderContext.width, this.renderContext.height); - return result; - }, - setup: function (canvas, startLat, startLng, startZoom) { - var $this = this; - - window.addEventListener('contextmenu', ss.bind('onContextMenu', this), false); - document.body.addEventListener('keydown', ss.bind('onKeyDown', this), false); - canvas.addEventListener('dblclick', ss.bind('onDoubleClick', this), false); - canvas.addEventListener('mousedown', ss.bind('onMouseDown', this), false); - canvas.addEventListener('wheel', ss.bind('onMouseWheel', this), false); - canvas.addEventListener('mousewheel', ss.bind('onMouseWheel', this), false); - canvas.addEventListener('DOMMouseScroll', ss.bind('onMouseWheel', this), false); - canvas.addEventListener('touchstart', ss.bind('onTouchStart', this), false); - canvas.addEventListener('touchmove', ss.bind('onTouchMove', this), false); - canvas.addEventListener('touchend', ss.bind('onTouchEnd', this), false); - canvas.addEventListener('gesturechange', ss.bind('onGestureChange', this), false); - canvas.addEventListener('gesturestart', ss.bind('onGestureStart', this), false); - canvas.addEventListener('gestureend', ss.bind('onGestureEnd', this), false); - canvas.addEventListener('pointerdown', ss.bind('onPointerDown', this), false); - canvas.addEventListener('pointermove', ss.bind('onPointerMove', this), false); - canvas.addEventListener('pointerup', ss.bind('onPointerUp', this), false); - this.renderContext.viewCamera.lat = startLat; - this.renderContext.viewCamera.lng = startLng; - this.renderContext.viewCamera.zoom = startZoom; - this.renderContext.targetCamera = this.renderContext.viewCamera.copy(); - if (this.renderContext.gl == null) { - this._foregroundCanvas = document.createElement('canvas'); - this._foregroundCanvas.width = canvas.width; - this._foregroundCanvas.height = canvas.height; - this._fgDevice = this._foregroundCanvas.getContext('2d'); - } - if (this.freestandingMode) { - setTimeout(function () { - $this._setupComplete(); - }, 0); - } - else { - Wtml.getWtmlFile(URLHelpers.singleton.coreDynamicUrl('wwtweb/catalog.aspx?X=ImageSets6'), ss.bind('_setupComplete', this), true); - } - }, - _setupComplete: function () { - WWTControl.scriptInterface._fireReady(); - }, - gotoRADecZoom: function (ra, dec, zoom, instant, roll) { - this._tracking = false; - this._trackingObject = null; - this.gotoTargetFull(false, instant, this._cameraParametersFromRADecZoom(ra, dec, zoom, roll), WWTControl.singleton.renderContext.get_foregroundImageset(), WWTControl.singleton.renderContext.get_backgroundImageset()); - }, - _cameraParametersFromRADecZoom: function (ra, dec, zoom, roll) { - while (ra > 24) { - ra -= 24; - } - while (ra < 0) { - ra += 24; - } - dec = DoubleUtilities.clamp(dec, -90, 90); - zoom = DoubleUtilities.clamp(zoom, this.get_zoomMin(), this.get_zoomMax()); - var rotation = (roll == null) ? WWTControl.singleton.renderContext.viewCamera.rotation : roll; - var cameraParams = CameraParameters.create(dec, WWTControl.singleton.renderContext.rAtoViewLng(ra), zoom, rotation, WWTControl.singleton.renderContext.viewCamera.angle, WWTControl.singleton.renderContext.viewCamera.opacity); - return cameraParams; - }, - timeToRADecZoom: function (ra, dec, zoom, roll) { - var cameraParams = this._cameraParametersFromRADecZoom(ra, dec, zoom, roll); - return this.timeToTargetFull(cameraParams, false); - }, - get_solarSystemMode: function () { - if (this.renderContext.get_backgroundImageset() == null) { - return false; - } - return this.renderContext.get_backgroundImageset().get_dataSetType() === 4; - }, - gotoTarget: function (place, noZoom, instant, trackObject) { - if (place == null) { - return; - } - if ((trackObject && this.get_solarSystemMode())) { - if ((place.get_classification() === 536870912 && place.get_type() !== 4) || (place.get_classification() === 1) || (place.get_classification() === 1048576) && place.get_distance() > 0) { - var target = 65536; - if (place.get_classification() === 1 || place.get_classification() === 1048576) { - target = 20; - } - else { - try { - if (place.get_target() !== 65536) { - target = place.get_target(); - } - else { - target = Planets.getPlanetIDFromName(place.get_name()); - } - } - catch ($e1) { - } - } - if (target !== 65536) { - this._trackingObject = place; - if (target === this._solarSystemTrack && !(place.get_classification() === 1 || place.get_classification() === 1048576)) { - this.gotoTarget3(place.get_camParams(), noZoom, instant); - return; - } - var jumpTime = 4; - if (target === 20) { - jumpTime = 17; - } - else { - jumpTime += 13 * (101 - Settings.get_active().get_solarSystemScale()) / 100; - } - if (instant) { - jumpTime = 1; - } - var camTo = this.renderContext.viewCamera.copy(); - camTo.targetReferenceFrame = ''; - camTo.target = target; - var zoom = 10; - if (target === 20) { - if (place.get_classification() === 1048576) { - zoom = 1404946007758; - } - else { - zoom = 63239.6717 * 100; - } - var vect = Coordinates.raDecTo3dAu(place.get_RA(), place.get_dec(), place.get_distance()); - var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; - vect.rotateX(ecliptic); - camTo.viewTarget = Vector3d.negate(camTo.viewTarget); - } - else { - camTo.viewTarget = Planets.getPlanet3dLocationJD(target, SpaceTimeController.getJNowForFutureTime(jumpTime)); - switch (target) { - case 0: - zoom = 0.6; - break; - case 1: - zoom = 0.0004; - break; - case 2: - zoom = 0.0004; - break; - case 3: - zoom = 0.0004; - break; - case 4: - zoom = 0.007; - break; - case 5: - zoom = 0.007; - break; - case 6: - zoom = 0.004; - break; - case 7: - zoom = 0.004; - break; - case 8: - zoom = 0.0004; - break; - case 9: - zoom = 0.0004; - break; - case 10: - zoom = 0.0004; - break; - case 11: - zoom = 0.0004; - break; - case 12: - zoom = 0.0004; - break; - case 13: - zoom = 0.0004; - break; - case 19: - zoom = 0.0004; - break; - case 20: - zoom = 10; - break; - default: - break; - } - zoom = zoom * Settings.get_active().get_solarSystemScale(); - } - var fromParams = this.renderContext.viewCamera.copy(); - if (this._solarSystemTrack === 20 && !ss.emptyString(this.renderContext.get_trackingFrame())) { - fromParams = this.renderContext.customTrackingParams; - this.renderContext.set_trackingFrame(''); - } - camTo.zoom = zoom; - var toVector = camTo.viewTarget; - toVector.subtract(fromParams.viewTarget); - if (place.get_classification() === 1) { - toVector = Vector3d.negate(toVector); - } - if (!!toVector.length()) { - var raDec = toVector.toRaDec(); - if (target === 20) { - camTo.lat = -raDec.y; - } - else { - camTo.lat = raDec.y; - } - camTo.lng = raDec.x * 15 - 90; - } - else { - camTo.lat = this.renderContext.viewCamera.lat; - camTo.lng = this.renderContext.viewCamera.lng; - } - if (target !== 20) { - camTo.viewTarget = Planets.getPlanetTargetPoint(target, camTo.lat, camTo.lng, SpaceTimeController.getJNowForFutureTime(jumpTime)); - } - var solarMover = new ViewMoverKenBurnsStyle(fromParams, camTo, jumpTime, SpaceTimeController.get_now(), SpaceTimeController.getTimeForFutureTime(jumpTime), 3); - solarMover.fastDirectionMove = true; - this.set__mover(solarMover); - return; - } - } - } - this._tracking = false; - this._trackingObject = null; - var camParams = place.get_camParams().copy(); - if (this.renderContext.get_backgroundImageset() != null && place.get_type() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { - this.renderContext.targetCamera = place.get_camParams().copy(); - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - this.renderContext.set_backgroundImageset(this.getDefaultImageset(place.get_type(), 3)); - instant = true; - } - else if (this.get_solarSystemMode() && place.get_target() !== this._solarSystemTrack) { - this.renderContext.targetCamera = place.get_camParams().copy(); - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - this._solarSystemTrack = place.get_target(); - instant = true; - } - if (place.get_classification() === 128) { - camParams.zoom = this.get_zoomMax(); - this.gotoTargetFull(false, instant, camParams, null, null); - } - else { - this._solarSystemTrack = place.get_target(); - this.gotoTargetFull(noZoom, instant, camParams, place.get_studyImageset(), place.get_backgroundImageset()); - if (trackObject) { - this._tracking = true; - this._trackingObject = place; - } - } - }, - gotoTarget3: function (camParams, noZoom, instant) { - this._tracking = false; - this._trackingObject = null; - this.gotoTargetFull(noZoom, instant, camParams, this.renderContext.get_foregroundImageset(), this.renderContext.get_backgroundImageset()); - }, - _tooCloseForSlewMove: function (cameraParams) { - return Math.abs(this.renderContext.viewCamera.lat - cameraParams.lat) < 1E-12 && Math.abs(this.renderContext.viewCamera.lng - cameraParams.lng) < 1E-12 && Math.abs(this.renderContext.viewCamera.zoom - cameraParams.zoom) < 1E-12 && Math.abs(this.renderContext.viewCamera.rotation - cameraParams.rotation) < 1E-12; - }, - gotoTargetFull: function (noZoom, instant, cameraParams, studyImageSet, backgroundImageSet) { - WWTControl.set_renderNeeded(true); - this._tracking = false; - this._trackingObject = null; - this._targetStudyImageset = studyImageSet; - this._targetBackgroundImageset = backgroundImageSet; - if (noZoom) { - cameraParams.zoom = this.renderContext.viewCamera.zoom; - cameraParams.angle = this.renderContext.viewCamera.angle; - cameraParams.rotation = this.renderContext.viewCamera.rotation; - } - else { - if (cameraParams.zoom === -1 || !cameraParams.zoom) { - if (this.renderContext.space) { - cameraParams.zoom = 1.40625; - } - else { - cameraParams.zoom = 0.09; - } - } - } - if (instant || this._tooCloseForSlewMove(cameraParams)) { - this.set__mover(null); - this.renderContext.targetCamera = cameraParams.copy(); - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - if (this.renderContext.space && Settings.get_active().get_galacticMode()) { - var gPoint = Coordinates.j2000toGalactic(this.renderContext.viewCamera.get_RA() * 15, this.renderContext.viewCamera.get_dec()); - this.renderContext.targetAlt = this.renderContext.alt = gPoint[1]; - this.renderContext.targetAz = this.renderContext.az = gPoint[0]; - } - else if (this.renderContext.space && Settings.get_active().get_localHorizonMode()) { - var currentAltAz = Coordinates.equitorialToHorizon(Coordinates.fromRaDec(this.renderContext.viewCamera.get_RA(), this.renderContext.viewCamera.get_dec()), SpaceTimeController.get_location(), SpaceTimeController.get_now()); - this.renderContext.targetAlt = this.renderContext.alt = currentAltAz.get_alt(); - this.renderContext.targetAz = this.renderContext.az = currentAltAz.get_az(); - } - this._mover_Midpoint(); - } - else { - this.set__mover(ViewMoverSlew.create(this.renderContext.viewCamera, cameraParams)); - WWTControl.set_renderNeeded(true); - this.get__mover().set_midpoint(ss.bind('_mover_Midpoint', this)); - } - }, - _slewTimeBetweenTargets: function (from, to) { - var mover = ViewMoverSlew.create(from, to); - return mover.get_moveTime(); - }, - timeToTargetFull: function (cameraParams, noZoom) { - if (noZoom) { - cameraParams.zoom = this.renderContext.viewCamera.zoom; - cameraParams.angle = this.renderContext.viewCamera.angle; - cameraParams.rotation = this.renderContext.viewCamera.rotation; - } - if (this._tooCloseForSlewMove(cameraParams)) { - return 0; - } - return this._slewTimeBetweenTargets(WWTControl.singleton.renderContext.viewCamera, cameraParams); - }, - _freezeView: function () { - this.renderContext.viewCamera = this.renderContext.targetCamera.copy(); - this.set__mover(null); - }, - get__mover: function () { - return this.renderContext.viewMover; - }, - set__mover: function (value) { - this.renderContext.viewMover = value; - WWTControl.set_renderNeeded(true); - return value; - }, - fadeInImageSet: function (newImageSet) { - if (this.renderContext.get_backgroundImageset() != null && newImageSet.get_dataSetType() !== this.renderContext.get_backgroundImageset().get_dataSetType()) { - TileCache.purgeQueue(); - TileCache.clearCache(); - } - this.renderContext.set_backgroundImageset(newImageSet); - }, - _mover_Midpoint: function () { - if ((this._targetStudyImageset != null && this.renderContext.get_foregroundImageset() == null) || (this.renderContext.get_foregroundImageset() != null && !this.renderContext.get_foregroundImageset().equals(this._targetStudyImageset))) { - this.renderContext.set_foregroundImageset(this._targetStudyImageset); - } - if (this.renderContext.get_backgroundImageset() != null && (this._targetBackgroundImageset != null && !this.renderContext.get_backgroundImageset().equals(this._targetBackgroundImageset))) { - if (this._targetBackgroundImageset != null && this._targetBackgroundImageset.get_generic()) { - this.fadeInImageSet(this._getRealImagesetFromGeneric(this._targetBackgroundImageset)); - } - else { - this.fadeInImageSet(this._targetBackgroundImageset); - } - } - }, - getDefaultImageset: function (imageSetType, bandPass) { - var $enum1 = ss.enumerate(WWTControl.imageSets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_defaultSet() && imageset.get_bandPass() === bandPass && imageset.get_dataSetType() === imageSetType) { - return imageset; - } - } - var $enum2 = ss.enumerate(WWTControl.imageSets); - while ($enum2.moveNext()) { - var imageset = $enum2.current; - if (imageset.get_bandPass() === bandPass && imageset.get_dataSetType() === imageSetType) { - return imageset; - } - } - var $enum3 = ss.enumerate(WWTControl.imageSets); - while ($enum3.moveNext()) { - var imageset = $enum3.current; - if (imageset.get_dataSetType() === imageSetType) { - return imageset; - } - } - return WWTControl.imageSets[0]; - }, - _getRealImagesetFromGeneric: function (generic) { - var $enum1 = ss.enumerate(WWTControl.imageSets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_defaultSet() && imageset.get_bandPass() === generic.get_bandPass() && imageset.get_dataSetType() === generic.get_dataSetType()) { - return imageset; - } - } - var $enum2 = ss.enumerate(WWTControl.imageSets); - while ($enum2.moveNext()) { - var imageset = $enum2.current; - if (imageset.get_bandPass() === generic.get_bandPass() && imageset.get_dataSetType() === generic.get_dataSetType()) { - return imageset; - } - } - return WWTControl.imageSets[0]; - }, - _hideUI: function (p) { - }, - createTour: function (name) { - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.stop(false); - } - this.tour = new TourDocument(); - this.tour.set_title(name); - this.setupTour(); - this.tour.set_editMode(true); - return this.tour; - }, - setupTour: function () { - this.tourEdit = new TourEditTab(); - this.tourEdit.set_tour(this.tour); - this.tour.set_currentTourstopIndex(0); - this.tour.set_editMode(false); - this.uiController = this.tourEdit.tourEditorUI; - }, - loadTour: function (url) { - var $this = this; - - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.stop(false); - } - this.tour = TourDocument.fromUrl(url, function () { - $this.setupTour(); - var player = new TourPlayer(); - player.set_tour($this.tour); - WWTControl.singleton.uiController = player; - WWTControl.scriptInterface._fireTourReady(); - }); - }, - playTour: function (url) { - var $this = this; - - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.stop(false); - } - this.tour = TourDocument.fromUrl(url, function () { - $this.setupTour(); - $this.tourEdit.playNow(true); - WWTControl.scriptInterface._fireTourReady(); - }); - }, - playCurrentTour: function () { - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.play(); - } - }, - pauseCurrentTour: function () { - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.pauseTour(); - } - }, - stopCurrentTour: function () { - if (ss.canCast(this.uiController, TourPlayer)) { - var player = this.uiController; - player.stop(false); - } - }, - _closeTour: function () { - }, - getImagesetByName: function (name) { - var $enum1 = ss.enumerate(WWTControl.imageSets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_name().toLowerCase().indexOf(name.toLowerCase()) > -1) { - return imageset; - } - } - return null; - }, - getImageSetByUrl: function (url) { - var $enum1 = ss.enumerate(WWTControl.imageSets); - while ($enum1.moveNext()) { - var imageset = $enum1.current; - if (imageset.get_url() === url) { - return imageset; - } - } - return null; - }, - setBackgroundImageByName: function (name) { - var newBackground = this.getImagesetByName(name); - if (newBackground != null) { - this.renderContext.set_backgroundImageset(newBackground); - } - }, - setForegroundImageByName: function (name) { - var newForeground = this.getImagesetByName(name); - if (newForeground != null) { - this.renderContext.set_foregroundImageset(newForeground); - } - }, - addCatalogHips: function (catalogHips) { - this.renderContext.addCatalogHips(catalogHips, null); - }, - addCatalogHipsByName: function (name) { - this.addCatalogHipsByNameWithCallback(name, null); - }, - addCatalogHipsByNameWithCallback: function (name, onLoad) { - var catalogHips = this.getImagesetByName(name); - if (catalogHips != null) { - this.renderContext.addCatalogHips(catalogHips, onLoad); - } - }, - removeCatalogHipsByName: function (name) { - var catalogHips = this.getImagesetByName(name); - if (catalogHips != null) { - this.renderContext.removeCatalogHips(catalogHips); - } - }, - getCatalogHipsByName: function (name) { - return this.renderContext.getCatalogHipsByName(name); - }, - getCatalogHipsDataInView: function (name, limit, onComplete) { - var catalogHips = this.getImagesetByName(name); - if (catalogHips != null) { - this.renderContext.getCatalogHipsDataInView(catalogHips, limit, onComplete); - } - }, - setCutsForFits: function (imagesetName, min, max) { - var imageset = this.getImagesetByName(imagesetName); - if (imageset != null && imageset.get_fitsProperties() != null) { - imageset.get_fitsProperties().lowerCut = min; - imageset.get_fitsProperties().upperCut = max; - } - else { - console.log(imagesetName + ' not found'); - } - }, - setColorMapForFits: function (imagesetName, colorMapName) { - var imageset = this.getImagesetByName(imagesetName); - if (imageset != null && imageset.get_fitsProperties() != null) { - imageset.get_fitsProperties().colorMapName = colorMapName; - } - else { - console.log(imagesetName + ' not found'); - } - }, - setScaleTypeForFits: function (imagesetName, scaleType) { - var imageset = this.getImagesetByName(imagesetName); - if (imageset != null && imageset.get_fitsProperties() != null) { - imageset.get_fitsProperties().scaleType = scaleType; - } - else { - console.log(imagesetName + ' not found'); - } - }, - _drawCrosshairs: function (context) { - if (context.gl == null) { - var ctx = context.device; - ctx.save(); - ctx.beginPath(); - ctx.strokeStyle = Settings.get_current().get_crosshairsColor(); - ctx.lineWidth = 2; - var x = context.width / 2, y = context.height / 2; - var halfLength = 5; - ctx.moveTo(x, y + halfLength); - ctx.lineTo(x, y - halfLength); - ctx.moveTo(x + halfLength, y); - ctx.lineTo(x - halfLength, y); - ctx.stroke(); - ctx.restore(); - } - else { - if (this._crossHairs == null) { - var halfHeight = 0.03; - var halfWidth = halfHeight * context.height / context.width; - this._crossHairs = new SimpleLineList(); - this._crossHairs.set_depthBuffered(false); - this._crossHairs.pure2D = true; - this._crossHairs.addLine(Vector3d.create(-halfWidth, 0, 0), Vector3d.create(halfWidth, 0, 0)); - this._crossHairs.addLine(Vector3d.create(0, -halfHeight, 0), Vector3d.create(0, halfHeight, 0)); - } - this._crossHairs.drawLines(context, 1, Color.load(Settings.get_current().get_crosshairsColor())); - } - }, - captureThumbnail: function (blobReady) { - this.captureFrame(blobReady, 96, 45, 'image/jpeg', true); - }, - captureCurrentFrame: function (blobReady, width, height, format) { - this.captureFrame(blobReady, width, height, format, false); - }, - captureFrameForVideo: function (blobReady, width, height, format) { - var $this = this; - - var frameNumber = SpaceTimeController.currentFrameNumber; - var forVideo = function (blob) { - var containsIndex; - if (frameNumber === $this._videoQueueIndex) { - blobReady(blob); - $this._videoQueueIndex += 1; - while ((containsIndex = ss.keyExists($this._videoBlobQueue, $this._videoQueueIndex)) || ($this._emptyFrames.indexOf($this._videoQueueIndex) >= 0)) { - if (containsIndex) { - blobReady($this._videoBlobQueue[$this._videoQueueIndex]); - $this._videoBlobQueue[$this._videoQueueIndex] = null; - } - else { - ss.remove($this._emptyFrames, $this._videoQueueIndex); - } - $this._videoQueueIndex += 1; - } - } - else { - if (blob != null) { - $this._videoBlobQueue[frameNumber] = blob; - } - else { - $this._emptyFrames.push(frameNumber); - } - } - if ($this._videoQueueIndex >= SpaceTimeController.totalFrames) { - $this._videoBlobReady = null; - $this._videoBlobQueue = null; - $this._videoQueueIndex = 0; - $this._emptyFrames.length = 0; - } - }; - this.captureCurrentFrame(forVideo, width, height, format); - }, - captureFrame: function (blobReady, width, height, format, needRender) { - if (needRender) { - this.renderOneFrame(); - } - var image = document.createElement('img'); - image.addEventListener('load', function (e) { - var imageAspect = (image.width) / image.height; - var clientAspect = width / height; - var cw = width; - var ch = height; - if (imageAspect < clientAspect) { - ch = ss.truncate((cw / imageAspect)); - } - else { - cw = ss.truncate((ch * imageAspect)); - } - var cx = (width - cw) / 2; - var cy = (height - ch) / 2; - var temp = document.createElement('canvas'); - temp.height = height; - temp.width = width; - var ctx = temp.getContext('2d'); - ctx.drawImage(image, cx, cy, cw, ch); - if (typeof temp.msToBlob == 'function') { var blob = temp.msToBlob(); blobReady(blob); } else { temp.toBlob(blobReady, format); }; - }, false); - image.src = WWTControl.singleton.canvas.toDataURL(); - }, - clampZooms: function (rc) { - rc.viewCamera.zoom = DoubleUtilities.clamp(rc.viewCamera.zoom, this.get_zoomMin(), this.get_zoomMax()); - rc.targetCamera.zoom = DoubleUtilities.clamp(rc.targetCamera.zoom, this.get_zoomMin(), this.get_zoomMax()); - } - }; - - - // wwtlib.WWTControlBuilder - - function WWTControlBuilder(divId) { - this._divId = null; - this._startRenderLoop = false; - this._startLat = 0; - this._startLng = 0; - this._startZoom = 360; - this._freestandingAssetBaseurl = ''; - this._startMode = ''; - this._divId = divId; - } - var WWTControlBuilder$ = { - startRenderLoop: function (value) { - this._startRenderLoop = value; - }, - initialView: function (lat, lng, zoom) { - this._startLat = lat; - this._startLng = lng; - this._startZoom = zoom; - }, - freestandingMode: function (asset_baseurl) { - this._freestandingAssetBaseurl = asset_baseurl; - }, - initialMode: function (value) { - this._startMode = value; - }, - create: function () { - var freestandingMode = !!this._freestandingAssetBaseurl; - var trueStartMode; - if (!!this._startMode) { - trueStartMode = this._startMode; - } - else if (freestandingMode) { - trueStartMode = 'black'; - } - else { - trueStartMode = 'sky'; - } - WWTControl.singleton.freestandingMode = freestandingMode; - if (freestandingMode) { - URLHelpers.singleton.overrideAssetBaseurl(this._freestandingAssetBaseurl); - } - return WWTControl.initControl6(this._divId, this._startRenderLoop, this._startLat, this._startLng, this._startZoom, trueStartMode); - } - }; - - - // wwtlib.WWTElementEvent - - function WWTElementEvent(x, y) { - this.offsetX = 0; - this.offsetY = 0; - this.offsetX = x; - this.offsetY = y; - } - var WWTElementEvent$ = { - - }; - - - // wwtlib.Coordinates - - function Coordinates(ascention, declination) { - this._ascention = 0; - this._declination = 0; - this._ascention = ascention + (Math.PI * 80) % (Math.PI * 2); - this._declination = declination; - } - Coordinates.geoTo3d = function (lat, lng) { - return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1, Math.sin(lat * Coordinates.RC) * 1, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1); - }; - Coordinates.geoTo3dDouble = function (lat, lng) { - return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1, Math.sin(lat * Coordinates.RC) * 1, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * 1); - }; - Coordinates.geoTo3dRad = function (lat, lng, radius) { - return Vector3d.create(Math.cos(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * radius, Math.sin(lat * Coordinates.RC) * radius, Math.sin(lng * Coordinates.RC) * Math.cos(lat * Coordinates.RC) * radius); - }; - Coordinates.raDecTo3d = function (ra, dec) { - return Vector3d.create(Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1, Math.sin(dec * Coordinates.RC) * 1, Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1); - }; - Coordinates.raDecTo3dAu = function (ra, dec, au) { - return Vector3d.create(Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * au, Math.sin(dec * Coordinates.RC) * au, Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * au); - }; - Coordinates.raDecTo3dMat = function (ra, dec, mat) { - return Vector3d._transformCoordinate(Vector3d.create((Math.cos(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1), (Math.sin(dec * Coordinates.RC) * 1), (Math.sin(ra * Coordinates.RCRA) * Math.cos(dec * Coordinates.RC) * 1)), mat); - }; - Coordinates.raDecTo3dPointRad = function (point, radius) { - point.set_dec(-point.get_dec()); - return Vector3d.create((Math.cos(point.get_RA() * Coordinates.RCRA) * Math.cos(point.get_dec() * Coordinates.RC) * radius), (Math.sin(point.get_dec() * Coordinates.RC) * radius), (Math.sin(point.get_RA() * Coordinates.RCRA) * Math.cos(point.get_dec() * Coordinates.RC) * radius)); - }; - Coordinates.sterographicTo3d = function (x, y, radius, standardLat, meridean, falseEasting, falseNorthing, scale, north) { - var lat = 90; - var lng = 0; - x -= falseEasting; - y -= falseNorthing; - if (!!x || !!y) { - var re = (1 + Math.sin(Math.abs(standardLat) / 180 * Math.PI)) * 6371000 / scale; - var rere = re * re; - var c1 = 180 / Math.PI; - if (!x) { - lng = (90 * y < 0) ? -1 : 1; - } - else { - lng = Math.atan2(y, x) * c1; - } - var len = (x * x) + (y * y); - lat = (rere - len) / (rere + len); - lat = Math.asin(lat) * c1; - if (!north) { - lat = -lat; - lng = -lng; - meridean = -meridean; - } - } - return Coordinates.geoTo3dRad(lat, 90 + lng + meridean, radius); - }; - Coordinates.equitorialToHorizon = function (equitorial, location, utc) { - var hourAngle = Coordinates.mstFromUTC2(utc, location.get_lng()) - (equitorial.get_RA() * 15); - if (hourAngle < 0) { - hourAngle += 360; - } - var ha = hourAngle * Coordinates.RC; - var dec = equitorial.get_dec() * Coordinates.RC; - var lat = location.get_lat() * Coordinates.RC; - var sinAlt = Math.sin(dec) * Math.sin(lat) + Math.cos(dec) * Math.cos(lat) * Math.cos(ha); - var altitude = Math.asin(sinAlt); - var cosAzimith = (Math.sin(dec) - Math.sin(altitude) * Math.sin(lat)) / (Math.cos(altitude) * Math.cos(lat)); - var azimuth = Math.acos(cosAzimith); - var altAz = new Coordinates(azimuth, altitude); - if (Math.sin(ha) > 0) { - altAz.set_az((360 - altAz.get_az())); - } - return altAz; - }; - Coordinates.horizonToEquitorial = function (altAz, location, utc) { - var hourAngle = Coordinates.mstFromUTC2(utc, location.get_lng()); - var haLocal; - var declination; - var raDec = Coordinates._altAzToRaDec(altAz.get_alt() * Coordinates.RC, altAz.get_az() * Coordinates.RC, location.get_lat() * Coordinates.RC); - haLocal = raDec.x; - declination = raDec.y; - var ha = (haLocal / Coordinates.RC); - hourAngle += ha; - if (hourAngle < 0) { - hourAngle += 360; - } - if (hourAngle > 360) { - hourAngle -= 360; - } - return Coordinates.fromRaDec(hourAngle / 15, declination / Coordinates.RC); - }; - Coordinates._altAzToRaDec = function (Altitude, Azimuth, Latitude) { - var hrAngle = 0; - var dec = 0; - Azimuth = Math.PI - Azimuth; - if (Azimuth < 0) { - Azimuth += Math.PI * 2; - } - hrAngle = Math.atan2(Math.sin(Azimuth), Math.cos(Azimuth) * Math.sin(Latitude) + Math.tan(Altitude) * Math.cos(Latitude)); - if (hrAngle < 0) { - hrAngle += Math.PI * 2; - } - dec = Math.asin(Math.sin(Latitude) * Math.sin(Altitude) - Math.cos(Latitude) * Math.cos(Altitude) * Math.cos(Azimuth)); - return Vector2d.create(hrAngle, dec); - }; - Coordinates.mstFromUTC2 = function (utc, lng) { - var year = utc.getUTCFullYear(); - var month = utc.getUTCMonth() + 1; - var day = utc.getUTCDate(); - var hour = utc.getUTCHours(); - var minute = utc.getUTCMinutes(); - var second = utc.getUTCSeconds() + utc.getUTCMilliseconds() / 1000; - if (month === 1 || month === 2) { - year -= 1; - month += 12; - } - var a = ss.truncate((year / 100)); - var b = 2 - a + Math.floor((a / 4)); - var c = Math.floor(365.25 * year); - var d = Math.floor(30.6001 * (month + 1)); - var julianDays; - var julianCenturies; - var mst; - julianDays = b + c + d - 730550.5 + day + (hour + minute / 60 + second / 3600) / 24; - julianCenturies = julianDays / 36525; - mst = 280.46061837 + 360.98564736629 * julianDays + 0.000387933 * julianCenturies * julianCenturies - julianCenturies * julianCenturies * julianCenturies / 38710000 + lng; - if (mst > 0) { - while (mst > 360) { - mst = mst - 360; - } - } - else { - while (mst < 0) { - mst = mst + 360; - } - } - return mst; - }; - Coordinates.cartesianToSpherical = function (vector) { - var ascention; - var declination; - var radius = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var XZ = Math.sqrt(vector.x * vector.x + vector.z * vector.z); - declination = Math.asin(vector.y / radius); - if (0 < vector.x) { - ascention = Math.asin(vector.z / XZ); - } - else if (0 > vector.x) { - ascention = Math.PI - Math.asin(vector.z / XZ); - } - else { - ascention = 0; - } - return new Coordinates(ascention, declination); - }; - Coordinates.cartesianToSpherical2 = function (vector) { - var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var longitude = Math.atan2(vector.z, vector.x); - var latitude = Math.asin(vector.y / rho); - return new Coordinates(longitude, latitude); - }; - Coordinates.cartesianToSphericalSky = function (vector) { - var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var ra = Math.atan2(vector.z, vector.x); - var dec = Math.asin(-vector.y / rho); - return Vector2d.create(ra / Math.PI * 12, dec / Math.PI * 180); - }; - Coordinates.sphericalSkyToCartesian = function (vector) { - var ra = vector.x * (Math.PI / 12); - var dec = vector.y * (Math.PI / 180); - var x = Math.cos(ra) * Math.cos(dec); - var y = -Math.sin(dec); - var z = Math.sin(ra) * Math.cos(dec); - return Vector3d.create(x, y, z); - }; - Coordinates.cartesianToLatLng = function (vector) { - var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var longitude = Math.atan2(vector.z, vector.x); - var latitude = Math.asin(vector.y / rho); - return Vector2d.create(longitude * 180 / Math.PI, latitude * 180 / Math.PI); - }; - Coordinates.cartesianToSpherical3 = function (vector) { - var rho = Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); - var longitude = Math.atan2(vector.z, vector.x); - var latitude = Math.asin(vector.y / rho); - return new Coordinates(longitude, latitude); - }; - Coordinates.sign = function (target) { - return (target < 0) ? -1 : 1; - }; - Coordinates.formatDMSSign = function (angle, sign) { - try { - angle += (Coordinates.sign(angle) * 0.0001388888888889); - var degrees = ss.truncate(angle); - var minutes = ((angle - ss.truncate(angle)) * 60); - var seconds = ((minutes - ss.truncate(minutes)) * 60); - if (sign) { - var signString = (angle > 0) ? '+' : '-'; - return ss.format('{3}{0:00;00}:{1:00}:{2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds)), signString); - } - else { - return ss.format('{0:00}:{1:00}:{2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds))); - } - } - catch ($e1) { - return ''; - } - }; - Coordinates.twoPlaces = function (val) { - var num = val.toString(); - if (num.length < 2) { - num = '0' + num; - } - return num; - }; - Coordinates.formatDMS = function (angle) { - try { - angle += (((angle < 0) ? -1 : 1) * 0.0001388888888889); - var degrees = Math.abs(ss.truncate(angle)); - var minutes = ((angle - ss.truncate(angle)) * 60); - var seconds = ((minutes - ss.truncate(minutes)) * 60); - var sign = (angle < 0) ? '-' : ''; - return ss.format('{3}{0}:{1}:{2}', Math.abs(degrees), Coordinates.twoPlaces(Math.abs(ss.truncate(minutes))), Coordinates.twoPlaces(Math.abs(ss.truncate(seconds))), sign); - } - catch ($e1) { - return ''; - } - }; - Coordinates.formatDMSWide = function (angle) { - try { - angle += (Coordinates.sign(angle) * 0.0001388888888889); - var degrees = Math.abs(ss.truncate(angle)); - var minutes = ((angle - ss.truncate(angle)) * 60); - var seconds = ((minutes - ss.truncate(minutes)) * 60); - var sign = (angle < 0) ? '-' : ''; - return ss.format('{3}{0:00} : {1:00} : {2:00}', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds)), sign); - } - catch ($e1) { - return ''; - } - }; - Coordinates.formatHMS = function (angle) { - try { - angle += (Coordinates.sign(angle) * 0.0001388888888889); - var degrees = ss.truncate(angle); - var minutes = ((angle - ss.truncate(angle)) * 60); - var seconds = ((minutes - ss.truncate(minutes)) * 60); - return ss.format('{0:00}h{1:00}m{2:00}s', degrees, Math.abs(ss.truncate(minutes)), Math.abs(ss.truncate(seconds))); - } - catch ($e1) { - return ''; - } - }; - Coordinates.parseRA = function (data, degrees) { - data = ss.trim(data).toLowerCase(); - if (data.indexOf('d') > -1 || data.indexOf('\u00b0') > -1) { - degrees = true; - } - if (data.indexOf('h') > -1 || data.indexOf(':') > -1) { - degrees = false; - } - var ra = Coordinates.parse(data) / ((degrees) ? 15 : 1); - return Math.max(Math.min(ra, 24), 0); - }; - Coordinates.parseDec = function (data) { - var dec = Coordinates.parse(data); - return Math.max(Math.min(dec, 90), -90); - }; - Coordinates.parse = function (data) { - try { - data = ss.trim(data).toLowerCase(); - data = ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(ss.replaceString(data, 'd ', 'd'), 'h ', 'h'), 'm ', 'm'), 's ', 's'), "' ", "'"), '" ', '"'); - if (Util.stringContains(data, [':', ' ', 'd', 'h', 'm', 's', "'", '"', '\u00b0'])) { - var hours = 0; - var minutes = 0; - var seconds = 0; - var sign = 0; - var parts = Util.splitString(data, [':', ' ', 'd', 'h', 'm', 's', "'", '"', '\u00b0']); - if (parts.length > 0) { - if (!ss.emptyString(parts[0])) { - hours = Math.abs(parseFloat(parts[0])); - sign = (parseFloat(parts[0]) < 0) ? -1 : 1; - if (parts[0].indexOf('-') > -1) { - sign = -1; - } - } - } - if (parts.length > 1) { - if (!ss.emptyString(parts[1])) { - minutes = parseFloat(parts[1]); - } - } - if (parts.length > 2) { - if (!ss.emptyString(parts[2])) { - seconds = parseFloat(parts[2]); - } - } - if (!sign) { - sign = 1; - } - return sign * (hours + minutes / 60 + seconds / 3600); - } - else { - var val = 0; - try { - val = parseFloat(data); - } - catch ($e1) { - val = 0; - } - return val; - } - } - catch ($e2) { - return 0; - } - }; - Coordinates.fromRaDec = function (ra, dec) { - return new Coordinates((ra - 12) * 15 * Coordinates.RC, dec * Coordinates.RC); - }; - Coordinates.fromLatLng = function (lat, lng) { - return new Coordinates(lng * Coordinates.RC, lat * Coordinates.RC); - }; - Coordinates.dmsToDegrees = function (Degrees, Minutes, Seconds) { - return Degrees + Minutes / 60 + Seconds / 3600; - }; - Coordinates.degreesToRadians = function (Degrees) { - return Degrees * 0.0174532925199433; - }; - Coordinates.radiansToDegrees = function (Radians) { - return Radians * 57.2957795130823; - }; - Coordinates.radiansToHours = function (Radians) { - return Radians * 3.81971863420549; - }; - Coordinates.hoursToRadians = function (Hours) { - return Hours * 0.261799387799149; - }; - Coordinates.hoursToDegrees = function (Hours) { - return Hours * 15; - }; - Coordinates.degreesToHours = function (Degrees) { - return Degrees / 15; - }; - Coordinates.PI = function () { - return 3.14159265358979; - }; - Coordinates.mapTo0To360Range = function (Degrees) { - var Value = Degrees; - while (Value < 0) { - Value += 360; - } - while (Value > 360) { - Value -= 360; - } - return Value; - }; - Coordinates.mapTo0To24Range = function (HourAngle) { - var Value = HourAngle; - while (Value < 0) { - Value += 24; - } - while (Value > 24) { - Value -= 24; - } - return Value; - }; - Coordinates.meanObliquityOfEcliptic = function (JD) { - var U = (JD - 2451545) / 3652500; - var Usquared = U * U; - var Ucubed = Usquared * U; - var U4 = Ucubed * U; - var U5 = U4 * U; - var U6 = U5 * U; - var U7 = U6 * U; - var U8 = U7 * U; - var U9 = U8 * U; - var U10 = U9 * U; - return Coordinates.dmsToDegrees(23, 26, 21.448) - Coordinates.dmsToDegrees(0, 0, 4680.93) * U - Coordinates.dmsToDegrees(0, 0, 1.55) * Usquared + Coordinates.dmsToDegrees(0, 0, 1999.25) * Ucubed - Coordinates.dmsToDegrees(0, 0, 51.38) * U4 - Coordinates.dmsToDegrees(0, 0, 249.67) * U5 - Coordinates.dmsToDegrees(0, 0, 39.05) * U6 + Coordinates.dmsToDegrees(0, 0, 7.12) * U7 + Coordinates.dmsToDegrees(0, 0, 27.87) * U8 + Coordinates.dmsToDegrees(0, 0, 5.79) * U9 + Coordinates.dmsToDegrees(0, 0, 2.45) * U10; - }; - Coordinates.j2000toGalactic = function (J2000RA, J2000DEC) { - var J2000pos = [Math.cos(J2000RA / 180 * Math.PI) * Math.cos(J2000DEC / 180 * Math.PI), Math.sin(J2000RA / 180 * Math.PI) * Math.cos(J2000DEC / 180 * Math.PI), Math.sin(J2000DEC / 180 * Math.PI)]; - if (Coordinates._rotationMatrix == null) { - Coordinates._rotationMatrix = new Array(3); - Coordinates._rotationMatrix[0] = [-0.0548755604, -0.8734370902, -0.4838350155]; - Coordinates._rotationMatrix[1] = [0.4941094279, -0.44482963, 0.7469822445]; - Coordinates._rotationMatrix[2] = [-0.867666149, -0.1980763734, 0.4559837762]; - } - var Galacticpos = new Array(3); - for (var i = 0; i < 3; i++) { - Galacticpos[i] = J2000pos[0] * Coordinates._rotationMatrix[i][0] + J2000pos[1] * Coordinates._rotationMatrix[i][1] + J2000pos[2] * Coordinates._rotationMatrix[i][2]; - } - var GalacticL2 = Math.atan2(Galacticpos[1], Galacticpos[0]); - if (GalacticL2 < 0) { - GalacticL2 = GalacticL2 + 2 * Math.PI; - } - if (GalacticL2 > 2 * Math.PI) { - GalacticL2 = GalacticL2 - 2 * Math.PI; - } - var GalacticB2 = Math.atan2(Galacticpos[2], Math.sqrt(Galacticpos[0] * Galacticpos[0] + Galacticpos[1] * Galacticpos[1])); - return [GalacticL2 / Math.PI * 180, GalacticB2 / Math.PI * 180]; - }; - Coordinates.galacticTo3dDouble = function (l, b) { - var result = Coordinates.galactictoJ2000(l, b); - return Coordinates.raDecTo3dAu(result[0] / 15, result[1], 1); - }; - Coordinates.galactictoJ2000 = function (GalacticL2, GalacticB2) { - var Galacticpos = [Math.cos(GalacticL2 / 180 * Math.PI) * Math.cos(GalacticB2 / 180 * Math.PI), Math.sin(GalacticL2 / 180 * Math.PI) * Math.cos(GalacticB2 / 180 * Math.PI), Math.sin(GalacticB2 / 180 * Math.PI)]; - if (Coordinates._rotationMatrix == null) { - Coordinates._rotationMatrix = new Array(3); - Coordinates._rotationMatrix[0] = [-0.0548755604, -0.8734370902, -0.4838350155]; - Coordinates._rotationMatrix[1] = [0.4941094279, -0.44482963, 0.7469822445]; - Coordinates._rotationMatrix[2] = [-0.867666149, -0.1980763734, 0.4559837762]; - } - var J2000pos = new Array(3); - for (var i = 0; i < 3; i++) { - J2000pos[i] = Galacticpos[0] * Coordinates._rotationMatrix[0][i] + Galacticpos[1] * Coordinates._rotationMatrix[1][i] + Galacticpos[2] * Coordinates._rotationMatrix[2][i]; - } - var J2000RA = Math.atan2(J2000pos[1], J2000pos[0]); - if (J2000RA < 0) { - J2000RA = J2000RA + 2 * Math.PI; - } - if (J2000RA > 2 * Math.PI) { - J2000RA = J2000RA - 2 * Math.PI; - } - var J2000DEC = Math.atan2(J2000pos[2], Math.sqrt(J2000pos[0] * J2000pos[0] + J2000pos[1] * J2000pos[1])); - return [J2000RA / Math.PI * 180, J2000DEC / Math.PI * 180]; - }; - var Coordinates$ = { - distance: function (pointB) { - var y = this.get_lat(); - var x = this.get_lng() * Math.cos(y * Coordinates.RC); - var y1 = pointB.get_lat(); - var x1 = pointB.get_lng() * Math.cos(y1 * Coordinates.RC); - return Math.sqrt((y - y1) * (y - y1) + (x - x1) * (x - x1)); - }, - distance3d: function (pointB) { - var pnt1 = Coordinates.geoTo3dDouble(pointB.get_lat(), pointB.get_lng()); - var pnt2 = Coordinates.geoTo3dDouble(this.get_lat(), this.get_lng()); - var pntDiff = Vector3d.subtractVectors(pnt1, pnt2); - return pntDiff.length() / Coordinates.RC; - }, - angle: function (pointB) { - var y = this.get_lat(); - var x = this.get_lng() * Math.cos(y * Coordinates.RC); - var y1 = pointB.get_lat(); - var x1 = pointB.get_lng() * Math.cos(y1 * Coordinates.RC); - return Math.atan2((y1 - y), (x1 - x)); - }, - get_RA: function () { - return (((this._ascention / Math.PI) * 12) + 12) % 24; - }, - set_RA: function (value) { - this._ascention = (value / 12) * Math.PI; - return value; - }, - get_dec: function () { - return this._declination / Coordinates.RC; - }, - set_dec: function (value) { - this._declination = value * Coordinates.RC; - return value; - }, - get_lat: function () { - return this._declination / Coordinates.RC; - }, - set_lat: function (value) { - this._declination = value * Coordinates.RC; - return value; - }, - get_lng: function () { - var lng = this._ascention / Coordinates.RC; - if (lng <= 180) { - return lng; - } - else { - return (-180 + (180 - lng)); - } - }, - set_lng: function (value) { - this._ascention = ((value * Coordinates.RC) + (Math.PI * 2) % (Math.PI * 2)); - return value; - }, - get_alt: function () { - return this._declination / Coordinates.RC; - }, - set_alt: function (value) { - this._declination = value * Coordinates.RC; - return value; - }, - get_az: function () { - return this._ascention / Coordinates.RC; - }, - set_az: function (value) { - this._ascention = value * Coordinates.RC; - return value; - }, - toString: function () { - return ss.format('Lat: {0}, Lng: {1}', this.get_lat(), this.get_lng()); - } - }; - - - // wwtlib.Fxyf - - function Fxyf() { - this.fx = 0; - this.fy = 0; - this.face = 0; - HealpixTables.call(this); - } - Fxyf.create = function (x, y, f) { - var temp = new Fxyf(); - temp.fx = x; - temp.fy = y; - temp.face = f; - return temp; - }; - Fxyf._fromHploc$1 = function (loc) { - var temp = new Fxyf(); - var z = loc.z, phi = loc.phi; - var za = Math.abs(z); - var tt = HealpixUtils.fmodulo((phi * Fxyf._inv_halfpi$1), 4); - if (za <= Fxyf._twothird$1) { - var temp1 = 0.5 + tt; - var temp2 = z * 0.75; - var jp = temp1 - temp2; - var jm = temp1 + temp2; - var ifp = jp; - var ifm = jm; - var face_num = (ifp === ifm) ? (ifp | 4) : ((ifp < ifm) ? ifp : (ifm + 8)); - temp.fx = HealpixUtils.fmodulo(jm, 1); - temp.fy = 1 - HealpixUtils.fmodulo(jp, 1); - temp.face = face_num; - } - else { - var ntt = Math.min(3, ss.truncate(tt)); - var tp = tt - ntt; - var tmp; - if ((za < 0.99) || (!loc.have_sth)) { - tmp = Math.sqrt(3 * (1 - za)); - } - else { - tmp = loc.sth / Math.sqrt((1 + za) / 3); - } - var jp = tp * tmp; - var jm = (1 - tp) * tmp; - if (jp >= 1) { - jp = 1; - } - if (jm >= 1) { - jm = 1; - } - if (z >= 0) { - temp.fx = 1 - jm; - temp.fy = 1 - jp; - temp.face = ntt; - } - else { - temp.fx = jp; - temp.fy = jm; - temp.face = ntt + 8; - } - } - return temp; - }; - Fxyf.fromVector = function (v) { - return Fxyf._fromHploc$1(Hploc.create(v)); - }; - var Fxyf$ = { - toHploc: function () { - var loc = new Hploc(); - var jr = HealpixTables.jrll[this.face] - this.fx - this.fy; - var nr; - var tmp; - if (jr < 1) { - nr = jr; - tmp = nr * nr / 3; - loc.z = 1 - tmp; - if (loc.z > 0.99) { - loc.sth = Math.sqrt(tmp * (2 - tmp)); - loc.have_sth = true; - } - } - else if (jr > 3) { - nr = 4 - jr; - tmp = nr * nr / 3; - loc.z = tmp - 1; - if (loc.z < -0.99) { - loc.sth = Math.sqrt(tmp * (2 - tmp)); - loc.have_sth = true; - } - } - else { - nr = 1; - loc.z = (2 - jr) * 2 / 3; - } - tmp = HealpixTables.jpll[this.face] * nr + this.fx - this.fy; - if (tmp < 0) { - tmp += 8; - } - if (tmp >= 8) { - tmp -= 8; - } - loc.phi = (nr < 1E-15) ? 0 : (0.5 * Fxyf._halfpi$1 * tmp) / nr; - return loc; - }, - toVec3: function () { - return this.toHploc().toVec3(); - } - }; - - - // wwtlib.HealpixTile - - function HealpixTile(level, x, y, dataset, parent) { - this.ipix = 0; - this.indexBuffer = new Array(4); - this._vertexList$1 = null; - this._nside$1 = 0; - this._tileIndex$1 = 0; - this._face$1 = 0; - this._faceX$1 = 0; - this._faceY$1 = 0; - this._step$1 = 0; - this._subDivided$1 = false; - this._catalogRows$1 = []; - Tile.call(this); - this.level = level; - this.tileX = x; - this.tileY = y; - this.dataset = dataset; - Tile.demEnabled = false; - if (!level) { - this._nside$1 = 4; - } - else { - this._nside$1 = Math.pow(2, level + 1); - } - if (parent == null) { - this._face$1 = x * 4 + y; - this.ipix = this._face$1; - } - else { - this.parent = parent; - var parentTile = parent; - this._face$1 = parentTile._face$1; - this._tileIndex$1 = parentTile._tileIndex$1 * 4 + y * 2 + x; - this.ipix = this._face$1 * this._nside$1 * this._nside$1 / 4 + this._tileIndex$1; - this._faceX$1 = parentTile._faceX$1 * 2 + x; - this._faceY$1 = parentTile._faceY$1 * 2 + y; - } - this.isCatalogTile = ss.keyExists(dataset.get_hipsProperties().get_properties(), 'dataproduct_type') && dataset.get_hipsProperties().get_properties()['dataproduct_type'].toLowerCase() === 'catalog'; - this._computeBoundingSphere$1(); - } - var HealpixTile$ = { - get_URL: function () { - if (this._url$1 == null) { - this._url$1 = this._getUrl$1(this.dataset, this.level, this.tileX, this.tileY); - return this._url$1; - } - else { - return this._url$1; - } - }, - _computeBoundingSphere$1: function () { - this._setStep$1(); - this.createGeometry(null); - var pointList = new Array(this._vertexList$1.length); - for (var i = 0; i < this._vertexList$1.length; i++) { - pointList[i] = this._vertexList$1[i].position; - } - this._calcSphere$1(pointList); - this._setCorners$1(); - }, - createGeometry: function (renderContext) { - if (this._vertexList$1 != null) { - return true; - } - this._vertexList$1 = []; - this._populateVertexList$1(this._vertexList$1, this._step$1); - if (ss.keyExists(this.dataset.get_hipsProperties().get_properties(), 'hips_frame') && this.dataset.get_hipsProperties().get_properties()['hips_frame'] === 'galactic') { - for (var i = 0; i < this._vertexList$1.length; i++) { - var vert = this._vertexList$1[i]; - HealpixTile._galacticMatrix$1.multiplyVector(vert.position); - } - } - this.triangleCount = this._step$1 * this._step$1 / 2; - var ui16array = new Uint16Array(3 * this.triangleCount); - var indexArray = ui16array; - if (!this._subDivided$1) { - try { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(this._vertexList$1.length * 5); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._vertexList$1); - while ($enum1.moveNext()) { - var vert = $enum1.current; - index = this.addVertex(buffer, index, vert); - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - index = 0; - var offset = this._vertexList$1.length / (4 * this._step$1); - this._setIndexBufferForQuadrant$1(indexArray, 0, 1); - if (this._step$1 > 1) { - this._setIndexBufferForQuadrant$1(indexArray, 0, 0); - this._setIndexBufferForQuadrant$1(indexArray, 1, 1); - this._setIndexBufferForQuadrant$1(indexArray, 1, 0); - } - } - catch (exception) { - } - } - return true; - }, - _setIndexBufferForQuadrant$1: function (indexArray, x, y) { - var index = 0; - for (var i = x * this._step$1 / 2; i < (this._step$1 / 2) * (x + 1); i++) { - for (var j = y * this._step$1 / 2; j < (this._step$1 / 2) * (y + 1); j++) { - indexArray[index++] = (i * (this._step$1 + 1) + j); - indexArray[index++] = (1 + i * (this._step$1 + 1) + j); - indexArray[index++] = (this._step$1 + 1 + i * (this._step$1 + 1) + j); - indexArray[index++] = (1 + i * (this._step$1 + 1) + j); - indexArray[index++] = (this._step$1 + 1 + i * (this._step$1 + 1) + j); - indexArray[index++] = (this._step$1 + 2 + i * (this._step$1 + 1) + j); - } - } - this._processIndexBuffer$1(indexArray, x * 2 + y); - }, - _getUrl$1: function (dataset, level, x, y) { - var extension = this._getHipsFileExtension$1(); - var tileTextureIndex = -1; - if (!level) { - tileTextureIndex = this._face$1; - } - else { - tileTextureIndex = this._face$1 * this._nside$1 * this._nside$1 / 4 + this._tileIndex$1; - } - var sb = new ss.StringBuilder(); - var subDirIndex = Math.floor(tileTextureIndex / 10000) * 10000; - return ss.format(dataset.get_url(), level.toString(), subDirIndex.toString(), tileTextureIndex.toString() + extension); - }, - _getHipsFileExtension$1: function () { - if (this.dataset.get_extension().toLowerCase().indexOf('png') > -1) { - return '.png'; - } - if (this.dataset.get_extension().toLowerCase().indexOf('jpeg') > -1 || this.dataset.get_extension().toLowerCase().indexOf('jpg') > -1) { - return '.jpg'; - } - if (this.dataset.get_extension().toLowerCase().indexOf('tsv') > -1) { - return '.tsv'; - } - if (this.dataset.get_extension().toLowerCase().indexOf('fits') > -1) { - return '.fits'; - } - return '.jpg'; - }, - isTileBigEnough: function (renderContext) { - if (this.dataset.get_dataSetType() === 1) { - var arcPixels = (180 / (Math.pow(2, this.level) * 4)); - return (renderContext.get_fovScale() < arcPixels); - } - else { - var arcPixels = (3600 / (Math.pow(2, this.level) * 4)); - return (renderContext.get_fovScale() < arcPixels); - } - }, - _boundaries$1: function (x, y, step) { - var nside = step * Math.pow(2, this.level); - var points = new Array(4); - var xyf = Xyf.create(x + this._faceX$1 * step, y + this._faceY$1 * step, this._face$1); - var dc = 0.5 / nside; - var xc = (xyf.ix + 0.5) / nside; - var yc = (xyf.iy + 0.5) / nside; - points[0] = Fxyf.create(xc + dc, yc + dc, xyf.face).toVec3(); - points[1] = Fxyf.create(xc - dc, yc + dc, xyf.face).toVec3(); - points[2] = Fxyf.create(xc - dc, yc - dc, xyf.face).toVec3(); - points[3] = Fxyf.create(xc + dc, yc - dc, xyf.face).toVec3(); - return points; - }, - _setCorners$1: function () { - var xyf = Xyf.create(this.tileX, this.tileY, this._face$1); - var dc = 0.5 / this._nside$1; - var xc = (xyf.ix + 0.5) / this._nside$1; - var yc = (xyf.iy + 0.5) / this._nside$1; - this.topLeft = Fxyf.create(xc + dc, yc + dc, xyf.face).toVec3(); - this.bottomLeft = Fxyf.create(xc - dc, yc + dc, xyf.face).toVec3(); - this.bottomRight = Fxyf.create(xc - dc, yc - dc, xyf.face).toVec3(); - this.topRight = Fxyf.create(xc + dc, yc - dc, xyf.face).toVec3(); - }, - draw3D: function (renderContext, opacity) { - if (this.isCatalogTile) { - this.drawCatalogTile(renderContext, opacity); - return true; - } - this.renderedGeneration = Tile.currentRenderGeneration; - Tile.tilesTouched++; - this.inViewFrustum = true; - var onlyDrawChildren = false; - if (!this.readyToRender) { - if (!this.errored) { - TileCache.addTileToQueue(this); - return false; - } - if (this.errored && this.level < 3) { - onlyDrawChildren = true; - } - else { - return false; - } - } - var partCount = this.triangleCount; - Tile.trianglesRendered += partCount; - var anythingToRender = false; - var childRendered = false; - var childIndex = 0; - for (var y1 = 0; y1 < 2; y1++) { - for (var x1 = 0; x1 < 2; x1++) { - if (this.level < this.dataset.get_levels()) { - if (this.children[childIndex] == null) { - this.children[childIndex] = TileCache.getTile(this.level + 1, x1, y1, this.dataset, this); - } - if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { - this.inViewFrustum = true; - if (this.children[childIndex].isTileBigEnough(renderContext) || onlyDrawChildren) { - this.renderChildPart[childIndex].set_targetState(!this.children[childIndex].draw3D(renderContext, opacity)); - if (this.renderChildPart[childIndex].get_targetState()) { - childRendered = true; - } - } - else { - this.renderChildPart[childIndex].set_targetState(true); - } - } - else { - this.renderChildPart[childIndex].set_targetState(this.renderChildPart[childIndex].set_state(false)); - } - } - else { - this.renderChildPart[childIndex].set_state(true); - } - if (!!this.renderChildPart[childIndex].get_state()) { - anythingToRender = true; - } - childIndex++; - } - } - if (childRendered || anythingToRender) { - this.renderedAtOrBelowGeneration = Tile.currentRenderGeneration; - if (this.parent != null) { - this.parent.renderedAtOrBelowGeneration = this.renderedAtOrBelowGeneration; - } - } - if (!anythingToRender) { - return true; - } - if (!this.createGeometry(renderContext)) { - return false; - } - if (onlyDrawChildren) { - return true; - } - Tile.tilesInView++; - for (var i = 0; i < 4; i++) { - if (this.renderChildPart[i].get_targetState()) { - this.renderPart(renderContext, i, opacity / 100, false); - } - } - return true; - }, - drawCatalogTile: function (renderContext, opacity) { - this.renderedGeneration = Tile.currentRenderGeneration; - Tile.tilesTouched++; - this.inViewFrustum = true; - var onlyDrawChildren = false; - if (!this.readyToRender) { - if (!this.errored) { - TileCache.addTileToQueue(this); - return; - } - if (this.errored && this.level < 3) { - onlyDrawChildren = true; - } - else { - return; - } - } - var anyChildInFrustum = false; - var childIndex = 0; - for (var y1 = 0; y1 < 2; y1++) { - for (var x1 = 0; x1 < 2; x1++) { - if (this.level < this.dataset.get_levels()) { - if (this.children[childIndex] == null) { - this.children[childIndex] = TileCache.getTile(this.level + 1, x1, y1, this.dataset, this); - } - if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { - this.inViewFrustum = true; - anyChildInFrustum = true; - if (this.children[childIndex].isTileBigEnough(renderContext) || onlyDrawChildren) { - (this.children[childIndex]).drawCatalogTile(renderContext, opacity); - } - else { - (this.children[childIndex]).removeCatalogTile(); - } - } - else { - (this.children[childIndex]).removeCatalogTile(); - } - } - childIndex++; - } - } - if (!this.level && !anyChildInFrustum && !onlyDrawChildren) { - this.removeCatalogTile(); - } - else if (anyChildInFrustum) { - Tile.tilesInView++; - this._addCatalogTile$1(); - } - }, - removeCatalogTile: function () { - this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().removeTileRows(this.get_key(), this._catalogRows$1); - }, - _addCatalogTile$1: function () { - this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().addTileRows(this.get_key(), this._catalogRows$1); - }, - _extractCatalogTileRows$1: function () { - var headerRemoved = false; - var $enum1 = ss.enumerate(this._catalogData$1.getText().split('\n')); - while ($enum1.moveNext()) { - var line = $enum1.current; - if (!ss.startsWith(line, '#') && !headerRemoved) { - headerRemoved = true; - continue; - } - if (!ss.startsWith(line, '#')) { - var rowData = UiTools.splitString(line, this.dataset.get_hipsProperties().get_catalogSpreadSheetLayer().get__table().delimiter); - this._catalogRows$1.push(rowData); - } - } - }, - getDataInView: function (renderContext, limit, catalogSpreadSheetLayer) { - if (!this.readyToRender) { - if (!this.errored) { - this.requestImage(); - if (limit) { - return false; - } - } - else if (this.level >= 3) { - return true; - } - } - var allChildrenReady = true; - var anyChildInFrustum = false; - var childIndex = 0; - for (var y1 = 0; y1 < 2; y1++) { - for (var x1 = 0; x1 < 2; x1++) { - if (this.level < this.dataset.get_levels()) { - if (this.children[childIndex] == null) { - this.children[childIndex] = TileCache.getTile(this.level + 1, x1, y1, this.dataset, this); - } - if (this.children[childIndex].isTileInFrustum(renderContext.get_frustum())) { - anyChildInFrustum = true; - allChildrenReady = allChildrenReady && (this.children[childIndex]).getDataInView(renderContext, limit, catalogSpreadSheetLayer); - } - } - childIndex++; - } - } - if (anyChildInFrustum) { - catalogSpreadSheetLayer.addTileRows(this.get_key(), this._catalogRows$1); - } - return allChildrenReady && !this.downloading; - }, - _setStep$1: function () { - if (this.isCatalogTile) { - this._step$1 = 2; - } - else { - switch (this.level) { - case 0: - case 1: - case 2: - case 3: - case 4: - this._step$1 = 16; - break; - case 5: - this._step$1 = 8; - break; - case 6: - this._step$1 = 4; - break; - default: - this._step$1 = 2; - break; - } - } - }, - requestImage: function () { - if (this.isCatalogTile) { - if (!this.downloading && !this.readyToRender) { - this.downloading = true; - this._catalogData$1 = new WebFile(this.get_URL()); - this._catalogData$1.onStateChange = ss.bind('_loadCatalogData$1', this); - this._catalogData$1.send(); - } - } - else { - Tile.prototype.requestImage.call(this); - } - }, - _loadCatalogData$1: function () { - if (this._catalogData$1.get_state() === 2) { - this.requestPending = false; - this.downloading = false; - this.errored = true; - TileCache.removeFromQueue(this.get_key(), true); - } - else if (this._catalogData$1.get_state() === 1) { - this._extractCatalogTileRows$1(); - this.texReady = true; - this.downloading = false; - this.errored = false; - this.readyToRender = true; - this.requestPending = false; - TileCache.removeFromQueue(this.get_key(), true); - } - }, - getIndexBuffer: function (index, accomidation) { - return this.indexBuffer[index]; - }, - _calcSphere$1: function (list) { - var result = ConvexHull.findEnclosingSphere(list); - this.sphereCenter = result.center; - this.sphereRadius = result.radius; - }, - isPointInTile: function (lat, lng) { - if (!this.level) { - return true; - } - if (this.level === 1) { - if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { - return true; - } - if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { - return true; - } - if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { - return true; - } - if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { - return true; - } - } - var testPoint = Coordinates.geoTo3dDouble(lat, lng); - var top = this._isLeftOfHalfSpace$1(this.topLeft, this.topRight, testPoint); - var right = this._isLeftOfHalfSpace$1(this.topRight, this.bottomRight, testPoint); - var bottom = this._isLeftOfHalfSpace$1(this.bottomRight, this.bottomLeft, testPoint); - var left = this._isLeftOfHalfSpace$1(this.bottomLeft, this.topLeft, testPoint); - if (top && right && bottom && left) { - return true; - } - return false; - }, - _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { - pntA.normalize(); - pntB.normalize(); - var cross = Vector3d.cross(pntA, pntB); - var dot = Vector3d.dot(cross, pntTest); - return dot > 0; - }, - getSurfacePointAltitude: function (lat, lng, meters) { - if (this.level < Tile.lastDeepestLevel) { - var $enum1 = ss.enumerate(this.children); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child != null) { - if (child.isPointInTile(lat, lng)) { - var retVal = child.getSurfacePointAltitude(lat, lng, meters); - if (!!retVal) { - return retVal; - } - else { - break; - } - } - } - } - } - return this._getAltitudeFromLatLng$1(lat, lng, meters); - }, - _getAltitudeFromLatLng$1: function (lat, lng, meters) { - var testPoint = Coordinates.geoTo3dDouble(lat, lng); - var uv = DistanceCalc.getUVFromInnerPoint(this.topLeft, this.topRight, this.bottomLeft, this.bottomRight, testPoint); - var uud = Math.max(0, Math.min(16, (uv.x * 16))); - var vvd = Math.max(0, Math.min(16, (uv.y * 16))); - var uu = Math.max(0, Math.min(15, ss.truncate((uv.x * 16)))); - var vv = Math.max(0, Math.min(15, ss.truncate((uv.y * 16)))); - var ha = uud - uu; - var va = vvd - vv; - if (this.demArray != null) { - var ul = this.demArray[uu + 17 * vv]; - var ur = this.demArray[(uu + 1) + 17 * vv]; - var ll = this.demArray[uu + 17 * (vv + 1)]; - var lr = this.demArray[(uu + 1) + 17 * (vv + 1)]; - var top = ul * (1 - ha) + ha * ur; - var bottom = ll * (1 - ha) + ha * lr; - var val = top * (1 - va) + va * bottom; - return val / ((meters) ? 1 : this.get__demScaleFactor()); - } - return this.demAverage / ((meters) ? 1 : this.get__demScaleFactor()); - }, - _processIndexBuffer$1: function (indexArray, part) { - this.indexBuffer[part] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this.indexBuffer[part]); - Tile.prepDevice.bufferData(34963, indexArray, 35044); - }, - cleanUp: function (removeFromParent) { - Tile.prototype.cleanUp.call(this, removeFromParent); - this._returnBuffers$1(); - this._subDivided$1 = false; - }, - _returnBuffers$1: function () { - if (this._vertexList$1 != null) { - this._vertexList$1 = null; - } - }, - _populateVertexList$1: function (vertexList, step) { - for (var i = 0; i < step; i += 2) { - for (var j = 0; j < step; j += 2) { - var points = this._boundaries$1(j, i, step); - vertexList[i * (step + 1) + j] = PositionTexture.createPos(points[2], (1 / step) * i, (1 / step) * j); - vertexList[i * (step + 1) + j + 1] = PositionTexture.createPos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j] = PositionTexture.createPos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - if (j + 2 >= step && step > 1) { - j = step - 1; - points = this._boundaries$1(j, i, step); - vertexList[i * (step + 1) + step] = PositionTexture.createPos(points[3], (1 / step) * i, (1 / step) + (1 / step) * j); - vertexList[(i + 1) * (step + 1) + step] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - } - } - } - if (step > 1) { - this._vertexOfLastRow$1(vertexList, step); - } - }, - _vertexOfLastRow$1: function (vertexList, step) { - var i = step - 1; - for (var j = 0; j < step; j += 2) { - var points = this._boundaries$1(j, i, step); - vertexList[(i + 1) * (step + 1) + j] = PositionTexture.createPos(points[1], (1 / step) + (1 / step) * i, (1 / step) * j); - vertexList[(i + 1) * (step + 1) + j + 1] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - if (j + 2 >= step) { - j = step - 1; - points = this._boundaries$1(j, i, step); - vertexList[(i + 1) * (step + 1) + step] = PositionTexture.createPos(points[0], (1 / step) + (1 / step) * i, (1 / step) + (1 / step) * j); - } - } - } - }; - - - // wwtlib.FitsImage - - function FitsImage(dataset, file, blob, callMeBack) { - this.errored = false; - this.numAxis = 0; - this.histogramMaxCount = 0; - this.sourceBlob = null; - this.header = {}; - this.position = 0; - this.bufferSize = 1; - this._parseSuccessful$1 = false; - WcsImage.call(this); - this.dataset = dataset; - this.fitsProperties = dataset.get_fitsProperties(); - this._callBack$1 = callMeBack; - this.filename = file; - if (blob != null) { - this._readFromBlob$1(blob); - } - else { - this.getFile(file); - } - } - var FitsImage$ = { - getFile: function (url) { - this._webFile$1 = new WebFile(url); - this._webFile$1.responseType = 'blob'; - this._webFile$1.onStateChange = ss.bind('fileStateChange', this); - this._webFile$1.send(); - }, - fileStateChange: function () { - if (this._webFile$1.get_state() === 2) { - this.errored = true; - if (this._callBack$1 != null) { - this._callBack$1(this); - } - } - else if (this._webFile$1.get_state() === 1) { - var mainBlob = this._webFile$1.getBlob(); - this._readFromBlob$1(mainBlob); - } - }, - _readFromBlob$1: function (blob) { - var $this = this; - - this.sourceBlob = blob; - var chunck = new FileReader(); - chunck.onloadend = function (e) { - $this.readFromBin(new DataView(chunck.result)); - $this.errored = !$this._parseSuccessful$1; - if ($this._callBack$1 != null) { - $this._callBack$1($this); - } - }; - chunck.readAsArrayBuffer(blob); - }, - _readByteString$1: function (dataView, count) { - var data = ''; - for (var i = 0; i < count; i++) { - data += String.fromCharCode(dataView.getUint8(this.position)); - this.position++; - } - return data; - }, - _validateFitsSimple$1: function (dataView) { - var data = this._readByteString$1(dataView, 8); - var keyword = ss.trimEnd(data); - this.position -= 8; - return keyword.toUpperCase() === 'SIMPLE'; - }, - readFromBin: function (dataView) { - if (!this._validateFitsSimple$1(dataView)) { - console.log('The requested file is not a valid FITS file.'); - return; - } - var foundEnd = false; - while (!foundEnd) { - for (var i = 0; i < 36; i++) { - var data = this._readByteString$1(dataView, 80); - if (!foundEnd) { - var keyword = ss.trimEnd(data.substring(0, 8)); - var values = data.substring(10).split('/'); - if (keyword.toUpperCase() === 'END') { - foundEnd = true; - i++; - data = this._readByteString$1(dataView, 80); - while (ss.whitespace(data)) { - i++; - data = this._readByteString$1(dataView, 80); - } - keyword = ss.trimEnd(data.substring(0, 8)); - if (keyword.toUpperCase() === 'XTENSION') { - foundEnd = false; - } - else { - this.position -= 80; - } - } - else { - this._addKeyword$1(keyword, values); - } - } - } - } - if (!foundEnd) { - console.log('Unable to parse requested FITS file.'); - return; - } - this.numAxis = parseInt(this.header['NAXIS']); - if (ss.keyExists(this.header, 'BLANK')) { - this.fitsProperties.blankValue = parseFloat(this.header['BLANK']); - this.fitsProperties.containsBlanks = true; - } - if (ss.keyExists(this.header, 'BZERO')) { - this.fitsProperties.bZero = parseFloat(this.header['BZERO']); - } - if (ss.keyExists(this.header, 'BSCALE')) { - this.fitsProperties.bScale = parseFloat(this.header['BSCALE']); - } - this.axisSize = new Array(this.numAxis); - for (var axis = 0; axis < this.numAxis; axis++) { - this.axisSize[axis] = parseInt(this.header[ss.format('NAXIS{0}', axis + 1)]); - this.bufferSize *= this.axisSize[axis]; - } - var bitpix = parseInt(this.header['BITPIX']); - this.readDataUnit(dataView, bitpix); - if (this.numAxis > 1) { - this.sizeX = this.axisSize[0]; - this.sizeY = this.axisSize[1]; - this.histogram = this.computeHistogram(256); - this.histogramMaxCount = this.histogram[256]; - } - this.computeWcs(); - this._parseSuccessful$1 = true; - }, - _addKeyword$1: function (keyword, values) { - if (keyword !== 'CONTINUE' && keyword !== 'COMMENT' && keyword !== 'HISTORY' && !ss.emptyString(keyword)) { - try { - if (ss.keyExists(this.header, keyword)) { - this.header[keyword] = ss.trim(values[0]); - } - else { - this.header[keyword.toUpperCase()] = ss.trim(values[0]); - } - } - catch ($e1) { - } - } - }, - readDataUnit: function (dataView, bitpix) { - this.dataUnit = new Float32Array(this.bufferSize); - switch (bitpix) { - case -64: - this.readDataUnitFloat64(dataView); - break; - case -32: - this.readDataUnitFloat32(dataView); - break; - case 8: - this.readDataUnitUint8(dataView); - break; - case 16: - this.readDataUnitInt16(dataView); - break; - case 32: - this.readDataUnitInt32(dataView); - break; - case 64: - console.log('64 bit integer FITS are not yet supported'); - break; - } - }, - readDataUnitFloat64: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getFloat64(this.position, false); - var physicalValue = this.dataUnit[i] * this.fitsProperties.bScale + this.fitsProperties.bZero; - if (this.fitsProperties.minVal > physicalValue) { - this.fitsProperties.minVal = physicalValue; - } - if (this.fitsProperties.maxVal < physicalValue) { - this.fitsProperties.maxVal = physicalValue; - } - i++; - this.position += 8; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - readDataUnitFloat32: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getFloat32(this.position, false); - var physicalValue = this.dataUnit[i] * this.fitsProperties.bScale + this.fitsProperties.bZero; - if (this.fitsProperties.minVal > physicalValue) { - this.fitsProperties.minVal = physicalValue; - } - if (this.fitsProperties.maxVal < physicalValue) { - this.fitsProperties.maxVal = physicalValue; - } - i++; - this.position += 4; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - readDataUnitUint8: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getUint8(this.position); - if (this.fitsProperties.minVal > this.dataUnit[i]) { - this.fitsProperties.minVal = this.dataUnit[i]; - } - if (this.fitsProperties.maxVal < this.dataUnit[i]) { - this.fitsProperties.maxVal = this.dataUnit[i]; - } - i++; - this.position += 1; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - readDataUnitInt16: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getInt16(this.position, false); - if (this.fitsProperties.minVal > this.dataUnit[i]) { - this.fitsProperties.minVal = this.dataUnit[i]; - } - if (this.fitsProperties.maxVal < this.dataUnit[i]) { - this.fitsProperties.maxVal = this.dataUnit[i]; - } - i++; - this.position += 2; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - readDataUnitInt32: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getInt32(this.position, false); - if (this.fitsProperties.minVal > this.dataUnit[i]) { - this.fitsProperties.minVal = this.dataUnit[i]; - } - if (this.fitsProperties.maxVal < this.dataUnit[i]) { - this.fitsProperties.maxVal = this.dataUnit[i]; - } - i++; - this.position += 4; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - computeWcs: function () { - if (ss.keyExists(this.header, 'CROTA2')) { - this.rotation = parseFloat(ss.trim(this.header['CROTA2'])); - this.hasRotation = true; - } - if (ss.keyExists(this.header, 'CDELT1')) { - this.scaleX = parseFloat(ss.trim(this.header['CDELT1'])); - if (ss.keyExists(this.header, 'CDELT2')) { - this.scaleY = parseFloat(ss.trim(this.header['CDELT2'])); - this.hasScale = true; - } - } - if (ss.keyExists(this.header, 'CRPIX1')) { - this.referenceX = parseFloat(ss.trim(this.header['CRPIX1'])) - 0.5; - if (ss.keyExists(this.header, 'CRPIX2')) { - this.referenceY = parseFloat(ss.trim(this.header['CRPIX2'])) - 0.5; - this.hasPixel = true; - } - } - var galactic = false; - var tan = false; - if (ss.keyExists(this.header, 'CTYPE1')) { - if (this.header['CTYPE1'].indexOf('GLON-') > -1) { - galactic = true; - tan = true; - } - if (this.header['CTYPE2'].indexOf('GLAT-') > -1) { - galactic = true; - tan = true; - } - if (this.header['CTYPE1'].indexOf('-TAN') > -1) { - tan = true; - } - if (this.header['CTYPE1'].indexOf('-SIN') > -1) { - tan = true; - } - } - if (!tan) { - throw new Error('Only TAN projected images are supported: '); - } - this.hasSize = true; - if (ss.keyExists(this.header, 'CRVAL1')) { - this.centerX = parseFloat(ss.trim(this.header['CRVAL1'])); - if (ss.keyExists(this.header, 'CRVAL2')) { - this.centerY = parseFloat(ss.trim(this.header['CRVAL2'])); - this.hasLocation = true; - } - } - if (galactic) { - var result = Coordinates.galactictoJ2000(this.centerX, this.centerY); - this.centerX = result[0]; - this.centerY = result[1]; - } - if (ss.keyExists(this.header, 'CD1_1') && ss.keyExists(this.header, 'CD1_2') && ss.keyExists(this.header, 'CD2_1') && ss.keyExists(this.header, 'CD2_2')) { - this.cd1_1 = parseFloat(ss.trim(this.header['CD1_1'])); - this.cd1_2 = parseFloat(ss.trim(this.header['CD1_2'])); - this.cd2_1 = parseFloat(ss.trim(this.header['CD2_1'])); - this.cd2_2 = parseFloat(ss.trim(this.header['CD2_2'])); - if (!this.hasRotation) { - this.calculateRotationFromCD(); - } - if (!this.hasScale) { - this.calculateScaleFromCD(); - } - this.hasScale = true; - this.hasRotation = true; - } - this.set_validWcs(this.hasScale && this.hasRotation && this.hasPixel && this.hasLocation); - }, - applyDisplaySettings: function () { - if (ss.keyExists(this.header, 'DATAMIN')) { - this.fitsProperties.lowerCut = parseFloat(ss.trim(this.header['DATAMIN'])); - this.fitsProperties.minVal = this.fitsProperties.lowerCut; - } - if (ss.keyExists(this.header, 'DATAMAX')) { - this.fitsProperties.upperCut = parseFloat(ss.trim(this.header['DATAMAX'])); - this.fitsProperties.maxVal = this.fitsProperties.upperCut; - } - if (ss.keyExists(this.header, 'PXCUTMIN')) { - this.fitsProperties.lowerCut = parseFloat(ss.trim(this.header['PXCUTMIN'])); - } - if (ss.keyExists(this.header, 'PXCUTMAX')) { - this.fitsProperties.upperCut = parseFloat(ss.trim(this.header['PXCUTMAX'])); - } - }, - computeHistogram: function (count) { - var histogram = new Array(count + 1); - for (var i = 0; i < count + 1; i++) { - histogram[i] = 0; - } - this.populateHistogram(histogram); - var maxCounter = 1; - var $enum1 = ss.enumerate(histogram); - while ($enum1.moveNext()) { - var val = $enum1.current; - if (val > maxCounter) { - maxCounter = val; - } - } - histogram[count] = maxCounter; - return histogram; - }, - populateHistogram: function (histogram) { - var buckets = histogram.length; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - for (var i = 0; i < this.dataUnit.length; i++) { - if (!(this.dataUnit[i] === FitsImage.naN)) { - histogram[Math.min(buckets - 1, ss.truncate(((this.fitsProperties.bZero + this.fitsProperties.bScale * this.dataUnit[i] - this.fitsProperties.minVal) / factor)))]++; - } - } - }, - drawHistogram: function (ctx) { - ctx.clearRect(0, 0, 255, 150); - ctx.beginPath(); - ctx.strokeStyle = 'rgba(255,255,255,255)'; - var logMax = Math.log(this.histogramMaxCount); - for (var i = 0; i < this.histogram.length; i++) { - var height = Math.log(this.histogram[i]) / logMax; - if (height < 0) { - height = 0; - } - ctx.moveTo(i, 150); - ctx.lineTo(i, 150 - (height * 150)); - ctx.stroke(); - } - } - }; - - - // wwtlib.Circle - - function Circle() { - this._fill$1 = false; - this._skyRelative$1 = false; - this._strokeWidth$1 = 1; - this._radius$1 = 10; - this._lineColor$1 = Colors.get_white(); - this._fillColor$1 = Colors.get_white(); - this._ra$1 = 0; - this._dec$1 = 0; - Annotation.call(this); - } - var Circle$ = { - get_fill: function () { - return this._fill$1; - }, - set_fill: function (value) { - Annotation.batchDirty = true; - this._fill$1 = value; - return value; - }, - get_skyRelative: function () { - return this._skyRelative$1; - }, - set_skyRelative: function (value) { - Annotation.batchDirty = true; - this._skyRelative$1 = value; - return value; - }, - get_lineWidth: function () { - return this._strokeWidth$1; - }, - set_lineWidth: function (value) { - Annotation.batchDirty = true; - this._strokeWidth$1 = value; - return value; - }, - get_radius: function () { - return this._radius$1; - }, - set_radius: function (value) { - Annotation.batchDirty = true; - this._radius$1 = value; - return value; - }, - get_lineColor: function () { - return this._lineColor$1.toString(); - }, - set_lineColor: function (value) { - Annotation.batchDirty = true; - this._lineColor$1 = Color.load(value); - return value; - }, - get_fillColor: function () { - return this._fillColor$1.toString(); - }, - set_fillColor: function (value) { - Annotation.batchDirty = true; - this._fillColor$1 = Color.fromName(value); - return value; - }, - setCenter: function (ra, dec) { - Annotation.batchDirty = true; - this._ra$1 = ra / 15; - this._dec$1 = dec; - this.center = Coordinates.raDecTo3d(this._ra$1, this._dec$1); - }, - draw: function (renderContext) { - var onScreen = true; - var rad = this._radius$1; - if (this._skyRelative$1) { - rad /= renderContext.get_fovScale() / 3600; - } - var screenSpacePnt = renderContext.WVP.transform(this.center); - if (screenSpacePnt.z < 0) { - onScreen = false; - } - if (Vector3d.dot(renderContext.get_viewPoint(), this.center) < 0.55) { - onScreen = false; - } - if (renderContext.gl != null) { - if (Annotation.batchDirty || this.annotationDirty) { - var up = Vector3d.create(0, 1, 0); - var xNormal = Vector3d.cross(this.center, up); - var yNormal = Vector3d.cross(this.center, xNormal); - var r = this._radius$1 / 44; - var segments = 72; - var radiansPerSegment = Math.PI * 2 / segments; - var vertexList = []; - for (var j = 0; j <= segments; j++) { - var x = Math.cos(j * radiansPerSegment) * r; - var y = Math.sin(j * radiansPerSegment) * r; - vertexList.push(Vector3d.create(this.center.x + x * xNormal.x + y * yNormal.x, this.center.y + x * xNormal.y + y * yNormal.y, this.center.z + x * xNormal.z + y * yNormal.z)); - } - if (this._strokeWidth$1 > 0 && vertexList.length > 1) { - var lineColorWithOpacity = this._lineColor$1._clone(); - lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); - for (var i = 0; i < (vertexList.length - 1); i++) { - Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - } - if (this._fill$1) { - var fillColorWithOpacity = this._fillColor$1._clone(); - fillColorWithOpacity.a = Math.round(fillColorWithOpacity.a * this.get_opacity()); - var pos = Vector3d.create(this.center.x, this.center.y, this.center.z); - vertexList.splice(0, 0, pos); - Annotation.triangleFanPointList.addShape(vertexList, fillColorWithOpacity, new Dates(0, 1)); - } - this.annotationDirty = false; - } - } - else { - if (onScreen) { - var ctx = renderContext.device; - ctx.save(); - ctx.globalAlpha = this.get_opacity(); - ctx.beginPath(); - ctx.arc(screenSpacePnt.x, screenSpacePnt.y, rad, 0, Math.PI * 2, true); - ctx.lineWidth = this._strokeWidth$1; - ctx.fillStyle = this._fillColor$1.toString(); - if (this._fill$1) { - ctx.fill(); - } - ctx.globalAlpha = 1; - ctx.strokeStyle = this._lineColor$1.toString(); - ctx.stroke(); - ctx.restore(); - } - } - }, - hitTest: function (renderContext, RA, dec, x, y) { - if (ss.emptyString(this.get_id())) { - return false; - } - var rad = this._radius$1; - if (!this._skyRelative$1) { - rad *= renderContext.get_fovScale() / 3600; - } - return Annotation.separation(RA, dec, this._ra$1, this._dec$1) < rad; - } - }; - - - // wwtlib.Poly - - function Poly() { - this._points$1 = []; - this._fill$1 = false; - this._strokeWidth$1 = 1; - this._lineColor$1 = Colors.get_white(); - this._fillColor$1 = Colors.get_white(); - Annotation.call(this); - } - var Poly$ = { - addPoint: function (x, y) { - Annotation.batchDirty = true; - this._points$1.push(Coordinates.raDecTo3d(x / 15, y)); - }, - get_fill: function () { - return this._fill$1; - }, - set_fill: function (value) { - Annotation.batchDirty = true; - this._fill$1 = value; - return value; - }, - get_lineWidth: function () { - return this._strokeWidth$1; - }, - set_lineWidth: function (value) { - Annotation.batchDirty = true; - this._strokeWidth$1 = value; - return value; - }, - get_lineColor: function () { - return this._lineColor$1.toString(); - }, - set_lineColor: function (value) { - Annotation.batchDirty = true; - this._lineColor$1 = Color.fromName(value); - return value; - }, - get_fillColor: function () { - return this._fillColor$1.toString(); - }, - set_fillColor: function (value) { - Annotation.batchDirty = true; - this._fillColor$1 = Color.fromName(value); - return value; - }, - draw: function (renderContext) { - if (renderContext.gl != null) { - if (Annotation.batchDirty || this.annotationDirty) { - var vertexList = this._points$1; - if (this._strokeWidth$1 > 0 && this._points$1.length > 1) { - var lineColorWithOpacity = this._lineColor$1._clone(); - lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); - for (var i = 0; i < (this._points$1.length - 1); i++) { - Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - Annotation.lineList.addLine(vertexList[this._points$1.length - 1], vertexList[0], lineColorWithOpacity, new Dates(0, 1)); - } - if (this._fill$1) { - var fillColorWithOpacity = this._fillColor$1._clone(); - fillColorWithOpacity.a = Math.round(fillColorWithOpacity.a * this.get_opacity()); - var indexes = Tessellator.tesselateSimplePoly(vertexList); - for (var i = 0; i < indexes.length; i += 3) { - Annotation.triangleList.addSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], fillColorWithOpacity, new Dates(0, 1), 2); - } - } - this.annotationDirty = false; - } - } - else { - var ctx = renderContext.device; - ctx.save(); - ctx.globalAlpha = this.get_opacity(); - ctx.beginPath(); - var first = true; - var $enum1 = ss.enumerate(this._points$1); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - var screenSpacePnt = renderContext.WVP.transform(pnt); - if (screenSpacePnt.z < 0) { - ctx.restore(); - return; - } - if (Vector3d.dot(renderContext.get_viewPoint(), pnt) < 0.75) { - ctx.restore(); - return; - } - if (first) { - first = false; - ctx.moveTo(screenSpacePnt.x, screenSpacePnt.y); - } - else { - ctx.lineTo(screenSpacePnt.x, screenSpacePnt.y); - } - } - ctx.closePath(); - ctx.lineWidth = this._strokeWidth$1; - if (this._fill$1) { - ctx.fillStyle = this._fillColor$1.toString(); - ctx.fill(); - } - ctx.strokeStyle = this._lineColor$1.toString(); - ctx.globalAlpha = 1; - ctx.stroke(); - ctx.restore(); - } - } - }; - - - // wwtlib.PolyLine - - function PolyLine() { - this._points$1 = []; - this._strokeWidth$1 = 1; - this._lineColor$1 = Colors.get_white(); - Annotation.call(this); - } - var PolyLine$ = { - addPoint: function (x, y) { - Annotation.batchDirty = true; - this._points$1.push(Coordinates.raDecTo3d(x / 15, y)); - }, - get_lineWidth: function () { - return this._strokeWidth$1; - }, - set_lineWidth: function (value) { - Annotation.batchDirty = true; - this._strokeWidth$1 = value; - return value; - }, - get_lineColor: function () { - return this._lineColor$1.toString(); - }, - set_lineColor: function (value) { - Annotation.batchDirty = true; - this._lineColor$1 = Color.fromName(value); - return value; - }, - draw: function (renderContext) { - if (renderContext.gl != null) { - if (Annotation.batchDirty || this.annotationDirty) { - var vertexList = this._points$1; - if (this._strokeWidth$1 > 0) { - var lineColorWithOpacity = this._lineColor$1._clone(); - lineColorWithOpacity.a = Math.round(lineColorWithOpacity.a * this.get_opacity()); - for (var i = 0; i < (this._points$1.length - 1); i++) { - Annotation.lineList.addLine(vertexList[i], vertexList[i + 1], lineColorWithOpacity, new Dates(0, 1)); - } - } - this.annotationDirty = false; - } - } - else { - var ctx = renderContext.device; - ctx.save(); - ctx.globalAlpha = this.get_opacity(); - var first = true; - var $enum1 = ss.enumerate(this._points$1); - while ($enum1.moveNext()) { - var pnt = $enum1.current; - var screenSpacePnt = renderContext.WVP.transform(pnt); - if (screenSpacePnt.z < 0) { - ctx.restore(); - return; - } - if (Vector3d.dot(renderContext.get_viewPoint(), pnt) < 0.75) { - ctx.restore(); - return; - } - if (first) { - first = false; - ctx.beginPath(); - ctx.moveTo(screenSpacePnt.x, screenSpacePnt.y); - } - else { - ctx.lineTo(screenSpacePnt.x, screenSpacePnt.y); - } - } - ctx.lineWidth = this._strokeWidth$1; - ctx.strokeStyle = this._lineColor$1.toString(); - ctx.stroke(); - ctx.restore(); - } - } - }; - - - // wwtlib.EquirectangularTile - - function EquirectangularTile() { - this._tileDegrees$1 = 0; - this._topDown$1 = true; - this._subDivisionLevel$1 = 1; - Tile.call(this); - } - EquirectangularTile.create = function (level, x, y, dataset, parent) { - var temp = new EquirectangularTile(); - temp.parent = parent; - temp.level = level; - temp.tileX = x; - temp.tileY = y; - temp.dataset = dataset; - temp._topDown$1 = !dataset.get_bottomsUp(); - temp.computeBoundingSphere(); - return temp; - }; - var EquirectangularTile$ = { - computeBoundingSphere: function () { - if (!this._topDown$1) { - this.computeBoundingSphereBottomsUp(); - return; - } - this._tileDegrees$1 = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var latMin = (90 - ((this.tileY) * this._tileDegrees$1)); - var latMax = (90 - (((this.tileY + 1)) * this._tileDegrees$1)); - var lngMin = ((this.tileX * this._tileDegrees$1) - 180); - var lngMax = ((((this.tileX + 1)) * this._tileDegrees$1) - 180); - var latCenter = (latMin + latMax) / 2; - var lngCenter = (lngMin + lngMax) / 2; - this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); - this.topLeft = this.geoTo3d(latMin, lngMin, false); - this.bottomRight = this.geoTo3d(latMax, lngMax, false); - this.topRight = this.geoTo3d(latMin, lngMax, false); - this.bottomLeft = this.geoTo3d(latMax, lngMin, false); - var distVect = this.geoTo3d(latMin, lngMin, false); - distVect.subtract(this.sphereCenter); - this.sphereRadius = distVect.length(); - this._tileDegrees$1 = lngMax - lngMin; - }, - computeBoundingSphereBottomsUp: function () { - var tileDegrees = this.dataset.get_baseTileDegrees() / (Math.pow(2, this.level)); - var latMin = (-90 + (((this.tileY + 1)) * tileDegrees)); - var latMax = (-90 + ((this.tileY) * tileDegrees)); - var lngMin = ((this.tileX * tileDegrees) - 180); - var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); - var latCenter = (latMin + latMax) / 2; - var lngCenter = (lngMin + lngMax) / 2; - this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); - this.topLeft = this.geoTo3d(latMin, lngMin, false); - this.bottomRight = this.geoTo3d(latMax, lngMax, false); - this.topRight = this.geoTo3d(latMin, lngMax, false); - this.bottomLeft = this.geoTo3d(latMax, lngMin, false); - var distVect = this.topLeft; - distVect.subtract(this.sphereCenter); - this.sphereRadius = distVect.length(); - tileDegrees = lngMax - lngMin; - }, - createGeometry: function (renderContext) { - Tile.prototype.createGeometry.call(this, renderContext); - if (renderContext.gl == null) { - if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { - this._subDivisionLevel$1 = Math.max(2, (4 - this.level) * 2); - } - } - else { - this._subDivisionLevel$1 = 32; - } - try { - for (var i = 0; i < 4; i++) { - this._renderTriangleLists[i] = []; - } - if (!this._topDown$1) { - return this._createGeometryBottomsUp$1(renderContext); - } - var lat, lng; - var index = 0; - var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var latMin = (90 - ((this.tileY) * tileDegrees)); - var latMax = (90 - (((this.tileY + 1)) * tileDegrees)); - var lngMin = ((this.tileX * tileDegrees) - 180); - var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); - var tileDegreesX = lngMax - lngMin; - var tileDegreesY = latMax - latMin; - this.topLeft = this.geoTo3d(latMin, lngMin, false); - this.bottomRight = this.geoTo3d(latMax, lngMax, false); - this.topRight = this.geoTo3d(latMin, lngMax, false); - this.bottomLeft = this.geoTo3d(latMax, lngMin, false); - var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); - var x, y; - var textureStep = 1 / this._subDivisionLevel$1; - for (y = 0; y <= this._subDivisionLevel$1; y++) { - if (y !== this._subDivisionLevel$1) { - lat = latMin + (textureStep * tileDegreesY * y); - } - else { - lat = latMax; - } - for (x = 0; x <= this._subDivisionLevel$1; x++) { - if (x !== this._subDivisionLevel$1) { - lng = lngMin + (textureStep * tileDegreesX * x); - } - else { - lng = lngMax; - } - index = y * (this._subDivisionLevel$1 + 1) + x; - verts[index] = PositionTexture.createPos(this.geoTo3d(lat, lng, false), x * textureStep, y * textureStep); - } - } - this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; - var quarterDivisions = this._subDivisionLevel$1 / 2; - var part = 0; - if (renderContext.gl == null) { - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - index = 0; - for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - var p1; - var p2; - var p3; - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); - } - } - part++; - } - } - } - else { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(verts.length * 5); - var buffer = f32array; - index = 0; - var $enum1 = ss.enumerate(verts); - while ($enum1.moveNext()) { - var pt = $enum1.current; - index = this.addVertex(buffer, index, pt); - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - var ui16array = new Uint16Array(this.triangleCount * 3); - var indexArray = ui16array; - index = 0; - for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - } - } - this._indexBuffers[part] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this._indexBuffers[part]); - Tile.prepDevice.bufferData(34963, ui16array, 35044); - part++; - } - } - } - } - catch ($e2) { - } - return true; - }, - _createGeometryBottomsUp$1: function (renderContext) { - var lat, lng; - var index = 0; - var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var latMin = (-90 + (((this.tileY + 1)) * tileDegrees)); - var latMax = (-90 + ((this.tileY) * tileDegrees)); - var lngMin = ((this.tileX * tileDegrees) - 180); - var lngMax = ((((this.tileX + 1)) * tileDegrees) - 180); - var tileDegreesX = lngMax - lngMin; - var tileDegreesY = latMax - latMin; - var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); - var x, y; - var textureStep = 1 / this._subDivisionLevel$1; - for (y = 0; y <= this._subDivisionLevel$1; y++) { - if (y !== this._subDivisionLevel$1) { - lat = latMin + (textureStep * tileDegreesY * y); - } - else { - lat = latMax; - } - for (x = 0; x <= this._subDivisionLevel$1; x++) { - if (x !== this._subDivisionLevel$1) { - lng = lngMin + (textureStep * tileDegreesX * x); - } - else { - lng = lngMax; - } - index = y * (this._subDivisionLevel$1 + 1) + x; - verts[index] = PositionTexture.createPos(this.geoTo3d(lat, lng, false), x * textureStep, y * textureStep); - } - } - this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; - var quarterDivisions = this._subDivisionLevel$1 / 2; - var part = 0; - if (renderContext.gl == null) { - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - index = 0; - for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - var p1; - var p2; - var p3; - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - this._renderTriangleLists[part].push(RenderTriangle.create(p1, p3, p2, this.texture, this.level)); - } - } - part++; - } - } - } - else { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(verts.length * 5); - var buffer = f32array; - index = 0; - var $enum1 = ss.enumerate(verts); - while ($enum1.moveNext()) { - var pt = $enum1.current; - index = this.addVertex(buffer, index, pt); - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - var ui16array = new Uint16Array(this.triangleCount * 3); - var indexArray = ui16array; - index = 0; - for (var y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (var x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - } - } - this._indexBuffers[part] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this._indexBuffers[part]); - Tile.prepDevice.bufferData(34963, ui16array, 35044); - part++; - } - } - } - return true; - } - }; - - - // wwtlib.PositionVertexBuffer - - function PositionVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - var PositionVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 3); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.x; - buffer[index++] = pt.y; - buffer[index++] = pt.z; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.PositionTextureVertexBuffer - - function PositionTextureVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - PositionTextureVertexBuffer.create = function (data) { - var buffer = new PositionTextureVertexBuffer(data.length); - buffer._verts$1 = data; - buffer.unlock(); - return buffer; - }; - var PositionTextureVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 5); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.PositionNormalTexturedVertexBuffer - - function PositionNormalTexturedVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - PositionNormalTexturedVertexBuffer.create = function (data) { - var buffer = new PositionNormalTexturedVertexBuffer(data.length); - buffer._verts$1 = data; - buffer.unlock(); - return buffer; - }; - var PositionNormalTexturedVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 8); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.x; - buffer[index++] = pt.y; - buffer[index++] = pt.z; - buffer[index++] = pt.nx; - buffer[index++] = pt.ny; - buffer[index++] = pt.nz; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.PositionNormalTexturedTangentVertexBuffer - - function PositionNormalTexturedTangentVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - PositionNormalTexturedTangentVertexBuffer.create = function (data) { - var buffer = new PositionNormalTexturedTangentVertexBuffer(data.length); - buffer._verts$1 = data; - buffer.unlock(); - return buffer; - }; - var PositionNormalTexturedTangentVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 11); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.x; - buffer[index++] = pt.y; - buffer[index++] = pt.z; - buffer[index++] = pt.nx; - buffer[index++] = pt.ny; - buffer[index++] = pt.nz; - buffer[index++] = pt.tanx; - buffer[index++] = pt.tany; - buffer[index++] = pt.tanz; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.KeplerVertexBuffer - - function KeplerVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - KeplerVertexBuffer.create = function (items) { - var tmp = new KeplerVertexBuffer(items.length); - tmp._verts$1 = items; - return tmp; - }; - var KeplerVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 19); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.ABC.x; - buffer[index++] = pt.ABC.y; - buffer[index++] = pt.ABC.z; - buffer[index++] = pt.abc1.x; - buffer[index++] = pt.abc1.y; - buffer[index++] = pt.abc1.z; - buffer[index++] = pt.pointSize; - buffer[index++] = pt.color.r / 255; - buffer[index++] = pt.color.g / 255; - buffer[index++] = pt.color.b / 255; - buffer[index++] = pt.color.a / 255; - buffer[index++] = pt.w; - buffer[index++] = pt.e; - buffer[index++] = pt.n; - buffer[index++] = pt.t; - buffer[index++] = pt.a; - buffer[index++] = pt.z; - buffer[index++] = pt.orbitPos; - buffer[index++] = pt.orbits; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.TimeSeriesLineVertexBuffer - - function TimeSeriesLineVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - var TimeSeriesLineVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 9); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.get_color().r / 255; - buffer[index++] = pt.get_color().g / 255; - buffer[index++] = pt.get_color().b / 255; - buffer[index++] = pt.get_color().a / 255; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.TimeSeriesPointVertexBuffer - - function TimeSeriesPointVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - var TimeSeriesPointVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 10); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.get_color().r / 255; - buffer[index++] = pt.get_color().g / 255; - buffer[index++] = pt.get_color().b / 255; - buffer[index++] = pt.get_color().a / 255; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - buffer[index++] = pt.pointSize; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - }, - dispose: function () { - Tile.prepDevice.bindBuffer(34962, null); - Tile.prepDevice.deleteBuffer(this.vertexBuffer); - this.vertexBuffer = null; - } - }; - - - // wwtlib.PositionColoredVertexBuffer - - function PositionColoredVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - var PositionColoredVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 7); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.color.r / 255; - buffer[index++] = pt.color.g / 255; - buffer[index++] = pt.color.b / 255; - buffer[index++] = pt.color.a / 255; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.PositionColoredTexturedVertexBuffer - - function PositionColoredTexturedVertexBuffer(count) { - this.count = 0; - this._verts$1 = null; - VertexBufferBase.call(this); - this.count = count; - } - var PositionColoredTexturedVertexBuffer$ = { - lock: function () { - this._verts$1 = new Array(this.count); - return this._verts$1; - }, - unlock: function () { - this.vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this.vertexBuffer); - var f32array = new Float32Array(this.count * 9); - var buffer = f32array; - var index = 0; - var $enum1 = ss.enumerate(this._verts$1); - while ($enum1.moveNext()) { - var pt = $enum1.current; - buffer[index++] = pt.position.x; - buffer[index++] = pt.position.y; - buffer[index++] = pt.position.z; - buffer[index++] = pt.color.r / 255; - buffer[index++] = pt.color.g / 255; - buffer[index++] = pt.color.b / 255; - buffer[index++] = pt.color.a / 255; - buffer[index++] = pt.tu; - buffer[index++] = pt.tv; - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - } - }; - - - // wwtlib.ScaleLinear - - function ScaleLinear(min, max) { - this._min$1 = 0; - this._max$1 = 0; - this._factor$1 = 0; - this._logFactor$1 = 0; - ScaleMap.call(this); - this._min$1 = min; - this._max$1 = max; - this._factor$1 = max - min; - } - var ScaleLinear$ = { - map: function (val) { - return Math.min(255, Math.max(0, ss.truncate(((val - this._min$1) / this._factor$1 * 255)))); - } - }; - - - // wwtlib.ScaleLog - - function ScaleLog(min, max) { - this._min$1 = 0; - this._max$1 = 0; - this._factor$1 = 0; - this._logFactor$1 = 0; - ScaleMap.call(this); - this._min$1 = min; - this._max$1 = max; - this._factor$1 = max - min; - this._logFactor$1 = 255 / Math.log(255); - } - var ScaleLog$ = { - map: function (val) { - return Math.min(255, Math.max(0, ss.truncate((Math.log((val - this._min$1) / this._factor$1 * 255) * this._logFactor$1)))); - } - }; - - - // wwtlib.ScalePow - - function ScalePow(min, max) { - this._min$1 = 0; - this._max$1 = 0; - this._factor$1 = 0; - this._powFactor$1 = 0; - ScaleMap.call(this); - this._min$1 = min; - this._max$1 = max; - this._factor$1 = max - min; - this._powFactor$1 = 255 / Math.pow(255, 2); - } - var ScalePow$ = { - map: function (val) { - return Math.min(255, Math.max(0, ss.truncate((Math.pow((val - this._min$1) / this._factor$1 * 255, 2) * this._powFactor$1)))); - } - }; - - - // wwtlib.ScaleSqrt - - function ScaleSqrt(min, max) { - this._min$1 = 0; - this._max$1 = 0; - this._factor$1 = 0; - this._sqrtFactor$1 = 0; - ScaleMap.call(this); - this._min$1 = min; - this._max$1 = max; - this._factor$1 = max - min; - this._sqrtFactor$1 = 255 / Math.sqrt(255); - } - var ScaleSqrt$ = { - map: function (val) { - return Math.min(255, Math.max(0, ss.truncate((Math.sqrt((val - this._min$1) / this._factor$1 * 255) * this._sqrtFactor$1)))); - } - }; - - - // wwtlib.HistogramEqualization - - function HistogramEqualization(image, min, max) { - this._min$1 = 0; - this._max$1 = 0; - this._factor$1 = 0; - this._maxHistogramValue$1 = 1; - ScaleMap.call(this); - this._min$1 = min; - this._max$1 = max; - this._factor$1 = max - min; - this._histogram$1 = image.computeHistogram(10000); - this._maxHistogramValue$1 = this._histogram$1[10000]; - this._lookup$1 = new Array(10000); - var totalCounts = ss.truncate((image.get_sizeX() * image.get_sizeY())); - var sum = 0; - for (var i = 0; i < 10000; i++) { - sum += this._histogram$1[i]; - this._lookup$1[i] = (Math.min(255, (sum * 255) / totalCounts) + 0.5); - } - } - var HistogramEqualization$ = { - map: function (val) { - return this._lookup$1[Math.min(10000 - 1, Math.max(0, ss.truncate(((val - this._min$1) / this._factor$1 * (10000 - 1)))))]; - } - }; - - - // wwtlib.GreatCirlceRouteLayer - - function GreatCirlceRouteLayer() { - this._triangleList$1 = null; - this._latStart$1 = 0; - this._lngStart$1 = 0; - this._latEnd$1 = 0; - this._lngEnd$1 = 0; - this._width$1 = 4; - this._percentComplete$1 = 100; - Layer.call(this); - } - var GreatCirlceRouteLayer$ = { - getTypeName: function () { - return 'TerraViewer.GreatCirlceRouteLayer'; - }, - cleanUp: function () { - if (this._triangleList$1 != null) { - this._triangleList$1.clear(); - } - this._triangleList$1 = null; - Layer.prototype.cleanUp.call(this); - }, - draw: function (renderContext, opacity, flat) { - if (this._triangleList$1 == null) { - this._initializeRoute$1(renderContext); - } - this._triangleList$1.jNow = this._percentComplete$1 / 100; - this._triangleList$1.draw(renderContext, opacity * this.get_opacity(), 2); - return true; - }, - _initializeRoute$1: function (renderContext) { - this._triangleList$1 = new TriangleList(); - this._triangleList$1.decay = 1000; - this._triangleList$1.sky = this.get_astronomical(); - this._triangleList$1.timeSeries = true; - this._triangleList$1.depthBuffered = false; - this._triangleList$1.autoTime = false; - var steps = 500; - var start = Coordinates.geoTo3dDouble(this._latStart$1, this._lngStart$1); - var end = Coordinates.geoTo3dDouble(this._latEnd$1, this._lngEnd$1); - var dir = Vector3d.subtractVectors(end, start); - dir.normalize(); - var startNormal = start; - startNormal.normalize(); - var left = Vector3d.cross(startNormal, dir); - var right = Vector3d.cross(dir, startNormal); - left.normalize(); - right.normalize(); - left.multiply(0.001 * this._width$1); - right.multiply(0.001 * this._width$1); - var lastLeft = new Vector3d(); - var lastRight = new Vector3d(); - var firstTime = true; - for (var i = 0; i <= steps; i++) { - var v = Vector3d.lerp(start, end, i / steps); - v.normalize(); - var cl = v; - var cr = v; - cl.add(left); - cr.add(right); - if (!firstTime) { - this._triangleList$1.addQuad(lastRight, lastLeft, cr, cl, this.get_color(), new Dates(i / steps, 2)); - } - else { - firstTime = false; - } - lastLeft = cl; - lastRight = cr; - } - }, - getParams: function () { - return [this._percentComplete$1]; - }, - getParamNames: function () { - return ['Percentage']; - }, - setParams: function (paramList) { - if (paramList.length > 0) { - this._percentComplete$1 = paramList[0]; - } - }, - get_latStart: function () { - return this._latStart$1; - }, - set_latStart: function (value) { - if (this._latStart$1 !== value) { - this._latStart$1 = value; - this.version++; - } - return value; - }, - get_lngStart: function () { - return this._lngStart$1; - }, - set_lngStart: function (value) { - if (this._lngStart$1 !== value) { - this._lngStart$1 = value; - this.version++; - } - return value; - }, - get_latEnd: function () { - return this._latEnd$1; - }, - set_latEnd: function (value) { - if (this._latEnd$1 !== value) { - this._latEnd$1 = value; - this.version++; - } - return value; - }, - get_lngEnd: function () { - return this._lngEnd$1; - }, - set_lngEnd: function (value) { - if (this._lngEnd$1 !== value) { - this._lngEnd$1 = value; - this.version++; - } - return value; - }, - get_width: function () { - return this._width$1; - }, - set_width: function (value) { - if (this._width$1 !== value) { - this._width$1 = value; - this.version++; - } - return value; - }, - get_percentComplete: function () { - return this._percentComplete$1; - }, - set_percentComplete: function (value) { - if (this._percentComplete$1 !== value) { - this._percentComplete$1 = value; - this.version++; - } - return value; - }, - writeLayerProperties: function (xmlWriter) { - xmlWriter._writeAttributeString('LatStart', this.get_latStart().toString()); - xmlWriter._writeAttributeString('LngStart', this.get_lngStart().toString()); - xmlWriter._writeAttributeString('LatEnd', this.get_latEnd().toString()); - xmlWriter._writeAttributeString('LngEnd', this.get_lngEnd().toString()); - xmlWriter._writeAttributeString('Width', this.get_width().toString()); - xmlWriter._writeAttributeString('PercentComplete', this.get_percentComplete().toString()); - }, - initializeFromXml: function (node) { - this._latStart$1 = parseFloat(node.attributes.getNamedItem('LatStart').nodeValue); - this._lngStart$1 = parseFloat(node.attributes.getNamedItem('LngStart').nodeValue); - this._latEnd$1 = parseFloat(node.attributes.getNamedItem('LatEnd').nodeValue); - this._lngEnd$1 = parseFloat(node.attributes.getNamedItem('LngEnd').nodeValue); - this._width$1 = parseFloat(node.attributes.getNamedItem('Width').nodeValue); - this._percentComplete$1 = parseFloat(node.attributes.getNamedItem('PercentComplete').nodeValue); - } - }; - - - // wwtlib.GridLayer - - function GridLayer() { - Layer.call(this); - } - var GridLayer$ = { - draw: function (renderContext, opacity, flat) { - Grids.drawPlanetGrid(renderContext, opacity * this.get_opacity(), this.get_color()); - Grids.drawPlanetGridText(renderContext, opacity * this.get_opacity(), this.get_color()); - return true; - } - }; - - - // wwtlib.ImageSetLayer - - function ImageSetLayer() { - this._imageSet$1 = null; - this._extension$1 = '.txt'; - this._overrideDefaultLayer$1 = false; - this._loaded$1 = false; - Layer.call(this); - } - ImageSetLayer.create = function (set) { - var isl = new ImageSetLayer(); - isl._imageSet$1 = set; - return isl; - }; - var ImageSetLayer$ = { - get_imageSet: function () { - return this._imageSet$1; - }, - set_imageSet: function (value) { - this._imageSet$1 = value; - return value; - }, - get_overrideDefaultLayer: function () { - return this._overrideDefaultLayer$1; - }, - set_overrideDefaultLayer: function (value) { - this._overrideDefaultLayer$1 = value; - return value; - }, - getFitsImage: function () { - return ss.safeCast(this._imageSet$1.get_wcsImage(), FitsImage); - }, - _isFitsImageset$1: function () { - var hasFitsExt = this._imageSet$1.get_extension() === '.fits'; - return ss.canCast(this._imageSet$1.get_wcsImage(), FitsImage) || (this._imageSet$1.get_wcsImage() == null && hasFitsExt); - }, - initializeFromXml: function (node) { - var imageSetNode = Util.selectSingleNode(node, 'ImageSet'); - this._imageSet$1 = Imageset.fromXMLNode(imageSetNode); - if (node.attributes.getNamedItem('Extension') != null) { - this._extension$1 = node.attributes.getNamedItem('Extension').nodeValue; - } - if (node.attributes.getNamedItem('ScaleType') != null) { - this.get_imageSet().get_fitsProperties().scaleType = Enums.parse('ScaleTypes', node.attributes.getNamedItem('ScaleType').nodeValue); - } - if (node.attributes.getNamedItem('MinValue') != null) { - this.get_imageSet().get_fitsProperties().minVal = parseFloat(node.attributes.getNamedItem('MinValue').nodeValue); - this.get_imageSet().get_fitsProperties().lowerCut = (node.attributes.getNamedItem('LowerCut') != null) ? parseFloat(node.attributes.getNamedItem('LowerCut').nodeValue) : this.get_imageSet().get_fitsProperties().minVal; - } - if (node.attributes.getNamedItem('MaxValue') != null) { - this.get_imageSet().get_fitsProperties().maxVal = parseFloat(node.attributes.getNamedItem('MaxValue').nodeValue); - this.get_imageSet().get_fitsProperties().upperCut = (node.attributes.getNamedItem('UpperCut') != null) ? parseFloat(node.attributes.getNamedItem('UpperCut').nodeValue) : this.get_imageSet().get_fitsProperties().maxVal; - } - if (node.attributes.getNamedItem('ColorMapperName') != null) { - this.get_imageSet().get_fitsProperties().colorMapName = node.attributes.getNamedItem('ColorMapperName').nodeValue; - } - if (node.attributes.getNamedItem('OverrideDefault') != null) { - this._overrideDefaultLayer$1 = ss.boolean(node.attributes.getNamedItem('OverrideDefault').nodeValue); - } - }, - draw: function (renderContext, opacity, flat) { - if (!this._loaded$1) { - return false; - } - renderContext.set_worldBase(renderContext.get_world()); - renderContext.set_viewBase(renderContext.get_view()); - renderContext.makeFrustum(); - renderContext.drawImageSet(this._imageSet$1, this.get_opacity() * opacity * 100); - return true; - }, - writeLayerProperties: function (xmlWriter) { - if (this._imageSet$1.get_wcsImage() != null) { - if (this._isFitsImageset$1()) { - this._extension$1 = '.fit'; - } - else { - this._extension$1 = '.png'; - } - xmlWriter._writeAttributeString('Extension', this._extension$1); - } - if (this._isFitsImageset$1()) { - xmlWriter._writeAttributeString('ScaleType', Enums.toXml('ScaleTypes', this._imageSet$1.get_fitsProperties().scaleType)); - xmlWriter._writeAttributeString('MinValue', this._imageSet$1.get_fitsProperties().minVal.toString()); - xmlWriter._writeAttributeString('MaxValue', this._imageSet$1.get_fitsProperties().maxVal.toString()); - xmlWriter._writeAttributeString('LowerCut', this._imageSet$1.get_fitsProperties().lowerCut.toString()); - xmlWriter._writeAttributeString('UpperCut', this._imageSet$1.get_fitsProperties().upperCut.toString()); - if (this._imageSet$1.get_fitsProperties().colorMapName != null) { - xmlWriter._writeAttributeString('ColorMapperName', this._imageSet$1.get_fitsProperties().colorMapName); - } - } - xmlWriter._writeAttributeString('OverrideDefault', this._overrideDefaultLayer$1.toString()); - Imageset.saveToXml(xmlWriter, this._imageSet$1, ''); - Layer.prototype.writeLayerProperties.call(this, xmlWriter); - }, - getTypeName: function () { - return 'TerraViewer.ImageSetLayer'; - }, - cleanUp: function () { - Layer.prototype.cleanUp.call(this); - }, - addFilesToCabinet: function (fc) { - if (ss.canCast(this._imageSet$1.get_wcsImage(), FitsImage)) { - var fName = (this._imageSet$1.get_wcsImage()).get_filename(); - var fileName = fc.tempDirectory + ss.format('{0}\\{1}{2}', fc.get_packageID(), this.id.toString(), this._extension$1); - fc.addFile(fileName, (this._imageSet$1.get_wcsImage()).sourceBlob); - } - }, - getParamNames: function () { - return Layer.prototype.getParamNames.call(this); - }, - getParams: function () { - return Layer.prototype.getParams.call(this); - }, - setParams: function (paramList) { - Layer.prototype.setParams.call(this, paramList); - }, - setImageScale: function (scaleType, min, max) { - console.warn('SetImageScale is considered deprecated. Use setImageScaleRaw or setImageScalePhysical instead.'); - this.setImageScaleRaw(scaleType, min, max); - }, - setImageScaleRaw: function (scaleType, min, max) { - this.get_imageSet().get_fitsProperties().lowerCut = min; - this.get_imageSet().get_fitsProperties().upperCut = max; - this.get_imageSet().get_fitsProperties().scaleType = scaleType; - if (ss.canCast(this._imageSet$1.get_wcsImage(), FitsImageJs)) { - Histogram.updateScale(this, scaleType, min, max); - } - }, - setImageScalePhysical: function (scaleType, min, max) { - var newMin = min; - var newMax = max; - if (this._isFitsImageset$1()) { - newMin = (newMin - this._imageSet$1.get_fitsProperties().bZero) / this._imageSet$1.get_fitsProperties().bScale; - newMax = (newMax - this._imageSet$1.get_fitsProperties().bZero) / this._imageSet$1.get_fitsProperties().bScale; - } - this.setImageScaleRaw(scaleType, newMin, newMax); - }, - setImageZ: function (z) { - if (this._isFitsImageset$1()) { - Histogram.updateImage(this, z); - } - }, - get_colorMapperName: function () { - return this.get_imageSet().get_fitsProperties().colorMapName; - }, - set_colorMapperName: function (value) { - if (ColorMapContainer.fromNamedColormap(value) == null) { - throw new Error('Invalid colormap name'); - } - this.version++; - if (this._isFitsImageset$1()) { - if (RenderContext.useGlVersion2) { - this._imageSet$1.get_fitsProperties().colorMapName = value; - } - else { - Histogram.updateColorMapper(this, value); - } - } - return value; - }, - get_colorMapper: function () { - if (this.get_imageSet().get_fitsProperties().colorMapName == null) { - return null; - } - else { - return ColorMapContainer.fromNamedColormap(this.get_imageSet().get_fitsProperties().colorMapName); - } - }, - loadData: function (tourDoc, filename) { - if (ss.startsWith(this._extension$1.toLowerCase(), '.fit')) { - var blob = tourDoc.getFileBlob(ss.replaceString(filename, '.txt', this._extension$1)); - var fi; - if (RenderContext.useGlVersion2) { - fi = new FitsImage(this._imageSet$1, 'image.fit', blob, ss.bind('doneLoading', this)); - } - else { - fi = new FitsImageJs(this._imageSet$1, 'image.fit', blob, ss.bind('doneLoading', this)); - } - this._imageSet$1.set_wcsImage(fi); - } - else { - this._loaded$1 = true; - } - }, - doneLoading: function (wcsImage) { - this._loaded$1 = true; - } - }; - - - // wwtlib.LayerCollection - - function LayerCollection() { - Layer.call(this); - } - var LayerCollection$ = { - draw: function (renderContext, opacity, flat) { - return Layer.prototype.draw.call(this, renderContext, opacity, false); - } - }; - - - // wwtlib.Object3dLayer - - function Object3dLayer() { - this._primaryUI$1 = null; - this._heading$1 = 0; - this._flipV$1 = true; - this._flipHandedness$1 = false; - this._smooth$1 = true; - this._twoSidedGeometry$1 = false; - this._pitch$1 = 0; - this._roll$1 = 0; - this._scale$1 = Vector3d.create(1, 1, 1); - this._translate$1 = Vector3d.create(0, 0, 0); - this._lightID$1 = 0; - this._dirty$1 = false; - this.objType = false; - this._xHandle$1 = new Vector2d(); - this._yHandle$1 = new Vector2d(); - this._zHandle$1 = new Vector2d(); - this._hprHandles$1 = new Array(6); - this._uiScale$1 = 1; - this._showEditUi$1 = false; - this._dragMode$1 = 0; - this._pntDown$1 = new Vector2d(); - this._valueOnDown$1 = 0; - this._valueOnDown2$1 = 0; - this._hitDist$1 = 20; - this._lockPreferedAxis$1 = false; - this._preferY$1 = false; - Layer.call(this); - } - Object3dLayer._initTranslateUI$1 = function () { - Object3dLayer._translateUILines$1 = new LineList(); - Object3dLayer._translateUILines$1.timeSeries = false; - Object3dLayer._translateUILines$1.set_depthBuffered(false); - Object3dLayer._translateUILines$1.showFarSide = true; - Object3dLayer._translateUI$1 = new TriangleList(); - Object3dLayer._translateUI$1.depthBuffered = false; - Object3dLayer._translateUI$1.timeSeries = false; - Object3dLayer._translateUI$1.writeZbuffer = false; - var twoPi = Math.PI * 2; - var step = twoPi / 45; - var rad = 0.05; - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(1 - rad * 4, 0, 0); - var pnt2 = Vector3d.create(1 - rad * 4, Math.cos(a) * rad, Math.sin(a) * rad); - var pnt3 = Vector3d.create(1 - rad * 4, Math.cos(a + step) * rad, Math.sin(a + step) * rad); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_red(), Dates.empty()); - } - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(1, 0, 0); - var pnt3 = Vector3d.create(1 - rad * 4, Math.cos(a) * rad, Math.sin(a) * rad); - var pnt2 = Vector3d.create(1 - rad * 4, Math.cos(a + step) * rad, Math.sin(a + step) * rad); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, 255, Math.max(0, (Math.sin(a) * 128)), Math.max(0, (Math.sin(a) * 128))), Dates.empty()); - } - Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(1, 0, 0), Colors.get_red(), Dates.empty()); - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(0, 1 - rad * 4, 0); - var pnt3 = Vector3d.create(Math.cos(a) * rad, 1 - rad * 4, Math.sin(a) * rad); - var pnt2 = Vector3d.create(Math.cos(a + step) * rad, 1 - rad * 4, Math.sin(a + step) * rad); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_green(), Dates.empty()); - } - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(0, 1, 0); - var pnt2 = Vector3d.create(Math.cos(a) * rad, 1 - rad * 4, Math.sin(a) * rad); - var pnt3 = Vector3d.create(Math.cos(a + step) * rad, 1 - rad * 4, Math.sin(a + step) * rad); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, Math.max(0, (Math.sin(a) * 128)), 255, Math.max(0, (Math.sin(a) * 128))), Dates.empty()); - } - Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(0, 1, 0), Colors.get_green(), Dates.empty()); - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(0, 0, 1 - rad * 4); - var pnt2 = Vector3d.create(Math.cos(a) * rad, Math.sin(a) * rad, 1 - rad * 4); - var pnt3 = Vector3d.create(Math.cos(a + step) * rad, Math.sin(a + step) * rad, 1 - rad * 4); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Colors.get_blue(), Dates.empty()); - } - for (var a = 0; a < twoPi; a += step) { - var pnt1 = Vector3d.create(0, 0, 1); - var pnt3 = Vector3d.create(Math.cos(a) * rad, Math.sin(a) * rad, 1 - rad * 4); - var pnt2 = Vector3d.create(Math.cos(a + step) * rad, Math.sin(a + step) * rad, 1 - rad * 4); - Object3dLayer._translateUI$1.addTriangle(pnt1, pnt2, pnt3, Color.fromArgb(255, Math.max(0, (Math.sin(a) * 128)), Math.max(0, (Math.sin(a) * 128)), 255), Dates.empty()); - } - Object3dLayer._translateUILines$1.addLine(Vector3d.create(0, 0, 0), Vector3d.create(0, 0, 1), Colors.get_blue(), Dates.empty()); - Object3dLayer._initRotateUI$1(); - Object3dLayer._initScaleUI$1(); - }; - Object3dLayer._initScaleUI$1 = function () { - Object3dLayer._scaleUI$1 = new TriangleList(); - Object3dLayer._scaleUI$1.depthBuffered = false; - Object3dLayer._scaleUI$1.timeSeries = false; - Object3dLayer._scaleUI$1.writeZbuffer = false; - var twoPi = Math.PI * 2; - var step = twoPi / 45; - var rad = 0.05; - Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(1 - rad * 2, 0, 0), rad * 2, Colors.get_red()); - Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(0, 1 - rad * 2, 0), rad * 2, Colors.get_green()); - Object3dLayer._makeCube$1(Object3dLayer._scaleUI$1, Vector3d.create(0, 0, 1 - rad * 2), rad * 2, Colors.get_blue()); - }; - Object3dLayer._makeCube$1 = function (tl, center, size, color) { - var dark = Color.fromArgb(255, ss.truncate((color.r * 0.6)), color.g, ss.truncate((color.b * 0.6))); - var med = Color.fromArgb(255, ss.truncate((color.r * 0.8)), ss.truncate((color.g * 0.8)), ss.truncate((color.b * 0.8))); - tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z - size), color, Dates.empty()); - tl.addQuad(Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z - size), color, Dates.empty()); - tl.addQuad(Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z - size), dark, Dates.empty()); - tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x + size, center.y - size, center.z - size), dark, Dates.empty()); - tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z + size), Vector3d.create(center.x - size, center.y + size, center.z + size), Vector3d.create(center.x + size, center.y - size, center.z + size), Vector3d.create(center.x - size, center.y - size, center.z + size), med, Dates.empty()); - tl.addQuad(Vector3d.create(center.x + size, center.y + size, center.z - size), Vector3d.create(center.x + size, center.y - size, center.z - size), Vector3d.create(center.x - size, center.y + size, center.z - size), Vector3d.create(center.x - size, center.y - size, center.z - size), med, Dates.empty()); - }; - Object3dLayer._initRotateUI$1 = function () { - Object3dLayer._rotateUi$1 = new TriangleList(); - Object3dLayer._rotateUi$1.depthBuffered = false; - Object3dLayer._rotateUi$1.timeSeries = false; - Object3dLayer._rotateUi$1.writeZbuffer = false; - var twoPi = Math.PI * 2; - var step = twoPi / 40; - var rad = 0.05; - var index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); - var pnt2 = Vector3d.create(-rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); - var pnt3 = Vector3d.create(rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); - var pnt4 = Vector3d.create(-rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Color._fromArgbColor(192, Colors.get_red()), Dates.empty()); - index++; - } - index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(Math.cos(a), Math.sin(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1))); - var pnt2 = Vector3d.create(Math.cos(a), Math.sin(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1))); - var pnt3 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1))); - var pnt4 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1))); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Color._fromArgbColor(192, Colors.get_blue()), Dates.empty()); - index++; - } - index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(Math.cos(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); - var pnt2 = Vector3d.create(Math.cos(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); - var pnt3 = Vector3d.create(Math.cos(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); - var pnt4 = Vector3d.create(Math.cos(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt2, pnt3, pnt4, Color._fromArgbColor(192, Colors.get_green()), Dates.empty()); - index++; - } - index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(-rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); - var pnt2 = Vector3d.create(rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.cos(a), Math.sin(a)); - var pnt3 = Vector3d.create(-rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); - var pnt4 = Vector3d.create(rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.cos(a + step), Math.sin(a + step)); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Colors.get_red(), Dates.empty()); - index++; - } - index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(Math.cos(a), Math.sin(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1))); - var pnt2 = Vector3d.create(Math.cos(a), Math.sin(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1))); - var pnt3 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1))); - var pnt4 = Vector3d.create(Math.cos(a + step), Math.sin(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1))); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt3, pnt2, pnt4, Colors.get_blue(), Dates.empty()); - index++; - } - index = 0; - for (var a = 0; a < twoPi; a += step) { - var start = !(index % 10); - var end = !((index + 1) % 10); - var pnt1 = Vector3d.create(Math.cos(a), -rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); - var pnt2 = Vector3d.create(Math.cos(a), rad * ((start) ? 0 : ((end) ? 1.5 : 1)), Math.sin(a)); - var pnt3 = Vector3d.create(Math.cos(a + step), -rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); - var pnt4 = Vector3d.create(Math.cos(a + step), rad * ((start) ? 1.5 : ((end) ? 0 : 1)), Math.sin(a + step)); - Object3dLayer._rotateUi$1.addQuad(pnt1, pnt2, pnt3, pnt4, Colors.get_green(), Dates.empty()); - index++; - } - }; - var Object3dLayer$ = { - getPrimaryUI: function () { - if (this._primaryUI$1 == null) { - this._primaryUI$1 = new Object3dLayerUI(this); - } - return this._primaryUI$1; - }, - get_flipV: function () { - return this._flipV$1; - }, - set_flipV: function (value) { - if (this._flipV$1 !== value) { - this._flipV$1 = value; - if (this.object3d != null) { - this.object3d.flipV = this._flipV$1; - this.object3d._reload(); - } - this.version++; - } - return value; - }, - get_flipHandedness: function () { - return this._flipHandedness$1; - }, - set_flipHandedness: function (value) { - if (this._flipHandedness$1 !== value) { - this._flipHandedness$1 = value; - if (this.object3d != null) { - this.object3d.flipHandedness = this._flipHandedness$1; - this.object3d._reload(); - } - this.version++; - } - return value; - }, - get_smooth: function () { - return this._smooth$1; - }, - set_smooth: function (value) { - if (this._smooth$1 !== value) { - this._smooth$1 = value; - if (this.object3d != null) { - this.object3d.smooth = this._smooth$1; - this.object3d._reload(); - } - this.version++; - } - return value; - }, - get_twoSidedGeometry: function () { - return this._twoSidedGeometry$1; - }, - set_twoSidedGeometry: function (value) { - if (this._twoSidedGeometry$1 !== value) { - this._twoSidedGeometry$1 = value; - this.version++; - } - return value; - }, - get_heading: function () { - return this._heading$1; - }, - set_heading: function (value) { - if (this._heading$1 !== value) { - this.version++; - this._heading$1 = value; - } - return value; - }, - get_pitch: function () { - return this._pitch$1; - }, - set_pitch: function (value) { - if (this._pitch$1 !== value) { - this.version++; - this._pitch$1 = value; - } - return value; - }, - get_roll: function () { - return this._roll$1; - }, - set_roll: function (value) { - if (this._roll$1 !== value) { - this.version++; - this._roll$1 = value; - } - return value; - }, - get_scale: function () { - return this._scale$1; - }, - set_scale: function (value) { - if (this._scale$1 !== value) { - this.version++; - this._scale$1 = value; - } - return value; - }, - get_translate: function () { - return this._translate$1; - }, - set_translate: function (value) { - if (this._translate$1 !== value) { - this.version++; - this._translate$1 = value; - } - return value; - }, - get_lightID: function () { - return this._lightID$1; - }, - set_lightID: function (value) { - this._lightID$1 = value; - return value; - }, - cleanUp: function () { - this._dirty$1 = true; - }, - colorChanged: function () { - if (this.object3d != null) { - this.object3d.color = this.get_color(); - } - }, - writeLayerProperties: function (xmlWriter) { - xmlWriter._writeAttributeString('FlipV', this.get_flipV().toString()); - xmlWriter._writeAttributeString('FlipHandedness', this.get_flipHandedness().toString()); - xmlWriter._writeAttributeString('Smooth', this.get_smooth().toString()); - xmlWriter._writeAttributeString('TwoSidedGeometry', this.get_twoSidedGeometry().toString()); - xmlWriter._writeAttributeString('Heading', this.get_heading().toString()); - xmlWriter._writeAttributeString('Pitch', this.get_pitch().toString()); - xmlWriter._writeAttributeString('Roll', this.get_roll().toString()); - xmlWriter._writeAttributeString('Scale', this.get_scale().toString()); - xmlWriter._writeAttributeString('Translate', this.get_translate().toString()); - xmlWriter._writeAttributeString('LightID', this.get_lightID().toString()); - xmlWriter._writeAttributeString('Obj', this.objType.toString()); - }, - getParams: function () { - var paramList = new Array(14); - paramList[0] = this._heading$1; - paramList[1] = this._pitch$1; - paramList[2] = this._roll$1; - paramList[3] = this._scale$1.x; - paramList[4] = this._scale$1.y; - paramList[5] = this._scale$1.z; - paramList[6] = this._translate$1.x; - paramList[7] = this._translate$1.y; - paramList[8] = this._translate$1.z; - paramList[9] = this.get_color().r / 255; - paramList[10] = this.get_color().g / 255; - paramList[11] = this.get_color().b / 255; - paramList[12] = this.get_color().a / 255; - paramList[13] = this.get_opacity(); - return paramList; - }, - getParamNames: function () { - return ['Heading', 'Pitch', 'Roll', 'Scale.X', 'Scale.Y', 'Scale.Z', 'Translate.X', 'Translate.Y', 'Translate.Z', 'Colors.Red', 'Colors.Green', 'Colors.Blue', 'Colors.Alpha', 'Opacity']; - }, - setParams: function (paramList) { - if (paramList.length === 14) { - this._heading$1 = paramList[0]; - this._pitch$1 = paramList[1]; - this._roll$1 = paramList[2]; - this._scale$1.x = paramList[3]; - this._scale$1.y = paramList[4]; - this._scale$1.z = paramList[5]; - this._translate$1.x = paramList[6]; - this._translate$1.y = paramList[7]; - this._translate$1.z = paramList[8]; - this.set_opacity(paramList[13]); - var color = Color.fromArgb(ss.truncate((paramList[12] * 255)), ss.truncate((paramList[9] * 255)), ss.truncate((paramList[10] * 255)), ss.truncate((paramList[11] * 255))); - this.set_color(color); - } - }, - add_propertiesChanged: function (value) { - this.__propertiesChanged$1 = ss.bindAdd(this.__propertiesChanged$1, value); - }, - remove_propertiesChanged: function (value) { - this.__propertiesChanged$1 = ss.bindSub(this.__propertiesChanged$1, value); - }, - fireChanged: function () { - if (this.__propertiesChanged$1 != null) { - this.__propertiesChanged$1(this, new ss.EventArgs()); - } - }, - getEditUI: function () { - return ss.safeCast(this, IUiController); - }, - initializeFromXml: function (node) { - this.set_flipV(ss.boolean(node.attributes.getNamedItem('FlipV').nodeValue)); - if (node.attributes.getNamedItem('FlipHandedness') != null) { - this.set_flipHandedness(ss.boolean(node.attributes.getNamedItem('FlipHandedness').nodeValue)); - } - else { - this.set_flipHandedness(false); - } - if (node.attributes.getNamedItem('Smooth') != null) { - this.set_smooth(ss.boolean(node.attributes.getNamedItem('Smooth').nodeValue)); - } - else { - this.set_smooth(true); - } - if (node.attributes.getNamedItem('TwoSidedGeometry') != null) { - this.set_twoSidedGeometry(ss.boolean(node.attributes.getNamedItem('TwoSidedGeometry').nodeValue)); - } - else { - this.set_twoSidedGeometry(false); - } - if (node.attributes.getNamedItem('Obj') != null) { - this.objType = ss.boolean(node.attributes.getNamedItem('Obj').nodeValue); - } - else { - this.objType = false; - } - this.set_heading(parseFloat(node.attributes.getNamedItem('Heading').nodeValue)); - this.set_pitch(parseFloat(node.attributes.getNamedItem('Pitch').nodeValue)); - this.set_roll(parseFloat(node.attributes.getNamedItem('Roll').nodeValue)); - this.set_scale(Vector3d.parse(node.attributes.getNamedItem('Scale').nodeValue)); - this.set_translate(Vector3d.parse(node.attributes.getNamedItem('Translate').nodeValue)); - if (node.attributes.getNamedItem('LightID') != null) { - this.set_lightID(parseInt(node.attributes.getNamedItem('LightID').nodeValue)); - } - }, - draw: function (renderContext, opacity, flat) { - var oldWorld = renderContext.get_world(); - var rotation = Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d._rotationZ(-this._roll$1 / 180 * Math.PI), Matrix3d._rotationX(-this._pitch$1 / 180 * Math.PI)), Matrix3d._rotationY(this._heading$1 / 180 * Math.PI)); - renderContext.set_world(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(Matrix3d.multiplyMatrix(rotation, Matrix3d._scaling(this._scale$1.x, this._scale$1.y, this._scale$1.z)), Matrix3d.translation(this._translate$1)), oldWorld)); - renderContext.set_twoSidedLighting(this.get_twoSidedGeometry()); - Planets.drawPointPlanet(renderContext, new Vector3d(), 1, Colors.get_red(), false); - if (this._lightID$1 > 0) { - } - else { - if (this.object3d != null) { - this.object3d.color = this.get_color(); - this.object3d.render(renderContext, opacity * this.get_opacity()); - } - } - renderContext.set_twoSidedLighting(false); - renderContext.set_world(oldWorld); - return true; - }, - addFilesToCabinet: function (fc) { - }, - loadData: function (doc, filename) { - if (ss.endsWith(filename.toLowerCase(), '.obj')) { - this.objType = true; - } - if (!this._lightID$1) { - if (this.objType) { - this.object3d = new Object3d(doc, ss.replaceString(filename, '.txt', '.obj'), this.get_flipV(), this._flipHandedness$1, true, this.get_color()); - } - else { - this.object3d = new Object3d(doc, ss.replaceString(filename, '.txt', '.3ds'), this.get_flipV(), this._flipHandedness$1, true, this.get_color()); - } - } - }, - pointToView: function (pnt) { - var clientHeight = WWTControl.singleton.renderContext.height; - var clientWidth = WWTControl.singleton.renderContext.width; - var viewWidth = (WWTControl.singleton.renderContext.width / WWTControl.singleton.renderContext.height) * 1116; - var x = ((pnt.x) / (clientWidth) * viewWidth) - ((viewWidth - 1920) / 2); - var y = (pnt.y) / clientHeight * 1116; - return Vector2d.create(x, y); - }, - render: function (renderEngine) { - this._showEditUi$1 = true; - return; - }, - preRender: function (renderEngine) { - this._showEditUi$1 = true; - return; - }, - mouseDown: function (sender, e) { - var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - this._pntDown$1 = location; - var pnt = location; - if (e.shiftKey) { - if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 10; - this._valueOnDown$1 = this._scale$1.x; - return true; - } - if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 10; - this._valueOnDown$1 = this._scale$1.y; - return true; - } - if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 10; - this._valueOnDown$1 = this._scale$1.z; - return true; - } - } - else { - if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 1; - this._valueOnDown$1 = this._translate$1.x; - return true; - } - if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 2; - this._valueOnDown$1 = this._translate$1.y; - return true; - } - if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { - this._dragMode$1 = 3; - this._valueOnDown$1 = this._translate$1.z; - return true; - } - } - for (var i = 0; i < this._hprHandles$1.length; i++) { - if (Vector2d.subtract(pnt, this._hprHandles$1[i]).get_length() < this._hitDist$1) { - switch (i) { - case 0: - this._dragMode$1 = 4; - this._valueOnDown$1 = this._heading$1; - this._valueOnDown2$1 = this._pitch$1; - return true; - case 1: - this._dragMode$1 = 7; - this._valueOnDown$1 = this._heading$1; - this._valueOnDown2$1 = this._pitch$1; - return true; - case 2: - this._dragMode$1 = 5; - this._valueOnDown$1 = this._pitch$1; - this._valueOnDown2$1 = this._roll$1; - return true; - case 3: - this._dragMode$1 = 8; - this._valueOnDown$1 = this._pitch$1; - this._valueOnDown2$1 = this._roll$1; - return true; - case 4: - this._dragMode$1 = 6; - this._valueOnDown$1 = this._roll$1; - this._valueOnDown2$1 = this._heading$1; - return true; - case 5: - this._dragMode$1 = 9; - this._valueOnDown$1 = this._roll$1; - this._valueOnDown2$1 = this._heading$1; - return true; - default: - break; - } - } - } - return false; - }, - mouseUp: function (sender, e) { - if (!!this._dragMode$1) { - this._dragMode$1 = 0; - this._lockPreferedAxis$1 = false; - return true; - } - return false; - }, - mouseMove: function (sender, e) { - var location = this.pointToView(Vector2d.create(e.offsetX, e.offsetY)); - if (!!this._dragMode$1) { - var dist = 0; - var distX = location.x - this._pntDown$1.x; - var distY = -(location.y - this._pntDown$1.y); - if (this._lockPreferedAxis$1) { - if (this._preferY$1) { - dist = distY; - this._preferY$1 = true; - Cursor.set_current(Cursors.get_sizeNS()); - } - else { - dist = distX; - this._preferY$1 = false; - Cursor.set_current(Cursors.get_sizeWE()); - } - } - else { - if (Math.abs(distX) > Math.abs(distY)) { - dist = distX; - this._preferY$1 = false; - } - else { - dist = distY; - this._preferY$1 = true; - } - if (dist > 5) { - this._lockPreferedAxis$1 = true; - } - } - switch (this._dragMode$1) { - case 0: - break; - case 1: - this._translate$1.x = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / WWTControl.singleton.renderContext.width)); - break; - case 2: - this._translate$1.y = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / WWTControl.singleton.renderContext.width)); - break; - case 3: - this._translate$1.z = this._valueOnDown$1 + (12 * this._uiScale$1 * (dist / WWTControl.singleton.renderContext.width)); - break; - case 4: - this._heading$1 = this._valueOnDown$1 - distX / 4; - this._pitch$1 = this._valueOnDown2$1 + distY / 4; - break; - case 5: - this._pitch$1 = this._valueOnDown$1 + distY / 4; - this._roll$1 = this._valueOnDown2$1 - distX / 4; - break; - case 6: - this._roll$1 = this._valueOnDown$1 + distY / 4; - this._heading$1 = this._valueOnDown2$1 - distX / 4; - break; - case 7: - this._heading$1 = this._valueOnDown$1 - distX / 4; - this._pitch$1 = this._valueOnDown2$1 - distY / 4; - break; - case 8: - this._pitch$1 = this._valueOnDown$1 + distY / 4; - this._roll$1 = this._valueOnDown2$1 + distX / 4; - break; - case 9: - this._roll$1 = this._valueOnDown$1 - distY / 4; - this._heading$1 = this._valueOnDown2$1 - distX / 4; - break; - case 10: - this._scale$1.x = this._scale$1.y = this._scale$1.z = this._valueOnDown$1 * Math.pow(2, (dist / 100)); - break; - default: - break; - } - this.fireChanged(); - return true; - } - else { - var pnt = location; - if (Vector2d.subtract(pnt, this._xHandle$1).get_length() < this._hitDist$1) { - Cursor.set_current(Cursors.get_sizeAll()); - return true; - } - if (Vector2d.subtract(pnt, this._yHandle$1).get_length() < this._hitDist$1) { - Cursor.set_current(Cursors.get_sizeAll()); - return true; - } - if (Vector2d.subtract(pnt, this._zHandle$1).get_length() < this._hitDist$1) { - Cursor.set_current(Cursors.get_sizeAll()); - return true; - } - for (var i = 0; i < this._hprHandles$1.length; i++) { - if (Vector2d.subtract(pnt, this._hprHandles$1[i]).get_length() < this._hitDist$1) { - Cursor.set_current(Cursors.get_sizeAll()); - return true; - } - } - } - return false; - }, - mouseClick: function (sender, e) { - return false; - }, - click: function (sender, e) { - return false; - }, - mouseDoubleClick: function (sender, e) { - return false; - }, - keyDown: function (sender, e) { - return false; - }, - keyUp: function (sender, e) { - return false; - }, - hover: function (pnt) { - return false; - } - }; - - - // wwtlib.Object3dLayerUI - - function Object3dLayerUI(layer) { - this._layer$1 = null; - this._opened$1 = true; - this._callbacks$1 = null; - LayerUI.call(this); - this._layer$1 = layer; - } - var Object3dLayerUI$ = { - setUICallbacks: function (callbacks) { - this._callbacks$1 = callbacks; - }, - get_hasTreeViewNodes: function () { - return true; - }, - getTreeNodes: function () { - var nodes = []; - if (this._layer$1.object3d.objects.length > 0 && this._layer$1.object3d.objects[0].children != null) { - this._loadTree$1(nodes, this._layer$1.object3d.objects[0].children); - } - return nodes; - }, - _loadTree$1: function (nodes, children) { - var $enum1 = ss.enumerate(children); - while ($enum1.moveNext()) { - var child = $enum1.current; - var node = new LayerUITreeNode(); - node.set_name(child.name); - node.set_tag(child); - node.set_checked(child.enabled); - node.add_nodeSelected(ss.bind('_node_NodeSelected$1', this)); - node.add_nodeChecked(ss.bind('_node_NodeChecked$1', this)); - nodes.push(node); - this._loadTree$1(node.get_nodes(), child.children); - } - }, - _node_NodeChecked$1: function (node, newState) { - var child = node.get_tag(); - if (child != null) { - child.enabled = newState; - } - }, - _node_NodeSelected$1: function (node) { - if (this._callbacks$1 != null) { - var child = node.get_tag(); - var rowData = {}; - rowData['Name'] = child.name; - rowData['Pivot.X'] = child.pivotPoint.x.toString(); - rowData['Pivot.Y'] = child.pivotPoint.y.toString(); - rowData['Pivot.Z'] = child.pivotPoint.z.toString(); - this._callbacks$1.showRowData(rowData); - } - }, - getNodeContextMenu: function (node) { - return LayerUI.prototype.getNodeContextMenu.call(this, node); - } - }; - - - // wwtlib.OrbitLayer - - function OrbitLayer() { - this._frames$1 = []; - this._primaryUI$1 = null; - this._pointOpacity$1 = 1; - this._pointColor$1 = Colors.get_yellow(); - this._filename$1 = ''; - this._dataFile$1 = ''; - Layer.call(this); - } - var OrbitLayer$ = { - get_frames: function () { - return this._frames$1; - }, - set_frames: function (value) { - this._frames$1 = value; - return value; - }, - getPrimaryUI: function () { - if (this._primaryUI$1 == null) { - this._primaryUI$1 = new OrbitLayerUI(this); - } - return this._primaryUI$1; - }, - cleanUp: function () { - var $enum1 = ss.enumerate(this._frames$1); - while ($enum1.moveNext()) { - var frame = $enum1.current; - if (frame.get_orbit() != null) { - frame.get_orbit().cleanUp(); - frame.set_orbit(null); - } - } - }, - writeLayerProperties: function (xmlWriter) { - xmlWriter._writeAttributeString('PointOpacity', this.get_pointOpacity().toString()); - xmlWriter._writeAttributeString('PointColor', this._pointColor$1.save()); - }, - get_pointOpacity: function () { - return this._pointOpacity$1; - }, - set_pointOpacity: function (value) { - if (this._pointOpacity$1 !== value) { - this.version++; - this._pointOpacity$1 = value; - } - return value; - }, - get_pointColor: function () { - return this._pointColor$1; - }, - set_pointColor: function (value) { - if (this._pointColor$1 !== value) { - this.version++; - this._pointColor$1 = value; - } - return value; - }, - getParams: function () { - var paramList = new Array(6); - paramList[0] = this._pointOpacity$1; - paramList[1] = this.get_color().r / 255; - paramList[2] = this.get_color().g / 255; - paramList[3] = this.get_color().b / 255; - paramList[4] = this.get_color().a / 255; - paramList[5] = this.get_opacity(); - return paramList; - }, - getParamNames: function () { - return ['PointOpacity', 'Color.Red', 'Color.Green', 'Color.Blue', 'Color.Alpha', 'Opacity']; - }, - setParams: function (paramList) { - if (paramList.length === 6) { - this._pointOpacity$1 = paramList[0]; - this.set_opacity(paramList[5]); - var color = Color.fromArgb(ss.truncate((paramList[4] * 255)), ss.truncate((paramList[1] * 255)), ss.truncate((paramList[2] * 255)), ss.truncate((paramList[3] * 255))); - this.set_color(color); - } - }, - initializeFromXml: function (node) { - this.set_pointOpacity(parseFloat(node.attributes.getNamedItem('PointOpacity').nodeValue)); - this.set_pointColor(Color.load(node.attributes.getNamedItem('PointColor').nodeValue)); - }, - draw: function (renderContext, opacity, flat) { - var matSaved = renderContext.get_world(); - renderContext.set_world(renderContext.get_worldBaseNonRotating()); - var $enum1 = ss.enumerate(this._frames$1); - while ($enum1.moveNext()) { - var frame = $enum1.current; - if (frame.showOrbitPath) { - if (frame.get_orbit() == null) { - frame.set_orbit(new Orbit(frame.get_elements(), 360, this.get_color(), 1, renderContext.get_nominalRadius())); - } - frame.get_orbit().draw3D(renderContext, opacity * this.get_opacity(), new Vector3d()); - } - } - renderContext.set_world(matSaved); - return true; - }, - addFilesToCabinet: function (fc) { - this._filename$1 = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); - var dir = this._filename$1.substring(0, this._filename$1.lastIndexOf('\\')); - var blob = new Blob([this._dataFile$1]); - fc.addFile(this._filename$1, blob); - Layer.prototype.addFilesToCabinet.call(this, fc); - }, - loadData: function (tourDoc, filename) { - var $this = this; - - var blob = tourDoc.getFileBlob(filename); - var doc = new FileReader(); - doc.onloadend = function (ee) { - $this._dataFile$1 = ss.safeCast(doc.result, String); - $this.loadString($this._dataFile$1); - }; - doc.readAsText(blob); - }, - loadString: function (dataFile) { - var data = dataFile.split('\n'); - this._frames$1.length = 0; - for (var i = 0; i < data.length; i += 2) { - var line1 = i; - var line2 = i + 1; - if (data[i].length > 0) { - var frame = new ReferenceFrame(); - if (data[i].substring(0, 1) !== '1') { - line1++; - line2++; - frame.name = ss.trim(data[i]); - i++; - } - else if (data[i].substring(0, 1) === '1') { - frame.name = data[i].substring(2, 5); - } - else { - i -= 2; - continue; - } - frame.reference = 18; - frame.oblateness = 0; - frame.showOrbitPath = true; - frame.showAsPoint = true; - frame.referenceFrameType = 1; - frame.scale = 1; - frame.semiMajorAxisUnits = 1; - frame.meanRadius = 10; - frame.oblateness = 0; - frame.fromTLE(data[line1], data[line2], 398600441800000); - this._frames$1.push(frame); - } - else { - i -= 1; - } - } - } - }; - - - // wwtlib.OrbitLayerUI - - function OrbitLayerUI(layer) { - this._layer$1 = null; - this._opened$1 = true; - this._callbacks$1 = null; - LayerUI.call(this); - this._layer$1 = layer; - } - var OrbitLayerUI$ = { - setUICallbacks: function (callbacks) { - this._callbacks$1 = callbacks; - }, - get_hasTreeViewNodes: function () { - return true; - }, - getTreeNodes: function () { - var nodes = []; - var $enum1 = ss.enumerate(this._layer$1.get_frames()); - while ($enum1.moveNext()) { - var frame = $enum1.current; - var node = new LayerUITreeNode(); - node.set_name(frame.name); - node.set_tag(frame); - node.set_checked(frame.showOrbitPath); - node.add_nodeSelected(ss.bind('_node_NodeSelected$1', this)); - node.add_nodeChecked(ss.bind('_node_NodeChecked$1', this)); - nodes.push(node); - } - return nodes; - }, - _node_NodeChecked$1: function (node, newState) { - var frame = node.get_tag(); - if (frame != null) { - frame.showOrbitPath = newState; - } - }, - _node_NodeSelected$1: function (node) { - if (this._callbacks$1 != null) { - var frame = node.get_tag(); - var rowData = {}; - rowData['Name'] = frame.name; - rowData['SemiMajor Axis'] = frame.semiMajorAxis.toString(); - rowData['SMA Units'] = frame.semiMajorAxisUnits.toString(); - rowData['Inclination'] = frame.inclination.toString(); - rowData['Eccentricity'] = frame.eccentricity.toString(); - rowData['Long of Asc. Node'] = frame.longitudeOfAscendingNode.toString(); - rowData['Argument Of Periapsis'] = frame.argumentOfPeriapsis.toString(); - rowData['Epoch'] = frame.epoch.toString(); - rowData['Mean Daily Motion'] = frame.meanDailyMotion.toString(); - rowData['Mean Anomoly at Epoch'] = frame.meanAnomolyAtEpoch.toString(); - this._callbacks$1.showRowData(rowData); - } - }, - getNodeContextMenu: function (node) { - return LayerUI.prototype.getNodeContextMenu.call(this, node); - } - }; - - - // wwtlib.SpreadSheetLayer - - function SpreadSheetLayer() { - this._dataDirty$1 = false; - this._lastNormalizeSizeColumnIndex$1 = -1; - this._lastDynamicColorColumnIndex$1 = -1; - this._table_backcompat$1 = null; - this._barChartBitmask$1 = 0; - this._barScaleFactor$1 = 20; - this._meanRadius$1 = 6371000; - this._table$1 = new Table(); - this.isLongIndex = false; - this.shapeVertexCount = 0; - this.lines = false; - this.latColumn = -1; - this.fixedSize = 1; - this.decay = 16; - this.timeSeries = false; - this._dynamicData$1 = false; - this._autoUpdate$1 = false; - this._dataSourceUrl$1 = ''; - this._beginRange$1 = new Date('1/1/2100'); - this._endRange$1 = new Date('01/01/1800'); - this.markerDomainValues = {}; - this.colorDomainValues = {}; - this._coordinatesType$1 = 0; - this.lngColumn = -1; - this.geometryColumn = -1; - this._xAxisColumn$1 = -1; - this._yAxisColumn$1 = -1; - this._zAxisColumn$1 = -1; - this._xAxisReverse$1 = false; - this._yAxisReverse$1 = false; - this._zAxisReverse$1 = false; - this._altType$1 = 3; - this._markerMix$1 = 0; - this._raUnits$1 = 0; - this.colorMap = 3; - this.colorMapperName = 'Greys'; - this._dynamicColorColumnName$1 = '2efc32e3-b9d9-47ff-8036-8cc344c585bd'; - this.dynamicColor = false; - this.normalizeColorMap = false; - this.normalizeColorMapMin = 0; - this.normalizeColorMapMax = 1; - this._markerColumn$1 = -1; - this.colorMapColumn = -1; - this._plotType$1 = 0; - this._markerIndex$1 = 0; - this._showFarSide$1 = false; - this._markerScale$1 = 1; - this._altUnit$1 = 1; - this._cartesianScale$1 = 1; - this._cartesianCustomScale$1 = 1; - this.altColumn = -1; - this.startDateColumn = -1; - this.endDateColumn = -1; - this.sizeColumn = -1; - this._normalizeSizeColumnName$1 = 'dfe78b4c-f972-4796-b04f-68c5efd4ecb0'; - this.normalizeSize = false; - this.normalizeSizeClip = false; - this.normalizeSizeMin = 0; - this.normalizeSizeMax = 1; - this.nameColumn = 0; - this._hyperlinkFormat$1 = ''; - this._hyperlinkColumn$1 = -1; - this.scaleFactor = 1; - this.pointScaleType = 1; - this.positions = []; - this.bufferIsFlat = false; - this.baseDate = new Date(2010, 0, 1, 12, 0, 0); - this.dirty = true; - this.lastVersion = 0; - Layer.call(this); - } - SpreadSheetLayer._getDatafromFeed$1 = function (url) { - return ''; - }; - SpreadSheetLayer._executeQuery$1 = function (url) { - return ''; - }; - SpreadSheetLayer.parseDate = function (date) { - var dt = ss.now(); - try { - dt = new Date(date); - } - catch ($e1) { - try { - return SpreadSheetLayer.execlToDateTime(parseFloat(date)); - } - catch ($e2) { - } - } - return dt; - }; - SpreadSheetLayer.execlToDateTime = function (excelDate) { - if (excelDate > 59) { - excelDate -= 1; - } - if (excelDate > 730000) { - excelDate = 730000; - } - var es = new Date(1899, 12, 31); - return new Date(es.getDate() + ss.truncate((excelDate * 24 * 60 * 60 * 1000))); - }; - SpreadSheetLayer.get__circleTexture$1 = function () { - if (SpreadSheetLayer._circleTexture$1 == null) { - var url = URLHelpers.singleton.engineAssetUrl('circle.png'); - SpreadSheetLayer._circleTexture$1 = Planets.loadPlanetTexture(url); - } - return SpreadSheetLayer._circleTexture$1; - }; - var SpreadSheetLayer$ = { - getTypeName: function () { - return 'TerraViewer.SpreadSheetLayer'; - }, - get_header: function () { - return this._table$1.header; - }, - canCopyToClipboard: function () { - return true; - }, - copyToClipboard: function () { - }, - dynamicUpdate: function () { - var data = SpreadSheetLayer._getDatafromFeed$1(this.get_dataSourceUrl()); - if (data != null) { - this.updateData(data, false, true, true); - this.guessHeaderAssignments(); - return true; - } - return false; - }, - updateData: function (data, purgeOld, purgeAll, hasHeader) { - this.loadFromString(ss.safeCast(data, String), true, purgeOld, purgeAll, hasHeader); - this.computeDateDomainRange(-1, -1); - this._dataDirty$1 = true; - this.dirty = true; - return true; - }, - loadData: function (tourDoc, filename) { - var $this = this; - - this._table$1 = new Table(); - var blob = tourDoc.getFileBlob(filename); - this.getStringFromGzipBlob(blob, function (data) { - $this._table$1.loadFromString(data, false, true, true); - if ($this._table$1.header.indexOf($this._normalizeSizeColumnName$1) > -1) { - $this._table$1.removeColumn($this._normalizeSizeColumnName$1); - } - $this.computeDateDomainRange(-1, -1); - if ($this.get_dynamicData() && $this.get_autoUpdate()) { - $this.dynamicUpdate(); - } - $this._dataDirty$1 = true; - $this.dirty = true; - }); - }, - addFilesToCabinet: function (fc) { - this._fileName$1 = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); - var dir = this._fileName$1.substring(0, this._fileName$1.lastIndexOf('\\')); - var data = ''; - if (this._table_backcompat$1 == null) { - data = this._table$1.save(); - } - else { - data = this._table_backcompat$1.save(); - } - var blob = new Blob([data]); - fc.addFile(this._fileName$1, blob); - Layer.prototype.addFilesToCabinet.call(this, fc); - }, - _prepareBackCompatTable$1: function () { - if ((this.sizeColumn === -1 || !this.get_normalizeSize()) && (this.colorMapColumn === -1 || !this.get_dynamicColor())) { - this._lastNormalizeSizeColumnIndex$1 = -1; - this._lastDynamicColorColumnIndex$1 = -1; - return; - } - this._table_backcompat$1 = this._table$1.clone(); - if (this.sizeColumn > -1 && this.get_normalizeSize()) { - var normalizedPointSize = []; - var $enum1 = ss.enumerate(this._table_backcompat$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - normalizedPointSize.push(this.normalizePointSize(parseFloat(row[this.sizeColumn])).toString()); - } - this._table_backcompat$1.addColumn(this._normalizeSizeColumnName$1, normalizedPointSize); - this._lastNormalizeSizeColumnIndex$1 = this._table_backcompat$1.header.length - 1; - } - else { - this._lastNormalizeSizeColumnIndex$1 = -1; - } - if (this.colorMapColumn > -1 && this.get_dynamicColor()) { - var pointColors = []; - var $enum2 = ss.enumerate(this._table_backcompat$1.rows); - while ($enum2.moveNext()) { - var row = $enum2.current; - pointColors.push(this.get_colorMapper().findClosestColor(this.normalizeColorMapValue(parseFloat(row[this.get_colorMapColumn()]))).toSimpleHex()); - } - this._table_backcompat$1.addColumn(this._dynamicColorColumnName$1, pointColors); - this._lastDynamicColorColumnIndex$1 = this._table_backcompat$1.header.length - 1; - } - else { - this._lastDynamicColorColumnIndex$1 = -1; - } - }, - guessHeaderAssignments: function () { - var index = 0; - var $enum1 = ss.enumerate(this._table$1.header); - while ($enum1.moveNext()) { - var headerName = $enum1.current; - this._guessHeaderAssignment$1(headerName, index++); - } - if (this._table$1.header.length > 0) { - this.nameColumn = 0; - } - }, - guessHeaderAssignmentsFromVoTable: function (votable) { - var decColumn = votable.getDecColumn(); - if (decColumn != null) { - this.latColumn = decColumn.index; - this.astronomical = true; - } - var raColumn = votable.getRAColumn(); - if (raColumn != null) { - this.lngColumn = raColumn.index; - this.astronomical = true; - this.pointScaleType = 4; - } - var magColumn = votable.getMagColumn(); - if (magColumn != null) { - this.sizeColumn = magColumn.index; - } - var index = 0; - var $enum1 = ss.enumerate(votable.column); - while ($enum1.moveNext()) { - var column = $enum1.current; - this._guessHeaderAssignment$1(column.name, index++); - } - if (this._table$1.header.length > 0) { - this.nameColumn = 0; - } - }, - _guessHeaderAssignment$1: function (name, index) { - name = name.toLowerCase(); - if (name.indexOf('lat') > -1 && this.latColumn === -1) { - this.latColumn = index; - } - if ((name.indexOf('lon') > -1 || name.indexOf('lng') > -1) && this.lngColumn === -1) { - this.lngColumn = index; - } - if (name.indexOf('dec') > -1 && this.latColumn === -1) { - this.latColumn = index; - this.astronomical = true; - } - if ((name.indexOf('ra') > -1 || name.indexOf('ascen') > -1) && this.lngColumn === -1) { - this.lngColumn = index; - this.astronomical = true; - this.pointScaleType = 4; - } - if ((name.indexOf('mag') > -1 || name.indexOf('size') > -1) && this.sizeColumn === -1) { - this.sizeColumn = index; - } - if ((name.indexOf('date') > -1 || name.indexOf('time') > -1 || name.indexOf('dt') > -1 || name.indexOf('tm') > -1)) { - if (name.indexOf('end') > -1 && this.endDateColumn === -1) { - this.endDateColumn = index; - } - else if (this.startDateColumn === -1) { - this.startDateColumn = index; - } - } - if ((name.indexOf('altitude') > -1 || name.indexOf('alt') > -1) && this.altColumn === -1) { - this.altColumn = index; - this.set_altType(1); - this.set_altUnit(1); - } - if (name.indexOf('depth') > -1 && this.altColumn === -1) { - this.altColumn = index; - this.set_altType(0); - this.set_altUnit(5); - } - if (ss.startsWith(name, 'x') && this.get_xAxisColumn() === -1) { - this.set_xAxisColumn(index); - } - if (ss.startsWith(name, 'y') && this.get_yAxisColumn() === -1) { - this.set_yAxisColumn(index); - } - if (ss.startsWith(name, 'z') && this.get_zAxisColumn() === -1) { - this.set_zAxisColumn(index); - } - if (name.indexOf('color') > -1 && this.get_colorMapColumn() === -1) { - this.set_colorMapColumn(index); - } - if ((name.indexOf('geometry') > -1 || name.indexOf('geography') > -1) && this.geometryColumn === -1) { - this.geometryColumn = index; - } - }, - computeDateDomainRange: function (columnStart, columnEnd) { - if (columnStart === -1) { - columnStart = this.startDateColumn; - } - if (columnEnd === -1) { - columnEnd = this.endDateColumn; - } - if (columnEnd === -1) { - columnEnd = columnStart; - } - this.set_beginRange(new Date('12/31/2100')); - this.set_endRange(new Date('12/31/1890')); - var $enum1 = ss.enumerate(this._table$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - try { - if (columnStart > -1) { - var sucsess = true; - var dateTimeStart = new Date('12/31/2100'); - try { - dateTimeStart = new Date(row[columnStart]); - if (dateTimeStart < this.get_beginRange()) { - this.set_beginRange(dateTimeStart); - } - } - catch ($e2) { - } - try { - var dateTimeEnd = new Date('12/31/1890'); - if (columnEnd > -1) { - dateTimeEnd = new Date(row[columnEnd]); - if (sucsess && dateTimeEnd > this.get_endRange()) { - this.set_endRange(dateTimeEnd); - } - } - } - catch ($e3) { - } - } - } - catch ($e4) { - } - } - }, - checkState: function () { - }, - getMaxValue: function (column) { - var max = 0; - this._table$1.lock(); - var $enum1 = ss.enumerate(this._table$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - try { - if (column > -1) { - var sucsess = true; - try { - var val = parseFloat(row[column]); - if (sucsess && val > max) { - max = val; - } - } - catch ($e2) { - } - } - } - catch ($e3) { - } - } - this._table$1.unlock(); - return max; - }, - getDomainValues: function (column) { - var domainValues = []; - this._table$1.lock(); - var $enum1 = ss.enumerate(this._table$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - try { - if (column > -1) { - if (!(domainValues.indexOf(row[column]) >= 0)) { - domainValues.push(row[column]); - } - } - } - catch ($e2) { - } - } - domainValues.sort(); - this._table$1.unlock(); - return domainValues; - }, - get_barChartBitmask: function () { - return this._barChartBitmask$1; - }, - set_barChartBitmask: function (value) { - this._barChartBitmask$1 = value; - return value; - }, - _isPointInFrustum$1: function (position, frustum) { - var centerV4 = new Vector4d(position.x, position.y, position.z, 1); - for (var i = 0; i < 6; i++) { - if (frustum[i].dot(centerV4) < 0) { - return false; - } - } - return true; - }, - getTableDataInView: function () { - var data = ''; - var first = true; - var $enum1 = ss.enumerate(this.get_header()); - while ($enum1.moveNext()) { - var col = $enum1.current; - if (!first) { - data += '\t'; - } - else { - first = false; - } - data += col; - } - data += '\r\n'; - var $enum2 = ss.enumerate(this.get__table().rows); - while ($enum2.moveNext()) { - var row = $enum2.current; - var ra = parseFloat(row[this.get_lngColumn()]); - var dec = parseFloat(row[this.get_latColumn()]); - var position = Coordinates.geoTo3dDouble(dec, ra); - if (!this._isPointInFrustum$1(position, WWTControl.singleton.renderContext.get_frustum())) { - continue; - } - first = true; - var $enum3 = ss.enumerate(row); - while ($enum3.moveNext()) { - var col = $enum3.current; - if (!first) { - data += '\t'; - } - else { - first = false; - } - data += col; - } - data += '\r\n'; - } - return data; - }, - prepVertexBuffer: function (renderContext, opacity) { - this._table$1.lock(); - if (this.lineList != null) { - this.lineList.clear(); - } - if (this.lineList2d != null) { - this.lineList2d.clear(); - } - if (this.triangleList != null) { - this.triangleList.clear(); - } - if (this.pointList != null) { - this.pointList.clear(); - } - if (this.triangleList2d != null) { - this.triangleList2d.clear(); - } - if (this.lineList == null) { - this.lineList = new LineList(); - } - if (this.pointList == null) { - this.pointList = new PointList(renderContext); - } - this.lineList.timeSeries = this.timeSeries; - if (this.lineList2d == null) { - this.lineList2d = new LineList(); - this.lineList2d.set_depthBuffered(false); - } - this.lineList.timeSeries = this.timeSeries; - if (this.triangleList == null) { - this.triangleList = new TriangleList(); - } - if (this.triangleList2d == null) { - this.triangleList2d = new TriangleList(); - this.triangleList2d.depthBuffered = false; - } - this.positions.length = 0; - var currentIndex = 0; - var colorLocal = this.get_color(); - var ecliptic = Coordinates.meanObliquityOfEcliptic(SpaceTimeController.get_jNow()) / 180 * Math.PI; - var selectDomain = {}; - var mr = LayerManager.get_allMaps()[this.get_referenceFrame()].frame.meanRadius; - if (!!mr) { - this._meanRadius$1 = mr; - } - var position = new Vector3d(); - var pointSize = 0.0002; - var pointColor = Colors.get_white(); - var pointStartTime = 0; - var pointEndTime = 0; - var $enum1 = ss.enumerate(this._table$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - try { - if (this.geometryColumn > -1 || (!this.get_coordinatesType() && (this.lngColumn > -1 && this.latColumn > -1)) || ((this.get_coordinatesType() === 1) && (this.get_xAxisColumn() > -1 && this.get_yAxisColumn() > -1))) { - var Xcoord = 0; - var Ycoord = 0; - var Zcoord = 0; - var alt = 1; - var altitude = 0; - var distParces = 0; - var factor = this.getScaleFactor(this.get_altUnit(), 1); - if (this.altColumn === -1 || this.get_altType() === 3 || this.bufferIsFlat) { - alt = 1; - if ((this.astronomical & !this.bufferIsFlat) === 1) { - alt = 63239.6717 * 100; - } - } - else { - if (!this.get_altType()) { - factor = -factor; - } - alt = 0; - try { - alt = parseFloat(row[this.altColumn]); - } - catch ($e2) { - } - if (this.astronomical) { - factor = factor / (1000 * 149598000); - distParces = (alt * factor) / 206264.806; - altitude = (factor * alt); - alt = (factor * alt); - } - else if (this.get_altType() === 2) { - altitude = (factor * alt); - alt = (factor * alt / this._meanRadius$1); - } - else { - altitude = (factor * alt); - alt = 1 + (factor * alt / this._meanRadius$1); - } - } - if (!this.get_coordinatesType() && this.lngColumn > -1 && this.latColumn > -1) { - Xcoord = parseFloat(row[this.lngColumn]); - Ycoord = parseFloat(row[this.latColumn]); - if (this.astronomical) { - if (!this.get_raUnits()) { - Xcoord *= 15; - } - if (this.bufferIsFlat) { - } - } - else { - Xcoord += 180; - } - var pos = Coordinates.geoTo3dRad(Ycoord, Xcoord, alt); - if (this.astronomical && !this.bufferIsFlat) { - pos.rotateX(ecliptic); - } - position = pos; - this.positions.push(position); - } - else if (this.get_coordinatesType() === 1) { - var xyzScale = this.getScaleFactor(this.get_cartesianScale(), this.get_cartesianCustomScale()); - if (this.astronomical) { - xyzScale /= (1000 * 149598000); - } - else { - xyzScale /= this._meanRadius$1; - } - if (this.get_zAxisColumn() > -1) { - Zcoord = parseFloat(row[this.get_zAxisColumn()]); - } - Xcoord = parseFloat(row[this.get_xAxisColumn()]); - Ycoord = parseFloat(row[this.get_yAxisColumn()]); - if (this.get_xAxisReverse()) { - Xcoord = -Xcoord; - } - if (this.get_yAxisReverse()) { - Ycoord = -Ycoord; - } - if (this.get_zAxisReverse()) { - Zcoord = -Zcoord; - } - position = Vector3d.create((Xcoord * xyzScale), (Zcoord * xyzScale), (Ycoord * xyzScale)); - this.positions.push(position); - } - switch (this.get_colorMap()) { - case 0: - pointColor = colorLocal; - break; - case 3: - if (this.get_colorMapColumn() > -1) { - if (this.get_dynamicColor()) { - pointColor = this.get_colorMapper().findClosestColor(this.normalizeColorMapValue(parseFloat(row[this.get_colorMapColumn()]))); - } - else { - pointColor = this._parseColor$1(row[this.get_colorMapColumn()], colorLocal); - } - } - else { - pointColor = colorLocal; - } - break; - default: - break; - } - if (pointColor == null) { - pointColor = Colors.get_transparent(); - } - if (this.sizeColumn > -1) { - switch (this.pointScaleType) { - case 0: - pointSize = parseFloat(row[this.sizeColumn]); - pointSize = this.normalizePointSize(pointSize); - break; - case 2: - pointSize = parseFloat(row[this.sizeColumn]); - pointSize = Math.log(pointSize); - break; - case 1: - try { - pointSize = parseFloat(row[this.sizeColumn]); - pointSize = this.normalizePointSize(pointSize); - pointSize = Math.pow(2, pointSize); - } - catch ($e3) { - pointSize = 0; - } - break; - case 4: - var size = 0; - try { - size = parseFloat(row[this.sizeColumn]); - if (!this.bufferIsFlat) { - size = size - 5 * (Util.logN(distParces, 10) - 1); - pointSize = (120000000 / Math.pow(1.6, size)); - } - else { - pointSize = (40 / Math.pow(1.6, size)); - } - } - catch ($e4) { - pointSize = 0; - } - break; - case 3: - pointSize = 1; - break; - default: - break; - } - } - else { - pointSize = 0.2; - } - if (this.get_plotType() === 1) { - pointSize = 1; - } - if ((this.astronomical & !this.bufferIsFlat) === 1) { - } - if (this.startDateColumn > -1) { - var dateTime = new Date(row[this.startDateColumn]); - pointStartTime = (SpaceTimeController.utcToJulian(dateTime) - SpaceTimeController.utcToJulian(this.baseDate)); - if (this.endDateColumn > -1) { - dateTime = new Date(row[this.endDateColumn]); - pointEndTime = (SpaceTimeController.utcToJulian(dateTime) - SpaceTimeController.utcToJulian(this.baseDate)); - } - else { - pointEndTime = pointStartTime; - } - } - this.pointList.addPoint(position, pointColor, new Dates(pointStartTime, pointEndTime), pointSize); - if (this.geometryColumn > -1) { - this._parseGeometry$1(row[this.geometryColumn], pointColor, pointColor, altitude, new Dates(pointStartTime, pointEndTime)); - } - currentIndex++; - } - } - catch ($e5) { - } - this.lines = false; - } - this._table$1.unlock(); - this._dataDirty$1 = false; - this.dirty = false; - return false; - }, - _parseGeometry$1: function (gs, lineColor, polyColor, alt, date) { - gs = ss.trim(gs).toLowerCase(); - var index = gs.indexOf('('); - if (index < 0) { - return; - } - if (!ss.endsWith(gs, ')')) { - return; - } - var commandPart = ss.trim(gs.substring(0, index)); - var parens = gs.substr(index); - var parts = commandPart.split(' '); - var command = null; - var mods = null; - if (parts.length > 0) { - var $enum1 = ss.enumerate(parts); - while ($enum1.moveNext()) { - var item = $enum1.current; - if (ss.emptyString(command)) { - command = item; - } - else if (ss.emptyString(mods)) { - mods = item; - } - } - } - switch (command) { - case 'multipolygon': - case 'polygon': - this._parsePolygon$1(parens, mods, lineColor, polyColor, alt, date); - break; - case 'multilinestring': - this._parseLineString$1(parens, mods, lineColor, alt, false, date); - break; - case 'linestring': - this._parseLineString$1(parens, mods, lineColor, alt, true, date); - break; - case 'geometrycollection': - parens = parens.substring(1, parens.length - 2); - var shapes = UiTools.splitString(parens, ','); - var $enum2 = ss.enumerate(shapes); - while ($enum2.moveNext()) { - var shape = $enum2.current; - this._parseGeometry$1(shape, lineColor, polyColor, alt, date); - } - break; - default: - break; - } - }, - _parsePolygon$1: function (parens, mods, lineColor, polyColor, alt, date) { - if (!ss.startsWith(parens, '(') && ss.endsWith(parens, ')')) { - return; - } - parens = parens.substring(1, parens.length - 2); - var shapes = UiTools.splitString(parens, ','); - var $enum1 = ss.enumerate(shapes); - while ($enum1.moveNext()) { - var shape = $enum1.current; - var lineList = new KmlLineList(); - lineList.astronomical = this.astronomical; - lineList.meanRadius = this._meanRadius$1; - lineList.parseWkt(shape, mods, alt, date); - if (!alt) { - this._addPolygonFlat$1(false, lineList, 1, polyColor, lineColor, true, true, date); - } - else { - this._addPolygon$1(false, lineList, 1, polyColor, lineColor, true, true, date); - } - } - }, - _parseLineString$1: function (parens, mods, lineColor, alt, single, date) { - if (!ss.startsWith(parens, '(') && ss.endsWith(parens, ')')) { - return; - } - if (!single) { - parens = parens.substring(1, parens.length - 2); - } - var shapes = UiTools.splitString(parens, ','); - var $enum1 = ss.enumerate(shapes); - while ($enum1.moveNext()) { - var shape = $enum1.current; - var lineList = new KmlLineList(); - lineList.astronomical = this.astronomical; - lineList.meanRadius = this._meanRadius$1; - lineList.parseWkt(shape, mods, alt, date); - this._addPolygon$1(false, lineList, 1, Colors.get_white(), lineColor, false, false, date); - } - }, - _splitShapes$1: function (shapes) { - var shapeList = []; - var nesting = 0; - var current = 0; - while (current < shapes.length) { - if (shapes.substr(current, 1) === '(') { - nesting++; - } - } - return shapeList; - }, - _addPolygon$1: function (sky, geo, lineWidth, polyColor, lineColor, extrude, fill, date) { - var vertexList = []; - var vertexListGround = []; - for (var i = 0; i < geo.pointList.length; i++) { - vertexList.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1 + (geo.pointList[i].alt / this._meanRadius$1))); - vertexListGround.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1)); - } - for (var i = 0; i < (geo.pointList.length - 1); i++) { - if (sky) { - } - else { - if (extrude) { - this.triangleList.addQuad(vertexList[i], vertexList[i + 1], vertexListGround[i], vertexListGround[i + 1], polyColor, date); - } - if (lineWidth > 0) { - if (extrude) { - this.lineList.addLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - else { - this.lineList2d.addLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - if (extrude) { - this.lineList.addLine(vertexListGround[i], vertexListGround[i + 1], lineColor, date); - this.lineList.addLine(vertexList[i], vertexListGround[i], lineColor, date); - this.lineList.addLine(vertexList[i + 1], vertexListGround[i + 1], lineColor, date); - } - } - } - } - if (fill) { - var indexes = Tessellator.tesselateSimplePoly(vertexList); - for (var i = 0; i < indexes.length; i += 3) { - this.triangleList.addTriangle(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date); - } - } - }, - _addPolygonFlat$1: function (sky, geo, lineWidth, polyColor, lineColor, extrude, fill, date) { - var vertexList = []; - for (var i = 0; i < geo.pointList.length; i++) { - vertexList.push(Coordinates.geoTo3dRad(geo.pointList[i].lat, geo.pointList[i].lng, 1 + (geo.pointList[i].alt / this._meanRadius$1))); - } - for (var i = 0; i < (geo.pointList.length - 1); i++) { - if (sky) { - } - else { - if (lineWidth > 0) { - this.lineList2d.addLine(vertexList[i], vertexList[i + 1], lineColor, date); - } - } - } - if (fill) { - var indexes = Tessellator.tesselateSimplePoly(vertexList); - for (var i = 0; i < indexes.length; i += 3) { - this.triangleList2d.addSubdividedTriangles(vertexList[indexes[i]], vertexList[indexes[i + 1]], vertexList[indexes[i + 2]], polyColor, date, 2); - } - } - }, - _parseColor$1: function (colorText, defaultColor) { - return Color.load(colorText); - }, - getScaleFactor: function (AltUnit, custom) { - var factor = 1; - switch (AltUnit) { - case 1: - factor = 1; - break; - case 2: - factor = 1 * 0.3048; - break; - case 3: - factor = (1 / 12) * 0.3048; - break; - case 4: - factor = 5280 * 0.3048; - break; - case 5: - factor = 1000; - break; - case 6: - factor = 1000 * 149598000; - break; - case 7: - factor = 1000 * 149598000 * 63239.6717; - break; - case 8: - factor = 1000 * 149598000 * 206264.806; - break; - case 9: - factor = 1000 * 149598000 * 206264.806 * 1000000; - break; - case 10: - factor = custom; - break; - default: - break; - } - return factor; - }, - get__table: function () { - return this._table$1; - }, - set__table: function (value) { - this._table$1 = value; - return value; - }, - useHeadersFromVoTable: function (voTable) { - var $enum1 = ss.enumerate(voTable.column); - while ($enum1.moveNext()) { - var column = $enum1.current; - this.get_header().push(column.name); - } - this.guessHeaderAssignmentsFromVoTable(voTable); - if (voTable.getRAColumn() != null && voTable.getRAColumn().unit.toLowerCase() === 'deg') { - this.set_raUnits(1); - } - }, - loadFromString: function (data, isUpdate, purgeOld, purgeAll, hasHeader) { - if (!isUpdate) { - this._table$1 = new Table(); - } - this._table$1.lock(); - this._table$1.loadFromString(data, isUpdate, purgeAll, hasHeader); - if (!isUpdate) { - this.guessHeaderAssignments(); - if (this.astronomical && this.lngColumn > -1) { - var max = this.getMaxValue(this.lngColumn); - if (max > 24) { - this.set_raUnits(1); - } - } - } - if (purgeOld) { - this.purgeByTime(); - } - this._table$1.unlock(); - }, - purgeByTime: function () { - if (this.startDateColumn < 0) { - return; - } - var columnToUse = this.startDateColumn; - if (this.endDateColumn > -1) { - columnToUse = this.endDateColumn; - } - var threasholdTime = SpaceTimeController.get_now(); - var ts = ss.truncate(this.decay) * 24 * 60 * 60 * 1000; - threasholdTime = new Date(threasholdTime.getDate() - ts); - var count = this._table$1.rows.length; - for (var i = 0; i < count; i++) { - try { - var row = this._table$1.rows[i]; - var colDate = new Date(row[columnToUse]); - if (colDate < threasholdTime) { - this._table$1.rows.splice(i, 1); - count--; - i--; - } - } - catch ($e1) { - } - } - }, - cleanUp: function () { - this.cleanUpBase(); - this._table$1.lock(); - Layer.prototype.cleanUp.call(this); - this._table$1.unlock(); - this.dirty = true; - }, - writeLayerProperties: function (xmlWriter) { - xmlWriter._writeAttributeString('TimeSeries', this.get_timeSeries().toString()); - xmlWriter._writeAttributeString('BeginRange', Util.xmlDate(this.get_beginRange())); - xmlWriter._writeAttributeString('EndRange', Util.xmlDate(this.get_endRange())); - xmlWriter._writeAttributeString('Decay', this.get_decay().toString()); - xmlWriter._writeAttributeString('CoordinatesType', Enums.toXml('CoordinatesTypes', this.get_coordinatesType())); - xmlWriter._writeAttributeString('LatColumn', this.get_latColumn().toString()); - xmlWriter._writeAttributeString('LngColumn', this.get_lngColumn().toString()); - xmlWriter._writeAttributeString('GeometryColumn', this.get_geometryColumn().toString()); - xmlWriter._writeAttributeString('AltType', Enums.toXml('AltTypes', this.get_altType())); - xmlWriter._writeAttributeString('MarkerMix', Enums.toXml('MarkerMixes', this.get_markerMix())); - xmlWriter._writeAttributeString('ColorMap', Enums.toXml('ColorMaps', this.get_colorMap())); - xmlWriter._writeAttributeString('MarkerColumn', this.get_markerColumn().toString()); - xmlWriter._writeAttributeString('PlotType', Enums.toXml('PlotTypes', this.get_plotType())); - xmlWriter._writeAttributeString('MarkerIndex', this.get_markerIndex().toString()); - xmlWriter._writeAttributeString('MarkerScale', Enums.toXml('MarkerScales', this.get_markerScale())); - xmlWriter._writeAttributeString('AltUnit', Enums.toXml('AltUnits', this.get_altUnit())); - xmlWriter._writeAttributeString('AltColumn', this.get_altColumn().toString()); - xmlWriter._writeAttributeString('StartDateColumn', this.get_startDateColumn().toString()); - xmlWriter._writeAttributeString('EndDateColumn', this.get_endDateColumn().toString()); - this._prepareBackCompatTable$1(); - if (this._lastNormalizeSizeColumnIndex$1 > -1) { - xmlWriter._writeAttributeString('SizeColumn', this._lastNormalizeSizeColumnIndex$1); - xmlWriter._writeAttributeString('NormalizeSizeColumn', this.sizeColumn.toString()); - } - else { - xmlWriter._writeAttributeString('SizeColumn', this.get_sizeColumn().toString()); - } - xmlWriter._writeAttributeString('NormalizeSize', this.get_normalizeSize().toString()); - xmlWriter._writeAttributeString('NormalizeSizeClip', this.get_normalizeSizeClip().toString()); - xmlWriter._writeAttributeString('NormalizeSizeMin', this.get_normalizeSizeMin().toString()); - xmlWriter._writeAttributeString('NormalizeSizeMax', this.get_normalizeSizeMax().toString()); - if (this._lastDynamicColorColumnIndex$1 > -1) { - xmlWriter._writeAttributeString('ColorMapColumn', this._lastDynamicColorColumnIndex$1); - xmlWriter._writeAttributeString('DynamicColorColumn', this.get_colorMapColumn().toString()); - } - else { - xmlWriter._writeAttributeString('ColorMapColumn', this.get_colorMapColumn().toString()); - } - xmlWriter._writeAttributeString('DynamicColor', this.get_dynamicColor().toString()); - xmlWriter._writeAttributeString('ColorMapperName', this.get_colorMapperName()); - xmlWriter._writeAttributeString('NormalizeColorMap', this.get_normalizeColorMap().toString()); - xmlWriter._writeAttributeString('NormalizeColorMapMin', this.get_normalizeColorMapMin().toString()); - xmlWriter._writeAttributeString('NormalizeColorMapMax', this.get_normalizeColorMapMax().toString()); - xmlWriter._writeAttributeString('HyperlinkFormat', this.get_hyperlinkFormat()); - xmlWriter._writeAttributeString('HyperlinkColumn', this.get_hyperlinkColumn().toString()); - xmlWriter._writeAttributeString('ScaleFactor', this.get_scaleFactor().toString()); - xmlWriter._writeAttributeString('PointScaleType', Enums.toXml('PointScaleTypes', this.get_pointScaleType())); - xmlWriter._writeAttributeString('ShowFarSide', this.get_showFarSide().toString()); - xmlWriter._writeAttributeString('RaUnits', Enums.toXml('RAUnits', this.get_raUnits())); - xmlWriter._writeAttributeString('HoverTextColumn', this.get_nameColumn().toString()); - xmlWriter._writeAttributeString('XAxisColumn', this.get_xAxisColumn().toString()); - xmlWriter._writeAttributeString('XAxisReverse', this.get_xAxisReverse().toString()); - xmlWriter._writeAttributeString('YAxisColumn', this.get_yAxisColumn().toString()); - xmlWriter._writeAttributeString('YAxisReverse', this.get_yAxisReverse().toString()); - xmlWriter._writeAttributeString('ZAxisColumn', this.get_zAxisColumn().toString()); - xmlWriter._writeAttributeString('ZAxisReverse', this.get_zAxisReverse().toString()); - xmlWriter._writeAttributeString('CartesianScale', Enums.toXml('AltUnits', this.get_cartesianScale())); - xmlWriter._writeAttributeString('CartesianCustomScale', this.get_cartesianCustomScale().toString()); - xmlWriter._writeAttributeString('DynamicData', this.get_dynamicData().toString()); - xmlWriter._writeAttributeString('AutoUpdate', this.get_autoUpdate().toString()); - xmlWriter._writeAttributeString('DataSourceUrl', this.get_dataSourceUrl()); - }, - get_dynamicData: function () { - return this._dynamicData$1; - }, - set_dynamicData: function (value) { - this._dynamicData$1 = value; - return value; - }, - get_autoUpdate: function () { - return this._autoUpdate$1; - }, - set_autoUpdate: function (value) { - this._autoUpdate$1 = value; - return value; - }, - get_dataSourceUrl: function () { - return this._dataSourceUrl$1; - }, - set_dataSourceUrl: function (value) { - this._dataSourceUrl$1 = value; - return value; - }, - get_timeSeries: function () { - return this.timeSeries; - }, - set_timeSeries: function (value) { - if (this.timeSeries !== value) { - this.version++; - this.timeSeries = value; - } - return value; - }, - get_beginRange: function () { - return this._beginRange$1; - }, - set_beginRange: function (value) { - if (!ss.compareDates(this._beginRange$1, value)) { - this.version++; - this._beginRange$1 = value; - } - return value; - }, - get_endRange: function () { - return this._endRange$1; - }, - set_endRange: function (value) { - if (!ss.compareDates(this._endRange$1, value)) { - this.version++; - this._endRange$1 = value; - } - return value; - }, - initializeFromXml: function (node) { - this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); - this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); - this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); - this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); - this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); - if (this.get_coordinatesType() < 0) { - this.set_coordinatesType(0); - } - this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); - this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); - if (node.attributes.getNamedItem('GeometryColumn') != null) { - this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); - } - this.set_altType(Enums.parse('AltTypes', node.attributes.getNamedItem('AltType').nodeValue)); - this.set_markerMix(0); - this.set_colorMap(Enums.parse('ColorMaps', node.attributes.getNamedItem('ColorMap').nodeValue)); - this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); - this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); - this.set_plotType(Enums.parse('PlotTypes', node.attributes.getNamedItem('PlotType').nodeValue)); - this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); - this.set_markerScale(Enums.parse('MarkerScales', node.attributes.getNamedItem('MarkerScale').nodeValue)); - this.set_altUnit(Enums.parse('AltUnits', node.attributes.getNamedItem('AltUnit').nodeValue)); - this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); - this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); - this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); - if (node.attributes.getNamedItem('NormalizeSizeColumn') != null) { - this.set_sizeColumn(parseInt(node.attributes.getNamedItem('NormalizeSizeColumn').nodeValue)); - } - else { - this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); - } - if (node.attributes.getNamedItem('NormalizeSize') != null) { - this.set_normalizeSize(ss.boolean(node.attributes.getNamedItem('NormalizeSize').nodeValue)); - this.set_normalizeSizeClip(ss.boolean(node.attributes.getNamedItem('NormalizeSizeClip').nodeValue)); - this.set_normalizeSizeMin(parseFloat(node.attributes.getNamedItem('NormalizeSizeMin').nodeValue)); - this.set_normalizeSizeMax(parseFloat(node.attributes.getNamedItem('NormalizeSizeMax').nodeValue)); - } - if (node.attributes.getNamedItem('DynamicColorColumn') != null) { - this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('DynamicColorColumn').nodeValue)); - } - else { - this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); - } - if (node.attributes.getNamedItem('DynamicColor') != null) { - this.set_dynamicColor(ss.boolean(node.attributes.getNamedItem('DynamicColor').nodeValue)); - this.set_colorMapperName(node.attributes.getNamedItem('ColorMapperName').nodeValue); - this.set_normalizeColorMap(ss.boolean(node.attributes.getNamedItem('NormalizeColorMap').nodeValue)); - this.set_normalizeColorMapMin(parseFloat(node.attributes.getNamedItem('NormalizeColorMapMin').nodeValue)); - this.set_normalizeColorMapMax(parseFloat(node.attributes.getNamedItem('NormalizeColorMapMax').nodeValue)); - } - this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); - this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); - this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); - this.set_pointScaleType(Enums.parse('PointScaleTypes', node.attributes.getNamedItem('PointScaleType').nodeValue)); - if (node.attributes.getNamedItem('ShowFarSide') != null) { - this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); - } - if (node.attributes.getNamedItem('RaUnits') != null) { - this.set_raUnits(Enums.parse('RAUnits', node.attributes.getNamedItem('RaUnits').nodeValue)); - } - if (node.attributes.getNamedItem('HoverTextColumn') != null) { - this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); - } - if (node.attributes.getNamedItem('XAxisColumn') != null) { - this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); - this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); - this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); - this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); - this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); - this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); - this.set_cartesianScale(Enums.parse('AltUnits', node.attributes.getNamedItem('CartesianScale').nodeValue)); - this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); - } - if (node.attributes.getNamedItem('DynamicData') != null) { - this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); - this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); - this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); - } - }, - get_decay: function () { - return this.decay; - }, - set_decay: function (value) { - if (this.decay !== value) { - this.version++; - this.decay = value; - } - return value; - }, - get_coordinatesType: function () { - return this._coordinatesType$1; - }, - set_coordinatesType: function (value) { - if (this._coordinatesType$1 !== value) { - this.version++; - this._coordinatesType$1 = value; - } - return value; - }, - get_latColumn: function () { - return this.latColumn; - }, - set_latColumn: function (value) { - if (this.latColumn !== value) { - this.version++; - this.latColumn = value; - } - return value; - }, - get_lngColumn: function () { - return this.lngColumn; - }, - set_lngColumn: function (value) { - if (this.lngColumn !== value) { - this.version++; - this.lngColumn = value; - } - return value; - }, - get_geometryColumn: function () { - return this.geometryColumn; - }, - set_geometryColumn: function (value) { - if (this.geometryColumn !== value) { - this.version++; - this.geometryColumn = value; - } - return value; - }, - get_xAxisColumn: function () { - return this._xAxisColumn$1; - }, - set_xAxisColumn: function (value) { - if (this._xAxisColumn$1 !== value) { - this.version++; - this._xAxisColumn$1 = value; - } - return value; - }, - get_yAxisColumn: function () { - return this._yAxisColumn$1; - }, - set_yAxisColumn: function (value) { - if (this._yAxisColumn$1 !== value) { - this.version++; - this._yAxisColumn$1 = value; - } - return value; - }, - get_zAxisColumn: function () { - return this._zAxisColumn$1; - }, - set_zAxisColumn: function (value) { - if (this._zAxisColumn$1 !== value) { - this.version++; - this._zAxisColumn$1 = value; - } - return value; - }, - get_xAxisReverse: function () { - return this._xAxisReverse$1; - }, - set_xAxisReverse: function (value) { - if (this._xAxisReverse$1 !== value) { - this.version++; - this._xAxisReverse$1 = value; - } - return value; - }, - get_yAxisReverse: function () { - return this._yAxisReverse$1; - }, - set_yAxisReverse: function (value) { - if (this._yAxisReverse$1 !== value) { - this.version++; - this._yAxisReverse$1 = value; - } - return value; - }, - get_zAxisReverse: function () { - return this._zAxisReverse$1; - }, - set_zAxisReverse: function (value) { - if (this._zAxisReverse$1 !== value) { - this.version++; - this._zAxisReverse$1 = value; - } - return value; - }, - get_altType: function () { - return this._altType$1; - }, - set_altType: function (value) { - if (this._altType$1 !== value) { - this.version++; - this._altType$1 = value; - } - return value; - }, - get_markerMix: function () { - return this._markerMix$1; - }, - set_markerMix: function (value) { - if (this._markerMix$1 !== value) { - this.version++; - this._markerMix$1 = value; - } - return value; - }, - get_raUnits: function () { - return this._raUnits$1; - }, - set_raUnits: function (value) { - if (this._raUnits$1 !== value) { - this.version++; - this._raUnits$1 = value; - } - return value; - }, - get_colorMap: function () { - return this.colorMap; - }, - set_colorMap: function (value) { - if (this.colorMap !== value) { - this.version++; - this.colorMap = value; - } - return value; - }, - get_colorMapperName: function () { - return this.colorMapperName; - }, - set_colorMapperName: function (value) { - if (ColorMapContainer.fromNamedColormap(value) == null) { - throw new Error('Invalid colormap name'); - } - this.version++; - this.colorMapperName = value; - return value; - }, - get_colorMapper: function () { - return ColorMapContainer.fromNamedColormap(this.colorMapperName); - }, - get_dynamicColor: function () { - return this.dynamicColor; - }, - set_dynamicColor: function (value) { - this.version++; - this.dynamicColor = value; - return value; - }, - get_normalizeColorMap: function () { - return this.normalizeColorMap; - }, - set_normalizeColorMap: function (value) { - this.version++; - this.normalizeColorMap = value; - return value; - }, - get_normalizeColorMapMin: function () { - return this.normalizeColorMapMin; - }, - set_normalizeColorMapMin: function (value) { - this.version++; - this.normalizeColorMapMin = value; - return value; - }, - get_normalizeColorMapMax: function () { - return this.normalizeColorMapMax; - }, - set_normalizeColorMapMax: function (value) { - this.version++; - this.normalizeColorMapMax = value; - return value; - }, - normalizeColorMapValue: function (value) { - if (!this.get_normalizeColorMap()) { - return value; - } - var new_value = (value - this.get_normalizeColorMapMin()) / (this.get_normalizeColorMapMax() - this.get_normalizeColorMapMin()); - if (new_value < 0) { - new_value = 0; - } - else if (new_value > 1) { - new_value = 1; - } - return new_value; - }, - get_markerColumn: function () { - return this._markerColumn$1; - }, - set_markerColumn: function (value) { - if (this._markerColumn$1 !== value) { - this.version++; - this._markerColumn$1 = value; - } - return value; - }, - get_colorMapColumn: function () { - return this.colorMapColumn; - }, - set_colorMapColumn: function (value) { - if (this.colorMapColumn !== value) { - this.version++; - this.colorMapColumn = value; - } - return value; - }, - get_plotType: function () { - return this._plotType$1; - }, - set_plotType: function (value) { - if (this._plotType$1 !== value) { - this.version++; - this._plotType$1 = value; - } - return value; - }, - get_markerIndex: function () { - return this._markerIndex$1; - }, - set_markerIndex: function (value) { - if (this._markerIndex$1 !== value) { - this.version++; - this._markerIndex$1 = value; - } - return value; - }, - get_showFarSide: function () { - return this._showFarSide$1; - }, - set_showFarSide: function (value) { - if (this._showFarSide$1 !== value) { - this.version++; - this._showFarSide$1 = value; - } - return value; - }, - get_markerScale: function () { - return this._markerScale$1; - }, - set_markerScale: function (value) { - if (this._markerScale$1 !== value) { - this.version++; - this._markerScale$1 = value; - } - return value; - }, - get_altUnit: function () { - return this._altUnit$1; - }, - set_altUnit: function (value) { - if (this._altUnit$1 !== value) { - this.version++; - this._altUnit$1 = value; - } - return value; - }, - get_cartesianScale: function () { - return this._cartesianScale$1; - }, - set_cartesianScale: function (value) { - if (this._cartesianScale$1 !== value) { - this.version++; - this._cartesianScale$1 = value; - } - return value; - }, - get_cartesianCustomScale: function () { - return this._cartesianCustomScale$1; - }, - set_cartesianCustomScale: function (value) { - if (this._cartesianCustomScale$1 !== value) { - this.version++; - this._cartesianCustomScale$1 = value; - } - return value; - }, - get_altColumn: function () { - return this.altColumn; - }, - set_altColumn: function (value) { - if (this.altColumn !== value) { - this.version++; - this.altColumn = value; - } - return value; - }, - get_startDateColumn: function () { - return this.startDateColumn; - }, - set_startDateColumn: function (value) { - if (this.startDateColumn !== value) { - this.version++; - this.startDateColumn = value; - } - return value; - }, - get_endDateColumn: function () { - return this.endDateColumn; - }, - set_endDateColumn: function (value) { - if (this.endDateColumn !== value) { - this.version++; - this.endDateColumn = value; - } - return value; - }, - get_sizeColumn: function () { - return this.sizeColumn; - }, - set_sizeColumn: function (value) { - if (this.sizeColumn !== value) { - this.version++; - this.sizeColumn = value; - } - return value; - }, - get_normalizeSize: function () { - return this.normalizeSize; - }, - set_normalizeSize: function (value) { - if (this.normalizeSize !== value) { - this.version++; - this.normalizeSize = value; - } - return value; - }, - get_normalizeSizeClip: function () { - return this.normalizeSizeClip; - }, - set_normalizeSizeClip: function (value) { - if (this.normalizeSizeClip !== value) { - this.version++; - this.normalizeSizeClip = value; - } - return value; - }, - get_normalizeSizeMin: function () { - return this.normalizeSizeMin; - }, - set_normalizeSizeMin: function (value) { - if (this.normalizeSizeMin !== value) { - this.version++; - this.normalizeSizeMin = value; - } - return value; - }, - get_normalizeSizeMax: function () { - return this.normalizeSizeMax; - }, - set_normalizeSizeMax: function (value) { - if (this.normalizeSizeMax !== value) { - this.version++; - this.normalizeSizeMax = value; - } - return value; - }, - normalizePointSize: function (value) { - if (!this.get_normalizeSize()) { - return value; - } - var new_value = (value - this.get_normalizeSizeMin()) / (this.get_normalizeSizeMax() - this.get_normalizeSizeMin()); - if (this.get_normalizeSizeClip()) { - if (new_value < 0) { - new_value = 0; - } - else if (new_value > 1) { - new_value = 1; - } - } - return new_value; - }, - get_nameColumn: function () { - return this.nameColumn; - }, - set_nameColumn: function (value) { - if (this.nameColumn !== value) { - this.version++; - this.nameColumn = value; - } - return value; - }, - get_hyperlinkFormat: function () { - return this._hyperlinkFormat$1; - }, - set_hyperlinkFormat: function (value) { - if (this._hyperlinkFormat$1 !== value) { - this.version++; - this._hyperlinkFormat$1 = value; - } - return value; - }, - get_hyperlinkColumn: function () { - return this._hyperlinkColumn$1; - }, - set_hyperlinkColumn: function (value) { - if (this._hyperlinkColumn$1 !== value) { - this.version++; - this._hyperlinkColumn$1 = value; - } - return value; - }, - get_scaleFactor: function () { - return this.scaleFactor; - }, - set_scaleFactor: function (value) { - if (this.scaleFactor !== value) { - this.version++; - this.scaleFactor = value; - } - return value; - }, - get_pointScaleType: function () { - return this.pointScaleType; - }, - set_pointScaleType: function (value) { - if (this.pointScaleType !== value) { - this.version++; - this.pointScaleType = value; - } - return value; - }, - draw: function (renderContext, opacity, flat) { - var device = renderContext; - if (this.version !== this.lastVersion) { - this.cleanUp(); - } - this.lastVersion = this.version; - if (this.bufferIsFlat !== flat) { - this.cleanUp(); - this.bufferIsFlat = flat; - } - if (this.dirty) { - this.prepVertexBuffer(device, opacity); - } - var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); - var adjustedScale = this.scaleFactor * 3; - if (flat && this.astronomical && (this._markerScale$1 === 1)) { - adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); - } - if (this.triangleList2d != null) { - this.triangleList2d.decay = this.decay; - this.triangleList2d.sky = this.get_astronomical(); - this.triangleList2d.timeSeries = this.timeSeries; - this.triangleList2d.jNow = jNow; - this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.triangleList != null) { - this.triangleList.decay = this.decay; - this.triangleList.sky = this.get_astronomical(); - this.triangleList.timeSeries = this.timeSeries; - this.triangleList.jNow = jNow; - this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.pointList != null) { - this.pointList.depthBuffered = false; - this.pointList.showFarSide = this.get_showFarSide(); - this.pointList.decay = (this.timeSeries) ? this.decay : 0; - this.pointList.sky = this.get_astronomical(); - this.pointList.timeSeries = this.timeSeries; - this.pointList.jNow = jNow; - this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; - switch (this._plotType$1) { - case 0: - this.pointList.draw(renderContext, opacity * this.get_opacity(), false); - break; - case 2: - this.pointList.drawTextured(renderContext, SpreadSheetLayer.get__circleTexture$1().texture2d, opacity * this.get_opacity()); - break; - case 1: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(19), opacity * this.get_opacity()); - break; - case 3: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(35), opacity * this.get_opacity()); - break; - case 5: - case 4: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(this._markerIndex$1), opacity * this.get_opacity()); - break; - default: - break; - } - } - if (this.lineList != null) { - this.lineList.sky = this.get_astronomical(); - this.lineList.decay = this.decay; - this.lineList.timeSeries = this.timeSeries; - this.lineList.jNow = jNow; - this.lineList.drawLines(renderContext, opacity * this.get_opacity()); - } - if (this.lineList2d != null) { - this.lineList2d.sky = this.get_astronomical(); - this.lineList2d.decay = this.decay; - this.lineList2d.timeSeries = this.timeSeries; - this.lineList2d.showFarSide = this.get_showFarSide(); - this.lineList2d.jNow = jNow; - this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); - } - return true; - }, - cleanUpBase: function () { - if (this.lineList != null) { - this.lineList.clear(); - } - if (this.lineList2d != null) { - this.lineList2d.clear(); - } - if (this.triangleList2d != null) { - this.triangleList2d.clear(); - } - if (this.pointList != null) { - this.pointList.clear(); - } - if (this.triangleList != null) { - this.triangleList.clear(); - } - } - }; - - - // wwtlib.TimeSeriesLayer - - function TimeSeriesLayer() { - this.isLongIndex = false; - this.shapeVertexCount = 0; - this.lines = false; - this.latColumn = -1; - this.fixedSize = 1; - this.decay = 16; - this.timeSeries = false; - this._dynamicData$1 = false; - this._autoUpdate$1 = false; - this._dataSourceUrl$1 = ''; - this._beginRange$1 = new Date('1/1/2100'); - this._endRange$1 = new Date('01/01/1800'); - this.markerDomainValues = {}; - this.colorDomainValues = {}; - this._coordinatesType$1 = 0; - this.lngColumn = -1; - this.geometryColumn = -1; - this._xAxisColumn$1 = -1; - this._yAxisColumn$1 = -1; - this._zAxisColumn$1 = -1; - this._xAxisReverse$1 = false; - this._yAxisReverse$1 = false; - this._zAxisReverse$1 = false; - this._altType$1 = 3; - this._markerMix$1 = 0; - this._raUnits$1 = 0; - this._colorMap$1 = 3; - this._markerColumn$1 = -1; - this._colorMapColumn$1 = -1; - this._plotType$1 = 0; - this._markerIndex$1 = 0; - this._showFarSide$1 = false; - this._markerScale$1 = 1; - this._altUnit$1 = 1; - this._cartesianScale$1 = 1; - this._cartesianCustomScale$1 = 1; - this.altColumn = -1; - this.startDateColumn = -1; - this.endDateColumn = -1; - this.sizeColumn = -1; - this.nameColumn = 0; - this._hyperlinkFormat$1 = ''; - this._hyperlinkColumn$1 = -1; - this.scaleFactor = 1; - this.pointScaleType = 1; - this.positions = []; - this.bufferIsFlat = false; - this.baseDate = new Date(2010, 0, 1, 12, 0, 0); - this.dirty = true; - this.lastVersion = 0; - Layer.call(this); - } - TimeSeriesLayer.get__circleTexture$1 = function () { - return TimeSeriesLayer._circleTexture$1; - }; - var TimeSeriesLayer$ = { - get_dynamicData: function () { - return this._dynamicData$1; - }, - set_dynamicData: function (value) { - this._dynamicData$1 = value; - return value; - }, - get_autoUpdate: function () { - return this._autoUpdate$1; - }, - set_autoUpdate: function (value) { - this._autoUpdate$1 = value; - return value; - }, - get_dataSourceUrl: function () { - return this._dataSourceUrl$1; - }, - set_dataSourceUrl: function (value) { - this._dataSourceUrl$1 = value; - return value; - }, - get_timeSeries: function () { - return this.timeSeries; - }, - set_timeSeries: function (value) { - if (this.timeSeries !== value) { - this.version++; - this.timeSeries = value; - } - return value; - }, - get_header: function () { - return null; - }, - get_beginRange: function () { - return this._beginRange$1; - }, - set_beginRange: function (value) { - if (!ss.compareDates(this._beginRange$1, value)) { - this.version++; - this._beginRange$1 = value; - } - return value; - }, - get_endRange: function () { - return this._endRange$1; - }, - set_endRange: function (value) { - if (!ss.compareDates(this._endRange$1, value)) { - this.version++; - this._endRange$1 = value; - } - return value; - }, - initializeFromXml: function (node) { - this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); - this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); - this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); - this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); - this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); - if (this.get_coordinatesType() < 0) { - this.set_coordinatesType(0); - } - this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); - this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); - if (node.attributes.getNamedItem('GeometryColumn') != null) { - this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); - } - switch (node.attributes.getNamedItem('AltType').nodeValue) { - case 'Depth': - this.set_altType(0); - break; - case 'Altitude': - this.set_altType(1); - break; - case 'Distance': - this.set_altType(2); - break; - case 'SeaLevel': - this.set_altType(3); - break; - case 'Terrain': - this.set_altType(4); - break; - default: - break; - } - this.set_markerMix(0); - switch (node.attributes.getNamedItem('ColorMap').nodeValue) { - case 'Same_For_All': - this.set__colorMap(0); - break; - case 'Group_by_Values': - this.set__colorMap(2); - break; - case 'Per_Column_Literal': - this.set__colorMap(3); - break; - default: - break; - } - this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); - this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); - switch (node.attributes.getNamedItem('PlotType').nodeValue) { - case 'Gaussian': - this.set_plotType(0); - break; - case 'Point': - this.set_plotType(1); - break; - case 'Circle': - this.set_plotType(2); - break; - case 'PushPin': - this.set_plotType(4); - break; - default: - break; - } - this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); - switch (node.attributes.getNamedItem('MarkerScale').nodeValue) { - case 'Screen': - this.set_markerScale(0); - break; - case 'World': - this.set_markerScale(1); - break; - default: - break; - } - switch (node.attributes.getNamedItem('AltUnit').nodeValue) { - case 'Meters': - this.set_altUnit(1); - break; - case 'Feet': - this.set_altUnit(2); - break; - case 'Inches': - this.set_altUnit(3); - break; - case 'Miles': - this.set_altUnit(4); - break; - case 'Kilometers': - this.set_altUnit(5); - break; - case 'AstronomicalUnits': - this.set_altUnit(6); - break; - case 'LightYears': - this.set_altUnit(7); - break; - case 'Parsecs': - this.set_altUnit(8); - break; - case 'MegaParsecs': - this.set_altUnit(9); - break; - case 'Custom': - this.set_altUnit(10); - break; - default: - break; - } - this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); - this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); - this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); - this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); - this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); - this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); - this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); - switch (node.attributes.getNamedItem('PointScaleType').nodeValue) { - case 'Linear': - this.set_pointScaleType(0); - break; - case 'Power': - this.set_pointScaleType(1); - break; - case 'Log': - this.set_pointScaleType(2); - break; - case 'Constant': - this.set_pointScaleType(3); - break; - case 'StellarMagnitude': - this.set_pointScaleType(4); - break; - default: - break; - } - if (node.attributes.getNamedItem('ShowFarSide') != null) { - this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); - } - if (node.attributes.getNamedItem('RaUnits') != null) { - switch (node.attributes.getNamedItem('RaUnits').nodeValue) { - case 'Hours': - this.set_raUnits(0); - break; - case 'Degrees': - this.set_raUnits(1); - break; - } - } - if (node.attributes.getNamedItem('HoverTextColumn') != null) { - this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); - } - if (node.attributes.getNamedItem('XAxisColumn') != null) { - this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); - this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); - this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); - this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); - this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); - this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); - switch (node.attributes.getNamedItem('CartesianScale').nodeValue) { - case 'Meters': - this.set_cartesianScale(1); - break; - case 'Feet': - this.set_cartesianScale(2); - break; - case 'Inches': - this.set_cartesianScale(3); - break; - case 'Miles': - this.set_cartesianScale(4); - break; - case 'Kilometers': - this.set_cartesianScale(5); - break; - case 'AstronomicalUnits': - this.set_cartesianScale(6); - break; - case 'LightYears': - this.set_cartesianScale(7); - break; - case 'Parsecs': - this.set_cartesianScale(8); - break; - case 'MegaParsecs': - this.set_cartesianScale(9); - break; - case 'Custom': - this.set_cartesianScale(10); - break; - default: - break; - } - this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); - } - if (node.attributes.getNamedItem('DynamicData') != null) { - this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); - this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); - this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); - } - }, - computeDateDomainRange: function (columnStart, columnEnd) { - }, - getDomainValues: function (column) { - return []; - }, - get_decay: function () { - return this.decay; - }, - set_decay: function (value) { - if (this.decay !== value) { - this.version++; - this.decay = value; - } - return value; - }, - get_coordinatesType: function () { - return this._coordinatesType$1; - }, - set_coordinatesType: function (value) { - if (this._coordinatesType$1 !== value) { - this.version++; - this._coordinatesType$1 = value; - } - return value; - }, - get_latColumn: function () { - return this.latColumn; - }, - set_latColumn: function (value) { - if (this.latColumn !== value) { - this.version++; - this.latColumn = value; - } - return value; - }, - get_lngColumn: function () { - return this.lngColumn; - }, - set_lngColumn: function (value) { - if (this.lngColumn !== value) { - this.version++; - this.lngColumn = value; - } - return value; - }, - get_geometryColumn: function () { - return this.geometryColumn; - }, - set_geometryColumn: function (value) { - if (this.geometryColumn !== value) { - this.version++; - this.geometryColumn = value; - } - return value; - }, - get_xAxisColumn: function () { - return this._xAxisColumn$1; - }, - set_xAxisColumn: function (value) { - if (this._xAxisColumn$1 !== value) { - this.version++; - this._xAxisColumn$1 = value; - } - return value; - }, - get_yAxisColumn: function () { - return this._yAxisColumn$1; - }, - set_yAxisColumn: function (value) { - if (this._yAxisColumn$1 !== value) { - this.version++; - this._yAxisColumn$1 = value; - } - return value; - }, - get_zAxisColumn: function () { - return this._zAxisColumn$1; - }, - set_zAxisColumn: function (value) { - if (this._zAxisColumn$1 !== value) { - this.version++; - this._zAxisColumn$1 = value; - } - return value; - }, - get_xAxisReverse: function () { - return this._xAxisReverse$1; - }, - set_xAxisReverse: function (value) { - if (this._xAxisReverse$1 !== value) { - this.version++; - this._xAxisReverse$1 = value; - } - return value; - }, - get_yAxisReverse: function () { - return this._yAxisReverse$1; - }, - set_yAxisReverse: function (value) { - if (this._yAxisReverse$1 !== value) { - this.version++; - this._yAxisReverse$1 = value; - } - return value; - }, - get_zAxisReverse: function () { - return this._zAxisReverse$1; - }, - set_zAxisReverse: function (value) { - if (this._zAxisReverse$1 !== value) { - this.version++; - this._zAxisReverse$1 = value; - } - return value; - }, - get_altType: function () { - return this._altType$1; - }, - set_altType: function (value) { - if (this._altType$1 !== value) { - this.version++; - this._altType$1 = value; - } - return value; - }, - get_markerMix: function () { - return this._markerMix$1; - }, - set_markerMix: function (value) { - if (this._markerMix$1 !== value) { - this.version++; - this._markerMix$1 = value; - } - return value; - }, - get_raUnits: function () { - return this._raUnits$1; - }, - set_raUnits: function (value) { - if (this._raUnits$1 !== value) { - this.version++; - this._raUnits$1 = value; - } - return value; - }, - get__colorMap: function () { - return this._colorMap$1; - }, - set__colorMap: function (value) { - if (this._colorMap$1 !== value) { - this.version++; - this._colorMap$1 = value; - } - return value; - }, - get_markerColumn: function () { - return this._markerColumn$1; - }, - set_markerColumn: function (value) { - if (this._markerColumn$1 !== value) { - this.version++; - this._markerColumn$1 = value; - } - return value; - }, - get_colorMapColumn: function () { - return this._colorMapColumn$1; - }, - set_colorMapColumn: function (value) { - if (this._colorMapColumn$1 !== value) { - this.version++; - this._colorMapColumn$1 = value; - } - return value; - }, - get_plotType: function () { - return this._plotType$1; - }, - set_plotType: function (value) { - if (this._plotType$1 !== value) { - this.version++; - this._plotType$1 = value; - } - return value; - }, - get_markerIndex: function () { - return this._markerIndex$1; - }, - set_markerIndex: function (value) { - if (this._markerIndex$1 !== value) { - this.version++; - this._markerIndex$1 = value; - } - return value; - }, - get_showFarSide: function () { - return this._showFarSide$1; - }, - set_showFarSide: function (value) { - if (this._showFarSide$1 !== value) { - this.version++; - this._showFarSide$1 = value; - } - return value; - }, - get_markerScale: function () { - return this._markerScale$1; - }, - set_markerScale: function (value) { - if (this._markerScale$1 !== value) { - this.version++; - this._markerScale$1 = value; - } - return value; - }, - get_altUnit: function () { - return this._altUnit$1; - }, - set_altUnit: function (value) { - if (this._altUnit$1 !== value) { - this.version++; - this._altUnit$1 = value; - } - return value; - }, - get_cartesianScale: function () { - return this._cartesianScale$1; - }, - set_cartesianScale: function (value) { - if (this._cartesianScale$1 !== value) { - this.version++; - this._cartesianScale$1 = value; - } - return value; - }, - get_cartesianCustomScale: function () { - return this._cartesianCustomScale$1; - }, - set_cartesianCustomScale: function (value) { - if (this._cartesianCustomScale$1 !== value) { - this.version++; - this._cartesianCustomScale$1 = value; - } - return value; - }, - get_altColumn: function () { - return this.altColumn; - }, - set_altColumn: function (value) { - if (this.altColumn !== value) { - this.version++; - this.altColumn = value; - } - return value; - }, - get_startDateColumn: function () { - return this.startDateColumn; - }, - set_startDateColumn: function (value) { - if (this.startDateColumn !== value) { - this.version++; - this.startDateColumn = value; - } - return value; - }, - get_endDateColumn: function () { - return this.endDateColumn; - }, - set_endDateColumn: function (value) { - if (this.endDateColumn !== value) { - this.version++; - this.endDateColumn = value; - } - return value; - }, - get_sizeColumn: function () { - return this.sizeColumn; - }, - set_sizeColumn: function (value) { - if (this.sizeColumn !== value) { - this.version++; - this.sizeColumn = value; - } - return value; - }, - get_nameColumn: function () { - return this.nameColumn; - }, - set_nameColumn: function (value) { - if (this.nameColumn !== value) { - this.version++; - this.nameColumn = value; - } - return value; - }, - get_hyperlinkFormat: function () { - return this._hyperlinkFormat$1; - }, - set_hyperlinkFormat: function (value) { - if (this._hyperlinkFormat$1 !== value) { - this.version++; - this._hyperlinkFormat$1 = value; - } - return value; - }, - get_hyperlinkColumn: function () { - return this._hyperlinkColumn$1; - }, - set_hyperlinkColumn: function (value) { - if (this._hyperlinkColumn$1 !== value) { - this.version++; - this._hyperlinkColumn$1 = value; - } - return value; - }, - get_scaleFactor: function () { - return this.scaleFactor; - }, - set_scaleFactor: function (value) { - if (this.scaleFactor !== value) { - this.version++; - this.scaleFactor = value; - } - return value; - }, - get_pointScaleType: function () { - return this.pointScaleType; - }, - set_pointScaleType: function (value) { - if (this.pointScaleType !== value) { - this.version++; - this.pointScaleType = value; - } - return value; - }, - prepVertexBuffer: function (renderContext, opacity) { - return true; - }, - draw: function (renderContext, opacity, flat) { - var device = renderContext; - if (this.version !== this.lastVersion) { - this.cleanUp(); - } - if (this.bufferIsFlat !== flat) { - this.cleanUp(); - this.bufferIsFlat = flat; - } - if (this.dirty) { - this.prepVertexBuffer(device, opacity); - } - var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); - var adjustedScale = this.scaleFactor; - if (flat && this.astronomical && (this._markerScale$1 === 1)) { - adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); - } - if (this.triangleList2d != null) { - this.triangleList2d.decay = this.decay; - this.triangleList2d.sky = this.get_astronomical(); - this.triangleList2d.timeSeries = this.timeSeries; - this.triangleList2d.jNow = jNow; - this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.triangleList != null) { - this.triangleList.decay = this.decay; - this.triangleList.sky = this.get_astronomical(); - this.triangleList.timeSeries = this.timeSeries; - this.triangleList.jNow = jNow; - this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.pointList != null) { - this.pointList.depthBuffered = false; - this.pointList.decay = this.decay; - this.pointList.sky = this.get_astronomical(); - this.pointList.timeSeries = this.timeSeries; - this.pointList.jNow = jNow; - this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; - this.pointList.draw(renderContext, opacity * this.get_opacity(), false); - } - if (this.lineList != null) { - this.lineList.sky = this.get_astronomical(); - this.lineList.decay = this.decay; - this.lineList.timeSeries = this.timeSeries; - this.lineList.jNow = jNow; - this.lineList.drawLines(renderContext, opacity * this.get_opacity()); - } - if (this.lineList2d != null) { - this.lineList2d.sky = this.get_astronomical(); - this.lineList2d.decay = this.decay; - this.lineList2d.timeSeries = this.timeSeries; - this.lineList2d.showFarSide = this.get_showFarSide(); - this.lineList2d.jNow = jNow; - this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); - } - return true; - }, - initFromXml: function (node) { - Layer.prototype.initFromXml.call(this, node); - }, - cleanUp: function () { - if (this.lineList != null) { - this.lineList.clear(); - } - if (this.lineList2d != null) { - this.lineList2d.clear(); - } - if (this.triangleList2d != null) { - this.triangleList2d.clear(); - } - if (this.pointList != null) { - this.pointList.clear(); - } - if (this.triangleList != null) { - this.triangleList.clear(); - } - }, - dynamicUpdate: function () { - return false; - } - }; - - - // wwtlib.VoTableLayer - - function VoTableLayer() { - this.isLongIndex = false; - this.shapeVertexCount = 0; - this.lines = false; - this.latColumn = -1; - this.fixedSize = 1; - this.decay = 0; - this.timeSeries = false; - this._dynamicData$1 = false; - this._autoUpdate$1 = false; - this._dataSourceUrl$1 = ''; - this._beginRange$1 = new Date('1/1/2100'); - this._endRange$1 = new Date('01/01/1800'); - this.markerDomainValues = {}; - this.colorDomainValues = {}; - this._coordinatesType$1 = 0; - this.lngColumn = -1; - this.geometryColumn = -1; - this._xAxisColumn$1 = -1; - this._yAxisColumn$1 = -1; - this._zAxisColumn$1 = -1; - this._xAxisReverse$1 = false; - this._yAxisReverse$1 = false; - this._zAxisReverse$1 = false; - this._altType$1 = 3; - this._markerMix$1 = 0; - this._raUnits$1 = 0; - this._colorMap$1 = 3; - this._markerColumn$1 = -1; - this._colorMapColumn$1 = -1; - this._plotType$1 = 0; - this._markerIndex$1 = 0; - this._showFarSide$1 = false; - this._markerScale$1 = 1; - this._altUnit$1 = 1; - this._cartesianScale$1 = 1; - this._cartesianCustomScale$1 = 1; - this.altColumn = -1; - this.startDateColumn = -1; - this.endDateColumn = -1; - this.sizeColumn = -1; - this.nameColumn = 0; - this._hyperlinkFormat$1 = ''; - this._hyperlinkColumn$1 = -1; - this.scaleFactor = 1; - this.pointScaleType = 1; - this.positions = []; - this.bufferIsFlat = false; - this.baseDate = new Date(2010, 0, 1, 12, 0, 0); - this.dirty = true; - this._filename$1 = ''; - Layer.call(this); - this._table$1 = null; - this._filename$1 = ''; - this.set_plotType(2); - } - VoTableLayer.get__circleTexture$1 = function () { - if (VoTableLayer._circleTexture$1 == null) { - var url = URLHelpers.singleton.engineAssetUrl('circle.png'); - VoTableLayer._circleTexture$1 = Planets.loadPlanetTexture(url); - } - return VoTableLayer._circleTexture$1; - }; - VoTableLayer.create = function (table, plotType) { - var layer = new VoTableLayer(); - layer._table$1 = table; - layer._filename$1 = table.loadFilename; - layer.set_lngColumn(table.getRAColumn().index); - layer.set_latColumn(table.getDecColumn().index); - layer.sizeColumn = table.getColumnByUcd('phot.mag').index; - layer.set_plotType(plotType); - return layer; - }; - var VoTableLayer$ = { - get_dynamicData: function () { - return this._dynamicData$1; - }, - set_dynamicData: function (value) { - this._dynamicData$1 = value; - return value; - }, - get_autoUpdate: function () { - return this._autoUpdate$1; - }, - set_autoUpdate: function (value) { - this._autoUpdate$1 = value; - return value; - }, - get_dataSourceUrl: function () { - return this._dataSourceUrl$1; - }, - set_dataSourceUrl: function (value) { - this._dataSourceUrl$1 = value; - return value; - }, - get_timeSeries: function () { - return this.timeSeries; - }, - set_timeSeries: function (value) { - if (this.timeSeries !== value) { - this.version++; - this.timeSeries = value; - } - return value; - }, - get_beginRange: function () { - return this._beginRange$1; - }, - set_beginRange: function (value) { - if (!ss.compareDates(this._beginRange$1, value)) { - this.version++; - this._beginRange$1 = value; - } - return value; - }, - get_endRange: function () { - return this._endRange$1; - }, - set_endRange: function (value) { - if (!ss.compareDates(this._endRange$1, value)) { - this.version++; - this._endRange$1 = value; - } - return value; - }, - initializeFromXml: function (node) { - this.set_timeSeries(ss.boolean(node.attributes.getNamedItem('TimeSeries').nodeValue)); - this.set_beginRange(new Date(node.attributes.getNamedItem('BeginRange').nodeValue)); - this.set_endRange(new Date(node.attributes.getNamedItem('EndRange').nodeValue)); - this.set_decay(parseFloat(node.attributes.getNamedItem('Decay').nodeValue)); - this.set_coordinatesType(Enums.parse('CoordinatesTypes', node.attributes.getNamedItem('CoordinatesType').nodeValue)); - if (this.get_coordinatesType() < 0) { - this.set_coordinatesType(0); - } - this.set_latColumn(parseInt(node.attributes.getNamedItem('LatColumn').nodeValue)); - this.set_lngColumn(parseInt(node.attributes.getNamedItem('LngColumn').nodeValue)); - if (node.attributes.getNamedItem('GeometryColumn') != null) { - this.set_geometryColumn(parseInt(node.attributes.getNamedItem('GeometryColumn').nodeValue)); - } - switch (node.attributes.getNamedItem('AltType').nodeValue) { - case 'Depth': - this.set_altType(0); - break; - case 'Altitude': - this.set_altType(1); - break; - case 'Distance': - this.set_altType(2); - break; - case 'SeaLevel': - this.set_altType(3); - break; - case 'Terrain': - this.set_altType(4); - break; - default: - break; - } - this.set_markerMix(0); - switch (node.attributes.getNamedItem('ColorMap').nodeValue) { - case 'Same_For_All': - this.set__colorMap(0); - break; - case 'Group_by_Values': - this.set__colorMap(2); - break; - case 'Per_Column_Literal': - this.set__colorMap(3); - break; - default: - break; - } - this.set_markerColumn(parseInt(node.attributes.getNamedItem('MarkerColumn').nodeValue)); - this.set_colorMapColumn(parseInt(node.attributes.getNamedItem('ColorMapColumn').nodeValue)); - switch (node.attributes.getNamedItem('PlotType').nodeValue) { - case 'Gaussian': - this.set_plotType(0); - break; - case 'Point': - this.set_plotType(1); - break; - case 'Circle': - this.set_plotType(2); - break; - case 'PushPin': - this.set_plotType(4); - break; - default: - break; - } - this.set_markerIndex(parseInt(node.attributes.getNamedItem('MarkerIndex').nodeValue)); - switch (node.attributes.getNamedItem('MarkerScale').nodeValue) { - case 'Screen': - this.set_markerScale(0); - break; - case 'World': - this.set_markerScale(1); - break; - default: - break; - } - switch (node.attributes.getNamedItem('AltUnit').nodeValue) { - case 'Meters': - this.set_altUnit(1); - break; - case 'Feet': - this.set_altUnit(2); - break; - case 'Inches': - this.set_altUnit(3); - break; - case 'Miles': - this.set_altUnit(4); - break; - case 'Kilometers': - this.set_altUnit(5); - break; - case 'AstronomicalUnits': - this.set_altUnit(6); - break; - case 'LightYears': - this.set_altUnit(7); - break; - case 'Parsecs': - this.set_altUnit(8); - break; - case 'MegaParsecs': - this.set_altUnit(9); - break; - case 'Custom': - this.set_altUnit(10); - break; - default: - break; - } - this.set_altColumn(parseInt(node.attributes.getNamedItem('AltColumn').nodeValue)); - this.set_startDateColumn(parseInt(node.attributes.getNamedItem('StartDateColumn').nodeValue)); - this.set_endDateColumn(parseInt(node.attributes.getNamedItem('EndDateColumn').nodeValue)); - this.set_sizeColumn(parseInt(node.attributes.getNamedItem('SizeColumn').nodeValue)); - this.set_hyperlinkFormat(node.attributes.getNamedItem('HyperlinkFormat').nodeValue); - this.set_hyperlinkColumn(parseInt(node.attributes.getNamedItem('HyperlinkColumn').nodeValue)); - this.set_scaleFactor(parseFloat(node.attributes.getNamedItem('ScaleFactor').nodeValue)); - switch (node.attributes.getNamedItem('PointScaleType').nodeValue) { - case 'Linear': - this.set_pointScaleType(0); - break; - case 'Power': - this.set_pointScaleType(1); - break; - case 'Log': - this.set_pointScaleType(2); - break; - case 'Constant': - this.set_pointScaleType(3); - break; - case 'StellarMagnitude': - this.set_pointScaleType(4); - break; - default: - break; - } - if (node.attributes.getNamedItem('ShowFarSide') != null) { - this.set_showFarSide(ss.boolean(node.attributes.getNamedItem('ShowFarSide').nodeValue)); - } - if (node.attributes.getNamedItem('RaUnits') != null) { - switch (node.attributes.getNamedItem('RaUnits').nodeValue) { - case 'Hours': - this.set_raUnits(0); - break; - case 'Degrees': - this.set_raUnits(1); - break; - } - } - if (node.attributes.getNamedItem('HoverTextColumn') != null) { - this.set_nameColumn(parseInt(node.attributes.getNamedItem('HoverTextColumn').nodeValue)); - } - if (node.attributes.getNamedItem('XAxisColumn') != null) { - this.set_xAxisColumn(parseInt(node.attributes.getNamedItem('XAxisColumn').nodeValue)); - this.set_xAxisReverse(ss.boolean(node.attributes.getNamedItem('XAxisReverse').nodeValue)); - this.set_yAxisColumn(parseInt(node.attributes.getNamedItem('YAxisColumn').nodeValue)); - this.set_yAxisReverse(ss.boolean(node.attributes.getNamedItem('YAxisReverse').nodeValue)); - this.set_zAxisColumn(parseInt(node.attributes.getNamedItem('ZAxisColumn').nodeValue)); - this.set_zAxisReverse(ss.boolean(node.attributes.getNamedItem('ZAxisReverse').nodeValue)); - switch (node.attributes.getNamedItem('CartesianScale').nodeValue) { - case 'Meters': - this.set_cartesianScale(1); - break; - case 'Feet': - this.set_cartesianScale(2); - break; - case 'Inches': - this.set_cartesianScale(3); - break; - case 'Miles': - this.set_cartesianScale(4); - break; - case 'Kilometers': - this.set_cartesianScale(5); - break; - case 'AstronomicalUnits': - this.set_cartesianScale(6); - break; - case 'LightYears': - this.set_cartesianScale(7); - break; - case 'Parsecs': - this.set_cartesianScale(8); - break; - case 'MegaParsecs': - this.set_cartesianScale(9); - break; - case 'Custom': - this.set_cartesianScale(10); - break; - default: - break; - } - this.set_cartesianCustomScale(parseFloat(node.attributes.getNamedItem('CartesianCustomScale').nodeValue)); - } - if (node.attributes.getNamedItem('DynamicData') != null) { - this.set_dynamicData(ss.boolean(node.attributes.getNamedItem('DynamicData').nodeValue)); - this.set_autoUpdate(ss.boolean(node.attributes.getNamedItem('AutoUpdate').nodeValue)); - this.set_dataSourceUrl(node.attributes.getNamedItem('DataSourceUrl').nodeValue); - } - }, - get_decay: function () { - return this.decay; - }, - set_decay: function (value) { - if (this.decay !== value) { - this.version++; - this.decay = value; - } - return value; - }, - get_coordinatesType: function () { - return this._coordinatesType$1; - }, - set_coordinatesType: function (value) { - if (this._coordinatesType$1 !== value) { - this.version++; - this._coordinatesType$1 = value; - } - return value; - }, - get_latColumn: function () { - return this.latColumn; - }, - set_latColumn: function (value) { - if (this.latColumn !== value) { - this.version++; - this.latColumn = value; - } - return value; - }, - get_lngColumn: function () { - return this.lngColumn; - }, - set_lngColumn: function (value) { - if (this.lngColumn !== value) { - this.version++; - this.lngColumn = value; - } - return value; - }, - get_geometryColumn: function () { - return this.geometryColumn; - }, - set_geometryColumn: function (value) { - if (this.geometryColumn !== value) { - this.version++; - this.geometryColumn = value; - } - return value; - }, - get_xAxisColumn: function () { - return this._xAxisColumn$1; - }, - set_xAxisColumn: function (value) { - if (this._xAxisColumn$1 !== value) { - this.version++; - this._xAxisColumn$1 = value; - } - return value; - }, - get_yAxisColumn: function () { - return this._yAxisColumn$1; - }, - set_yAxisColumn: function (value) { - if (this._yAxisColumn$1 !== value) { - this.version++; - this._yAxisColumn$1 = value; - } - return value; - }, - get_zAxisColumn: function () { - return this._zAxisColumn$1; - }, - set_zAxisColumn: function (value) { - if (this._zAxisColumn$1 !== value) { - this.version++; - this._zAxisColumn$1 = value; - } - return value; - }, - get_xAxisReverse: function () { - return this._xAxisReverse$1; - }, - set_xAxisReverse: function (value) { - if (this._xAxisReverse$1 !== value) { - this.version++; - this._xAxisReverse$1 = value; - } - return value; - }, - get_yAxisReverse: function () { - return this._yAxisReverse$1; - }, - set_yAxisReverse: function (value) { - if (this._yAxisReverse$1 !== value) { - this.version++; - this._yAxisReverse$1 = value; - } - return value; - }, - get_zAxisReverse: function () { - return this._zAxisReverse$1; - }, - set_zAxisReverse: function (value) { - if (this._zAxisReverse$1 !== value) { - this.version++; - this._zAxisReverse$1 = value; - } - return value; - }, - get_altType: function () { - return this._altType$1; - }, - set_altType: function (value) { - if (this._altType$1 !== value) { - this.version++; - this._altType$1 = value; - } - return value; - }, - get_markerMix: function () { - return this._markerMix$1; - }, - set_markerMix: function (value) { - if (this._markerMix$1 !== value) { - this.version++; - this._markerMix$1 = value; - } - return value; - }, - get_raUnits: function () { - return this._raUnits$1; - }, - set_raUnits: function (value) { - if (this._raUnits$1 !== value) { - this.version++; - this._raUnits$1 = value; - } - return value; - }, - get__colorMap: function () { - return this._colorMap$1; - }, - set__colorMap: function (value) { - if (this._colorMap$1 !== value) { - this.version++; - this._colorMap$1 = value; - } - return value; - }, - get_markerColumn: function () { - return this._markerColumn$1; - }, - set_markerColumn: function (value) { - if (this._markerColumn$1 !== value) { - this.version++; - this._markerColumn$1 = value; - } - return value; - }, - get_colorMapColumn: function () { - return this._colorMapColumn$1; - }, - set_colorMapColumn: function (value) { - if (this._colorMapColumn$1 !== value) { - this.version++; - this._colorMapColumn$1 = value; - } - return value; - }, - get_plotType: function () { - return this._plotType$1; - }, - set_plotType: function (value) { - if (this._plotType$1 !== value) { - this.version++; - this._plotType$1 = value; - } - return value; - }, - get_markerIndex: function () { - return this._markerIndex$1; - }, - set_markerIndex: function (value) { - if (this._markerIndex$1 !== value) { - this.version++; - this._markerIndex$1 = value; - } - return value; - }, - get_showFarSide: function () { - return this._showFarSide$1; - }, - set_showFarSide: function (value) { - if (this._showFarSide$1 !== value) { - this.version++; - this._showFarSide$1 = value; - } - return value; - }, - get_markerScale: function () { - return this._markerScale$1; - }, - set_markerScale: function (value) { - if (this._markerScale$1 !== value) { - this.version++; - this._markerScale$1 = value; - } - return value; - }, - get_altUnit: function () { - return this._altUnit$1; - }, - set_altUnit: function (value) { - if (this._altUnit$1 !== value) { - this.version++; - this._altUnit$1 = value; - } - return value; - }, - get_cartesianScale: function () { - return this._cartesianScale$1; - }, - set_cartesianScale: function (value) { - if (this._cartesianScale$1 !== value) { - this.version++; - this._cartesianScale$1 = value; - } - return value; - }, - get_cartesianCustomScale: function () { - return this._cartesianCustomScale$1; - }, - set_cartesianCustomScale: function (value) { - if (this._cartesianCustomScale$1 !== value) { - this.version++; - this._cartesianCustomScale$1 = value; - } - return value; - }, - get_altColumn: function () { - return this.altColumn; - }, - set_altColumn: function (value) { - if (this.altColumn !== value) { - this.version++; - this.altColumn = value; - } - return value; - }, - get_startDateColumn: function () { - return this.startDateColumn; - }, - set_startDateColumn: function (value) { - if (this.startDateColumn !== value) { - this.version++; - this.startDateColumn = value; - } - return value; - }, - get_endDateColumn: function () { - return this.endDateColumn; - }, - set_endDateColumn: function (value) { - if (this.endDateColumn !== value) { - this.version++; - this.endDateColumn = value; - } - return value; - }, - get_sizeColumn: function () { - return this.sizeColumn; - }, - set_sizeColumn: function (value) { - if (this.sizeColumn !== value) { - this.version++; - this.sizeColumn = value; - } - return value; - }, - get_nameColumn: function () { - return this.nameColumn; - }, - set_nameColumn: function (value) { - if (this.nameColumn !== value) { - this.version++; - this.nameColumn = value; - } - return value; - }, - get_hyperlinkFormat: function () { - return this._hyperlinkFormat$1; - }, - set_hyperlinkFormat: function (value) { - if (this._hyperlinkFormat$1 !== value) { - this.version++; - this._hyperlinkFormat$1 = value; - } - return value; - }, - get_hyperlinkColumn: function () { - return this._hyperlinkColumn$1; - }, - set_hyperlinkColumn: function (value) { - if (this._hyperlinkColumn$1 !== value) { - this.version++; - this._hyperlinkColumn$1 = value; - } - return value; - }, - get_scaleFactor: function () { - return this.scaleFactor; - }, - set_scaleFactor: function (value) { - if (this.scaleFactor !== value) { - this.version++; - this.scaleFactor = value; - } - return value; - }, - get_pointScaleType: function () { - return this.pointScaleType; - }, - set_pointScaleType: function (value) { - if (this.pointScaleType !== value) { - this.version++; - this.pointScaleType = value; - } - return value; - }, - draw: function (renderContext, opacity, flat) { - var device = renderContext; - if (this.bufferIsFlat !== flat) { - this.cleanUp(); - this.bufferIsFlat = flat; - } - if (this.dirty) { - this.prepVertexBuffer(renderContext, opacity); - this.dirty = false; - } - var jNow = SpaceTimeController.get_jNow() - SpaceTimeController.utcToJulian(this.baseDate); - var adjustedScale = this.scaleFactor; - if (flat && this.astronomical && (this._markerScale$1 === 1)) { - adjustedScale = (this.scaleFactor / (renderContext.viewCamera.zoom / 360)); - } - if (this.triangleList2d != null) { - this.triangleList2d.decay = this.decay; - this.triangleList2d.sky = this.get_astronomical(); - this.triangleList2d.timeSeries = this.timeSeries; - this.triangleList2d.jNow = jNow; - this.triangleList2d.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.triangleList != null) { - this.triangleList.decay = this.decay; - this.triangleList.sky = this.get_astronomical(); - this.triangleList.timeSeries = this.timeSeries; - this.triangleList.jNow = jNow; - this.triangleList.draw(renderContext, opacity * this.get_opacity(), 1); - } - if (this.pointList != null) { - this.pointList.depthBuffered = false; - this.pointList.showFarSide = this.get_showFarSide(); - this.pointList.decay = (this.timeSeries) ? this.decay : 0; - this.pointList.sky = this.get_astronomical(); - this.pointList.timeSeries = this.timeSeries; - this.pointList.jNow = jNow; - this.pointList.scale = (this._markerScale$1 === 1) ? adjustedScale : -adjustedScale; - switch (this._plotType$1) { - case 0: - this.pointList.draw(renderContext, opacity * this.get_opacity(), false); - break; - case 2: - this.pointList.drawTextured(renderContext, VoTableLayer.get__circleTexture$1().texture2d, opacity * this.get_opacity()); - break; - case 1: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(19), opacity * this.get_opacity()); - break; - case 3: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(35), opacity * this.get_opacity()); - break; - case 5: - case 4: - this.pointList.drawTextured(renderContext, PushPin.getPushPinTexture(this._markerIndex$1), opacity * this.get_opacity()); - break; - default: - break; - } - } - if (this.lineList != null) { - this.lineList.sky = this.get_astronomical(); - this.lineList.decay = this.decay; - this.lineList.timeSeries = this.timeSeries; - this.lineList.jNow = jNow; - this.lineList.drawLines(renderContext, opacity * this.get_opacity()); - } - if (this.lineList2d != null) { - this.lineList2d.sky = this.get_astronomical(); - this.lineList2d.decay = this.decay; - this.lineList2d.timeSeries = this.timeSeries; - this.lineList2d.showFarSide = this.get_showFarSide(); - this.lineList2d.jNow = jNow; - this.lineList2d.drawLines(renderContext, opacity * this.get_opacity()); - } - return true; - }, - initFromXml: function (node) { - Layer.prototype.initFromXml.call(this, node); - }, - cleanUp: function () { - this.dirty = true; - if (this.lineList != null) { - this.lineList.clear(); - } - if (this.lineList2d != null) { - this.lineList2d.clear(); - } - if (this.triangleList2d != null) { - this.triangleList2d.clear(); - } - if (this.pointList != null) { - this.pointList.clear(); - } - if (this.triangleList != null) { - this.triangleList.clear(); - } - }, - dynamicUpdate: function () { - return false; - }, - addFilesToCabinet: function (fc) { - var fName = this._filename$1; - var fileName = fc.tempDirectory + ss.format('{0}\\{1}.txt', fc.get_packageID(), this.id.toString()); - var path = fName.substring(0, fName.lastIndexOf('\\') + 1); - var path2 = fileName.substring(0, fileName.lastIndexOf('\\') + 1); - }, - loadData: function (tourDoc, filename) { - var $this = this; - - var blob = tourDoc.getFileBlob(filename); - var doc = new FileReader(); - doc.onloadend = function (ee) { - var data = ss.safeCast(doc.result, String); - $this._table$1 = VoTable.loadFromString(data); - $this.set_lngColumn($this._table$1.getRAColumn().index); - $this.set_latColumn($this._table$1.getDecColumn().index); - }; - doc.readAsText(blob); - }, - canCopyToClipboard: function () { - return true; - }, - copyToClipboard: function () { - }, - findClosest: function (target, distance, defaultPlace, astronomical) { - var searchPoint = Coordinates.geoTo3dDouble(target.get_lat(), target.get_lng()); - var dist; - if (defaultPlace != null) { - var testPoint = Coordinates.raDecTo3dAu(defaultPlace.get_RA(), -defaultPlace.get_dec(), -1); - dist = Vector3d.subtractVectors(searchPoint, testPoint); - distance = dist.length(); - } - var closestItem = -1; - var index = 0; - var $enum1 = ss.enumerate(this.positions); - while ($enum1.moveNext()) { - var point = $enum1.current; - dist = Vector3d.subtractVectors(searchPoint, point); - if (dist.length() < distance) { - distance = dist.length(); - closestItem = index; - } - index++; - } - if (closestItem === -1) { - return defaultPlace; - } - var pnt = Coordinates.cartesianToSpherical2(this.positions[closestItem]); - var name = this._table$1.rows[closestItem].columnData[this.nameColumn].toString(); - if (this.nameColumn === this.startDateColumn || this.nameColumn === this.endDateColumn) { - name = SpreadSheetLayer.parseDate(name).toString(); - } - if (ss.emptyString(name)) { - name = ss.format('RA={0}, Dec={1}', Coordinates.formatHMS(pnt.get_RA()), Coordinates.formatDMS(pnt.get_dec())); - } - var place = Place.create(name, pnt.get_lat(), pnt.get_RA(), 268435456, '', 2, -1); - var rowData = {}; - for (var i = 0; i < ss.keyCount(this._table$1.columns); i++) { - var colValue = this._table$1.rows[closestItem].get_item(i).toString(); - if (i === this.startDateColumn || i === this.endDateColumn) { - colValue = SpreadSheetLayer.parseDate(colValue).toString(); - } - if (!ss.keyExists(rowData, this._table$1.column[i].name) && !ss.emptyString(this._table$1.column[i].name)) { - rowData[this._table$1.column[i].name] = colValue; - } - else { - rowData['Column' + i.toString()] = colValue; - } - } - place.set_tag(rowData); - return place; - }, - prepVertexBuffer: function (renderContext, opacity) { - var col = this._table$1.getColumnByUcd('meta.id'); - if (col == null) { - col = this._table$1.column[0]; - } - var siapSet = this.isSiapResultSet(); - if (this.pointList == null) { - this.pointList = new PointList(renderContext); - } - if (this.lineList2d == null) { - this.lineList2d = new LineList(); - } - this.lineList2d.clear(); - var stcsCol = this._table$1.getColumnByUcd('phys.area;obs.field'); - if (stcsCol == null && ss.keyExists(this._table$1.columns, 'regionSTCS')) { - stcsCol = this._table$1.columns['regionSTCS']; - } - if (!this.get_plotType()) { - this.set_markerScale(1); - } - else { - this.set_markerScale(0); - } - var vertList = []; - var indexList = []; - var lastItem = new TimeSeriesPointVertex(); - this.positions.length = 0; - var currentIndex = 0; - var color = Color.fromArgb(ss.truncate((opacity * this.get_color().a)), this.get_color().r, this.get_color().g, this.get_color().b); - this.pointScaleType = 4; - var $enum1 = ss.enumerate(this._table$1.rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - try { - if (this.lngColumn > -1 && this.latColumn > -1) { - var ra = parseFloat(row.get_item(this.get_lngColumn()).toString()); - var dec = parseFloat(row.get_item(this.get_latColumn()).toString()); - var position = Coordinates.geoTo3dDouble(dec, ra); - lastItem.position = position; - this.positions.push(lastItem.position); - lastItem.set_color(color); - if (this.sizeColumn > -1) { - try { - if (!this.get_markerScale()) { - lastItem.pointSize = 20; - } - else { - switch (this.pointScaleType) { - case 0: - lastItem.pointSize = parseFloat(row.get_item(this.sizeColumn).toString()); - break; - case 2: - lastItem.pointSize = Math.log(parseFloat(row.get_item(this.sizeColumn).toString())); - break; - case 1: - lastItem.pointSize = Math.pow(2, parseFloat(row.get_item(this.sizeColumn).toString())); - break; - case 4: - var size = parseFloat(row.get_item(this.sizeColumn).toString()); - lastItem.pointSize = (40 / Math.pow(1.6, size)) * 10; - break; - case 3: - lastItem.pointSize = 1; - break; - default: - break; - } - } - } - catch ($e2) { - lastItem.pointSize = 0.01; - } - } - else { - if (!this.get_markerScale()) { - lastItem.pointSize = 20; - } - else { - lastItem.pointSize = Math.pow(2, 1) * 100; - } - } - if (this.startDateColumn > -1) { - var dateTime = ss.date(row.get_item(this.startDateColumn).toString()); - lastItem.tu = SpaceTimeController.utcToJulian(dateTime); - lastItem.tv = 0; - } - vertList.push(lastItem); - this.pointList.addPoint(lastItem.position, lastItem.color, new Dates(lastItem.tu, lastItem.tv), lastItem.pointSize); - currentIndex++; - } - if (siapSet && stcsCol != null) { - this._addSiapStcRow$1(stcsCol.name, row, row === this._table$1.selectedRow); - } - } - catch ($e3) { - } - this.lines = false; - } - if (siapSet && stcsCol != null) { - this._addSiapStcRow$1(stcsCol.name, this._table$1.selectedRow, true); - } - return true; - }, - _addSiapStcRow$1: function (stcsColName, row, selected) { - var stcs = ss.replaceString(row.getColumnData(stcsColName).toString(), ' ', ' '); - var col = Color.fromArgb(120, 255, 255, 255); - if (selected) { - col = Colors.get_yellow(); - } - if (ss.startsWith(stcs, 'Polygon J2000')) { - var parts = stcs.split(' '); - var len = parts.length; - var index = 0; - while (index < len) { - if (parts[index] === 'Polygon') { - index += 2; - var lastPoint = new Vector3d(); - var firstPoint = new Vector3d(); - var start = true; - for (var i = index; i < len; i += 2) { - if (parts[i] === 'Polygon') { - start = true; - break; - } - else { - var Xcoord = Coordinates.parseRA(parts[i], true) * 15 + 180; - var Ycoord = Coordinates.parseDec(parts[i + 1]); - var pnt = Coordinates.geoTo3dDouble(Ycoord, Xcoord); - if (!start) { - this.lineList2d.addLine(lastPoint, pnt, col, new Dates(0, 0)); - } - else { - firstPoint = pnt; - start = false; - } - lastPoint = pnt; - } - index += 2; - } - if (len > 4) { - this.lineList2d.addLine(firstPoint, lastPoint, col, new Dates(0, 0)); - } - } - } - } - }, - isSiapResultSet: function () { - return this._table$1.getColumnByUcd('vox:image.title') != null && this._table$1.getColumnByUcd('VOX:Image.AccessReference') != null; - }, - get_header: function () { - var header = new Array(ss.keyCount(this._table$1.columns)); - var index = 0; - var $enum1 = ss.enumerate(this._table$1.column); - while ($enum1.moveNext()) { - var col = $enum1.current; - header[index++] = col.name; - } - return header; - }, - get_table: function () { - return this._table$1; - }, - set_table: function (value) { - this._table$1 = value; - return value; - } - }; - - - // wwtlib.MercatorTile - - function MercatorTile() { - this._tileDegrees$1 = 0; - this._latMin$1 = 0; - this._latMax$1 = 0; - this._lngMin$1 = 0; - this._lngMax$1 = 0; - this._subDivisionLevel$1 = 32; - Tile.call(this); - } - MercatorTile.create = function (level, X, Y, dataset, parent) { - var temp = new MercatorTile(); - temp.parent = parent; - temp.level = level; - temp.tileX = X; - temp.tileY = Y; - temp.dataset = dataset; - temp.computeBoundingSphere(); - return temp; - }; - MercatorTile.getCentrePointOffsetAsTileRatio = function (lat, lon, zoom) { - var metersX = MercatorTile.absoluteLonToMetersAtZoom(lon, zoom); - var relativeXIntoCell = (metersX / 256) - Math.floor(metersX / 256); - var metersY = MercatorTile.absoluteLatToMetersAtZoom(lat, zoom); - var relativeYIntoCell = (metersY / 256) - Math.floor(metersY / 256); - return Vector2d.create(relativeXIntoCell, relativeYIntoCell); - }; - MercatorTile.relativeMetersToLatAtZoom = function (Y, zoom) { - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - var metersY = Y * metersPerPixel; - return MercatorTile._radToDeg$1(Math.PI / 2 - 2 * Math.atan(Math.exp(0 - metersY / 6378137))); - }; - MercatorTile.relativeMetersToLonAtZoom = function (X, zoom) { - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - var metersX = X * metersPerPixel; - return MercatorTile._radToDeg$1(metersX / 6378137); - }; - MercatorTile.absoluteLatToMetersAtZoom = function (latitude, zoom) { - var sinLat = Math.sin(MercatorTile._degToRad$1(latitude)); - var metersY = 6378137 / 2 * Math.log((1 + sinLat) / (1 - sinLat)); - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - return ss.truncate((Math.round(20037508 - metersY) / metersPerPixel)); - }; - MercatorTile.absoluteMetersToLatAtZoom = function (Y, zoom) { - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - var metersY = 20037508 - Y * metersPerPixel; - return MercatorTile._radToDeg$1(Math.PI / 2 - 2 * Math.atan(Math.exp(0 - metersY / 6378137))); - }; - MercatorTile.absoluteLonToMetersAtZoom = function (longitude, zoom) { - var metersX = 6378137 * MercatorTile._degToRad$1(longitude); - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - return ss.truncate(((metersX + 20037508) / metersPerPixel)); - }; - MercatorTile.absoluteMetersToLonAtZoom = function (X, zoom) { - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - var metersX = X * metersPerPixel - 20037508; - return MercatorTile._radToDeg$1(metersX / 6378137); - }; - MercatorTile.absoluteLonToMetersAtZoomTile = function (longitude, zoom, tileX) { - var metersX = 6378137 * MercatorTile._degToRad$1(longitude); - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - return ss.truncate(((metersX + 20037508) / metersPerPixel)); - }; - MercatorTile.absoluteLatToMetersAtZoomTile = function (latitude, zoom, tileX) { - var sinLat = Math.sin(MercatorTile._degToRad$1(latitude)); - var metersY = 6378137 / 2 * Math.log((1 + sinLat) / (1 - sinLat)); - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - return ss.truncate((Math.round(20037508 - metersY) / metersPerPixel)); - }; - MercatorTile.absoluteMetersToLonAtZoomByTileY = function (X, zoom, tileY) { - var metersPerPixel = MercatorTile.metersPerPixel2(zoom); - var metersX = X * metersPerPixel - 20037508; - return MercatorTile._radToDeg$1(metersX / 6378137); - }; - MercatorTile._degToRad$1 = function (deg) { - return (deg * Math.PI / 180); - }; - MercatorTile.metersPerPixel2 = function (zoom) { - return (156543 / (1 << zoom)); - }; - MercatorTile._radToDeg$1 = function (rad) { - return (rad * 180 / Math.PI); - }; - var MercatorTile$ = { - computeBoundingSphere: function () { - this._tileDegrees$1 = 360 / Math.pow(2, this.level); - this._latMin$1 = MercatorTile.absoluteMetersToLatAtZoom(this.tileY * 256, this.level); - this._latMax$1 = MercatorTile.absoluteMetersToLatAtZoom((this.tileY + 1) * 256, this.level); - this._lngMin$1 = ((this.tileX * this._tileDegrees$1) - 180); - this._lngMax$1 = ((((this.tileX + 1)) * this._tileDegrees$1) - 180); - var latCenter = (this._latMin$1 + this._latMax$1) / 2; - var lngCenter = (this._lngMin$1 + this._lngMax$1) / 2; - this.sphereCenter = this.geoTo3d(latCenter, lngCenter, false); - this.topLeft = this.geoTo3d(this._latMin$1, this._lngMin$1, false); - this.bottomRight = this.geoTo3d(this._latMax$1, this._lngMax$1, false); - this.topRight = this.geoTo3d(this._latMin$1, this._lngMax$1, false); - this.bottomLeft = this.geoTo3d(this._latMax$1, this._lngMin$1, false); - if (!this.tileY) { - this.topLeft = Vector3d.create(0, 1, 0); - this.topRight = Vector3d.create(0, 1, 0); - } - if (this.tileY === Math.pow(2, this.level) - 1) { - this.bottomRight = Vector3d.create(0, -1, 0); - this.bottomLeft = Vector3d.create(0, -1, 0); - } - var distVect = this.topLeft; - distVect.subtract(this.sphereCenter); - this.sphereRadius = distVect.length(); - distVect = this.bottomRight; - distVect.subtract(this.sphereCenter); - var len = distVect.length(); - if (this.sphereRadius < len) { - this.sphereRadius = len; - } - this._tileDegrees$1 = Math.abs(this._latMax$1 - this._latMin$1); - }, - isPointInTile: function (lat, lng) { - if (!this.demReady || this.demData == null || lat < Math.min(this._latMin$1, this._latMax$1) || lat > Math.max(this._latMax$1, this._latMin$1) || lng < Math.min(this._lngMin$1, this._lngMax$1) || lng > Math.max(this._lngMin$1, this._lngMax$1)) { - return false; - } - return true; - }, - getSurfacePointAltitude: function (lat, lng, meters) { - if (this.level < Tile.lastDeepestLevel) { - var $enum1 = ss.enumerate(this.children); - while ($enum1.moveNext()) { - var child = $enum1.current; - if (child != null) { - if (child.isPointInTile(lat, lng)) { - var retVal = child.getSurfacePointAltitude(lat, lng, meters); - if (!!retVal) { - return retVal; - } - else { - break; - } - } - } - } - } - var alt = this._getAltitudeAtLatLng$1(lat, lng, (meters) ? 1 : this.get__demScaleFactor()); - return alt; - }, - _getAltitudeAtLatLng$1: function (lat, lng, scaleFactor) { - var height = Math.abs(this._latMax$1 - this._latMin$1); - var width = Math.abs(this._lngMax$1 - this._lngMin$1); - var yy = ((lat - Math.min(this._latMax$1, this._latMin$1)) / height * 32); - var xx = ((lng - Math.min(this._lngMax$1, this._lngMin$1)) / width * 32); - var indexY = Math.min(31, ss.truncate(yy)); - var indexX = Math.min(31, ss.truncate(xx)); - var ha = xx - indexX; - var va = yy - indexY; - var ul = this.demData[indexY * 33 + indexX]; - var ur = this.demData[indexY * 33 + (indexX + 1)]; - var ll = this.demData[(indexY + 1) * 33 + indexX]; - var lr = this.demData[(indexY + 1) * 33 + (indexX + 1)]; - var top = ul * (1 - ha) + ha * ur; - var bottom = ll * (1 - ha) + ha * lr; - var val = top * (1 - va) + va * bottom; - return val / scaleFactor; - }, - createGeometry: function (renderContext) { - Tile.prototype.createGeometry.call(this, renderContext); - if (this.geometryCreated) { - return true; - } - this.geometryCreated = true; - if (Tile.uvMultiple === 256) { - if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { - this._subDivisionLevel$1 = Math.max(2, (6 - this.level) * 2); - } - } - for (var i = 0; i < 4; i++) { - this._renderTriangleLists[i] = []; - } - var lat, lng; - var index = 0; - var tileDegrees = 360 / Math.pow(2, this.level); - this._latMin$1 = MercatorTile.absoluteMetersToLatAtZoom(this.tileY * 256, this.level); - this._latMax$1 = MercatorTile.absoluteMetersToLatAtZoom((this.tileY + 1) * 256, this.level); - this._lngMin$1 = ((this.tileX * tileDegrees) - 180); - this._lngMax$1 = ((((this.tileX + 1)) * tileDegrees) - 180); - var latCenter = MercatorTile.absoluteMetersToLatAtZoom(((this.tileY * 2) + 1) * 256, this.level + 1); - this.topLeft = this.geoTo3d(this._latMin$1, this._lngMin$1, false); - this.bottomRight = this.geoTo3d(this._latMax$1, this._lngMax$1, false); - this.topRight = this.geoTo3d(this._latMin$1, this._lngMax$1, false); - this.bottomLeft = this.geoTo3d(this._latMax$1, this._lngMin$1, false); - var verts = new Array((this._subDivisionLevel$1 + 1) * (this._subDivisionLevel$1 + 1)); - tileDegrees = this._lngMax$1 - this._lngMin$1; - var dGrid = (tileDegrees / this._subDivisionLevel$1); - var x1, y1; - var textureStep = 1 / this._subDivisionLevel$1; - var latDegrees = this._latMax$1 - latCenter; - for (y1 = 0; y1 < this._subDivisionLevel$1 / 2; y1++) { - if (y1 !== this._subDivisionLevel$1 / 2) { - lat = this._latMax$1 - (2 * textureStep * latDegrees * y1); - } - else { - lat = latCenter; - } - for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { - if (x1 !== this._subDivisionLevel$1) { - lng = this._lngMin$1 + (textureStep * tileDegrees * x1); - } - else { - lng = this._lngMax$1; - } - index = y1 * (this._subDivisionLevel$1 + 1) + x1; - verts[index] = new PositionTexture(); - verts[index].position = this.geoTo3dWithAlt(lat, lng, false, true); - verts[index].tu = (x1 * textureStep) * Tile.uvMultiple; - verts[index].tv = ((MercatorTile.absoluteLatToMetersAtZoom(lat, this.level) - (this.tileY * 256)) / 256) * Tile.uvMultiple; - this.demIndex++; - } - } - latDegrees = this._latMin$1 - latCenter; - for (y1 = this._subDivisionLevel$1 / 2; y1 <= this._subDivisionLevel$1; y1++) { - if (y1 !== this._subDivisionLevel$1) { - lat = latCenter + (2 * textureStep * latDegrees * (y1 - (this._subDivisionLevel$1 / 2))); - } - else { - lat = this._latMin$1; - } - for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { - if (x1 !== this._subDivisionLevel$1) { - lng = this._lngMin$1 + (textureStep * tileDegrees * x1); - } - else { - lng = this._lngMax$1; - } - index = y1 * (this._subDivisionLevel$1 + 1) + x1; - verts[index] = new PositionTexture(); - verts[index].position = this.geoTo3dWithAlt(lat, lng, false, true); - verts[index].tu = (x1 * textureStep) * Tile.uvMultiple; - verts[index].tv = ((MercatorTile.absoluteLatToMetersAtZoom(lat, this.level) - (this.tileY * 256)) / 256) * Tile.uvMultiple; - this.demIndex++; - } - } - if (!this.tileY) { - y1 = this._subDivisionLevel$1; - for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { - index = y1 * (this._subDivisionLevel$1 + 1) + x1; - verts[index].position = Vector3d.create(0, 1, 0); - } - } - if (this.tileY === Math.pow(2, this.level) - 1) { - y1 = 0; - for (x1 = 0; x1 <= this._subDivisionLevel$1; x1++) { - index = y1 * (this._subDivisionLevel$1 + 1) + x1; - verts[index].position = Vector3d.create(0, -1, 0); - } - } - this.triangleCount = this._subDivisionLevel$1 * this._subDivisionLevel$1 * 2; - var quarterDivisions = this._subDivisionLevel$1 / 2; - var part = 0; - if (renderContext.gl == null) { - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - index = 0; - for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - var p1; - var p2; - var p3; - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + x1)]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - var tri = RenderTriangle.create(p1, p2, p3, this.texture, this.level); - this._renderTriangleLists[part].push(tri); - p1 = verts[(y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - p2 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1)]; - p3 = verts[((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1))]; - tri = RenderTriangle.create(p1, p2, p3, this.texture, this.level); - this._renderTriangleLists[part].push(tri); - } - } - part++; - } - } - } - else { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(verts.length * 5); - var buffer = f32array; - index = 0; - var $enum1 = ss.enumerate(verts); - while ($enum1.moveNext()) { - var pt = $enum1.current; - index = this.addVertex(buffer, index, pt); - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - for (var y2 = 0; y2 < 2; y2++) { - for (var x2 = 0; x2 < 2; x2++) { - var ui16array = new Uint16Array(this.triangleCount * 3); - var indexArray = ui16array; - index = 0; - for (y1 = (quarterDivisions * y2); y1 < (quarterDivisions * (y2 + 1)); y1++) { - for (x1 = (quarterDivisions * x2); x1 < (quarterDivisions * (x2 + 1)); x1++) { - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = (y1 * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + x1); - indexArray[index++] = ((y1 + 1) * (this._subDivisionLevel$1 + 1) + (x1 + 1)); - } - } - this._indexBuffers[part] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this._indexBuffers[part]); - Tile.prepDevice.bufferData(34963, ui16array, 35044); - part++; - } - } - } - return true; - }, - _getDemSample$1: function (x, y) { - return this.demData[(32 - y) * 33 + x]; - }, - createDemFromParent: function () { - var parent = ss.safeCast(this.parent, MercatorTile); - if (parent == null || parent.demData == null) { - return false; - } - var offsetX = (((this.tileX % 2) === 1) ? 16 : 0); - var offsetY = (((this.tileY % 2) === 1) ? 16 : 0); - this.demData = new Array(this.demSize); - for (var y = 0; y < 33; y += 2) { - var copy = true; - for (var x = 0; x < 33; x++) { - if (copy) { - this.demData[(32 - y) * 33 + x] = parent._getDemSample$1((x / 2) + offsetX, (y / 2) + offsetY); - } - else { - this.demData[(32 - y) * 33 + x] = ((parent._getDemSample$1((x / 2) + offsetX, (y / 2) + offsetY) + parent._getDemSample$1(((x / 2) + offsetX) + 1, (y / 2) + offsetY)) / 2); - } - copy = !copy; - } - } - for (var y = 1; y < 33; y += 2) { - for (var x = 0; x < 33; x++) { - this.demData[(32 - y) * 33 + x] = ((this._getDemSample$1(x, y - 1) + this._getDemSample$1(x, y + 1)) / 2); - } - } - var $enum1 = ss.enumerate(this.demData); - while ($enum1.moveNext()) { - var sample = $enum1.current; - this.demAverage += sample; - } - this.demAverage /= this.demData.length; - this.demReady = true; - return true; - } - }; - - - // wwtlib.PlotTile - - function PlotTile() { - this._topDown$1 = true; - this.backslash = false; - this._vertexList$1 = null; - this._childTriangleList$1 = null; - this._stars$1 = []; - this._subDivisionLevel$1 = 4; - this._subDivided$1 = false; - Tile.call(this); - } - PlotTile.create = function (level, xc, yc, dataset, parent) { - var temp = new PlotTile(); - temp.parent = parent; - temp.level = level; - temp.tileX = xc; - temp.tileY = yc; - temp.dataset = dataset; - temp._topDown$1 = !dataset.get_bottomsUp(); - if (temp.tileX !== xc) { - alert('bad'); - } - if (!!dataset.get_meanRadius()) { - temp.set__demScaleFactor(dataset.get_meanRadius()); - } - else { - if (!dataset.get_dataSetType()) { - temp.set__demScaleFactor(6371000); - } - else { - temp.set__demScaleFactor(3396010); - } - } - temp.computeBoundingSphere(); - return temp; - }; - var PlotTile$ = { - computeBoundingSphere: function () { - this._initializeGrids$1(); - this.topLeft = this.bounds[0 + 3 * 0].position.copy(); - this.bottomRight = this.bounds[2 + 3 * 2].position.copy(); - this.topRight = this.bounds[2 + 3 * 0].position.copy(); - this.bottomLeft = this.bounds[0 + 3 * 2].position.copy(); - this.calcSphere(); - }, - renderPart: function (renderContext, part, opacity, combine) { - if (renderContext.gl != null) { - } - else { - if (!part) { - var $enum1 = ss.enumerate(this._stars$1); - while ($enum1.moveNext()) { - var star = $enum1.current; - var radDec = 25 / Math.pow(1.6, star.magnitude); - Planets.drawPointPlanet(renderContext, star.position, radDec, star.col, false); - } - } - } - }, - requestImage: function () { - if (!this.downloading && !this.readyToRender) { - this.downloading = true; - this._webFile$1 = new WebFile(URLHelpers.singleton.rewrite(this.get_URL(), 0)); - this._webFile$1.onStateChange = ss.bind('fileStateChange', this); - this._webFile$1.send(); - } - }, - fileStateChange: function () { - if (this._webFile$1.get_state() === 2) { - this.downloading = false; - this.readyToRender = false; - this.errored = true; - this.requestPending = false; - TileCache.removeFromQueue(this.get_key(), true); - } - else if (this._webFile$1.get_state() === 1) { - this.texReady = true; - this.downloading = false; - this.errored = false; - this.readyToRender = this.texReady && (this.demReady || !this.demTile); - this.requestPending = false; - TileCache.removeFromQueue(this.get_key(), true); - this._loadData$1(this._webFile$1.getText()); - } - }, - _loadData$1: function (data) { - var rows = ss.replaceString(data, '\r\n', '\n').split('\n'); - var firstRow = true; - var type = 0; - var star = null; - var $enum1 = ss.enumerate(rows); - while ($enum1.moveNext()) { - var row = $enum1.current; - if (firstRow) { - firstRow = false; - continue; - } - if (ss.trim(row).length > 5) { - star = new Star(row); - star.position = Coordinates.raDecTo3dAu(star.RA, star.dec, 1); - this._stars$1.push(star); - } - } - }, - isPointInTile: function (lat, lng) { - if (!this.level) { - return true; - } - if (this.level === 1) { - if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { - return true; - } - if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { - return true; - } - if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { - return true; - } - if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { - return true; - } - return false; - } - if (!this.demReady || this.demData == null) { - return false; - } - var testPoint = Coordinates.geoTo3dDouble(-lat, lng); - var top = this._isLeftOfHalfSpace$1(this.topLeft.copy(), this.topRight.copy(), testPoint); - var right = this._isLeftOfHalfSpace$1(this.topRight.copy(), this.bottomRight.copy(), testPoint); - var bottom = this._isLeftOfHalfSpace$1(this.bottomRight.copy(), this.bottomLeft.copy(), testPoint); - var left = this._isLeftOfHalfSpace$1(this.bottomLeft.copy(), this.topLeft.copy(), testPoint); - if (top && right && bottom && left) { - return true; - } - return false; - }, - _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { - pntA.normalize(); - pntB.normalize(); - var cross = Vector3d.cross(pntA, pntB); - var dot = Vector3d.dot(cross, pntTest); - return dot < 0; - }, - _initializeGrids$1: function () { - this._vertexList$1 = []; - this._childTriangleList$1 = new Array(4); - this._childTriangleList$1[0] = []; - this._childTriangleList$1[1] = []; - this._childTriangleList$1[2] = []; - this._childTriangleList$1[3] = []; - this.bounds = new Array(9); - if (this.level > 0) { - if (this.parent == null) { - this.parent = TileCache.getTile(this.level - 1, this.tileX / 2, this.tileY / 2, this.dataset, null); - } - var parent = this.parent; - var xIndex = this.tileX % 2; - var yIndex = this.tileY % 2; - if (this.level > 1) { - this.backslash = parent.backslash; - } - else { - this.backslash = (xIndex === 1 ^ yIndex === 1) === 1; - } - this.bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].copy(); - this.bounds[1 + 3 * 0] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); - this.bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].copy(); - this.bounds[0 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - if (this.backslash) { - this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - } - else { - this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - } - this.bounds[2 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - this.bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].copy(); - this.bounds[1 + 3 * 2] = this._midpoint$1(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - this.bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].copy(); - this.bounds[0 + 3 * 0].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[1 + 3 * 0].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[2 + 3 * 0].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 1].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 1].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[2 + 3 * 1].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[0 + 3 * 2].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 2].tv = 1 * Tile.uvMultiple; - this.bounds[1 + 3 * 2].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 2].tv = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 2].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 2].tv = 1 * Tile.uvMultiple; - } - else { - this.bounds[0 + 3 * 0] = PositionTexture.create(0, -1, 0, 0, 0); - this.bounds[1 + 3 * 0] = PositionTexture.create(0, 0, 1, 0.5, 0); - this.bounds[2 + 3 * 0] = PositionTexture.create(0, -1, 0, 1, 0); - this.bounds[0 + 3 * 1] = PositionTexture.create(-1, 0, 0, 0, 0.5); - this.bounds[1 + 3 * 1] = PositionTexture.create(0, 1, 0, 0.5, 0.5); - this.bounds[2 + 3 * 1] = PositionTexture.create(1, 0, 0, 1, 0.5); - this.bounds[0 + 3 * 2] = PositionTexture.create(0, -1, 0, 0, 1); - this.bounds[1 + 3 * 2] = PositionTexture.create(0, 0, -1, 0.5, 1); - this.bounds[2 + 3 * 2] = PositionTexture.create(0, -1, 0, 1, 1); - } - }, - _midpoint$1: function (positionNormalTextured, positionNormalTextured_2) { - var a1 = Vector3d.lerp(positionNormalTextured.position, positionNormalTextured_2.position, 0.5); - var a1uv = Vector2d.lerp(Vector2d.create(positionNormalTextured.tu, positionNormalTextured.tv), Vector2d.create(positionNormalTextured_2.tu, positionNormalTextured_2.tv), 0.5); - a1.normalize(); - return PositionTexture.createPos(a1, a1uv.x, a1uv.y); - }, - createGeometry: function (renderContext) { - if (this.geometryCreated) { - return true; - } - this.geometryCreated = true; - Tile.prototype.createGeometry.call(this, renderContext); - return true; - }, - cleanUp: function (removeFromParent) { - Tile.prototype.cleanUp.call(this, removeFromParent); - if (this._vertexList$1 != null) { - this._vertexList$1 = null; - } - if (this._childTriangleList$1 != null) { - this._childTriangleList$1 = null; - } - this._subDivided$1 = false; - this.demArray = null; - } - }; - - - // wwtlib.TangentTile - - function TangentTile(level, x, y, dataset, parent) { - this._topDown$1 = true; - Tile.call(this); - this.parent = parent; - this.level = level; - this.tileX = x; - this.tileY = y; - this.dataset = dataset; - this._topDown$1 = !dataset.get_bottomsUp(); - this.computeBoundingSphere(); - } - var TangentTile$ = { - computeBoundingSphere: function () { - if (!this._topDown$1) { - this.computeBoundingSphereBottomsUp(); - return; - } - var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var latMin = (this.dataset.get_baseTileDegrees() / 2 - (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); - var latMax = (this.dataset.get_baseTileDegrees() / 2 - ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); - var lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - var lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - var latCenter = (latMin + latMax) / 2; - var lngCenter = (lngMin + lngMax) / 2; - this.sphereCenter = this.geoTo3dTan(latCenter, lngCenter); - this.topLeft = this.geoTo3dTan(latMin, lngMin); - this.bottomRight = this.geoTo3dTan(latMax, lngMax); - this.topRight = this.geoTo3dTan(latMin, lngMax); - this.bottomLeft = this.geoTo3dTan(latMax, lngMin); - var distVect = this.geoTo3dTan(latMin, lngMin); - distVect.subtract(this.sphereCenter); - this.sphereRadius = distVect.length(); - }, - computeBoundingSphereBottomsUp: function () { - var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var latMin = (this.dataset.get_baseTileDegrees() / 2 + ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); - var latMax = (this.dataset.get_baseTileDegrees() / 2 + (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); - var lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - var lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - this.topLeft = this.geoTo3dTan(latMin, lngMin); - this.bottomRight = this.geoTo3dTan(latMax, lngMax); - this.topRight = this.geoTo3dTan(latMin, lngMax); - this.bottomLeft = this.geoTo3dTan(latMax, lngMin); - }, - getLatLngEdges: function () { - var tileDegrees = this.dataset.get_baseTileDegrees() / Math.pow(2, this.level); - var edges = new LatLngEdges(); - edges.latMin = (this.dataset.get_baseTileDegrees() / 2 - (this.tileY) * tileDegrees) + this.dataset.get_offsetY(); - edges.latMax = (this.dataset.get_baseTileDegrees() / 2 - ((this.tileY + 1)) * tileDegrees) + this.dataset.get_offsetY(); - edges.lngMin = ((this.tileX) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - edges.lngMax = (((this.tileX + 1)) * tileDegrees - this.dataset.get_baseTileDegrees() / this.dataset.get_widthFactor()) + this.dataset.get_offsetX(); - return edges; - }, - geoTo3dTan: function (lat, lng) { - lng = -lng; - var fac1 = this.dataset.get_baseTileDegrees() / 2; - var factor = Math.tan(fac1 * Tile.RC); - return this.dataset.get_matrix().transform(Vector3d.create(1, (lat / fac1 * factor), (lng / fac1 * factor))); - }, - requestImage: function () { - this.fitsImage = ss.safeCast(this.dataset.get_wcsImage(), FitsImage); - if (this.fitsImage != null) { - this.texReady = true; - this.downloading = false; - this.errored = this.fitsImage.errored; - this.requestPending = false; - TileCache.removeFromQueue(this.get_key(), true); - if (RenderContext.useGlVersion2) { - this.makeTexture(); - this.readyToRender = true; - } - else { - this.bmp = this.fitsImage.getBitmap(); - this.texture2d = this.bmp.getTexture(); - this.readyToRender = true; - } - } - else { - Tile.prototype.requestImage.call(this); - } - }, - createGeometry: function (renderContext) { - if (this.geometryCreated) { - return true; - } - this.geometryCreated = true; - for (var i = 0; i < 4; i++) { - this._renderTriangleLists[i] = []; - } - this.globalCenter = this.geoTo3dTan(0, 0); - var edges = this.getLatLngEdges(); - this.topLeft = this.geoTo3dTan(edges.latMin, edges.lngMin).subtract(this.globalCenter); - this.bottomRight = this.geoTo3dTan(edges.latMax, edges.lngMax).subtract(this.globalCenter); - this.topRight = this.geoTo3dTan(edges.latMin, edges.lngMax).subtract(this.globalCenter); - this.bottomLeft = this.geoTo3dTan(edges.latMax, edges.lngMin).subtract(this.globalCenter); - var center = Vector3d.midPoint(this.topLeft, this.bottomRight); - var leftCenter = Vector3d.midPoint(this.topLeft, this.bottomLeft); - var rightCenter = Vector3d.midPoint(this.topRight, this.bottomRight); - var topCenter = Vector3d.midPoint(this.topLeft, this.topRight); - var bottomCenter = Vector3d.midPoint(this.bottomLeft, this.bottomRight); - if (renderContext.gl == null) { - this._renderTriangleLists[0].push(RenderTriangle.create(PositionTexture.createPos(this.topLeft, 0, 0), PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(topCenter, 0.5, 0), this.texture, this.level)); - this._renderTriangleLists[0].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(topCenter, 0.5, 0), this.texture, this.level)); - this._renderTriangleLists[1].push(RenderTriangle.create(PositionTexture.createPos(topCenter, 0.5, 0), PositionTexture.createPos(rightCenter, 1, 0.5), PositionTexture.createPos(this.topRight, 1, 0), this.texture, this.level)); - this._renderTriangleLists[1].push(RenderTriangle.create(PositionTexture.createPos(topCenter, 0.5, 0), PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(rightCenter, 1, 0.5), this.texture, this.level)); - this._renderTriangleLists[2].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(bottomCenter, 0.5, 1), PositionTexture.createPos(center, 0.5, 0.5), this.texture, this.level)); - this._renderTriangleLists[2].push(RenderTriangle.create(PositionTexture.createPos(leftCenter, 0, 0.5), PositionTexture.createPos(this.bottomLeft, 0, 1), PositionTexture.createPos(bottomCenter, 0.5, 1), this.texture, this.level)); - this._renderTriangleLists[3].push(RenderTriangle.create(PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(this.bottomRight, 1, 1), PositionTexture.createPos(rightCenter, 1, 0.5), this.texture, this.level)); - this._renderTriangleLists[3].push(RenderTriangle.create(PositionTexture.createPos(center, 0.5, 0.5), PositionTexture.createPos(bottomCenter, 0.5, 1), PositionTexture.createPos(this.bottomRight, 1, 1), this.texture, this.level)); - this.readyToRender = true; - } - else { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(9 * 5); - var buffer = f32array; - var index = 0; - index = this.addVertex(buffer, index, PositionTexture.createPos(bottomCenter, 0.5, 1)); - index = this.addVertex(buffer, index, PositionTexture.createPos(this.bottomLeft, 0, 1)); - index = this.addVertex(buffer, index, PositionTexture.createPos(this.bottomRight, 1, 1)); - index = this.addVertex(buffer, index, PositionTexture.createPos(center, 0.5, 0.5)); - index = this.addVertex(buffer, index, PositionTexture.createPos(leftCenter, 0, 0.5)); - index = this.addVertex(buffer, index, PositionTexture.createPos(rightCenter, 1, 0.5)); - index = this.addVertex(buffer, index, PositionTexture.createPos(topCenter, 0.5, 0)); - index = this.addVertex(buffer, index, PositionTexture.createPos(this.topLeft, 0, 0)); - index = this.addVertex(buffer, index, PositionTexture.createPos(this.topRight, 1, 0)); - Tile.prepDevice.bufferData(34962, f32array, 35044); - for (var i = 0; i < 4; i++) { - index = 0; - this.triangleCount = 2; - var ui16array = new Uint16Array(this.triangleCount * 3); - var indexArray = ui16array; - switch (i) { - case 0: - indexArray[index++] = 7; - indexArray[index++] = 4; - indexArray[index++] = 6; - indexArray[index++] = 4; - indexArray[index++] = 3; - indexArray[index++] = 6; - break; - case 1: - indexArray[index++] = 6; - indexArray[index++] = 5; - indexArray[index++] = 8; - indexArray[index++] = 6; - indexArray[index++] = 3; - indexArray[index++] = 5; - break; - case 2: - indexArray[index++] = 4; - indexArray[index++] = 0; - indexArray[index++] = 3; - indexArray[index++] = 4; - indexArray[index++] = 1; - indexArray[index++] = 0; - break; - case 3: - indexArray[index++] = 3; - indexArray[index++] = 2; - indexArray[index++] = 5; - indexArray[index++] = 3; - indexArray[index++] = 0; - indexArray[index++] = 2; - break; - } - this._indexBuffers[i] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, this._indexBuffers[i]); - Tile.prepDevice.bufferData(34963, ui16array, 35044); - } - } - return true; - } - }; - - - // wwtlib.ToastTile - - function ToastTile() { - this._topDown$1 = true; - this.backslash = false; - this._vertexList$1 = null; - this._childTriangleList$1 = null; - this._subDivisionLevel$1 = 4; - this._subDivided$1 = false; - Tile.call(this); - } - ToastTile._cloneArray$1 = function (indexArray) { - var count = indexArray.length; - var ui16array = new Uint16Array(count); - var indexArrayNew = ui16array; - for (var i = 0; i < count; i++) { - indexArrayNew[i] = indexArray[i]; - } - return indexArrayNew; - }; - ToastTile.create = function (level, xc, yc, dataset, parent) { - var temp = new ToastTile(); - temp.parent = parent; - temp.level = level; - temp.tileX = xc; - temp.tileY = yc; - temp.dataset = dataset; - temp._topDown$1 = !dataset.get_bottomsUp(); - if (temp.tileX !== xc) { - alert('bad'); - } - if (!!dataset.get_meanRadius()) { - temp.set__demScaleFactor(dataset.get_meanRadius()); - } - else { - if (!dataset.get_dataSetType()) { - temp.set__demScaleFactor(6371000); - } - else { - temp.set__demScaleFactor(3396010); - } - } - temp.computeBoundingSphere(); - return temp; - }; - var ToastTile$ = { - computeBoundingSphere: function () { - this._initializeGrids$1(); - this.topLeft = this.bounds[0 + 3 * 0].position.copy(); - this.bottomRight = this.bounds[2 + 3 * 2].position.copy(); - this.topRight = this.bounds[2 + 3 * 0].position.copy(); - this.bottomLeft = this.bounds[0 + 3 * 2].position.copy(); - this.calcSphere(); - }, - getIndexBuffer: function (index, accomidation) { - if (!this.level) { - return ToastTile.rootIndexBuffer[index]; - } - if (this.backslash) { - return ToastTile.backSlashIndexBuffer[index * 16 + accomidation]; - } - else { - return ToastTile.slashIndexBuffer[index * 16 + accomidation]; - } - }, - _processIndexBuffer$1: function (indexArray, part) { - if (!this.level) { - ToastTile.rootIndexBuffer[part] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, ToastTile.rootIndexBuffer[part]); - Tile.prepDevice.bufferData(34963, indexArray, 35044); - return; - } - for (var a = 0; a < 16; a++) { - var partArray = ToastTile._cloneArray$1(indexArray); - this._processAccomindations$1(partArray, a); - if (this.backslash) { - ToastTile.backSlashIndexBuffer[part * 16 + a] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, ToastTile.backSlashIndexBuffer[part * 16 + a]); - Tile.prepDevice.bufferData(34963, partArray, 35044); - } - else { - ToastTile.slashIndexBuffer[part * 16 + a] = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34963, ToastTile.slashIndexBuffer[part * 16 + a]); - Tile.prepDevice.bufferData(34963, partArray, 35044); - } - } - }, - _processAccomindations$1: function (indexArray, a) { - var map = {}; - var gridMap = {}; - var $enum1 = ss.enumerate(indexArray); - while ($enum1.moveNext()) { - var index = $enum1.current; - var vert = this._vertexList$1[index]; - var arrayX = ss.truncate((vert.tu * 16 + 0.5)); - var arrayY = ss.truncate((vert.tv * 16 + 0.5)); - var ii = (arrayY << 8) + arrayX; - if (!ss.keyExists(gridMap, ii)) { - gridMap[ii] = index; - } - } - var sections = 16; - if ((a & 1) === 1) { - for (var x = 1; x < sections; x += 2) { - var y = sections; - var key = (y << 8) + x; - var val = (y << 8) + x + 1; - if (ss.keyExists(gridMap, key)) { - map[gridMap[key]] = gridMap[val]; - } - } - } - if ((a & 2) === 2) { - for (var y = 1; y < sections; y += 2) { - var x = sections; - var key = (y << 8) + x; - var val = ((y + 1) << 8) + x; - if (ss.keyExists(gridMap, key)) { - map[gridMap[key]] = gridMap[val]; - } - } - } - if ((a & 4) === 4) { - for (var x = 1; x < sections; x += 2) { - var y = 0; - var key = (y << 8) + x; - var val = (y << 8) + x + 1; - if (ss.keyExists(gridMap, key)) { - map[gridMap[key]] = gridMap[val]; - } - } - } - if ((a & 8) === 8) { - for (var y = 1; y < sections; y += 2) { - var x = 0; - var key = (y << 8) + x; - var val = ((y + 1) << 8) + x; - if (ss.keyExists(gridMap, key)) { - map[gridMap[key]] = gridMap[val]; - } - } - } - if (!ss.keyCount(map)) { - return; - } - for (var i = 0; i < indexArray.length; i++) { - if (ss.keyExists(map, indexArray[i])) { - indexArray[i] = map[indexArray[i]]; - } - } - }, - calculateFullSphere: function (list) { - var result = ConvexHull.findEnclosingSphere(list); - this.sphereCenter = result.center; - this.sphereRadius = result.radius; - }, - isPointInTile: function (lat, lng) { - if (!this.level) { - return true; - } - if (this.level === 1) { - if ((lng >= 0 && lng <= 90) && (!this.tileX && this.tileY === 1)) { - return true; - } - if ((lng > 90 && lng <= 180) && (this.tileX === 1 && this.tileY === 1)) { - return true; - } - if ((lng < 0 && lng >= -90) && (!this.tileX && !this.tileY)) { - return true; - } - if ((lng < -90 && lng >= -180) && (this.tileX === 1 && !this.tileY)) { - return true; - } - return false; - } - if (!this.demReady || this.demData == null) { - return false; - } - var testPoint = Coordinates.geoTo3dDouble(-lat, lng); - var top = this._isLeftOfHalfSpace$1(this.topLeft.copy(), this.topRight.copy(), testPoint); - var right = this._isLeftOfHalfSpace$1(this.topRight.copy(), this.bottomRight.copy(), testPoint); - var bottom = this._isLeftOfHalfSpace$1(this.bottomRight.copy(), this.bottomLeft.copy(), testPoint); - var left = this._isLeftOfHalfSpace$1(this.bottomLeft.copy(), this.topLeft.copy(), testPoint); - if (top && right && bottom && left) { - return true; - } - return false; - }, - _isLeftOfHalfSpace$1: function (pntA, pntB, pntTest) { - pntA.normalize(); - pntB.normalize(); - var cross = Vector3d.cross(pntA, pntB); - var dot = Vector3d.dot(cross, pntTest); - return dot < 0; - }, - getSurfacePointAltitude: function (lat, lng, meters) { - if (this.level < Tile.lastDeepestLevel) { - for (var ii = 0; ii < 4; ii++) { - var child = this.children[ii]; - if (child != null) { - if (child.isPointInTile(lat, lng)) { - var retVal = child.getSurfacePointAltitude(lat, lng, meters); - if (!!retVal) { - return retVal; - } - else { - break; - } - } - } - } - } - Tile.tileTargetLevel = this.level; - Tile.tileTargetX = this.tileX; - Tile.tileTargetY = this.tileY; - var testPoint = Coordinates.geoTo3dDouble(-lat, lng); - testPoint = Vector3d.subtractVectors(new Vector3d(), testPoint); - var uv = DistanceCalc.getUVFromInnerPoint(this.topLeft.copy(), this.topRight.copy(), this.bottomLeft.copy(), this.bottomRight.copy(), testPoint.copy()); - var uud = Math.max(0, Math.min(16, (uv.x * 16))); - var vvd = Math.max(0, Math.min(16, (uv.y * 16))); - var uu = Math.max(0, Math.min(15, ss.truncate((uv.x * 16)))); - var vv = Math.max(0, Math.min(15, ss.truncate((uv.y * 16)))); - var ha = uud - uu; - var va = vvd - vv; - if (this.demArray != null) { - var ul = this.demArray[uu + 17 * vv]; - var ur = this.demArray[(uu + 1) + 17 * vv]; - var ll = this.demArray[uu + 17 * (vv + 1)]; - var lr = this.demArray[(uu + 1) + 17 * (vv + 1)]; - var top = ul * (1 - ha) + ha * ur; - var bottom = ll * (1 - ha) + ha * lr; - var val = top * (1 - va) + va * bottom; - return val / this.get__demScaleFactor(); - } - return this.demAverage / this.get__demScaleFactor(); - }, - _initializeGrids$1: function () { - this._vertexList$1 = []; - this._childTriangleList$1 = new Array(4); - this._childTriangleList$1[0] = []; - this._childTriangleList$1[1] = []; - this._childTriangleList$1[2] = []; - this._childTriangleList$1[3] = []; - this.bounds = new Array(9); - if (this.level > 0) { - if (this.parent == null) { - this.parent = TileCache.getTile(this.level - 1, this.tileX / 2, this.tileY / 2, this.dataset, null); - } - var parent = this.parent; - var xIndex = this.tileX % 2; - var yIndex = this.tileY % 2; - if (this.level > 1) { - this.backslash = parent.backslash; - } - else { - this.backslash = (xIndex === 1 ^ yIndex === 1) === 1; - } - this.bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].copy(); - this.bounds[1 + 3 * 0] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); - this.bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].copy(); - this.bounds[0 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - if (this.backslash) { - this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - } - else { - this.bounds[1 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); - } - this.bounds[2 + 3 * 1] = this._midpoint$1(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - this.bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].copy(); - this.bounds[1 + 3 * 2] = this._midpoint$1(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); - this.bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].copy(); - this.bounds[0 + 3 * 0].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[1 + 3 * 0].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[2 + 3 * 0].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 0].tv = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 1].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 1].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[2 + 3 * 1].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 1].tv = 0.5 * Tile.uvMultiple; - this.bounds[0 + 3 * 2].tu = 0 * Tile.uvMultiple; - this.bounds[0 + 3 * 2].tv = 1 * Tile.uvMultiple; - this.bounds[1 + 3 * 2].tu = 0.5 * Tile.uvMultiple; - this.bounds[1 + 3 * 2].tv = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 2].tu = 1 * Tile.uvMultiple; - this.bounds[2 + 3 * 2].tv = 1 * Tile.uvMultiple; - this._vertexList$1.push(this.bounds[0 + 3 * 0]); - this._vertexList$1.push(this.bounds[1 + 3 * 0]); - this._vertexList$1.push(this.bounds[2 + 3 * 0]); - this._vertexList$1.push(this.bounds[0 + 3 * 1]); - this._vertexList$1.push(this.bounds[1 + 3 * 1]); - this._vertexList$1.push(this.bounds[2 + 3 * 1]); - this._vertexList$1.push(this.bounds[0 + 3 * 2]); - this._vertexList$1.push(this.bounds[1 + 3 * 2]); - this._vertexList$1.push(this.bounds[2 + 3 * 2]); - if (this.backslash) { - this._childTriangleList$1[0].push(Triangle.create(4, 1, 0)); - this._childTriangleList$1[0].push(Triangle.create(3, 4, 0)); - this._childTriangleList$1[1].push(Triangle.create(5, 2, 1)); - this._childTriangleList$1[1].push(Triangle.create(4, 5, 1)); - this._childTriangleList$1[2].push(Triangle.create(7, 4, 3)); - this._childTriangleList$1[2].push(Triangle.create(6, 7, 3)); - this._childTriangleList$1[3].push(Triangle.create(8, 5, 4)); - this._childTriangleList$1[3].push(Triangle.create(7, 8, 4)); - } - else { - this._childTriangleList$1[0].push(Triangle.create(3, 1, 0)); - this._childTriangleList$1[0].push(Triangle.create(4, 1, 3)); - this._childTriangleList$1[1].push(Triangle.create(4, 2, 1)); - this._childTriangleList$1[1].push(Triangle.create(5, 2, 4)); - this._childTriangleList$1[2].push(Triangle.create(6, 4, 3)); - this._childTriangleList$1[2].push(Triangle.create(7, 4, 6)); - this._childTriangleList$1[3].push(Triangle.create(7, 5, 4)); - this._childTriangleList$1[3].push(Triangle.create(8, 5, 7)); - } - } - else { - this.bounds[0 + 3 * 0] = PositionTexture.create(0, -1, 0, 0, 0); - this.bounds[1 + 3 * 0] = PositionTexture.create(0, 0, 1, 0.5, 0); - this.bounds[2 + 3 * 0] = PositionTexture.create(0, -1, 0, 1, 0); - this.bounds[0 + 3 * 1] = PositionTexture.create(-1, 0, 0, 0, 0.5); - this.bounds[1 + 3 * 1] = PositionTexture.create(0, 1, 0, 0.5, 0.5); - this.bounds[2 + 3 * 1] = PositionTexture.create(1, 0, 0, 1, 0.5); - this.bounds[0 + 3 * 2] = PositionTexture.create(0, -1, 0, 0, 1); - this.bounds[1 + 3 * 2] = PositionTexture.create(0, 0, -1, 0.5, 1); - this.bounds[2 + 3 * 2] = PositionTexture.create(0, -1, 0, 1, 1); - this._vertexList$1.push(this.bounds[0 + 3 * 0]); - this._vertexList$1.push(this.bounds[1 + 3 * 0]); - this._vertexList$1.push(this.bounds[2 + 3 * 0]); - this._vertexList$1.push(this.bounds[0 + 3 * 1]); - this._vertexList$1.push(this.bounds[1 + 3 * 1]); - this._vertexList$1.push(this.bounds[2 + 3 * 1]); - this._vertexList$1.push(this.bounds[0 + 3 * 2]); - this._vertexList$1.push(this.bounds[1 + 3 * 2]); - this._vertexList$1.push(this.bounds[2 + 3 * 2]); - this._childTriangleList$1[0].push(Triangle.create(3, 1, 0)); - this._childTriangleList$1[0].push(Triangle.create(4, 1, 3)); - this._childTriangleList$1[1].push(Triangle.create(5, 2, 1)); - this._childTriangleList$1[1].push(Triangle.create(4, 5, 1)); - this._childTriangleList$1[2].push(Triangle.create(7, 4, 3)); - this._childTriangleList$1[2].push(Triangle.create(6, 7, 3)); - this._childTriangleList$1[3].push(Triangle.create(7, 5, 4)); - this._childTriangleList$1[3].push(Triangle.create(8, 5, 7)); - } - }, - _midpoint$1: function (positionNormalTextured, positionNormalTextured_2) { - var a1 = Vector3d.lerp(positionNormalTextured.position, positionNormalTextured_2.position, 0.5); - var a1uv = Vector2d.lerp(Vector2d.create(positionNormalTextured.tu, positionNormalTextured.tv), Vector2d.create(positionNormalTextured_2.tu, positionNormalTextured_2.tv), 0.5); - a1.normalize(); - return PositionTexture.createPos(a1, a1uv.x, a1uv.y); - }, - createGeometry: function (renderContext) { - if (this.geometryCreated) { - return true; - } - this.geometryCreated = true; - Tile.prototype.createGeometry.call(this, renderContext); - if (!this._subDivided$1) { - if (this._vertexList$1 == null) { - this._initializeGrids$1(); - } - if (Tile.uvMultiple === 256) { - if (!this.dataset.get_dataSetType() || this.dataset.get_dataSetType() === 1) { - this._subDivisionLevel$1 = Math.min(5, Math.max(0, 5 - this.level)); - } - else { - this._subDivisionLevel$1 = Math.min(5, Math.max(0, 5 - this.level)); - } - } - else { - if (this.demTile && this.level > 1) { - this.demArray = new Array(17 * 17); - this.demSize = 17 * 17; - if (this.backslash) { - if (ToastTile._backslashYIndex$1 == null) { - this._tempBackslashYIndex$1 = new Array(this.demSize); - this._tempBackslashXIndex$1 = new Array(this.demSize); - } - } - else { - if (ToastTile._slashYIndex$1 == null) { - this._tempSlashYIndex$1 = new Array(this.demSize); - this._tempSlashXIndex$1 = new Array(this.demSize); - } - } - } - } - for (var i = 0; i < 4; i++) { - var count = this._subDivisionLevel$1; - while (count-- > 1) { - var newList = []; - var $enum1 = ss.enumerate(this._childTriangleList$1[i]); - while ($enum1.moveNext()) { - var tri = $enum1.current; - tri.subDivide(newList, this._vertexList$1); - } - this._childTriangleList$1[i] = newList; - } - } - if (renderContext.gl == null) { - for (var i = 0; i < 4; i++) { - this._renderTriangleLists[i] = []; - var $enum2 = ss.enumerate(this._childTriangleList$1[i]); - while ($enum2.moveNext()) { - var tri = $enum2.current; - var p1 = this._vertexList$1[tri.c]; - var p2 = this._vertexList$1[tri.b]; - var p3 = this._vertexList$1[tri.a]; - this._renderTriangleLists[i].push(RenderTriangle.create(p1, p2, p3, this.texture, this.level)); - } - } - } - else { - this._vertexBuffer = Tile.prepDevice.createBuffer(); - Tile.prepDevice.bindBuffer(34962, this._vertexBuffer); - var f32array = new Float32Array(this._vertexList$1.length * 5); - var buffer = f32array; - var index = 0; - var $enum3 = ss.enumerate(this._vertexList$1); - while ($enum3.moveNext()) { - var pt = $enum3.current; - if (this.demTile) { - index = this.addVertex(buffer, index, this._getMappedVertex(pt)); - this.demIndex++; - } - else { - index = this.addVertex(buffer, index, pt); - } - } - if (this.demTile) { - if (this.backslash) { - if (this._tempBackslashXIndex$1 != null) { - ToastTile._backslashXIndex$1 = this._tempBackslashXIndex$1; - ToastTile._backslashYIndex$1 = this._tempBackslashYIndex$1; - this._tempBackslashXIndex$1 = null; - this._tempBackslashYIndex$1 = null; - } - } - else { - if (this._tempSlashYIndex$1 != null) { - ToastTile._slashXIndex$1 = this._tempSlashXIndex$1; - ToastTile._slashYIndex$1 = this._tempSlashYIndex$1; - this._tempSlashYIndex$1 = null; - this._tempSlashXIndex$1 = null; - } - } - } - Tile.prepDevice.bufferData(34962, f32array, 35044); - for (var i = 0; i < 4; i++) { - this.triangleCount = this._childTriangleList$1[i].length; - if (this.getIndexBuffer(i, 0) == null) { - var ui16array = new Uint16Array(this.triangleCount * 3); - var indexArray = ui16array; - index = 0; - var $enum4 = ss.enumerate(this._childTriangleList$1[i]); - while ($enum4.moveNext()) { - var tri = $enum4.current; - indexArray[index++] = tri.c; - indexArray[index++] = tri.b; - indexArray[index++] = tri.a; - } - this._processIndexBuffer$1(indexArray, i); - } - } - } - this._subDivided$1 = true; - } - return true; - }, - _getMappedVertex: function (vert) { - var vertOut = new PositionTexture(); - var latLng = Coordinates.cartesianToSpherical2(vert.position); - if (latLng.get_lng() < -180) { - latLng.set_lng(latLng.get_lng() + 360); - } - if (latLng.get_lng() > 180) { - latLng.set_lng(latLng.get_lng() - 360); - } - if (this.level > 1) { - var arrayX = ss.truncate((vert.tu * 16 + 0.5)); - var arrayY = ss.truncate((vert.tv * 16 + 0.5)); - this.demArray[arrayX + arrayY * 17] = this.demData[this.demIndex]; - if (this.backslash) { - if (this._tempBackslashYIndex$1 != null) { - this._tempBackslashXIndex$1[this.demIndex] = arrayX; - this._tempBackslashYIndex$1[this.demIndex] = arrayY; - } - } - else { - if (this._tempSlashYIndex$1 != null) { - this._tempSlashXIndex$1[this.demIndex] = arrayX; - this._tempSlashYIndex$1[this.demIndex] = arrayY; - } - } - } - var pos = this.geoTo3dWithAlt(latLng.get_lat(), latLng.get_lng(), false, false); - vertOut.tu = vert.tu; - vertOut.tv = vert.tv; - pos.subtract(this.localCenter); - vertOut.position = pos; - return vertOut; - }, - cleanUp: function (removeFromParent) { - Tile.prototype.cleanUp.call(this, removeFromParent); - if (this._vertexList$1 != null) { - this._vertexList$1 = null; - } - if (this._childTriangleList$1 != null) { - this._childTriangleList$1 = null; - } - this._subDivided$1 = false; - this.demArray = null; - }, - _getDemSample$1: function (xc, yc) { - return this.demArray[(16 - yc) * 17 + xc]; - }, - createDemFromParent: function () { - var parent = ss.safeCast(this.parent, ToastTile); - if (parent == null) { - return false; - } - var offsetX = (((this.tileX % 2) === 1) ? 8 : 0); - var offsetY = ((!(this.tileY % 2)) ? 8 : 0); - this.demArray = new Array(17 * 17); - for (var yy1 = 0; yy1 < 17; yy1 += 2) { - var copy = true; - for (var xx1 = 0; xx1 < 17; xx1++) { - if (copy) { - this.demArray[(16 - yy1) * 17 + xx1] = parent._getDemSample$1((xx1 / 2) + offsetX, (yy1 / 2) + offsetY); - } - else { - this.demArray[(16 - yy1) * 17 + xx1] = ((parent._getDemSample$1((xx1 / 2) + offsetX, (yy1 / 2) + offsetY) + parent._getDemSample$1(((xx1 / 2) + offsetX) + 1, (yy1 / 2) + offsetY)) / 2); - } - copy = !copy; - } - } - for (var yy2 = 1; yy2 < 17; yy2 += 2) { - for (var xx2 = 0; xx2 < 17; xx2++) { - this.demArray[(16 - yy2) * 17 + xx2] = ((this._getDemSample$1(xx2, yy2 - 1) + this._getDemSample$1(xx2, yy2 + 1)) / 2); - } - } - this.demData = new Array(this.demSize); - for (var i = 0; i < this.demSize; i++) { - if (this.backslash) { - this.demData[i] = this.demArray[ToastTile._backslashXIndex$1[i] + ToastTile._backslashYIndex$1[i] * 17]; - } - else { - this.demData[i] = this.demArray[ToastTile._slashXIndex$1[i] + ToastTile._slashYIndex$1[i] * 17]; - } - this.demAverage += this.demData[i]; - } - this.demAverage /= this.demData.length; - this.demReady = true; - return true; - } - }; - - - // wwtlib.BitmapOverlay - - function BitmapOverlay() { - this._textureReady$1 = false; - this._sprite$1 = new Sprite2d(); - Overlay.call(this); - } - BitmapOverlay.create = function (owner, file) { - var temp = new BitmapOverlay(); - temp.set_owner(owner); - temp._filename$1 = file.name; - temp.set_name(owner.getNextDefaultName('Image')); - temp.set_x(0); - temp.set_y(0); - owner.get_owner().addCachedFile(file.name, file); - return temp; - }; - var BitmapOverlay$ = { - getTypeName: function () { - return 'TerraViewer.BitmapOverlay'; - }, - copy: function (owner) { - var newBmpOverlay = new BitmapOverlay(); - newBmpOverlay.set_owner(owner); - newBmpOverlay._filename$1 = this._filename$1; - newBmpOverlay.set_x(this.get_x()); - newBmpOverlay.set_y(this.get_y()); - newBmpOverlay.set_width(this.get_width()); - newBmpOverlay.set_height(this.get_height()); - newBmpOverlay.set_color(this.get_color()); - newBmpOverlay.set_opacity(this.get_opacity()); - newBmpOverlay.set_rotationAngle(this.get_rotationAngle()); - newBmpOverlay.set_name(this.get_name() + ' - Copy'); - return newBmpOverlay; - }, - cleanUp: function () { - this.texture = null; - if (this.texture2d != null) { - this.texture2d.cleanUp(); - this.texture2d = null; - } - }, - initializeTexture: function () { - var $this = this; - - try { - if (RenderContext.useGl) { - this.texture2d = this.get_owner().get_owner().getCachedTexture2d(this._filename$1); - this._textureReady$1 = true; - } - else { - this.texture = this.get_owner().get_owner().getCachedTexture(this._filename$1, function () { - $this._textureReady$1 = true; - }); - } - } - catch ($e1) { - } - }, - draw3D: function (renderContext, designTime) { - if (RenderContext.useGl) { - if (this.texture2d == null) { - this.initializeTexture(); - } - if (!this.get_width() && !this.get_height()) { - this.set_width(this.texture2d.imageElement.width); - this.set_height(this.texture2d.imageElement.height); - } - this.initializeGeometry(); - this.updateRotation(); - this._sprite$1.draw(renderContext, this.points, this.points.length, this.texture2d, true, 1); - } - else { - if (this.texture == null) { - this.initializeTexture(); - } - if (!this._textureReady$1) { - return; - } - if (!this.get_width() && !this.get_height()) { - this.set_width(this.texture.width); - this.set_height(this.texture.height); - } - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.globalAlpha = this.get_opacity(); - ctx.drawImage(this.texture, -this.get_width() / 2, -this.get_height() / 2, this.get_width(), this.get_height()); - ctx.restore(); - } - }, - addFilesToCabinet: function (fc) { - fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); - }, - writeOverlayProperties: function (xmlWriter) { - xmlWriter._writeStartElement('Bitmap'); - xmlWriter._writeAttributeString('Filename', this._filename$1); - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - var bitmap = Util.selectSingleNode(node, 'Bitmap'); - this._filename$1 = bitmap.attributes.getNamedItem('Filename').nodeValue; - } - }; - - - // wwtlib.TextOverlay - - function TextOverlay() { - this._sprite$1 = new Sprite2d(); - this._ctx$1 = null; - this._ce$1 = null; - Overlay.call(this); - } - TextOverlay.create = function (textObject) { - var to = new TextOverlay(); - to.textObject = textObject; - to._calculateTextSize$1(); - return to; - }; - var TextOverlay$ = { - getTypeName: function () { - return 'TerraViewer.TextOverlay'; - }, - get_color: function () { - return Overlay.prototype.get_color.call(this); - }, - set_color: function (value) { - if (this.textObject.foregroundColor !== value) { - this.textObject.foregroundColor = value; - Overlay.prototype.set_color.call(this, value); - this.cleanUp(); - } - return value; - }, - draw3D: function (renderContext, designTime) { - if (RenderContext.useGl) { - this.initializeTexture(); - this.initializeGeometry(); - this.updateRotation(); - this._sprite$1.draw(renderContext, this.points, this.points.length, this.texture2d, true, 1); - } - else { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.globalAlpha = this.get_opacity(); - this._drawCanvasText$1(ctx); - ctx.restore(); - } - }, - _drawCanvasText$1: function (ctx) { - ctx.fillStyle = this.textObject.foregroundColor.toString(); - ctx.font = ((this.textObject.italic) ? 'italic' : 'normal') + ' ' + ((this.textObject.bold) ? 'bold' : 'normal') + ' ' + Math.round(this.textObject.fontSize * 1.2).toString() + 'px ' + this.textObject.fontName; - ctx.textBaseline = 'top'; - var text = this.textObject.text; - if (text.indexOf('{$') > -1) { - if (text.indexOf('{$DATE}') > -1) { - var date = ss.format('{0:yyyy/MM/dd}', SpaceTimeController.get_now()); - text = ss.replaceString(text, '{$DATE}', date); - } - if (text.indexOf('{$TIME}') > -1) { - var time = ss.format('{0:HH:mm:ss}', SpaceTimeController.get_now()); - text = ss.replaceString(text, '{$TIME}', time); - } - text = ss.replaceString(text, '{$DIST}', UiTools.formatDistance(WWTControl.singleton.renderContext.get_solarSystemCameraDistance())); - text = ss.replaceString(text, '{$LAT}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.lat)); - text = ss.replaceString(text, '{$LNG}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.lat)); - text = ss.replaceString(text, '{$RA}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.get_RA())); - text = ss.replaceString(text, '{$DEC}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.get_dec())); - text = ss.replaceString(text, '{$FOV}', Coordinates.formatDMS(WWTControl.singleton.renderContext.get_fovAngle())); - } - var lines = text.split('\n'); - var baseline = -(this.get_height() / 2); - var lineSpace = this.textObject.fontSize * 1.7; - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var line = $enum1.current; - var parts = Util.getWrappedText(ctx, line, this.get_width()); - var $enum2 = ss.enumerate(parts); - while ($enum2.moveNext()) { - var part = $enum2.current; - ctx.fillText(part, -this.get_width() / 2, baseline); - baseline += lineSpace; - } - } - }, - _calculateTextSize$1: function () { - if (this._ctx$1 == null || this._ce$1 == null) { - this._ce$1 = document.createElement('canvas'); - this._ce$1.height = 100; - this._ce$1.width = 100; - this._ctx$1 = this._ce$1.getContext('2d'); - } - this._ctx$1.fillStyle = this.textObject.foregroundColor.toString(); - this._ctx$1.font = ((this.textObject.italic) ? 'italic' : 'normal') + ' ' + ((this.textObject.bold) ? 'bold' : 'normal') + ' ' + Math.round(this.textObject.fontSize * 1.2).toString() + 'px ' + this.textObject.fontName; - this._ctx$1.textBaseline = 'top'; - var text = this.textObject.text; - if (text.indexOf('{$') > -1) { - if (text.indexOf('{$DATE}') > -1) { - var date = ss.format('{0:yyyy/MM/dd}', SpaceTimeController.get_now()); - text = ss.replaceString(text, '{$DATE}', date); - } - if (text.indexOf('{$TIME}') > -1) { - var time = ss.format('{0:HH:mm:ss}', SpaceTimeController.get_now()); - text = ss.replaceString(text, '{$TIME}', time); - } - text = ss.replaceString(text, '{$DIST}', UiTools.formatDistance(WWTControl.singleton.renderContext.get_solarSystemCameraDistance())); - text = ss.replaceString(text, '{$LAT}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.lat)); - text = ss.replaceString(text, '{$LNG}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.lat)); - text = ss.replaceString(text, '{$RA}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.get_RA())); - text = ss.replaceString(text, '{$DEC}', Coordinates.formatDMS(WWTControl.singleton.renderContext.viewCamera.get_dec())); - text = ss.replaceString(text, '{$FOV}', Coordinates.formatDMS(WWTControl.singleton.renderContext.get_fovAngle())); - } - var lines = text.split('\n'); - var baseline = 0; - var lineSpace = this.textObject.fontSize * 1.7; - var maxWidth = 0; - var $enum1 = ss.enumerate(lines); - while ($enum1.moveNext()) { - var line = $enum1.current; - var width = this._ctx$1.measureText(line).width; - maxWidth = Math.max(width, maxWidth); - baseline += lineSpace; - } - this.set_width(maxWidth * 1.01); - this.set_height(baseline); - this._ce$1 = null; - this._ctx$1 = null; - }, - initializeTexture: function () { - if (this.texture2d == null || (this.textObject.text.indexOf('{$') > -1)) { - if (!this.get_height() || !this.get_width()) { - this._calculateTextSize$1(); - } - if (this._ctx$1 == null || this._ce$1 == null) { - this._ce$1 = document.createElement('canvas'); - this._ce$1.height = ss.truncate(this.get_height()); - this._ce$1.width = ss.truncate(this.get_width()); - this._ctx$1 = this._ce$1.getContext('2d'); - } - this._ctx$1.translate(this.get_width() / 2, this.get_height() / 2); - this._ctx$1.clearRect(0, 0, this.get_width(), this.get_height()); - this._drawCanvasText$1(this._ctx$1); - this.texture2d = new Texture(); - this.texture2d.imageElement = this._ce$1; - this.texture2d.makeTexture(); - this._ce$1 = null; - this._ctx$1 = null; - } - }, - writeOverlayProperties: function (xmlWriter) { - xmlWriter._writeStartElement('Text'); - this.textObject._saveToXml(xmlWriter); - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - var text = Util.selectSingleNode(node, 'Text'); - this.textObject = TextObject._fromXml(Util.selectSingleNode(text, 'TextObject')); - }, - initializeGeometry: function () { - if (RenderContext.useGl) { - Overlay.prototype.initializeGeometry.call(this); - } - } - }; - - - // wwtlib.ShapeOverlay - - function ShapeOverlay() { - this._shapeType$1 = 1; - this._sprite$1 = new Sprite2d(); - this._triangleStrip$1 = true; - Overlay.call(this); - } - ShapeOverlay._create = function (currentTourStop, shapeType) { - var overlay = new ShapeOverlay(); - overlay._shapeType$1 = shapeType; - overlay.set_owner(currentTourStop); - return overlay; - }; - var ShapeOverlay$ = { - getTypeName: function () { - return 'TerraViewer.ShapeOverlay'; - }, - get_shapeType: function () { - return this._shapeType$1; - }, - set_shapeType: function (value) { - this._shapeType$1 = value; - this.cleanUpGeometry(); - return value; - }, - draw3D: function (renderContext, designTime) { - if (RenderContext.useGl) { - this.initializeGeometry(); - this._sprite$1.draw(renderContext, this.points, this.points.length, null, this._triangleStrip$1, this.get_opacity()); - } - else { - switch (this._shapeType$1) { - case 0: - this._drawCircleGeometry$1(renderContext); - break; - case 1: - this._drawRectGeometry$1(renderContext); - break; - case 6: - this._drawOpenRectGeometry$1(renderContext); - break; - case 2: - this._drawStarGeometry$1(renderContext); - break; - case 3: - this._drawDonutGeometry$1(renderContext); - break; - case 4: - this._drawArrowGeometry$1(renderContext); - break; - case 5: - this._drawLineGeometry$1(renderContext); - break; - default: - break; - } - } - }, - initializeGeometry: function () { - if (this.points == null) { - switch (this._shapeType$1) { - case 0: - this._createCircleGeometry$1(); - break; - case 1: - Overlay.prototype.initializeGeometry.call(this); - break; - case 6: - this._createOpenRectGeometry$1(); - break; - case 2: - this._createStarGeometry$1(); - break; - case 3: - this._createDonutGeometry$1(); - break; - case 4: - this._createArrowGeometry$1(); - break; - case 5: - this._createLineGeometry$1(); - break; - default: - break; - } - } - }, - _createLineGeometry$1: function () { - var centerX = this.get_x(); - var centerY = this.get_y(); - var radius = this.get_width() / 2; - var length = this.get_width(); - var segments = ss.truncate((length / 12)) + 1; - var radiansPerSegment = (Math.PI * 2) / segments; - if (this.points == null) { - this.points = new Array(segments * 2 + 2); - } - for (var j = 0; j <= segments; j++) { - var i = j * 2; - this.points[i] = new PositionColoredTextured(); - this.points[i].position = this.makePosition(this.get_x(), this.get_y(), ((j / segments) * this.get_width() - (this.get_width() / 2)), 6, this.get_rotationAngle()); - this.points[i].tu = (j % 2); - this.points[i].tv = 0; - this.points[i].color = this.get_color(); - this.points[i + 1] = new PositionColoredTextured(); - this.points[i + 1].position = this.makePosition(this.get_x(), this.get_y(), ((j / segments) * this.get_width() - (this.get_width() / 2)), -6, this.get_rotationAngle()); - this.points[i + 1].tu = (j % 2); - this.points[i + 1].tv = 1; - this.points[i + 1].color = this.get_color(); - } - }, - _createOpenRectGeometry$1: function () { - var centerX = this.get_x(); - var centerY = this.get_y(); - var radius = this.get_width() / 2; - var length = this.get_width(); - var segments = ss.truncate((length / 12)) + 1; - var segmentsHigh = ss.truncate((this.get_height() / 12)) + 1; - var totalPoints = (((segments + 1) * 2) + ((segmentsHigh + 1) * 2)) * 2; - if (this.points == null) { - this.points = new Array(totalPoints); - } - for (var j = 0; j <= segments; j++) { - var i = j * 2; - this.points[i] = new PositionColoredTextured(); - this.points[i].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (this.get_height() / 2), this.get_rotationAngle()); - this.points[i].tu = (j % 2); - this.points[i].tv = 0; - this.points[i].color = this.get_color(); - this.points[i + 1] = new PositionColoredTextured(); - this.points[i + 1].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), ((this.get_height() / 2) - 12), this.get_rotationAngle()); - this.points[i + 1].tu = (j % 2); - this.points[i + 1].tv = 1; - this.points[i + 1].color = this.get_color(); - var k = (((segments + 1) * 4) + ((segmentsHigh + 1) * 2) - 2) - i; - this.points[k] = new PositionColoredTextured(); - this.points[k].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (-(this.get_height() / 2)) + 12, this.get_rotationAngle()); - this.points[k].tu = (j % 2); - this.points[k].tv = 0; - this.points[k].color = this.get_color(); - this.points[k + 1] = new PositionColoredTextured(); - this.points[k + 1].position = this.makePosition(centerX, centerY, (j / segments) * this.get_width() - (this.get_width() / 2), (-(this.get_height() / 2)), this.get_rotationAngle()); - this.points[k + 1].tu = (j % 2); - this.points[k + 1].tv = 1; - this.points[k + 1].color = this.get_color(); - } - var offset = ((segments + 1) * 2); - for (var j = 0; j <= segmentsHigh; j++) { - var top = ((segmentsHigh + 1) * 2) + offset - 2; - var i = j * 2; - this.points[top - i] = new PositionColoredTextured(); - this.points[top - i].position = this.makePosition(centerX, centerY, (this.get_width() / 2), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); - this.points[top - i].tu = (j % 2); - this.points[top - i].tv = 0; - this.points[top - i].color = this.get_color(); - this.points[top - i + 1] = new PositionColoredTextured(); - this.points[top - i + 1].position = this.makePosition(centerX, centerY, ((this.get_width() / 2) - 12), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); - this.points[top - i + 1].tu = (j % 2); - this.points[top - i + 1].tv = 1; - this.points[top - i + 1].color = this.get_color(); - var k = i + ((segments + 1) * 4) + ((segmentsHigh + 1) * 2); - this.points[k] = new PositionColoredTextured(); - this.points[k].position = this.makePosition(centerX, centerY, (-(this.get_width() / 2) + 12), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); - this.points[k].tu = (j % 2); - this.points[k].tv = 0; - this.points[k].color = this.get_color(); - this.points[k + 1] = new PositionColoredTextured(); - this.points[k + 1].position = this.makePosition(centerX, centerY, (-(this.get_width() / 2)), ((j / segmentsHigh) * this.get_height() - (this.get_height() / 2)), this.get_rotationAngle()); - this.points[k + 1].tu = (j % 2); - this.points[k + 1].tv = 1; - this.points[k + 1].color = this.get_color(); - } - }, - _createStarGeometry$1: function () { - var centerX = this.get_x(); - var centerY = this.get_y(); - var radius = this.get_width() / 2; - var radiansPerSegment = (Math.PI * 2) / 5; - if (this.points == null) { - this.points = new Array(12); - } - if (this._pnts$1 == null) { - this._pnts$1 = new Array(10); - } - for (var i = 0; i < 5; i++) { - var rads = i * radiansPerSegment - (Math.PI / 2); - this._pnts$1[i] = new PositionColoredTextured(); - this._pnts$1[i].position = this.makePosition(centerX, centerY, (Math.cos(rads) * (this.get_width() / 2)), (Math.sin(rads) * (this.get_height() / 2)), this.get_rotationAngle()); - this._pnts$1[i].tu = 0; - this._pnts$1[i].tv = 0; - this._pnts$1[i].color = this.get_color(); - } - for (var i = 5; i < 10; i++) { - var rads = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); - this._pnts$1[i] = new PositionColoredTextured(); - this._pnts$1[i].position = this.makePosition(centerX, centerY, (Math.cos(rads) * (this.get_width() / 5.3)), (Math.sin(rads) * (this.get_height() / 5.3)), this.get_rotationAngle()); - this._pnts$1[i].tu = 0; - this._pnts$1[i].tv = 0; - this._pnts$1[i].color = this.get_color(); - } - this.points[0] = this._pnts$1[0]; - this.points[1] = this._pnts$1[5]; - this.points[2] = this._pnts$1[9]; - this.points[3] = this._pnts$1[1]; - this.points[4] = this._pnts$1[7]; - this.points[5] = this._pnts$1[4]; - this.points[6] = this._pnts$1[6]; - this.points[7] = this._pnts$1[2]; - this.points[8] = this._pnts$1[7]; - this.points[9] = this._pnts$1[7]; - this.points[10] = this._pnts$1[3]; - this.points[11] = this._pnts$1[8]; - this._triangleStrip$1 = false; - }, - _createArrowGeometry$1: function () { - if (this.points == null) { - this.points = new Array(9); - } - this.points[0] = new PositionColoredTextured(); - this.points[0].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, -this.get_height() / 4, this.get_rotationAngle()); - this.points[0].tu = 0; - this.points[0].tv = 0; - this.points[0].color = this.get_color(); - this.points[1] = new PositionColoredTextured(); - this.points[1].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 4, this.get_rotationAngle()); - this.points[1].tu = 1; - this.points[1].tv = 0; - this.points[1].color = this.get_color(); - this.points[2] = new PositionColoredTextured(); - this.points[2].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 4, this.get_rotationAngle()); - this.points[2].tu = 0; - this.points[2].tv = 1; - this.points[2].color = this.get_color(); - this.points[3] = new PositionColoredTextured(); - this.points[3].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 4, this.get_rotationAngle()); - this.points[3].tu = 1; - this.points[3].tv = 0; - this.points[3].color = this.get_color(); - this.points[4] = new PositionColoredTextured(); - this.points[4].position = this.makePosition(this.get_x(), this.get_y(), -this.get_width() / 2, this.get_height() / 4, this.get_rotationAngle()); - this.points[4].tu = 0; - this.points[4].tv = 1; - this.points[4].color = this.get_color(); - this.points[5] = new PositionColoredTextured(); - this.points[5].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, this.get_height() / 4, this.get_rotationAngle()); - this.points[5].tu = 1; - this.points[5].tv = 1; - this.points[5].color = this.get_color(); - this.points[6] = new PositionColoredTextured(); - this.points[6].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, -this.get_height() / 2, this.get_rotationAngle()); - this.points[6].tu = 1; - this.points[6].tv = 1; - this.points[6].color = this.get_color(); - this.points[7] = new PositionColoredTextured(); - this.points[7].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 2, 0, this.get_rotationAngle()); - this.points[7].tu = 1; - this.points[7].tv = 0.5; - this.points[7].color = this.get_color(); - this.points[8] = new PositionColoredTextured(); - this.points[8].position = this.makePosition(this.get_x(), this.get_y(), this.get_width() / 4, this.get_height() / 2, this.get_rotationAngle()); - this.points[8].tu = 1; - this.points[8].tv = 1; - this.points[8].color = this.get_color(); - this._triangleStrip$1 = false; - }, - _createDonutGeometry$1: function () { - var centerX = this.get_x(); - var centerY = this.get_y(); - var radius = this.get_width() / 2; - var circumference = Math.PI * 2 * radius; - var segments = ss.truncate((circumference / 12)) + 1; - var radiansPerSegment = (Math.PI * 2) / segments; - if (this.points == null) { - this.points = new Array(segments * 2 + 2); - } - for (var j = 0; j <= segments; j++) { - var i = j * 2; - this.points[i] = new PositionColoredTextured(); - this.points[i].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * (this.get_width() / 2)), (Math.sin(j * radiansPerSegment) * (this.get_height() / 2)), this.get_rotationAngle()); - this.points[i].tu = (j % 2); - this.points[i].tv = 0; - this.points[i].color = this.get_color(); - this.points[i + 1] = new PositionColoredTextured(); - this.points[i + 1].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * ((this.get_width() / 2) - 10)), (Math.sin(j * radiansPerSegment) * ((this.get_height() / 2) - 10)), this.get_rotationAngle()); - this.points[i + 1].tu = (j % 2); - this.points[i + 1].tv = 1; - this.points[i + 1].color = this.get_color(); - } - }, - _createCircleGeometry$1: function () { - var centerX = this.get_x(); - var centerY = this.get_y(); - var radius = this.get_width() / 2; - var circumference = Math.PI * 2 * radius; - var segments = ss.truncate((circumference / 12)) + 1; - var radiansPerSegment = (Math.PI * 2) / segments; - if (this.points == null) { - this.points = new Array(segments * 2 + 2); - } - for (var j = 0; j <= segments; j++) { - var i = j * 2; - this.points[i] = new PositionColoredTextured(); - this.points[i].position = this.makePosition(centerX, centerY, (Math.cos(j * radiansPerSegment) * (this.get_width() / 2)), (Math.sin(j * radiansPerSegment) * (this.get_height() / 2)), this.get_rotationAngle()); - this.points[i].tu = (j % 2); - this.points[i].tv = 0; - this.points[i].color = this.get_color(); - this.points[i + 1] = new PositionColoredTextured(); - this.points[i + 1].position = this.makePosition(centerX, centerY, 0, 0, this.get_rotationAngle()); - this.points[i + 1].tu = (j % 2); - this.points[i + 1].tv = 1; - this.points[i + 1].color = this.get_color(); - } - }, - initializeTexture: function () { - switch (this.get_shapeType()) { - case 5: - case 3: - case 6: - break; - case 0: - case 1: - case 2: - case 4: - default: - this.texture = null; - break; - } - }, - _drawLineGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - var radius = this.get_width() / 2; - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.moveTo(-radius, 0); - ctx.lineTo(radius, 0); - ctx.lineWidth = 9; - ctx.strokeStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.stroke(); - ctx.restore(); - }, - _drawOpenRectGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - ctx.moveTo(-this.get_width() / 2, -this.get_height() / 2); - ctx.lineTo(this.get_width() / 2, -this.get_height() / 2); - ctx.lineTo(this.get_width() / 2, this.get_height() / 2); - ctx.lineTo(-this.get_width() / 2, this.get_height() / 2); - ctx.closePath(); - ctx.lineWidth = 9; - ctx.strokeStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.stroke(); - ctx.restore(); - }, - _drawRectGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - ctx.moveTo(-this.get_width() / 2, -this.get_height() / 2); - ctx.lineTo(this.get_width() / 2, -this.get_height() / 2); - ctx.lineTo(this.get_width() / 2, this.get_height() / 2); - ctx.lineTo(-this.get_width() / 2, this.get_height() / 2); - ctx.closePath(); - ctx.lineWidth = 0; - ctx.fillStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.fill(); - ctx.restore(); - }, - _drawStarGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - var centerX = 0; - var centerY = 0; - var radius = this.get_width() / 2; - var radiansPerSegment = (Math.PI * 2) / 5; - var first = true; - for (var i = 0; i < 5; i++) { - var rads = i * radiansPerSegment - (Math.PI / 2); - if (first) { - first = false; - ctx.moveTo(centerX + Math.cos(rads) * (this.get_width() / 2), centerY + Math.sin(rads) * (this.get_height() / 2)); - } - else { - ctx.lineTo(centerX + Math.cos(rads) * (this.get_width() / 2), centerY + Math.sin(rads) * (this.get_height() / 2)); - } - var rads2 = i * radiansPerSegment + (radiansPerSegment / 2) - (Math.PI / 2); - ctx.lineTo(centerX + Math.cos(rads2) * (this.get_width() / 5.3), centerY + Math.sin(rads2) * (this.get_height() / 5.3)); - } - ctx.closePath(); - ctx.lineWidth = 0; - ctx.fillStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.fill(); - ctx.restore(); - }, - _drawArrowGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - ctx.moveTo((-(this.get_width() / 2)), (-(this.get_height() / 4))); - ctx.lineTo((this.get_width() / 4), (-(this.get_height() / 4))); - ctx.lineTo((this.get_width() / 4), (-(this.get_height() / 2))); - ctx.lineTo((this.get_width() / 2), 0); - ctx.lineTo((this.get_width() / 4), (this.get_height() / 2)); - ctx.lineTo((this.get_width() / 4), (this.get_height() / 4)); - ctx.lineTo((-(this.get_width() / 2)), (this.get_height() / 4)); - ctx.closePath(); - ctx.lineWidth = 0; - ctx.fillStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.fill(); - ctx.restore(); - }, - _drawDonutGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.translate(this.get_x(), this.get_y()); - ctx.scale(1, this.get_height() / this.get_width()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - ctx.arc(0, 0, this.get_width() / 2, 0, Math.PI * 2, false); - ctx.closePath(); - ctx.lineWidth = 9; - ctx.strokeStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.stroke(); - ctx.restore(); - }, - _drawCircleGeometry$1: function (renderContext) { - var ctx = renderContext.device; - ctx.save(); - ctx.scale(1, this.get_width() / this.get_height()); - ctx.translate(this.get_x(), this.get_y()); - ctx.rotate(this.get_rotationAngle() * Overlay.RC); - ctx.beginPath(); - ctx.arc(0, 0, this.get_width(), 0, Math.PI * 2, false); - ctx.closePath(); - ctx.lineWidth = 0; - ctx.fillStyle = this.get_color().toString(); - ctx.globalAlpha = this.get_opacity(); - ctx.fill(); - ctx.restore(); - }, - cleanUpGeometry: function () { - Overlay.prototype.cleanUpGeometry.call(this); - this.cleanUp(); - }, - writeOverlayProperties: function (xmlWriter) { - xmlWriter._writeStartElement('Shape'); - xmlWriter._writeAttributeString('ShapeType', Enums.toXml('ShapeType', this._shapeType$1)); - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - var shape = Util.selectSingleNode(node, 'Shape'); - this._shapeType$1 = Enums.parse('ShapeType', shape.attributes.getNamedItem('ShapeType').nodeValue); - } - }; - - - // wwtlib.AudioOverlay - - function AudioOverlay() { - this._audio$1 = null; - this._audioReady$1 = false; - this._wantPlaying$1 = false; - this._volume$1 = 100; - this._mute$1 = false; - this._position$1 = 0; - this._trackType$1 = 0; - Overlay.call(this); - this.isDesignTimeOnly = true; - } - AudioOverlay.create = function (currentTourStop, file) { - var ao = new AudioOverlay(); - ao.set_owner(currentTourStop); - ao._filename$1 = file.name; - ao.get_owner().get_owner().addCachedFile(file.name, file); - return ao; - }; - var AudioOverlay$ = { - getTypeName: function () { - return 'TerraViewer.AudioOverlay'; - }, - get_mute: function () { - return this._mute$1; - }, - set_mute: function (value) { - this._mute$1 = value; - this.set_volume(this.get_volume()); - return value; - }, - get_volume: function () { - return this._volume$1; - }, - set_volume: function (value) { - this._volume$1 = value; - if (this._audio$1 != null) { - this._audio$1.volume = (this._mute$1) ? 0 : (this._volume$1 / 100); - } - return value; - }, - addFilesToCabinet: function (fc) { - fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); - }, - play: function () { - if (this._audio$1 == null) { - this.prepMultimedia(); - } - this._wantPlaying$1 = true; - if (this._audio$1 != null && this._audioReady$1) { - this._audio$1.play(); - this.set_volume(this.get_volume()); - this._audio$1.currentTime = this._position$1; - } - }, - pause: function () { - if (this._audio$1 == null) { - this.prepMultimedia(); - } - this._wantPlaying$1 = false; - if (this._audio$1 != null && this._audioReady$1) { - this._audio$1.pause(); - } - }, - stop: function () { - this.pause(); - }, - seek: function (time) { - this._position$1 = time; - if (this._audio$1 == null) { - this.prepMultimedia(); - } - if (this._audioReady$1) { - if (this._audio$1.duration < time) { - this._audio$1.pause(); - } - else { - this._audio$1.currentTime = this._position$1; - } - } - }, - prepMultimedia: function () { - var $this = this; - - if (this._audio$1 != null) { - return; - } - this._audio$1 = document.createElement('audio'); - this._audio$1.addEventListener('canplaythrough', function () { - if (!$this._audioReady$1) { - $this._audioReady$1 = true; - if ($this._wantPlaying$1) { - $this.play(); - } - } - }, false); - var source = document.createElement('source'); - this._audio$1.appendChild(source); - source.src = this.get_owner().get_owner().getFileStream(this._filename$1); - source.type = 'audio/mp3'; - this._audio$1.load(); - }, - initializeTexture: function () { - this.prepMultimedia(); - }, - cleanUp: function () { - Overlay.prototype.cleanUp.call(this); - this._wantPlaying$1 = false; - if (this._audio$1 != null) { - this._audio$1.pause(); - this._audio$1.src = null; - this._audio$1 = null; - } - }, - get_trackType: function () { - return this._trackType$1; - }, - set_trackType: function (value) { - this._trackType$1 = value; - return value; - }, - writeOverlayProperties: function (xmlWriter) { - xmlWriter._writeStartElement('Audio'); - xmlWriter._writeAttributeString('Filename', this._filename$1); - xmlWriter._writeAttributeString('Volume', this._volume$1.toString()); - xmlWriter._writeAttributeString('Mute', this._mute$1.toString()); - xmlWriter._writeAttributeString('TrackType', Enums.toXml('AudioType', this._trackType$1)); - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - var audio = Util.selectSingleNode(node, 'Audio'); - this._filename$1 = audio.attributes.getNamedItem('Filename').nodeValue; - if (audio.attributes.getNamedItem('Volume') != null) { - this._volume$1 = parseInt(audio.attributes.getNamedItem('Volume').nodeValue); - } - if (audio.attributes.getNamedItem('Mute') != null) { - this._mute$1 = ss.boolean(audio.attributes.getNamedItem('Mute').nodeValue); - } - if (audio.attributes.getNamedItem('TrackType') != null) { - this._trackType$1 = Enums.parse('AudioType', audio.attributes.getNamedItem('TrackType').nodeValue); - } - } - }; - - - // wwtlib.FlipbookOverlay - - function FlipbookOverlay() { - this._loopType$1 = 1; - this._startFrame$1 = 0; - this._framesList$1 = []; - this._frames$1 = 1; - this._framesX$1 = 8; - this._framesY$1 = 8; - this._textureReady$1 = false; - this._currentFrame$1 = 0; - this._cellHeight$1 = 256; - this._cellWidth$1 = 256; - this._timeStart$1 = ss.now(); - this._playing$1 = true; - Overlay.call(this); - } - var FlipbookOverlay$ = { - getTypeName: function () { - return 'TerraViewer.FlipbookOverlay'; - }, - get_loopType: function () { - return this._loopType$1; - }, - set_loopType: function (value) { - this._loopType$1 = value; - return value; - }, - get_startFrame: function () { - return this._startFrame$1; - }, - set_startFrame: function (value) { - this._startFrame$1 = value; - return value; - }, - get_frameSequence: function () { - return this._frameSequence$1; - }, - set_frameSequence: function (value) { - if (this._frameSequence$1 !== value) { - this._frameSequence$1 = value; - this._framesList$1 = []; - if (!ss.emptyString(this._frameSequence$1)) { - try { - var parts = this._frameSequence$1.split(','); - var $enum1 = ss.enumerate(parts); - while ($enum1.moveNext()) { - var part = $enum1.current; - var x = parseInt(ss.trim(part)); - this._framesList$1.push(x); - } - } - catch ($e2) { - } - } - } - return value; - }, - get_frames: function () { - return this._frames$1; - }, - set_frames: function (value) { - this._frames$1 = value; - return value; - }, - get_framesX: function () { - return this._framesX$1; - }, - set_framesX: function (value) { - this._framesX$1 = value; - return value; - }, - get_framesY: function () { - return this._framesY$1; - }, - set_framesY: function (value) { - this._framesY$1 = value; - return value; - }, - copy: function (owner) { - var newFlipbookOverlay = new FlipbookOverlay(); - newFlipbookOverlay.set_owner(owner); - newFlipbookOverlay._filename$1 = this._filename$1; - newFlipbookOverlay.set_x(this.get_x()); - newFlipbookOverlay.set_y(this.get_y()); - newFlipbookOverlay.set_width(this.get_width()); - newFlipbookOverlay.set_height(this.get_height()); - newFlipbookOverlay.set_color(this.get_color()); - newFlipbookOverlay.set_opacity(this.get_opacity()); - newFlipbookOverlay.set_rotationAngle(this.get_rotationAngle()); - newFlipbookOverlay.set_name(this.get_name() + ' - Copy'); - newFlipbookOverlay.set_startFrame(this.get_startFrame()); - newFlipbookOverlay.set_frames(this.get_frames()); - newFlipbookOverlay.set_loopType(this.get_loopType()); - newFlipbookOverlay.set_frameSequence(this.get_frameSequence()); - newFlipbookOverlay.set_framesX(this.get_framesX()); - newFlipbookOverlay.set_framesY(this.get_framesY()); - return newFlipbookOverlay; - }, - cleanUp: function () { - this.texture = null; - }, - initializeTexture: function () { - var $this = this; - - try { - var colorKey = ss.endsWith(this._filename$1.toLowerCase(), '.jpg'); - this.texture = this.get_owner().get_owner().getCachedTexture(this._filename$1, function () { - $this._textureReady$1 = true; - }); - } - catch ($e1) { - } - }, - addFilesToCabinet: function (fc) { - fc.addFile(this.get_owner().get_owner().get_workingDirectory() + this._filename$1, this.get_owner().get_owner().getFileBlob(this._filename$1)); - }, - writeOverlayProperties: function (xmlWriter) { - xmlWriter._writeStartElement('Flipbook'); - xmlWriter._writeAttributeString('Filename', this._filename$1); - xmlWriter._writeAttributeString('Frames', this._frames$1.toString()); - xmlWriter._writeAttributeString('Loop', Enums.toXml('LoopTypes', this._loopType$1)); - xmlWriter._writeAttributeString('FramesX', this._framesX$1.toString()); - xmlWriter._writeAttributeString('FramesY', this._framesY$1.toString()); - xmlWriter._writeAttributeString('StartFrame', this._startFrame$1.toString()); - if (!ss.emptyString(this._frameSequence$1)) { - xmlWriter._writeAttributeString('FrameSequence', this._frameSequence$1); - } - xmlWriter._writeEndElement(); - }, - initializeFromXml: function (node) { - var flipbook = Util.selectSingleNode(node, 'Flipbook'); - this._filename$1 = flipbook.attributes.getNamedItem('Filename').nodeValue; - this._frames$1 = parseInt(flipbook.attributes.getNamedItem('Frames').nodeValue); - this._loopType$1 = Enums.parse('LoopTypes', flipbook.attributes.getNamedItem('Loop').nodeValue); - if (flipbook.attributes.getNamedItem('FramesX') != null) { - this.set_framesX(parseInt(flipbook.attributes.getNamedItem('FramesX').nodeValue)); - } - if (flipbook.attributes.getNamedItem('FramesY') != null) { - this.set_framesY(parseInt(flipbook.attributes.getNamedItem('FramesY').nodeValue)); - } - if (flipbook.attributes.getNamedItem('StartFrame') != null) { - this.set_startFrame(parseInt(flipbook.attributes.getNamedItem('StartFrame').nodeValue)); - } - if (flipbook.attributes.getNamedItem('FrameSequence') != null) { - this.set_frameSequence(flipbook.attributes.getNamedItem('FrameSequence').nodeValue); - } - }, - play: function () { - this._playing$1 = true; - this._timeStart$1 = ss.now(); - }, - pause: function () { - this._playing$1 = false; - }, - stop: function () { - this._playing$1 = false; - this._currentFrame$1 = 0; - }, - initializeGeometry: function () { - var frameCount = this._frames$1; - if (!ss.emptyString(this._frameSequence$1)) { - frameCount = this._framesList$1.length; - } - if (this._playing$1) { - var ts = ss.now() - this._timeStart$1; - switch (this._loopType$1) { - case 0: - this._currentFrame$1 = ss.truncate(((ts / 1000 * 24) % frameCount)) + this._startFrame$1; - break; - case 1: - this._currentFrame$1 = Math.abs(ss.truncate(((ts / 1000 * 24 + frameCount) % (frameCount * 2 - 1))) - (frameCount - 1)) + this._startFrame$1; - if (this._currentFrame$1 < 0 || this._currentFrame$1 > frameCount - 1) { - var p = 0; - } - break; - case 2: - this._currentFrame$1 = Math.max(0, frameCount - ss.truncate(((ts / 1000 * 24) % frameCount))) + this._startFrame$1; - break; - case 3: - var temp = Math.min(ts / 1000 * 24, frameCount * 2 + 1) + frameCount; - this._currentFrame$1 = Math.abs((temp % (frameCount * 2 - 1)) - (frameCount - 1)) + this._startFrame$1; - break; - case 4: - this._currentFrame$1 = Math.min(frameCount - 1, ss.truncate((ts / 1000 * 24))); - break; - case 5: - this._currentFrame$1 = this._startFrame$1; - break; - case 6: - this._currentFrame$1 = (frameCount - 1) + this._startFrame$1; - break; - default: - this._currentFrame$1 = this._startFrame$1; - break; - } - } - if (!ss.emptyString(this._frameSequence$1)) { - if (this._currentFrame$1 < this._framesList$1.length && this._currentFrame$1 > -1) { - this._currentFrame$1 = this._framesList$1[this._currentFrame$1]; - } - else { - this._currentFrame$1 = 0; - } - } - this.currentRotation = 0; - } - }; - - - // wwtlib.ToolStripSeparator - - function ToolStripSeparator() { - ToolStripMenuItem.call(this); - this.name = '--------------------------------------'; - } - var ToolStripSeparator$ = { - - }; - - - // wwtlib.FrameWizard - - function FrameWizard() { - Dialog.call(this); - } - var FrameWizard$ = { - OK: function (frame) { - LayerManager.referenceFrameWizardFinished(frame); - } - }; - - - // wwtlib.ReferenceFrameProps - - function ReferenceFrameProps() { - Dialog.call(this); - } - var ReferenceFrameProps$ = { - OK: function (frame) { - LayerManager.loadTree(); - } - }; - - - // wwtlib.GreatCircleDialog - - function GreatCircleDialog() { - Dialog.call(this); - } - var GreatCircleDialog$ = { - OK: function (frame) { - } - }; - - - // wwtlib.DataVizWizard - - function DataVizWizard() { - Dialog.call(this); - } - var DataVizWizard$ = { - OK: function () { - } - }; - - - // wwtlib.FitsImageTile - - function FitsImageTile(dataset, file, callMeBack) { - FitsImage.call(this, dataset, file, null, callMeBack); - } - var FitsImageTile$ = { - readDataUnitFloat64: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getFloat64(this.position, false); - i++; - this.position += 8; - } - }, - readDataUnitFloat32: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getFloat32(this.position, false); - i++; - this.position += 4; - } - }, - readDataUnitUint8: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getUint8(this.position); - i++; - this.position += 1; - } - }, - readDataUnitInt16: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getInt16(this.position, false); - i++; - this.position += 2; - } - }, - readDataUnitInt32: function (dataView) { - var i = 0; - while (this.position < dataView.byteLength) { - this.dataUnit[i] = dataView.getInt32(this.position, false); - i++; - this.position += 4; - } - }, - computeWcs: function () { - } - }; - - - // wwtlib.FitsImageJs - - function FitsImageJs(dataset, file, blob, callMeBack) { - this.dataType = 5; - this._color$2 = false; - this.isTiledFits = false; - FitsImage.call(this, dataset, file, blob, callMeBack); - } - FitsImageJs.createTiledFits = function (dataset, file, callMeBack) { - var fits = new FitsImageJs(dataset, file, null, callMeBack); - fits.isTiledFits = true; - return fits; - }; - var FitsImageJs$ = { - readFromBin: function (dataView) { - FitsImage.prototype.readFromBin.call(this, dataView); - if (this.numAxis === 3) { - if (this.axisSize[2] === 3) { - this._color$2 = true; - } - } - }, - readDataUnit: function (dataView, bitpix) { - var br = new BinaryReader(new Uint8Array(dataView.buffer)); - br.position = this.position; - switch (bitpix) { - case -64: - this.dataType = 4; - this._readDataUnitFloat64$2(br); - break; - case -32: - this.dataType = 3; - this._readDataUnitFloat32$2(br); - break; - case 8: - this.dataType = 0; - this._readDataUnitUint8$2(br); - break; - case 16: - this.dataType = 1; - this._readDataUnitInt16$2(br); - break; - case 32: - this.dataType = 2; - this._readDataUnitInt32$2(br); - break; - } - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - }, - _readDataUnitUint8$2: function (br) { - var buffer = new Array(this.bufferSize); - this._dataBuffer$2 = buffer; - for (var i = 0; i < this.bufferSize; i++) { - buffer[i] = br.readByte(); - if (this.fitsProperties.minVal > buffer[i]) { - this.fitsProperties.minVal = buffer[i]; - } - if (this.fitsProperties.maxVal < buffer[i]) { - this.fitsProperties.maxVal = buffer[i]; - } - } - }, - _readDataUnitInt16$2: function (br) { - var buffer = new Array(this.bufferSize); - this._dataBuffer$2 = buffer; - for (var i = 0; i < this.bufferSize; i++) { - buffer[i] = ((br.readSByte() * 256) + br.readByte()); - if (this.fitsProperties.minVal > buffer[i]) { - this.fitsProperties.minVal = buffer[i]; - } - if (this.fitsProperties.maxVal < buffer[i]) { - this.fitsProperties.maxVal = buffer[i]; - } - } - }, - _readDataUnitInt32$2: function (br) { - var buffer = new Array(this.bufferSize); - this._dataBuffer$2 = buffer; - for (var i = 0; i < this.bufferSize; i++) { - buffer[i] = (br.readSByte() << 24) + (br.readSByte() << 16) + (br.readSByte() << 8) + br.readByte(); - if (this.fitsProperties.minVal > buffer[i]) { - this.fitsProperties.minVal = buffer[i]; - } - if (this.fitsProperties.maxVal < buffer[i]) { - this.fitsProperties.maxVal = buffer[i]; - } - } - }, - _readDataUnitFloat32$2: function (br) { - var buffer = new Array(this.bufferSize); - this._dataBuffer$2 = buffer; - var part = new Uint8Array(4); - for (var i = 0; i < this.bufferSize; i++) { - part[3] = br.readByte(); - part[2] = br.readByte(); - part[1] = br.readByte(); - part[0] = br.readByte(); - buffer[i] = new Float32Array(part.buffer, 0, 1)[0]; - if (this.fitsProperties.minVal > buffer[i]) { - this.fitsProperties.minVal = buffer[i]; - } - if (this.fitsProperties.maxVal < buffer[i]) { - this.fitsProperties.maxVal = buffer[i]; - } - } - }, - _readDataUnitFloat64$2: function (br) { - var buffer = new Array(this.bufferSize); - var part = new Uint8Array(8); - this._dataBuffer$2 = buffer; - for (var i = 0; i < this.bufferSize; i++) { - part[7] = br.readByte(); - part[6] = br.readByte(); - part[5] = br.readByte(); - part[4] = br.readByte(); - part[3] = br.readByte(); - part[2] = br.readByte(); - part[1] = br.readByte(); - part[0] = br.readByte(); - buffer[i] = new Float64Array(part.buffer, 0, 1)[0]; - if (this.fitsProperties.minVal > buffer[i]) { - this.fitsProperties.minVal = buffer[i]; - } - if (this.fitsProperties.maxVal < buffer[i]) { - this.fitsProperties.maxVal = buffer[i]; - } - } - }, - getBitmap: function () { - if (!this.fitsProperties.upperCut && !this.fitsProperties.lowerCut) { - this.fitsProperties.lowerCut = this.fitsProperties.minVal; - this.fitsProperties.upperCut = this.fitsProperties.maxVal; - } - return this.getScaledBitmap(this.fitsProperties.lowerCut, this.fitsProperties.upperCut, this.fitsProperties.scaleType, 0, this.fitsProperties.colorMapName); - }, - getScaledBitmap: function (min, max, scaleType, z, colorMapperName) { - var scale; - this.fitsProperties.scaleType = scaleType; - this.fitsProperties.lowerCut = min; - this.fitsProperties.upperCut = max; - this.fitsProperties.colorMapName = colorMapperName; - var colorMapper = ColorMapContainer.fromNamedColormap(colorMapperName); - switch (scaleType) { - case 0: - default: - scale = new ScaleLinear(min, max); - break; - case 1: - scale = new ScaleLog(min, max); - break; - case 2: - scale = new ScalePow(min, max); - break; - case 3: - scale = new ScaleSqrt(min, max); - break; - case 4: - scale = new HistogramEqualization(this, min, max); - break; - } - try { - switch (this.dataType) { - case 0: - return this._getBitmapByte$2(min, max, scale, 0, colorMapper); - case 1: - return this.getBitmapShort(min, max, scale, 0, colorMapper); - case 2: - return this._getBitmapInt$2(min, max, scale, 0, colorMapper); - case 3: - return this._getBitmapFloat$2(min, max, scale, 0, colorMapper); - case 4: - return this._getBitmapDouble$2(min, max, scale, 0, colorMapper); - case 5: - default: - return Bitmap.create(100, 100); - } - } - catch ($e1) { - return Bitmap.create(10, 10); - } - }, - _setPixelWithColorMap$2: function (bmp, x, y, val, colorMapper) { - if (colorMapper == null) { - bmp.setPixel(x, y, val, val, val, (this.fitsProperties.transparentBlack && !val) ? 0 : 255); - return; - } - var pixel_value = val / 255; - if (pixel_value !== pixel_value) { - bmp.setPixel(x, y, 0, 0, 0, 0); - return; - } - var pixel_color = colorMapper.findClosestColor(pixel_value); - bmp.setPixel(x, y, ss.truncate(pixel_color.r), ss.truncate(pixel_color.g), ss.truncate(pixel_color.b), (this.fitsProperties.transparentBlack && !val) ? 0 : 255); - }, - _getBitmapByte$2: function (min, max, scale, z, colorMapper) { - var buf = this._dataBuffer$2; - var factor = max - min; - var stride = this.axisSize[0]; - var page = this.axisSize[0] * this.axisSize[1] * z; - var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); - for (var y = 0; y < this.axisSize[1]; y++) { - var indexY = ((this.axisSize[1] - 1) - y); - for (var x = 0; x < this.axisSize[0]; x++) { - if (this._color$2) { - var datR = buf[(x + indexY * stride)]; - var datG = buf[(x + indexY * stride) + page]; - var datB = buf[(x + indexY * stride) + page * 2]; - if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var r = scale.map(datR); - var g = scale.map(datG); - var b = scale.map(datB); - bmp.setPixel(x, y, r, g, b, 255); - } - } - else { - var dataValue = buf[x + indexY * stride + page]; - if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var val = scale.map(dataValue); - this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - }, - _getBitmapDouble$2: function (min, max, scale, z, colorMapper) { - var buf = this._dataBuffer$2; - var factor = max - min; - var stride = this.axisSize[0]; - var page = this.axisSize[0] * this.axisSize[1] * z; - var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); - for (var y = 0; y < this.axisSize[1]; y++) { - var indexY = ((this.axisSize[1] - 1) - y); - for (var x = 0; x < this.axisSize[0]; x++) { - if (this._color$2) { - var datR = buf[(x + indexY * stride)]; - var datG = buf[(x + indexY * stride) + page]; - var datB = buf[(x + indexY * stride) + page * 2]; - if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var r = scale.map(datR); - var g = scale.map(datG); - var b = scale.map(datB); - bmp.setPixel(x, y, r, g, b, 255); - } - } - else { - var dataValue = buf[x + indexY * stride + page]; - if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var val = scale.map(dataValue); - this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - }, - _getBitmapFloat$2: function (min, max, scale, z, colorMapper) { - var buf = this._dataBuffer$2; - var factor = max - min; - var stride = this.axisSize[0]; - var page = this.axisSize[0] * this.axisSize[1] * z; - var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); - for (var y = 0; y < this.axisSize[1]; y++) { - var indexY = ((this.axisSize[1] - 1) - y); - for (var x = 0; x < this.axisSize[0]; x++) { - if (this._color$2) { - var datR = buf[(x + indexY * stride)]; - var datG = buf[(x + indexY * stride) + page]; - var datB = buf[(x + indexY * stride) + page * 2]; - if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var r = scale.map(datR); - var g = scale.map(datG); - var b = scale.map(datB); - bmp.setPixel(x, y, r, g, b, 255); - } - } - else { - var dataValue = buf[x + indexY * stride + page]; - if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var val = scale.map(dataValue); - this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - }, - _getBitmapInt$2: function (min, max, scale, z, colorMapper) { - var buf = this._dataBuffer$2; - var factor = max - min; - var stride = this.axisSize[0]; - var page = this.axisSize[0] * this.axisSize[1] * z; - var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); - for (var y = 0; y < this.axisSize[1]; y++) { - var indexY = ((this.axisSize[1] - 1) - y); - for (var x = 0; x < this.axisSize[0]; x++) { - if (this._color$2) { - var datR = buf[(x + indexY * stride)]; - var datG = buf[(x + indexY * stride) + page]; - var datB = buf[(x + indexY * stride) + page * 2]; - if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var r = scale.map(datR); - var g = scale.map(datG); - var b = scale.map(datB); - bmp.setPixel(x, y, r, g, b, 255); - } - } - else { - var dataValue = buf[x + indexY * stride + page]; - if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var val = scale.map(dataValue); - this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - }, - getBitmapShort: function (min, max, scale, z, colorMapper) { - var buf = this._dataBuffer$2; - var factor = max - min; - var stride = this.axisSize[0]; - var page = this.axisSize[0] * this.axisSize[1] * z; - var bmp = Bitmap.create(this.axisSize[0], this.axisSize[1]); - for (var y = 0; y < this.axisSize[1]; y++) { - var indexY = ((this.axisSize[1] - 1) - y); - for (var x = 0; x < this.axisSize[0]; x++) { - if (this._color$2) { - var datR = buf[(x + indexY * stride)]; - var datG = buf[(x + indexY * stride) + page]; - var datB = buf[(x + indexY * stride) + page * 2]; - if (this.fitsProperties.containsBlanks && datR === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var r = scale.map(datR); - var g = scale.map(datG); - var b = scale.map(datB); - bmp.setPixel(x, y, r, g, b, 255); - } - } - else { - var dataValue = buf[x + indexY * stride + page]; - if (this.fitsProperties.containsBlanks && dataValue === this.fitsProperties.blankValue) { - bmp.setPixel(x, y, 0, 0, 0, 0); - } - else { - var val = scale.map(dataValue); - this._setPixelWithColorMap$2(bmp, x, y, val, colorMapper); - } - } - } - } - return bmp; - }, - computeWcs: function () { - if (!this.isTiledFits) { - FitsImage.prototype.computeWcs.call(this); - } - }, - populateHistogram: function (histogram) { - switch (this.dataType) { - case 0: - this._populateHistogramByte$2(histogram); - break; - case 1: - this._populateHistogramInt16$2(histogram); - break; - case 2: - this._populateHistogramInt32$2(histogram); - break; - case 3: - this._populateHistogramFloat$2(histogram); - break; - case 4: - this._populateHistogramDouble$2(histogram); - break; - } - }, - _populateHistogramDouble$2: function (histogram) { - var buckets = histogram.length; - var buf = this._dataBuffer$2; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - var $enum1 = ss.enumerate(buf); - while ($enum1.moveNext()) { - var val = $enum1.current; - if (!(val === Number.NaN)) { - histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; - } - } - }, - _populateHistogramFloat$2: function (histogram) { - var buckets = histogram.length; - var buf = this._dataBuffer$2; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - var $enum1 = ss.enumerate(buf); - while ($enum1.moveNext()) { - var val = $enum1.current; - if (!(val === FitsImage.naN)) { - histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; - } - } - }, - _populateHistogramInt32$2: function (histogram) { - var buckets = histogram.length; - var buf = this._dataBuffer$2; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - var $enum1 = ss.enumerate(buf); - while ($enum1.moveNext()) { - var val = $enum1.current; - histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; - } - }, - _populateHistogramInt16$2: function (histogram) { - var buckets = histogram.length; - var buf = this._dataBuffer$2; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - var $enum1 = ss.enumerate(buf); - while ($enum1.moveNext()) { - var val = $enum1.current; - histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; - } - }, - _populateHistogramByte$2: function (histogram) { - var buckets = histogram.length; - var buf = this._dataBuffer$2; - var factor = (this.fitsProperties.maxVal - this.fitsProperties.minVal) / buckets; - var $enum1 = ss.enumerate(buf); - while ($enum1.moveNext()) { - var val = $enum1.current; - histogram[Math.min(buckets - 1, ss.truncate(((val - this.fitsProperties.minVal) / factor)))]++; - } - } - }; - - - // wwtlib.ISSLayer - - function ISSLayer() { - Object3dLayer.call(this); - this.id = ISSLayer.issGuid; - } - ISSLayer.loadBackground = function () { - if (ISSLayer._loading$2 || WWTControl.singleton.freestandingMode) { - return; - } - ISSLayer._loading$2 = true; - var url = URLHelpers.singleton.coreStaticUrl('data/iss.wtt'); - ISSLayer._doc$2 = TourDocument.fromUrlRaw(url, function () { - ISSLayer.createSpaceStation(); - }); - }; - ISSLayer.createSpaceStation = function () { - ISSLayer._doc$2.set_id('28016047-97a9-4b33-a226-cd820262a151'); - var filename = '0c10ae54-b6da-4282-bfda-f34562d403bc.3ds'; - var o3d = new Object3d(ISSLayer._doc$2, filename, true, false, true, Colors.get_white()); - if (o3d != null) { - o3d.issLayer = true; - ISSLayer._issmodel$2 = o3d; - } - }; - var ISSLayer$ = { - draw: function (renderContext, opacity, flat) { - if (this.object3d == null && ISSLayer._issmodel$2 == null) { - if (!ISSLayer._loading$2) { - var worldView = Matrix3d.multiplyMatrix(renderContext.get_world(), renderContext.get_view()); - var v = worldView.transform(Vector3d.get_empty()); - var scaleFactor = Math.sqrt(worldView.get_m11() * worldView.get_m11() + worldView.get_m22() * worldView.get_m22() + worldView.get_m33() * worldView.get_m33()); - var dist = v.length(); - var radius = scaleFactor; - var viewportHeight = ss.truncate(renderContext.height); - var p11 = renderContext.get_projection().get_m11(); - var p34 = renderContext.get_projection().get_m34(); - var p44 = renderContext.get_projection().get_m44(); - var w = Math.abs(p34) * dist + p44; - var pixelsPerUnit = (p11 / w) * viewportHeight; - var radiusInPixels = (radius * pixelsPerUnit); - if (radiusInPixels > 0.5) { - ISSLayer.loadBackground(); - } - } - } - this.object3d = ISSLayer._issmodel$2; - return Object3dLayer.prototype.draw.call(this, renderContext, opacity, flat); - }, - getPrimaryUI: function () { - return null; - }, - addFilesToCabinet: function (fc) { - return; - }, - loadData: function (doc, filename) { - return; - }, - cleanUp: function () { - } - }; - - - // wwtlib.CatalogSpreadSheetLayer - - function CatalogSpreadSheetLayer() { - this._addedTiles$2 = {}; - SpreadSheetLayer.call(this); - } - var CatalogSpreadSheetLayer$ = { - addTileRows: function (tileKey, catalogRows) { - if (!ss.keyExists(this._addedTiles$2, tileKey)) { - var $enum1 = ss.enumerate(catalogRows); - while ($enum1.moveNext()) { - var row = $enum1.current; - this.get__table().rows.push(row); - } - this.dirty = true; - this._addedTiles$2[tileKey] = true; - } - }, - removeTileRows: function (tileKey, catalogRows) { - if (ss.keyExists(this._addedTiles$2, tileKey)) { - var $enum1 = ss.enumerate(catalogRows); - while ($enum1.moveNext()) { - var row = $enum1.current; - ss.remove(this.get__table().rows, row); - } - this.dirty = true; - delete this._addedTiles$2[tileKey]; - } - }, - cleanUp: function () { - SpreadSheetLayer.prototype.cleanUp.call(this); - ss.clearKeys(this._addedTiles$2); - this.get__table().rows.length = 0; - } - }; - - - // wwtlib.SlideChangedEventArgs - - function SlideChangedEventArgs(caption) { - ss.EventArgs.call(this); - this.set_caption(caption); - } - var SlideChangedEventArgs$ = { - get_caption: function () { - return this._caption$2; - }, - set_caption: function (value) { - this._caption$2 = value; - return value; - } - }; - - - // wwtlib.ArrivedEventArgs - - function ArrivedEventArgs(ra, dec, zoom) { - this._ra$2 = 0; - this._dec$2 = 0; - this._zoom$2 = 0; - ss.EventArgs.call(this); - this.set_RA(ra * 15); - this.set_dec(dec); - this.set_zoom(zoom / 6); - } - var ArrivedEventArgs$ = { - get_RA: function () { - return this._ra$2; - }, - set_RA: function (value) { - this._ra$2 = value; - return value; - }, - get_dec: function () { - return this._dec$2; - }, - set_dec: function (value) { - this._dec$2 = value; - return value; - }, - get_zoom: function () { - return this._zoom$2; - }, - set_zoom: function (value) { - this._zoom$2 = value; - return value; - } - }; - - - // wwtlib.AnnotationClickEventArgs - - function AnnotationClickEventArgs(ra, dec, id) { - this._ra$2 = 0; - this._dec$2 = 0; - ss.EventArgs.call(this); - this.set_RA(ra * 15); - this.set_dec(dec); - this.set_id(id); - } - var AnnotationClickEventArgs$ = { - get_RA: function () { - return this._ra$2; - }, - set_RA: function (value) { - this._ra$2 = value; - return value; - }, - get_dec: function () { - return this._dec$2; - }, - set_dec: function (value) { - this._dec$2 = value; - return value; - }, - get_id: function () { - return this._id$2; - }, - set_id: function (value) { - this._id$2 = value; - return value; - } - }; - - - // wwtlib.CollectionLoadedEventArgs - - function CollectionLoadedEventArgs(url) { - ss.EventArgs.call(this); - this._url$2 = url; - } - var CollectionLoadedEventArgs$ = { - get_url: function () { - return this._url$2; - }, - set_url: function (value) { - this._url$2 = value; - return value; - } - }; - - - // wwtlib.SkyImageTile - - function SkyImageTile(level, x, y, dataset, parent) { - this.pixelCenterX = 0; - this.pixelCenterY = 0; - this.scaleX = 0.01; - this.scaleY = 0.01; - this.height = 0; - this.width = 0; - TangentTile.call(this, level, x, y, dataset, parent); - this.pixelCenterX = dataset.get_offsetX(); - this.pixelCenterY = dataset.get_offsetY(); - this.scaleX = -(this.scaleY = dataset.get_baseTileDegrees()); - if (dataset.get_bottomsUp()) { - this.scaleX = -this.scaleX; - } - this.sphereCenter = this.geoTo3dTan(0, 0); - this.radius = 1.25; - this.computeBoundingSphere(); - } - var SkyImageTile$ = { - getLatLngEdges: function () { - var edges = new LatLngEdges(); - var wcsImage = ss.safeCast(this.dataset.get_wcsImage(), WcsImage); - if (wcsImage != null && RenderContext.useGl) { - if (RenderContext.useGlVersion2) { - this.width = wcsImage.get_sizeX(); - this.height = wcsImage.get_sizeY(); - } - else { - this.height = this.bmp.height; - this.width = this.bmp.width; - if (this.bmp.height !== wcsImage.get_sizeY()) { - this.pixelCenterY += this.bmp.height - wcsImage.get_sizeY(); - } - } - } - else if (this.texture != null) { - this.height = this.texture.naturalHeight; - this.width = this.texture.naturalWidth; - } - else { - this.height = 256; - this.width = 256; - } - edges.latMin = 0 + (this.scaleY * (this.height - this.pixelCenterY)); - edges.latMax = 0 - (this.scaleY * this.pixelCenterY); - edges.lngMin = 0 + (this.scaleX * this.pixelCenterX); - edges.lngMax = 0 - (this.scaleX * (this.width - this.pixelCenterX)); - return edges; - } - }; - - - var $exports = ss.module('wwtlib', - { - IFolder: [IFolder], - Sprite2d: [Sprite2d, Sprite2d$, null], - ViewMoverSlew: [ViewMoverSlew, ViewMoverSlew$, null, IViewMover], - VertexPosition: [VertexPosition, VertexPosition$, null], - MainView: [MainView, null, null], - MinorPlanets: [MinorPlanets, MinorPlanets$, null], - TileCache: [TileCache, TileCache$, null], - DistanceCalc: [DistanceCalc, DistanceCalc$, null], - Triangle: [Triangle, Triangle$, null], - PositionTextureVertexBuffer: [PositionTextureVertexBuffer, PositionTextureVertexBuffer$, VertexBufferBase], - KeplerVertexBuffer: [KeplerVertexBuffer, KeplerVertexBuffer$, VertexBufferBase], - TimeSeriesLineVertexBuffer: [TimeSeriesLineVertexBuffer, TimeSeriesLineVertexBuffer$, VertexBufferBase], - TimeSeriesPointVertexBuffer: [TimeSeriesPointVertexBuffer, TimeSeriesPointVertexBuffer$, VertexBufferBase], - PositionColoredVertexBuffer: [PositionColoredVertexBuffer, PositionColoredVertexBuffer$, VertexBufferBase], - PositionColoredTexturedVertexBuffer: [PositionColoredTexturedVertexBuffer, PositionColoredTexturedVertexBuffer$, VertexBufferBase], - LayerCollection: [LayerCollection, LayerCollection$, Layer] - }, - { - DAY_OF_WEEK: DAY_OF_WEEK, - EO: EO, - ScaleTypes: ScaleTypes, - URLRewriteMode: URLRewriteMode, - SolarSystemObjects: SolarSystemObjects, - InterpolationType: InterpolationType, - PointType: PointType, - LocationHint: LocationHint, - FolderGroup: FolderGroup, - FolderRefreshType: FolderRefreshType, - FolderType: FolderType, - ThumbnailSize: ThumbnailSize, - CullMode: CullMode, - PointScaleTypes: PointScaleTypes, - ProjectionType: ProjectionType, - ImageSetType: ImageSetType, - BandPass: BandPass, - Classification: Classification, - DataTypes: DataTypes, - AltUnits: AltUnits, - FadeType: FadeType, - ReferenceFrames: ReferenceFrames, - ReferenceFrameTypes: ReferenceFrameTypes, - CoordinatesTypes: CoordinatesTypes, - AltTypes: AltTypes, - MarkerMixes: MarkerMixes, - ColorMaps: ColorMaps, - PlotTypes: PlotTypes, - MarkerScales: MarkerScales, - RAUnits: RAUnits, - Primitives: Primitives, - Alignment: Alignment, - StockSkyOverlayTypes: StockSkyOverlayTypes, - OverlayAnchor: OverlayAnchor, - AudioType: AudioType, - ShapeType: ShapeType, - LoopTypes: LoopTypes, - SelectionAnchor: SelectionAnchor, - TextBorderStyle: TextBorderStyle, - UserLevel: UserLevel, - TransitionType: TransitionType, - Keys: Keys, - DialogResult: DialogResult, - Formatting: Formatting, - StateType: StateType, - IThumbnail: [IThumbnail], - IPlace: [IPlace], - IUiController: [IUiController], - IViewMover: [IViewMover], - IUIServicesCallbacks: [IUIServicesCallbacks], - ISettings: [ISettings], - IUndoStep: [IUndoStep], - Imports: [Imports, null, null], - GFX: [GFX, null, null], - ABR: [ABR, ABR$, null], - ACFT: [ACFT, ACFT$, null], - ASEP: [ASEP, ASEP$, null], - COR: [COR, COR$, null], - C3D: [C3D, C3D$, null], - CT: [CT, CT$, null], - CalD: [CalD, CalD$, null], - DT: [DT, DT$, null], - DYT: [DYT, DYT$, null], - CAAEarth: [CAAEarth, CAAEarth$, null], - VSC: [VSC, VSC$, null], - CAAEclipticalElementDetails: [CAAEclipticalElementDetails, CAAEclipticalElementDetails$, null], - CAAEclipticalElements: [CAAEclipticalElements, CAAEclipticalElements$, null], - EPO: [EPO, EPO$, null], - EOE: [EOE, EOE$, null], - EPD: [EPD, EPD$, null], - EOD: [EOD, EOD$, null], - ELL: [ELL, ELL$, null], - EOT: [EOT, EOT$, null], - CAAFK5: [CAAFK5, CAAFK5$, null], - GMD: [GMD, GMD$, null], - GMDS: [GMDS, GMDS$, null], - GM: [GM, GM$, null], - CAAGlobe: [CAAGlobe, CAAGlobe$, null], - IFR: [IFR, IFR$, null], - INTP: [INTP, INTP$, null], - CAAJupiter: [CAAJupiter, CAAJupiter$, null], - CAAKepler: [CAAKepler, CAAKepler$, null], - CAAMars: [CAAMars, CAAMars$, null], - CAAMercury: [CAAMercury, CAAMercury$, null], - CAAMoon: [CAAMoon, CAAMoon$, null], - MoonCoefficient1: [MoonCoefficient1, MoonCoefficient1$, null], - MoonCoefficient2: [MoonCoefficient2, MoonCoefficient2$, null], - MIFR: [MIFR, MIFR$, null], - CAAMoonNodes: [CAAMoonNodes, CAAMoonNodes$, null], - CAAMoonPerigeeApogee: [CAAMoonPerigeeApogee, CAAMoonPerigeeApogee$, null], - MPAC: [MPAC, MPAC$, null], - CAAMoonPhases: [CAAMoonPhases, CAAMoonPhases$, null], - CAANeptune: [CAANeptune, CAANeptune$, null], - CAANutation: [CAANutation, CAANutation$, null], - NUC: [NUC, NUC$, null], - CAATopocentricEclipticDetails: [CAATopocentricEclipticDetails, CAATopocentricEclipticDetails$, null], - CAAParallax: [CAAParallax, CAAParallax$, null], - CAAPhysicalJupiterDetails: [CAAPhysicalJupiterDetails, CAAPhysicalJupiterDetails$, null], - CAAPhysicalJupiter: [CAAPhysicalJupiter, CAAPhysicalJupiter$, null], - CAAPhysicalMarsDetails: [CAAPhysicalMarsDetails, CAAPhysicalMarsDetails$, null], - CAAPhysicalMars: [CAAPhysicalMars, CAAPhysicalMars$, null], - CAAPhysicalSunDetails: [CAAPhysicalSunDetails, CAAPhysicalSunDetails$, null], - CAAPhysicalSun: [CAAPhysicalSun, CAAPhysicalSun$, null], - CAAPluto: [CAAPluto, CAAPluto$, null], - PlutoCoefficient1: [PlutoCoefficient1, PlutoCoefficient1$, null], - PlutoCoefficient2: [PlutoCoefficient2, PlutoCoefficient2$, null], - CAAPrecession: [CAAPrecession, CAAPrecession$, null], - CAARiseTransitSetDetails: [CAARiseTransitSetDetails, CAARiseTransitSetDetails$, null], - CAARiseTransitSet: [CAARiseTransitSet, CAARiseTransitSet$, null], - CAASaturn: [CAASaturn, CAASaturn$, null], - CAASaturnRingDetails: [CAASaturnRingDetails, CAASaturnRingDetails$, null], - CAASaturnRings: [CAASaturnRings, CAASaturnRings$, null], - CAASidereal: [CAASidereal, CAASidereal$, null], - CAAStellarMagnitudes: [CAAStellarMagnitudes, CAAStellarMagnitudes$, null], - CAASun: [CAASun, CAASun$, null], - CAAUranus: [CAAUranus, CAAUranus$, null], - CAAVenus: [CAAVenus, CAAVenus$, null], - VideoOutputType: [VideoOutputType, VideoOutputType$, null], - FitsProperties: [FitsProperties, FitsProperties$, null], - HipsProperties: [HipsProperties, HipsProperties$, null], - FastMath: [FastMath, FastMath$, null], - HealpixTables: [HealpixTables, HealpixTables$, null], - Xyf: [Xyf, Xyf$, null], - HealpixUtils: [HealpixUtils, HealpixUtils$, null], - Hploc: [Hploc, Hploc$, null], - Pointing: [Pointing, Pointing$, null], - URLHelpers: [URLHelpers, URLHelpers$, null], - Annotation: [Annotation, Annotation$, null], - AstroRaDec: [AstroRaDec, AstroRaDec$, null], - RiseSetDetails: [RiseSetDetails, RiseSetDetails$, null], - AstroCalc: [AstroCalc, AstroCalc$, null], - BlendState: [BlendState, BlendState$, null], - CameraParameters: [CameraParameters, CameraParameters$, null], - Color: [Color, Color$, null], - Colors: [Colors, Colors$, null], - Constellations: [Constellations, Constellations$, null], - Lineset: [Lineset, Lineset$, null], - Linepoint: [Linepoint, Linepoint$, null], - ConstellationFilter: [ConstellationFilter, ConstellationFilter$, null], - PositionTexture: [PositionTexture, PositionTexture$, null], - PositionColoredTextured: [PositionColoredTextured, PositionColoredTextured$, null], - PositionColored: [PositionColored, PositionColored$, null], - PositionNormalTexturedTangent: [PositionNormalTexturedTangent, PositionNormalTexturedTangent$, null], - Vector3d: [Vector3d, Vector3d$, null], - Vector2d: [Vector2d, Vector2d$, null], - Matrix3d: [Matrix3d, Matrix3d$, null], - Matrix2d: [Matrix2d, Matrix2d$, null], - DoubleUtilities: [DoubleUtilities, null, null], - PlaneD: [PlaneD, PlaneD$, null], - Vector4d: [Vector4d, Vector4d$, null], - PositionNormalTexturedX2: [PositionNormalTexturedX2, PositionNormalTexturedX2$, null], - PositionNormalTextured: [PositionNormalTextured, PositionNormalTextured$, null], - SphereHull: [SphereHull, SphereHull$, null], - ConvexHull: [ConvexHull, ConvexHull$, null], - Folder: [Folder, Folder$, null, IThumbnail], - FolderBrowser: [FolderBrowser, FolderBrowser$, null], - FolderUp: [FolderUp, FolderUp$, null, IThumbnail], - ShortIndexBuffer: [ShortIndexBuffer, ShortIndexBuffer$, null], - IndexBuffer: [IndexBuffer, IndexBuffer$, null, ss.IDisposable], - VertexBufferBase: [VertexBufferBase, VertexBufferBase$, null, ss.IDisposable], - Dates: [Dates, Dates$, null], - SimpleLineList: [SimpleLineList, SimpleLineList$, null], - OrbitLineList: [OrbitLineList, OrbitLineList$, null], - LineList: [LineList, LineList$, null], - TriangleList: [TriangleList, TriangleList$, null], - TriangleFanList: [TriangleFanList, TriangleFanList$, null], - PointList: [PointList, PointList$, null], - TimeSeriesLineVertex: [TimeSeriesLineVertex, TimeSeriesLineVertex$, null], - TimeSeriesPointVertex: [TimeSeriesPointVertex, TimeSeriesPointVertex$, null], - SimpleLineShader: [SimpleLineShader, SimpleLineShader$, null], - SimpleLineShader2D: [SimpleLineShader2D, SimpleLineShader2D$, null], - OrbitLineShader: [OrbitLineShader, OrbitLineShader$, null], - LineShaderNormalDates: [LineShaderNormalDates, LineShaderNormalDates$, null], - TimeSeriesPointSpriteShader: [TimeSeriesPointSpriteShader, TimeSeriesPointSpriteShader$, null], - KeplerPointSpriteShader: [KeplerPointSpriteShader, KeplerPointSpriteShader$, null], - EllipseShader: [EllipseShader, EllipseShader$, null], - ModelShader: [ModelShader, ModelShader$, null], - ModelShaderTan: [ModelShaderTan, ModelShaderTan$, null], - TileShader: [TileShader, TileShader$, null], - FitsShader: [FitsShader, FitsShader$, null], - ImageShader: [ImageShader, ImageShader$, null], - ImageShader2: [ImageShader2, ImageShader2$, null], - SpriteShader: [SpriteShader, SpriteShader$, null], - ShapeSpriteShader: [ShapeSpriteShader, ShapeSpriteShader$, null], - TextShader: [TextShader, TextShader$, null], - Tessellator: [Tessellator, Tessellator$, null], - Texture: [Texture, Texture$, null, ss.IDisposable], - Grids: [Grids, Grids$, null], - Imageset: [Imageset, Imageset$, null, IThumbnail], - ViewMoverKenBurnsStyle: [ViewMoverKenBurnsStyle, ViewMoverKenBurnsStyle$, null, IViewMover], - KeplerVertex: [KeplerVertex, KeplerVertex$, null], - ScaleMap: [ScaleMap, ScaleMap$, null], - ColorMapContainer: [ColorMapContainer, ColorMapContainer$, null], - Layer: [Layer, Layer$, null], - DomainValue: [DomainValue, DomainValue$, null], - LayerManager: [LayerManager, LayerManager$, null], - LayerMap: [LayerMap, LayerMap$, null], - SkyOverlays: [SkyOverlays, SkyOverlays$, null], - GroundOverlayLayer: [GroundOverlayLayer, GroundOverlayLayer$, null], - FrameTarget: [FrameTarget, FrameTarget$, null], - LayerUI: [LayerUI, LayerUI$, null], - LayerUIMenuItem: [LayerUIMenuItem, LayerUIMenuItem$, null], - LayerUITreeNode: [LayerUITreeNode, LayerUITreeNode$, null], - Group: [Group, Group$, null], - Mesh: [Mesh, Mesh$, null, ss.IDisposable], - Object3d: [Object3d, Object3d$, null], - ObjectNode: [ObjectNode, ObjectNode$, null], - Orbit: [Orbit, Orbit$, null], - EllipseRenderer: [EllipseRenderer, EllipseRenderer$, null], - ReferenceFrame: [ReferenceFrame, ReferenceFrame$, null], - KmlCoordinate: [KmlCoordinate, KmlCoordinate$, null], - KmlLineList: [KmlLineList, KmlLineList$, null], - PushPin: [PushPin, PushPin$, null], - Table: [Table, Table$, null], - VoTable: [VoTable, VoTable$, null], - VoRow: [VoRow, VoRow$, null], - VoColumn: [VoColumn, VoColumn$, null], - WcsImage: [WcsImage, WcsImage$, null], - Place: [Place, Place$, null, IThumbnail, IPlace], - KeplerianElements: [KeplerianElements, KeplerianElements$, null], - BodyAngles: [BodyAngles, BodyAngles$, null], - Planets: [Planets, Planets$, null], - Material: [Material, Material$, null], - InViewReturnMessage: [InViewReturnMessage, InViewReturnMessage$, null], - RenderContext: [RenderContext, RenderContext$, null], - RenderTriangle: [RenderTriangle, RenderTriangle$, null], - ScriptInterface: [ScriptInterface, ScriptInterface$, null], - Settings: [Settings, Settings$, null, ISettings], - Text3dBatch: [Text3dBatch, Text3dBatch$, null], - GlyphItem: [GlyphItem, GlyphItem$, null], - GlyphCache: [GlyphCache, GlyphCache$, null, ss.IDisposable], - Text3d: [Text3d, Text3d$, null], - SpaceTimeController: [SpaceTimeController, SpaceTimeController$, null], - Star: [Star, Star$, null], - Galaxy: [Galaxy, Galaxy$, null], - LatLngEdges: [LatLngEdges, LatLngEdges$, null], - Tile: [Tile, Tile$, null], - Tour: [Tour, Tour$, null, IThumbnail], - FileEntry: [FileEntry, FileEntry$, null], - FileCabinet: [FileCabinet, FileCabinet$, null], - SettingParameter: [SettingParameter, SettingParameter$, null], - Overlay: [Overlay, Overlay$, null], - Selection: [Selection, Selection$, null], - TextObject: [TextObject, TextObject$, null], - TourDocument: [TourDocument, TourDocument$, null], - TourEditTab: [TourEditTab, TourEditTab$, null], - TourEditor: [TourEditor, TourEditor$, null, IUiController], - OverlayList: [OverlayList, OverlayList$, null], - TourEdit: [TourEdit, TourEdit$, null], - SoundEditor: [SoundEditor, SoundEditor$, null], - TourStopList: [TourStopList, TourStopList$, null], - TimeLine: [TimeLine, TimeLine$, null], - TourPlayer: [TourPlayer, TourPlayer$, null, IUiController], - MasterTime: [MasterTime, MasterTime$, null], - TourStop: [TourStop, TourStop$, null, ISettings], - LayerInfo: [LayerInfo, LayerInfo$, null], - UndoTourStopChange: [UndoTourStopChange, UndoTourStopChange$, null, IUndoStep], - Undo: [Undo, Undo$, null], - UndoStep: [UndoStep, UndoStep$, null, IUndoStep], - UndoTourSlidelistChange: [UndoTourSlidelistChange, UndoTourSlidelistChange$, null, IUndoStep], - UndoTourPropertiesChange: [UndoTourPropertiesChange, UndoTourPropertiesChange$, null, IUndoStep], - UiTools: [UiTools, UiTools$, null], - Util: [Util, Util$, null], - Rectangle: [Rectangle, Rectangle$, null], - Guid: [Guid, Guid$, null], - Enums: [Enums, Enums$, null], - Mouse: [Mouse, null, null], - Language: [Language, Language$, null], - Cursor: [Cursor, Cursor$, null], - Cursors: [Cursors, Cursors$, null], - SelectLink: [SelectLink, SelectLink$, null], - PopupVolume: [PopupVolume, PopupVolume$, null], - PopupColorPicker: [PopupColorPicker, PopupColorPicker$, null], - OverlayProperties: [OverlayProperties, OverlayProperties$, null], - BinaryReader: [BinaryReader, BinaryReader$, null], - Bitmap: [Bitmap, Bitmap$, null], - ColorPicker: [ColorPicker, ColorPicker$, null], - ContextMenuStrip: [ContextMenuStrip, ContextMenuStrip$, null], - ToolStripMenuItem: [ToolStripMenuItem, ToolStripMenuItem$, null], - TagMe: [TagMe, TagMe$, null], - Dialog: [Dialog, Dialog$, null], - Histogram: [Histogram, Histogram$, null], - SimpleInput: [SimpleInput, SimpleInput$, null], - XmlTextWriter: [XmlTextWriter, XmlTextWriter$, null], - VizLayer: [VizLayer, VizLayer$, null], - DataItem: [DataItem, DataItem$, null], - WebFile: [WebFile, WebFile$, null], - FolderDownloadAction: [FolderDownloadAction, FolderDownloadAction$, null], - Wtml: [Wtml, Wtml$, null], - WWTControl: [WWTControl, WWTControl$, null], - WWTControlBuilder: [WWTControlBuilder, WWTControlBuilder$, null], - WWTElementEvent: [WWTElementEvent, WWTElementEvent$, null], - Coordinates: [Coordinates, Coordinates$, null], - Fxyf: [Fxyf, Fxyf$, HealpixTables], - HealpixTile: [HealpixTile, HealpixTile$, Tile], - FitsImage: [FitsImage, FitsImage$, WcsImage], - Circle: [Circle, Circle$, Annotation], - Poly: [Poly, Poly$, Annotation], - PolyLine: [PolyLine, PolyLine$, Annotation], - EquirectangularTile: [EquirectangularTile, EquirectangularTile$, Tile], - PositionVertexBuffer: [PositionVertexBuffer, PositionVertexBuffer$, VertexBufferBase], - PositionNormalTexturedVertexBuffer: [PositionNormalTexturedVertexBuffer, PositionNormalTexturedVertexBuffer$, VertexBufferBase], - PositionNormalTexturedTangentVertexBuffer: [PositionNormalTexturedTangentVertexBuffer, PositionNormalTexturedTangentVertexBuffer$, VertexBufferBase], - ScaleLinear: [ScaleLinear, ScaleLinear$, ScaleMap], - ScaleLog: [ScaleLog, ScaleLog$, ScaleMap], - ScalePow: [ScalePow, ScalePow$, ScaleMap], - ScaleSqrt: [ScaleSqrt, ScaleSqrt$, ScaleMap], - HistogramEqualization: [HistogramEqualization, HistogramEqualization$, ScaleMap], - GreatCirlceRouteLayer: [GreatCirlceRouteLayer, GreatCirlceRouteLayer$, Layer], - GridLayer: [GridLayer, GridLayer$, Layer], - ImageSetLayer: [ImageSetLayer, ImageSetLayer$, Layer], - Object3dLayer: [Object3dLayer, Object3dLayer$, Layer, IUiController], - Object3dLayerUI: [Object3dLayerUI, Object3dLayerUI$, LayerUI], - OrbitLayer: [OrbitLayer, OrbitLayer$, Layer], - OrbitLayerUI: [OrbitLayerUI, OrbitLayerUI$, LayerUI], - SpreadSheetLayer: [SpreadSheetLayer, SpreadSheetLayer$, Layer], - TimeSeriesLayer: [TimeSeriesLayer, TimeSeriesLayer$, Layer], - VoTableLayer: [VoTableLayer, VoTableLayer$, Layer], - MercatorTile: [MercatorTile, MercatorTile$, Tile], - PlotTile: [PlotTile, PlotTile$, Tile], - TangentTile: [TangentTile, TangentTile$, Tile], - ToastTile: [ToastTile, ToastTile$, Tile], - BitmapOverlay: [BitmapOverlay, BitmapOverlay$, Overlay], - TextOverlay: [TextOverlay, TextOverlay$, Overlay], - ShapeOverlay: [ShapeOverlay, ShapeOverlay$, Overlay], - AudioOverlay: [AudioOverlay, AudioOverlay$, Overlay], - FlipbookOverlay: [FlipbookOverlay, FlipbookOverlay$, Overlay], - ToolStripSeparator: [ToolStripSeparator, ToolStripSeparator$, ToolStripMenuItem], - FrameWizard: [FrameWizard, FrameWizard$, Dialog], - ReferenceFrameProps: [ReferenceFrameProps, ReferenceFrameProps$, Dialog], - GreatCircleDialog: [GreatCircleDialog, GreatCircleDialog$, Dialog], - DataVizWizard: [DataVizWizard, DataVizWizard$, Dialog], - FitsImageTile: [FitsImageTile, FitsImageTile$, FitsImage], - FitsImageJs: [FitsImageJs, FitsImageJs$, FitsImage], - ISSLayer: [ISSLayer, ISSLayer$, Object3dLayer], - CatalogSpreadSheetLayer: [CatalogSpreadSheetLayer, CatalogSpreadSheetLayer$, SpreadSheetLayer], - SlideChangedEventArgs: [SlideChangedEventArgs, SlideChangedEventArgs$, ss.EventArgs], - ArrivedEventArgs: [ArrivedEventArgs, ArrivedEventArgs$, ss.EventArgs], - AnnotationClickEventArgs: [AnnotationClickEventArgs, AnnotationClickEventArgs$, ss.EventArgs], - CollectionLoadedEventArgs: [CollectionLoadedEventArgs, CollectionLoadedEventArgs$, ss.EventArgs], - SkyImageTile: [SkyImageTile, SkyImageTile$, TangentTile] - }); - - let pako; - if (typeof window !== "undefined" && "pako" in window) { - ; - pako = window["pako"]; - } else { - ; - import('pako').then(function (result) { pako = result; }); - }; - let uuid; - if (typeof window !== "undefined" && "uuid" in window) { - ; - uuid = window["uuid"]; - } else { - ; - import('uuid').then(function (result) { uuid = result; }); - }; - GFX.g_ACft = [new ACFT(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1719914, -2, -25, 0, 25, -13, 1578089, 156, 10, 32, 684185, -358), new ACFT(0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6434, 141, 28007, -107, 25697, -95, -5904, -130, 11141, -48, -2559, -55), new ACFT(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 715, 0, 0, 0, 6, 0, -657, 0, -15, 0, -282, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 715, 0, 0, 0, 0, 0, -656, 0, 0, 0, -285, 0), new ACFT(0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 486, -5, -236, -4, -216, -4, -446, 5, -94, 0, -193, 0), new ACFT(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 2, 0, -147, 0, -6, 0, -61, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, -59, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 39, 0, 0, 0, 0, 0, -36, 0, 0, 0, -16, 0), new ACFT(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 33, 0, -10, 0, -9, 0, -30, 0, -5, 0, -13, 0), new ACFT(0, 2, 0, -1, 0, 0, 0, 0, 0, 0, 0, 31, 0, 1, 0, 1, 0, -28, 0, 0, 0, -12, 0), new ACFT(0, 3, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, 25, 0, 8, 0, 11, 0, 3, 0), new ACFT(0, 5, -8, 3, 0, 0, 0, 0, 0, 0, 0, 8, 0, -28, 0, -25, 0, -8, 0, -11, 0, -3, 0), new ACFT(2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, -19, 0, 0, 0, -8, 0), new ACFT(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -19, 0, 0, 0, 0, 0, 17, 0, 0, 0, 8, 0), new ACFT(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, -16, 0, 0, 0, -7, 0), new ACFT(0, 1, 0, -2, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 1, 0, 7, 0), new ACFT(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, -15, 0, -3, 0, -6, 0), new ACFT(0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 11, 0, -1, 0, -1, 0, -10, 0, -1, 0, -5, 0), new ACFT(2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -11, 0, -10, 0, 0, 0, -4, 0, 0, 0), new ACFT(0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -11, 0, -2, 0, -2, 0, 9, 0, -1, 0, 4, 0), new ACFT(0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -8, 0, -8, 0, 6, 0, -3, 0, 3, 0), new ACFT(0, 3, 0, -2, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, 0, 0, 0, 9, 0, 0, 0, 4, 0), new ACFT(1, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -9, 0, 0, 0, -4, 0), new ACFT(2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -8, 0, 0, 0, -4, 0), new ACFT(0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, -8, 0, 0, 0, -3, 0, 0, 0), new ACFT(2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 0, 8, 0, 0, 0, 3, 0, 0, 0), new ACFT(0, 3, -2, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, -8, 0, 0, 0, -3, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, 2, -1, 0, 8, 0, 0, 0, 0, 0, -7, 0, 0, 0, -3, 0), new ACFT(8, -12, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, -6, 0, 4, 0, -3, 0, 2, 0), new ACFT(8, -14, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, -7, 0, 6, 0, -4, 0, 3, 0, -2, 0), new ACFT(0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, -6, 0, -5, 0, -4, 0, 5, 0, -2, 0, 2, 0), new ACFT(3, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -2, 0, -7, 0, 1, 0, -4, 0), new ACFT(0, 2, 0, -2, 0, 0, 0, 0, 0, 0, 0, 4, 0, -6, 0, -5, 0, -4, 0, -2, 0, -2, 0), new ACFT(3, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -7, 0, -6, 0, 0, 0, -3, 0, 0, 0), new ACFT(0, 2, -2, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, -5, 0, -4, 0, -5, 0, -2, 0, -2, 0), new ACFT(0, 0, 0, 0, 0, 0, 0, 1, -2, 0, 0, 5, 0, 0, 0, 0, 0, -5, 0, 0, 0, -2, 0)]; - GFX.deltaTTable = [121, 112, 103, 95, 88, 82, 77, 72, 68, 63, 60, 56, 53, 51, 48, 46, 44, 42, 40, 38, 35, 33, 31, 29, 26, 24, 22, 20, 18, 16, 14, 12, 11, 10, 9, 8, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 14, 13, 13.1, 12.5, 12.2, 12, 12, 12, 12, 12, 12, 11.9, 11.6, 11, 10.2, 9.2, 8.2, 7.1, 6.2, 5.6, 5.4, 5.3, 5.4, 5.6, 5.9, 6.2, 6.5, 6.8, 7.1, 7.3, 7.5, 7.6, 7.7, 7.3, 6.2, 5.2, 2.7, 1.4, -1.2, -2.8, -3.8, -4.8, -5.5, -5.3, -5.6, -5.7, -5.9, -6, -6.3, -6.5, -6.2, -4.7, -2.8, -0.1, 2.6, 5.3, 7.7, 10.4, 13.3, 16, 18.2, 20.2, 21.2, 22.4, 23.5, 23.8, 24.3, 24, 23.9, 23.9, 23.7, 24, 24.3, 25.3, 26.2, 27.3, 28.2, 29.1, 30, 30.7, 31.4, 32.2, 33.1, 34, 35, 36.5, 38.3, 40.18, 42.2, 44.5, 46.5, 48.5, 50.54, 52.2, 53.8, 54.9, 55.8, 56.86, 58.31, 59.99, 61.63, 62.97]; - GFX.g_L0EarthCoefficients = [new VSC(175347046, 0, 0), new VSC(3341656, 4.6692568, 6283.07585), new VSC(34894, 4.6261, 12566.1517), new VSC(3497, 2.7441, 5753.3849), new VSC(3418, 2.8289, 3.5231), new VSC(3136, 3.6277, 77713.7715), new VSC(2676, 4.4181, 7860.4194), new VSC(2343, 6.1352, 3930.2097), new VSC(1324, 0.7425, 11506.7698), new VSC(1273, 2.0371, 529.691), new VSC(1199, 1.1096, 1577.3435), new VSC(990, 5.233, 5884.927), new VSC(902, 2.045, 26.298), new VSC(857, 3.508, 398.149), new VSC(780, 1.179, 5223.694), new VSC(753, 2.533, 5507.553), new VSC(505, 4.583, 18849.228), new VSC(492, 4.205, 775.523), new VSC(357, 2.92, 0.067), new VSC(317, 5.849, 11790.629), new VSC(284, 1.899, 796.288), new VSC(271, 0.315, 10977.079), new VSC(243, 0.345, 5486.778), new VSC(206, 4.806, 2544.314), new VSC(205, 1.869, 5573.143), new VSC(202, 2.458, 6069.777), new VSC(156, 0.833, 213.299), new VSC(132, 3.411, 2942.463), new VSC(126, 1.083, 20.775), new VSC(115, 0.645, 0.98), new VSC(103, 0.636, 4694.003), new VSC(102, 0.976, 15720.839), new VSC(102, 4.267, 7.114), new VSC(99, 6.21, 2146.17), new VSC(98, 0.68, 155.42), new VSC(86, 5.98, 161000.69), new VSC(85, 1.3, 6275.96), new VSC(85, 3.67, 71430.7), new VSC(80, 1.81, 17260.15), new VSC(79, 3.04, 12036.46), new VSC(75, 1.76, 5088.63), new VSC(74, 3.5, 3154.69), new VSC(74, 4.68, 801.82), new VSC(70, 0.83, 9437.76), new VSC(62, 3.98, 8827.39), new VSC(61, 1.82, 7084.9), new VSC(57, 2.78, 6286.6), new VSC(56, 4.39, 14143.5), new VSC(56, 3.47, 6279.55), new VSC(52, 0.19, 12139.55), new VSC(52, 1.33, 1748.02), new VSC(51, 0.28, 5856.48), new VSC(49, 0.49, 1194.45), new VSC(41, 5.37, 8429.24), new VSC(41, 2.4, 19651.05), new VSC(39, 6.17, 10447.39), new VSC(37, 6.04, 10213.29), new VSC(37, 2.57, 1059.38), new VSC(36, 1.71, 2352.87), new VSC(36, 1.78, 6812.77), new VSC(33, 0.59, 17789.85), new VSC(30, 0.44, 83996.85), new VSC(30, 2.74, 1349.87), new VSC(25, 3.16, 4690.48)]; - GFX.g_L1EarthCoefficients = [new VSC(628331966747, 0, 0), new VSC(206059, 2.678235, 6283.07585), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.59, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.4, 796.3), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.3), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694), new VSC(11, 0.77, 553.57), new VSC(10, 1.3, 6286.6), new VSC(10, 4.24, 1349.87), new VSC(9, 2.7, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.3, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48)]; - GFX.g_L2EarthCoefficients = [new VSC(52919, 0, 0), new VSC(8720, 1.0721, 6283.0758), new VSC(309, 0.867, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.3), new VSC(16, 3.68, 155.42), new VSC(10, 0.76, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.3), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.31, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98)]; - GFX.g_L3EarthCoefficients = [new VSC(289, 5.844, 6283.076), new VSC(35, 0, 0), new VSC(17, 5.49, 12566.15), new VSC(3, 5.2, 155.42), new VSC(1, 4.72, 3.52), new VSC(1, 5.3, 18849.23), new VSC(1, 5.97, 242.73)]; - GFX.g_L4EarthCoefficients = [new VSC(114, 3.142, 0), new VSC(8, 4.13, 6283.08), new VSC(1, 3.84, 12566.15)]; - GFX.g_L5EarthCoefficients = [new VSC(1, 3.14, 0)]; - GFX.g_B0EarthCoefficients = [new VSC(280, 3.199, 84334.662), new VSC(102, 5.422, 5507.553), new VSC(80, 3.88, 5223.69), new VSC(44, 3.7, 2352.87), new VSC(32, 4, 1577.34)]; - GFX.g_B1EarthCoefficients = [new VSC(9, 3.9, 5507.55), new VSC(6, 1.73, 5223.69)]; - GFX.g_B2EarthCoefficients = [new VSC(22378, 3.38509, 10213.28555), new VSC(282, 0, 0), new VSC(173, 5.256, 20426.571), new VSC(27, 3.87, 30639.86)]; - GFX.g_B3EarthCoefficients = [new VSC(647, 4.992, 10213.286), new VSC(20, 3.14, 0), new VSC(6, 0.77, 20426.57), new VSC(3, 5.44, 30639.86)]; - GFX.g_B4EarthCoefficients = [new VSC(14, 0.32, 10213.29)]; - GFX.g_R0EarthCoefficients = [new VSC(100013989, 0, 0), new VSC(1670700, 3.0984635, 6283.07585), new VSC(13956, 3.05525, 12566.1517), new VSC(3084, 5.1985, 77713.7715), new VSC(1628, 1.1739, 5753.3849), new VSC(1576, 2.8469, 7860.4194), new VSC(925, 5.453, 11506.77), new VSC(542, 4.564, 3930.21), new VSC(472, 3.661, 5884.927), new VSC(346, 0.964, 5507.553), new VSC(329, 5.9, 5223.694), new VSC(307, 0.299, 5573.143), new VSC(243, 4.273, 11790.629), new VSC(212, 5.847, 1577.344), new VSC(186, 5.022, 10977.079), new VSC(175, 3.012, 18849.228), new VSC(110, 5.055, 5486.778), new VSC(98, 0.89, 6069.78), new VSC(86, 5.69, 15720.84), new VSC(86, 1.27, 161000.69), new VSC(65, 0.27, 17260.15), new VSC(63, 0.92, 529.69), new VSC(57, 2.01, 83996.85), new VSC(56, 5.24, 71430.7), new VSC(49, 3.25, 2544.31), new VSC(47, 2.58, 775.52), new VSC(45, 5.54, 9437.76), new VSC(43, 6.01, 6275.96), new VSC(39, 5.36, 4694), new VSC(38, 2.39, 8827.39), new VSC(37, 0.83, 19651.05), new VSC(37, 4.9, 12139.55), new VSC(36, 1.67, 12036.46), new VSC(35, 1.84, 2942.46), new VSC(33, 0.24, 7084.9), new VSC(32, 0.18, 5088.63), new VSC(32, 1.78, 398.15), new VSC(28, 1.21, 6286.6), new VSC(28, 1.9, 6279.55), new VSC(26, 4.59, 10447.39)]; - GFX.g_R1EarthCoefficients = [new VSC(103019, 1.10749, 6283.07585), new VSC(1721, 1.0644, 12566.1517), new VSC(702, 3.142, 0), new VSC(32, 1.02, 18849.23), new VSC(31, 2.84, 5507.55), new VSC(25, 1.32, 5223.69), new VSC(18, 1.42, 1577.34), new VSC(10, 5.91, 10977.08), new VSC(9, 1.42, 6275.96), new VSC(9, 0.27, 5486.78)]; - GFX.g_R2EarthCoefficients = [new VSC(4359, 5.7846, 6283.0758), new VSC(124, 5.579, 12566.152), new VSC(12, 3.14, 0), new VSC(9, 3.63, 77713.77), new VSC(6, 1.87, 5573.14), new VSC(3, 5.47, 18849.23)]; - GFX.g_R3EarthCoefficients = [new VSC(145, 4.273, 6283.076), new VSC(7, 3.92, 12566.15)]; - GFX.g_R4EarthCoefficients = [new VSC(4, 2.56, 6283.08)]; - GFX.g_L1EarthCoefficientsJ2000 = [new VSC(628307584999, 0, 0), new VSC(206059, 2.678235, 6283.07585), new VSC(4303, 2.6351, 12566.1517), new VSC(425, 1.59, 3.523), new VSC(119, 5.796, 26.298), new VSC(109, 2.966, 1577.344), new VSC(93, 2.59, 18849.23), new VSC(72, 1.14, 529.69), new VSC(68, 1.87, 398.15), new VSC(67, 4.41, 5507.55), new VSC(59, 2.89, 5223.69), new VSC(56, 2.17, 155.42), new VSC(45, 0.4, 796.3), new VSC(36, 0.47, 775.52), new VSC(29, 2.65, 7.11), new VSC(21, 5.43, 0.98), new VSC(19, 1.85, 5486.78), new VSC(19, 4.97, 213.3), new VSC(17, 2.99, 6275.96), new VSC(16, 0.03, 2544.31), new VSC(16, 1.43, 2146.17), new VSC(15, 1.21, 10977.08), new VSC(12, 2.83, 1748.02), new VSC(12, 3.26, 5088.63), new VSC(12, 5.27, 1194.45), new VSC(12, 2.08, 4694), new VSC(11, 0.77, 553.57), new VSC(10, 1.3, 6286.6), new VSC(10, 4.24, 1349.87), new VSC(9, 2.7, 242.73), new VSC(9, 5.64, 951.72), new VSC(8, 5.3, 2352.87), new VSC(6, 2.65, 9437.76), new VSC(6, 4.67, 4690.48)]; - GFX.g_L2EarthCoefficientsJ2000 = [new VSC(8722, 1.0725, 6283.0758), new VSC(991, 3.1416, 0), new VSC(295, 0.437, 12566.152), new VSC(27, 0.05, 3.52), new VSC(16, 5.19, 26.3), new VSC(16, 3.69, 155.42), new VSC(9, 0.3, 18849.23), new VSC(9, 2.06, 77713.77), new VSC(7, 0.83, 775.52), new VSC(5, 4.66, 1577.34), new VSC(4, 1.03, 7.11), new VSC(4, 3.44, 5573.14), new VSC(3, 5.14, 796.3), new VSC(3, 6.05, 5507.55), new VSC(3, 1.19, 242.73), new VSC(3, 6.12, 529.69), new VSC(3, 0.3, 398.15), new VSC(3, 2.28, 553.57), new VSC(2, 4.38, 5223.69), new VSC(2, 3.75, 0.98)]; - GFX.g_L3EarthCoefficientsJ2000 = [new VSC(289, 5.842, 6283.076), new VSC(21, 6.05, 12566.15), new VSC(3, 5.2, 155.42), new VSC(3, 3.14, 0), new VSC(1, 4.72, 3.52), new VSC(1, 5.97, 242.73), new VSC(1, 5.54, 18849.23)]; - GFX.g_L4EarthCoefficientsJ2000 = [new VSC(8, 4.14, 6283.08), new VSC(1, 3.28, 12566.15)]; - GFX.g_B1EarthCoefficientsJ2000 = [new VSC(227778, 3.413766, 6283.07585), new VSC(3806, 3.3706, 12566.1517), new VSC(3620, 0, 0), new VSC(72, 3.33, 18849.23), new VSC(8, 3.89, 5507.55), new VSC(8, 1.79, 5223.69), new VSC(6, 5.2, 2352.87)]; - GFX.g_B2EarthCoefficientsJ2000 = [new VSC(9721, 5.1519, 6283.07585), new VSC(233, 3.1416, 0), new VSC(134, 0.644, 12566.152), new VSC(7, 1.07, 18849.23)]; - GFX.g_B3EarthCoefficientsJ2000 = [new VSC(276, 0.595, 6283.076), new VSC(17, 3.14, 0), new VSC(4, 0.12, 12566.15)]; - GFX.g_B4EarthCoefficientsJ2000 = [new VSC(6, 2.27, 6283.08), new VSC(1, 0, 0)]; - GFX.g_L0JupiterCoefficients = [new VSC(59954691, 0, 0), new VSC(9695899, 5.0619179, 529.6909651), new VSC(573610, 1.444062, 7.113547), new VSC(306389, 5.417347, 1059.38193), new VSC(97178, 4.14265, 632.78374), new VSC(72903, 3.64043, 522.57742), new VSC(64264, 3.41145, 103.09277), new VSC(39806, 2.29377, 419.48464), new VSC(38858, 1.27232, 316.39187), new VSC(27965, 1.78455, 536.80451), new VSC(13590, 5.77481, 1589.0729), new VSC(8769, 3.63, 949.1756), new VSC(8246, 3.5823, 206.1855), new VSC(7368, 5.081, 735.8765), new VSC(6263, 0.025, 213.2991), new VSC(6114, 4.5132, 1162.4747), new VSC(5305, 4.1863, 1052.2684), new VSC(5305, 1.3067, 14.2271), new VSC(4905, 1.3208, 110.2063), new VSC(4647, 4.6996, 3.9322), new VSC(3045, 4.3168, 426.5982), new VSC(2610, 1.5667, 846.0828), new VSC(2028, 1.0638, 3.1814), new VSC(1921, 0.9717, 639.8973), new VSC(1765, 2.1415, 1066.4955), new VSC(1723, 3.8804, 1265.5675), new VSC(1633, 3.582, 515.4639), new VSC(1432, 4.2968, 625.6702), new VSC(973, 4.098, 95.979), new VSC(884, 2.437, 412.371), new VSC(733, 6.085, 838.969), new VSC(731, 3.806, 1581.959), new VSC(709, 1.293, 742.99), new VSC(692, 6.134, 2118.764), new VSC(614, 4.109, 1478.867), new VSC(582, 4.54, 309.278), new VSC(495, 3.756, 323.505), new VSC(441, 2.958, 454.909), new VSC(417, 1.036, 2.488), new VSC(390, 4.897, 1692.166), new VSC(376, 4.703, 1368.66), new VSC(341, 5.715, 533.623), new VSC(330, 4.74, 0.048), new VSC(262, 1.877, 0.963), new VSC(261, 0.82, 380.128), new VSC(257, 3.724, 199.072), new VSC(244, 5.22, 728.763), new VSC(235, 1.227, 909.819), new VSC(220, 1.651, 543.918), new VSC(207, 1.855, 525.759), new VSC(202, 1.807, 1375.774), new VSC(197, 5.293, 1155.361), new VSC(175, 3.73, 942.062), new VSC(175, 3.226, 1898.351), new VSC(175, 5.91, 956.289), new VSC(158, 4.365, 1795.258), new VSC(151, 3.906, 74.782), new VSC(149, 4.377, 1685.052), new VSC(141, 3.136, 491.558), new VSC(138, 1.318, 1169.588), new VSC(131, 4.169, 1045.155), new VSC(117, 2.5, 1596.186), new VSC(117, 3.389, 0.521), new VSC(106, 4.554, 526.51)]; - GFX.g_L1JupiterCoefficients = [new VSC(52993480757, 0, 0), new VSC(489741, 4.220667, 529.690965), new VSC(228919, 6.026475, 7.113547), new VSC(27655, 4.57266, 1059.38193), new VSC(20721, 5.45939, 522.57742), new VSC(12106, 0.16986, 536.80451), new VSC(6068, 4.4242, 103.0928), new VSC(5434, 3.9848, 419.4846), new VSC(4238, 5.8901, 14.2271), new VSC(2212, 5.2677, 206.1855), new VSC(1746, 4.9267, 1589.0729), new VSC(1296, 5.5513, 3.1814), new VSC(1173, 5.8565, 1052.2684), new VSC(1163, 0.5145, 3.9322), new VSC(1099, 5.307, 515.4639), new VSC(1007, 0.4648, 735.8765), new VSC(1004, 3.1504, 426.5982), new VSC(848, 5.758, 110.206), new VSC(827, 4.803, 213.299), new VSC(816, 0.586, 1066.495), new VSC(725, 5.518, 639.897), new VSC(568, 5.989, 625.67), new VSC(474, 4.132, 412.371), new VSC(413, 5.737, 95.979), new VSC(345, 4.242, 632.784), new VSC(336, 3.732, 1162.475), new VSC(234, 4.035, 949.176), new VSC(234, 6.243, 309.278), new VSC(199, 1.505, 838.969), new VSC(195, 2.219, 323.505), new VSC(187, 6.086, 742.99), new VSC(184, 6.28, 543.918), new VSC(171, 5.417, 199.072), new VSC(131, 0.626, 728.763), new VSC(115, 0.68, 846.083), new VSC(115, 5.286, 2118.764), new VSC(108, 4.493, 956.289), new VSC(80, 5.82, 1045.15), new VSC(72, 5.34, 942.06), new VSC(70, 5.97, 532.87), new VSC(67, 5.73, 21.34), new VSC(66, 0.13, 526.51), new VSC(65, 6.09, 1581.96), new VSC(59, 0.59, 1155.36), new VSC(58, 0.99, 1596.19), new VSC(57, 5.97, 1169.59), new VSC(57, 1.41, 533.62), new VSC(55, 5.43, 10.29), new VSC(52, 5.73, 117.32), new VSC(52, 0.23, 1368.66), new VSC(50, 6.08, 525.76), new VSC(47, 3.63, 1478.87), new VSC(47, 0.51, 1265.57), new VSC(40, 4.16, 1692.17), new VSC(34, 0.1, 302.16), new VSC(33, 5.04, 220.41), new VSC(32, 5.37, 508.35), new VSC(29, 5.42, 1272.68), new VSC(29, 3.36, 4.67), new VSC(29, 0.76, 88.87), new VSC(25, 1.61, 831.86)]; - GFX.g_L2JupiterCoefficients = [new VSC(47234, 4.32148, 7.11355), new VSC(38966, 0, 0), new VSC(30629, 2.93021, 529.69097), new VSC(3189, 1.055, 522.5774), new VSC(2729, 4.8455, 536.8045), new VSC(2723, 3.4141, 1059.3819), new VSC(1721, 4.1873, 14.2271), new VSC(383, 5.768, 419.485), new VSC(378, 0.76, 515.464), new VSC(367, 6.055, 103.093), new VSC(337, 3.786, 3.181), new VSC(308, 0.694, 206.186), new VSC(218, 3.814, 1589.073), new VSC(199, 5.34, 1066.495), new VSC(197, 2.484, 3.932), new VSC(156, 1.406, 1052.268), new VSC(146, 3.814, 639.897), new VSC(142, 1.634, 426.598), new VSC(130, 5.837, 412.371), new VSC(117, 1.414, 625.67), new VSC(97, 4.03, 110.21), new VSC(91, 1.11, 95.98), new VSC(87, 2.52, 632.78), new VSC(79, 4.64, 543.92), new VSC(72, 2.22, 735.88), new VSC(58, 0.83, 199.07), new VSC(57, 3.12, 213.3), new VSC(49, 1.67, 309.28), new VSC(40, 4.02, 21.34), new VSC(40, 0.62, 323.51), new VSC(36, 2.33, 728.76), new VSC(29, 3.61, 10.29), new VSC(28, 3.24, 838.97), new VSC(26, 4.5, 742.99), new VSC(26, 2.51, 1162.47), new VSC(25, 1.22, 1045.15), new VSC(24, 3.01, 956.29), new VSC(19, 4.29, 532.87), new VSC(18, 0.81, 508.35), new VSC(17, 4.2, 2118.76), new VSC(17, 1.83, 526.51), new VSC(15, 5.81, 1596.19), new VSC(15, 0.68, 942.06), new VSC(15, 4, 117.32), new VSC(14, 5.95, 316.39), new VSC(14, 1.8, 302.16), new VSC(13, 2.52, 88.87), new VSC(13, 4.37, 1169.59), new VSC(11, 4.44, 525.76), new VSC(10, 1.72, 1581.96), new VSC(9, 2.18, 1155.36), new VSC(9, 3.29, 220.41), new VSC(9, 3.32, 831.86), new VSC(8, 5.76, 846.08), new VSC(8, 2.71, 533.62), new VSC(7, 2.18, 1265.57), new VSC(6, 0.5, 949.18)]; - GFX.g_L3JupiterCoefficients = [new VSC(6502, 2.5986, 7.1135), new VSC(1357, 1.3464, 529.691), new VSC(471, 2.475, 14.227), new VSC(417, 3.245, 536.805), new VSC(353, 2.974, 522.577), new VSC(155, 2.076, 1059.382), new VSC(87, 2.51, 515.46), new VSC(44, 0, 0), new VSC(34, 3.83, 1066.5), new VSC(28, 2.45, 206.19), new VSC(24, 1.28, 412.37), new VSC(23, 2.98, 543.92), new VSC(20, 2.1, 639.9), new VSC(20, 1.4, 419.48), new VSC(19, 1.59, 103.09), new VSC(17, 2.3, 21.34), new VSC(17, 2.6, 1589.07), new VSC(16, 3.15, 625.67), new VSC(16, 3.36, 1052.27), new VSC(13, 2.76, 95.98), new VSC(13, 2.54, 199.07), new VSC(13, 6.27, 426.6), new VSC(9, 1.76, 10.29), new VSC(9, 2.27, 110.21), new VSC(7, 3.43, 309.28), new VSC(7, 4.04, 728.76), new VSC(6, 2.52, 508.35), new VSC(5, 2.91, 1045.15), new VSC(5, 5.25, 323.51), new VSC(4, 4.3, 88.87), new VSC(4, 3.52, 302.16), new VSC(4, 4.09, 735.88), new VSC(3, 1.43, 956.29), new VSC(3, 4.36, 1596.19), new VSC(3, 1.25, 213.3), new VSC(3, 5.02, 838.97), new VSC(3, 2.24, 117.32), new VSC(2, 2.9, 742.99), new VSC(2, 2.36, 942.06)]; - GFX.g_L4JupiterCoefficients = [new VSC(669, 0.853, 7.114), new VSC(114, 3.142, 0), new VSC(100, 0.743, 14.227), new VSC(50, 1.65, 536.8), new VSC(44, 5.82, 529.69), new VSC(32, 4.86, 522.58), new VSC(15, 4.29, 515.46), new VSC(9, 0.71, 1059.38), new VSC(5, 1.3, 543.92), new VSC(4, 2.32, 1066.5), new VSC(4, 0.48, 21.34), new VSC(3, 3, 412.37), new VSC(2, 0.4, 639.9), new VSC(2, 4.26, 199.07), new VSC(2, 4.91, 625.67), new VSC(2, 4.26, 206.19), new VSC(1, 5.26, 1052.27), new VSC(1, 4.72, 95.98), new VSC(1, 1.29, 1589.07)]; - GFX.g_L5JupiterCoefficients = [new VSC(50, 5.26, 7.11), new VSC(16, 5.25, 14.23), new VSC(4, 0.01, 536.8), new VSC(2, 1.1, 522.58), new VSC(1, 3.14, 0)]; - GFX.g_B0JupiterCoefficients = [new VSC(2268616, 3.5585261, 529.6909651), new VSC(110090, 0, 0), new VSC(109972, 3.908093, 1059.38193), new VSC(8101, 3.6051, 522.5774), new VSC(6438, 0.3063, 536.8045), new VSC(6044, 4.2588, 1589.0729), new VSC(1107, 2.9853, 1162.4747), new VSC(944, 1.675, 426.598), new VSC(942, 2.936, 1052.268), new VSC(894, 1.754, 7.114), new VSC(836, 5.179, 103.093), new VSC(767, 2.155, 632.784), new VSC(684, 3.678, 213.299), new VSC(629, 0.643, 1066.495), new VSC(559, 0.014, 846.083), new VSC(532, 2.703, 110.206), new VSC(464, 1.173, 949.176), new VSC(431, 2.608, 419.485), new VSC(351, 4.611, 2118.764), new VSC(132, 4.778, 742.99), new VSC(123, 3.35, 1692.166), new VSC(116, 1.387, 323.505), new VSC(115, 5.049, 316.392), new VSC(104, 3.701, 515.464), new VSC(103, 2.319, 1478.867), new VSC(102, 3.153, 1581.959)]; - GFX.g_B1JupiterCoefficients = [new VSC(177352, 5.701665, 529.690965), new VSC(3230, 5.7794, 1059.3819), new VSC(3081, 5.4746, 522.5774), new VSC(2212, 4.7348, 536.8045), new VSC(1694, 3.1416, 0), new VSC(346, 4.746, 1052.268), new VSC(234, 5.189, 1066.495), new VSC(196, 6.186, 7.114), new VSC(150, 3.927, 1589.073), new VSC(114, 3.439, 632.784), new VSC(97, 2.91, 949.18), new VSC(82, 5.08, 1162.47), new VSC(77, 2.51, 103.09), new VSC(77, 0.61, 419.48), new VSC(74, 5.5, 515.46), new VSC(61, 5.45, 213.3), new VSC(50, 3.95, 735.88), new VSC(46, 0.54, 110.21), new VSC(45, 1.9, 846.08), new VSC(37, 4.7, 543.92), new VSC(36, 6.11, 316.39), new VSC(32, 4.92, 1581.96)]; - GFX.g_B2JupiterCoefficients = [new VSC(8094, 1.4632, 529.691), new VSC(813, 3.1416, 0), new VSC(742, 0.957, 522.577), new VSC(399, 2.899, 536.805), new VSC(342, 1.447, 1059.382), new VSC(74, 0.41, 1052.27), new VSC(46, 3.48, 1066.5), new VSC(30, 1.93, 1589.07), new VSC(29, 0.99, 515.46), new VSC(23, 4.27, 7.11), new VSC(14, 2.92, 543.92), new VSC(12, 5.22, 632.78), new VSC(11, 4.88, 949.18), new VSC(6, 6.21, 1045.15)]; - GFX.g_B3JupiterCoefficients = [new VSC(252, 3.381, 529.691), new VSC(122, 2.733, 522.577), new VSC(49, 1.04, 536.8), new VSC(11, 2.31, 1052.27), new VSC(8, 2.77, 515.46), new VSC(7, 4.25, 1059.38), new VSC(6, 1.78, 1066.5), new VSC(4, 1.13, 543.92), new VSC(3, 3.14, 0)]; - GFX.g_B4JupiterCoefficients = [new VSC(15, 4.53, 522.58), new VSC(5, 4.47, 529.69), new VSC(4, 5.44, 536.8), new VSC(3, 0, 0), new VSC(2, 4.52, 515.46), new VSC(1, 4.2, 1052.27)]; - GFX.g_B5JupiterCoefficients = [new VSC(1, 0.09, 522.58)]; - GFX.g_R0JupiterCoefficients = [new VSC(520887429, 0, 0), new VSC(25209327, 3.4910864, 529.69096509), new VSC(610600, 3.841154, 1059.38193), new VSC(282029, 2.574199, 632.783739), new VSC(187647, 2.075904, 522.577418), new VSC(86793, 0.71001, 419.48464), new VSC(72063, 0.21466, 536.80451), new VSC(65517, 5.97996, 316.39187), new VSC(30135, 2.16132, 949.17561), new VSC(29135, 1.67759, 103.09277), new VSC(23947, 0.27458, 7.11355), new VSC(23453, 3.54023, 735.87651), new VSC(22284, 4.19363, 1589.0729), new VSC(13033, 2.96043, 1162.4747), new VSC(12749, 2.7155, 1052.26838), new VSC(9703, 1.9067, 206.1855), new VSC(9161, 4.4135, 213.2991), new VSC(7895, 2.4791, 426.5982), new VSC(7058, 2.1818, 1265.5675), new VSC(6138, 6.2642, 846.0828), new VSC(5477, 5.6573, 639.8973), new VSC(4170, 2.0161, 515.4639), new VSC(4137, 2.7222, 625.6702), new VSC(3503, 0.5653, 1066.4955), new VSC(2617, 2.0099, 1581.9593), new VSC(2500, 4.5518, 838.9693), new VSC(2128, 6.1275, 742.9901), new VSC(1912, 0.8562, 412.3711), new VSC(1611, 3.0887, 1368.6603), new VSC(1479, 2.6803, 1478.8666), new VSC(1231, 1.8904, 323.5054), new VSC(1217, 1.8017, 110.2063), new VSC(1015, 1.3867, 454.9094), new VSC(999, 2.872, 309.278), new VSC(961, 4.549, 2118.764), new VSC(886, 4.148, 533.623), new VSC(821, 1.593, 1898.351), new VSC(812, 5.941, 909.819), new VSC(777, 3.677, 728.763), new VSC(727, 3.988, 1155.361), new VSC(655, 2.791, 1685.052), new VSC(654, 3.382, 1692.166), new VSC(621, 4.823, 956.289), new VSC(615, 2.276, 942.062), new VSC(562, 0.081, 543.918), new VSC(542, 0.284, 525.759)]; - GFX.g_R1JupiterCoefficients = [new VSC(1271802, 2.6493751, 529.6909651), new VSC(61662, 3.00076, 1059.38193), new VSC(53444, 3.89718, 522.57742), new VSC(41390, 0, 0), new VSC(31185, 4.88277, 536.80451), new VSC(11847, 2.4133, 419.48464), new VSC(9166, 4.7598, 7.1135), new VSC(3404, 3.3469, 1589.0729), new VSC(3203, 5.2108, 735.8765), new VSC(3176, 2.793, 103.0928), new VSC(2806, 3.7422, 515.4639), new VSC(2677, 4.3305, 1052.2684), new VSC(2600, 3.6344, 206.1855), new VSC(2412, 1.4695, 426.5982), new VSC(2101, 3.9276, 639.8973), new VSC(1646, 4.4163, 1066.4955), new VSC(1641, 4.4163, 625.6702), new VSC(1050, 3.1611, 213.2991), new VSC(1025, 2.5543, 412.3711), new VSC(806, 2.678, 632.784), new VSC(741, 2.171, 1162.475), new VSC(677, 6.25, 838.969), new VSC(567, 4.577, 742.99), new VSC(485, 2.469, 949.176), new VSC(469, 4.71, 543.918), new VSC(445, 0.403, 323.505), new VSC(416, 5.368, 728.763), new VSC(402, 4.605, 309.278), new VSC(347, 4.681, 14.227), new VSC(338, 3.168, 956.289), new VSC(261, 5.343, 846.083), new VSC(247, 3.923, 942.062), new VSC(220, 4.842, 1368.66), new VSC(203, 5.6, 1155.361), new VSC(200, 4.439, 1045.155), new VSC(197, 3.706, 2118.764), new VSC(196, 3.759, 199.072), new VSC(184, 4.265, 95.979), new VSC(180, 4.402, 532.872), new VSC(170, 4.846, 526.51), new VSC(146, 6.13, 533.623), new VSC(133, 1.322, 110.206), new VSC(132, 4.512, 525.759)]; - GFX.g_R2JupiterCoefficients = [new VSC(79645, 1.35866, 529.69097), new VSC(8252, 5.7777, 522.5774), new VSC(7030, 3.2748, 536.8045), new VSC(5314, 1.8384, 1059.3819), new VSC(1861, 2.9768, 7.1135), new VSC(964, 5.48, 515.464), new VSC(836, 4.199, 419.485), new VSC(498, 3.142, 0), new VSC(427, 2.228, 639.897), new VSC(406, 3.783, 1066.495), new VSC(377, 2.242, 1589.073), new VSC(363, 5.368, 206.186), new VSC(342, 6.099, 1052.268), new VSC(339, 6.127, 625.67), new VSC(333, 0.003, 426.598), new VSC(280, 4.262, 412.371), new VSC(257, 0.963, 632.784), new VSC(230, 0.705, 735.877), new VSC(201, 3.069, 543.918), new VSC(200, 4.429, 103.093), new VSC(139, 2.932, 14.227), new VSC(114, 0.787, 728.763), new VSC(95, 1.7, 838.97), new VSC(86, 5.14, 323.51), new VSC(83, 0.06, 309.28), new VSC(80, 2.98, 742.99), new VSC(75, 1.6, 956.29), new VSC(70, 1.51, 213.3), new VSC(67, 5.47, 199.07), new VSC(62, 6.1, 1045.15), new VSC(56, 0.96, 1162.47), new VSC(52, 5.58, 942.06), new VSC(50, 2.72, 532.87), new VSC(45, 5.52, 508.35), new VSC(44, 0.27, 526.51), new VSC(40, 5.95, 95.98)]; - GFX.g_R3JupiterCoefficients = [new VSC(3519, 6.058, 529.691), new VSC(1073, 1.6732, 536.8045), new VSC(916, 1.413, 522.577), new VSC(342, 0.523, 1059.382), new VSC(255, 1.196, 7.114), new VSC(222, 0.952, 515.464), new VSC(90, 3.14, 0), new VSC(69, 2.27, 1066.5), new VSC(58, 1.41, 543.92), new VSC(58, 0.53, 639.9), new VSC(51, 5.98, 412.37), new VSC(47, 1.58, 625.67), new VSC(43, 6.12, 419.48), new VSC(37, 1.18, 14.23), new VSC(34, 1.67, 1052.27), new VSC(34, 0.85, 206.19), new VSC(31, 1.04, 1589.07), new VSC(30, 4.63, 426.6), new VSC(21, 2.5, 728.76), new VSC(15, 0.89, 199.07), new VSC(14, 0.96, 508.35), new VSC(13, 1.5, 1045.15), new VSC(12, 2.61, 735.88), new VSC(12, 3.56, 323.51), new VSC(11, 1.79, 309.28), new VSC(11, 6.28, 956.29), new VSC(10, 6.26, 103.09), new VSC(9, 3.45, 838.97)]; - GFX.g_R4JupiterCoefficients = [new VSC(129, 0.084, 536.805), new VSC(113, 4.249, 529.691), new VSC(83, 3.3, 522.58), new VSC(38, 2.73, 515.46), new VSC(27, 5.69, 7.11), new VSC(18, 5.4, 1059.38), new VSC(13, 6.02, 543.92), new VSC(9, 0.77, 1066.5), new VSC(8, 5.68, 14.23), new VSC(7, 1.43, 412.37), new VSC(6, 5.12, 639.9), new VSC(5, 3.34, 625.67), new VSC(3, 3.4, 1052.27), new VSC(3, 4.16, 728.76), new VSC(3, 2.9, 426.6)]; - GFX.g_R5JupiterCoefficients = [new VSC(11, 4.75, 536.8), new VSC(4, 5.92, 522.58), new VSC(2, 5.57, 515.46), new VSC(2, 4.3, 543.92), new VSC(2, 3.69, 7.11), new VSC(2, 4.13, 1059.38), new VSC(2, 5.49, 1066.5)]; - GFX.g_L0MarsCoefficients = [new VSC(620347712, 0, 0), new VSC(18656368, 5.050371, 3340.6124267), new VSC(1108217, 5.4009984, 6681.2248534), new VSC(91798, 5.75479, 10021.83728), new VSC(27745, 5.9705, 3.52312), new VSC(12316, 0.84956, 2810.92146), new VSC(10610, 2.93959, 2281.2305), new VSC(8927, 4.157, 0.0173), new VSC(8716, 6.1101, 13362.4497), new VSC(7775, 3.3397, 5621.8429), new VSC(6798, 0.3646, 398.149), new VSC(4161, 0.2281, 2942.4634), new VSC(3575, 1.6619, 2544.3144), new VSC(3075, 0.857, 191.4483), new VSC(2938, 6.0789, 0.0673), new VSC(2628, 0.6481, 3337.0893), new VSC(2580, 0.03, 3344.1355), new VSC(2389, 5.039, 796.298), new VSC(1799, 0.6563, 529.691), new VSC(1546, 2.9158, 1751.5395), new VSC(1528, 1.1498, 6151.5339), new VSC(1286, 3.068, 2146.1654), new VSC(1264, 3.6228, 5092.152), new VSC(1025, 3.6933, 8962.4553), new VSC(892, 0.183, 16703.062), new VSC(859, 2.401, 2914.014), new VSC(833, 4.495, 3340.63), new VSC(833, 2.464, 3340.595), new VSC(749, 3.822, 155.42), new VSC(724, 0.675, 3738.761), new VSC(713, 3.663, 1059.382), new VSC(655, 0.489, 3127.313), new VSC(636, 2.922, 8432.764), new VSC(553, 4.475, 1748.016), new VSC(550, 3.81, 0.98), new VSC(472, 3.625, 1194.447), new VSC(426, 0.554, 6283.076), new VSC(415, 0.497, 213.299), new VSC(312, 0.999, 6677.702), new VSC(307, 0.381, 6684.748), new VSC(302, 4.486, 3532.061), new VSC(299, 2.783, 6254.627), new VSC(293, 4.221, 20.775), new VSC(284, 5.769, 3149.164), new VSC(281, 5.882, 1349.867), new VSC(274, 0.542, 3340.545), new VSC(274, 0.134, 3340.68), new VSC(239, 5.372, 4136.91), new VSC(236, 5.755, 3333.499), new VSC(231, 1.282, 3870.303), new VSC(221, 3.505, 382.897), new VSC(204, 2.821, 1221.849), new VSC(193, 3.357, 3.59), new VSC(189, 1.491, 9492.146), new VSC(179, 1.006, 951.718), new VSC(174, 2.414, 553.569), new VSC(172, 0.439, 5486.778), new VSC(160, 3.949, 4562.461), new VSC(144, 1.419, 135.065), new VSC(140, 3.326, 2700.715), new VSC(138, 4.301, 7.114), new VSC(131, 4.045, 12303.068), new VSC(128, 2.208, 1592.596), new VSC(128, 1.807, 5088.629), new VSC(117, 3.128, 7903.073), new VSC(113, 3.701, 1589.073), new VSC(110, 1.052, 242.729), new VSC(105, 0.785, 8827.39), new VSC(100, 3.243, 11773.377)]; - GFX.g_L1MarsCoefficients = [new VSC(334085627474, 0, 0), new VSC(1458227, 3.6042605, 3340.6124267), new VSC(164901, 3.926313, 6681.224853), new VSC(19963, 4.26594, 10021.83728), new VSC(3452, 4.7321, 3.5231), new VSC(2485, 4.6128, 13362.4497), new VSC(842, 4.459, 2281.23), new VSC(538, 5.016, 398.149), new VSC(521, 4.994, 3344.136), new VSC(433, 2.561, 191.448), new VSC(430, 5.316, 155.42), new VSC(382, 3.539, 796.298), new VSC(314, 4.963, 16703.062), new VSC(283, 3.16, 2544.314), new VSC(206, 4.569, 2146.165), new VSC(169, 1.329, 3337.089), new VSC(158, 4.185, 1751.54), new VSC(134, 2.233, 0.98), new VSC(134, 5.974, 1748.016), new VSC(118, 6.024, 6151.534), new VSC(117, 2.213, 1059.382), new VSC(114, 2.129, 1194.447), new VSC(114, 5.428, 3738.761), new VSC(91, 1.1, 1349.87), new VSC(85, 3.91, 553.57), new VSC(83, 5.3, 6684.75), new VSC(81, 4.43, 529.69), new VSC(80, 2.25, 8962.46), new VSC(73, 2.5, 951.72), new VSC(73, 5.84, 242.73), new VSC(71, 3.86, 2914.01), new VSC(68, 5.02, 382.9), new VSC(65, 1.02, 3340.6), new VSC(65, 3.05, 3340.63), new VSC(62, 4.15, 3149.16), new VSC(57, 3.89, 4136.91), new VSC(48, 4.87, 213.3), new VSC(48, 1.18, 3333.5), new VSC(47, 1.31, 3185.19), new VSC(41, 0.71, 1592.6), new VSC(40, 2.73, 7.11), new VSC(40, 5.32, 20043.67), new VSC(33, 5.41, 6283.08), new VSC(28, 0.05, 9492.15), new VSC(27, 3.89, 1221.85), new VSC(27, 5.11, 2700.72)]; - GFX.g_L2MarsCoefficients = [new VSC(58016, 2.04979, 3340.61243), new VSC(54188, 0, 0), new VSC(13908, 2.45742, 6681.22485), new VSC(2465, 2.8, 10021.8373), new VSC(398, 3.141, 13362.45), new VSC(222, 3.194, 3.523), new VSC(121, 0.543, 155.42), new VSC(62, 3.49, 16703.06), new VSC(54, 3.54, 3344.14), new VSC(34, 6, 2281.23), new VSC(32, 4.14, 191.45), new VSC(30, 2, 796.3), new VSC(23, 4.33, 242.73), new VSC(22, 3.45, 398.15), new VSC(20, 5.42, 553.57), new VSC(16, 0.66, 0.98), new VSC(16, 6.11, 2146.17), new VSC(16, 1.22, 1748.02), new VSC(15, 6.1, 3185.19), new VSC(14, 4.02, 951.72), new VSC(14, 2.62, 1349.87), new VSC(13, 0.6, 1194.45), new VSC(12, 3.86, 6684.75), new VSC(11, 4.72, 2544.31), new VSC(10, 0.25, 382.9), new VSC(9, 0.68, 1059.38), new VSC(9, 3.83, 20043.67), new VSC(9, 3.88, 3738.76), new VSC(8, 5.46, 1751.54), new VSC(7, 2.58, 3149.16), new VSC(7, 2.38, 4136.91), new VSC(6, 5.48, 1592.6), new VSC(6, 2.34, 3097.88)]; - GFX.g_L3MarsCoefficients = [new VSC(1482, 0.4443, 3340.6124), new VSC(662, 0.885, 6681.225), new VSC(188, 1.288, 10021.837), new VSC(41, 1.65, 13362.45), new VSC(26, 0, 0), new VSC(23, 2.05, 155.42), new VSC(10, 1.58, 3.52), new VSC(8, 2, 16703.06), new VSC(5, 2.82, 242.73), new VSC(4, 2.02, 3344.14), new VSC(3, 4.59, 3185.19), new VSC(3, 0.65, 553.57)]; - GFX.g_L4MarsCoefficients = [new VSC(114, 3.1416, 0), new VSC(29, 5.64, 6681.22), new VSC(24, 5.14, 3340.61), new VSC(11, 6.03, 10021.84), new VSC(3, 0.13, 13362.45), new VSC(3, 3.56, 155.42), new VSC(1, 0.49, 16703.06), new VSC(1, 1.32, 242.73)]; - GFX.g_L5MarsCoefficients = [new VSC(1, 3.14, 0), new VSC(1, 4.04, 6681.22)]; - GFX.g_B0MarsCoefficients = [new VSC(3197135, 3.7683204, 3340.6124267), new VSC(298033, 4.10617, 6681.224853), new VSC(289105, 0, 0), new VSC(31366, 4.44651, 10021.83728), new VSC(3484, 4.7881, 13362.4497), new VSC(443, 5.026, 3344.136), new VSC(443, 5.652, 3337.089), new VSC(399, 5.131, 16703.062), new VSC(293, 3.793, 2281.23), new VSC(182, 6.136, 6151.534), new VSC(163, 4.264, 529.691), new VSC(160, 2.232, 1059.382), new VSC(149, 2.165, 5621.843), new VSC(143, 1.182, 3340.595), new VSC(143, 3.213, 3340.63), new VSC(139, 2.418, 8962.455)]; - GFX.g_B1MarsCoefficients = [new VSC(350069, 5.368478, 3340.612427), new VSC(14116, 3.14159, 0), new VSC(9671, 5.4788, 6681.2249), new VSC(1472, 3.2021, 10021.8373), new VSC(426, 3.408, 13362.45), new VSC(102, 0.776, 3337.089), new VSC(79, 3.72, 16703.06), new VSC(33, 3.46, 5621.84), new VSC(26, 2.48, 2281.23)]; - GFX.g_B2MarsCoefficients = [new VSC(16727, 0.60221, 3340.61243), new VSC(4987, 4.1416, 0), new VSC(302, 3.559, 6681.225), new VSC(26, 1.9, 13362.45), new VSC(21, 0.92, 10021.84), new VSC(12, 2.24, 3337.09), new VSC(8, 2.25, 16703.06)]; - GFX.g_B3MarsCoefficients = [new VSC(607, 1.981, 3340.612), new VSC(43, 0, 0), new VSC(14, 1.8, 6681.22), new VSC(3, 3.45, 10021.84)]; - GFX.g_B4MarsCoefficients = [new VSC(13, 0, 0), new VSC(11, 3.46, 3340.61), new VSC(1, 0.5, 6681.22)]; - GFX.g_R0MarsCoefficients = [new VSC(153033488, 0, 0), new VSC(14184953, 3.47971284, 3340.6124267), new VSC(660776, 3.817834, 6681.224853), new VSC(46179, 4.15595, 10021.83728), new VSC(8110, 5.5596, 2810.9215), new VSC(7485, 1.7724, 5621.8429), new VSC(5523, 1.3644, 2281.2305), new VSC(3825, 4.4941, 13362.4497), new VSC(2484, 4.9255, 2942.4634), new VSC(2307, 0.0908, 2544.3144), new VSC(1999, 5.3606, 3337.0893), new VSC(1960, 4.7425, 3344.1355), new VSC(1167, 2.1126, 5092.152), new VSC(1103, 5.0091, 398.149), new VSC(992, 5.839, 6151.534), new VSC(899, 4.408, 529.691), new VSC(807, 2.102, 1059.382), new VSC(798, 3.448, 796.298), new VSC(741, 1.499, 2146.165), new VSC(726, 1.245, 8432.764), new VSC(692, 2.134, 8962.455), new VSC(633, 0.894, 3340.595), new VSC(633, 2.924, 3340.63), new VSC(630, 1.287, 1751.54), new VSC(574, 0.829, 2914.014), new VSC(526, 5.383, 3738.761), new VSC(473, 5.199, 3127.313), new VSC(348, 4.832, 16703.062), new VSC(284, 2.907, 3532.061), new VSC(280, 5.257, 6283.076), new VSC(276, 1.218, 6254.627), new VSC(275, 2.908, 1748.016), new VSC(270, 3.764, 5884.927), new VSC(239, 2.037, 1194.447), new VSC(234, 5.105, 5486.778), new VSC(228, 3.255, 6872.673), new VSC(223, 4.199, 3149.164), new VSC(219, 5.583, 191.448), new VSC(208, 5.255, 3340.545), new VSC(208, 4.846, 3340.68), new VSC(186, 5.699, 6677.702), new VSC(183, 5.081, 6684.748), new VSC(179, 4.184, 3333.499), new VSC(176, 5.953, 3870.303), new VSC(164, 3.799, 4136.91)]; - GFX.g_R1MarsCoefficients = [new VSC(1107433, 2.0325052, 3340.6124267), new VSC(103176, 2.370718, 6681.224853), new VSC(12877, 0, 0), new VSC(10816, 2.70888, 10021.83728), new VSC(1195, 3.047, 13362.4497), new VSC(439, 2.888, 2281.23), new VSC(396, 3.423, 3344.136), new VSC(183, 1.584, 2544.314), new VSC(136, 3.385, 16703.062), new VSC(128, 6.043, 3337.089), new VSC(128, 0.63, 1059.382), new VSC(127, 1.954, 796.298), new VSC(118, 2.998, 2146.165), new VSC(88, 3.42, 398.15), new VSC(83, 3.86, 3738.76), new VSC(76, 4.45, 6151.53), new VSC(72, 2.76, 529.69), new VSC(67, 2.55, 1751.54), new VSC(66, 4.41, 1748.02), new VSC(58, 0.54, 1194.45), new VSC(54, 0.68, 8962.46), new VSC(51, 3.73, 6684.75), new VSC(49, 5.73, 3340.6), new VSC(49, 1.48, 3340.63), new VSC(48, 2.58, 3149.16), new VSC(48, 2.29, 2914.01), new VSC(39, 2.32, 4136.91)]; - GFX.g_R2MarsCoefficients = [new VSC(44242, 0.47931, 3340.61243), new VSC(8138, 0.87, 6681.2249), new VSC(1275, 1.2259, 10021.8373), new VSC(187, 1.573, 13362.45), new VSC(52, 3.14, 0), new VSC(41, 1.97, 3344.14), new VSC(27, 1.92, 16703.06), new VSC(18, 4.43, 2281.23), new VSC(12, 4.53, 3185.19), new VSC(10, 5.39, 1059.38), new VSC(10, 0.42, 796.3)]; - GFX.g_R3MarsCoefficients = [new VSC(1113, 5.1499, 3340.6124), new VSC(424, 5.613, 6681.225), new VSC(100, 5.997, 10021.837), new VSC(20, 0.08, 13362.45), new VSC(5, 3.14, 0), new VSC(3, 0.43, 16703.06)]; - GFX.g_R4MarsCoefficients = [new VSC(20, 3.58, 3340.61), new VSC(16, 4.05, 6681.22), new VSC(6, 4.46, 10021.84), new VSC(2, 4.84, 13362.45)]; - GFX.g_L0MercuryCoefficients = [new VSC(440250710, 0, 0), new VSC(40989415, 1.48302034, 26087.90314157), new VSC(5046294, 4.47785449, 52175.8062831), new VSC(855347, 1.165203, 78263.709425), new VSC(165590, 4.119692, 104351.612566), new VSC(34562, 0.77931, 130439.51571), new VSC(7583, 3.7135, 156527.4188), new VSC(3560, 1.512, 1109.3786), new VSC(1803, 4.1033, 5661.332), new VSC(1726, 0.3583, 182615.322), new VSC(1590, 2.9951, 25028.5212), new VSC(1365, 4.5992, 27197.2817), new VSC(1017, 0.8803, 31749.2352), new VSC(714, 1.541, 24978.525), new VSC(644, 5.303, 21535.95), new VSC(451, 6.05, 51116.424), new VSC(404, 3.282, 208703.225), new VSC(352, 5.242, 20426.571), new VSC(345, 2.792, 15874.618), new VSC(343, 5.765, 955.6), new VSC(339, 5.863, 25558.212), new VSC(325, 1.337, 53285.185), new VSC(273, 2.495, 529.691), new VSC(264, 3.917, 57837.138), new VSC(260, 0.987, 4551.953), new VSC(239, 0.113, 1059.382), new VSC(235, 0.267, 11322.664), new VSC(217, 0.66, 13521.751), new VSC(209, 2.092, 47623.853), new VSC(183, 2.629, 27043.503), new VSC(182, 2.434, 25661.305), new VSC(176, 4.536, 51066.428), new VSC(173, 2.452, 24498.83), new VSC(142, 3.36, 37410.567), new VSC(138, 0.291, 10213.286), new VSC(125, 3.721, 39609.655), new VSC(118, 2.781, 77204.327), new VSC(106, 4.206, 19804.827)]; - GFX.g_L1MercuryCoefficients = [new VSC(2608814706223, 0, 0), new VSC(1126008, 6.2170397, 26087.9031416), new VSC(303471, 3.055655, 52175.806283), new VSC(80538, 6.10455, 78263.70942), new VSC(21245, 2.83532, 104351.61257), new VSC(5592, 5.8268, 130439.5157), new VSC(1472, 2.5185, 156527.4188), new VSC(388, 5.48, 182615.322), new VSC(352, 3.052, 1109.379), new VSC(103, 2.149, 208703.225), new VSC(94, 6.12, 27197.28), new VSC(91, 0, 24978.52), new VSC(52, 5.62, 5661.33), new VSC(44, 4.57, 25028.52), new VSC(28, 3.04, 51066.43), new VSC(27, 5.09, 234791.13)]; - GFX.g_L2MercuryCoefficients = [new VSC(53050, 0, 0), new VSC(16904, 4.69072, 26087.90314), new VSC(7397, 1.3474, 52175.8063), new VSC(3018, 4.4564, 78263.7094), new VSC(1107, 1.264, 104351.6126), new VSC(378, 4.32, 130439.516), new VSC(123, 1.069, 156527.419), new VSC(39, 4.08, 182615.32), new VSC(15, 4.63, 1109.38), new VSC(12, 0.79, 208703.23)]; - GFX.g_L3MercuryCoefficients = [new VSC(188, 0.035, 52175.806), new VSC(142, 3.125, 26087.903), new VSC(97, 3, 78263.71), new VSC(44, 6.02, 104351.61), new VSC(35, 0, 0), new VSC(18, 2.78, 130439.52), new VSC(7, 5.82, 156527.42), new VSC(3, 2.57, 182615.32)]; - GFX.g_L4MercuryCoefficients = [new VSC(114, 3.1416, 0), new VSC(2, 2.03, 26087.9), new VSC(2, 1.42, 78263.71), new VSC(2, 4.5, 52175.81), new VSC(1, 4.5, 104351.61), new VSC(1, 1.27, 130439.52)]; - GFX.g_L5MercuryCoefficients = [new VSC(1, 3.14, 0)]; - GFX.g_B0MercuryCoefficients = [new VSC(11737529, 1.98357499, 26087.90314157), new VSC(2388077, 5.0373896, 52175.8062831), new VSC(1222840, 3.1415927, 0), new VSC(543252, 1.796444, 78263.709425), new VSC(129779, 4.832325, 104351.612566), new VSC(31867, 1.58088, 130439.51571), new VSC(7963, 4.6097, 156527.4188), new VSC(2014, 1.3532, 182615.322), new VSC(514, 4.378, 208703.325), new VSC(209, 2.02, 24978.525), new VSC(208, 4.918, 27197.282), new VSC(132, 1.119, 234791.128), new VSC(121, 1.813, 53285.185), new VSC(100, 5.657, 20426.571)]; - GFX.g_B1MercuryCoefficients = [new VSC(429151, 3.501698, 26087.903142), new VSC(146234, 3.141593, 0), new VSC(22675, 0.01515, 52175.80628), new VSC(10895, 0.4854, 78263.70942), new VSC(6353, 3.4294, 104351.6126), new VSC(2496, 0.1605, 130439.5157), new VSC(860, 3.185, 156527.419), new VSC(278, 6.21, 182615.322), new VSC(86, 2.95, 208703.23), new VSC(28, 0.29, 27197.28), new VSC(26, 5.98, 234791.13)]; - GFX.g_B2MercuryCoefficients = [new VSC(11831, 4.79066, 26087.90314), new VSC(1914, 0, 0), new VSC(1045, 1.2122, 52175.8063), new VSC(266, 4.434, 78263.709), new VSC(170, 1.623, 104351.613), new VSC(96, 4.8, 130439.52), new VSC(45, 1.61, 156527.42), new VSC(18, 4.67, 182615.32), new VSC(7, 1.43, 208703.23)]; - GFX.g_B3MercuryCoefficients = [new VSC(235, 0.354, 26087.903), new VSC(161, 0, 0), new VSC(19, 4.36, 52175.81), new VSC(6, 2.51, 78263.71), new VSC(5, 6.14, 104351.61), new VSC(3, 3.12, 130439.52), new VSC(2, 6.27, 156527.42)]; - GFX.g_B4MercuryCoefficients = [new VSC(4, 1.75, 26087.9), new VSC(1, 3.14, 0)]; - GFX.g_R0MercuryCoefficients = [new VSC(39528272, 0, 0), new VSC(7834132, 6.1923372, 26087.9031416), new VSC(795526, 2.959897, 52175.806283), new VSC(121282, 6.010642, 78263.709425), new VSC(21922, 2.7782, 104351.61257), new VSC(4354, 5.8289, 130439.5157), new VSC(918, 2.597, 156527.419), new VSC(290, 1.424, 25028.521), new VSC(260, 3.028, 27197.282), new VSC(202, 5.647, 182615.322), new VSC(201, 5.592, 31749.235), new VSC(142, 6.253, 24978.525), new VSC(100, 3.734, 21535.95)]; - GFX.g_R1MercuryCoefficients = [new VSC(217348, 4.656172, 26087.903142), new VSC(44142, 1.42386, 52175.80628), new VSC(10094, 4.47466, 78263.70942), new VSC(2433, 1.2423, 104351.6126), new VSC(1624, 0, 0), new VSC(604, 4.293, 130439.516), new VSC(153, 1.061, 156527.419), new VSC(39, 4.11, 182615.32)]; - GFX.g_R2MercuryCoefficients = [new VSC(3118, 3.0823, 26087.9031), new VSC(1245, 6.1518, 52175.8063), new VSC(425, 2.926, 78263.709), new VSC(136, 5.98, 104351.613), new VSC(42, 2.75, 130439.52), new VSC(22, 3.14, 0), new VSC(13, 5.8, 156527.42)]; - GFX.g_R3MercuryCoefficients = [new VSC(33, 1.68, 26087.9), new VSC(24, 4.63, 52175.81), new VSC(12, 1.39, 78263.71), new VSC(5, 4.44, 104351.61), new VSC(2, 1.21, 130439.52)]; - GFX.g_MoonCoefficients1 = [new MoonCoefficient1(0, 0, 1, 0), new MoonCoefficient1(2, 0, -1, 0), new MoonCoefficient1(2, 0, 0, 0), new MoonCoefficient1(0, 0, 2, 0), new MoonCoefficient1(0, 1, 0, 0), new MoonCoefficient1(0, 0, 0, 2), new MoonCoefficient1(2, 0, -2, 0), new MoonCoefficient1(2, -1, -1, 0), new MoonCoefficient1(2, 0, 1, 0), new MoonCoefficient1(2, -1, 0, 0), new MoonCoefficient1(0, 1, -1, 0), new MoonCoefficient1(1, 0, 0, 0), new MoonCoefficient1(0, 1, 1, 0), new MoonCoefficient1(2, 0, 0, -2), new MoonCoefficient1(0, 0, 1, 2), new MoonCoefficient1(0, 0, 1, -2), new MoonCoefficient1(4, 0, -1, 0), new MoonCoefficient1(0, 0, 3, 0), new MoonCoefficient1(4, 0, -2, 0), new MoonCoefficient1(2, 1, -1, 0), new MoonCoefficient1(2, 1, 0, 0), new MoonCoefficient1(1, 0, -1, 0), new MoonCoefficient1(1, 1, 0, 0), new MoonCoefficient1(2, -1, 1, 0), new MoonCoefficient1(2, 0, 2, 0), new MoonCoefficient1(4, 0, 0, 0), new MoonCoefficient1(2, 0, -3, 0), new MoonCoefficient1(0, 1, -2, 0), new MoonCoefficient1(2, 0, -1, 2), new MoonCoefficient1(2, -1, -2, 0), new MoonCoefficient1(1, 0, 1, 0), new MoonCoefficient1(2, -2, 0, 0), new MoonCoefficient1(0, 1, 2, 0), new MoonCoefficient1(0, 2, 0, 0), new MoonCoefficient1(2, -2, -1, 0), new MoonCoefficient1(2, 0, 1, -2), new MoonCoefficient1(2, 0, 0, 2), new MoonCoefficient1(4, -1, -1, 0), new MoonCoefficient1(0, 0, 2, 2), new MoonCoefficient1(3, 0, -1, 0), new MoonCoefficient1(2, 1, 1, 0), new MoonCoefficient1(4, -1, -2, 0), new MoonCoefficient1(0, 2, -1, 0), new MoonCoefficient1(2, 2, -1, 0), new MoonCoefficient1(2, 1, -2, 0), new MoonCoefficient1(2, -1, 0, -2), new MoonCoefficient1(4, 0, 1, 0), new MoonCoefficient1(0, 0, 4, 0), new MoonCoefficient1(4, -1, 0, 0), new MoonCoefficient1(1, 0, -2, 0), new MoonCoefficient1(2, 1, 0, -2), new MoonCoefficient1(0, 0, 2, -2), new MoonCoefficient1(1, 1, 1, 0), new MoonCoefficient1(3, 0, -2, 0), new MoonCoefficient1(4, 0, -3, 0), new MoonCoefficient1(2, -1, 2, 0), new MoonCoefficient1(0, 2, 1, 0), new MoonCoefficient1(1, 1, -1, 0), new MoonCoefficient1(2, 0, 3, 0), new MoonCoefficient1(2, 0, -1, -2)]; - GFX.g_MoonCoefficients2 = [new MoonCoefficient2(6288774, -20905355), new MoonCoefficient2(1274027, -3699111), new MoonCoefficient2(658314, -2955968), new MoonCoefficient2(213618, -569925), new MoonCoefficient2(-185116, 48888), new MoonCoefficient2(-114332, -3149), new MoonCoefficient2(58793, 246158), new MoonCoefficient2(57066, -152138), new MoonCoefficient2(53322, -170733), new MoonCoefficient2(45758, -204586), new MoonCoefficient2(-40923, -129620), new MoonCoefficient2(-34720, 108743), new MoonCoefficient2(-30383, 104755), new MoonCoefficient2(15327, 10321), new MoonCoefficient2(-12528, 0), new MoonCoefficient2(10980, 79661), new MoonCoefficient2(10675, -34782), new MoonCoefficient2(10034, -23210), new MoonCoefficient2(8548, -21636), new MoonCoefficient2(-7888, 24208), new MoonCoefficient2(-6766, 30824), new MoonCoefficient2(-5163, -8379), new MoonCoefficient2(4987, -16675), new MoonCoefficient2(4036, -12831), new MoonCoefficient2(3994, -10445), new MoonCoefficient2(3861, -11650), new MoonCoefficient2(3665, 14403), new MoonCoefficient2(-2689, -7003), new MoonCoefficient2(-2602, 0), new MoonCoefficient2(2390, 10056), new MoonCoefficient2(-2348, 6322), new MoonCoefficient2(2236, -9884), new MoonCoefficient2(-2120, 5751), new MoonCoefficient2(-2069, 0), new MoonCoefficient2(2048, -4950), new MoonCoefficient2(-1773, 4130), new MoonCoefficient2(-1595, 0), new MoonCoefficient2(1215, -3958), new MoonCoefficient2(-1110, 0), new MoonCoefficient2(-892, 3258), new MoonCoefficient2(-810, 2616), new MoonCoefficient2(759, -1897), new MoonCoefficient2(-713, -2117), new MoonCoefficient2(-700, 2354), new MoonCoefficient2(691, 0), new MoonCoefficient2(596, 0), new MoonCoefficient2(549, -1423), new MoonCoefficient2(537, -1117), new MoonCoefficient2(520, -1571), new MoonCoefficient2(-487, -1739), new MoonCoefficient2(-399, 0), new MoonCoefficient2(-381, -4421), new MoonCoefficient2(351, 0), new MoonCoefficient2(-340, 0), new MoonCoefficient2(330, 0), new MoonCoefficient2(327, 0), new MoonCoefficient2(-323, 1165), new MoonCoefficient2(299, 0), new MoonCoefficient2(294, 0), new MoonCoefficient2(0, 8752)]; - GFX.g_MoonCoefficients3 = [new MoonCoefficient1(0, 0, 0, 1), new MoonCoefficient1(0, 0, 1, 1), new MoonCoefficient1(0, 0, 1, -1), new MoonCoefficient1(2, 0, 0, -1), new MoonCoefficient1(2, 0, -1, 1), new MoonCoefficient1(2, 0, -1, -1), new MoonCoefficient1(2, 0, 0, 1), new MoonCoefficient1(0, 0, 2, 1), new MoonCoefficient1(2, 0, 1, -1), new MoonCoefficient1(0, 0, 2, -1), new MoonCoefficient1(2, -1, 0, -1), new MoonCoefficient1(2, 0, -2, -1), new MoonCoefficient1(2, 0, 1, 1), new MoonCoefficient1(2, 1, 0, -1), new MoonCoefficient1(2, -1, -1, 1), new MoonCoefficient1(2, -1, 0, 1), new MoonCoefficient1(2, -1, -1, -1), new MoonCoefficient1(0, 1, -1, -1), new MoonCoefficient1(4, 0, -1, -1), new MoonCoefficient1(0, 1, 0, 1), new MoonCoefficient1(0, 0, 0, 3), new MoonCoefficient1(0, 1, -1, 1), new MoonCoefficient1(1, 0, 0, 1), new MoonCoefficient1(0, 1, 1, 1), new MoonCoefficient1(0, 1, 1, -1), new MoonCoefficient1(0, 1, 0, -1), new MoonCoefficient1(1, 0, 0, -1), new MoonCoefficient1(0, 0, 3, 1), new MoonCoefficient1(4, 0, 0, -1), new MoonCoefficient1(4, 0, -1, 1), new MoonCoefficient1(0, 0, 1, -3), new MoonCoefficient1(4, 0, -2, 1), new MoonCoefficient1(2, 0, 0, -3), new MoonCoefficient1(2, 0, 2, -1), new MoonCoefficient1(2, -1, 1, -1), new MoonCoefficient1(2, 0, -2, 1), new MoonCoefficient1(0, 0, 3, -1), new MoonCoefficient1(2, 0, 2, 1), new MoonCoefficient1(2, 0, -3, -1), new MoonCoefficient1(2, 1, -1, 1), new MoonCoefficient1(2, 1, 0, 1), new MoonCoefficient1(4, 0, 0, 1), new MoonCoefficient1(2, -1, 1, 1), new MoonCoefficient1(2, -2, 0, -1), new MoonCoefficient1(0, 0, 1, 3), new MoonCoefficient1(2, 1, 1, -1), new MoonCoefficient1(1, 1, 0, -1), new MoonCoefficient1(1, 1, 0, 1), new MoonCoefficient1(0, 1, -2, -1), new MoonCoefficient1(2, 1, -1, -1), new MoonCoefficient1(1, 0, 1, 1), new MoonCoefficient1(2, -1, -2, -1), new MoonCoefficient1(0, 1, 2, 1), new MoonCoefficient1(4, 0, -2, -1), new MoonCoefficient1(4, -1, -1, -1), new MoonCoefficient1(1, 0, 1, -1), new MoonCoefficient1(4, 0, 1, -1), new MoonCoefficient1(1, 0, -1, -1), new MoonCoefficient1(4, -1, 0, -1), new MoonCoefficient1(2, -2, 0, 1)]; - GFX.g_MoonCoefficients4 = [5128122, 280602, 277693, 173237, 55413, 46271, 32573, 17198, 9266, 8822, 8216, 4324, 4200, -3359, 2463, 2211, 2065, -1870, 1828, -1794, -1749, -1565, -1491, -1475, -1410, -1344, -1335, 1107, 1021, 833, 777, 671, 607, 596, 491, -451, 439, 422, 421, -366, -351, 331, 315, 302, -283, -229, 223, 223, -220, -220, -185, 181, -177, 176, 166, -164, 132, -119, 115, 107]; - GFX.g_MoonPerigeeApogeeCoefficients1 = [new MPAC(2, 0, 0, -1.6769, 0), new MPAC(4, 0, 0, 0.4589, 0), new MPAC(6, 0, 0, -0.1856, 0), new MPAC(8, 0, 0, 0.0883, 0), new MPAC(2, -1, 0, -0.0773, 0.00019), new MPAC(0, 1, 0, 0.0502, -0.00013), new MPAC(10, 0, 0, -0.046, 0), new MPAC(4, -1, 0, 0.0422, -0.00011), new MPAC(6, -1, 0, -0.0256, 0), new MPAC(12, 0, 0, 0.0253, 0), new MPAC(1, 0, 0, 0.0237, 0), new MPAC(8, -1, 0, 0.0162, 0), new MPAC(14, 0, 0, -0.0145, 0), new MPAC(0, 0, 2, 0.0129, 0), new MPAC(3, 0, 0, -0.0112, 0), new MPAC(10, -1, 0, -0.0104, 0), new MPAC(16, 0, 0, 0.0086, 0), new MPAC(12, -1, 0, 0.0069, 0), new MPAC(5, 0, 0, 0.0066, 0), new MPAC(2, 0, 2, -0.0053, 0), new MPAC(18, 0, 0, -0.0052, 0), new MPAC(14, -1, 0, -0.0046, 0), new MPAC(7, 0, 0, -0.0041, 0), new MPAC(2, 1, 0, 0.004, 0), new MPAC(20, 0, 0, 0.0032, 0), new MPAC(1, 1, 0, -0.0032, 0), new MPAC(16, -1, 0, 0.0031, 0), new MPAC(4, 1, 0, -0.0029, 0), new MPAC(9, 0, 0, 0.0027, 0), new MPAC(4, 0, 2, 0.0027, 0), new MPAC(2, -2, 0, -0.0027, 0), new MPAC(4, -2, 0, 0.0024, 0), new MPAC(6, -2, 0, -0.0021, 0), new MPAC(22, 0, 0, -0.0021, 0), new MPAC(18, -1, 0, -0.0021, 0), new MPAC(6, 1, 0, 0.0019, 0), new MPAC(11, 0, 0, -0.0018, 0), new MPAC(8, 1, 0, -0.0014, 0), new MPAC(4, 0, -2, -0.0014, 0), new MPAC(6, 0, 2, -0.0014, 0), new MPAC(3, 1, 0, 0.0014, 0), new MPAC(5, 1, 0, -0.0014, 0), new MPAC(13, 0, 0, 0.0013, 0), new MPAC(20, -1, 0, 0.0013, 0), new MPAC(3, 2, 0, 0.0011, 0), new MPAC(4, -2, 2, -0.0011, 0), new MPAC(1, 2, 0, -0.0011, 0), new MPAC(22, -1, 0, -0.0009, 0), new MPAC(0, 0, 4, -0.0008, 0), new MPAC(6, 0, -2, 0.0008, 0), new MPAC(2, 1, -2, 0.0008, 0), new MPAC(0, 2, 0, 0.0007, 0), new MPAC(0, -1, 2, 0.0007, 0), new MPAC(2, 0, 4, 0.0007, 0), new MPAC(0, -2, 2, -0.0006, 0), new MPAC(2, 2, -2, -0.0006, 0), new MPAC(24, 0, 0, 0.0006, 0), new MPAC(4, 0, -4, 0.0005, 0), new MPAC(2, 2, 0, 0.0005, 0), new MPAC(1, -1, 0, -0.0004, 0)]; - GFX.g_MoonPerigeeApogeeCoefficients2 = [new MPAC(2, 0, 0, 0.4392, 0), new MPAC(4, 0, 0, 0.0684, 0), new MPAC(0, 1, 0, 0.0456, -0.00011), new MPAC(2, -1, 0, 0.0426, -0.00011), new MPAC(0, 0, 2, 0.0212, 0), new MPAC(1, 0, 0, -0.0189, 0), new MPAC(6, 0, 0, 0.0144, 0), new MPAC(4, -1, 0, 0.0113, 0), new MPAC(2, 0, 2, 0.0047, 0), new MPAC(1, 1, 0, 0.0036, 0), new MPAC(8, 0, 0, 0.0035, 0), new MPAC(6, -1, 0, 0.0034, 0), new MPAC(2, 0, -2, -0.0034, 0), new MPAC(2, -2, 0, 0.0022, 0), new MPAC(3, 0, 0, -0.0017, 0), new MPAC(4, 0, 2, 0.0013, 0), new MPAC(8, -1, 0, 0.0011, 0), new MPAC(4, -2, 0, 0.001, 0), new MPAC(10, 0, 0, 0.0009, 0), new MPAC(3, 1, 0, 0.0007, 0), new MPAC(0, 2, 0, 0.0006, 0), new MPAC(2, 1, 0, 0.0005, 0), new MPAC(2, 2, 0, 0.0005, 0), new MPAC(6, 0, 2, 0.0004, 0), new MPAC(6, -2, 0, 0.0004, 0), new MPAC(10, -1, 0, 0.0004, 0), new MPAC(5, 0, 0, -0.0004, 0), new MPAC(4, 0, -2, -0.0004, 0), new MPAC(0, 1, 2, 0.0003, 0), new MPAC(12, 0, 0, 0.0003, 0), new MPAC(2, -1, 2, 0.0003, 0), new MPAC(1, -1, 0, -0.0003, 0)]; - GFX.g_MoonPerigeeApogeeCoefficients3 = [new MPAC(2, 0, 0, 63.224, 0), new MPAC(4, 0, 0, -6.99, 0), new MPAC(2, -1, 0, 2.834, 0), new MPAC(2, -1, 0, 0, -0.0071), new MPAC(6, 0, 0, 1.927, 0), new MPAC(1, 0, 0, -1.263, 0), new MPAC(8, 0, 0, -0.702, 0), new MPAC(0, 1, 0, 0.696, 0), new MPAC(0, 1, 0, 0, -0.0017), new MPAC(0, 0, 2, -0.69, 0), new MPAC(4, -1, 0, -0.629, 0), new MPAC(4, -1, 0, 0, 0.0016), new MPAC(2, 0, -2, -0.392, 0), new MPAC(10, 0, 0, 0.297, 0), new MPAC(6, -1, 0, 0.26, 0), new MPAC(3, 0, 0, 0.201, 0), new MPAC(2, 1, 0, -0.161, 0), new MPAC(1, 1, 0, 0.157, 0), new MPAC(12, 0, 0, -0.138, 0), new MPAC(8, -1, 0, -0.127, 0), new MPAC(2, 0, 2, 0.104, 0), new MPAC(2, -2, 0, 0.104, 0), new MPAC(5, 0, 0, -0.079, 0), new MPAC(14, 0, 0, 0.068, 0), new MPAC(10, -1, 0, 0.067, 0), new MPAC(4, 1, 0, 0.054, 0), new MPAC(12, -1, 0, -0.038, 0), new MPAC(4, -2, 0, -0.038, 0), new MPAC(7, 0, 0, 0.037, 0), new MPAC(4, 0, 2, -0.037, 0), new MPAC(16, 0, 0, -0.035, 0), new MPAC(3, 1, 0, -0.03, 0), new MPAC(1, -1, 0, 0.029, 0), new MPAC(6, 1, 0, -0.025, 0), new MPAC(0, 2, 0, 0.023, 0), new MPAC(14, -1, 0, 0.023, 0), new MPAC(2, 2, 0, -0.023, 0), new MPAC(6, -2, 0, 0.022, 0), new MPAC(2, -1, -2, -0.021, 0), new MPAC(9, 0, 0, -0.02, 0), new MPAC(18, 0, 0, 0.019, 0), new MPAC(6, 0, 2, 0.017, 0), new MPAC(0, -1, 2, 0.014, 0), new MPAC(16, -1, 0, -0.014, 0), new MPAC(4, 0, -20, 0.013, 0), new MPAC(8, 1, 0, 0.012, 0), new MPAC(11, 0, 0, 0.011, 0), new MPAC(5, 1, 0, 0.01, 0), new MPAC(20, 0, 0, -0.01, 0)]; - GFX.g_MoonPerigeeApogeeCoefficients4 = [new MPAC(2, 0, 0, -9.147, 0), new MPAC(1, 0, 0, -0.841, 0), new MPAC(0, 0, 2, 0.697, 0), new MPAC(0, 1, 0, -0.656, 0.0016), new MPAC(4, 0, 0, 0.355, 0), new MPAC(2, -1, 0, 0.159, 0), new MPAC(1, 1, 0, 0.127, 0), new MPAC(4, -1, 0, 0.065, 0), new MPAC(6, 0, 0, 0.052, 0), new MPAC(2, 1, 0, 0.043, 0), new MPAC(2, 0, 2, 0.031, 0), new MPAC(2, 0, -2, -0.023, 0), new MPAC(2, -2, 0, 0.022, 0), new MPAC(2, 2, 0, 0.019, 0), new MPAC(0, 2, 0, -0.016, 0), new MPAC(6, -1, 0, 0.014, 0), new MPAC(8, 0, 0, 0.01, 0)]; - GFX.g_L0NC = [new VSC(531188633, 0, 0), new VSC(1798476, 2.9010127, 38.1330356), new VSC(1019728, 0.4858092, 1.4844727), new VSC(124532, 4.830081, 36.648563), new VSC(42064, 5.41055, 2.96895), new VSC(37715, 6.09222, 35.16409), new VSC(33785, 1.24489, 76.26607), new VSC(16483, 8E-05, 491.55793), new VSC(9199, 4.9375, 39.6175), new VSC(8994, 0.2746, 175.1661), new VSC(4216, 1.9871, 73.2971), new VSC(3365, 1.0359, 33.6796), new VSC(2285, 4.2061, 4.4534), new VSC(1434, 2.7834, 74.7816), new VSC(900, 2.076, 109.946), new VSC(745, 3.19, 71.813), new VSC(506, 5.748, 114.399), new VSC(400, 0.35, 1021.249), new VSC(345, 3.462, 41.102), new VSC(340, 3.304, 77.751), new VSC(323, 2.248, 32.195), new VSC(306, 0.497, 0.521), new VSC(287, 4.505, 0.048), new VSC(282, 2.246, 146.594), new VSC(267, 4.889, 0.963), new VSC(252, 5.782, 388.465), new VSC(245, 1.247, 9.561), new VSC(233, 2.505, 137.033), new VSC(227, 1.797, 453.425), new VSC(170, 3.324, 108.461), new VSC(151, 2.192, 33.94), new VSC(150, 2.997, 5.938), new VSC(148, 0.859, 111.43), new VSC(119, 3.677, 2.448), new VSC(109, 2.416, 183.243), new VSC(103, 0.041, 0.261), new VSC(103, 4.404, 70.328), new VSC(102, 5.705, 0.112)]; - GFX.g_L1NC = [new VSC(3837687717, 0, 0), new VSC(16604, 4.86319, 1.48447), new VSC(15807, 2.27923, 38.13304), new VSC(3335, 3.682, 76.2661), new VSC(1306, 3.6732, 2.9689), new VSC(605, 1.505, 35.164), new VSC(179, 3.453, 39.618), new VSC(107, 2.451, 4.453), new VSC(106, 2.755, 33.68), new VSC(73, 5.49, 36.65), new VSC(57, 1.86, 114.4), new VSC(57, 5.22, 0.52), new VSC(35, 4.52, 74.78), new VSC(32, 5.9, 77.75), new VSC(30, 3.67, 388.47), new VSC(29, 5.17, 9.56), new VSC(29, 5.17, 2.45), new VSC(26, 5.25, 168.05)]; - GFX.g_L2NC = [new VSC(53893, 0, 0), new VSC(296, 1.855, 1.484), new VSC(281, 1.191, 38.133), new VSC(270, 5.721, 76.266), new VSC(23, 1.21, 2.97), new VSC(9, 4.43, 35.16), new VSC(7, 0.54, 2.45)]; - GFX.g_L3NC = [new VSC(31, 0, 0), new VSC(15, 1.35, 76.27), new VSC(12, 6.04, 1.48), new VSC(12, 6.11, 38.13)]; - GFX.g_L4NC = [new VSC(114, 3.142, 0)]; - GFX.g_B0NC = [new VSC(3088623, 1.4410437, 38.1330356), new VSC(27789, 5.91272, 76.26607), new VSC(27624, 0, 0), new VSC(15448, 3.50877, 39.61751), new VSC(15355, 2.52124, 36.64856), new VSC(2000, 1.51, 74.7816), new VSC(1968, 4.3778, 1.4845), new VSC(1015, 3.2156, 35.1641), new VSC(606, 2.802, 73.297), new VSC(595, 2.129, 41.102), new VSC(589, 3.187, 2.969), new VSC(402, 4.169, 114.399), new VSC(280, 1.682, 77.751), new VSC(262, 3.767, 213.299), new VSC(254, 3.271, 453.425), new VSC(206, 4.257, 529.691), new VSC(140, 3.53, 137.033)]; - GFX.g_B1NC = [new VSC(227279, 3.807931, 38.133036), new VSC(1803, 1.9758, 76.2661), new VSC(1433, 3.1416, 0), new VSC(1386, 4.8256, 36.6486), new VSC(1073, 6.0805, 39.6175), new VSC(148, 3.858, 74.782), new VSC(136, 0.478, 1.484), new VSC(70, 6.19, 35.16), new VSC(52, 5.05, 73.3), new VSC(43, 0.31, 114.4), new VSC(37, 4.89, 41.1), new VSC(37, 5.76, 2.97), new VSC(26, 5.22, 213.3)]; - GFX.g_B2NC = [new VSC(9691, 5.5712, 38.133), new VSC(79, 3.63, 76.27), new VSC(72, 0.45, 36.65), new VSC(59, 3.14, 0), new VSC(30, 1.61, 39.62), new VSC(6, 5.61, 74.78)]; - GFX.g_B3NC = [new VSC(273, 1.017, 38.133), new VSC(2, 0, 0), new VSC(2, 2.37, 36.65), new VSC(2, 5.33, 76.27)]; - GFX.g_B4NC = [new VSC(6, 2.67, 38.13)]; - GFX.g_R0NC = [new VSC(3007013206, 0, 0), new VSC(27062259, 1.32999459, 38.13303564), new VSC(1691764, 3.2518614, 36.6485629), new VSC(807831, 5.185928, 1.484473), new VSC(537761, 4.521139, 35.16409), new VSC(495726, 1.571057, 491.557929), new VSC(274572, 1.845523, 175.16606), new VSC(135134, 3.372206, 39.617508), new VSC(121802, 5.797544, 76.266071), new VSC(100895, 0.377027, 73.297126), new VSC(69792, 3.79617, 2.96895), new VSC(46688, 5.74938, 33.67962), new VSC(24594, 0.50802, 109.94569), new VSC(16939, 1.59422, 71.81265), new VSC(14230, 1.07786, 74.7816), new VSC(12012, 1.92062, 1021.24889), new VSC(8395, 0.6782, 146.5943), new VSC(7572, 1.0715, 388.4652), new VSC(5721, 2.5906, 4.4534), new VSC(4840, 1.9069, 41.102), new VSC(4483, 2.9057, 529.691), new VSC(4421, 1.7499, 108.4612), new VSC(4354, 0.6799, 32.1951), new VSC(4270, 3.4134, 453.4249), new VSC(3381, 0.8481, 183.2428), new VSC(2881, 1.986, 137.033), new VSC(2879, 3.6742, 350.3321), new VSC(2636, 3.0976, 213.2991), new VSC(2530, 5.7984, 490.0735), new VSC(2523, 0.4863, 493.0424), new VSC(2306, 2.8096, 70.3282), new VSC(2087, 0.6186, 33.9402)]; - GFX.g_R1NC = [new VSC(236339, 0.70498, 38.133036), new VSC(13220, 3.32015, 1.48447), new VSC(8622, 6.2163, 35.1641), new VSC(2702, 1.8814, 39.6175), new VSC(2155, 2.0943, 2.9689), new VSC(2153, 5.1687, 76.2661), new VSC(1603, 0, 0), new VSC(1464, 1.1842, 33.6796), new VSC(1136, 3.9189, 36.6486), new VSC(898, 5.241, 388.465), new VSC(790, 0.533, 168.053), new VSC(760, 0.021, 182.28), new VSC(607, 1.077, 1021.249), new VSC(572, 3.401, 484.444), new VSC(561, 2.887, 498.671)]; - GFX.g_R2NC = [new VSC(4247, 5.8991, 38.133), new VSC(218, 0.346, 1.484), new VSC(163, 2.239, 168.053), new VSC(156, 4.594, 182.28), new VSC(127, 2.848, 35.164)]; - GFX.g_R3NC = [new VSC(166, 4.552, 38.133)]; - GFX.g_NuC = [new NUC(0, 0, 0, 0, 1, -171996, -174.2, 92025, 8.9), new NUC(-2, 0, 0, 2, 2, -13187, -1.6, 5736, -3.1), new NUC(0, 0, 0, 2, 2, -2274, -0.2, 977, -0.5), new NUC(0, 0, 0, 0, 2, 2062, 0.2, -895, 0.5), new NUC(0, 1, 0, 0, 0, 1426, -3.4, 54, -0.1), new NUC(0, 0, 1, 0, 0, 712, 0.1, -7, 0), new NUC(-2, 1, 0, 2, 2, -517, 1.2, 224, -0.6), new NUC(0, 0, 0, 2, 1, -386, -0.4, 200, 0), new NUC(0, 0, 1, 2, 2, -301, 0, 129, -0.1), new NUC(-2, -1, 0, 2, 2, 217, -0.5, -95, 0.3), new NUC(-2, 0, 1, 0, 0, -158, 0, 0, 0), new NUC(-2, 0, 0, 2, 1, 129, 0.1, -70, 0), new NUC(0, 0, -1, 2, 2, 123, 0, -53, 0), new NUC(2, 0, 0, 0, 0, 63, 0, 0, 0), new NUC(0, 0, 1, 0, 1, 63, 0.1, -33, 0), new NUC(2, 0, -1, 2, 2, -59, 0, 26, 0), new NUC(0, 0, -1, 0, 1, -58, -0.1, 32, 0), new NUC(0, 0, 1, 2, 1, -51, 0, 27, 0), new NUC(-2, 0, 2, 0, 0, 48, 0, 0, 0), new NUC(0, 0, -2, 2, 1, 46, 0, -24, 0), new NUC(2, 0, 0, 2, 2, -38, 0, 16, 0), new NUC(0, 0, 2, 2, 2, -31, 0, 13, 0), new NUC(0, 0, 2, 0, 0, 29, 0, 0, 0), new NUC(-2, 0, 1, 2, 2, 29, 0, -12, 0), new NUC(0, 0, 0, 2, 0, 26, 0, 0, 0), new NUC(-2, 0, 0, 2, 0, -22, 0, 0, 0), new NUC(0, 0, -1, 2, 1, 21, 0, -10, 0), new NUC(0, 2, 0, 0, 0, 17, -0.1, 0, 0), new NUC(2, 0, -1, 0, 1, 16, 0, -8, 0), new NUC(-2, 2, 0, 2, 2, -16, 0.1, 7, 0), new NUC(0, 1, 0, 0, 1, -15, 0, 9, 0), new NUC(-2, 0, 1, 0, 1, -13, 0, 7, 0), new NUC(0, -1, 0, 0, 1, -12, 0, 6, 0), new NUC(0, 0, 2, -2, 0, 11, 0, 0, 0), new NUC(2, 0, -1, 2, 1, -10, 0, 5, 0), new NUC(2, 0, 1, 2, 2, -8, 0, 3, 0), new NUC(0, 1, 0, 2, 2, 7, 0, -3, 0), new NUC(-2, 1, 1, 0, 0, -7, 0, 0, 0), new NUC(0, -1, 0, 2, 2, -7, 0, 3, 0), new NUC(2, 0, 0, 2, 1, -7, 0, 3, 0), new NUC(2, 0, 1, 0, 0, 6, 0, 0, 0), new NUC(-2, 0, 2, 2, 2, 6, 0, -3, 0), new NUC(-2, 0, 1, 2, 1, 6, 0, -3, 0), new NUC(2, 0, -2, 0, 1, -6, 0, 3, 0), new NUC(2, 0, 0, 0, 1, -6, 0, 3, 0), new NUC(0, -1, 1, 0, 0, 5, 0, 0, 0), new NUC(-2, -1, 0, 2, 1, -5, 0, 3, 0), new NUC(-2, 0, 0, 0, 1, -5, 0, 3, 0), new NUC(0, 0, 2, 2, 1, -5, 0, 3, 0), new NUC(-2, 0, 2, 0, 1, 4, 0, 0, 0), new NUC(-2, 1, 0, 2, 1, 4, 0, 0, 0), new NUC(0, 0, 1, -2, 0, 4, 0, 0, 0), new NUC(-1, 0, 1, 0, 0, -4, 0, 0, 0), new NUC(-2, 1, 0, 0, 0, -4, 0, 0, 0), new NUC(1, 0, 0, 0, 0, -4, 0, 0, 0), new NUC(0, 0, 1, 2, 0, 3, 0, 0, 0), new NUC(0, 0, -2, 2, 2, -3, 0, 0, 0), new NUC(-1, -1, 1, 0, 0, -3, 0, 0, 0), new NUC(0, 1, 1, 0, 0, -3, 0, 0, 0), new NUC(0, -1, 1, 2, 2, -3, 0, 0, 0), new NUC(2, -1, -1, 2, 2, -3, 0, 0, 0), new NUC(0, 0, 3, 2, 2, -3, 0, 0, 0), new NUC(2, -1, 0, 2, 2, -3, 0, 0, 0)]; - GFX.g_AAParallax_C1 = Math.sin(CT.d2R(CT.dmS2D(0, 0, 8.794))); - GFX.g_PlutoArgumentCoefficients = [new PlutoCoefficient1(0, 0, 1), new PlutoCoefficient1(0, 0, 2), new PlutoCoefficient1(0, 0, 3), new PlutoCoefficient1(0, 0, 4), new PlutoCoefficient1(0, 0, 5), new PlutoCoefficient1(0, 0, 6), new PlutoCoefficient1(0, 1, -1), new PlutoCoefficient1(0, 1, 0), new PlutoCoefficient1(0, 1, 1), new PlutoCoefficient1(0, 1, 2), new PlutoCoefficient1(0, 1, 3), new PlutoCoefficient1(0, 2, -2), new PlutoCoefficient1(0, 2, -1), new PlutoCoefficient1(0, 2, 0), new PlutoCoefficient1(1, -1, 0), new PlutoCoefficient1(1, -1, 1), new PlutoCoefficient1(1, 0, -3), new PlutoCoefficient1(1, 0, -2), new PlutoCoefficient1(1, 0, -1), new PlutoCoefficient1(1, 0, 0), new PlutoCoefficient1(1, 0, 1), new PlutoCoefficient1(1, 0, 2), new PlutoCoefficient1(1, 0, 3), new PlutoCoefficient1(1, 0, 4), new PlutoCoefficient1(1, 1, -3), new PlutoCoefficient1(1, 1, -2), new PlutoCoefficient1(1, 1, -1), new PlutoCoefficient1(1, 1, 0), new PlutoCoefficient1(1, 1, 1), new PlutoCoefficient1(1, 1, 3), new PlutoCoefficient1(2, 0, -6), new PlutoCoefficient1(2, 0, -5), new PlutoCoefficient1(2, 0, -4), new PlutoCoefficient1(2, 0, -3), new PlutoCoefficient1(2, 0, -2), new PlutoCoefficient1(2, 0, -1), new PlutoCoefficient1(2, 0, 0), new PlutoCoefficient1(2, 0, 1), new PlutoCoefficient1(2, 0, 2), new PlutoCoefficient1(2, 0, 3), new PlutoCoefficient1(3, 0, -2), new PlutoCoefficient1(3, 0, -1), new PlutoCoefficient1(3, 0, 0)]; - GFX.g_PlutoLongitudeCoefficients = [new PlutoCoefficient2(-19799805, 19850055), new PlutoCoefficient2(897144, -4954829), new PlutoCoefficient2(611149, 1211027), new PlutoCoefficient2(-341243, -189585), new PlutoCoefficient2(129287, -34992), new PlutoCoefficient2(-38164, 30893), new PlutoCoefficient2(20442, -9987), new PlutoCoefficient2(-4063, -5071), new PlutoCoefficient2(-6016, -3336), new PlutoCoefficient2(-3956, 3039), new PlutoCoefficient2(-667, 3572), new PlutoCoefficient2(1276, 501), new PlutoCoefficient2(1152, -917), new PlutoCoefficient2(630, -1277), new PlutoCoefficient2(2571, -459), new PlutoCoefficient2(899, -1449), new PlutoCoefficient2(-1016, 1043), new PlutoCoefficient2(-2343, -1012), new PlutoCoefficient2(7042, 788), new PlutoCoefficient2(1199, -338), new PlutoCoefficient2(418, -67), new PlutoCoefficient2(120, -274), new PlutoCoefficient2(-60, -159), new PlutoCoefficient2(-82, -29), new PlutoCoefficient2(-36, -29), new PlutoCoefficient2(-40, 7), new PlutoCoefficient2(-14, 22), new PlutoCoefficient2(4, 13), new PlutoCoefficient2(5, 2), new PlutoCoefficient2(-1, 0), new PlutoCoefficient2(2, 0), new PlutoCoefficient2(-4, 5), new PlutoCoefficient2(4, -7), new PlutoCoefficient2(14, 24), new PlutoCoefficient2(-49, -34), new PlutoCoefficient2(163, -48), new PlutoCoefficient2(9, -24), new PlutoCoefficient2(-4, 1), new PlutoCoefficient2(-3, 1), new PlutoCoefficient2(1, 3), new PlutoCoefficient2(-3, -1), new PlutoCoefficient2(5, -3), new PlutoCoefficient2(0, 0)]; - GFX.g_PlutoLatitudeCoefficients = [new PlutoCoefficient2(-5452852, -14974862), new PlutoCoefficient2(3527812, 1672790), new PlutoCoefficient2(-1050748, 327647), new PlutoCoefficient2(178690, -292153), new PlutoCoefficient2(18650, 100340), new PlutoCoefficient2(-30697, -25823), new PlutoCoefficient2(4878, 11248), new PlutoCoefficient2(226, -64), new PlutoCoefficient2(2030, -836), new PlutoCoefficient2(69, -604), new PlutoCoefficient2(-247, -567), new PlutoCoefficient2(-57, 1), new PlutoCoefficient2(-122, 175), new PlutoCoefficient2(-49, -164), new PlutoCoefficient2(-197, 199), new PlutoCoefficient2(-25, 217), new PlutoCoefficient2(589, -248), new PlutoCoefficient2(-269, 711), new PlutoCoefficient2(185, 193), new PlutoCoefficient2(315, 807), new PlutoCoefficient2(-130, -43), new PlutoCoefficient2(5, 3), new PlutoCoefficient2(2, 17), new PlutoCoefficient2(2, 5), new PlutoCoefficient2(2, 3), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(2, -1), new PlutoCoefficient2(1, -1), new PlutoCoefficient2(0, -1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-7, 0), new PlutoCoefficient2(10, -8), new PlutoCoefficient2(-3, 20), new PlutoCoefficient2(6, 5), new PlutoCoefficient2(14, 17), new PlutoCoefficient2(-2, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(0, 1), new PlutoCoefficient2(0, 0), new PlutoCoefficient2(1, 0)]; - GFX.g_PlutoRadiusCoefficients = [new PlutoCoefficient2(66865439, 68951812), new PlutoCoefficient2(-11827535, -332538), new PlutoCoefficient2(1593179, -1438890), new PlutoCoefficient2(-18444, 483220), new PlutoCoefficient2(-65977, -85431), new PlutoCoefficient2(31174, -6032), new PlutoCoefficient2(-5794, 22161), new PlutoCoefficient2(4601, 4032), new PlutoCoefficient2(-1729, 234), new PlutoCoefficient2(-415, 702), new PlutoCoefficient2(239, 723), new PlutoCoefficient2(67, -67), new PlutoCoefficient2(1034, -451), new PlutoCoefficient2(-129, 504), new PlutoCoefficient2(480, -231), new PlutoCoefficient2(2, -441), new PlutoCoefficient2(-3359, 265), new PlutoCoefficient2(7856, -7832), new PlutoCoefficient2(36, 45763), new PlutoCoefficient2(8663, 8547), new PlutoCoefficient2(-809, -769), new PlutoCoefficient2(263, -144), new PlutoCoefficient2(-126, 32), new PlutoCoefficient2(-35, -16), new PlutoCoefficient2(-19, -4), new PlutoCoefficient2(-15, 8), new PlutoCoefficient2(-4, 12), new PlutoCoefficient2(5, 6), new PlutoCoefficient2(3, 1), new PlutoCoefficient2(6, -2), new PlutoCoefficient2(2, 2), new PlutoCoefficient2(-2, -2), new PlutoCoefficient2(14, 13), new PlutoCoefficient2(-63, 13), new PlutoCoefficient2(136, -236), new PlutoCoefficient2(273, 1065), new PlutoCoefficient2(251, 149), new PlutoCoefficient2(-25, -9), new PlutoCoefficient2(9, -2), new PlutoCoefficient2(-8, 7), new PlutoCoefficient2(2, -10), new PlutoCoefficient2(19, 35), new PlutoCoefficient2(10, 3)]; - GFX.g_L0SaturnCoefficients = [new VSC(87401354, 0, 0), new VSC(11107660, 3.9620509, 213.29909544), new VSC(1414151, 4.5858152, 7.113547), new VSC(398379, 0.52112, 206.185548), new VSC(350769, 3.303299, 426.598191), new VSC(206816, 0.246584, 103.092774), new VSC(79271, 3.84007, 220.41264), new VSC(23990, 4.66977, 110.20632), new VSC(16574, 0.43719, 419.48464), new VSC(15820, 0.93809, 632.78374), new VSC(15054, 2.7167, 639.89729), new VSC(14907, 5.76903, 316.39187), new VSC(14610, 1.56519, 3.93215), new VSC(13160, 4.44891, 14.22709), new VSC(13005, 5.98119, 11.0457), new VSC(10725, 3.1294, 202.2534), new VSC(6126, 1.7633, 277.035), new VSC(5863, 0.2366, 529.691), new VSC(5228, 4.2078, 3.1814), new VSC(5020, 3.1779, 433.7117), new VSC(4593, 0.6198, 199.072), new VSC(4006, 2.2448, 63.7359), new VSC(3874, 3.2228, 138.5175), new VSC(3269, 0.7749, 949.1756), new VSC(2954, 0.9828, 95.9792), new VSC(2461, 2.0316, 735.8765), new VSC(1758, 3.2658, 522.5774), new VSC(1640, 5.505, 846.0828), new VSC(1581, 4.3727, 309.2783), new VSC(1391, 4.0233, 323.5054), new VSC(1124, 2.8373, 415.5525), new VSC(1087, 4.1834, 2.4477), new VSC(1017, 3.717, 227.5262), new VSC(957, 0.507, 1265.567), new VSC(853, 3.421, 175.166), new VSC(849, 3.191, 209.367), new VSC(789, 5.007, 0.963), new VSC(749, 2.144, 853.196), new VSC(744, 5.253, 224.345), new VSC(687, 1.747, 1052.268), new VSC(654, 1.599, 0.048), new VSC(634, 2.299, 412.371), new VSC(625, 0.97, 210.118), new VSC(580, 3.093, 74.782), new VSC(546, 2.127, 350.332), new VSC(543, 1.518, 9.561), new VSC(530, 4.449, 117.32), new VSC(478, 2.965, 137.033), new VSC(474, 5.475, 742.99), new VSC(452, 1.044, 490.334), new VSC(449, 1.29, 127.472), new VSC(372, 2.278, 217.231), new VSC(355, 3.013, 838.969), new VSC(347, 1.539, 340.771), new VSC(343, 0.246, 0.521), new VSC(330, 0.247, 1581.959), new VSC(322, 0.961, 203.738), new VSC(322, 2.572, 647.011), new VSC(309, 3.495, 216.48), new VSC(287, 2.37, 351.817), new VSC(278, 0.4, 211.815), new VSC(249, 1.47, 1368.66), new VSC(227, 4.91, 12.53), new VSC(220, 4.204, 200.769), new VSC(209, 1.345, 625.67), new VSC(208, 0.483, 1162.475), new VSC(208, 1.283, 39.357), new VSC(204, 6.011, 265.989), new VSC(185, 3.503, 149.563), new VSC(184, 0.973, 4.193), new VSC(182, 5.491, 2.921), new VSC(174, 1.863, 0.751), new VSC(165, 0.44, 5.417), new VSC(149, 5.736, 52.69), new VSC(148, 1.535, 5.629), new VSC(146, 6.231, 195.14), new VSC(140, 4.295, 21.341), new VSC(131, 4.068, 10.295), new VSC(125, 6.277, 1898.351), new VSC(122, 1.976, 4.666), new VSC(118, 5.341, 554.07), new VSC(117, 2.679, 1155.361), new VSC(114, 5.594, 1059.382), new VSC(112, 1.105, 191.208), new VSC(110, 0.166, 1.484), new VSC(109, 3.438, 536.805), new VSC(107, 4.012, 956.289), new VSC(104, 2.192, 88.866), new VSC(103, 1.197, 1685.052), new VSC(101, 4.965, 269.921)]; - GFX.g_L1SaturnCoefficients = [new VSC(21354295596, 0, 0), new VSC(1296855, 1.8282054, 213.2990954), new VSC(564348, 2.885001, 7.113547), new VSC(107679, 2.277699, 206.185548), new VSC(98323, 1.0807, 426.59819), new VSC(40255, 2.04128, 220.41264), new VSC(19942, 1.27955, 103.09277), new VSC(10512, 2.7488, 14.22709), new VSC(6939, 0.4049, 639.8973), new VSC(4803, 2.4419, 419.4846), new VSC(4056, 2.9217, 110.2063), new VSC(3769, 3.6497, 3.9322), new VSC(3385, 2.4169, 3.1814), new VSC(3302, 1.2626, 433.7117), new VSC(3071, 2.3274, 199.072), new VSC(1953, 3.5639, 11.0457), new VSC(1249, 2.628, 95.9792), new VSC(922, 1.961, 227.526), new VSC(706, 4.417, 529.691), new VSC(650, 6.174, 202.253), new VSC(628, 6.111, 309.278), new VSC(487, 6.04, 853.196), new VSC(479, 4.988, 522.577), new VSC(468, 4.617, 63.736), new VSC(417, 2.117, 323.505), new VSC(408, 1.299, 209.367), new VSC(352, 2.317, 632.784), new VSC(344, 3.959, 412.371), new VSC(340, 3.634, 316.392), new VSC(336, 3.772, 735.877), new VSC(332, 2.861, 210.118), new VSC(289, 2.733, 117.32), new VSC(281, 5.744, 2.448), new VSC(266, 0.543, 647.011), new VSC(230, 1.644, 216.48), new VSC(192, 2.965, 224.345), new VSC(173, 4.077, 846.083), new VSC(167, 2.597, 21.341), new VSC(136, 2.286, 10.295), new VSC(131, 3.441, 742.99), new VSC(128, 4.095, 217.231), new VSC(109, 6.161, 415.552), new VSC(98, 4.73, 838.97), new VSC(94, 3.48, 1052.27), new VSC(92, 3.95, 88.87), new VSC(87, 1.22, 440.83), new VSC(83, 3.11, 625.67), new VSC(78, 6.24, 302.16), new VSC(67, 0.29, 4.67), new VSC(66, 5.65, 9.56), new VSC(62, 4.29, 127.47), new VSC(62, 1.83, 195.14), new VSC(58, 2.48, 191.96), new VSC(57, 5.02, 137.03), new VSC(55, 0.28, 74.78), new VSC(54, 5.13, 490.33), new VSC(51, 1.46, 536.8), new VSC(47, 1.18, 149.56), new VSC(47, 5.15, 515.46), new VSC(46, 2.23, 956.29), new VSC(44, 2.71, 5.42), new VSC(40, 0.41, 269.92), new VSC(40, 3.89, 728.76), new VSC(38, 0.65, 422.67), new VSC(38, 2.53, 12.53), new VSC(37, 3.78, 2.92), new VSC(35, 6.08, 5.63), new VSC(34, 3.21, 1368.66), new VSC(33, 4.64, 277.03), new VSC(33, 5.43, 1066.5), new VSC(33, 0.3, 351.82), new VSC(32, 4.39, 1155.36), new VSC(31, 2.43, 52.69), new VSC(30, 2.84, 203), new VSC(30, 6.19, 284.15), new VSC(30, 3.39, 1059.38), new VSC(29, 2.03, 330.62), new VSC(28, 2.74, 265.99), new VSC(26, 4.51, 340.77)]; - GFX.g_L2SaturnCoefficients = [new VSC(116441, 1.179879, 7.113547), new VSC(91921, 0.07425, 213.2991), new VSC(90592, 0, 0), new VSC(15277, 4.06492, 206.18555), new VSC(10631, 0.25778, 220.41264), new VSC(10605, 5.40964, 426.59819), new VSC(4265, 1.046, 14.2271), new VSC(1216, 2.9186, 103.0928), new VSC(1165, 4.6094, 639.8973), new VSC(1082, 5.6913, 433.7117), new VSC(1045, 4.0421, 199.072), new VSC(1020, 0.6337, 3.1814), new VSC(634, 4.388, 419.485), new VSC(549, 5.573, 3.932), new VSC(457, 1.268, 110.206), new VSC(425, 0.209, 227.526), new VSC(274, 4.288, 95.979), new VSC(162, 1.381, 11.046), new VSC(129, 1.566, 309.278), new VSC(117, 3.881, 853.196), new VSC(105, 4.9, 647.011), new VSC(101, 0.893, 21.341), new VSC(96, 2.91, 316.39), new VSC(95, 5.63, 412.37), new VSC(85, 5.73, 209.37), new VSC(83, 6.05, 216.48), new VSC(82, 1.02, 117.32), new VSC(75, 4.76, 210.12), new VSC(67, 0.46, 522.58), new VSC(66, 0.48, 10.29), new VSC(64, 0.35, 323.51), new VSC(61, 4.88, 632.78), new VSC(53, 2.75, 529.69), new VSC(46, 5.69, 440.83), new VSC(45, 1.67, 202.25), new VSC(42, 5.71, 88.87), new VSC(32, 0.07, 63.74), new VSC(32, 1.67, 302.16), new VSC(31, 4.16, 191.96), new VSC(27, 0.83, 224.34), new VSC(25, 5.66, 735.88), new VSC(20, 5.94, 217.23), new VSC(18, 4.9, 625.67), new VSC(17, 1.63, 742.99), new VSC(16, 0.58, 515.46), new VSC(14, 0.21, 838.97), new VSC(14, 3.76, 195.14), new VSC(12, 4.72, 203), new VSC(12, 0.13, 234.64), new VSC(12, 3.12, 846.08), new VSC(11, 5.92, 536.8), new VSC(11, 5.6, 728.76), new VSC(11, 3.2, 1066.5), new VSC(10, 4.99, 422.67), new VSC(10, 0.26, 330.62), new VSC(10, 4.15, 860.31), new VSC(9, 0.46, 956.29), new VSC(8, 2.14, 269.92), new VSC(8, 5.25, 429.78), new VSC(8, 4.03, 9.56), new VSC(7, 5.4, 1052.27), new VSC(6, 4.46, 284.15), new VSC(6, 5.93, 405.26)]; - GFX.g_L3SaturnCoefficients = [new VSC(16039, 5.73945, 7.11355), new VSC(4250, 4.5854, 213.2991), new VSC(1907, 4.7608, 220.4126), new VSC(1466, 5.9133, 206.1855), new VSC(1162, 5.6197, 14.2271), new VSC(1067, 3.6082, 426.5982), new VSC(239, 3.861, 433.712), new VSC(237, 5.768, 199.072), new VSC(166, 5.116, 3.181), new VSC(151, 2.736, 639.897), new VSC(131, 4.743, 227.526), new VSC(63, 0.23, 419.48), new VSC(62, 4.74, 103.09), new VSC(40, 5.47, 21.34), new VSC(40, 5.96, 95.98), new VSC(39, 5.83, 110.21), new VSC(28, 3.01, 647.01), new VSC(25, 0.99, 3.93), new VSC(19, 1.92, 853.2), new VSC(18, 4.97, 10.29), new VSC(18, 1.03, 412.37), new VSC(18, 4.2, 216.48), new VSC(18, 3.32, 309.28), new VSC(16, 3.9, 440.83), new VSC(16, 5.62, 117.32), new VSC(13, 1.18, 88.87), new VSC(11, 5.58, 11.05), new VSC(11, 5.93, 191.96), new VSC(10, 3.95, 209.37), new VSC(9, 3.39, 302.16), new VSC(8, 4.88, 323.51), new VSC(7, 0.38, 632.78), new VSC(6, 2.25, 522.58), new VSC(6, 1.06, 210.12), new VSC(5, 4.64, 234.64), new VSC(4, 3.14, 0), new VSC(4, 2.31, 515.46), new VSC(3, 2.2, 860.31), new VSC(3, 0.59, 529.69), new VSC(3, 4.93, 224.34), new VSC(3, 0.42, 625.67), new VSC(2, 4.77, 330.62), new VSC(2, 3.35, 429.78), new VSC(2, 3.2, 202.25), new VSC(2, 1.19, 1066.5), new VSC(2, 1.35, 405.26), new VSC(2, 4.16, 223.59), new VSC(2, 3.07, 654.12)]; - GFX.g_L4SaturnCoefficients = [new VSC(1662, 3.9983, 7.1135), new VSC(257, 2.984, 220.413), new VSC(236, 3.902, 14.227), new VSC(149, 2.741, 213.299), new VSC(114, 3.142, 0), new VSC(110, 1.515, 206.186), new VSC(68, 1.72, 426.6), new VSC(40, 2.05, 433.71), new VSC(38, 1.24, 199.07), new VSC(31, 3.01, 227.53), new VSC(15, 0.83, 639.9), new VSC(9, 3.71, 21.34), new VSC(6, 2.42, 419.48), new VSC(6, 1.16, 647.01), new VSC(4, 1.45, 95.98), new VSC(4, 2.12, 440.83), new VSC(3, 4.09, 110.21), new VSC(3, 2.77, 412.37), new VSC(3, 3.01, 88.87), new VSC(3, 0, 853.2), new VSC(3, 0.39, 103.09), new VSC(2, 3.78, 117.32), new VSC(2, 2.83, 234.64), new VSC(2, 5.08, 309.28), new VSC(2, 2.24, 216.48), new VSC(2, 5.19, 302.16), new VSC(1, 1.55, 191.96)]; - GFX.g_L5SaturnCoefficients = [new VSC(124, 2.259, 7.114), new VSC(34, 2.16, 14.23), new VSC(28, 1.2, 220.41), new VSC(6, 1.22, 227.53), new VSC(5, 0.24, 433.71), new VSC(4, 6.23, 426.6), new VSC(3, 2.97, 199.07), new VSC(3, 4.29, 206.19), new VSC(2, 6.25, 213.3), new VSC(1, 5.28, 639.9), new VSC(1, 0.24, 440.83), new VSC(1, 3.14, 0)]; - GFX.g_B0SaturnCoefficients = [new VSC(4330678, 3.6028443, 213.2990954), new VSC(240348, 2.852385, 426.598191), new VSC(84746, 0, 0), new VSC(34116, 0.57297, 206.18555), new VSC(30863, 3.48442, 220.41264), new VSC(14734, 2.11847, 639.89729), new VSC(9917, 5.79, 419.4846), new VSC(6994, 4.736, 7.1135), new VSC(4808, 5.4331, 316.3919), new VSC(4788, 4.9651, 110.2063), new VSC(3432, 2.7326, 433.7117), new VSC(1506, 6.013, 103.0928), new VSC(1060, 5.631, 529.691), new VSC(969, 5.204, 632.784), new VSC(942, 1.396, 853.196), new VSC(708, 3.803, 323.505), new VSC(552, 5.131, 202.253), new VSC(400, 3.359, 227.526), new VSC(319, 3.626, 209.367), new VSC(316, 1.997, 647.011), new VSC(314, 0.465, 217.231), new VSC(284, 4.886, 224.345), new VSC(236, 2.139, 11.046), new VSC(215, 5.95, 846.083), new VSC(209, 2.12, 415.552), new VSC(207, 0.73, 199.072), new VSC(179, 2.954, 63.736), new VSC(141, 0.644, 490.334), new VSC(139, 4.595, 14.227), new VSC(139, 1.998, 735.877), new VSC(135, 5.245, 742.99), new VSC(122, 3.115, 522.577), new VSC(116, 3.109, 216.48), new VSC(114, 0.963, 210.118)]; - GFX.g_B1SaturnCoefficients = [new VSC(397555, 5.3329, 213.299095), new VSC(49479, 3.14159, 0), new VSC(18572, 6.09919, 426.59819), new VSC(14801, 2.30586, 206.18555), new VSC(9644, 1.6967, 220.4126), new VSC(3757, 1.2543, 419.4846), new VSC(2717, 5.9117, 639.8973), new VSC(1455, 0.8516, 433.7117), new VSC(1291, 2.9177, 7.1135), new VSC(853, 0.436, 316.392), new VSC(298, 0.919, 632.784), new VSC(292, 5.316, 853.196), new VSC(284, 1.619, 227.526), new VSC(275, 3.889, 103.093), new VSC(172, 0.052, 647.011), new VSC(166, 2.444, 199.072), new VSC(158, 5.209, 110.206), new VSC(128, 1.207, 529.691), new VSC(110, 2.457, 217.231), new VSC(82, 2.76, 210.12), new VSC(81, 2.86, 14.23), new VSC(69, 1.66, 202.25), new VSC(65, 1.26, 216.48), new VSC(61, 1.25, 209.37), new VSC(59, 1.82, 323.51), new VSC(46, 0.82, 440.83), new VSC(36, 1.82, 224.34), new VSC(34, 2.84, 117.32), new VSC(33, 1.31, 412.37), new VSC(32, 1.19, 846.08), new VSC(27, 4.65, 1066.5), new VSC(27, 4.44, 11.05)]; - GFX.g_B2SaturnCoefficients = [new VSC(20630, 0.50482, 213.2991), new VSC(3720, 3.9983, 206.1855), new VSC(1627, 6.1819, 220.4126), new VSC(1346, 0, 0), new VSC(706, 3.039, 419.485), new VSC(365, 5.099, 426.598), new VSC(330, 5.279, 433.712), new VSC(219, 3.828, 639.897), new VSC(139, 1.043, 7.114), new VSC(104, 6.157, 227.526), new VSC(93, 1.98, 316.39), new VSC(71, 4.15, 199.07), new VSC(52, 2.88, 632.78), new VSC(49, 4.43, 647.01), new VSC(41, 3.16, 853.2), new VSC(29, 4.53, 210.12), new VSC(24, 1.12, 14.23), new VSC(21, 4.35, 217.23), new VSC(20, 5.31, 440.83), new VSC(18, 0.85, 110.21), new VSC(17, 5.68, 216.48), new VSC(16, 4.26, 103.09), new VSC(14, 3, 412.37), new VSC(12, 2.53, 529.69), new VSC(8, 3.32, 202.25), new VSC(7, 5.56, 209.37), new VSC(7, 0.29, 323.51), new VSC(6, 1.16, 117.32), new VSC(6, 3.61, 869.31)]; - GFX.g_B3SaturnCoefficients = [new VSC(666, 1.99, 213.299), new VSC(632, 5.698, 206.186), new VSC(398, 0, 0), new VSC(188, 4.338, 220.413), new VSC(92, 4.84, 419.48), new VSC(52, 3.42, 433.71), new VSC(42, 2.38, 426.6), new VSC(26, 4.4, 227.53), new VSC(21, 5.85, 199.07), new VSC(18, 1.99, 639.9), new VSC(11, 5.37, 7.11), new VSC(10, 2.55, 647.01), new VSC(7, 3.46, 316.39), new VSC(6, 4.8, 632.78), new VSC(6, 0.02, 210.12), new VSC(6, 3.52, 440.83), new VSC(5, 5.64, 14.23), new VSC(5, 1.22, 853.2), new VSC(4, 4.71, 412.37), new VSC(3, 0.63, 103.09), new VSC(2, 3.72, 216.48)]; - GFX.g_B4SaturnCoefficients = [new VSC(80, 1.12, 206.19), new VSC(32, 3.12, 213.3), new VSC(17, 2.48, 220.41), new VSC(12, 3.14, 0), new VSC(9, 0.38, 419.48), new VSC(6, 1.56, 433.71), new VSC(5, 2.63, 227.53), new VSC(5, 1.28, 199.07), new VSC(1, 1.43, 426.6), new VSC(1, 0.67, 647.01), new VSC(1, 1.72, 440.83), new VSC(1, 6.18, 639.9)]; - GFX.g_B5SaturnCoefficients = [new VSC(8, 2.82, 206.19), new VSC(1, 0.51, 220.41)]; - GFX.g_R0SaturnCoefficients = [new VSC(955758136, 0, 0), new VSC(52921382, 2.3922622, 213.29909544), new VSC(1873680, 5.2354961, 206.1855484), new VSC(1464664, 1.6476305, 426.5981909), new VSC(821891, 5.9352, 316.39187), new VSC(547507, 5.015326, 103.092774), new VSC(371684, 2.271148, 220.412642), new VSC(361778, 3.139043, 7.113547), new VSC(140618, 5.704067, 632.783739), new VSC(108975, 3.293136, 110.206321), new VSC(69007, 5.941, 419.48464), new VSC(61053, 0.94038, 639.89729), new VSC(48913, 1.55733, 202.2534), new VSC(34144, 0.19519, 277.03499), new VSC(32402, 5.47085, 949.17561), new VSC(20937, 0.46349, 735.87651), new VSC(20839, 1.52103, 433.71174), new VSC(20747, 5.33256, 199.072), new VSC(15298, 3.05944, 529.69097), new VSC(14296, 2.60434, 323.50542), new VSC(12884, 1.64892, 138.5175), new VSC(11993, 5.98051, 846.08283), new VSC(11380, 1.73106, 522.57742), new VSC(9796, 5.2048, 1265.5675), new VSC(7753, 5.8519, 95.9792), new VSC(6771, 3.0043, 14.2271), new VSC(6466, 0.1773, 1052.2684), new VSC(5850, 1.4552, 415.5525), new VSC(5307, 0.5974, 63.7359), new VSC(4696, 2.1492, 227.5262), new VSC(4044, 1.6401, 209.3669), new VSC(3688, 0.7802, 412.3711), new VSC(3461, 1.8509, 175.1661), new VSC(3420, 4.9455, 1581.9593), new VSC(3401, 0.5539, 350.3321), new VSC(3376, 3.6953, 224.3448), new VSC(2976, 5.6847, 210.1177), new VSC(2885, 1.3876, 838.9693), new VSC(2881, 0.1796, 853.1964), new VSC(2508, 3.5385, 742.9901), new VSC(2448, 6.1841, 1368.6603), new VSC(2406, 2.9656, 117.3199), new VSC(2174, 0.0151, 340.7709), new VSC(2024, 5.0541, 11.0457)]; - GFX.g_R1SaturnCoefficients = [new VSC(6182981, 0.2584352, 213.2990954), new VSC(506578, 0.711147, 206.185548), new VSC(341394, 5.796358, 426.598191), new VSC(188491, 0.472157, 220.412642), new VSC(186262, 3.141593, 0), new VSC(143891, 1.407449, 7.113547), new VSC(49621, 6.01744, 103.09277), new VSC(20928, 5.09246, 639.89729), new VSC(19953, 1.1756, 419.48464), new VSC(18840, 1.6082, 110.20632), new VSC(13877, 0.75886, 199.072), new VSC(12893, 5.9433, 433.71174), new VSC(5397, 1.2885, 14.2271), new VSC(4869, 0.8679, 323.5054), new VSC(4247, 0.393, 227.5262), new VSC(3252, 1.2585, 95.9792), new VSC(3081, 3.4366, 522.5774), new VSC(2909, 4.6068, 202.2534), new VSC(2856, 2.1673, 735.8765), new VSC(1988, 2.4505, 412.3711), new VSC(1941, 6.0239, 209.3669), new VSC(1581, 1.2919, 210.1177), new VSC(1340, 4.308, 853.1964), new VSC(1316, 1.253, 117.3199), new VSC(1203, 1.8665, 316.3919), new VSC(1091, 0.0753, 216.4805), new VSC(966, 0.48, 632.784), new VSC(954, 5.152, 647.011), new VSC(898, 0.983, 529.691), new VSC(882, 1.885, 1052.268), new VSC(874, 1.402, 224.345), new VSC(785, 3.064, 838.969), new VSC(740, 1.382, 625.67), new VSC(658, 4.144, 309.278), new VSC(650, 1.725, 742.99), new VSC(613, 3.033, 63.736), new VSC(599, 2.549, 217.231), new VSC(503, 2.13, 3.932)]; - GFX.g_R2SaturnCoefficients = [new VSC(436902, 4.786717, 213.299095), new VSC(71923, 2.5007, 206.18555), new VSC(49767, 4.97168, 220.41264), new VSC(43221, 3.8694, 426.59819), new VSC(29646, 5.9631, 7.11355), new VSC(4721, 2.4753, 199.072), new VSC(4142, 4.1067, 433.7117), new VSC(3789, 3.0977, 639.8973), new VSC(2964, 1.3721, 103.0928), new VSC(2556, 2.8507, 419.4846), new VSC(2327, 0, 0), new VSC(2208, 6.2759, 110.2063), new VSC(2188, 5.8555, 14.2271), new VSC(1957, 4.9245, 227.5262), new VSC(924, 5.464, 323.505), new VSC(706, 2.971, 95.979), new VSC(546, 4.129, 412.371), new VSC(431, 5.178, 522.577), new VSC(405, 4.173, 209.367), new VSC(391, 4.481, 216.48), new VSC(374, 5.834, 117.32), new VSC(361, 3.277, 647.011), new VSC(356, 3.192, 210.118), new VSC(326, 2.269, 853.196), new VSC(207, 4.022, 735.877), new VSC(204, 0.088, 202.253), new VSC(180, 3.597, 632.784), new VSC(178, 4.097, 440.825), new VSC(154, 3.135, 625.67), new VSC(148, 0.136, 302.165), new VSC(133, 2.594, 191.958), new VSC(132, 5.933, 309.278)]; - GFX.g_R3SaturnCoefficients = [new VSC(20315, 3.02187, 213.2991), new VSC(8924, 3.1914, 220.4126), new VSC(6909, 4.3517, 206.1855), new VSC(4087, 4.2241, 7.1135), new VSC(3879, 2.0106, 426.5982), new VSC(1071, 4.2036, 199.072), new VSC(907, 2.283, 433.712), new VSC(606, 3.175, 227.526), new VSC(597, 4.135, 14.227), new VSC(483, 1.173, 639.897), new VSC(393, 0, 0), new VSC(229, 4.698, 419.485), new VSC(188, 4.59, 110.206), new VSC(150, 3.202, 103.093), new VSC(121, 3.768, 323.505), new VSC(102, 4.71, 95.979), new VSC(101, 5.819, 412.371), new VSC(93, 1.44, 647.01), new VSC(84, 2.63, 216.48), new VSC(73, 4.15, 117.32), new VSC(62, 2.31, 440.83), new VSC(55, 0.31, 853.2), new VSC(50, 2.39, 209.37), new VSC(45, 4.37, 191.96), new VSC(41, 0.69, 522.58), new VSC(40, 1.84, 302.16), new VSC(38, 5.94, 88.87), new VSC(32, 4.01, 21.34)]; - GFX.g_R4SaturnCoefficients = [new VSC(1202, 1.415, 220.4126), new VSC(708, 1.162, 213.299), new VSC(516, 6.24, 206.186), new VSC(427, 2.469, 7.114), new VSC(268, 0.187, 426.598), new VSC(170, 5.959, 199.072), new VSC(150, 0.48, 433.712), new VSC(145, 1.442, 227.526), new VSC(121, 2.405, 14.227), new VSC(47, 5.57, 639.9), new VSC(19, 5.86, 647.01), new VSC(17, 0.53, 440.83), new VSC(16, 2.9, 110.21), new VSC(15, 0.3, 419.48), new VSC(14, 1.3, 412.37), new VSC(13, 2.09, 323.51), new VSC(11, 0.22, 95.98), new VSC(11, 2.46, 117.32), new VSC(10, 3.14, 0), new VSC(9, 1.56, 88.87), new VSC(9, 2.28, 21.34), new VSC(9, 0.68, 216.48), new VSC(8, 1.27, 234.64)]; - GFX.g_R5SaturnCoefficients = [new VSC(129, 5.913, 220.413), new VSC(32, 0.69, 7.11), new VSC(27, 5.91, 227.53), new VSC(20, 4.95, 433.71), new VSC(20, 0.67, 14.23), new VSC(14, 2.67, 206.19), new VSC(14, 1.46, 199.07), new VSC(13, 4.59, 426.6), new VSC(7, 4.63, 213.3), new VSC(5, 3.61, 639.9), new VSC(4, 4.9, 440.83), new VSC(3, 4.07, 647.01), new VSC(3, 4.66, 191.96), new VSC(3, 0.49, 323.51), new VSC(3, 3.18, 419.48), new VSC(2, 3.7, 88.87), new VSC(2, 3.32, 95.98), new VSC(2, 0.56, 117.32)]; - GFX.g_L0UranusCoefficients = [new VSC(548129294, 0, 0), new VSC(9260408, 0.8910642, 74.7815986), new VSC(1504248, 3.6271926, 1.4844727), new VSC(365982, 1.899622, 73.297126), new VSC(272328, 3.358237, 149.563197), new VSC(70328, 5.39254, 63.7359), new VSC(68893, 6.09292, 76.26607), new VSC(61999, 2.26952, 2.96895), new VSC(61951, 2.85099, 11.0457), new VSC(26469, 3.14152, 71.81265), new VSC(25711, 6.1138, 454.90937), new VSC(21079, 4.36059, 148.07872), new VSC(17819, 1.74437, 36.64856), new VSC(14613, 4.73732, 3.93215), new VSC(11163, 5.82682, 224.3448), new VSC(10998, 0.48865, 138.5175), new VSC(9527, 2.9552, 35.1641), new VSC(7546, 5.2363, 109.9457), new VSC(4220, 3.2333, 70.8494), new VSC(4052, 2.2775, 151.0477), new VSC(3490, 5.4831, 146.5943), new VSC(3355, 1.0655, 4.4534), new VSC(3144, 4.752, 77.7505), new VSC(2927, 4.629, 9.5612), new VSC(2922, 5.3524, 85.8273), new VSC(2273, 4.366, 70.3282), new VSC(2149, 0.6075, 38.133), new VSC(2051, 1.5177, 0.1119), new VSC(1992, 4.9244, 277.035), new VSC(1667, 3.6274, 380.1278), new VSC(1533, 2.5859, 52.6902), new VSC(1376, 2.0428, 65.2204), new VSC(1372, 4.1964, 111.4302), new VSC(1284, 3.1135, 202.2534), new VSC(1282, 0.5427, 222.8603), new VSC(1244, 0.9161, 2.4477), new VSC(1221, 0.199, 108.4612), new VSC(1151, 4.179, 33.6796), new VSC(1150, 0.9334, 3.1814), new VSC(1090, 1.775, 12.5302), new VSC(1072, 0.2356, 62.2514), new VSC(946, 1.192, 127.472), new VSC(708, 5.183, 213.299), new VSC(653, 0.966, 78.714), new VSC(628, 0.182, 984.6), new VSC(607, 5.432, 529.691), new VSC(559, 3.358, 0.521), new VSC(524, 2.013, 299.126), new VSC(483, 2.106, 0.963), new VSC(471, 1.407, 184.727), new VSC(467, 0.415, 145.11), new VSC(434, 5.521, 183.243), new VSC(405, 5.987, 8.077), new VSC(399, 0.338, 415.552), new VSC(396, 5.87, 351.817), new VSC(379, 2.35, 56.622), new VSC(310, 5.833, 145.631), new VSC(300, 5.644, 22.091), new VSC(294, 5.839, 39.618), new VSC(252, 1.637, 221.376), new VSC(249, 4.746, 225.829), new VSC(239, 2.35, 137.033), new VSC(224, 0.516, 84.343), new VSC(223, 2.843, 0.261), new VSC(220, 1.922, 67.668), new VSC(217, 6.142, 5.938), new VSC(216, 4.778, 340.771), new VSC(208, 5.58, 68.844), new VSC(202, 1.297, 0.048), new VSC(199, 0.956, 152.532), new VSC(194, 1.888, 456.394), new VSC(193, 0.916, 453.425), new VSC(187, 1.319, 0.16), new VSC(182, 3.536, 79.235), new VSC(173, 1.539, 160.609), new VSC(172, 5.68, 219.891), new VSC(170, 3.677, 5.417), new VSC(169, 5.879, 18.159), new VSC(165, 1.424, 106.977), new VSC(163, 3.05, 112.915), new VSC(158, 0.738, 54.175), new VSC(147, 1.263, 59.804), new VSC(143, 1.3, 35.425), new VSC(139, 5.386, 32.195), new VSC(139, 4.26, 909.819), new VSC(124, 1.374, 7.114), new VSC(110, 2.027, 554.07), new VSC(109, 5.706, 77.963), new VSC(104, 5.028, 0.751), new VSC(104, 1.458, 24.379), new VSC(103, 0.681, 14.978)]; - GFX.g_L1UranusCoefficients = [new VSC(7502543122, 0, 0), new VSC(154458, 5.242017, 74.781599), new VSC(24456, 1.71256, 1.48447), new VSC(9258, 0.4284, 11.0457), new VSC(8266, 1.5022, 63.7359), new VSC(7842, 1.3198, 149.5632), new VSC(3899, 0.4648, 3.9322), new VSC(2284, 4.1737, 76.2661), new VSC(1927, 0.5301, 2.9689), new VSC(1233, 1.5863, 70.8494), new VSC(791, 5.436, 3.181), new VSC(767, 1.996, 73.297), new VSC(482, 2.984, 85.827), new VSC(450, 4.138, 138.517), new VSC(446, 3.723, 224.345), new VSC(427, 4.731, 71.813), new VSC(354, 2.583, 148.079), new VSC(348, 2.454, 9.561), new VSC(317, 5.579, 52.69), new VSC(206, 2.363, 2.448), new VSC(189, 4.202, 56.622), new VSC(184, 0.284, 151.048), new VSC(180, 5.684, 12.53), new VSC(171, 3.001, 78.714), new VSC(158, 2.909, 0.963), new VSC(155, 5.591, 4.453), new VSC(154, 4.652, 35.164), new VSC(152, 2.942, 77.751), new VSC(143, 2.59, 62.251), new VSC(121, 4.148, 127.472), new VSC(116, 3.732, 65.22), new VSC(102, 4.188, 145.631), new VSC(102, 6.034, 0.112), new VSC(88, 3.99, 18.16), new VSC(88, 6.16, 202.25), new VSC(81, 2.64, 22.09), new VSC(72, 6.05, 70.33), new VSC(69, 4.05, 77.96), new VSC(59, 3.7, 67.67), new VSC(47, 3.54, 351.82), new VSC(44, 5.91, 7.11), new VSC(43, 5.72, 5.42), new VSC(39, 4.92, 222.86), new VSC(36, 5.9, 33.68), new VSC(36, 3.29, 8.08), new VSC(36, 3.33, 71.6), new VSC(35, 5.08, 38.13), new VSC(31, 5.62, 984.6), new VSC(31, 5.5, 59.8), new VSC(31, 5.46, 160.61), new VSC(30, 1.66, 447.8), new VSC(29, 1.15, 462.02), new VSC(29, 4.52, 84.34), new VSC(27, 5.54, 131.4), new VSC(27, 6.15, 299.13), new VSC(26, 4.99, 137.03), new VSC(25, 5.74, 380.13)]; - GFX.g_L2UranusCoefficients = [new VSC(53033, 0, 0), new VSC(2358, 2.2601, 74.7816), new VSC(769, 4.526, 11.046), new VSC(552, 3.258, 63.736), new VSC(542, 2.276, 3.932), new VSC(529, 4.923, 1.484), new VSC(258, 3.691, 3.181), new VSC(239, 5.858, 149.563), new VSC(182, 6.218, 70.849), new VSC(54, 1.44, 76.27), new VSC(49, 6.03, 56.62), new VSC(45, 3.91, 2.45), new VSC(45, 0.81, 85.83), new VSC(38, 1.78, 52.69), new VSC(37, 4.46, 2.97), new VSC(33, 0.86, 9.56), new VSC(29, 5.1, 73.3), new VSC(24, 2.11, 18.16), new VSC(22, 5.99, 138.52), new VSC(22, 4.82, 78.71), new VSC(21, 2.4, 77.96), new VSC(21, 2.17, 224.34), new VSC(17, 2.54, 145.63), new VSC(17, 3.47, 12.53), new VSC(12, 0.02, 22.09), new VSC(11, 0.08, 127.47), new VSC(10, 5.16, 71.6), new VSC(10, 4.46, 62.25), new VSC(9, 4.26, 7.11), new VSC(8, 5.5, 67.67), new VSC(7, 1.25, 5.42), new VSC(6, 3.36, 447.8), new VSC(6, 5.45, 65.22), new VSC(6, 4.52, 151.05), new VSC(6, 5.73, 462.02)]; - GFX.g_L3UranusCoefficients = [new VSC(121, 0.024, 74.782), new VSC(68, 4.12, 3.93), new VSC(53, 2.39, 11.05), new VSC(46, 0, 0), new VSC(45, 2.04, 3.18), new VSC(44, 2.96, 1.48), new VSC(25, 4.89, 63.74), new VSC(21, 4.55, 70.85), new VSC(20, 2.31, 149.56), new VSC(9, 1.58, 56.62), new VSC(4, 0.23, 18.16), new VSC(4, 5.39, 76.27), new VSC(4, 0.95, 77.96), new VSC(3, 4.98, 85.83), new VSC(3, 4.13, 52.69), new VSC(3, 0.37, 78.71), new VSC(2, 0.86, 145.63), new VSC(2, 5.66, 9.56)]; - GFX.g_L4UranusCoefficients = [new VSC(114, 3.142, 0), new VSC(6, 4.58, 74.78), new VSC(3, 0.35, 11.05), new VSC(1, 3.42, 56.62)]; - GFX.g_B0UranusCoefficients = [new VSC(1346278, 2.6187781, 74.7815986), new VSC(62341, 5.08111, 149.5632), new VSC(61601, 3.14159, 0), new VSC(9964, 1.616, 76.2661), new VSC(9926, 0.5763, 73.2971), new VSC(3259, 1.2612, 224.3448), new VSC(2972, 2.2437, 1.4845), new VSC(2010, 6.0555, 148.0787), new VSC(1522, 0.2796, 63.7359), new VSC(924, 4.038, 151.048), new VSC(761, 6.14, 71.813), new VSC(522, 3.321, 138.517), new VSC(463, 0.743, 85.827), new VSC(437, 3.381, 529.691), new VSC(435, 0.341, 77.751), new VSC(431, 3.554, 213.299), new VSC(420, 5.213, 11.046), new VSC(245, 0.788, 2.969), new VSC(233, 2.257, 222.86), new VSC(216, 1.591, 38.133), new VSC(180, 3.725, 299.126), new VSC(175, 1.236, 146.594), new VSC(174, 1.937, 380.128), new VSC(160, 5.336, 111.43), new VSC(144, 5.962, 35.164), new VSC(116, 5.739, 70.849), new VSC(106, 0.941, 70.328), new VSC(102, 2.619, 78.714)]; - GFX.g_B1UranusCoefficients = [new VSC(206366, 4.123943, 74.781599), new VSC(8563, 0.3382, 149.5632), new VSC(1726, 2.1219, 73.2971), new VSC(1374, 0, 0), new VSC(1369, 3.0686, 76.2661), new VSC(451, 3.777, 1.484), new VSC(400, 2.848, 224.345), new VSC(307, 1.255, 148.079), new VSC(154, 3.786, 63.736), new VSC(112, 5.573, 151.048), new VSC(111, 5.329, 138.517), new VSC(83, 3.59, 71.81), new VSC(56, 3.4, 85.83), new VSC(54, 1.7, 77.75), new VSC(42, 1.21, 11.05), new VSC(41, 4.45, 78.71), new VSC(32, 3.77, 222.86), new VSC(30, 2.56, 2.97), new VSC(27, 5.34, 213.3), new VSC(26, 0.42, 380.13)]; - GFX.g_B2UranusCoefficients = [new VSC(9212, 5.8004, 74.7816), new VSC(557, 0, 0), new VSC(286, 2.177, 149.563), new VSC(95, 3.84, 73.3), new VSC(45, 4.88, 76.27), new VSC(20, 5.46, 1.48), new VSC(15, 0.88, 138.52), new VSC(14, 2.85, 148.08), new VSC(14, 5.07, 63.74), new VSC(10, 5, 224.34), new VSC(8, 6.27, 78.71)]; - GFX.g_B3UranusCoefficients = [new VSC(268, 1.251, 74.782), new VSC(11, 3.14, 0), new VSC(6, 4.01, 149.56), new VSC(3, 5.78, 73.3)]; - GFX.g_B4UranusCoefficients = [new VSC(6, 2.85, 74.78)]; - GFX.g_R0UranusCoefficients = [new VSC(1921264848, 0, 0), new VSC(88784984, 5.60377527, 74.78159857), new VSC(3440836, 0.328361, 73.2971259), new VSC(2055653, 1.7829517, 149.5631971), new VSC(649322, 4.522473, 76.266071), new VSC(602248, 3.860038, 63.735898), new VSC(496404, 1.401399, 454.909367), new VSC(338526, 1.580027, 138.517497), new VSC(243508, 1.570866, 71.812653), new VSC(190522, 1.998094, 1.484473), new VSC(161858, 2.791379, 148.078724), new VSC(143706, 1.383686, 11.0457), new VSC(93192, 0.17437, 36.64856), new VSC(89806, 3.66105, 109.94569), new VSC(71424, 4.24509, 224.3448), new VSC(46677, 1.39977, 35.16409), new VSC(39026, 3.36235, 277.03499), new VSC(39010, 1.66971, 70.84945), new VSC(36755, 3.88649, 146.59425), new VSC(30349, 0.701, 151.04767), new VSC(29156, 3.18056, 77.75054), new VSC(25786, 3.78538, 85.8273), new VSC(25620, 5.25656, 380.12777), new VSC(22637, 0.72519, 529.69097), new VSC(20473, 2.7964, 70.32818), new VSC(20472, 1.55589, 202.2534), new VSC(17901, 0.55455, 2.96895), new VSC(15503, 5.35405, 38.13304), new VSC(14702, 4.90434, 108.46122), new VSC(12897, 2.62154, 111.43016), new VSC(12328, 5.96039, 127.4718), new VSC(11959, 1.75044, 984.60033), new VSC(11853, 0.99343, 52.6902), new VSC(11696, 3.29826, 3.93215), new VSC(11495, 0.43774, 65.22037), new VSC(10793, 1.42105, 213.2991), new VSC(9111, 4.9964, 62.2514), new VSC(8421, 5.2535, 222.8603), new VSC(8402, 5.0388, 415.5525), new VSC(7449, 0.7949, 351.8166), new VSC(7329, 3.9728, 183.2428), new VSC(6046, 5.6796, 78.7138), new VSC(5524, 3.115, 9.5612), new VSC(5445, 5.1058, 145.1098), new VSC(5238, 2.6296, 33.6796), new VSC(4079, 3.2206, 340.7709), new VSC(3919, 4.2502, 39.6175), new VSC(3802, 6.1099, 184.7273), new VSC(3781, 3.4584, 456.3938), new VSC(3687, 2.4872, 453.4249), new VSC(3102, 4.1403, 219.8914), new VSC(2963, 0.8298, 56.6224), new VSC(2942, 0.4239, 299.1264), new VSC(2940, 2.1464, 137.033), new VSC(2938, 3.6766, 140.002), new VSC(2865, 0.31, 12.5302), new VSC(2538, 4.8546, 131.4039), new VSC(2364, 0.4425, 554.07), new VSC(2183, 2.9404, 305.3462)]; - GFX.g_R1UranusCoefficients = [new VSC(1479896, 3.6720571, 74.7815986), new VSC(71212, 6.22601, 63.7359), new VSC(68627, 6.13411, 149.5632), new VSC(24060, 3.14159, 0), new VSC(21468, 2.60177, 76.26607), new VSC(20857, 5.24625, 11.0457), new VSC(11405, 0.01848, 70.84945), new VSC(7497, 0.4236, 73.2971), new VSC(4244, 1.4169, 85.8273), new VSC(3927, 3.1551, 71.8127), new VSC(3578, 2.3116, 224.3448), new VSC(3506, 2.5835, 138.5175), new VSC(3229, 5.255, 3.9322), new VSC(3060, 0.1532, 1.4845), new VSC(2564, 0.9808, 148.0787), new VSC(2429, 3.9944, 52.6902), new VSC(1645, 2.6535, 127.4718), new VSC(1584, 1.4305, 78.7138), new VSC(1508, 5.06, 151.0477), new VSC(1490, 2.6756, 56.6224), new VSC(1413, 4.5746, 202.2534), new VSC(1403, 1.3699, 77.7505), new VSC(1228, 1.047, 62.2514), new VSC(1033, 0.2646, 131.4039), new VSC(992, 2.172, 65.22), new VSC(862, 5.055, 351.817), new VSC(744, 3.076, 35.164), new VSC(687, 2.499, 77.963), new VSC(647, 4.473, 70.328), new VSC(624, 0.863, 9.561), new VSC(604, 0.907, 984.6), new VSC(575, 3.231, 447.796), new VSC(562, 2.718, 462.023), new VSC(530, 5.917, 213.299), new VSC(528, 5.151, 2.969)]; - GFX.g_R2UranusCoefficients = [new VSC(22440, 0.69953, 74.7816), new VSC(4727, 1.699, 63.7359), new VSC(1682, 4.6483, 70.8494), new VSC(1650, 3.0966, 11.0457), new VSC(1434, 3.5212, 149.5632), new VSC(770, 0, 0), new VSC(500, 6.172, 76.266), new VSC(461, 0.767, 3.932), new VSC(390, 4.496, 56.622), new VSC(390, 5.527, 85.827), new VSC(292, 0.204, 52.69), new VSC(287, 3.534, 73.297), new VSC(273, 3.847, 138.517), new VSC(220, 1.964, 131.404), new VSC(216, 0.848, 77.963), new VSC(205, 3.248, 78.714), new VSC(149, 4.898, 127.472), new VSC(129, 2.081, 3.181)]; - GFX.g_R3UranusCoefficients = [new VSC(1164, 4.7345, 74.7816), new VSC(212, 3.343, 63.736), new VSC(196, 2.98, 70.849), new VSC(105, 0.958, 11.046), new VSC(73, 1, 149.56), new VSC(72, 0.03, 56.62), new VSC(55, 2.59, 3.93), new VSC(36, 5.65, 77.96), new VSC(34, 3.82, 76.27), new VSC(32, 3.6, 131.4)]; - GFX.g_R4UranusCoefficients = [new VSC(53, 3.01, 74.78), new VSC(10, 1.91, 56.62)]; - GFX.g_L0VenusCoefficients = [new VSC(317614667, 0, 0), new VSC(1353968, 5.5931332, 10213.2855462), new VSC(89892, 5.3065, 20426.57109), new VSC(5477, 4.4163, 7860.4194), new VSC(3456, 2.6996, 11790.6291), new VSC(2372, 2.9938, 3930.2097), new VSC(1664, 4.2502, 1577.3435), new VSC(1438, 4.1575, 9683.5946), new VSC(1317, 5.1867, 26.2983), new VSC(1201, 6.1536, 30639.8566), new VSC(769, 0.816, 9437.763), new VSC(761, 1.95, 529.691), new VSC(708, 1.065, 775.523), new VSC(585, 3.998, 191.448), new VSC(500, 4.123, 15720.839), new VSC(429, 3.586, 19367.189), new VSC(327, 5.677, 5507.553), new VSC(326, 4.591, 10404.734), new VSC(232, 3.163, 9153.904), new VSC(180, 4.653, 1109.379), new VSC(155, 5.57, 19651.048), new VSC(128, 4.226, 20.775), new VSC(128, 0.962, 5661.332), new VSC(106, 1.537, 801.821)]; - GFX.g_L1VenusCoefficients = [new VSC(1021352943053, 0, 0), new VSC(95708, 2.46424, 10213.28555), new VSC(14445, 0.51625, 20426.57109), new VSC(213, 1.795, 30639.857), new VSC(174, 2.655, 26.298), new VSC(152, 6.106, 1577.344), new VSC(82, 5.7, 191.45), new VSC(70, 2.68, 9437.76), new VSC(52, 3.6, 775.52), new VSC(38, 1.03, 529.69), new VSC(30, 1.25, 5507.55), new VSC(25, 6.11, 10404.73)]; - GFX.g_L2VenusCoefficients = [new VSC(54127, 0, 0), new VSC(3891, 0.3451, 10213.2855), new VSC(1338, 2.0201, 20426.5711), new VSC(24, 2.05, 26.3), new VSC(19, 3.54, 30639.86), new VSC(10, 3.97, 775.52), new VSC(7, 1.52, 1577.34), new VSC(6, 1, 191.45)]; - GFX.g_L3VenusCoefficients = [new VSC(136, 4.804, 10213.286), new VSC(78, 3.67, 20426.57), new VSC(26, 0, 0)]; - GFX.g_L4VenusCoefficients = [new VSC(114, 3.1416, 0), new VSC(3, 5.21, 20426.57), new VSC(2, 2.51, 10213.29)]; - GFX.g_L5VenusCoefficients = [new VSC(1, 3.14, 0)]; - GFX.g_B0VenusCoefficients = [new VSC(5923638, 0.2670278, 10213.2855462), new VSC(40108, 1.14737, 20426.57109), new VSC(32815, 3.14737, 0), new VSC(1011, 1.0895, 30639.8566), new VSC(149, 6.254, 18073.705), new VSC(138, 0.86, 1577.344), new VSC(130, 3.672, 9437.763), new VSC(120, 3.705, 2352.866), new VSC(108, 4.539, 22003.915)]; - GFX.g_B1VenusCoefficients = [new VSC(513348, 1.803643, 10213.285546), new VSC(4380, 3.3862, 20426.5711), new VSC(199, 0, 0), new VSC(197, 2.53, 30639.857)]; - GFX.g_B2VenusCoefficients = [new VSC(22378, 3.38509, 10213.28555), new VSC(282, 0, 0), new VSC(173, 5.256, 20426.571), new VSC(27, 3.87, 30639.86)]; - GFX.g_B3VenusCoefficients = [new VSC(647, 4.992, 10213.286), new VSC(20, 3.14, 0), new VSC(6, 0.77, 20426.57), new VSC(3, 5.44, 30639.86)]; - GFX.g_B4VenusCoefficients = [new VSC(14, 0.32, 10213.29)]; - GFX.g_R0VenusCoefficients = [new VSC(72334821, 0, 0), new VSC(489824, 4.021518, 10213.285546), new VSC(1658, 4.9021, 20426.5711), new VSC(1632, 2.8455, 7860.4194), new VSC(1378, 1.1285, 11790.6291), new VSC(498, 2.587, 9683.595), new VSC(374, 1.423, 3930.21), new VSC(264, 5.529, 9437.763), new VSC(237, 2.551, 15720.839), new VSC(222, 2.013, 19367.189), new VSC(126, 2.728, 1577.344), new VSC(119, 3.02, 10404.734)]; - GFX.g_R1VenusCoefficients = [new VSC(34551, 0.89199, 10213.28555), new VSC(234, 1.772, 20426.571), new VSC(234, 3.142, 0)]; - GFX.g_R2VenusCoefficients = [new VSC(1407, 5.0637, 10213.2855), new VSC(16, 5.47, 20426.57), new VSC(13, 0, 0)]; - GFX.g_R3VenusCoefficients = [new VSC(50, 3.22, 10213.29)]; - GFX.g_R4VenusCoefficients = [new VSC(1, 0.92, 10213.29)]; - FastMath._pI4_A = 0.785398155450821; - FastMath._pI4_B = 7.94662735614793E-09; - FastMath._pI4_C = 3.06161699786838E-17; - FastMath._m_1_PI = 0.318309886183791; - HealpixTables.ctab = [0, 1, 256, 257, 2, 3, 258, 259, 512, 513, 768, 769, 514, 515, 770, 771, 4, 5, 260, 261, 6, 7, 262, 263, 516, 517, 772, 773, 518, 519, 774, 775, 1024, 1025, 1280, 1281, 1026, 1027, 1282, 1283, 1536, 1537, 1792, 1793, 1538, 1539, 1794, 1795, 1028, 1029, 1284, 1285, 1030, 1031, 1286, 1287, 1540, 1541, 1796, 1797, 1542, 1543, 1798, 1799, 8, 9, 264, 265, 10, 11, 266, 267, 520, 521, 776, 777, 522, 523, 778, 779, 12, 13, 268, 269, 14, 15, 270, 271, 524, 525, 780, 781, 526, 527, 782, 783, 1032, 1033, 1288, 1289, 1034, 1035, 1290, 1291, 1544, 1545, 1800, 1801, 1546, 1547, 1802, 1803, 1036, 1037, 1292, 1293, 1038, 1039, 1294, 1295, 1548, 1549, 1804, 1805, 1550, 1551, 1806, 1807, 2048, 2049, 2304, 2305, 2050, 2051, 2306, 2307, 2560, 2561, 2816, 2817, 2562, 2563, 2818, 2819, 2052, 2053, 2308, 2309, 2054, 2055, 2310, 2311, 2564, 2565, 2820, 2821, 2566, 2567, 2822, 2823, 3072, 3073, 3328, 3329, 3074, 3075, 3330, 3331, 3584, 3585, 3840, 3841, 3586, 3587, 3842, 3843, 3076, 3077, 3332, 3333, 3078, 3079, 3334, 3335, 3588, 3589, 3844, 3845, 3590, 3591, 3846, 3847, 2056, 2057, 2312, 2313, 2058, 2059, 2314, 2315, 2568, 2569, 2824, 2825, 2570, 2571, 2826, 2827, 2060, 2061, 2316, 2317, 2062, 2063, 2318, 2319, 2572, 2573, 2828, 2829, 2574, 2575, 2830, 2831, 3080, 3081, 3336, 3337, 3082, 3083, 3338, 3339, 3592, 3593, 3848, 3849, 3594, 3595, 3850, 3851, 3084, 3085, 3340, 3341, 3086, 3087, 3342, 3343, 3596, 3597, 3852, 3853, 3598, 3599, 3854, 3855]; - HealpixTables.utab = [0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85, 256, 257, 260, 261, 272, 273, 276, 277, 320, 321, 324, 325, 336, 337, 340, 341, 1024, 1025, 1028, 1029, 1040, 1041, 1044, 1045, 1088, 1089, 1092, 1093, 1104, 1105, 1108, 1109, 1280, 1281, 1284, 1285, 1296, 1297, 1300, 1301, 1344, 1345, 1348, 1349, 1360, 1361, 1364, 1365, 4096, 4097, 4100, 4101, 4112, 4113, 4116, 4117, 4160, 4161, 4164, 4165, 4176, 4177, 4180, 4181, 4352, 4353, 4356, 4357, 4368, 4369, 4372, 4373, 4416, 4417, 4420, 4421, 4432, 4433, 4436, 4437, 5120, 5121, 5124, 5125, 5136, 5137, 5140, 5141, 5184, 5185, 5188, 5189, 5200, 5201, 5204, 5205, 5376, 5377, 5380, 5381, 5392, 5393, 5396, 5397, 5440, 5441, 5444, 5445, 5456, 5457, 5460, 5461, 16384, 16385, 16388, 16389, 16400, 16401, 16404, 16405, 16448, 16449, 16452, 16453, 16464, 16465, 16468, 16469, 16640, 16641, 16644, 16645, 16656, 16657, 16660, 16661, 16704, 16705, 16708, 16709, 16720, 16721, 16724, 16725, 17408, 17409, 17412, 17413, 17424, 17425, 17428, 17429, 17472, 17473, 17476, 17477, 17488, 17489, 17492, 17493, 17664, 17665, 17668, 17669, 17680, 17681, 17684, 17685, 17728, 17729, 17732, 17733, 17744, 17745, 17748, 17749, 20480, 20481, 20484, 20485, 20496, 20497, 20500, 20501, 20544, 20545, 20548, 20549, 20560, 20561, 20564, 20565, 20736, 20737, 20740, 20741, 20752, 20753, 20756, 20757, 20800, 20801, 20804, 20805, 20816, 20817, 20820, 20821, 21504, 21505, 21508, 21509, 21520, 21521, 21524, 21525, 21568, 21569, 21572, 21573, 21584, 21585, 21588, 21589, 21760, 21761, 21764, 21765, 21776, 21777, 21780, 21781, 21824, 21825, 21828, 21829, 21840, 21841, 21844, 21845]; - HealpixTables.jrll = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]; - HealpixTables.jpll = [1, 3, 5, 7, 0, 2, 4, 6, 1, 3, 5, 7]; - HealpixTables.xoffset = [-1, -1, 0, 1, 1, 1, 0, -1]; - HealpixTables.yoffset = [0, 1, 1, 1, 0, -1, -1, -1]; - URLHelpers.singleton = new URLHelpers(); - Annotation.pointList = null; - Annotation.lineList = null; - Annotation.triangleFanPointList = null; - Annotation.triangleList = null; - Annotation.batchDirty = true; - AstroCalc._galDetails = new GMDS(); - AstroCalc._jupDetails = new EPD(); - AstroCalc._jupPhisical = new CAAPhysicalJupiterDetails(); - AstroCalc._jDateLast = 0; - Constellations.RC = 0.017453292519943; - Constellations._maxSeperation = 0.745; - Constellations.containment = null; - Constellations._constToDraw = ''; - Constellations.selectedSegment = null; - Constellations._artFile = null; - Constellations.artwork = null; - Constellations.boundries = null; - Constellations.pictureBlendStates = {}; - ConstellationFilter.families = {}; - Vector3d.zero = new Vector3d(); - Matrix3d._s_identity = Matrix3d._createIdentity(); - FolderBrowser._downloading = false; - FolderBrowser._imagesLoaded = false; - FolderBrowser._imageLoadCount = 0; - PointList.starTexture = null; - SimpleLineShader.vertLoc = 0; - SimpleLineShader.initialized = false; - SimpleLineShader._prog = null; - SimpleLineShader2D.vertLoc = 0; - SimpleLineShader2D.initialized = false; - SimpleLineShader2D._prog = null; - OrbitLineShader.vertLoc = 0; - OrbitLineShader.colorLoc = 0; - OrbitLineShader.initialized = false; - OrbitLineShader._prog = null; - LineShaderNormalDates.vertLoc = 0; - LineShaderNormalDates.colorLoc = 0; - LineShaderNormalDates.timeLoc = 0; - LineShaderNormalDates.initialized = false; - LineShaderNormalDates._prog = null; - TimeSeriesPointSpriteShader.vertLoc = 0; - TimeSeriesPointSpriteShader.colorLoc = 0; - TimeSeriesPointSpriteShader.pointSizeLoc = 0; - TimeSeriesPointSpriteShader.timeLoc = 0; - TimeSeriesPointSpriteShader.initialized = false; - TimeSeriesPointSpriteShader._prog = null; - KeplerPointSpriteShader.abcLoc = 0; - KeplerPointSpriteShader.abcLoc1 = 0; - KeplerPointSpriteShader.pointSizeLoc = 0; - KeplerPointSpriteShader.colorLoc = 0; - KeplerPointSpriteShader.weLoc = 0; - KeplerPointSpriteShader.nTLoc = 0; - KeplerPointSpriteShader.azLoc = 0; - KeplerPointSpriteShader.orbitLoc = 0; - KeplerPointSpriteShader.initialized = false; - KeplerPointSpriteShader._prog = null; - EllipseShader.angleLoc = 0; - EllipseShader.initialized = false; - EllipseShader._prog = null; - ModelShader.vertLoc = 0; - ModelShader.normalLoc = 0; - ModelShader.textureLoc = 0; - ModelShader.initialized = false; - ModelShader._prog = null; - ModelShader.sunPosition = Vector3d.create(-1, -1, -1); - ModelShader.minLightingBrightness = 1; - ModelShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); - ModelShaderTan.vertLoc = 0; - ModelShaderTan.normalLoc = 0; - ModelShaderTan.textureLoc = 0; - ModelShaderTan.initialized = false; - ModelShaderTan._prog = null; - ModelShaderTan.sunPosition = Vector3d.create(-1, -1, -1); - ModelShaderTan.minLightingBrightness = 1; - ModelShaderTan.atmosphereColor = Color.fromArgb(0, 0, 0, 0); - TileShader.vertLoc = 0; - TileShader.textureLoc = 0; - TileShader.initialized = false; - TileShader._prog = null; - TileShader.sunPosition = Vector3d.create(-1, -1, -1); - TileShader.minLightingBrightness = 1; - TileShader.atmosphereColor = Color.fromArgb(0, 0, 0, 0); - FitsShader.vertLoc = 0; - FitsShader.textureLoc = 0; - FitsShader.initialized = false; - FitsShader._prog = null; - FitsShader.blankValue = 0; - FitsShader.bScale = 1; - FitsShader.bZero = 0; - FitsShader.min = 0; - FitsShader.max = 0; - FitsShader.transparentBlack = false; - FitsShader.containsBlanks = false; - FitsShader.scaleType = 0; - ImageShader.vertLoc = 0; - ImageShader.textureLoc = 0; - ImageShader.initialized = false; - ImageShader._prog = null; - ImageShader2.vertLoc = 0; - ImageShader2.textureLoc = 0; - ImageShader2.initialized = false; - ImageShader2._prog = null; - SpriteShader.vertLoc = 0; - SpriteShader.textureLoc = 0; - SpriteShader.colorLoc = 0; - SpriteShader.initialized = false; - SpriteShader._prog = null; - ShapeSpriteShader.vertLoc = 0; - ShapeSpriteShader.textureLoc = 0; - ShapeSpriteShader.colorLoc = 0; - ShapeSpriteShader.initialized = false; - ShapeSpriteShader._prog = null; - TextShader.vertLoc = 0; - TextShader.textureLoc = 0; - TextShader.initialized = false; - TextShader._prog = null; - Texture.empty = null; - Grids._galaxyImageIndexBuffer = null; - Grids._galaxyImageTriangleCount = 0; - Grids._milkyWayImage = null; - Grids._starSprites = null; - Grids._starCount = 0; - Grids._starsDownloading = false; - Grids._stars = null; - Grids._hipparcosIndex = {}; - Grids._limitingMagnitude = 16; - Grids._galaxyTextures = null; - Grids._galaxyVertexCounts = null; - Grids._largeSet = true; - Grids._cosmosReady = false; - Grids._cosmos = null; - Grids._downloadingGalaxy = false; - Grids._eclipticCount = 0; - Grids._eclipticYear = 0; - Grids._monthDays = [31, 28.2421, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - Grids._monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - Grids._eclipticTextYear = 0; - KeplerVertex._sine = 0; - KeplerVertex._cose = 1; - KeplerVertex._degrad = Math.PI / 180; - KeplerVertex.baseDate = ss.truncate(SpaceTimeController.utcToJulian(ss.now())); - ColorMapContainer.colorTextures = {}; - ColorMapContainer.viridis = ColorMapContainer.fromStringList(['#440154', '#440256', '#450457', '#450559', '#46075a', '#46085c', '#460a5d', '#460b5e', '#470d60', '#470e61', '#471063', '#471164', '#471365', '#481467', '#481668', '#481769', '#48186a', '#481a6c', '#481b6d', '#481c6e', '#481d6f', '#481f70', '#482071', '#482173', '#482374', '#482475', '#482576', '#482677', '#482878', '#482979', '#472a7a', '#472c7a', '#472d7b', '#472e7c', '#472f7d', '#46307e', '#46327e', '#46337f', '#463480', '#453581', '#453781', '#453882', '#443983', '#443a83', '#443b84', '#433d84', '#433e85', '#423f85', '#424086', '#424186', '#414287', '#414487', '#404588', '#404688', '#3f4788', '#3f4889', '#3e4989', '#3e4a89', '#3e4c8a', '#3d4d8a', '#3d4e8a', '#3c4f8a', '#3c508b', '#3b518b', '#3b528b', '#3a538b', '#3a548c', '#39558c', '#39568c', '#38588c', '#38598c', '#375a8c', '#375b8d', '#365c8d', '#365d8d', '#355e8d', '#355f8d', '#34608d', '#34618d', '#33628d', '#33638d', '#32648e', '#32658e', '#31668e', '#31678e', '#31688e', '#30698e', '#306a8e', '#2f6b8e', '#2f6c8e', '#2e6d8e', '#2e6e8e', '#2e6f8e', '#2d708e', '#2d718e', '#2c718e', '#2c728e', '#2c738e', '#2b748e', '#2b758e', '#2a768e', '#2a778e', '#2a788e', '#29798e', '#297a8e', '#297b8e', '#287c8e', '#287d8e', '#277e8e', '#277f8e', '#27808e', '#26818e', '#26828e', '#26828e', '#25838e', '#25848e', '#25858e', '#24868e', '#24878e', '#23888e', '#23898e', '#238a8d', '#228b8d', '#228c8d', '#228d8d', '#218e8d', '#218f8d', '#21908d', '#21918c', '#20928c', '#20928c', '#20938c', '#1f948c', '#1f958b', '#1f968b', '#1f978b', '#1f988b', '#1f998a', '#1f9a8a', '#1e9b8a', '#1e9c89', '#1e9d89', '#1f9e89', '#1f9f88', '#1fa088', '#1fa188', '#1fa187', '#1fa287', '#20a386', '#20a486', '#21a585', '#21a685', '#22a785', '#22a884', '#23a983', '#24aa83', '#25ab82', '#25ac82', '#26ad81', '#27ad81', '#28ae80', '#29af7f', '#2ab07f', '#2cb17e', '#2db27d', '#2eb37c', '#2fb47c', '#31b57b', '#32b67a', '#34b679', '#35b779', '#37b878', '#38b977', '#3aba76', '#3bbb75', '#3dbc74', '#3fbc73', '#40bd72', '#42be71', '#44bf70', '#46c06f', '#48c16e', '#4ac16d', '#4cc26c', '#4ec36b', '#50c46a', '#52c569', '#54c568', '#56c667', '#58c765', '#5ac864', '#5cc863', '#5ec962', '#60ca60', '#63cb5f', '#65cb5e', '#67cc5c', '#69cd5b', '#6ccd5a', '#6ece58', '#70cf57', '#73d056', '#75d054', '#77d153', '#7ad151', '#7cd250', '#7fd34e', '#81d34d', '#84d44b', '#86d549', '#89d548', '#8bd646', '#8ed645', '#90d743', '#93d741', '#95d840', '#98d83e', '#9bd93c', '#9dd93b', '#a0da39', '#a2da37', '#a5db36', '#a8db34', '#aadc32', '#addc30', '#b0dd2f', '#b2dd2d', '#b5de2b', '#b8de29', '#bade28', '#bddf26', '#c0df25', '#c2df23', '#c5e021', '#c8e020', '#cae11f', '#cde11d', '#d0e11c', '#d2e21b', '#d5e21a', '#d8e219', '#dae319', '#dde318', '#dfe318', '#e2e418', '#e5e419', '#e7e419', '#eae51a', '#ece51b', '#efe51c', '#f1e51d', '#f4e61e', '#f6e620', '#f8e621', '#fbe723', '#fde725']); - ColorMapContainer.plasma = ColorMapContainer.fromStringList(['#0d0887', '#100788', '#130789', '#16078a', '#19068c', '#1b068d', '#1d068e', '#20068f', '#220690', '#240691', '#260591', '#280592', '#2a0593', '#2c0594', '#2e0595', '#2f0596', '#310597', '#330597', '#350498', '#370499', '#38049a', '#3a049a', '#3c049b', '#3e049c', '#3f049c', '#41049d', '#43039e', '#44039e', '#46039f', '#48039f', '#4903a0', '#4b03a1', '#4c02a1', '#4e02a2', '#5002a2', '#5102a3', '#5302a3', '#5502a4', '#5601a4', '#5801a4', '#5901a5', '#5b01a5', '#5c01a6', '#5e01a6', '#6001a6', '#6100a7', '#6300a7', '#6400a7', '#6600a7', '#6700a8', '#6900a8', '#6a00a8', '#6c00a8', '#6e00a8', '#6f00a8', '#7100a8', '#7201a8', '#7401a8', '#7501a8', '#7701a8', '#7801a8', '#7a02a8', '#7b02a8', '#7d03a8', '#7e03a8', '#8004a8', '#8104a7', '#8305a7', '#8405a7', '#8606a6', '#8707a6', '#8808a6', '#8a09a5', '#8b0aa5', '#8d0ba5', '#8e0ca4', '#8f0da4', '#910ea3', '#920fa3', '#9410a2', '#9511a1', '#9613a1', '#9814a0', '#99159f', '#9a169f', '#9c179e', '#9d189d', '#9e199d', '#a01a9c', '#a11b9b', '#a21d9a', '#a31e9a', '#a51f99', '#a62098', '#a72197', '#a82296', '#aa2395', '#ab2494', '#ac2694', '#ad2793', '#ae2892', '#b02991', '#b12a90', '#b22b8f', '#b32c8e', '#b42e8d', '#b52f8c', '#b6308b', '#b7318a', '#b83289', '#ba3388', '#bb3488', '#bc3587', '#bd3786', '#be3885', '#bf3984', '#c03a83', '#c13b82', '#c23c81', '#c33d80', '#c43e7f', '#c5407e', '#c6417d', '#c7427c', '#c8437b', '#c9447a', '#ca457a', '#cb4679', '#cc4778', '#cc4977', '#cd4a76', '#ce4b75', '#cf4c74', '#d04d73', '#d14e72', '#d24f71', '#d35171', '#d45270', '#d5536f', '#d5546e', '#d6556d', '#d7566c', '#d8576b', '#d9586a', '#da5a6a', '#da5b69', '#db5c68', '#dc5d67', '#dd5e66', '#de5f65', '#de6164', '#df6263', '#e06363', '#e16462', '#e26561', '#e26660', '#e3685f', '#e4695e', '#e56a5d', '#e56b5d', '#e66c5c', '#e76e5b', '#e76f5a', '#e87059', '#e97158', '#e97257', '#ea7457', '#eb7556', '#eb7655', '#ec7754', '#ed7953', '#ed7a52', '#ee7b51', '#ef7c51', '#ef7e50', '#f07f4f', '#f0804e', '#f1814d', '#f1834c', '#f2844b', '#f3854b', '#f3874a', '#f48849', '#f48948', '#f58b47', '#f58c46', '#f68d45', '#f68f44', '#f79044', '#f79143', '#f79342', '#f89441', '#f89540', '#f9973f', '#f9983e', '#f99a3e', '#fa9b3d', '#fa9c3c', '#fa9e3b', '#fb9f3a', '#fba139', '#fba238', '#fca338', '#fca537', '#fca636', '#fca835', '#fca934', '#fdab33', '#fdac33', '#fdae32', '#fdaf31', '#fdb130', '#fdb22f', '#fdb42f', '#fdb52e', '#feb72d', '#feb82c', '#feba2c', '#febb2b', '#febd2a', '#febe2a', '#fec029', '#fdc229', '#fdc328', '#fdc527', '#fdc627', '#fdc827', '#fdca26', '#fdcb26', '#fccd25', '#fcce25', '#fcd025', '#fcd225', '#fbd324', '#fbd524', '#fbd724', '#fad824', '#fada24', '#f9dc24', '#f9dd25', '#f8df25', '#f8e125', '#f7e225', '#f7e425', '#f6e626', '#f6e826', '#f5e926', '#f5eb27', '#f4ed27', '#f3ee27', '#f3f027', '#f2f227', '#f1f426', '#f1f525', '#f0f724', '#f0f921']); - ColorMapContainer.inferno = ColorMapContainer.fromStringList(['#000004', '#010005', '#010106', '#010108', '#02010a', '#02020c', '#02020e', '#030210', '#040312', '#040314', '#050417', '#060419', '#07051b', '#08051d', '#09061f', '#0a0722', '#0b0724', '#0c0826', '#0d0829', '#0e092b', '#10092d', '#110a30', '#120a32', '#140b34', '#150b37', '#160b39', '#180c3c', '#190c3e', '#1b0c41', '#1c0c43', '#1e0c45', '#1f0c48', '#210c4a', '#230c4c', '#240c4f', '#260c51', '#280b53', '#290b55', '#2b0b57', '#2d0b59', '#2f0a5b', '#310a5c', '#320a5e', '#340a5f', '#360961', '#380962', '#390963', '#3b0964', '#3d0965', '#3e0966', '#400a67', '#420a68', '#440a68', '#450a69', '#470b6a', '#490b6a', '#4a0c6b', '#4c0c6b', '#4d0d6c', '#4f0d6c', '#510e6c', '#520e6d', '#540f6d', '#550f6d', '#57106e', '#59106e', '#5a116e', '#5c126e', '#5d126e', '#5f136e', '#61136e', '#62146e', '#64156e', '#65156e', '#67166e', '#69166e', '#6a176e', '#6c186e', '#6d186e', '#6f196e', '#71196e', '#721a6e', '#741a6e', '#751b6e', '#771c6d', '#781c6d', '#7a1d6d', '#7c1d6d', '#7d1e6d', '#7f1e6c', '#801f6c', '#82206c', '#84206b', '#85216b', '#87216b', '#88226a', '#8a226a', '#8c2369', '#8d2369', '#8f2469', '#902568', '#922568', '#932667', '#952667', '#972766', '#982766', '#9a2865', '#9b2964', '#9d2964', '#9f2a63', '#a02a63', '#a22b62', '#a32c61', '#a52c60', '#a62d60', '#a82e5f', '#a92e5e', '#ab2f5e', '#ad305d', '#ae305c', '#b0315b', '#b1325a', '#b3325a', '#b43359', '#b63458', '#b73557', '#b93556', '#ba3655', '#bc3754', '#bd3853', '#bf3952', '#c03a51', '#c13a50', '#c33b4f', '#c43c4e', '#c63d4d', '#c73e4c', '#c83f4b', '#ca404a', '#cb4149', '#cc4248', '#ce4347', '#cf4446', '#d04545', '#d24644', '#d34743', '#d44842', '#d54a41', '#d74b3f', '#d84c3e', '#d94d3d', '#da4e3c', '#db503b', '#dd513a', '#de5238', '#df5337', '#e05536', '#e15635', '#e25734', '#e35933', '#e45a31', '#e55c30', '#e65d2f', '#e75e2e', '#e8602d', '#e9612b', '#ea632a', '#eb6429', '#eb6628', '#ec6726', '#ed6925', '#ee6a24', '#ef6c23', '#ef6e21', '#f06f20', '#f1711f', '#f1731d', '#f2741c', '#f3761b', '#f37819', '#f47918', '#f57b17', '#f57d15', '#f67e14', '#f68013', '#f78212', '#f78410', '#f8850f', '#f8870e', '#f8890c', '#f98b0b', '#f98c0a', '#f98e09', '#fa9008', '#fa9207', '#fa9407', '#fb9606', '#fb9706', '#fb9906', '#fb9b06', '#fb9d07', '#fc9f07', '#fca108', '#fca309', '#fca50a', '#fca60c', '#fca80d', '#fcaa0f', '#fcac11', '#fcae12', '#fcb014', '#fcb216', '#fcb418', '#fbb61a', '#fbb81d', '#fbba1f', '#fbbc21', '#fbbe23', '#fac026', '#fac228', '#fac42a', '#fac62d', '#f9c72f', '#f9c932', '#f9cb35', '#f8cd37', '#f8cf3a', '#f7d13d', '#f7d340', '#f6d543', '#f6d746', '#f5d949', '#f5db4c', '#f4dd4f', '#f4df53', '#f4e156', '#f3e35a', '#f3e55d', '#f2e661', '#f2e865', '#f2ea69', '#f1ec6d', '#f1ed71', '#f1ef75', '#f1f179', '#f2f27d', '#f2f482', '#f3f586', '#f3f68a', '#f4f88e', '#f5f992', '#f6fa96', '#f8fb9a', '#f9fc9d', '#fafda1', '#fcffa4']); - ColorMapContainer.magma = ColorMapContainer.fromStringList(['#000004', '#010005', '#010106', '#010108', '#020109', '#02020b', '#02020d', '#03030f', '#030312', '#040414', '#050416', '#060518', '#06051a', '#07061c', '#08071e', '#090720', '#0a0822', '#0b0924', '#0c0926', '#0d0a29', '#0e0b2b', '#100b2d', '#110c2f', '#120d31', '#130d34', '#140e36', '#150e38', '#160f3b', '#180f3d', '#19103f', '#1a1042', '#1c1044', '#1d1147', '#1e1149', '#20114b', '#21114e', '#221150', '#241253', '#251255', '#271258', '#29115a', '#2a115c', '#2c115f', '#2d1161', '#2f1163', '#311165', '#331067', '#341069', '#36106b', '#38106c', '#390f6e', '#3b0f70', '#3d0f71', '#3f0f72', '#400f74', '#420f75', '#440f76', '#451077', '#471078', '#491078', '#4a1079', '#4c117a', '#4e117b', '#4f127b', '#51127c', '#52137c', '#54137d', '#56147d', '#57157e', '#59157e', '#5a167e', '#5c167f', '#5d177f', '#5f187f', '#601880', '#621980', '#641a80', '#651a80', '#671b80', '#681c81', '#6a1c81', '#6b1d81', '#6d1d81', '#6e1e81', '#701f81', '#721f81', '#732081', '#752181', '#762181', '#782281', '#792282', '#7b2382', '#7c2382', '#7e2482', '#802582', '#812581', '#832681', '#842681', '#862781', '#882781', '#892881', '#8b2981', '#8c2981', '#8e2a81', '#902a81', '#912b81', '#932b80', '#942c80', '#962c80', '#982d80', '#992d80', '#9b2e7f', '#9c2e7f', '#9e2f7f', '#a02f7f', '#a1307e', '#a3307e', '#a5317e', '#a6317d', '#a8327d', '#aa337d', '#ab337c', '#ad347c', '#ae347b', '#b0357b', '#b2357b', '#b3367a', '#b5367a', '#b73779', '#b83779', '#ba3878', '#bc3978', '#bd3977', '#bf3a77', '#c03a76', '#c23b75', '#c43c75', '#c53c74', '#c73d73', '#c83e73', '#ca3e72', '#cc3f71', '#cd4071', '#cf4070', '#d0416f', '#d2426f', '#d3436e', '#d5446d', '#d6456c', '#d8456c', '#d9466b', '#db476a', '#dc4869', '#de4968', '#df4a68', '#e04c67', '#e24d66', '#e34e65', '#e44f64', '#e55064', '#e75263', '#e85362', '#e95462', '#ea5661', '#eb5760', '#ec5860', '#ed5a5f', '#ee5b5e', '#ef5d5e', '#f05f5e', '#f1605d', '#f2625d', '#f2645c', '#f3655c', '#f4675c', '#f4695c', '#f56b5c', '#f66c5c', '#f66e5c', '#f7705c', '#f7725c', '#f8745c', '#f8765c', '#f9785d', '#f9795d', '#f97b5d', '#fa7d5e', '#fa7f5e', '#fa815f', '#fb835f', '#fb8560', '#fb8761', '#fc8961', '#fc8a62', '#fc8c63', '#fc8e64', '#fc9065', '#fd9266', '#fd9467', '#fd9668', '#fd9869', '#fd9a6a', '#fd9b6b', '#fe9d6c', '#fe9f6d', '#fea16e', '#fea36f', '#fea571', '#fea772', '#fea973', '#feaa74', '#feac76', '#feae77', '#feb078', '#feb27a', '#feb47b', '#feb67c', '#feb77e', '#feb97f', '#febb81', '#febd82', '#febf84', '#fec185', '#fec287', '#fec488', '#fec68a', '#fec88c', '#feca8d', '#fecc8f', '#fecd90', '#fecf92', '#fed194', '#fed395', '#fed597', '#fed799', '#fed89a', '#fdda9c', '#fddc9e', '#fddea0', '#fde0a1', '#fde2a3', '#fde3a5', '#fde5a7', '#fde7a9', '#fde9aa', '#fdebac', '#fcecae', '#fceeb0', '#fcf0b2', '#fcf2b4', '#fcf4b6', '#fcf6b8', '#fcf7b9', '#fcf9bb', '#fcfbbd', '#fcfdbf']); - ColorMapContainer.cividis = ColorMapContainer.fromStringList(['#00224e', '#00234f', '#002451', '#002553', '#002554', '#002656', '#002758', '#002859', '#00285b', '#00295d', '#002a5f', '#002a61', '#002b62', '#002c64', '#002c66', '#002d68', '#002e6a', '#002e6c', '#002f6d', '#00306f', '#003070', '#003170', '#003171', '#013271', '#053371', '#083370', '#0c3470', '#0f3570', '#123570', '#143670', '#163770', '#18376f', '#1a386f', '#1c396f', '#1e3a6f', '#203a6f', '#213b6e', '#233c6e', '#243c6e', '#263d6e', '#273e6e', '#293f6e', '#2a3f6d', '#2b406d', '#2d416d', '#2e416d', '#2f426d', '#31436d', '#32436d', '#33446d', '#34456c', '#35456c', '#36466c', '#38476c', '#39486c', '#3a486c', '#3b496c', '#3c4a6c', '#3d4a6c', '#3e4b6c', '#3f4c6c', '#404c6c', '#414d6c', '#424e6c', '#434e6c', '#444f6c', '#45506c', '#46516c', '#47516c', '#48526c', '#49536c', '#4a536c', '#4b546c', '#4c556c', '#4d556c', '#4e566c', '#4f576c', '#50576c', '#51586d', '#52596d', '#535a6d', '#545a6d', '#555b6d', '#555c6d', '#565c6d', '#575d6d', '#585e6d', '#595e6e', '#5a5f6e', '#5b606e', '#5c616e', '#5d616e', '#5e626e', '#5e636f', '#5f636f', '#60646f', '#61656f', '#62656f', '#636670', '#646770', '#656870', '#656870', '#666970', '#676a71', '#686a71', '#696b71', '#6a6c71', '#6b6d72', '#6c6d72', '#6c6e72', '#6d6f72', '#6e6f73', '#6f7073', '#707173', '#717274', '#727274', '#727374', '#737475', '#747475', '#757575', '#767676', '#777776', '#777777', '#787877', '#797977', '#7a7a78', '#7b7a78', '#7c7b78', '#7d7c78', '#7e7c78', '#7e7d78', '#7f7e78', '#807f78', '#817f78', '#828079', '#838179', '#848279', '#858279', '#868379', '#878478', '#888578', '#898578', '#8a8678', '#8b8778', '#8c8878', '#8d8878', '#8e8978', '#8f8a78', '#908b78', '#918b78', '#928c78', '#928d78', '#938e78', '#948e77', '#958f77', '#969077', '#979177', '#989277', '#999277', '#9a9376', '#9b9476', '#9c9576', '#9d9576', '#9e9676', '#9f9775', '#a09875', '#a19975', '#a29975', '#a39a74', '#a49b74', '#a59c74', '#a69c74', '#a79d73', '#a89e73', '#a99f73', '#aaa073', '#aba072', '#aca172', '#ada272', '#aea371', '#afa471', '#b0a571', '#b1a570', '#b3a670', '#b4a76f', '#b5a86f', '#b6a96f', '#b7a96e', '#b8aa6e', '#b9ab6d', '#baac6d', '#bbad6d', '#bcae6c', '#bdae6c', '#beaf6b', '#bfb06b', '#c0b16a', '#c1b26a', '#c2b369', '#c3b369', '#c4b468', '#c5b568', '#c6b667', '#c7b767', '#c8b866', '#c9b965', '#cbb965', '#ccba64', '#cdbb63', '#cebc63', '#cfbd62', '#d0be62', '#d1bf61', '#d2c060', '#d3c05f', '#d4c15f', '#d5c25e', '#d6c35d', '#d7c45c', '#d9c55c', '#dac65b', '#dbc75a', '#dcc859', '#ddc858', '#dec958', '#dfca57', '#e0cb56', '#e1cc55', '#e2cd54', '#e4ce53', '#e5cf52', '#e6d051', '#e7d150', '#e8d24f', '#e9d34e', '#ead34c', '#ebd44b', '#edd54a', '#eed649', '#efd748', '#f0d846', '#f1d945', '#f2da44', '#f3db42', '#f5dc41', '#f6dd3f', '#f7de3e', '#f8df3c', '#f9e03a', '#fbe138', '#fce236', '#fde334', '#fee434', '#fee535', '#fee636', '#fee838']); - ColorMapContainer.greys = ColorMapContainer.fromStringList(['#ffffff', '#ffffff', '#fefefe', '#fefefe', '#fdfdfd', '#fdfdfd', '#fcfcfc', '#fcfcfc', '#fbfbfb', '#fbfbfb', '#fafafa', '#fafafa', '#f9f9f9', '#f9f9f9', '#f8f8f8', '#f8f8f8', '#f7f7f7', '#f7f7f7', '#f7f7f7', '#f6f6f6', '#f6f6f6', '#f5f5f5', '#f5f5f5', '#f4f4f4', '#f4f4f4', '#f3f3f3', '#f3f3f3', '#f2f2f2', '#f2f2f2', '#f1f1f1', '#f1f1f1', '#f0f0f0', '#f0f0f0', '#efefef', '#eeeeee', '#eeeeee', '#ededed', '#ececec', '#ececec', '#ebebeb', '#eaeaea', '#e9e9e9', '#e9e9e9', '#e8e8e8', '#e7e7e7', '#e7e7e7', '#e6e6e6', '#e5e5e5', '#e4e4e4', '#e4e4e4', '#e3e3e3', '#e2e2e2', '#e1e1e1', '#e1e1e1', '#e0e0e0', '#dfdfdf', '#dfdfdf', '#dedede', '#dddddd', '#dcdcdc', '#dcdcdc', '#dbdbdb', '#dadada', '#dadada', '#d9d9d9', '#d8d8d8', '#d7d7d7', '#d6d6d6', '#d5d5d5', '#d4d4d4', '#d4d4d4', '#d3d3d3', '#d2d2d2', '#d1d1d1', '#d0d0d0', '#cfcfcf', '#cecece', '#cdcdcd', '#cccccc', '#cccccc', '#cbcbcb', '#cacaca', '#c9c9c9', '#c8c8c8', '#c7c7c7', '#c6c6c6', '#c5c5c5', '#c5c5c5', '#c4c4c4', '#c3c3c3', '#c2c2c2', '#c1c1c1', '#c0c0c0', '#bfbfbf', '#bebebe', '#bebebe', '#bdbdbd', '#bbbbbb', '#bababa', '#b9b9b9', '#b8b8b8', '#b6b6b6', '#b5b5b5', '#b4b4b4', '#b3b3b3', '#b2b2b2', '#b0b0b0', '#afafaf', '#aeaeae', '#adadad', '#ababab', '#aaaaaa', '#a9a9a9', '#a8a8a8', '#a7a7a7', '#a5a5a5', '#a4a4a4', '#a3a3a3', '#a2a2a2', '#a0a0a0', '#9f9f9f', '#9e9e9e', '#9d9d9d', '#9c9c9c', '#9a9a9a', '#999999', '#989898', '#979797', '#959595', '#949494', '#939393', '#929292', '#919191', '#909090', '#8f8f8f', '#8e8e8e', '#8d8d8d', '#8c8c8c', '#8a8a8a', '#898989', '#888888', '#878787', '#868686', '#858585', '#848484', '#838383', '#828282', '#818181', '#7f7f7f', '#7e7e7e', '#7d7d7d', '#7c7c7c', '#7b7b7b', '#7a7a7a', '#797979', '#787878', '#777777', '#767676', '#757575', '#737373', '#727272', '#717171', '#707070', '#6f6f6f', '#6e6e6e', '#6d6d6d', '#6c6c6c', '#6b6b6b', '#6a6a6a', '#696969', '#686868', '#676767', '#666666', '#656565', '#646464', '#636363', '#626262', '#616161', '#606060', '#5f5f5f', '#5e5e5e', '#5d5d5d', '#5c5c5c', '#5b5b5b', '#5a5a5a', '#585858', '#575757', '#565656', '#555555', '#545454', '#535353', '#525252', '#515151', '#505050', '#4e4e4e', '#4d4d4d', '#4b4b4b', '#4a4a4a', '#484848', '#474747', '#464646', '#444444', '#434343', '#414141', '#404040', '#3f3f3f', '#3d3d3d', '#3c3c3c', '#3a3a3a', '#393939', '#383838', '#363636', '#353535', '#333333', '#323232', '#303030', '#2f2f2f', '#2e2e2e', '#2c2c2c', '#2b2b2b', '#292929', '#282828', '#272727', '#252525', '#242424', '#232323', '#222222', '#212121', '#1f1f1f', '#1e1e1e', '#1d1d1d', '#1c1c1c', '#1b1b1b', '#1a1a1a', '#181818', '#171717', '#161616', '#151515', '#141414', '#131313', '#111111', '#101010', '#0f0f0f', '#0e0e0e', '#0d0d0d', '#0c0c0c', '#0a0a0a', '#090909', '#080808', '#070707', '#060606', '#050505', '#030303', '#020202', '#010101', '#000000']); - ColorMapContainer.gray = ColorMapContainer.fromStringList(['#000000', '#010101', '#020202', '#030303', '#040404', '#050505', '#060606', '#070707', '#080808', '#090909', '#0a0a0a', '#0b0b0b', '#0c0c0c', '#0d0d0d', '#0e0e0e', '#0f0f0f', '#101010', '#111111', '#121212', '#131313', '#141414', '#151515', '#161616', '#171717', '#181818', '#191919', '#1a1a1a', '#1b1b1b', '#1c1c1c', '#1d1d1d', '#1e1e1e', '#1f1f1f', '#202020', '#212121', '#222222', '#232323', '#242424', '#252525', '#262626', '#272727', '#282828', '#292929', '#2a2a2a', '#2b2b2b', '#2c2c2c', '#2d2d2d', '#2e2e2e', '#2f2f2f', '#303030', '#313131', '#323232', '#333333', '#343434', '#353535', '#363636', '#373737', '#383838', '#393939', '#3a3a3a', '#3b3b3b', '#3c3c3c', '#3d3d3d', '#3e3e3e', '#3f3f3f', '#404040', '#414141', '#424242', '#434343', '#444444', '#454545', '#464646', '#474747', '#484848', '#494949', '#4a4a4a', '#4b4b4b', '#4c4c4c', '#4d4d4d', '#4e4e4e', '#4f4f4f', '#505050', '#515151', '#525252', '#535353', '#545454', '#555555', '#565656', '#575757', '#585858', '#595959', '#5a5a5a', '#5b5b5b', '#5c5c5c', '#5d5d5d', '#5e5e5e', '#5f5f5f', '#606060', '#616161', '#626262', '#636363', '#646464', '#656565', '#666666', '#676767', '#686868', '#696969', '#6a6a6a', '#6b6b6b', '#6c6c6c', '#6d6d6d', '#6e6e6e', '#6f6f6f', '#707070', '#717171', '#727272', '#737373', '#747474', '#757575', '#767676', '#777777', '#787878', '#797979', '#7a7a7a', '#7b7b7b', '#7c7c7c', '#7d7d7d', '#7e7e7e', '#7f7f7f', '#808080', '#818181', '#828282', '#838383', '#848484', '#858585', '#868686', '#878787', '#888888', '#898989', '#8a8a8a', '#8b8b8b', '#8c8c8c', '#8d8d8d', '#8e8e8e', '#8f8f8f', '#909090', '#919191', '#929292', '#939393', '#949494', '#959595', '#969696', '#979797', '#989898', '#999999', '#9a9a9a', '#9b9b9b', '#9c9c9c', '#9d9d9d', '#9e9e9e', '#9f9f9f', '#a0a0a0', '#a1a1a1', '#a2a2a2', '#a3a3a3', '#a4a4a4', '#a5a5a5', '#a6a6a6', '#a7a7a7', '#a8a8a8', '#a9a9a9', '#aaaaaa', '#ababab', '#acacac', '#adadad', '#aeaeae', '#afafaf', '#b0b0b0', '#b1b1b1', '#b2b2b2', '#b3b3b3', '#b4b4b4', '#b5b5b5', '#b6b6b6', '#b7b7b7', '#b8b8b8', '#b9b9b9', '#bababa', '#bbbbbb', '#bcbcbc', '#bdbdbd', '#bebebe', '#bfbfbf', '#c0c0c0', '#c1c1c1', '#c2c2c2', '#c3c3c3', '#c4c4c4', '#c5c5c5', '#c6c6c6', '#c7c7c7', '#c8c8c8', '#c9c9c9', '#cacaca', '#cbcbcb', '#cccccc', '#cdcdcd', '#cecece', '#cfcfcf', '#d0d0d0', '#d1d1d1', '#d2d2d2', '#d3d3d3', '#d4d4d4', '#d5d5d5', '#d6d6d6', '#d7d7d7', '#d8d8d8', '#d9d9d9', '#dadada', '#dbdbdb', '#dcdcdc', '#dddddd', '#dedede', '#dfdfdf', '#e0e0e0', '#e1e1e1', '#e2e2e2', '#e3e3e3', '#e4e4e4', '#e5e5e5', '#e6e6e6', '#e7e7e7', '#e8e8e8', '#e9e9e9', '#eaeaea', '#ebebeb', '#ececec', '#ededed', '#eeeeee', '#efefef', '#f0f0f0', '#f1f1f1', '#f2f2f2', '#f3f3f3', '#f4f4f4', '#f5f5f5', '#f6f6f6', '#f7f7f7', '#f8f8f8', '#f9f9f9', '#fafafa', '#fbfbfb', '#fcfcfc', '#fdfdfd', '#fefefe', '#ffffff']); - ColorMapContainer.purples = ColorMapContainer.fromStringList(['#fcfbfd', '#fcfbfd', '#fbfafc', '#fbfafc', '#faf9fc', '#faf9fc', '#faf8fb', '#f9f8fb', '#f9f7fb', '#f8f7fb', '#f8f7fa', '#f8f6fa', '#f7f6fa', '#f7f5fa', '#f6f5f9', '#f6f4f9', '#f5f4f9', '#f5f4f9', '#f5f3f8', '#f4f3f8', '#f4f2f8', '#f3f2f8', '#f3f1f7', '#f3f1f7', '#f2f0f7', '#f2f0f7', '#f1f0f6', '#f1eff6', '#f1eff6', '#f0eef6', '#f0eef5', '#efedf5', '#efedf5', '#eeecf5', '#eeecf4', '#edebf4', '#ecebf4', '#eceaf3', '#ebe9f3', '#eae9f3', '#eae8f2', '#e9e8f2', '#e8e7f2', '#e8e6f2', '#e7e6f1', '#e6e5f1', '#e6e5f1', '#e5e4f0', '#e4e3f0', '#e4e3f0', '#e3e2ef', '#e2e2ef', '#e2e1ef', '#e1e0ee', '#e0e0ee', '#e0dfee', '#dfdfed', '#dedeed', '#dedded', '#ddddec', '#dcdcec', '#dcdcec', '#dbdbec', '#dadaeb', '#dadaeb', '#d9d9ea', '#d8d8ea', '#d7d7e9', '#d6d6e9', '#d5d5e9', '#d4d4e8', '#d3d3e8', '#d2d2e7', '#d1d2e7', '#d0d1e6', '#cfd0e6', '#cecfe5', '#cecee5', '#cdcde4', '#cccce4', '#cbcbe3', '#cacae3', '#c9c9e2', '#c8c8e2', '#c7c8e1', '#c6c7e1', '#c5c6e1', '#c4c5e0', '#c3c4e0', '#c2c3df', '#c1c2df', '#c0c1de', '#bfc0de', '#bebfdd', '#bebedd', '#bdbedc', '#bcbddc', '#bbbbdb', '#babadb', '#b9b9da', '#b8b8d9', '#b7b7d9', '#b6b6d8', '#b5b5d7', '#b4b4d7', '#b3b3d6', '#b2b2d5', '#b1b1d5', '#b0afd4', '#afaed4', '#aeadd3', '#aeacd2', '#adabd2', '#acaad1', '#aba9d0', '#aaa8d0', '#a9a7cf', '#a8a6cf', '#a7a4ce', '#a6a3cd', '#a5a2cd', '#a4a1cc', '#a3a0cb', '#a29fcb', '#a19eca', '#a09dca', '#9f9cc9', '#9e9bc8', '#9e9ac8', '#9d99c7', '#9c98c7', '#9b97c6', '#9a96c6', '#9995c6', '#9894c5', '#9793c5', '#9692c4', '#9591c4', '#9490c3', '#9390c3', '#928fc3', '#918ec2', '#908dc2', '#8f8cc1', '#8e8bc1', '#8e8ac0', '#8d89c0', '#8c88bf', '#8b87bf', '#8a86bf', '#8986be', '#8885be', '#8784bd', '#8683bd', '#8582bc', '#8481bc', '#8380bb', '#827fbb', '#817ebb', '#807dba', '#807cba', '#7f7bb9', '#7e79b8', '#7d78b7', '#7d77b7', '#7c75b6', '#7b74b5', '#7b72b4', '#7a71b4', '#7970b3', '#796eb2', '#786db2', '#776cb1', '#776ab0', '#7669af', '#7567af', '#7566ae', '#7465ad', '#7363ad', '#7262ac', '#7261ab', '#715faa', '#705eaa', '#705ca9', '#6f5ba8', '#6e5aa8', '#6e58a7', '#6d57a6', '#6c55a5', '#6c54a5', '#6b53a4', '#6a51a3', '#6950a3', '#694fa2', '#684da1', '#674ca1', '#674ba0', '#66499f', '#65489f', '#65479e', '#64459e', '#63449d', '#63439c', '#62429c', '#61409b', '#613f9a', '#603e9a', '#5f3c99', '#5e3b98', '#5e3a98', '#5d3897', '#5c3797', '#5c3696', '#5b3495', '#5a3395', '#5a3294', '#593093', '#582f93', '#582e92', '#572c92', '#562b91', '#552a90', '#552890', '#54278f', '#53268f', '#53258e', '#52238d', '#51228d', '#51218c', '#50208c', '#4f1f8b', '#4f1d8b', '#4e1c8a', '#4d1b89', '#4d1a89', '#4c1888', '#4c1788', '#4b1687', '#4a1587', '#4a1486', '#491285', '#481185', '#481084', '#470f84', '#460d83', '#460c83', '#450b82', '#440a82', '#440981', '#430780', '#420680', '#42057f', '#41047f', '#40027e', '#40017e', '#3f007d']); - ColorMapContainer.blues = ColorMapContainer.fromStringList(['#f7fbff', '#f6faff', '#f5fafe', '#f5f9fe', '#f4f9fe', '#f3f8fe', '#f2f8fd', '#f2f7fd', '#f1f7fd', '#f0f6fd', '#eff6fc', '#eef5fc', '#eef5fc', '#edf4fc', '#ecf4fb', '#ebf3fb', '#eaf3fb', '#eaf2fb', '#e9f2fa', '#e8f1fa', '#e7f1fa', '#e7f0fa', '#e6f0f9', '#e5eff9', '#e4eff9', '#e3eef9', '#e3eef8', '#e2edf8', '#e1edf8', '#e0ecf8', '#dfecf7', '#dfebf7', '#deebf7', '#ddeaf7', '#dceaf6', '#dce9f6', '#dbe9f6', '#dae8f6', '#d9e8f5', '#d9e7f5', '#d8e7f5', '#d7e6f5', '#d6e6f4', '#d6e5f4', '#d5e5f4', '#d4e4f4', '#d3e4f3', '#d3e3f3', '#d2e3f3', '#d1e2f3', '#d0e2f2', '#d0e1f2', '#cfe1f2', '#cee0f2', '#cde0f1', '#cddff1', '#ccdff1', '#cbdef1', '#cadef0', '#caddf0', '#c9ddf0', '#c8dcf0', '#c7dcef', '#c7dbef', '#c6dbef', '#c4daee', '#c3daee', '#c2d9ee', '#c1d9ed', '#bfd8ed', '#bed8ec', '#bdd7ec', '#bcd7eb', '#bad6eb', '#b9d6ea', '#b8d5ea', '#b7d4ea', '#b5d4e9', '#b4d3e9', '#b3d3e8', '#b2d2e8', '#b0d2e7', '#afd1e7', '#aed1e7', '#add0e6', '#abd0e6', '#aacfe5', '#a9cfe5', '#a8cee4', '#a6cee4', '#a5cde3', '#a4cce3', '#a3cce3', '#a1cbe2', '#a0cbe2', '#9fcae1', '#9dcae1', '#9cc9e1', '#9ac8e0', '#99c7e0', '#97c6df', '#95c5df', '#94c4df', '#92c4de', '#91c3de', '#8fc2de', '#8dc1dd', '#8cc0dd', '#8abfdd', '#89bedc', '#87bddc', '#85bcdc', '#84bcdb', '#82bbdb', '#81badb', '#7fb9da', '#7db8da', '#7cb7da', '#7ab6d9', '#79b5d9', '#77b5d9', '#75b4d8', '#74b3d8', '#72b2d8', '#71b1d7', '#6fb0d7', '#6dafd7', '#6caed6', '#6aaed6', '#69add5', '#68acd5', '#66abd4', '#65aad4', '#64a9d3', '#63a8d3', '#61a7d2', '#60a7d2', '#5fa6d1', '#5da5d1', '#5ca4d0', '#5ba3d0', '#5aa2cf', '#58a1cf', '#57a0ce', '#56a0ce', '#549fcd', '#539ecd', '#529dcc', '#519ccc', '#4f9bcb', '#4e9acb', '#4d99ca', '#4b98ca', '#4a98c9', '#4997c9', '#4896c8', '#4695c8', '#4594c7', '#4493c7', '#4292c6', '#4191c6', '#4090c5', '#3f8fc5', '#3e8ec4', '#3d8dc4', '#3c8cc3', '#3b8bc2', '#3a8ac2', '#3989c1', '#3888c1', '#3787c0', '#3686c0', '#3585bf', '#3484bf', '#3383be', '#3282be', '#3181bd', '#3080bd', '#2f7fbc', '#2e7ebc', '#2d7dbb', '#2c7cba', '#2b7bba', '#2a7ab9', '#2979b9', '#2777b8', '#2676b8', '#2575b7', '#2474b7', '#2373b6', '#2272b6', '#2171b5', '#2070b4', '#206fb4', '#1f6eb3', '#1e6db2', '#1d6cb1', '#1c6bb0', '#1c6ab0', '#1b69af', '#1a68ae', '#1967ad', '#1966ad', '#1865ac', '#1764ab', '#1663aa', '#1562a9', '#1561a9', '#1460a8', '#135fa7', '#125ea6', '#125da6', '#115ca5', '#105ba4', '#0f5aa3', '#0e59a2', '#0e58a2', '#0d57a1', '#0c56a0', '#0b559f', '#0a549e', '#0a539e', '#09529d', '#08519c', '#08509b', '#084f99', '#084e98', '#084d96', '#084c95', '#084b93', '#084a91', '#084990', '#08488e', '#08478d', '#08468b', '#08458a', '#084488', '#084387', '#084285', '#084184', '#084082', '#083e81', '#083d7f', '#083c7d', '#083b7c', '#083a7a', '#083979', '#083877', '#083776', '#083674', '#083573', '#083471', '#083370', '#08326e', '#08316d', '#08306b']); - ColorMapContainer.greens = ColorMapContainer.fromStringList(['#f7fcf5', '#f6fcf4', '#f6fcf4', '#f5fbf3', '#f5fbf2', '#f4fbf2', '#f4fbf1', '#f3faf0', '#f2faf0', '#f2faef', '#f1faee', '#f1faee', '#f0f9ed', '#f0f9ec', '#eff9ec', '#eff9eb', '#eef8ea', '#edf8ea', '#edf8e9', '#ecf8e8', '#ecf8e8', '#ebf7e7', '#ebf7e7', '#eaf7e6', '#e9f7e5', '#e9f7e5', '#e8f6e4', '#e8f6e3', '#e7f6e3', '#e7f6e2', '#e6f5e1', '#e5f5e1', '#e5f5e0', '#e4f5df', '#e3f4de', '#e2f4dd', '#e1f3dc', '#e0f3db', '#dff3da', '#def2d9', '#ddf2d8', '#dcf2d7', '#dbf1d6', '#dbf1d5', '#daf0d4', '#d9f0d3', '#d8f0d2', '#d7efd1', '#d6efd0', '#d5efcf', '#d4eece', '#d3eecd', '#d2edcc', '#d1edcb', '#d0edca', '#cfecc9', '#ceecc8', '#cdecc7', '#ccebc6', '#cbebc5', '#cbeac4', '#caeac3', '#c9eac2', '#c8e9c1', '#c7e9c0', '#c6e8bf', '#c4e8bd', '#c3e7bc', '#c2e7bb', '#c1e6ba', '#c0e6b9', '#bee5b8', '#bde5b6', '#bce4b5', '#bbe4b4', '#bae3b3', '#b8e3b2', '#b7e2b1', '#b6e2af', '#b5e1ae', '#b4e1ad', '#b2e0ac', '#b1e0ab', '#b0dfaa', '#afdfa8', '#aedea7', '#acdea6', '#abdda5', '#aadda4', '#a9dca3', '#a8dca2', '#a7dba0', '#a5db9f', '#a4da9e', '#a3da9d', '#a2d99c', '#a0d99b', '#9fd899', '#9ed798', '#9cd797', '#9bd696', '#99d595', '#98d594', '#97d492', '#95d391', '#94d390', '#92d28f', '#91d28e', '#90d18d', '#8ed08b', '#8dd08a', '#8bcf89', '#8ace88', '#88ce87', '#87cd86', '#86cc85', '#84cc83', '#83cb82', '#81ca81', '#80ca80', '#7fc97f', '#7dc87e', '#7cc87c', '#7ac77b', '#79c67a', '#78c679', '#76c578', '#75c477', '#73c476', '#72c375', '#70c274', '#6ec173', '#6dc072', '#6bc072', '#6abf71', '#68be70', '#66bd6f', '#65bd6f', '#63bc6e', '#62bb6d', '#60ba6c', '#5eb96b', '#5db96b', '#5bb86a', '#5ab769', '#58b668', '#56b567', '#55b567', '#53b466', '#52b365', '#50b264', '#4eb264', '#4db163', '#4bb062', '#4aaf61', '#48ae60', '#46ae60', '#45ad5f', '#43ac5e', '#42ab5d', '#40aa5d', '#3fa95c', '#3fa85b', '#3ea75a', '#3da65a', '#3ca559', '#3ba458', '#3aa357', '#39a257', '#38a156', '#37a055', '#369f54', '#359e53', '#349d53', '#339c52', '#329b51', '#319a50', '#309950', '#2f984f', '#2f974e', '#2e964d', '#2d954d', '#2c944c', '#2b934b', '#2a924a', '#29914a', '#289049', '#278f48', '#268e47', '#258d47', '#248c46', '#238b45', '#228a44', '#218944', '#208843', '#1f8742', '#1e8741', '#1d8640', '#1c8540', '#1a843f', '#19833e', '#18823d', '#17813d', '#16803c', '#157f3b', '#147e3a', '#137d39', '#127c39', '#117b38', '#107a37', '#0e7936', '#0d7836', '#0c7735', '#0b7734', '#0a7633', '#097532', '#087432', '#077331', '#067230', '#05712f', '#03702e', '#026f2e', '#016e2d', '#006d2c', '#006c2c', '#006b2b', '#00692a', '#00682a', '#006729', '#006529', '#006428', '#006328', '#006227', '#006027', '#005f26', '#005e26', '#005c25', '#005b25', '#005a24', '#005924', '#005723', '#005622', '#005522', '#005321', '#005221', '#005120', '#005020', '#004e1f', '#004d1f', '#004c1e', '#004a1e', '#00491d', '#00481d', '#00471c', '#00451c', '#00441b']); - ColorMapContainer.oranges = ColorMapContainer.fromStringList(['#fff5eb', '#fff5ea', '#fff4e9', '#fff4e8', '#fff3e7', '#fff3e6', '#fff2e6', '#fff2e5', '#fff1e4', '#fff1e3', '#fff0e2', '#fff0e1', '#ffefe0', '#ffefdf', '#ffeede', '#ffeedd', '#feeddc', '#feeddc', '#feeddb', '#feecda', '#feecd9', '#feebd8', '#feebd7', '#feead6', '#feead5', '#fee9d4', '#fee9d3', '#fee8d2', '#fee8d2', '#fee7d1', '#fee7d0', '#fee6cf', '#fee6ce', '#fee5cc', '#fee5cb', '#fee4ca', '#fee3c8', '#fee2c7', '#fee2c6', '#fee1c4', '#fee0c3', '#fee0c1', '#fedfc0', '#fedebf', '#fedebd', '#feddbc', '#fedcbb', '#fedcb9', '#fddbb8', '#fddab6', '#fdd9b5', '#fdd9b4', '#fdd8b2', '#fdd7b1', '#fdd7af', '#fdd6ae', '#fdd5ad', '#fdd5ab', '#fdd4aa', '#fdd3a9', '#fdd3a7', '#fdd2a6', '#fdd1a4', '#fdd1a3', '#fdd0a2', '#fdcfa0', '#fdce9e', '#fdcd9c', '#fdcb9b', '#fdca99', '#fdc997', '#fdc895', '#fdc794', '#fdc692', '#fdc590', '#fdc48f', '#fdc38d', '#fdc28b', '#fdc189', '#fdc088', '#fdbf86', '#fdbe84', '#fdbd83', '#fdbb81', '#fdba7f', '#fdb97d', '#fdb87c', '#fdb77a', '#fdb678', '#fdb576', '#fdb475', '#fdb373', '#fdb271', '#fdb170', '#fdb06e', '#fdaf6c', '#fdae6a', '#fdad69', '#fdac67', '#fdab66', '#fda965', '#fda863', '#fda762', '#fda660', '#fda55f', '#fda45d', '#fda35c', '#fda25a', '#fda159', '#fda057', '#fd9f56', '#fd9e54', '#fd9d53', '#fd9c51', '#fd9b50', '#fd9a4e', '#fd994d', '#fd984b', '#fd974a', '#fd9649', '#fd9547', '#fd9446', '#fd9344', '#fd9243', '#fd9141', '#fd9040', '#fd8f3e', '#fd8e3d', '#fd8c3b', '#fc8b3a', '#fc8a39', '#fc8937', '#fb8836', '#fb8735', '#fb8634', '#fa8532', '#fa8331', '#f98230', '#f9812e', '#f9802d', '#f87f2c', '#f87e2b', '#f87d29', '#f77b28', '#f77a27', '#f67925', '#f67824', '#f67723', '#f57622', '#f57520', '#f5741f', '#f4721e', '#f4711c', '#f3701b', '#f36f1a', '#f36e19', '#f26d17', '#f26c16', '#f26b15', '#f16913', '#f16813', '#f06712', '#ef6612', '#ee6511', '#ee6410', '#ed6310', '#ec620f', '#eb610f', '#eb600e', '#ea5f0e', '#e95e0d', '#e85d0c', '#e75c0c', '#e75b0b', '#e65a0b', '#e5590a', '#e4580a', '#e45709', '#e35608', '#e25508', '#e15407', '#e15307', '#e05206', '#df5106', '#de5005', '#de4e05', '#dd4d04', '#dc4c03', '#db4b03', '#db4a02', '#da4902', '#d94801', '#d84801', '#d64701', '#d54601', '#d34601', '#d14501', '#d04501', '#ce4401', '#cd4401', '#cb4302', '#c94202', '#c84202', '#c64102', '#c54102', '#c34002', '#c14002', '#c03f02', '#be3f02', '#bd3e02', '#bb3d02', '#b93d02', '#b83c02', '#b63c02', '#b53b02', '#b33b02', '#b13a03', '#b03903', '#ae3903', '#ad3803', '#ab3803', '#a93703', '#a83703', '#a63603', '#a53603', '#a43503', '#a23503', '#a13403', '#a03403', '#9f3303', '#9e3303', '#9c3203', '#9b3203', '#9a3103', '#993103', '#973003', '#963003', '#952f03', '#942f03', '#932f03', '#912e04', '#902e04', '#8f2d04', '#8e2d04', '#8c2c04', '#8b2c04', '#8a2b04', '#892b04', '#882a04', '#862a04', '#852904', '#842904', '#832804', '#812804', '#802704', '#7f2704']); - ColorMapContainer.reds = ColorMapContainer.fromStringList(['#fff5f0', '#fff4ef', '#fff4ee', '#fff3ed', '#fff2ec', '#fff2eb', '#fff1ea', '#fff0e9', '#fff0e8', '#ffefe8', '#ffeee7', '#ffeee6', '#ffede5', '#ffece4', '#ffece3', '#ffebe2', '#feeae1', '#feeae0', '#fee9df', '#fee8de', '#fee8dd', '#fee7dc', '#fee7db', '#fee6da', '#fee5d9', '#fee5d8', '#fee4d8', '#fee3d7', '#fee3d6', '#fee2d5', '#fee1d4', '#fee1d3', '#fee0d2', '#fedfd0', '#fedecf', '#fedccd', '#fedbcc', '#fedaca', '#fed9c9', '#fed8c7', '#fdd7c6', '#fdd5c4', '#fdd4c2', '#fdd3c1', '#fdd2bf', '#fdd1be', '#fdd0bc', '#fdcebb', '#fdcdb9', '#fdccb8', '#fdcbb6', '#fdcab5', '#fdc9b3', '#fdc7b2', '#fdc6b0', '#fdc5ae', '#fcc4ad', '#fcc3ab', '#fcc2aa', '#fcc1a8', '#fcbfa7', '#fcbea5', '#fcbda4', '#fcbca2', '#fcbba1', '#fcb99f', '#fcb89e', '#fcb79c', '#fcb69b', '#fcb499', '#fcb398', '#fcb296', '#fcb095', '#fcaf93', '#fcae92', '#fcad90', '#fcab8f', '#fcaa8d', '#fca98c', '#fca78b', '#fca689', '#fca588', '#fca486', '#fca285', '#fca183', '#fca082', '#fc9e80', '#fc9d7f', '#fc9c7d', '#fc9b7c', '#fc997a', '#fc9879', '#fc9777', '#fc9576', '#fc9474', '#fc9373', '#fc9272', '#fc9070', '#fc8f6f', '#fc8e6e', '#fc8d6d', '#fc8b6b', '#fc8a6a', '#fc8969', '#fc8767', '#fc8666', '#fc8565', '#fc8464', '#fc8262', '#fc8161', '#fc8060', '#fc7f5f', '#fb7d5d', '#fb7c5c', '#fb7b5b', '#fb7a5a', '#fb7858', '#fb7757', '#fb7656', '#fb7555', '#fb7353', '#fb7252', '#fb7151', '#fb7050', '#fb6e4e', '#fb6d4d', '#fb6c4c', '#fb6b4b', '#fb694a', '#fa6849', '#fa6648', '#fa6547', '#f96346', '#f96245', '#f96044', '#f85f43', '#f85d42', '#f75c41', '#f75b40', '#f7593f', '#f6583e', '#f6563d', '#f6553c', '#f5533b', '#f5523a', '#f4503a', '#f44f39', '#f44d38', '#f34c37', '#f34a36', '#f34935', '#f24734', '#f24633', '#f14432', '#f14331', '#f14130', '#f0402f', '#f03f2e', '#f03d2d', '#ef3c2c', '#ee3a2c', '#ed392b', '#ec382b', '#eb372a', '#ea362a', '#e93529', '#e83429', '#e63328', '#e53228', '#e43027', '#e32f27', '#e22e27', '#e12d26', '#e02c26', '#de2b25', '#dd2a25', '#dc2924', '#db2824', '#da2723', '#d92523', '#d82422', '#d72322', '#d52221', '#d42121', '#d32020', '#d21f20', '#d11e1f', '#d01d1f', '#cf1c1f', '#ce1a1e', '#cc191e', '#cb181d', '#ca181d', '#c9181d', '#c8171c', '#c7171c', '#c5171c', '#c4161c', '#c3161b', '#c2161b', '#c1161b', '#bf151b', '#be151a', '#bd151a', '#bc141a', '#bb141a', '#b91419', '#b81419', '#b71319', '#b61319', '#b51318', '#b31218', '#b21218', '#b11218', '#b01217', '#af1117', '#ad1117', '#ac1117', '#ab1016', '#aa1016', '#a91016', '#a81016', '#a60f15', '#a50f15', '#a30f15', '#a10e15', '#9f0e14', '#9d0d14', '#9c0d14', '#9a0c14', '#980c13', '#960b13', '#940b13', '#920a13', '#900a12', '#8e0912', '#8c0912', '#8a0812', '#880811', '#860811', '#840711', '#820711', '#800610', '#7e0610', '#7c0510', '#7a0510', '#79040f', '#77040f', '#75030f', '#73030f', '#71020e', '#6f020e', '#6d010e', '#6b010e', '#69000d', '#67000d']); - ColorMapContainer.rdYlBu = ColorMapContainer.fromStringList(['#a50026', '#a70226', '#a90426', '#ab0626', '#ad0826', '#af0926', '#b10b26', '#b30d26', '#b50f26', '#b71126', '#b91326', '#bb1526', '#bd1726', '#be1827', '#c01a27', '#c21c27', '#c41e27', '#c62027', '#c82227', '#ca2427', '#cc2627', '#ce2827', '#d02927', '#d22b27', '#d42d27', '#d62f27', '#d83128', '#d93429', '#da362a', '#db382b', '#dc3b2c', '#dd3d2d', '#de402e', '#e0422f', '#e14430', '#e24731', '#e34933', '#e44c34', '#e54e35', '#e65036', '#e75337', '#e95538', '#ea5739', '#eb5a3a', '#ec5c3b', '#ed5f3c', '#ee613e', '#ef633f', '#f16640', '#f26841', '#f36b42', '#f46d43', '#f47044', '#f57245', '#f57547', '#f57748', '#f67a49', '#f67c4a', '#f67f4b', '#f7814c', '#f7844e', '#f8864f', '#f88950', '#f88c51', '#f98e52', '#f99153', '#f99355', '#fa9656', '#fa9857', '#fa9b58', '#fb9d59', '#fba05b', '#fba35c', '#fca55d', '#fca85e', '#fcaa5f', '#fdad60', '#fdaf62', '#fdb164', '#fdb366', '#fdb567', '#fdb769', '#fdb96b', '#fdbb6d', '#fdbd6f', '#fdbf71', '#fdc173', '#fdc374', '#fdc576', '#fdc778', '#fec87a', '#feca7c', '#fecc7e', '#fece7f', '#fed081', '#fed283', '#fed485', '#fed687', '#fed889', '#feda8a', '#fedc8c', '#fede8e', '#fee090', '#fee192', '#fee294', '#fee496', '#fee597', '#fee699', '#fee79b', '#fee99d', '#feea9f', '#feeba1', '#feeca2', '#feeda4', '#feefa6', '#fff0a8', '#fff1aa', '#fff2ac', '#fff3ad', '#fff5af', '#fff6b1', '#fff7b3', '#fff8b5', '#fffab7', '#fffbb9', '#fffcba', '#fffdbc', '#fffebe', '#feffc0', '#fdfec2', '#fcfec5', '#fbfdc7', '#fafdc9', '#f8fccb', '#f7fcce', '#f6fbd0', '#f5fbd2', '#f3fbd4', '#f2fad6', '#f1fad9', '#f0f9db', '#eff9dd', '#edf8df', '#ecf8e2', '#ebf7e4', '#eaf7e6', '#e9f6e8', '#e7f6eb', '#e6f5ed', '#e5f5ef', '#e4f4f1', '#e2f4f4', '#e1f3f6', '#e0f3f8', '#def2f7', '#dcf1f7', '#daf0f6', '#d8eff6', '#d6eef5', '#d4edf4', '#d1ecf4', '#cfebf3', '#cdeaf3', '#cbe9f2', '#c9e8f2', '#c7e7f1', '#c5e6f0', '#c3e5f0', '#c1e4ef', '#bfe3ef', '#bde2ee', '#bbe1ed', '#b9e0ed', '#b6dfec', '#b4deec', '#b2ddeb', '#b0dcea', '#aedbea', '#acdae9', '#aad8e9', '#a8d6e8', '#a6d5e7', '#a3d3e6', '#a1d1e5', '#9fd0e4', '#9dcee3', '#9bcce2', '#99cae1', '#97c9e0', '#94c7df', '#92c5de', '#90c3dd', '#8ec2dc', '#8cc0db', '#8abeda', '#87bdd9', '#85bbd9', '#83b9d8', '#81b7d7', '#7fb6d6', '#7db4d5', '#7ab2d4', '#78b0d3', '#76afd2', '#74add1', '#72abd0', '#70a9cf', '#6ea6ce', '#6da4cc', '#6ba2cb', '#69a0ca', '#679ec9', '#659bc8', '#6399c7', '#6297c6', '#6095c4', '#5e93c3', '#5c90c2', '#5a8ec1', '#588cc0', '#578abf', '#5588be', '#5385bd', '#5183bb', '#4f81ba', '#4d7fb9', '#4b7db8', '#4a7ab7', '#4878b6', '#4676b5', '#4574b3', '#4471b2', '#436fb1', '#426cb0', '#416aaf', '#4167ad', '#4065ac', '#3f62ab', '#3e60aa', '#3e5ea8', '#3d5ba7', '#3c59a6', '#3b56a5', '#3a54a4', '#3a51a2', '#394fa1', '#384ca0', '#374a9f', '#36479e', '#36459c', '#35429b', '#34409a', '#333d99', '#333b97', '#323896', '#313695']); - LayerManager._version = 0; - LayerManager._frameWizardDialog = new FrameWizard(); - LayerManager._dataVizWizardDialog = new DataVizWizard(); - LayerManager._referenceFramePropsDialog = new ReferenceFrameProps(); - LayerManager._greatCircleDialog = new GreatCircleDialog(); - LayerManager._tourLayers = false; - LayerManager._layerMaps = {}; - LayerManager._layerMapsTours = {}; - LayerManager._allMaps = {}; - LayerManager._allMapsTours = {}; - LayerManager._currentMap = 'Earth'; - LayerManager._layerList = {}; - LayerManager._layerListTours = {}; - LayerManager._moonfile = ''; - LayerManager._selectedLayer = null; - LayerManager._lastMenuClick = new Vector2d(); - LayerUI._type = null; - Object3d.maX_VERTICES = 8000; - Object3d.maX_POLYGONS = 8000; - Orbit._orbitalToWwt = Matrix3d.create(1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1); - Orbit._initBegun = false; - PushPin._pinTextureCache = {}; - PushPin._pins = null; - (function () { - if (typeof document === "undefined") { canvas = null; return; }; - var canvas = document.getElementById('canvas'); - })(); - MinorPlanets.mpcList = []; - MinorPlanets._initBegun = false; - MinorPlanets._mpcBlendStates = new Array(7); - MinorPlanets.starTexture = null; - MinorPlanets._mpcVertexBuffer = null; - MinorPlanets._mpcCount = 0; - Planets.highPercision = true; - Planets.showActualSize = Settings.get_active().get_actualPlanetScale(); - Planets.RC = (Math.PI / 180); - Planets._jNow = 0; - Planets._planetAngles = [new BodyAngles(286.13, 63.87, 84.176, 14.1844), new BodyAngles(281.0097, 61.4143, 329.548, 6.1385025), new BodyAngles(272.76, 67.16, 160.2, -1.4813688), new BodyAngles(317.68143, 52.8865, 176.63, 350.89198226), new BodyAngles(268.056595, 64.495303, 284.95, 870.536), new BodyAngles(40.589, 83.537, 38.9, 810.7939024), new BodyAngles(257.311, -15.175, 203.81, 501.1600928), new BodyAngles(299.36, 43.46, 253.18, 536.3128492), new BodyAngles(132.993, -6.163, 302.695, 56.3625225), new BodyAngles(269.9949, 66.5392, 38.3213, 13.17635815), new BodyAngles(268.05, 64.5, 200.39, 203.4889538), new BodyAngles(268.08, 64.51, 36.022, 101.3747235), new BodyAngles(268.2, 64.57, 44.064, 50.3176081), new BodyAngles(268.72, 64.83, 259.51, 21.5710715), new BodyAngles(0, 0, 0, 0), new BodyAngles(0, 0, 0, 0), new BodyAngles(0, 0, 0, 0), new BodyAngles(0, 0, 0, 0), new BodyAngles(0, 0, 0, 0), new BodyAngles(0, 90, 190.147, 360.9856235)]; - Planets._lastPlanetCenterID = -2; - Planets._orbitalSampleRate = 256; - Planets._obliquity = 23.5 * Planets.RC; - Planets._drawOrder = {}; - Planets.earthMatrix = new Matrix3d(); - Planets.earthMatrixInv = new Matrix3d(); - Planets._lastUpdate = new Date(); - Planets._ringsTriangleLists = new Array(2); - Planets._ringImage = null; - Planets._triangleCountRings = 192 + 1 * 2; - Planets._ringsVertexBuffer = null; - Planets._planetSprite = new Sprite2d(); - Planets._planetPoints = null; - RenderContext.useGl = false; - RenderContext.useGlVersion2 = false; - RenderContext.back = 0; - RenderTriangle.width = 1024; - RenderTriangle.height = 768; - RenderTriangle._contractionInPixels = -0.5; - RenderTriangle.trianglesRendered = 0; - RenderTriangle.trianglesCulled = 0; - RenderTriangle.renderingOn = true; - RenderTriangle._factor = 1; - RenderTriangle.cullInside = true; - RenderTriangle._hw = 0; - RenderTriangle._qw = 0; - RenderTriangle._hh = 0; - RenderTriangle._qh = 0; - Settings._active = null; - Settings.tourSettings = null; - GlyphCache._caches = {}; - GlyphCache._allGlyphs = ''; - SpaceTimeController.last = SpaceTimeController.get_metaNow(); - SpaceTimeController.framesPerSecond = 30; - SpaceTimeController.frameDumping = false; - SpaceTimeController.cancelFrameDump = false; - SpaceTimeController.currentFrameNumber = 0; - SpaceTimeController.totalFrames = 0; - SpaceTimeController._metaNow = ss.now(); - SpaceTimeController._offset = 0; - SpaceTimeController._now = ss.now(); - SpaceTimeController._syncToClock = true; - SpaceTimeController._timeRate = 1; - SpaceTimeController._altitude = 0; - Galaxy._eTypeBuckets = [-3, -0.186, -0.168, -0.158, -0.15, -0.143, -0.137, -0.13, -0.123, -0.115, -0.104, -0.089, -0.068, -0.042, -0.011, 0.024, 0.064, 0.111, 0.169, 0.252, 3]; - Tile.currentRenderGeneration = 0; - Tile.tileTargetX = -1; - Tile.tileTargetY = -1; - Tile.tileTargetLevel = -1; - Tile.tilesInView = 0; - Tile.trianglesRendered = 0; - Tile.tilesTouched = 0; - Tile.frustumList = null; - Tile.prepDevice = null; - Tile.uvMultiple = 256; - Tile.callCount = 0; - Tile.useAccomidation = true; - Tile.demEnabled = false; - Tile.maxLevel = 20; - Tile.meshComplexity = 50; - Tile.imageQuality = 50; - Tile.lastDeepestLevel = 0; - Tile.deepestLevel = 0; - Tile.RC = (3.1415927 / 180); - TileCache._queue = {}; - TileCache._tiles = {}; - TileCache.openThreads = 8; - TileCache.readyToRenderCount = 0; - TileCache.maxTileCacheSize = 800; - TileCache.maxReadyToRenderSize = 200; - TileCache.accessID = 0; - TileCache._maxTotalToPurge = 0; - Overlay.defaultAnchor = 1; - Overlay.clipboardFormat = 'WorldWideTelescope.Overlay'; - Overlay.nextId = 11231; - Overlay.RC = 3.1415927 / 180; - Selection._points = new Array(9 * 3 * 2); - TourEditor.capturing = false; - TourEditor.currentEditor = null; - TourPlayer._playing = false; - TourPlayer._switchedToFullScreen = false; - TourPlayer.noRestoreUIOnStop = false; - TourStop.clipboardFormat = 'WorldWideTelescope.Slide'; - Undo._undoStack = new ss.Stack(); - Undo._redoStack = new ss.Stack(); - UiTools.kilometersPerAu = 149598000; - UiTools.auPerParsec = 206264.806; - UiTools.auPerLightYear = 63239.6717; - UiTools.ssmUnitConversion = 370; - BinaryReader.id = 1; - VizLayer.earthRadius = 6371000; - WWTControl.imageSets = []; - WWTControl.exploreRoot = new Folder(); - WWTControl.imageSetName = ''; - WWTControl.showDataLayers = false; - WWTControl._renderNeeded = false; - WWTControl.constellationsFigures = null; - WWTControl.constellationsBoundries = null; - WWTControl.solarSystemObjectsNames = ['Sun', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto', 'Moon', 'Io', 'Europa', 'Ganymede', 'Callisto', 'IoShadow', 'EuropaShadow', 'GanymedeShadow', 'CallistoShadow', 'SunEclipsed', 'Earth', 'Custom', 'Undefined']; - WWTControl.singleton = new WWTControl(); - WWTControl.singleton.renderContext = new RenderContext(); - SpaceTimeController.last = ss.now(); - SpaceTimeController.updateClock(); - Coordinates.RC = (3.1415927 / 180); - Coordinates.RCRA = (3.1415927 / 12); - Coordinates.radius = 1; - Coordinates._rotationMatrix = null; - Fxyf._halfpi$1 = Math.PI / 2; - Fxyf._inv_halfpi$1 = 2 / Math.PI; - Fxyf._twothird$1 = 2 / 3; - HealpixTile._galacticMatrix$1 = Matrix3d.create(-0.0548755604024359, -0.483835015526738, -0.873437090247923, 0, -0.867666148981161, 0.455983776232537, -0.198076373464674, 0, 0.494109427943568, 0.746982244476371, -0.444829629919504, 0, 0, 0, 0, 1); - FitsImage.naN = 0 / 0; - Object3dLayer._translateUI$1 = null; - Object3dLayer._translateUILines$1 = null; - Object3dLayer._scaleUI$1 = null; - Object3dLayer._rotateUi$1 = null; - SpreadSheetLayer._circleTexture$1 = null; - TimeSeriesLayer._circleTexture$1 = null; - VoTableLayer._circleTexture$1 = null; - ToastTile.slashIndexBuffer = new Array(64); - ToastTile.backSlashIndexBuffer = new Array(64); - ToastTile.rootIndexBuffer = new Array(4); - ISSLayer.issGuid = Guid.fromString('00000001-0002-0003-0405-060708090a0b'); - ISSLayer._loading$2 = false; - ISSLayer._issmodel$2 = null; - ISSLayer._doc$2 = null; - - return $exports; -}); diff --git a/engine/js/umd_footer.js b/engine/js/umd_footer.js deleted file mode 100644 index 14aee29d..00000000 --- a/engine/js/umd_footer.js +++ /dev/null @@ -1,3 +0,0 @@ -// (umd_footer.js intentionally incomplete -- it is concatenated to form index.js) - return _exports_object; -})); \ No newline at end of file diff --git a/engine/js/umd_header.js b/engine/js/umd_header.js deleted file mode 100644 index 6dbd95c9..00000000 --- a/engine/js/umd_header.js +++ /dev/null @@ -1,21 +0,0 @@ -/* AAS WorldWide Telescope WebGL engine */ -/* eslint-disable */ -/* (this file ends up so big that eslint takes ~forever to run on it) */ -/* Licensed under the MIT License. */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], factory); - } else if (typeof module === 'object' && module.exports) { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - root.wwtlib = factory(); - } -}(typeof self !== 'undefined' ? self : this, function () { - -// (umd_header.js intentionally incomplete -- it is concatenated to form index.js) \ No newline at end of file diff --git a/engine/js/umd_middle.js b/engine/js/umd_middle.js deleted file mode 100644 index 2e537b27..00000000 --- a/engine/js/umd_middle.js +++ /dev/null @@ -1,12 +0,0 @@ -// ScriptSharp generates a file that invokes define() - -var _exports_object = null; - -function define(name, deps, factory) { - _exports_object = factory(ss); - _exports_object.ss = ss; - - // Gross hack to get Enums.parse() and Enums.toXml() to work. See - // wwtlib/Util.cs for the other half of this. - _exports_object.Enums._wwtlib = _exports_object; -} diff --git a/engine/package.json b/engine/package.json index 4ab52daa..15dbd2c1 100644 --- a/engine/package.json +++ b/engine/package.json @@ -15,13 +15,13 @@ "@typescript-eslint/eslint-plugin": "^5.38.1", "@typescript-eslint/parser": "^5.38.1", "chai": "^4.2.0", - "concat-cli": "^4.0.0", "eslint": "^8.24.0", "mocha-headless-chrome": "^4.0.0", "rimraf": "^3", "typedoc": "0.23.20", "typescript": "~4.8.4", - "uglify-js": "^3.9.1" + "webpack": "^5.76.0", + "webpack-cli": "^5.1.4" }, "files": [ ".eslintrc.json", @@ -46,15 +46,15 @@ }, "repository": "github:WorldWideTelescope/wwt-webgl-engine", "scripts": { - "build": "yarn run concat-index && yarn run uglify", - "clean": "rimraf src/index.js src/index.min.js tests/results.xml tsconfig.tsbuildinfo", - "concat-index": "concat-cli -f js/umd_header.js js/ss.js js/umd_middle.js js/transpiled.js js/umd_footer.js -o src/index.js", + "build": "yarn build-dev && yarn build-prod", + "build-dev": "webpack --mode development", + "build-prod": "webpack --mode production", + "clean": "rimraf src/index.js src/index.js.map src/index.min.js tests/results.xml tsconfig.tsbuildinfo", "doc": "typedoc src/index.d.ts", - "lint": "tsc", + "lint": "eslint esm", "test": "mocha-headless-chrome -f tests/tests.html -r xunit >tests/results.xml", - "tscheck": "tsc", - "uglify": "uglifyjs src/index.js -c -o src/index.min.js" + "tscheck": "tsc" }, "types": "./src/index.d.ts", "version": "0.0.0-dev.0" -} \ No newline at end of file +} diff --git a/engine/tests/test_fitsimage.js b/engine/tests/test_fitsimage.js index 5fcf871f..bcef87e1 100644 --- a/engine/tests/test_fitsimage.js +++ b/engine/tests/test_fitsimage.js @@ -3,26 +3,26 @@ var assert = chai.assert; var FITS_FILE_BASE64 = 'U0lNUExFICA9ICAgICAgICAgICAgICAgICAgICBUIC8gY29uZm9ybXMgdG8gRklUUyBzdGFuZGFyZCAgICAgICAgICAgICAgICAgICAgICBCSVRQSVggID0gICAgICAgICAgICAgICAgICAtNjQgLyBhcnJheSBkYXRhIHR5cGUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIE5BWElTICAgPSAgICAgICAgICAgICAgICAgICAgMiAvIG51bWJlciBvZiBhcnJheSBkaW1lbnNpb25zICAgICAgICAgICAgICAgICAgICAgTkFYSVMxICA9ICAgICAgICAgICAgICAgICAgICAxICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBOQVhJUzIgID0gICAgICAgICAgICAgICAgICAgIDEgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFdDU0FYRVMgPSAgICAgICAgICAgICAgICAgICAgMiAvIE51bWJlciBvZiBjb29yZGluYXRlIGF4ZXMgICAgICAgICAgICAgICAgICAgICAgQ1JQSVgxICA9ICAgICAgICAgICAgICAgICAgMC4wIC8gUGl4ZWwgY29vcmRpbmF0ZSBvZiByZWZlcmVuY2UgcG9pbnQgICAgICAgICAgICBDUlBJWDIgID0gICAgICAgICAgICAgICAgICAwLjAgLyBQaXhlbCBjb29yZGluYXRlIG9mIHJlZmVyZW5jZSBwb2ludCAgICAgICAgICAgIENERUxUMSAgPSAgICAgICAgICAgICAgICAgIDEuMCAvIFtkZWddIENvb3JkaW5hdGUgaW5jcmVtZW50IGF0IHJlZmVyZW5jZSBwb2ludCAgQ0RFTFQyICA9ICAgICAgICAgICAgICAgICAgMS4wIC8gW2RlZ10gQ29vcmRpbmF0ZSBpbmNyZW1lbnQgYXQgcmVmZXJlbmNlIHBvaW50ICBDVU5JVDEgID0gJ2RlZycgICAgICAgICAgICAgICAgLyBVbml0cyBvZiBjb29yZGluYXRlIGluY3JlbWVudCBhbmQgdmFsdWUgICAgICAgIENVTklUMiAgPSAnZGVnJyAgICAgICAgICAgICAgICAvIFVuaXRzIG9mIGNvb3JkaW5hdGUgaW5jcmVtZW50IGFuZCB2YWx1ZSAgICAgICAgQ1RZUEUxICA9ICdSQS0tLVRBTicgICAgICAgICAgIC8gUmlnaHQgYXNjZW5zaW9uLCBnbm9tb25pYyBwcm9qZWN0aW9uICAgICAgICAgICBDVFlQRTIgID0gJ0RFQy0tVEFOJyAgICAgICAgICAgLyBEZWNsaW5hdGlvbiwgZ25vbW9uaWMgcHJvamVjdGlvbiAgICAgICAgICAgICAgIENSVkFMMSAgPSAgICAgICAgICAgICAgICAgIDAuMCAvIFtkZWddIENvb3JkaW5hdGUgdmFsdWUgYXQgcmVmZXJlbmNlIHBvaW50ICAgICAgQ1JWQUwyICA9ICAgICAgICAgICAgICAgICAgMC4wIC8gW2RlZ10gQ29vcmRpbmF0ZSB2YWx1ZSBhdCByZWZlcmVuY2UgcG9pbnQgICAgICBMT05QT0xFID0gICAgICAgICAgICAgICAgMTgwLjAgLyBbZGVnXSBOYXRpdmUgbG9uZ2l0dWRlIG9mIGNlbGVzdGlhbCBwb2xlICAgICAgIExBVFBPTEUgPSAgICAgICAgICAgICAgICAgIDAuMCAvIFtkZWddIE5hdGl2ZSBsYXRpdHVkZSBvZiBjZWxlc3RpYWwgcG9sZSAgICAgICAgUkFERVNZUyA9ICdJQ1JTJyAgICAgICAgICAgICAgIC8gRXF1YXRvcmlhbCBjb29yZGluYXRlIHN5c3RlbSAgICAgICAgICAgICAgICAgICBFTkQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgP/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; class FakePrepDevice { - createTexture() {} - bindTexture() {} - texParameteri() {} - texImage2D() {} - generateMipmap() {} - } + createTexture() { } + bindTexture() { } + texParameteri() { } + texImage2D() { } + generateMipmap() { } +} -describe('FitsImage', function() { +describe('FitsImage', function () { - it('should include colormap name in XML serialization', function(done) { + it('should include colormap name in XML serialization', function (done) { // Mock the WebGL prepDevice - wwtlib.Tile.prepDevice = new FakePrepDevice(); - wwtlib.RenderContext.useGlVersion2 = true; + wwtlib.set_tilePrepDevice(new FakePrepDevice()); + wwtlib.set_useGlVersion2(true); var fits_blob = new Blob([atob(FITS_FILE_BASE64)]) var layer = new wwtlib.ImageSetLayer(); var imageset = new wwtlib.Imageset(); - var img = new wwtlib.FitsImage(imageset, "fitsName", fits_blob, function(wcsImage) { + var img = new wwtlib.FitsImage(imageset, "fitsName", fits_blob, function (wcsImage) { // Set up image layer with a FITS image var width = wwtlib.ss.truncate(wcsImage.get_sizeX()); @@ -57,11 +57,11 @@ describe('FitsImage', function() { }); - it('should error when specifying an incorrect colormap name', function(done) { + it('should error when specifying an incorrect colormap name', function (done) { var fits_blob = new Blob([atob(FITS_FILE_BASE64)]) var layer = new wwtlib.ImageSetLayer(); var imageset = new wwtlib.Imageset(); - var img = new wwtlib.FitsImage(imageset, "fitsName", fits_blob, function(wcsImage) { + var img = new wwtlib.FitsImage(imageset, "fitsName", fits_blob, function (wcsImage) { var width = wwtlib.ss.truncate(wcsImage.get_sizeX()); var height = wwtlib.ss.truncate(wcsImage.get_sizeY()); imageset.setInitialParameters( diff --git a/engine/webpack.config.js b/engine/webpack.config.js new file mode 100644 index 00000000..363fefb7 --- /dev/null +++ b/engine/webpack.config.js @@ -0,0 +1,25 @@ +const path = require("path"); + +var config = { + entry: "./esm/index.js", + output: { + path: path.resolve(__dirname, "src"), + library: { + name: "wwtlib", + type: "umd" + } + }, +}; + +module.exports = (_env, argv) => { + if (argv.mode === "development") { + config.devtool = "source-map"; + config.output.filename = "index.js"; + } + + if (argv.mode === "production") { + config.output.filename = "index.min.js"; + } + + return config; +}; diff --git a/yarn.lock b/yarn.lock index 16297308..252aeb5d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -33,12 +33,13 @@ __metadata: languageName: node linkType: hard -"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.22.5, @babel/code-frame@npm:^7.8.3": - version: 7.22.5 - resolution: "@babel/code-frame@npm:7.22.5" +"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.22.13, @babel/code-frame@npm:^7.8.3": + version: 7.22.13 + resolution: "@babel/code-frame@npm:7.22.13" dependencies: - "@babel/highlight": ^7.22.5 - checksum: cfe804f518f53faaf9a1d3e0f9f74127ab9a004912c3a16fda07fb6a633393ecb9918a053cb71804204c1b7ec3d49e1699604715e2cfb0c9f7bc4933d324ebb6 + "@babel/highlight": ^7.22.13 + chalk: ^2.4.2 + checksum: 22e342c8077c8b77eeb11f554ecca2ba14153f707b85294fcf6070b6f6150aae88a7b7436dd88d8c9289970585f3fe5b9b941c5aa3aa26a6d5a8ef3f292da058 languageName: node linkType: hard @@ -50,52 +51,50 @@ __metadata: linkType: hard "@babel/core@npm:^7.12.16": - version: 7.22.9 - resolution: "@babel/core@npm:7.22.9" + version: 7.22.19 + resolution: "@babel/core@npm:7.22.19" dependencies: "@ampproject/remapping": ^2.2.0 - "@babel/code-frame": ^7.22.5 - "@babel/generator": ^7.22.9 - "@babel/helper-compilation-targets": ^7.22.9 - "@babel/helper-module-transforms": ^7.22.9 - "@babel/helpers": ^7.22.6 - "@babel/parser": ^7.22.7 - "@babel/template": ^7.22.5 - "@babel/traverse": ^7.22.8 - "@babel/types": ^7.22.5 + "@babel/code-frame": ^7.22.13 + "@babel/generator": ^7.22.15 + "@babel/helper-compilation-targets": ^7.22.15 + "@babel/helper-module-transforms": ^7.22.19 + "@babel/helpers": ^7.22.15 + "@babel/parser": ^7.22.16 + "@babel/template": ^7.22.15 + "@babel/traverse": ^7.22.19 + "@babel/types": ^7.22.19 convert-source-map: ^1.7.0 debug: ^4.1.0 gensync: ^1.0.0-beta.2 - json5: ^2.2.2 + json5: ^2.2.3 semver: ^6.3.1 - checksum: 7bf069aeceb417902c4efdaefab1f7b94adb7dea694a9aed1bda2edf4135348a080820529b1a300c6f8605740a00ca00c19b2d5e74b5dd489d99d8c11d5e56d1 + checksum: d603f6f00b20c1edff6a6c9d32c559d4d09ee873380317271b57322bfb9da4349e59df53a21c65e9e5a1136f52bf612389d798640454e6fd9246a5c6d76b0c5c languageName: node linkType: hard -"@babel/generator@npm:^7.22.7, @babel/generator@npm:^7.22.9": - version: 7.22.9 - resolution: "@babel/generator@npm:7.22.9" +"@babel/generator@npm:^7.22.15": + version: 7.22.15 + resolution: "@babel/generator@npm:7.22.15" dependencies: - "@babel/types": ^7.22.5 + "@babel/types": ^7.22.15 "@jridgewell/gen-mapping": ^0.3.2 "@jridgewell/trace-mapping": ^0.3.17 jsesc: ^2.5.1 - checksum: 7c9d2c58b8d5ac5e047421a6ab03ec2ff5d9a5ff2c2212130a0055e063ac349e0b19d435537d6886c999771aef394832e4f54cd9fc810100a7f23d982f6af06b + checksum: 5b2a3ccdc3634f6ea86e0a442722bcd430238369432d31f15b428a4ee8013c2f4f917b5b135bf4fc1d0a3e2f87f10fd4ce5d07955ecc2d3b9400a05c2a481374 languageName: node linkType: hard -"@babel/helper-compilation-targets@npm:^7.12.16, @babel/helper-compilation-targets@npm:^7.22.9": - version: 7.22.9 - resolution: "@babel/helper-compilation-targets@npm:7.22.9" +"@babel/helper-compilation-targets@npm:^7.12.16, @babel/helper-compilation-targets@npm:^7.22.15": + version: 7.22.15 + resolution: "@babel/helper-compilation-targets@npm:7.22.15" dependencies: "@babel/compat-data": ^7.22.9 - "@babel/helper-validator-option": ^7.22.5 + "@babel/helper-validator-option": ^7.22.15 browserslist: ^4.21.9 lru-cache: ^5.1.1 semver: ^6.3.1 - peerDependencies: - "@babel/core": ^7.0.0 - checksum: ea0006c6a93759025f4a35a25228ae260538c9f15023e8aac2a6d45ca68aef4cf86cfc429b19af9a402cbdd54d5de74ad3fbcf6baa7e48184dc079f1a791e178 + checksum: ce85196769e091ae54dd39e4a80c2a9df1793da8588e335c383d536d54f06baf648d0a08fc873044f226398c4ded15c4ae9120ee18e7dfd7c639a68e3cdc9980 languageName: node linkType: hard @@ -125,27 +124,27 @@ __metadata: languageName: node linkType: hard -"@babel/helper-module-imports@npm:^7.22.5": - version: 7.22.5 - resolution: "@babel/helper-module-imports@npm:7.22.5" +"@babel/helper-module-imports@npm:^7.22.15": + version: 7.22.15 + resolution: "@babel/helper-module-imports@npm:7.22.15" dependencies: - "@babel/types": ^7.22.5 - checksum: 9ac2b0404fa38b80bdf2653fbeaf8e8a43ccb41bd505f9741d820ed95d3c4e037c62a1bcdcb6c9527d7798d2e595924c4d025daed73283badc180ada2c9c49ad + "@babel/types": ^7.22.15 + checksum: ecd7e457df0a46f889228f943ef9b4a47d485d82e030676767e6a2fdcbdaa63594d8124d4b55fd160b41c201025aec01fc27580352b1c87a37c9c6f33d116702 languageName: node linkType: hard -"@babel/helper-module-transforms@npm:^7.22.9": - version: 7.22.9 - resolution: "@babel/helper-module-transforms@npm:7.22.9" +"@babel/helper-module-transforms@npm:^7.22.19": + version: 7.22.19 + resolution: "@babel/helper-module-transforms@npm:7.22.19" dependencies: "@babel/helper-environment-visitor": ^7.22.5 - "@babel/helper-module-imports": ^7.22.5 + "@babel/helper-module-imports": ^7.22.15 "@babel/helper-simple-access": ^7.22.5 "@babel/helper-split-export-declaration": ^7.22.6 - "@babel/helper-validator-identifier": ^7.22.5 + "@babel/helper-validator-identifier": ^7.22.19 peerDependencies: "@babel/core": ^7.0.0 - checksum: 2751f77660518cf4ff027514d6f4794f04598c6393be7b04b8e46c6e21606e11c19f3f57ab6129a9c21bacdf8b3ffe3af87bb401d972f34af2d0ffde02ac3001 + checksum: ee1278a6850bb5c0efff35c4c20a13469a84d1bdc999a5e1c5aaf87d848b76cba464904c3c34bbbabcbe83e4632a5d7c64ac006de710c5d63c7b2c2473c33f77 languageName: node linkType: hard @@ -174,48 +173,48 @@ __metadata: languageName: node linkType: hard -"@babel/helper-validator-identifier@npm:^7.22.5": - version: 7.22.5 - resolution: "@babel/helper-validator-identifier@npm:7.22.5" - checksum: 7f0f30113474a28298c12161763b49de5018732290ca4de13cdaefd4fd0d635a6fe3f6686c37a02905fb1e64f21a5ee2b55140cf7b070e729f1bd66866506aea +"@babel/helper-validator-identifier@npm:^7.22.19, @babel/helper-validator-identifier@npm:^7.22.5": + version: 7.22.19 + resolution: "@babel/helper-validator-identifier@npm:7.22.19" + checksum: cf1f94d35cdb2d0f519b31954d1c54929fb31cf8af70fed12b3a1e777c296fabe747e56d9ae3d181c1c96f33ac66aff9501189542554b6fe0508748a38c1c17f languageName: node linkType: hard -"@babel/helper-validator-option@npm:^7.22.5": - version: 7.22.5 - resolution: "@babel/helper-validator-option@npm:7.22.5" - checksum: bbeca8a85ee86990215c0424997438b388b8d642d69b9f86c375a174d3cdeb270efafd1ff128bc7a1d370923d13b6e45829ba8581c027620e83e3a80c5c414b3 +"@babel/helper-validator-option@npm:^7.22.15": + version: 7.22.15 + resolution: "@babel/helper-validator-option@npm:7.22.15" + checksum: 68da52b1e10002a543161494c4bc0f4d0398c8fdf361d5f7f4272e95c45d5b32d974896d44f6a0ea7378c9204988879d73613ca683e13bd1304e46d25ff67a8d languageName: node linkType: hard -"@babel/helpers@npm:^7.22.6": - version: 7.22.6 - resolution: "@babel/helpers@npm:7.22.6" +"@babel/helpers@npm:^7.22.15": + version: 7.22.15 + resolution: "@babel/helpers@npm:7.22.15" dependencies: - "@babel/template": ^7.22.5 - "@babel/traverse": ^7.22.6 - "@babel/types": ^7.22.5 - checksum: 5c1f33241fe7bf7709868c2105134a0a86dca26a0fbd508af10a89312b1f77ca38ebae43e50be3b208613c5eacca1559618af4ca236f0abc55d294800faeff30 + "@babel/template": ^7.22.15 + "@babel/traverse": ^7.22.15 + "@babel/types": ^7.22.15 + checksum: 49f61a93cbae4df3328bda67af5db743fead659ae4242571226c3596b7df78546189cdf991fed1eca33b559de8abf396a90a001f474a1bab351418f07b7ae6ef languageName: node linkType: hard -"@babel/highlight@npm:^7.22.5": - version: 7.22.5 - resolution: "@babel/highlight@npm:7.22.5" +"@babel/highlight@npm:^7.22.13": + version: 7.22.13 + resolution: "@babel/highlight@npm:7.22.13" dependencies: "@babel/helper-validator-identifier": ^7.22.5 - chalk: ^2.0.0 + chalk: ^2.4.2 js-tokens: ^4.0.0 - checksum: f61ae6de6ee0ea8d9b5bcf2a532faec5ab0a1dc0f7c640e5047fc61630a0edb88b18d8c92eb06566d30da7a27db841aca11820ecd3ebe9ce514c9350fbed39c4 + checksum: 7266d2bff8aa8fc78eb65b6e92a8211e12897a731126a282d2f9bb50d8fcaa4c1b02af2284f990ac7e3ab8d892d448a2cab8f5ed0ea8a90bce2c025b11ebe802 languageName: node linkType: hard -"@babel/parser@npm:^7.20.15, @babel/parser@npm:^7.21.3, @babel/parser@npm:^7.22.5, @babel/parser@npm:^7.22.7": - version: 7.22.7 - resolution: "@babel/parser@npm:7.22.7" +"@babel/parser@npm:^7.20.15, @babel/parser@npm:^7.21.3, @babel/parser@npm:^7.22.15, @babel/parser@npm:^7.22.16": + version: 7.22.16 + resolution: "@babel/parser@npm:7.22.16" bin: parser: ./bin/babel-parser.js - checksum: 02209ddbd445831ee8bf966fdf7c29d189ed4b14343a68eb2479d940e7e3846340d7cc6bd654a5f3d87d19dc84f49f50a58cf9363bee249dc5409ff3ba3dab54 + checksum: 944c756b5bdeb07b9fec16ecef6b3c61aff9d4c4b924abadcf01afa1840a740b8e2357ae00482b5b37daad6d2bfd848c947f27ad65138d687b6fdc924bc59edd languageName: node linkType: hard @@ -230,62 +229,62 @@ __metadata: linkType: hard "@babel/runtime@npm:^7.13.10, @babel/runtime@npm:^7.21.0": - version: 7.22.6 - resolution: "@babel/runtime@npm:7.22.6" + version: 7.22.15 + resolution: "@babel/runtime@npm:7.22.15" dependencies: - regenerator-runtime: ^0.13.11 - checksum: e585338287c4514a713babf4fdb8fc2a67adcebab3e7723a739fc62c79cfda875b314c90fd25f827afb150d781af97bc16c85bfdbfa2889f06053879a1ddb597 + regenerator-runtime: ^0.14.0 + checksum: 793296df1e41599a935a3d77ec01eb6088410d3fd4dbe4e92f06c6b7bb2f8355024e6d78621a3a35f44e0e23b0b59107f23d585384df4f3123256a1e1492040e languageName: node linkType: hard -"@babel/template@npm:^7.22.5": - version: 7.22.5 - resolution: "@babel/template@npm:7.22.5" +"@babel/template@npm:^7.22.15, @babel/template@npm:^7.22.5": + version: 7.22.15 + resolution: "@babel/template@npm:7.22.15" dependencies: - "@babel/code-frame": ^7.22.5 - "@babel/parser": ^7.22.5 - "@babel/types": ^7.22.5 - checksum: c5746410164039aca61829cdb42e9a55410f43cace6f51ca443313f3d0bdfa9a5a330d0b0df73dc17ef885c72104234ae05efede37c1cc8a72dc9f93425977a3 + "@babel/code-frame": ^7.22.13 + "@babel/parser": ^7.22.15 + "@babel/types": ^7.22.15 + checksum: 1f3e7dcd6c44f5904c184b3f7fe280394b191f2fed819919ffa1e529c259d5b197da8981b6ca491c235aee8dbad4a50b7e31304aa531271cb823a4a24a0dd8fd languageName: node linkType: hard -"@babel/traverse@npm:^7.22.6, @babel/traverse@npm:^7.22.8": - version: 7.22.8 - resolution: "@babel/traverse@npm:7.22.8" +"@babel/traverse@npm:^7.22.15, @babel/traverse@npm:^7.22.19": + version: 7.22.19 + resolution: "@babel/traverse@npm:7.22.19" dependencies: - "@babel/code-frame": ^7.22.5 - "@babel/generator": ^7.22.7 + "@babel/code-frame": ^7.22.13 + "@babel/generator": ^7.22.15 "@babel/helper-environment-visitor": ^7.22.5 "@babel/helper-function-name": ^7.22.5 "@babel/helper-hoist-variables": ^7.22.5 "@babel/helper-split-export-declaration": ^7.22.6 - "@babel/parser": ^7.22.7 - "@babel/types": ^7.22.5 + "@babel/parser": ^7.22.16 + "@babel/types": ^7.22.19 debug: ^4.1.0 globals: ^11.1.0 - checksum: a381369bc3eedfd13ed5fef7b884657f1c29024ea7388198149f0edc34bd69ce3966e9f40188d15f56490a5e12ba250ccc485f2882b53d41b054fccefb233e33 + checksum: 119154fdfffd0fd560d2d5263ae2d740bcd3c75a6c432786f6ccdb28c9b0776f0fe21a16320c81a3e065c37249fb217dfec4201e44058462d26accfcdcd6c9bb languageName: node linkType: hard -"@babel/types@npm:^7.22.5, @babel/types@npm:^7.8.3": - version: 7.22.5 - resolution: "@babel/types@npm:7.22.5" +"@babel/types@npm:^7.22.15, @babel/types@npm:^7.22.19, @babel/types@npm:^7.22.5, @babel/types@npm:^7.8.3": + version: 7.22.19 + resolution: "@babel/types@npm:7.22.19" dependencies: "@babel/helper-string-parser": ^7.22.5 - "@babel/helper-validator-identifier": ^7.22.5 + "@babel/helper-validator-identifier": ^7.22.19 to-fast-properties: ^2.0.0 - checksum: c13a9c1dc7d2d1a241a2f8363540cb9af1d66e978e8984b400a20c4f38ba38ca29f06e26a0f2d49a70bad9e57615dac09c35accfddf1bb90d23cd3e0a0bab892 + checksum: 2d69740e69b55ba36ece0c17d5afb7b7213b34297157df39ef9ba24965aff677c56f014413052ecc5b2fbbf26910c63e5bb24a969df84d7a17153750cf75915e languageName: node linkType: hard -"@discoveryjs/json-ext@npm:0.5.7": +"@discoveryjs/json-ext@npm:0.5.7, @discoveryjs/json-ext@npm:^0.5.0": version: 0.5.7 resolution: "@discoveryjs/json-ext@npm:0.5.7" checksum: 2176d301cc258ea5c2324402997cf8134ebb212469c0d397591636cea8d3c02f2b3cf9fd58dcb748c7a0dade77ebdc1b10284fa63e608c033a1db52fddc69918 languageName: node linkType: hard -"@eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.3.0": +"@eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0": version: 4.4.0 resolution: "@eslint-community/eslint-utils@npm:4.4.0" dependencies: @@ -296,16 +295,16 @@ __metadata: languageName: node linkType: hard -"@eslint-community/regexpp@npm:^4.4.0": - version: 4.5.1 - resolution: "@eslint-community/regexpp@npm:4.5.1" - checksum: 6d901166d64998d591fab4db1c2f872981ccd5f6fe066a1ad0a93d4e11855ecae6bfb76660869a469563e8882d4307228cebd41142adb409d182f2966771e57e +"@eslint-community/regexpp@npm:^4.4.0, @eslint-community/regexpp@npm:^4.6.1": + version: 4.8.1 + resolution: "@eslint-community/regexpp@npm:4.8.1" + checksum: 82d62c845ef42b810f268cfdc84d803a2da01735fb52e902fd34bdc09f92464a094fd8e4802839874b000b2f73f67c972859e813ba705233515d3e954f234bf2 languageName: node linkType: hard -"@eslint/eslintrc@npm:^2.1.0": - version: 2.1.0 - resolution: "@eslint/eslintrc@npm:2.1.0" +"@eslint/eslintrc@npm:^2.1.2": + version: 2.1.2 + resolution: "@eslint/eslintrc@npm:2.1.2" dependencies: ajv: ^6.12.4 debug: ^4.3.2 @@ -316,39 +315,39 @@ __metadata: js-yaml: ^4.1.0 minimatch: ^3.1.2 strip-json-comments: ^3.1.1 - checksum: d5ed0adbe23f6571d8c9bb0ca6edf7618dc6aed4046aa56df7139f65ae7b578874e0d9c796df784c25bda648ceb754b6320277d828c8b004876d7443b8dc018c + checksum: bc742a1e3b361f06fedb4afb6bf32cbd27171292ef7924f61c62f2aed73048367bcc7ac68f98c06d4245cd3fabc43270f844e3c1699936d4734b3ac5398814a7 languageName: node linkType: hard -"@eslint/js@npm:8.44.0": - version: 8.44.0 - resolution: "@eslint/js@npm:8.44.0" - checksum: fc539583226a28f5677356e9f00d2789c34253f076643d2e32888250e509a4e13aafe0880cb2425139051de0f3a48d25bfc5afa96b7304f203b706c17340e3cf +"@eslint/js@npm:8.49.0": + version: 8.49.0 + resolution: "@eslint/js@npm:8.49.0" + checksum: a6601807c8aeeefe866926ad92ed98007c034a735af20ff709009e39ad1337474243d47908500a3bde04e37bfba16bcf1d3452417f962e1345bc8756edd6b830 languageName: node linkType: hard -"@fortawesome/fontawesome-common-types@npm:6.4.0": - version: 6.4.0 - resolution: "@fortawesome/fontawesome-common-types@npm:6.4.0" - checksum: a9b79136caa615352bd921cfe2710516321b402cd76c3f0ae68e579a7e3d7645c5a5c0ecd7516c0b207adeeffd1d2174978638d8c0d3c8c937d66fca4f2ff556 +"@fortawesome/fontawesome-common-types@npm:6.4.2": + version: 6.4.2 + resolution: "@fortawesome/fontawesome-common-types@npm:6.4.2" + checksum: 4a22932bd0cac65be1d35b739624f366b6c247b60eb5b8f66218957f54ce1cae56e2a20ea88789ede45d1e1c0c1014f160e01c1752122ec174ad0823e60f94bf languageName: node linkType: hard "@fortawesome/fontawesome-svg-core@npm:^6.2.0": - version: 6.4.0 - resolution: "@fortawesome/fontawesome-svg-core@npm:6.4.0" + version: 6.4.2 + resolution: "@fortawesome/fontawesome-svg-core@npm:6.4.2" dependencies: - "@fortawesome/fontawesome-common-types": 6.4.0 - checksum: 5d4e6c15f814f5ce29053b666d0c7d194dc8ba173d128a38cc5856403a09d4e817e54956d30ed8d48d621f2f5ebcc71756f4e8fe5c5a091c636fc728fcb2362b + "@fortawesome/fontawesome-common-types": 6.4.2 + checksum: 0c0ecd9058883b128127e2b281c983ba6272be38a17577aaa2293ada58e9b1538357fe44430ded508d49ae3f5cc55aa720a0448d2b9d99689bb912d786f034e5 languageName: node linkType: hard "@fortawesome/free-solid-svg-icons@npm:^6.2.0": - version: 6.4.0 - resolution: "@fortawesome/free-solid-svg-icons@npm:6.4.0" + version: 6.4.2 + resolution: "@fortawesome/free-solid-svg-icons@npm:6.4.2" dependencies: - "@fortawesome/fontawesome-common-types": 6.4.0 - checksum: efdd1688620be3d52aacaeac36c955571962e174ae981fc697b6e92fb0996b00166d02e7729a59ea93713a514e2c8d564ab1aa79c9653b4cfed0263e4874d070 + "@fortawesome/fontawesome-common-types": 6.4.2 + checksum: 4a365004990d5b1c970fb30c11b284b0b807903d0ecb193eb9b5a5e41ea7c0b8fff5c60480c580a1e44535cf23c5d9c90cb698189741e40ea3e10ac66290709c languageName: node linkType: hard @@ -378,14 +377,14 @@ __metadata: languageName: node linkType: hard -"@humanwhocodes/config-array@npm:^0.11.10": - version: 0.11.10 - resolution: "@humanwhocodes/config-array@npm:0.11.10" +"@humanwhocodes/config-array@npm:^0.11.11": + version: 0.11.11 + resolution: "@humanwhocodes/config-array@npm:0.11.11" dependencies: "@humanwhocodes/object-schema": ^1.2.1 debug: ^4.1.1 minimatch: ^3.0.5 - checksum: 1b1302e2403d0e35bc43e66d67a2b36b0ad1119efc704b5faff68c41f791a052355b010fb2d27ef022670f550de24cd6d08d5ecf0821c16326b7dcd0ee5d5d8a + checksum: db84507375ab77b8ffdd24f498a5b49ad6b64391d30dd2ac56885501d03964d29637e05b1ed5aefa09d57ac667e28028bc22d2da872bfcd619652fbdb5f4ca19 languageName: node linkType: hard @@ -428,10 +427,10 @@ __metadata: languageName: node linkType: hard -"@jridgewell/resolve-uri@npm:3.1.0": - version: 3.1.0 - resolution: "@jridgewell/resolve-uri@npm:3.1.0" - checksum: b5ceaaf9a110fcb2780d1d8f8d4a0bfd216702f31c988d8042e5f8fbe353c55d9b0f55a1733afdc64806f8e79c485d2464680ac48a0d9fcadb9548ee6b81d267 +"@jridgewell/resolve-uri@npm:^3.1.0": + version: 3.1.1 + resolution: "@jridgewell/resolve-uri@npm:3.1.1" + checksum: f5b441fe7900eab4f9155b3b93f9800a916257f4e8563afbcd3b5a5337b55e52bd8ae6735453b1b745457d9f6cdb16d74cd6220bbdd98cf153239e13f6cbb653 languageName: node linkType: hard @@ -452,14 +451,7 @@ __metadata: languageName: node linkType: hard -"@jridgewell/sourcemap-codec@npm:1.4.14": - version: 1.4.14 - resolution: "@jridgewell/sourcemap-codec@npm:1.4.14" - checksum: 61100637b6d173d3ba786a5dff019e1a74b1f394f323c1fee337ff390239f053b87266c7a948777f4b1ee68c01a8ad0ab61e5ff4abb5a012a0b091bec391ab97 - languageName: node - linkType: hard - -"@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.4.15": +"@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.4.15": version: 1.4.15 resolution: "@jridgewell/sourcemap-codec@npm:1.4.15" checksum: b881c7e503db3fc7f3c1f35a1dd2655a188cc51a3612d76efc8a6eb74728bef5606e6758ee77423e564092b4a518aba569bbb21c9bac5ab7a35b0c6ae7e344c8 @@ -467,12 +459,12 @@ __metadata: linkType: hard "@jridgewell/trace-mapping@npm:^0.3.17, @jridgewell/trace-mapping@npm:^0.3.9": - version: 0.3.18 - resolution: "@jridgewell/trace-mapping@npm:0.3.18" + version: 0.3.19 + resolution: "@jridgewell/trace-mapping@npm:0.3.19" dependencies: - "@jridgewell/resolve-uri": 3.1.0 - "@jridgewell/sourcemap-codec": 1.4.14 - checksum: 0572669f855260808c16fe8f78f5f1b4356463b11d3f2c7c0b5580c8ba1cbf4ae53efe9f627595830856e57dbac2325ac17eb0c3dd0ec42102e6f227cc289c02 + "@jridgewell/resolve-uri": ^3.1.0 + "@jridgewell/sourcemap-codec": ^1.4.14 + checksum: 956a6f0f6fec060fb48c6bf1f5ec2064e13cd38c8be3873877d4b92b4a27ba58289a34071752671262a3e3c202abcc3fa2aac64d8447b4b0fa1ba3c9047f1c20 languageName: node linkType: hard @@ -545,9 +537,9 @@ __metadata: linkType: hard "@polka/url@npm:^1.0.0-next.20": - version: 1.0.0-next.21 - resolution: "@polka/url@npm:1.0.0-next.21" - checksum: c7654046d38984257dd639eab3dc770d1b0340916097b2fac03ce5d23506ada684e05574a69b255c32ea6a144a957c8cd84264159b545fca031c772289d88788 + version: 1.0.0-next.23 + resolution: "@polka/url@npm:1.0.0-next.23" + checksum: 4b0330de1ceecd1002c7e7449094d0c41f2ed0e21765f4835ccc7b003f2f024ac557d503b9ffdf0918cf50b80d5b8c99dfc5a91927e7b3c468b09c6bb42a3c41 languageName: node linkType: hard @@ -619,9 +611,9 @@ __metadata: linkType: hard "@testim/chrome-version@npm:^1.0.7": - version: 1.1.3 - resolution: "@testim/chrome-version@npm:1.1.3" - checksum: 0874590ae515c2e9e80d62130cd9be070932b60724cef93217c6d2d62f2776a2a9cbc4ef3548e674f57236a4c75f322ce0df7b5ecfecbc8d8b5e3eeaee92391c + version: 1.1.4 + resolution: "@testim/chrome-version@npm:1.1.4" + checksum: 63817db694ab4a49d240217063a30dc2aac9799561132b51da97699207c47cb3355ae043ad1f8b15b770447834cbf36202133641b078f3944d0a502435b40827 languageName: node linkType: hard @@ -678,28 +670,28 @@ __metadata: linkType: hard "@types/chai@npm:*": - version: 4.3.5 - resolution: "@types/chai@npm:4.3.5" - checksum: c8f26a88c6b5b53a3275c7f5ff8f107028e3cbb9ff26795fff5f3d9dea07106a54ce9e2dce5e40347f7c4cc35657900aaf0c83934a25a1ae12e61e0f5516e431 + version: 4.3.6 + resolution: "@types/chai@npm:4.3.6" + checksum: 32a6c18bf53fb3dbd89d1bfcadb1c6fd45cc0007c34e436393cc37a0a5a556f9e6a21d1e8dd71674c40cc36589d2f30bf4d9369d7787021e54d6e997b0d7300a languageName: node linkType: hard "@types/connect-history-api-fallback@npm:^1.3.5": - version: 1.5.0 - resolution: "@types/connect-history-api-fallback@npm:1.5.0" + version: 1.5.1 + resolution: "@types/connect-history-api-fallback@npm:1.5.1" dependencies: "@types/express-serve-static-core": "*" "@types/node": "*" - checksum: f180e7c540728d6dd3a1eb2376e445fe7f9de4ee8a5b460d5ad80062cdb6de6efc91c6851f39e9d5933b3dcd5cd370673c52343a959aa091238b6f863ea4447c + checksum: bc5e46663300eba56eaf8ef242156256e2bdadc52bb7d6543f4b37f2945b6a810901c245711f8321fce7d94c7b588b308a86519f3e1f87a80eb87841d808dbdc languageName: node linkType: hard "@types/connect@npm:*": - version: 3.4.35 - resolution: "@types/connect@npm:3.4.35" + version: 3.4.36 + resolution: "@types/connect@npm:3.4.36" dependencies: "@types/node": "*" - checksum: fe81351470f2d3165e8b12ce33542eef89ea893e36dd62e8f7d72566dfb7e448376ae962f9f3ea888547ce8b55a40020ca0e01d637fab5d99567673084542641 + checksum: 4dee3d966fb527b98f0cbbdcf6977c9193fc3204ed539b7522fe5e64dfa45f9017bdda4ffb1f760062262fce7701a0ee1c2f6ce2e50af36c74d4e37052303172 languageName: node linkType: hard @@ -714,12 +706,12 @@ __metadata: linkType: hard "@types/eslint@npm:*, @types/eslint@npm:^7.29.0 || ^8.4.1": - version: 8.44.0 - resolution: "@types/eslint@npm:8.44.0" + version: 8.44.2 + resolution: "@types/eslint@npm:8.44.2" dependencies: "@types/estree": "*" "@types/json-schema": "*" - checksum: 2655f409a4ecdd64bb9dd9eb6715e7a2ac30c0e7f902b414e10dbe9d6d497baa5a0f13105e1f7bd5ad7a913338e2ab4bed1faf192a7a0d27d1acd45ba79d3f69 + checksum: 25b3ef61bae96350026593c9914c8a61ee02fde48ab8d568a73ee45032f13c0028c62e47a5ff78715af488dfe8e8bba913f7d30f859f60c7f9e639d328e80482 languageName: node linkType: hard @@ -731,14 +723,14 @@ __metadata: linkType: hard "@types/express-serve-static-core@npm:*, @types/express-serve-static-core@npm:^4.17.33": - version: 4.17.35 - resolution: "@types/express-serve-static-core@npm:4.17.35" + version: 4.17.36 + resolution: "@types/express-serve-static-core@npm:4.17.36" dependencies: "@types/node": "*" "@types/qs": "*" "@types/range-parser": "*" "@types/send": "*" - checksum: cc8995d10c6feda475ec1b3a0e69eb0f35f21ab6b49129ad5c6f279e0bc5de8175bc04ec51304cb79a43eec3ed2f5a1e01472eb6d5f827b8c35c6ca8ad24eb6e + checksum: 410b13cbd663f18c0f8729e7f2ff54d960d96de76ebbae7cadb612972f85cc66c54051e00d32f11aa230c0a683d81a6d6fc7f7e4e383a95c0801494c517f36e1 languageName: node linkType: hard @@ -785,13 +777,13 @@ __metadata: linkType: hard "@types/jsdom@npm:^21.1.0": - version: 21.1.1 - resolution: "@types/jsdom@npm:21.1.1" + version: 21.1.2 + resolution: "@types/jsdom@npm:21.1.2" dependencies: "@types/node": "*" "@types/tough-cookie": "*" parse5: ^7.0.0 - checksum: 7450d6e23aa31b837a1682f0e59b06838aacca85c9d030035f40e21d559169c773aee5cee9244f23c3004b78f7064f0c540ceb808d2f187deb3140f2b0449dee + checksum: 62513fc82afa0234034919dee37d3f82425245e1794c58bac55fabbd00de10b3c384992db1cdd53d35a0af58540e2733730f22dbeb57f5b76bca90bca8c368a8 languageName: node linkType: hard @@ -833,20 +825,20 @@ __metadata: linkType: hard "@types/nightwatch@npm:^2.3.12": - version: 2.3.24 - resolution: "@types/nightwatch@npm:2.3.24" + version: 2.3.25 + resolution: "@types/nightwatch@npm:2.3.25" dependencies: "@types/chai": "*" "@types/selenium-webdriver": "*" devtools-protocol: ^0.0.1025565 - checksum: 32ba86c2a2566079d5a02cfc58237da5c646170f35a192f0b6783cd66d2df646903e2ed9f3eb5a505c3344ce55314bc0171460a1e4522407968cfd4d56fc200e + checksum: f178f079260b660ab28c3b84d9f465f3ccaffd2c298150f9c91290194e371b44f1c87b6135e323537d63aa998e9588f1f0e80ecec4cd1e11ef7d46031fa1f7a4 languageName: node linkType: hard "@types/node@npm:*": - version: 20.4.2 - resolution: "@types/node@npm:20.4.2" - checksum: 99e544ea7560d51f01f95627fc40394c24a13da8f041121a0da13e4ef0a2aa332932eaf9a5e8d0e30d1c07106e96a183be392cbba62e8cf0bf6a085d5c0f4149 + version: 20.6.0 + resolution: "@types/node@npm:20.6.0" + checksum: 52611801af5cf151c6fac1963aa4a8a8ca2e388a9e9ed82b01b70bca762088ded5b32cc789c5564220d5d7dccba2b8dd34446a3d4fc74736805e1f2cf262e29d languageName: node linkType: hard @@ -865,9 +857,9 @@ __metadata: linkType: hard "@types/qs@npm:*": - version: 6.9.7 - resolution: "@types/qs@npm:6.9.7" - checksum: 7fd6f9c25053e9b5bb6bc9f9f76c1d89e6c04f7707a7ba0e44cc01f17ef5284adb82f230f542c2d5557d69407c9a40f0f3515e8319afd14e1e16b5543ac6cdba + version: 6.9.8 + resolution: "@types/qs@npm:6.9.8" + checksum: c28e07d00d07970e5134c6eed184a0189b8a4649e28fdf36d9117fe671c067a44820890de6bdecef18217647a95e9c6aebdaaae69f5fe4b0bec9345db885f77e languageName: node linkType: hard @@ -895,18 +887,18 @@ __metadata: linkType: hard "@types/selenium-webdriver@npm:*": - version: 4.1.15 - resolution: "@types/selenium-webdriver@npm:4.1.15" + version: 4.1.16 + resolution: "@types/selenium-webdriver@npm:4.1.16" dependencies: "@types/ws": "*" - checksum: 810ccb9155ca35cc8a6d25e8ba326b29e738b3afce62109f015ceb2007d30b0e818d9f39ff62a9ce9f5f6207ed9d38081cd5ceb3880ee0f694660085ac0e8631 + checksum: e704e81304247ad6d42d03bf10ab077842433637b01fee42f008964b1cf261c1974d0a5c32391a5d222b587636032d894d91d37e002d1ef262d22d3810beb2f8 languageName: node linkType: hard "@types/semver@npm:^7.3.12": - version: 7.5.0 - resolution: "@types/semver@npm:7.5.0" - checksum: 0a64b9b9c7424d9a467658b18dd70d1d781c2d6f033096a6e05762d20ebbad23c1b69b0083b0484722aabf35640b78ccc3de26368bcae1129c87e9df028a22e2 + version: 7.5.2 + resolution: "@types/semver@npm:7.5.2" + checksum: 743aa8a2b58e20b329c19bd2459152cb049d12fafab7279b90ac11e0f268c97efbcb606ea0c681cca03f79015381b40d9b1244349b354270bec3f939ed49f6e9 languageName: node linkType: hard @@ -950,9 +942,9 @@ __metadata: linkType: hard "@types/tough-cookie@npm:*": - version: 4.0.2 - resolution: "@types/tough-cookie@npm:4.0.2" - checksum: e055556ffdaa39ad85ede0af192c93f93f986f4bd9e9426efdc2948e3e2632db3a4a584d4937dbf6d7620527419bc99e6182d3daf2b08685e710f2eda5291905 + version: 4.0.3 + resolution: "@types/tough-cookie@npm:4.0.3" + checksum: f201be1bbca2f2d3572032513cdb9825845114d2604a7f4091af848eeee3228a573cdc5e8082b04468a2848bb1d058f1adbb97db822e22c975ebd6fcd851a453 languageName: node linkType: hard @@ -1436,8 +1428,8 @@ __metadata: linkType: hard "@vue/vue-loader-v15@npm:vue-loader@^15.9.7": - version: 15.10.1 - resolution: "vue-loader@npm:15.10.1" + version: 15.10.2 + resolution: "vue-loader@npm:15.10.2" dependencies: "@vue/component-compiler-utils": ^3.1.0 hash-sum: ^1.0.2 @@ -1450,9 +1442,11 @@ __metadata: peerDependenciesMeta: cache-loader: optional: true + prettier: + optional: true vue-template-compiler: optional: true - checksum: 753a6b6da29e8c0dc328365424cc43757573a2242b0dced5cf36aab775818b622a2bb831c053b43eabfc604755b6b957c196520a66da19bc634b245cb7b44a2b + checksum: 3f4bfd100967af90ad5bd37de9a1dc2ca2f04b1bd7e695772a960186d74c51e161c89c08dd8623062b9151bd2f0bf493d2bbcd381214fa189977e0d379519b57 languageName: node linkType: hard @@ -1614,6 +1608,39 @@ __metadata: languageName: node linkType: hard +"@webpack-cli/configtest@npm:^2.1.1": + version: 2.1.1 + resolution: "@webpack-cli/configtest@npm:2.1.1" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + checksum: 9f9f9145c2d05471fc83d426db1df85cf49f329836b0c4b9f46b6948bed4b013464c00622b136d2a0a26993ce2306976682592245b08ee717500b1db45009a72 + languageName: node + linkType: hard + +"@webpack-cli/info@npm:^2.0.2": + version: 2.0.2 + resolution: "@webpack-cli/info@npm:2.0.2" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + checksum: 8f9a178afca5c82e113aed1efa552d64ee5ae4fdff63fe747c096a981ec74f18a5d07bd6e89bbe6715c3e57d96eea024a410e58977169489fe1df044c10dd94e + languageName: node + linkType: hard + +"@webpack-cli/serve@npm:^2.0.5": + version: 2.0.5 + resolution: "@webpack-cli/serve@npm:2.0.5" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + peerDependenciesMeta: + webpack-dev-server: + optional: true + checksum: 75f0e54681796d567a71ac3e2781d2901a8d8cf1cdfc82f261034dddac59a8343e8c3bc5e32b4bb9d6766759ba49fb29a5cd86ef1701d79c506fe886bb63ac75 + languageName: node + linkType: hard + "@wwtelescope/astro@workspace:*, @wwtelescope/astro@workspace:0.0.0-dev.0, @wwtelescope/astro@workspace:astro": version: 0.0.0-use.local resolution: "@wwtelescope/astro@workspace:astro" @@ -1773,15 +1800,15 @@ __metadata: "@typescript-eslint/parser": ^5.38.1 "@wwtelescope/engine-types": "workspace:0.0.0-dev.0" chai: ^4.2.0 - concat-cli: ^4.0.0 eslint: ^8.24.0 mocha-headless-chrome: ^4.0.0 pako: ^1.0.11 rimraf: ^3 typedoc: 0.23.20 typescript: ~4.8.4 - uglify-js: ^3.9.1 uuid: ^8.3.2 + webpack: ^5.76.0 + webpack-cli: ^5.1.4 languageName: unknown linkType: soft @@ -1964,13 +1991,11 @@ __metadata: linkType: hard "agentkeepalive@npm:^4.2.1": - version: 4.3.0 - resolution: "agentkeepalive@npm:4.3.0" + version: 4.5.0 + resolution: "agentkeepalive@npm:4.5.0" dependencies: - debug: ^4.1.0 - depd: ^2.0.0 humanize-ms: ^1.2.1 - checksum: 982453aa44c11a06826c836025e5162c846e1200adb56f2d075400da7d32d87021b3b0a58768d949d824811f5654223d5a8a3dad120921a2439625eb847c6260 + checksum: 13278cd5b125e51eddd5079f04d6fe0914ac1b8b91c1f3db2c1822f99ac1a7457869068997784342fe455d59daaff22e14fb7b8c3da4e741896e7e31faf92481 languageName: node linkType: hard @@ -2018,7 +2043,7 @@ __metadata: languageName: node linkType: hard -"ajv@npm:^6.10.0, ajv@npm:^6.12.2, ajv@npm:^6.12.3, ajv@npm:^6.12.4, ajv@npm:^6.12.5": +"ajv@npm:^6.12.2, ajv@npm:^6.12.3, ajv@npm:^6.12.4, ajv@npm:^6.12.5": version: 6.12.6 resolution: "ajv@npm:6.12.6" dependencies: @@ -2065,13 +2090,6 @@ __metadata: languageName: node linkType: hard -"ansi-regex@npm:^2.0.0": - version: 2.1.1 - resolution: "ansi-regex@npm:2.1.1" - checksum: 190abd03e4ff86794f338a31795d262c1dfe8c91f7e01d04f13f646f1dcb16c5800818f886047876f1272f065570ab86b24b99089f8b68a0e11ff19aed4ca8f1 - languageName: node - linkType: hard - "ansi-regex@npm:^3.0.0": version: 3.0.1 resolution: "ansi-regex@npm:3.0.1" @@ -2100,13 +2118,6 @@ __metadata: languageName: node linkType: hard -"ansi-styles@npm:^2.2.1": - version: 2.2.1 - resolution: "ansi-styles@npm:2.2.1" - checksum: ebc0e00381f2a29000d1dac8466a640ce11943cef3bda3cd0020dc042e31e1058ab59bf6169cd794a54c3a7338a61ebc404b7c91e004092dd20e028c432c9c2c - languageName: node - linkType: hard - "ansi-styles@npm:^3.2.0, ansi-styles@npm:^3.2.1": version: 3.2.1 resolution: "ansi-styles@npm:3.2.1" @@ -2232,30 +2243,31 @@ __metadata: languageName: node linkType: hard -"array.prototype.reduce@npm:^1.0.5": - version: 1.0.5 - resolution: "array.prototype.reduce@npm:1.0.5" +"array.prototype.reduce@npm:^1.0.6": + version: 1.0.6 + resolution: "array.prototype.reduce@npm:1.0.6" dependencies: call-bind: ^1.0.2 - define-properties: ^1.1.4 - es-abstract: ^1.20.4 + define-properties: ^1.2.0 + es-abstract: ^1.22.1 es-array-method-boxes-properly: ^1.0.0 is-string: ^1.0.7 - checksum: f44691395f9202aba5ec2446468d4c27209bfa81464f342ae024b7157dbf05b164e47cca01250b8c7c2a8219953fb57651cca16aab3d16f43b85c0d92c26eef3 + checksum: c709c3f5caa2aac4fb10e0c6c1982cca50328a2a48658d53b1da8ee3a78069ad67cdac21296d6285521aa3a932a8178c0e192b5fc831fae2977b69a5a8a64ad7 languageName: node linkType: hard -"arraybuffer.prototype.slice@npm:^1.0.1": - version: 1.0.1 - resolution: "arraybuffer.prototype.slice@npm:1.0.1" +"arraybuffer.prototype.slice@npm:^1.0.2": + version: 1.0.2 + resolution: "arraybuffer.prototype.slice@npm:1.0.2" dependencies: array-buffer-byte-length: ^1.0.0 call-bind: ^1.0.2 define-properties: ^1.2.0 + es-abstract: ^1.22.1 get-intrinsic: ^1.2.1 is-array-buffer: ^3.0.2 is-shared-array-buffer: ^1.0.2 - checksum: e3e9b2a3e988ebfeddce4c7e8f69df730c9e48cb04b0d40ff0874ce3d86b3d1339dd520ffde5e39c02610bc172ecfbd4bc93324b1cabd9554c44a56b131ce0ce + checksum: c200faf437786f5b2c80d4564ff5481c886a16dee642ef02abdc7306c7edd523d1f01d1dd12b769c7eb42ac9bc53874510db19a92a2c035c0f6696172aafa5d3 languageName: node linkType: hard @@ -2322,11 +2334,11 @@ __metadata: linkType: hard "autoprefixer@npm:^10.2.4": - version: 10.4.14 - resolution: "autoprefixer@npm:10.4.14" + version: 10.4.15 + resolution: "autoprefixer@npm:10.4.15" dependencies: - browserslist: ^4.21.5 - caniuse-lite: ^1.0.30001464 + browserslist: ^4.21.10 + caniuse-lite: ^1.0.30001520 fraction.js: ^4.2.0 normalize-range: ^0.1.2 picocolors: ^1.0.0 @@ -2335,7 +2347,7 @@ __metadata: postcss: ^8.1.0 bin: autoprefixer: bin/autoprefixer - checksum: e9f18e664a4e4a54a8f4ec5f6b49ed228ec45afaa76efcae361c93721795dc5ab644f36d2fdfc0dea446b02a8067b9372f91542ea431994399e972781ed46d95 + checksum: d490b14fb098c043e109fc13cd23628f146af99a493d35b9df3a26f8ec0b4dd8937c5601cdbaeb465b98ea31d3ea05aa7184711d4d93dfb52358d073dcb67032 languageName: node linkType: hard @@ -2506,11 +2518,11 @@ __metadata: linkType: hard "bootstrap@npm:^5.2.2": - version: 5.3.0 - resolution: "bootstrap@npm:5.3.0" + version: 5.3.2 + resolution: "bootstrap@npm:5.3.2" peerDependencies: - "@popperjs/core": ^2.11.7 - checksum: 29a83cc8cac96d70051e265a5da342cc488df8fc76dff6746ef7d155698286cd5bdfa3e52c6ebf09f8e5a97f25929ee97aee36237117732e52b0d3276a72c45c + "@popperjs/core": ^2.11.8 + checksum: d5580b253d121ffc137388d41da58dce8d15f1ccd574e12f28d4a08e7649ca15e95db645b2b677cb8025bccd446bff04138fc0fe64f8cba0ccc5dc004a8644cf languageName: node linkType: hard @@ -2549,30 +2561,30 @@ __metadata: languageName: node linkType: hard -"browserslist@npm:^4.0.0, browserslist@npm:^4.14.5, browserslist@npm:^4.16.3, browserslist@npm:^4.21.4, browserslist@npm:^4.21.5, browserslist@npm:^4.21.9": - version: 4.21.9 - resolution: "browserslist@npm:4.21.9" +"browserslist@npm:^4.0.0, browserslist@npm:^4.14.5, browserslist@npm:^4.16.3, browserslist@npm:^4.21.10, browserslist@npm:^4.21.4, browserslist@npm:^4.21.9": + version: 4.21.10 + resolution: "browserslist@npm:4.21.10" dependencies: - caniuse-lite: ^1.0.30001503 - electron-to-chromium: ^1.4.431 - node-releases: ^2.0.12 + caniuse-lite: ^1.0.30001517 + electron-to-chromium: ^1.4.477 + node-releases: ^2.0.13 update-browserslist-db: ^1.0.11 bin: browserslist: cli.js - checksum: 80d3820584e211484ad1b1a5cfdeca1dd00442f47be87e117e1dda34b628c87e18b81ae7986fa5977b3e6a03154f6d13cd763baa6b8bf5dd9dd19f4926603698 + checksum: 1e27c0f111a35d1dd0e8fc2c61781b0daefabc2c9471b0b10537ce54843014bceb2a1ce4571af1a82b2bf1e6e6e05d38865916689a158f03bc2c7a4ec2577db8 languageName: node linkType: hard "browserstack-local@npm:^1.4.8": - version: 1.5.3 - resolution: "browserstack-local@npm:1.5.3" + version: 1.5.4 + resolution: "browserstack-local@npm:1.5.4" dependencies: agent-base: ^6.0.2 https-proxy-agent: ^5.0.1 is-running: ^2.1.0 ps-tree: =1.2.0 temp-fs: ^0.9.9 - checksum: 526138425ac2f184ad63d1d17e41f4496819edc7cfd59c031f3d84331f428c0d063849400390db4bebc46820b50f30f7c4cdc8994f80263990a117f09d6fb1a1 + checksum: beb2b1daadc8328bf635898983733232d4dc250981c29a9a231167f2bc4bf6118966ead779a7fc96873bb650462af8b57347242eb58040c6455019ece195e51d languageName: node linkType: hard @@ -2615,14 +2627,14 @@ __metadata: linkType: hard "cacache@npm:^17.0.0": - version: 17.1.3 - resolution: "cacache@npm:17.1.3" + version: 17.1.4 + resolution: "cacache@npm:17.1.4" dependencies: "@npmcli/fs": ^3.1.0 fs-minipass: ^3.0.0 glob: ^10.2.2 lru-cache: ^7.7.1 - minipass: ^5.0.0 + minipass: ^7.0.3 minipass-collect: ^1.0.2 minipass-flush: ^1.0.5 minipass-pipeline: ^1.2.4 @@ -2630,7 +2642,7 @@ __metadata: ssri: ^10.0.0 tar: ^6.1.11 unique-filename: ^3.0.0 - checksum: 385756781e1e21af089160d89d7462b7ed9883c978e848c7075b90b73cb823680e66092d61513050164588387d2ca87dd6d910e28d64bc13a9ac82cd8580c796 + checksum: b7751df756656954a51201335addced8f63fc53266fa56392c9f5ae83c8d27debffb4458ac2d168a744a4517ec3f2163af05c20097f93d17bdc2dc8a385e14a6 languageName: node linkType: hard @@ -2690,13 +2702,6 @@ __metadata: languageName: node linkType: hard -"camelcase@npm:^2.0.1": - version: 2.1.1 - resolution: "camelcase@npm:2.1.1" - checksum: 20a3ef08f348de832631d605362ffe447d883ada89617144a82649363ed5860923b021f8e09681624ef774afb93ff3597cfbcf8aaf0574f65af7648f1aea5e50 - languageName: node - linkType: hard - "camelcase@npm:^5.0.0": version: 5.3.1 resolution: "camelcase@npm:5.3.1" @@ -2716,10 +2721,10 @@ __metadata: languageName: node linkType: hard -"caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001464, caniuse-lite@npm:^1.0.30001503": - version: 1.0.30001517 - resolution: "caniuse-lite@npm:1.0.30001517" - checksum: e4e87436ae1c4408cf4438aac22902b31eb03f3f5bad7f33bc518d12ffb35f3fd9395ccf7efc608ee046f90ce324ec6f7f26f8a8172b8c43c26a06ecee612a29 +"caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001517, caniuse-lite@npm:^1.0.30001520": + version: 1.0.30001534 + resolution: "caniuse-lite@npm:1.0.30001534" + checksum: 8e8b63c1ce0d5b944ee2d8223955b33f3d4f60c33fed394ff6353b5c7106b2dc55219fd07d80c79e66ed1f82ed9367cee17bda96789cbd2ab57c8d30b1b5c510 languageName: node linkType: hard @@ -2747,8 +2752,8 @@ __metadata: linkType: hard "chai@npm:^4.2.0": - version: 4.3.7 - resolution: "chai@npm:4.3.7" + version: 4.3.8 + resolution: "chai@npm:4.3.8" dependencies: assertion-error: ^1.1.0 check-error: ^1.0.2 @@ -2757,11 +2762,11 @@ __metadata: loupe: ^2.3.1 pathval: ^1.1.1 type-detect: ^4.0.5 - checksum: 0bba7d267848015246a66995f044ce3f0ebc35e530da3cbdf171db744e14cbe301ab913a8d07caf7952b430257ccbb1a4a983c570a7c5748dc537897e5131f7c + checksum: 29e0984ed13308319cadc35437c8ef0a3e271544d226c991bf7e3b6d771bf89707321669e11d05e362bc0ad0bd26585079b989d1032f3c106e3bb95d7f079cce languageName: node linkType: hard -"chalk@npm:2.4.2, chalk@npm:^2.0.0, chalk@npm:^2.0.1, chalk@npm:^2.1.0, chalk@npm:^2.4.2": +"chalk@npm:2.4.2, chalk@npm:^2.0.1, chalk@npm:^2.1.0, chalk@npm:^2.4.2": version: 2.4.2 resolution: "chalk@npm:2.4.2" dependencies: @@ -2772,19 +2777,6 @@ __metadata: languageName: node linkType: hard -"chalk@npm:^1.1.1": - version: 1.1.3 - resolution: "chalk@npm:1.1.3" - dependencies: - ansi-styles: ^2.2.1 - escape-string-regexp: ^1.0.2 - has-ansi: ^2.0.0 - strip-ansi: ^3.0.0 - supports-color: ^2.0.0 - checksum: 9d2ea6b98fc2b7878829eec223abcf404622db6c48396a9b9257f6d0ead2acf18231ae368d6a664a83f272b0679158da12e97b5229f794939e555cc574478acd - languageName: node - linkType: hard - "chalk@npm:^3.0.0": version: 3.0.0 resolution: "chalk@npm:3.0.0" @@ -2934,9 +2926,9 @@ __metadata: linkType: hard "cli-spinners@npm:^2.2.0, cli-spinners@npm:^2.5.0": - version: 2.9.0 - resolution: "cli-spinners@npm:2.9.0" - checksum: a9c56e1f44457d4a9f4f535364e729cb8726198efa9e98990cfd9eda9e220dfa4ba12f92808d1be5e29029cdfead781db82dc8549b97b31c907d55f96aa9b0e2 + version: 2.9.1 + resolution: "cli-spinners@npm:2.9.1" + checksum: 1780618be58309c469205bc315db697934bac68bce78cd5dfd46248e507a533172d623c7348ecfd904734f597ce0a4e5538684843d2cfb7af485d4466699940c languageName: node linkType: hard @@ -2962,17 +2954,6 @@ __metadata: languageName: node linkType: hard -"cliui@npm:^3.0.3": - version: 3.2.0 - resolution: "cliui@npm:3.2.0" - dependencies: - string-width: ^1.0.1 - strip-ansi: ^3.0.1 - wrap-ansi: ^2.0.0 - checksum: c68d1dbc3e347bfe79ed19cc7f48007d5edd6cd8438342e32073e0b4e311e3c44e1f4f19221462bc6590de56c2df520e427533a9dde95dee25710bec322746ad - languageName: node - linkType: hard - "cliui@npm:^5.0.0": version: 5.0.0 resolution: "cliui@npm:5.0.0" @@ -3022,13 +3003,6 @@ __metadata: languageName: node linkType: hard -"code-point-at@npm:^1.0.0": - version: 1.1.0 - resolution: "code-point-at@npm:1.1.0" - checksum: 17d5666611f9b16d64fdf48176d9b7fb1c7d1c1607a189f7e600040a11a6616982876af148230336adb7d8fe728a559f743a4e29db3747e3b1a32fa7f4529681 - languageName: node - linkType: hard - "color-convert@npm:^1.9.0": version: 1.9.3 resolution: "color-convert@npm:1.9.3" @@ -3077,7 +3051,7 @@ __metadata: languageName: node linkType: hard -"colorette@npm:^2.0.10": +"colorette@npm:^2.0.10, colorette@npm:^2.0.14": version: 2.0.20 resolution: "colorette@npm:2.0.20" checksum: 0c016fea2b91b733eb9f4bcdb580018f52c0bc0979443dad930e5037a968237ac53d9beb98e218d2e9235834f8eebce7f8e080422d6194e957454255bde71d3d @@ -3093,7 +3067,14 @@ __metadata: languageName: node linkType: hard -"commander@npm:^2.20.0, commander@npm:^2.9.0": +"commander@npm:^10.0.1": + version: 10.0.1 + resolution: "commander@npm:10.0.1" + checksum: 436901d64a818295803c1996cd856621a74f30b9f9e28a588e726b2b1670665bccd7c1a77007ebf328729f0139838a88a19265858a0fa7a8728c4656796db948 + languageName: node + linkType: hard + +"commander@npm:^2.20.0": version: 2.20.3 resolution: "commander@npm:2.20.3" checksum: ab8c07884e42c3a8dbc5dd9592c606176c7eb5c1ca5ff274bcf907039b2c41de3626f684ea75ccf4d361ba004bbaff1f577d5384c155f3871e456bdf27becf9e @@ -3145,19 +3126,6 @@ __metadata: languageName: node linkType: hard -"concat-cli@npm:^4.0.0": - version: 4.0.0 - resolution: "concat-cli@npm:4.0.0" - dependencies: - chalk: ^1.1.1 - concat: ^1.0.0 - yargs: ^3.30.0 - bin: - concat-cli: ./index.js - checksum: 7bc028aa00c0f2ee98d16535f84025c540ea6359122816202fabdd0dc32913251c59ffa70698e9e34ce0900fdd243e4077ae0008079d57e9c6e7777b50f90e65 - languageName: node - linkType: hard - "concat-map@npm:0.0.1": version: 0.0.1 resolution: "concat-map@npm:0.0.1" @@ -3165,17 +3133,6 @@ __metadata: languageName: node linkType: hard -"concat@npm:^1.0.0": - version: 1.0.3 - resolution: "concat@npm:1.0.3" - dependencies: - commander: ^2.9.0 - bin: - concat: ./bin/concat - checksum: 02e6302f53cb5298576fdb2ef0475978f4736b766de9de9a8c8451fa7d401e01ecdf675a31d9e6a74468c607d69fd34d2fe8fb90e71b2cc5a1ea36101aa08365 - languageName: node - linkType: hard - "concurrently@npm:^5.2.0": version: 5.3.0 resolution: "concurrently@npm:5.3.0" @@ -3677,7 +3634,7 @@ __metadata: languageName: node linkType: hard -"decamelize@npm:^1.1.1, decamelize@npm:^1.2.0": +"decamelize@npm:^1.2.0": version: 1.2.0 resolution: "decamelize@npm:1.2.0" checksum: ad8c51a7e7e0720c70ec2eeb1163b66da03e7616d7b98c9ef43cce2416395e84c1e9548dd94f5f6ffecfee9f8b94251fc57121a8b021f2ff2469b2bae247b8aa @@ -3755,6 +3712,17 @@ __metadata: languageName: node linkType: hard +"define-data-property@npm:^1.0.1": + version: 1.1.0 + resolution: "define-data-property@npm:1.1.0" + dependencies: + get-intrinsic: ^1.2.1 + gopd: ^1.0.1 + has-property-descriptors: ^1.0.0 + checksum: 7ad4ee84cca8ad427a4831f5693526804b62ce9dfd4efac77214e95a4382aed930072251d4075dc8dc9fc949a353ed51f19f5285a84a788ba9216cc51472a093 + languageName: node + linkType: hard + "define-lazy-prop@npm:^2.0.0": version: 2.0.0 resolution: "define-lazy-prop@npm:2.0.0" @@ -3763,12 +3731,13 @@ __metadata: linkType: hard "define-properties@npm:^1.1.2, define-properties@npm:^1.1.3, define-properties@npm:^1.1.4, define-properties@npm:^1.2.0": - version: 1.2.0 - resolution: "define-properties@npm:1.2.0" + version: 1.2.1 + resolution: "define-properties@npm:1.2.1" dependencies: + define-data-property: ^1.0.1 has-property-descriptors: ^1.0.0 object-keys: ^1.1.1 - checksum: e60aee6a19b102df4e2b1f301816804e81ab48bb91f00d0d935f269bf4b3f79c88b39e4f89eaa132890d23267335fd1140dfcd8d5ccd61031a0a2c41a54e33a6 + checksum: b4ccd00597dd46cb2d4a379398f5b19fca84a16f3374e2249201992f36b30f6835949a9429669ee6b41b6e837205a163eadd745e472069e70dfc10f03e5fcc12 languageName: node linkType: hard @@ -3821,7 +3790,7 @@ __metadata: languageName: node linkType: hard -"depd@npm:2.0.0, depd@npm:^2.0.0": +"depd@npm:2.0.0": version: 2.0.0 resolution: "depd@npm:2.0.0" checksum: abbe19c768c97ee2eed6282d8ce3031126662252c58d711f646921c9623f9052e3e1906443066beec1095832f534e57c523b7333f8e7e0d93051ab6baef5ab3a @@ -3894,11 +3863,11 @@ __metadata: linkType: hard "dns-packet@npm:^5.2.2": - version: 5.6.0 - resolution: "dns-packet@npm:5.6.0" + version: 5.6.1 + resolution: "dns-packet@npm:5.6.1" dependencies: "@leichtgewicht/ip-codec": ^2.0.1 - checksum: 1b643814e5947a87620f8a906287079347492282964ce1c236d52c414e3e3941126b96581376b180ba6e66899e70b86b587bc1aa23e3acd9957765be952d83fc + checksum: 64c06457f0c6e143f7a0946e0aeb8de1c5f752217cfa143ef527467c00a6d78db1835cfdb6bb68333d9f9a4963cf23f410439b5262a8935cce1236f45e344b81 languageName: node linkType: hard @@ -4063,10 +4032,10 @@ __metadata: languageName: node linkType: hard -"electron-to-chromium@npm:^1.4.431": - version: 1.4.467 - resolution: "electron-to-chromium@npm:1.4.467" - checksum: 0ad9e61429991c5e384acde495f06ad9f718b2f7bd00321abc5a8c92d9a8d2fdc2915cbffb7ba7395389f2102f1d42341b3d4a80ce446ed312c8adfc5a7eac4a +"electron-to-chromium@npm:^1.4.477": + version: 1.4.520 + resolution: "electron-to-chromium@npm:1.4.520" + checksum: 3c12052f6532558f363e47da4de9f91c612e6123330ec8a439e34ffe282e1199de65c844af8955086f6a64ca1cd36995c6062133edc6cb6e6160c0b8ebc40229 languageName: node linkType: hard @@ -4154,7 +4123,7 @@ __metadata: languageName: node linkType: hard -"envinfo@npm:^7.5.1": +"envinfo@npm:^7.5.1, envinfo@npm:^7.7.3": version: 7.10.0 resolution: "envinfo@npm:7.10.0" bin: @@ -4199,17 +4168,17 @@ __metadata: languageName: node linkType: hard -"es-abstract@npm:^1.19.0, es-abstract@npm:^1.20.4, es-abstract@npm:^1.21.2": - version: 1.22.1 - resolution: "es-abstract@npm:1.22.1" +"es-abstract@npm:^1.22.1": + version: 1.22.2 + resolution: "es-abstract@npm:1.22.2" dependencies: array-buffer-byte-length: ^1.0.0 - arraybuffer.prototype.slice: ^1.0.1 + arraybuffer.prototype.slice: ^1.0.2 available-typed-arrays: ^1.0.5 call-bind: ^1.0.2 es-set-tostringtag: ^2.0.1 es-to-primitive: ^1.2.1 - function.prototype.name: ^1.1.5 + function.prototype.name: ^1.1.6 get-intrinsic: ^1.2.1 get-symbol-description: ^1.0.0 globalthis: ^1.0.3 @@ -4225,24 +4194,24 @@ __metadata: is-regex: ^1.1.4 is-shared-array-buffer: ^1.0.2 is-string: ^1.0.7 - is-typed-array: ^1.1.10 + is-typed-array: ^1.1.12 is-weakref: ^1.0.2 object-inspect: ^1.12.3 object-keys: ^1.1.1 object.assign: ^4.1.4 - regexp.prototype.flags: ^1.5.0 - safe-array-concat: ^1.0.0 + regexp.prototype.flags: ^1.5.1 + safe-array-concat: ^1.0.1 safe-regex-test: ^1.0.0 - string.prototype.trim: ^1.2.7 - string.prototype.trimend: ^1.0.6 - string.prototype.trimstart: ^1.0.6 + string.prototype.trim: ^1.2.8 + string.prototype.trimend: ^1.0.7 + string.prototype.trimstart: ^1.0.7 typed-array-buffer: ^1.0.0 typed-array-byte-length: ^1.0.0 typed-array-byte-offset: ^1.0.0 typed-array-length: ^1.0.4 unbox-primitive: ^1.0.2 - which-typed-array: ^1.1.10 - checksum: 614e2c1c3717cb8d30b6128ef12ea110e06fd7d75ad77091ca1c5dbfb00da130e62e4bbbbbdda190eada098a22b27fe0f99ae5a1171dac2c8663b1e8be8a3a9b + which-typed-array: ^1.1.11 + checksum: cc70e592d360d7d729859013dee7a610c6b27ed8630df0547c16b0d16d9fe6505a70ee14d1af08d970fdd132b3f88c9ca7815ce72c9011608abf8ab0e55fc515 languageName: node linkType: hard @@ -4254,9 +4223,9 @@ __metadata: linkType: hard "es-module-lexer@npm:^1.2.1": - version: 1.3.0 - resolution: "es-module-lexer@npm:1.3.0" - checksum: 48fd9f504a9d2a894126f75c8b7ccc6273a289983e9b67255f165bfd9ae765d50100218251e94e702ca567826905ea2f7b3b4a0c4d74d3ce99cce3a2a606a238 + version: 1.3.1 + resolution: "es-module-lexer@npm:1.3.1" + checksum: 3beafa7e171eb1e8cc45695edf8d51638488dddf65294d7911f8d6a96249da6a9838c87529262cc6ea53988d8272cec0f4bff93f476ed031a54ba3afb51a0ed3 languageName: node linkType: hard @@ -4296,7 +4265,7 @@ __metadata: languageName: node linkType: hard -"escape-string-regexp@npm:1.0.5, escape-string-regexp@npm:^1.0.2, escape-string-regexp@npm:^1.0.5": +"escape-string-regexp@npm:1.0.5, escape-string-regexp@npm:^1.0.5": version: 1.0.5 resolution: "escape-string-regexp@npm:1.0.5" checksum: 6092fda75c63b110c706b6a9bfde8a612ad595b628f0bd2147eea1d3406723020810e591effc7db1da91d80a71a737a313567c5abb3813e8d9c71f4aa595b410 @@ -4348,19 +4317,19 @@ __metadata: linkType: hard "eslint-plugin-vue@npm:^9.5.1": - version: 9.15.1 - resolution: "eslint-plugin-vue@npm:9.15.1" + version: 9.17.0 + resolution: "eslint-plugin-vue@npm:9.17.0" dependencies: - "@eslint-community/eslint-utils": ^4.3.0 + "@eslint-community/eslint-utils": ^4.4.0 natural-compare: ^1.4.0 - nth-check: ^2.0.1 - postcss-selector-parser: ^6.0.9 - semver: ^7.3.5 - vue-eslint-parser: ^9.3.0 + nth-check: ^2.1.1 + postcss-selector-parser: ^6.0.13 + semver: ^7.5.4 + vue-eslint-parser: ^9.3.1 xml-name-validator: ^4.0.0 peerDependencies: eslint: ^6.2.0 || ^7.0.0 || ^8.0.0 - checksum: b1cdb16e43e681938c25f1d3f2d5d0d76a99172efdcfa0fa98cdb21122d520e12ae2f8ff2b40bf47a5b9f476f54199494a2851d99edc5bad0a25156ef38eeac4 + checksum: 2ef53a03876f7c96828ad10dae7d1c4d87b51e348f58b16de3f2bedbbff9a3410eabfaf65e4890b0b7ae6d1e710c1c370998d5bc64d6ca3095a95713b3a4cf67 languageName: node linkType: hard @@ -4374,20 +4343,20 @@ __metadata: languageName: node linkType: hard -"eslint-scope@npm:^7.1.1, eslint-scope@npm:^7.2.0": - version: 7.2.1 - resolution: "eslint-scope@npm:7.2.1" +"eslint-scope@npm:^7.1.1, eslint-scope@npm:^7.2.2": + version: 7.2.2 + resolution: "eslint-scope@npm:7.2.2" dependencies: esrecurse: ^4.3.0 estraverse: ^5.2.0 - checksum: dccda5c8909216f6261969b72c77b95e385f9086bed4bc09d8a6276df8439d8f986810fd9ac3bd02c94c0572cefc7fdbeae392c69df2e60712ab8263986522c5 + checksum: ec97dbf5fb04b94e8f4c5a91a7f0a6dd3c55e46bfc7bbcd0e3138c3a76977570e02ed89a1810c778dcd72072ff0e9621ba1379b4babe53921d71e2e4486fda3e languageName: node linkType: hard -"eslint-visitor-keys@npm:^3.3.0, eslint-visitor-keys@npm:^3.4.1": - version: 3.4.1 - resolution: "eslint-visitor-keys@npm:3.4.1" - checksum: f05121d868202736b97de7d750847a328fcfa8593b031c95ea89425333db59676ac087fa905eba438d0a3c5769632f828187e0c1a0d271832a2153c1d3661c2c +"eslint-visitor-keys@npm:^3.3.0, eslint-visitor-keys@npm:^3.4.1, eslint-visitor-keys@npm:^3.4.3": + version: 3.4.3 + resolution: "eslint-visitor-keys@npm:3.4.3" + checksum: 36e9ef87fca698b6fd7ca5ca35d7b2b6eeaaf106572e2f7fd31c12d3bfdaccdb587bba6d3621067e5aece31c8c3a348b93922ab8f7b2cbc6aaab5e1d89040c60 languageName: node linkType: hard @@ -4408,25 +4377,25 @@ __metadata: linkType: hard "eslint@npm:^8.24.0": - version: 8.45.0 - resolution: "eslint@npm:8.45.0" + version: 8.49.0 + resolution: "eslint@npm:8.49.0" dependencies: "@eslint-community/eslint-utils": ^4.2.0 - "@eslint-community/regexpp": ^4.4.0 - "@eslint/eslintrc": ^2.1.0 - "@eslint/js": 8.44.0 - "@humanwhocodes/config-array": ^0.11.10 + "@eslint-community/regexpp": ^4.6.1 + "@eslint/eslintrc": ^2.1.2 + "@eslint/js": 8.49.0 + "@humanwhocodes/config-array": ^0.11.11 "@humanwhocodes/module-importer": ^1.0.1 "@nodelib/fs.walk": ^1.2.8 - ajv: ^6.10.0 + ajv: ^6.12.4 chalk: ^4.0.0 cross-spawn: ^7.0.2 debug: ^4.3.2 doctrine: ^3.0.0 escape-string-regexp: ^4.0.0 - eslint-scope: ^7.2.0 - eslint-visitor-keys: ^3.4.1 - espree: ^9.6.0 + eslint-scope: ^7.2.2 + eslint-visitor-keys: ^3.4.3 + espree: ^9.6.1 esquery: ^1.4.2 esutils: ^2.0.2 fast-deep-equal: ^3.1.3 @@ -4450,11 +4419,11 @@ __metadata: text-table: ^0.2.0 bin: eslint: bin/eslint.js - checksum: 3e6dcce5cc43c5e301662db88ee26d1d188b22c177b9f104d7eefd1191236980bd953b3670fe2fac287114b26d7c5420ab48407d7ea1c3a446d6313c000009da + checksum: 4dfe257e1e42da2f9da872b05aaaf99b0f5aa022c1a91eee8f2af1ab72651b596366320c575ccd4e0469f7b4c97aff5bb85ae3323ebd6a293c3faef4028b0d81 languageName: node linkType: hard -"espree@npm:^9.3.1, espree@npm:^9.6.0": +"espree@npm:^9.3.1, espree@npm:^9.6.0, espree@npm:^9.6.1": version: 9.6.1 resolution: "espree@npm:9.6.1" dependencies: @@ -4703,15 +4672,15 @@ __metadata: linkType: hard "fast-glob@npm:^3.2.7, fast-glob@npm:^3.2.9": - version: 3.3.0 - resolution: "fast-glob@npm:3.3.0" + version: 3.3.1 + resolution: "fast-glob@npm:3.3.1" dependencies: "@nodelib/fs.stat": ^2.0.2 "@nodelib/fs.walk": ^1.2.3 glob-parent: ^5.1.2 merge2: ^1.3.0 micromatch: ^4.0.4 - checksum: 20df62be28eb5426fe8e40e0d05601a63b1daceb7c3d87534afcad91bdcf1e4b1743cf2d5247d6e225b120b46df0b9053a032b2691ba34ee121e033acd81f547 + checksum: b6f3add6403e02cf3a798bfbb1183d0f6da2afd368f27456010c0bc1f9640aea308243d4cb2c0ab142f618276e65ecb8be1661d7c62a7b4e5ba774b9ce5432e5 languageName: node linkType: hard @@ -4729,6 +4698,13 @@ __metadata: languageName: node linkType: hard +"fastest-levenshtein@npm:^1.0.12": + version: 1.0.16 + resolution: "fastest-levenshtein@npm:1.0.16" + checksum: a78d44285c9e2ae2c25f3ef0f8a73f332c1247b7ea7fb4a191e6bb51aa6ee1ef0dfb3ed113616dcdc7023e18e35a8db41f61c8d88988e877cf510df8edafbc71 + languageName: node + linkType: hard + "fastq@npm:^1.6.0": version: 1.15.0 resolution: "fastq@npm:1.15.0" @@ -4855,12 +4831,13 @@ __metadata: linkType: hard "flat-cache@npm:^3.0.4": - version: 3.0.4 - resolution: "flat-cache@npm:3.0.4" + version: 3.1.0 + resolution: "flat-cache@npm:3.1.0" dependencies: - flatted: ^3.1.0 + flatted: ^3.2.7 + keyv: ^4.5.3 rimraf: ^3.0.2 - checksum: 4fdd10ecbcbf7d520f9040dd1340eb5dfe951e6f0ecf2252edeec03ee68d989ec8b9a20f4434270e71bcfd57800dc09b3344fca3966b2eb8f613072c7d9a2365 + checksum: 99312601d5b90f44aef403f17f056dc09be7e437703740b166cdc9386d99e681f74e6b6e8bd7d010bda66904ea643c9527276b1b80308a2119741d94108a4d8f languageName: node linkType: hard @@ -4875,7 +4852,7 @@ __metadata: languageName: node linkType: hard -"flatted@npm:^3.1.0": +"flatted@npm:^3.2.7": version: 3.2.7 resolution: "flatted@npm:3.2.7" checksum: 427633049d55bdb80201c68f7eb1cbd533e03eac541f97d3aecab8c5526f12a20ccecaeede08b57503e772c769e7f8680b37e8d482d1e5f8d7e2194687f9ea35 @@ -4979,9 +4956,9 @@ __metadata: linkType: hard "fraction.js@npm:^4.2.0": - version: 4.2.0 - resolution: "fraction.js@npm:4.2.0" - checksum: 8c76a6e21dedea87109d6171a0ac77afa14205794a565d71cb10d2925f629a3922da61bf45ea52dbc30bce4d8636dc0a27213a88cbd600eab047d82f9a3a94c5 + version: 4.3.6 + resolution: "fraction.js@npm:4.3.6" + checksum: e96ae77e64ebfd442d3a5a01a3f0637b0663fc2440bcf2841b3ad9341ba24c81fb2e3e7142e43ef7d088558c6b3f8609df135b201adc7a1c674aea6a71384162 languageName: node linkType: hard @@ -5039,11 +5016,11 @@ __metadata: linkType: hard "fs-minipass@npm:^3.0.0": - version: 3.0.2 - resolution: "fs-minipass@npm:3.0.2" + version: 3.0.3 + resolution: "fs-minipass@npm:3.0.3" dependencies: - minipass: ^5.0.0 - checksum: e9cc0e1f2d01c6f6f62f567aee59530aba65c6c7b2ae88c5027bc34c711ebcfcfaefd0caf254afa6adfe7d1fba16bc2537508a6235196bac7276747d078aef0a + minipass: ^7.0.3 + checksum: 8722a41109130851d979222d3ec88aabaceeaaf8f57b2a8f744ef8bd2d1ce95453b04a61daa0078822bc5cd21e008814f06fe6586f56fef511e71b8d2394d802 languageName: node linkType: hard @@ -5062,18 +5039,18 @@ __metadata: linkType: hard "fsevents@npm:~2.3.2": - version: 2.3.2 - resolution: "fsevents@npm:2.3.2" + version: 2.3.3 + resolution: "fsevents@npm:2.3.3" dependencies: node-gyp: latest - checksum: 97ade64e75091afee5265e6956cb72ba34db7819b4c3e94c431d4be2b19b8bb7a2d4116da417950c3425f17c8fe693d25e20212cac583ac1521ad066b77ae31f + checksum: 11e6ea6fea15e42461fc55b4b0e4a0a3c654faa567f1877dbd353f39156f69def97a69936d1746619d656c4b93de2238bf731f6085a03a50cabf287c9d024317 conditions: os=darwin languageName: node linkType: hard "fsevents@patch:fsevents@~2.3.2#~builtin": - version: 2.3.2 - resolution: "fsevents@patch:fsevents@npm%3A2.3.2#~builtin::version=2.3.2&hash=df0bf1" + version: 2.3.3 + resolution: "fsevents@patch:fsevents@npm%3A2.3.3#~builtin::version=2.3.3&hash=df0bf1" dependencies: node-gyp: latest conditions: os=darwin @@ -5097,19 +5074,19 @@ __metadata: languageName: node linkType: hard -"function.prototype.name@npm:^1.1.5": - version: 1.1.5 - resolution: "function.prototype.name@npm:1.1.5" +"function.prototype.name@npm:^1.1.6": + version: 1.1.6 + resolution: "function.prototype.name@npm:1.1.6" dependencies: call-bind: ^1.0.2 - define-properties: ^1.1.3 - es-abstract: ^1.19.0 - functions-have-names: ^1.2.2 - checksum: acd21d733a9b649c2c442f067567743214af5fa248dbeee69d8278ce7df3329ea5abac572be9f7470b4ec1cd4d8f1040e3c5caccf98ebf2bf861a0deab735c27 + define-properties: ^1.2.0 + es-abstract: ^1.22.1 + functions-have-names: ^1.2.3 + checksum: 7a3f9bd98adab09a07f6e1f03da03d3f7c26abbdeaeee15223f6c04a9fb5674792bdf5e689dac19b97ac71de6aad2027ba3048a9b883aa1b3173eed6ab07f479 languageName: node linkType: hard -"functions-have-names@npm:^1.2.2, functions-have-names@npm:^1.2.3": +"functions-have-names@npm:^1.2.3": version: 1.2.3 resolution: "functions-have-names@npm:1.2.3" checksum: c3f1f5ba20f4e962efb71344ce0a40722163e85bee2101ce25f88214e78182d2d2476aa85ef37950c579eb6cf6ee811c17b3101bb84004bb75655f3e33f3fdb5 @@ -5285,8 +5262,8 @@ __metadata: linkType: hard "glob@npm:^10.2.2": - version: 10.3.3 - resolution: "glob@npm:10.3.3" + version: 10.3.4 + resolution: "glob@npm:10.3.4" dependencies: foreground-child: ^3.1.0 jackspeak: ^2.0.3 @@ -5295,7 +5272,7 @@ __metadata: path-scurry: ^1.10.1 bin: glob: dist/cjs/src/bin.js - checksum: 29190d3291f422da0cb40b77a72fc8d2c51a36524e99b8bf412548b7676a6627489528b57250429612b6eec2e6fe7826d328451d3e694a9d15e575389308ec53 + checksum: 176b97c124414401cb51329a93d2ba112cef8814adbed10348481916b9521b677773eee2691cb6b24d66632d8c8bb8913533f5ac4bfb2d0ef5454a1856082361 languageName: node linkType: hard @@ -5321,11 +5298,11 @@ __metadata: linkType: hard "globals@npm:^13.19.0": - version: 13.20.0 - resolution: "globals@npm:13.20.0" + version: 13.21.0 + resolution: "globals@npm:13.21.0" dependencies: type-fest: ^0.20.2 - checksum: ad1ecf914bd051325faad281d02ea2c0b1df5d01bd94d368dcc5513340eac41d14b3c61af325768e3c7f8d44576e72780ec0b6f2d366121f8eec6e03c3a3b97a + checksum: 86c92ca8a04efd864c10852cd9abb1ebe6d447dcc72936783e66eaba1087d7dba5c9c3421a48d6ca722c319378754dbcc3f3f732dbe47592d7de908edf58a773 languageName: node linkType: hard @@ -5450,15 +5427,6 @@ __metadata: languageName: node linkType: hard -"has-ansi@npm:^2.0.0": - version: 2.0.0 - resolution: "has-ansi@npm:2.0.0" - dependencies: - ansi-regex: ^2.0.0 - checksum: 1b51daa0214440db171ff359d0a2d17bc20061164c57e76234f614c91dbd2a79ddd68dfc8ee73629366f7be45a6df5f2ea9de83f52e1ca24433f2cc78c35d8ec - languageName: node - linkType: hard - "has-bigints@npm:^1.0.1, has-bigints@npm:^1.0.2": version: 1.0.2 resolution: "has-bigints@npm:1.0.2" @@ -5842,9 +5810,9 @@ __metadata: linkType: hard "immutable@npm:^4.0.0": - version: 4.3.1 - resolution: "immutable@npm:4.3.1" - checksum: a3a5ba29bd43f3f9a2e4d599763d7455d11a0ea57e50bf43f2836672fc80003e90d69f2a4f5b589f1f3d6986faf97f08ce1e253583740dd33c00adebab88b217 + version: 4.3.4 + resolution: "immutable@npm:4.3.4" + checksum: de3edd964c394bab83432429d3fb0b4816b42f56050f2ca913ba520bd3068ec3e504230d0800332d3abc478616e8f55d3787424a90d0952e6aba864524f1afc3 languageName: node linkType: hard @@ -5858,6 +5826,18 @@ __metadata: languageName: node linkType: hard +"import-local@npm:^3.0.2": + version: 3.1.0 + resolution: "import-local@npm:3.1.0" + dependencies: + pkg-dir: ^4.2.0 + resolve-cwd: ^3.0.0 + bin: + import-local-fixture: fixtures/cli.js + checksum: bfcdb63b5e3c0e245e347f3107564035b128a414c4da1172a20dc67db2504e05ede4ac2eee1252359f78b0bfd7b19ef180aec427c2fce6493ae782d73a04cddd + languageName: node + linkType: hard + "imurmurhash@npm:^0.1.4": version: 0.1.4 resolution: "imurmurhash@npm:0.1.4" @@ -5914,10 +5894,10 @@ __metadata: languageName: node linkType: hard -"invert-kv@npm:^1.0.0": - version: 1.0.0 - resolution: "invert-kv@npm:1.0.0" - checksum: aebeee31dda3b3d25ffd242e9a050926e7fe5df642d60953ab183aca1a7d1ffb39922eb2618affb0e850cf2923116f0da1345367759d88d097df5da1f1e1590e +"interpret@npm:^3.1.1": + version: 3.1.1 + resolution: "interpret@npm:3.1.1" + checksum: 35cebcf48c7351130437596d9ab8c8fe131ce4038da4561e6d665f25640e0034702a031cf7e3a5cea60ac7ac548bf17465e0571ede126f3d3a6933152171ac82 languageName: node linkType: hard @@ -6027,12 +6007,12 @@ __metadata: languageName: node linkType: hard -"is-core-module@npm:^2.12.0": - version: 2.12.1 - resolution: "is-core-module@npm:2.12.1" +"is-core-module@npm:^2.13.0": + version: 2.13.0 + resolution: "is-core-module@npm:2.13.0" dependencies: has: ^1.0.3 - checksum: f04ea30533b5e62764e7b2e049d3157dc0abd95ef44275b32489ea2081176ac9746ffb1cdb107445cf1ff0e0dfcad522726ca27c27ece64dadf3795428b8e468 + checksum: 053ab101fb390bfeb2333360fd131387bed54e476b26860dc7f5a700bbf34a0ec4454f7c8c4d43e8a0030957e4b3db6e16d35e1890ea6fb654c833095e040355 languageName: node linkType: hard @@ -6070,15 +6050,6 @@ __metadata: languageName: node linkType: hard -"is-fullwidth-code-point@npm:^1.0.0": - version: 1.0.0 - resolution: "is-fullwidth-code-point@npm:1.0.0" - dependencies: - number-is-nan: ^1.0.0 - checksum: 4d46a7465a66a8aebcc5340d3b63a56602133874af576a9ca42c6f0f4bd787a743605771c5f246db77da96605fefeffb65fc1dbe862dcc7328f4b4d03edf5a57 - languageName: node - linkType: hard - "is-fullwidth-code-point@npm:^2.0.0": version: 2.0.0 resolution: "is-fullwidth-code-point@npm:2.0.0" @@ -6169,6 +6140,13 @@ __metadata: languageName: node linkType: hard +"is-plain-object@npm:^5.0.0": + version: 5.0.0 + resolution: "is-plain-object@npm:5.0.0" + checksum: e32d27061eef62c0847d303125440a38660517e586f2f3db7c9d179ae5b6674ab0f469d519b2e25c147a1a3bc87156d0d5f4d8821e0ce4a9ee7fe1fcf11ce45c + languageName: node + linkType: hard + "is-potential-custom-element-name@npm:^1.0.1": version: 1.0.1 resolution: "is-potential-custom-element-name@npm:1.0.1" @@ -6234,7 +6212,7 @@ __metadata: languageName: node linkType: hard -"is-typed-array@npm:^1.1.10, is-typed-array@npm:^1.1.9": +"is-typed-array@npm:^1.1.10, is-typed-array@npm:^1.1.12, is-typed-array@npm:^1.1.9": version: 1.1.12 resolution: "is-typed-array@npm:1.1.12" dependencies: @@ -6343,15 +6321,15 @@ __metadata: linkType: hard "jackspeak@npm:^2.0.3": - version: 2.2.1 - resolution: "jackspeak@npm:2.2.1" + version: 2.3.3 + resolution: "jackspeak@npm:2.3.3" dependencies: "@isaacs/cliui": ^8.0.2 "@pkgjs/parseargs": ^0.11.0 dependenciesMeta: "@pkgjs/parseargs": optional: true - checksum: e29291c0d0f280a063fa18fbd1e891ab8c2d7519fd34052c0ebde38538a15c603140d60c2c7f432375ff7ee4c5f1c10daa8b2ae19a97c3d4affe308c8360c1df + checksum: 4313a7c0cc44c7753c4cb9869935f0b06f4cf96827515f63f58ff46b3d2f6e29aba6b3b5151778397c3f5ae67ef8bfc48871967bd10343c27e90cff198ec7808 languageName: node linkType: hard @@ -6399,15 +6377,15 @@ __metadata: linkType: hard "joi@npm:^17.4.0": - version: 17.9.2 - resolution: "joi@npm:17.9.2" + version: 17.10.1 + resolution: "joi@npm:17.10.1" dependencies: "@hapi/hoek": ^9.0.0 "@hapi/topo": ^5.0.0 "@sideway/address": ^4.1.3 "@sideway/formula": ^3.0.1 "@sideway/pinpoint": ^2.0.0 - checksum: 8c3709849293411c524e5a679dba7b42598a29a663478941767b8d5b06288611dece58803c468a2c7320cc2429a3e71e3d94337fe47aefcf6c22174dbd90b601 + checksum: 7affbb27ae9283596d6471871352b85ebf73a1e782c0be1998bce1ecc86ba48bee834c8af9a44d7143bb470654d6ae1248a29009ee5463618675d655dbd69306 languageName: node linkType: hard @@ -6570,7 +6548,7 @@ __metadata: languageName: node linkType: hard -"json5@npm:^2.1.2, json5@npm:^2.2.2": +"json5@npm:^2.1.2, json5@npm:^2.2.3": version: 2.2.3 resolution: "json5@npm:2.2.3" bin: @@ -6630,7 +6608,7 @@ __metadata: languageName: node linkType: hard -"keyv@npm:^4.0.0": +"keyv@npm:^4.0.0, keyv@npm:^4.5.3": version: 4.5.3 resolution: "keyv@npm:4.5.3" dependencies: @@ -6672,15 +6650,6 @@ __metadata: languageName: node linkType: hard -"lcid@npm:^1.0.0": - version: 1.0.0 - resolution: "lcid@npm:1.0.0" - dependencies: - invert-kv: ^1.0.0 - checksum: e8c7a4db07663068c5c44b650938a2bc41aa992037eebb69376214320f202c1250e70b50c32f939e28345fd30c2d35b8e8cd9a19d5932c398246a864ce54843d - languageName: node - linkType: hard - "less-loader@npm:^11.0.0": version: 11.1.3 resolution: "less-loader@npm:11.1.3" @@ -6692,8 +6661,8 @@ __metadata: linkType: hard "less@npm:^4.1.3": - version: 4.1.3 - resolution: "less@npm:4.1.3" + version: 4.2.0 + resolution: "less@npm:4.2.0" dependencies: copy-anything: ^2.0.1 errno: ^0.1.1 @@ -6722,7 +6691,7 @@ __metadata: optional: true bin: lessc: bin/lessc - checksum: 1470fbec993a375eb28d729cd906805fd62b7a7f1b4f5b4d62d04e81eaba987a9373e74aa0b9fa9191149ebc0bfb42e2ea98a038555555b7b241c10a854067cc + checksum: 2ec4fa41e35e5c0331c1ee64419aa5c2cbb9a17b9e9d1deb524ec45843f59d9c4612dffc164ca16126911fbe9913e4ff811a13f33805f71e546f6d022ece93b6 languageName: node linkType: hard @@ -6908,6 +6877,13 @@ __metadata: languageName: node linkType: hard +"lodash.debounce@npm:^4.0.8": + version: 4.0.8 + resolution: "lodash.debounce@npm:4.0.8" + checksum: a3f527d22c548f43ae31c861ada88b2637eb48ac6aa3eb56e82d44917971b8aa96fbb37aa60efea674dc4ee8c42074f90f7b1f772e9db375435f6c83a19b3bc6 + languageName: node + linkType: hard + "lodash.defaultsdeep@npm:^4.6.1": version: 4.6.1 resolution: "lodash.defaultsdeep@npm:4.6.1" @@ -6915,6 +6891,27 @@ __metadata: languageName: node linkType: hard +"lodash.escape@npm:^4.0.1": + version: 4.0.1 + resolution: "lodash.escape@npm:4.0.1" + checksum: fcb54f457497256964d619d5cccbd80a961916fca60df3fe0fa3e7f052715c2944c0ed5aefb4f9e047d127d44aa2d55555f3350cb42c6549e9e293fb30b41e7f + languageName: node + linkType: hard + +"lodash.flatten@npm:^4.4.0": + version: 4.4.0 + resolution: "lodash.flatten@npm:4.4.0" + checksum: 0ac34a393d4b795d4b7421153d27c13ae67e08786c9cbb60ff5b732210d46f833598eee3fb3844bb10070e8488efe390ea53bb567377e0cb47e9e630bf0811cb + languageName: node + linkType: hard + +"lodash.invokemap@npm:^4.6.0": + version: 4.6.0 + resolution: "lodash.invokemap@npm:4.6.0" + checksum: 646ceebbefbcb6da301f8c2868254680fd0bcdc6ada470495d9ae49c9c32938829c1b38a38c95d0258409a9655f85db404b16e648381c7450b7ed3d9c52d8808 + languageName: node + linkType: hard + "lodash.isarguments@npm:^3.0.0": version: 3.1.0 resolution: "lodash.isarguments@npm:3.1.0" @@ -6961,6 +6958,13 @@ __metadata: languageName: node linkType: hard +"lodash.pullall@npm:^4.2.0": + version: 4.2.0 + resolution: "lodash.pullall@npm:4.2.0" + checksum: 7a5fbaedf186ec197ce1e0b9ba1d88a89773ebaf6a8291c7d273838cac59cb3b339cf36ef00e94172862ee84d2304c38face161846f08f5581d0553dcbdcd090 + languageName: node + linkType: hard + "lodash.uniq@npm:^4.5.0": version: 4.5.0 resolution: "lodash.uniq@npm:4.5.0" @@ -6968,6 +6972,13 @@ __metadata: languageName: node linkType: hard +"lodash.uniqby@npm:^4.7.0": + version: 4.7.0 + resolution: "lodash.uniqby@npm:4.7.0" + checksum: 659264545a95726d1493123345aad8cbf56e17810fa9a0b029852c6d42bc80517696af09d99b23bef1845d10d95e01b8b4a1da578f22aeba7a30d3e0022a4938 + languageName: node + linkType: hard + "lodash@npm:^4.17.14, lodash@npm:^4.17.15, lodash@npm:^4.17.19, lodash@npm:^4.17.20, lodash@npm:^4.17.21": version: 4.17.21 resolution: "lodash@npm:4.17.21" @@ -7075,9 +7086,9 @@ __metadata: linkType: hard "lru-cache@npm:^9.1.1 || ^10.0.0": - version: 10.0.0 - resolution: "lru-cache@npm:10.0.0" - checksum: 18f101675fe283bc09cda0ef1e3cc83781aeb8373b439f086f758d1d91b28730950db785999cd060d3c825a8571c03073e8c14512b6655af2188d623031baf50 + version: 10.0.1 + resolution: "lru-cache@npm:10.0.1" + checksum: 06f8d0e1ceabd76bb6f644a26dbb0b4c471b79c7b514c13c6856113879b3bf369eb7b497dad4ff2b7e2636db202412394865b33c332100876d838ad1372f0181 languageName: node linkType: hard @@ -7089,11 +7100,11 @@ __metadata: linkType: hard "magic-string@npm:^0.30.0": - version: 0.30.1 - resolution: "magic-string@npm:0.30.1" + version: 0.30.3 + resolution: "magic-string@npm:0.30.3" dependencies: "@jridgewell/sourcemap-codec": ^1.4.15 - checksum: 7bc7e4493e32a77068f3753bf8652d4ab44142122eb7fb9fa871af83bef2cd2c57518a6769701cd5d0379bd624a13bc8c72ca25ac5655b27e5a61adf1fd38db2 + checksum: a5a9ddf9bd3bf49a2de1048bf358464f1bda7b3cc1311550f4a0ba8f81a4070e25445d53a5ee28850161336f1bff3cf28aa3320c6b4aeff45ce3e689f300b2f3 languageName: node linkType: hard @@ -7356,17 +7367,17 @@ __metadata: linkType: hard "minipass-fetch@npm:^3.0.0": - version: 3.0.3 - resolution: "minipass-fetch@npm:3.0.3" + version: 3.0.4 + resolution: "minipass-fetch@npm:3.0.4" dependencies: encoding: ^0.1.13 - minipass: ^5.0.0 + minipass: ^7.0.3 minipass-sized: ^1.0.3 minizlib: ^2.1.2 dependenciesMeta: encoding: optional: true - checksum: af5ab2552a16fcf505d35fd7ffb84b57f4a0eeb269e6e1d9a2a75824dda48b36e527083250b7cca4a4def21d9544e2ade441e4730e233c0bc2133f6abda31e18 + checksum: af7aad15d5c128ab1ebe52e043bdf7d62c3c6f0cecb9285b40d7b395e1375b45dcdfd40e63e93d26a0e8249c9efd5c325c65575aceee192883970ff8cb11364a languageName: node linkType: hard @@ -7413,10 +7424,10 @@ __metadata: languageName: node linkType: hard -"minipass@npm:^5.0.0 || ^6.0.2 || ^7.0.0": - version: 7.0.2 - resolution: "minipass@npm:7.0.2" - checksum: 46776de732eb7cef2c7404a15fb28c41f5c54a22be50d47b03c605bf21f5c18d61a173c0a20b49a97e7a65f78d887245066410642551e45fffe04e9ac9e325bc +"minipass@npm:^5.0.0 || ^6.0.2 || ^7.0.0, minipass@npm:^7.0.3": + version: 7.0.3 + resolution: "minipass@npm:7.0.3" + checksum: 6f1614f5b5b55568a46bca5fec0e7c46dac027691db27d0e1923a8192866903144cd962ac772c0e9f89b608ea818b702709c042bce98e190d258847d85461531 languageName: node linkType: hard @@ -7760,8 +7771,8 @@ __metadata: linkType: hard "node-fetch@npm:^2.6.7": - version: 2.6.12 - resolution: "node-fetch@npm:2.6.12" + version: 2.7.0 + resolution: "node-fetch@npm:2.7.0" dependencies: whatwg-url: ^5.0.0 peerDependencies: @@ -7769,7 +7780,7 @@ __metadata: peerDependenciesMeta: encoding: optional: true - checksum: 3bc1655203d47ee8e313c0d96664b9673a3d4dd8002740318e9d27d14ef306693a4b2ef8d6525775056fd912a19e23f3ac0d7111ad8925877b7567b29a625592 + checksum: d76d2f5edb451a3f05b15115ec89fc6be39de37c6089f1b6368df03b91e1633fd379a7e01b7ab05089a25034b2023d959b47e59759cb38d88341b2459e89d6e5 languageName: node linkType: hard @@ -7801,7 +7812,7 @@ __metadata: languageName: node linkType: hard -"node-releases@npm:^2.0.12": +"node-releases@npm:^2.0.13": version: 2.0.13 resolution: "node-releases@npm:2.0.13" checksum: 17ec8f315dba62710cae71a8dad3cd0288ba943d2ece43504b3b1aa8625bf138637798ab470b1d9035b0545996f63000a8a926e0f6d35d0996424f8b6d36dda3 @@ -7928,7 +7939,7 @@ __metadata: languageName: node linkType: hard -"nth-check@npm:^2.0.1": +"nth-check@npm:^2.0.1, nth-check@npm:^2.1.1": version: 2.1.1 resolution: "nth-check@npm:2.1.1" dependencies: @@ -7937,13 +7948,6 @@ __metadata: languageName: node linkType: hard -"number-is-nan@npm:^1.0.0": - version: 1.0.1 - resolution: "number-is-nan@npm:1.0.1" - checksum: 13656bc9aa771b96cef209ffca31c31a03b507ca6862ba7c3f638a283560620d723d52e626d57892c7fff475f4c36ac07f0600f14544692ff595abff214b9ffb - languageName: node - linkType: hard - "nwsapi@npm:^2.2.4": version: 2.2.7 resolution: "nwsapi@npm:2.2.7" @@ -8004,15 +8008,15 @@ __metadata: linkType: hard "object.getownpropertydescriptors@npm:^2.0.3": - version: 2.1.6 - resolution: "object.getownpropertydescriptors@npm:2.1.6" + version: 2.1.7 + resolution: "object.getownpropertydescriptors@npm:2.1.7" dependencies: - array.prototype.reduce: ^1.0.5 + array.prototype.reduce: ^1.0.6 call-bind: ^1.0.2 define-properties: ^1.2.0 - es-abstract: ^1.21.2 + es-abstract: ^1.22.1 safe-array-concat: ^1.0.0 - checksum: 7757ce0ef61c8bee7f8043f8980fd3d46fc1ab3faf0795bd1f9f836781143b4afc91f7219a3eed4675fbd0b562f3708f7e736d679ebfd43ea37ab6077d9f5004 + checksum: 8e7ae1d522a3874d2d23a3d0fb75828cbcee60958b65c2ad8e58ce227f4efba8cc2b59c7431a0fd48b20d9e04ec075bc0e0d694b1d2c2296e534daf558beb10b languageName: node linkType: hard @@ -8163,15 +8167,6 @@ __metadata: languageName: node linkType: hard -"os-locale@npm:^1.4.0": - version: 1.4.0 - resolution: "os-locale@npm:1.4.0" - dependencies: - lcid: ^1.0.0 - checksum: 0161a1b6b5a8492f99f4b47fe465df9fc521c55ba5414fce6444c45e2500487b8ed5b40a47a98a2363fe83ff04ab033785300ed8df717255ec4c3b625e55b1fb - languageName: node - linkType: hard - "os-tmpdir@npm:^1.0.0": version: 1.0.2 resolution: "os-tmpdir@npm:1.0.2" @@ -8538,8 +8533,8 @@ __metadata: linkType: hard "pinia@npm:^2.0.22": - version: 2.1.4 - resolution: "pinia@npm:2.1.4" + version: 2.1.6 + resolution: "pinia@npm:2.1.6" dependencies: "@vue/devtools-api": ^6.5.0 vue-demi: ">=0.14.5" @@ -8552,11 +8547,11 @@ __metadata: optional: true typescript: optional: true - checksum: 5285b1415e6c88698d41393e9144dfd0fbbb7f88cdc90637f6bf3526046c1f171befe01b2b063e9f6004f16b6c8dc1ed3ae9b2434ccf69403fec291215f0e1e3 + checksum: 4e881e590c4f6ec9c2dc6174cf7ecc71a48bff1f3a5be878669b3b2fd32994fa64c3cbf499d138bc4e0f222ac6ad1d07935b0a592791acdaf8c9f2a12c98f042 languageName: node linkType: hard -"pkg-dir@npm:4.2.0, pkg-dir@npm:^4.1.0": +"pkg-dir@npm:4.2.0, pkg-dir@npm:^4.1.0, pkg-dir@npm:^4.2.0": version: 4.2.0 resolution: "pkg-dir@npm:4.2.0" dependencies: @@ -8923,7 +8918,7 @@ __metadata: languageName: node linkType: hard -"postcss-selector-parser@npm:^6.0.2, postcss-selector-parser@npm:^6.0.4, postcss-selector-parser@npm:^6.0.5, postcss-selector-parser@npm:^6.0.9": +"postcss-selector-parser@npm:^6.0.13, postcss-selector-parser@npm:^6.0.2, postcss-selector-parser@npm:^6.0.4, postcss-selector-parser@npm:^6.0.5, postcss-selector-parser@npm:^6.0.9": version: 6.0.13 resolution: "postcss-selector-parser@npm:6.0.13" dependencies: @@ -8974,13 +8969,13 @@ __metadata: linkType: hard "postcss@npm:^8.1.10, postcss@npm:^8.2.6, postcss@npm:^8.3.5, postcss@npm:^8.4.21": - version: 8.4.27 - resolution: "postcss@npm:8.4.27" + version: 8.4.29 + resolution: "postcss@npm:8.4.29" dependencies: nanoid: ^3.3.6 picocolors: ^1.0.0 source-map-js: ^1.0.2 - checksum: 1cdd0c298849df6cd65f7e646a3ba36870a37b65f55fd59d1a165539c263e9b4872a402bf4ed1ca1bc31f58b68b2835545e33ea1a23b161a1f8aa6d5ded81e78 + checksum: dd6daa25e781db9ae5b651d9b7bfde0ec6e60e86a37da69a18eb4773d5ddd51e28fc4ff054fbdc04636a31462e6bf09a1e50986f69ac52b10d46b7457cd36d12 languageName: node linkType: hard @@ -9333,21 +9328,37 @@ __metadata: languageName: node linkType: hard -"regenerator-runtime@npm:^0.13.11, regenerator-runtime@npm:^0.13.4": +"rechoir@npm:^0.8.0": + version: 0.8.0 + resolution: "rechoir@npm:0.8.0" + dependencies: + resolve: ^1.20.0 + checksum: ad3caed8afdefbc33fbc30e6d22b86c35b3d51c2005546f4e79bcc03c074df804b3640ad18945e6bef9ed12caedc035655ec1082f64a5e94c849ff939dc0a788 + languageName: node + linkType: hard + +"regenerator-runtime@npm:^0.13.4": version: 0.13.11 resolution: "regenerator-runtime@npm:0.13.11" checksum: 27481628d22a1c4e3ff551096a683b424242a216fee44685467307f14d58020af1e19660bf2e26064de946bad7eff28950eae9f8209d55723e2d9351e632bbb4 languageName: node linkType: hard -"regexp.prototype.flags@npm:^1.5.0": - version: 1.5.0 - resolution: "regexp.prototype.flags@npm:1.5.0" +"regenerator-runtime@npm:^0.14.0": + version: 0.14.0 + resolution: "regenerator-runtime@npm:0.14.0" + checksum: 1c977ad82a82a4412e4f639d65d22be376d3ebdd30da2c003eeafdaaacd03fc00c2320f18120007ee700900979284fc78a9f00da7fb593f6e6eeebc673fba9a3 + languageName: node + linkType: hard + +"regexp.prototype.flags@npm:^1.5.1": + version: 1.5.1 + resolution: "regexp.prototype.flags@npm:1.5.1" dependencies: call-bind: ^1.0.2 define-properties: ^1.2.0 - functions-have-names: ^1.2.3 - checksum: c541687cdbdfff1b9a07f6e44879f82c66bbf07665f9a7544c5fd16acdb3ec8d1436caab01662d2fbcad403f3499d49ab0b77fbc7ef29ef961d98cc4bc9755b4 + set-function-name: ^2.0.0 + checksum: 869edff00288442f8d7fa4c9327f91d85f3b3acf8cbbef9ea7a220345cf23e9241b6def9263d2c1ebcf3a316b0aa52ad26a43a84aa02baca3381717b3e307f47 languageName: node linkType: hard @@ -9459,6 +9470,15 @@ __metadata: languageName: node linkType: hard +"resolve-cwd@npm:^3.0.0": + version: 3.0.0 + resolution: "resolve-cwd@npm:3.0.0" + dependencies: + resolve-from: ^5.0.0 + checksum: 546e0816012d65778e580ad62b29e975a642989108d9a3c5beabfb2304192fa3c9f9146fbdfe213563c6ff51975ae41bac1d3c6e047dd9572c94863a057b4d81 + languageName: node + linkType: hard + "resolve-from@npm:^4.0.0": version: 4.0.0 resolution: "resolve-from@npm:4.0.0" @@ -9466,29 +9486,36 @@ __metadata: languageName: node linkType: hard -"resolve@npm:^1.10.0": - version: 1.22.3 - resolution: "resolve@npm:1.22.3" +"resolve-from@npm:^5.0.0": + version: 5.0.0 + resolution: "resolve-from@npm:5.0.0" + checksum: 4ceeb9113e1b1372d0cd969f3468fa042daa1dd9527b1b6bb88acb6ab55d8b9cd65dbf18819f9f9ddf0db804990901dcdaade80a215e7b2c23daae38e64f5bdf + languageName: node + linkType: hard + +"resolve@npm:^1.10.0, resolve@npm:^1.20.0": + version: 1.22.4 + resolution: "resolve@npm:1.22.4" dependencies: - is-core-module: ^2.12.0 + is-core-module: ^2.13.0 path-parse: ^1.0.7 supports-preserve-symlinks-flag: ^1.0.0 bin: resolve: bin/resolve - checksum: fb834b81348428cb545ff1b828a72ea28feb5a97c026a1cf40aa1008352c72811ff4d4e71f2035273dc536dcfcae20c13604ba6283c612d70fa0b6e44519c374 + checksum: 23f25174c2736ce24c6d918910e0d1f89b6b38fefa07a995dff864acd7863d59a7f049e691f93b4b2ee29696303390d921552b6d1b841ed4a8101f517e1d0124 languageName: node linkType: hard -"resolve@patch:resolve@^1.10.0#~builtin": - version: 1.22.3 - resolution: "resolve@patch:resolve@npm%3A1.22.3#~builtin::version=1.22.3&hash=c3c19d" +"resolve@patch:resolve@^1.10.0#~builtin, resolve@patch:resolve@^1.20.0#~builtin": + version: 1.22.4 + resolution: "resolve@patch:resolve@npm%3A1.22.4#~builtin::version=1.22.4&hash=c3c19d" dependencies: - is-core-module: ^2.12.0 + is-core-module: ^2.13.0 path-parse: ^1.0.7 supports-preserve-symlinks-flag: ^1.0.0 bin: resolve: bin/resolve - checksum: ad59734723b596d0891321c951592ed9015a77ce84907f89c9d9307dd0c06e11a67906a3e628c4cae143d3e44898603478af0ddeb2bba3f229a9373efe342665 + checksum: c45f2545fdc4d21883861b032789e20aa67a2f2692f68da320cc84d5724cd02f2923766c5354b3210897e88f1a7b3d6d2c7c22faeead8eed7078e4c783a444bc languageName: node linkType: hard @@ -9601,15 +9628,15 @@ __metadata: languageName: node linkType: hard -"safe-array-concat@npm:^1.0.0": - version: 1.0.0 - resolution: "safe-array-concat@npm:1.0.0" +"safe-array-concat@npm:^1.0.0, safe-array-concat@npm:^1.0.1": + version: 1.0.1 + resolution: "safe-array-concat@npm:1.0.1" dependencies: call-bind: ^1.0.2 - get-intrinsic: ^1.2.0 + get-intrinsic: ^1.2.1 has-symbols: ^1.0.3 isarray: ^2.0.5 - checksum: f43cb98fe3b566327d0c09284de2b15fb85ae964a89495c1b1a5d50c7c8ed484190f4e5e71aacc167e16231940079b326f2c0807aea633d47cc7322f40a6b57f + checksum: 001ecf1d8af398251cbfabaf30ed66e3855127fbceee178179524b24160b49d15442f94ed6c0db0b2e796da76bb05b73bf3cc241490ec9c2b741b41d33058581 languageName: node linkType: hard @@ -9670,15 +9697,15 @@ __metadata: linkType: hard "sass@npm:^1.26.3": - version: 1.64.0 - resolution: "sass@npm:1.64.0" + version: 1.67.0 + resolution: "sass@npm:1.67.0" dependencies: chokidar: ">=3.0.0 <4.0.0" immutable: ^4.0.0 source-map-js: ">=0.6.2 <2.0.0" bin: sass: sass.js - checksum: b4eb9b1bdeb1c00e76427d7fe3e5f80d831327178cdee657aa4e014edfc64ebbfe43177147403da1e04d76a24f4093f5a9b1c8d9d80c94579937d8adc5a6ef66 + checksum: 9e7566e8b7386cf265dddcdb266a023fb5759c5a8f48a11da199c8bf419e5f08f4ff6404d85d6bf5eac01e1f7c7061fdb6b7b65cbfda164e59b0a06b72ac8567 languageName: node linkType: hard @@ -9800,7 +9827,7 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.3.2, semver@npm:^7.3.4, semver@npm:^7.3.5, semver@npm:^7.3.6, semver@npm:^7.3.7, semver@npm:^7.3.8": +"semver@npm:^7.3.2, semver@npm:^7.3.4, semver@npm:^7.3.5, semver@npm:^7.3.6, semver@npm:^7.3.7, semver@npm:^7.3.8, semver@npm:^7.5.4": version: 7.5.4 resolution: "semver@npm:7.5.4" dependencies: @@ -9875,6 +9902,17 @@ __metadata: languageName: node linkType: hard +"set-function-name@npm:^2.0.0": + version: 2.0.1 + resolution: "set-function-name@npm:2.0.1" + dependencies: + define-data-property: ^1.0.1 + functions-have-names: ^1.2.3 + has-property-descriptors: ^1.0.0 + checksum: 4975d17d90c40168eee2c7c9c59d023429f0a1690a89d75656306481ece0c3c1fb1ebcc0150ea546d1913e35fbd037bace91372c69e543e51fc5d1f31a9fa126 + languageName: node + linkType: hard + "setprototypeof@npm:1.1.0": version: 1.1.0 resolution: "setprototypeof@npm:1.1.0" @@ -9967,20 +10005,20 @@ __metadata: linkType: hard "signal-exit@npm:^4.0.1": - version: 4.0.2 - resolution: "signal-exit@npm:4.0.2" - checksum: 41f5928431cc6e91087bf0343db786a6313dd7c6fd7e551dbc141c95bb5fb26663444fd9df8ea47c5d7fc202f60aa7468c3162a9365cbb0615fc5e1b1328fe31 + version: 4.1.0 + resolution: "signal-exit@npm:4.1.0" + checksum: 64c757b498cb8629ffa5f75485340594d2f8189e9b08700e69199069c8e3070fb3e255f7ab873c05dc0b3cec412aea7402e10a5990cb6a050bd33ba062a6c549 languageName: node linkType: hard -"sirv@npm:^1.0.7": - version: 1.0.19 - resolution: "sirv@npm:1.0.19" +"sirv@npm:^2.0.3": + version: 2.0.3 + resolution: "sirv@npm:2.0.3" dependencies: "@polka/url": ^1.0.0-next.20 mrmime: ^1.0.0 - totalist: ^1.0.0 - checksum: c943cfc61baf85f05f125451796212ec35d4377af4da90ae8ec1fa23e6d7b0b4d9c74a8fbf65af83c94e669e88a09dc6451ba99154235eead4393c10dda5b07c + totalist: ^3.0.0 + checksum: e2dfd4c97735a6ad6d842d0eec2cd9e3919ff0e46f0d228248c5753ad4b70b832711e77e1259c031c439cdb08303cc54d923685c92b0e890145cc733af7c5568 languageName: node linkType: hard @@ -10171,11 +10209,11 @@ __metadata: linkType: hard "ssri@npm:^10.0.0": - version: 10.0.4 - resolution: "ssri@npm:10.0.4" + version: 10.0.5 + resolution: "ssri@npm:10.0.5" dependencies: - minipass: ^5.0.0 - checksum: fb14da9f8a72b04eab163eb13a9dda11d5962cd2317f85457c4e0b575e9a6e0e3a6a87b5bf122c75cb36565830cd5f263fb457571bf6f1587eb5f95d095d6165 + minipass: ^7.0.3 + checksum: 0a31b65f21872dea1ed3f7c200d7bc1c1b91c15e419deca14f282508ba917cbb342c08a6814c7f68ca4ca4116dd1a85da2bbf39227480e50125a1ceffeecb750 languageName: node linkType: hard @@ -10243,17 +10281,6 @@ __metadata: languageName: node linkType: hard -"string-width@npm:^1.0.1": - version: 1.0.2 - resolution: "string-width@npm:1.0.2" - dependencies: - code-point-at: ^1.0.0 - is-fullwidth-code-point: ^1.0.0 - strip-ansi: ^3.0.0 - checksum: 5c79439e95bc3bd7233a332c5f5926ab2ee90b23816ed4faa380ce3b2576d7800b0a5bb15ae88ed28737acc7ea06a518c2eef39142dd727adad0e45c776cd37e - languageName: node - linkType: hard - "string-width@npm:^1.0.2 || 2, string-width@npm:^2.1.1": version: 2.1.1 resolution: "string-width@npm:2.1.1" @@ -10286,36 +10313,36 @@ __metadata: languageName: node linkType: hard -"string.prototype.trim@npm:^1.2.7": - version: 1.2.7 - resolution: "string.prototype.trim@npm:1.2.7" +"string.prototype.trim@npm:^1.2.8": + version: 1.2.8 + resolution: "string.prototype.trim@npm:1.2.8" dependencies: call-bind: ^1.0.2 - define-properties: ^1.1.4 - es-abstract: ^1.20.4 - checksum: 05b7b2d6af63648e70e44c4a8d10d8cc457536df78b55b9d6230918bde75c5987f6b8604438c4c8652eb55e4fc9725d2912789eb4ec457d6995f3495af190c09 + define-properties: ^1.2.0 + es-abstract: ^1.22.1 + checksum: 49eb1a862a53aba73c3fb6c2a53f5463173cb1f4512374b623bcd6b43ad49dd559a06fb5789bdec771a40fc4d2a564411c0a75d35fb27e76bbe738c211ecff07 languageName: node linkType: hard -"string.prototype.trimend@npm:^1.0.6": - version: 1.0.6 - resolution: "string.prototype.trimend@npm:1.0.6" +"string.prototype.trimend@npm:^1.0.7": + version: 1.0.7 + resolution: "string.prototype.trimend@npm:1.0.7" dependencies: call-bind: ^1.0.2 - define-properties: ^1.1.4 - es-abstract: ^1.20.4 - checksum: 0fdc34645a639bd35179b5a08227a353b88dc089adf438f46be8a7c197fc3f22f8514c1c9be4629b3cd29c281582730a8cbbad6466c60f76b5f99cf2addb132e + define-properties: ^1.2.0 + es-abstract: ^1.22.1 + checksum: 2375516272fd1ba75992f4c4aa88a7b5f3c7a9ca308d963bcd5645adf689eba6f8a04ebab80c33e30ec0aefc6554181a3a8416015c38da0aa118e60ec896310c languageName: node linkType: hard -"string.prototype.trimstart@npm:^1.0.6": - version: 1.0.6 - resolution: "string.prototype.trimstart@npm:1.0.6" +"string.prototype.trimstart@npm:^1.0.7": + version: 1.0.7 + resolution: "string.prototype.trimstart@npm:1.0.7" dependencies: call-bind: ^1.0.2 - define-properties: ^1.1.4 - es-abstract: ^1.20.4 - checksum: 89080feef416621e6ef1279588994305477a7a91648d9436490d56010a1f7adc39167cddac7ce0b9884b8cdbef086987c4dcb2960209f2af8bac0d23ceff4f41 + define-properties: ^1.2.0 + es-abstract: ^1.22.1 + checksum: 13d0c2cb0d5ff9e926fa0bec559158b062eed2b68cd5be777ffba782c96b2b492944e47057274e064549b94dd27cf81f48b27a31fee8af5b574cff253e7eb613 languageName: node linkType: hard @@ -10353,15 +10380,6 @@ __metadata: languageName: node linkType: hard -"strip-ansi@npm:^3.0.0, strip-ansi@npm:^3.0.1": - version: 3.0.1 - resolution: "strip-ansi@npm:3.0.1" - dependencies: - ansi-regex: ^2.0.0 - checksum: 9b974de611ce5075c70629c00fa98c46144043db92ae17748fb780f706f7a789e9989fd10597b7c2053ae8d1513fd707816a91f1879b2f71e6ac0b6a863db465 - languageName: node - linkType: hard - "strip-ansi@npm:^4.0.0": version: 4.0.0 resolution: "strip-ansi@npm:4.0.0" @@ -10445,13 +10463,6 @@ __metadata: languageName: node linkType: hard -"supports-color@npm:^2.0.0": - version: 2.0.0 - resolution: "supports-color@npm:2.0.0" - checksum: 602538c5812b9006404370b5a4b885d3e2a1f6567d314f8b4a41974ffe7d08e525bf92ae0f9c7030e3b4c78e4e34ace55d6a67a74f1571bc205959f5972f88f0 - languageName: node - linkType: hard - "supports-color@npm:^5.3.0": version: 5.5.0 resolution: "supports-color@npm:5.5.0" @@ -10573,8 +10584,8 @@ __metadata: linkType: hard "tar@npm:^6.1.11, tar@npm:^6.1.2": - version: 6.1.15 - resolution: "tar@npm:6.1.15" + version: 6.2.0 + resolution: "tar@npm:6.2.0" dependencies: chownr: ^2.0.0 fs-minipass: ^2.0.0 @@ -10582,7 +10593,7 @@ __metadata: minizlib: ^2.1.1 mkdirp: ^1.0.3 yallist: ^4.0.0 - checksum: f23832fceeba7578bf31907aac744ae21e74a66f4a17a9e94507acf460e48f6db598c7023882db33bab75b80e027c21f276d405e4a0322d58f51c7088d428268 + checksum: db4d9fe74a2082c3a5016630092c54c8375ff3b280186938cfd104f2e089c4fd9bad58688ef6be9cf186a889671bf355c7cda38f09bbf60604b281715ca57f5c languageName: node linkType: hard @@ -10628,8 +10639,8 @@ __metadata: linkType: hard "terser@npm:^5.10.0, terser@npm:^5.16.8": - version: 5.19.2 - resolution: "terser@npm:5.19.2" + version: 5.19.4 + resolution: "terser@npm:5.19.4" dependencies: "@jridgewell/source-map": ^0.3.3 acorn: ^8.8.2 @@ -10637,7 +10648,7 @@ __metadata: source-map-support: ~0.5.20 bin: terser: bin/terser - checksum: e059177775b4d4f4cff219ad89293175aefbd1b081252270444dc83e42a2c5f07824eb2a85eae6e22ef6eb7ef04b21af36dd7d1dd7cfb93912310e57d416a205 + checksum: 09273ce7d3fbe8fea0ec2603ad1c06cc304838bdac42bbfe77835b0b0b6c4a894054575ca518fe16c95d5c401574a8c703f4fde97da45f1c972ea568e6ecafda languageName: node linkType: hard @@ -10735,10 +10746,10 @@ __metadata: languageName: node linkType: hard -"totalist@npm:^1.0.0": - version: 1.1.0 - resolution: "totalist@npm:1.1.0" - checksum: dfab80c7104a1d170adc8c18782d6c04b7df08352dec452191208c66395f7ef2af7537ddfa2cf1decbdcfab1a47afbbf0dec6543ea191da98c1c6e1599f86adc +"totalist@npm:^3.0.0": + version: 3.0.1 + resolution: "totalist@npm:3.0.1" + checksum: 5132d562cf88ff93fd710770a92f31dbe67cc19b5c6ccae2efc0da327f0954d211bbfd9456389655d726c624f284b4a23112f56d1da931ca7cfabbe1f45e778a languageName: node linkType: hard @@ -10812,9 +10823,9 @@ __metadata: linkType: hard "tslib@npm:^2.0.1, tslib@npm:^2.0.3, tslib@npm:^2.3.0": - version: 2.6.0 - resolution: "tslib@npm:2.6.0" - checksum: c01066038f950016a18106ddeca4649b4d76caa76ec5a31e2a26e10586a59fceb4ee45e96719bf6c715648e7c14085a81fee5c62f7e9ebee68e77a5396e5538f + version: 2.6.2 + resolution: "tslib@npm:2.6.2" + checksum: 329ea56123005922f39642318e3d1f0f8265d1e7fcb92c633e0809521da75eeaca28d2cf96d7248229deb40e5c19adf408259f4b9640afd20d13aecc1430f3ad languageName: node linkType: hard @@ -10984,15 +10995,6 @@ __metadata: languageName: node linkType: hard -"uglify-js@npm:^3.9.1": - version: 3.17.4 - resolution: "uglify-js@npm:3.17.4" - bin: - uglifyjs: bin/uglifyjs - checksum: 7b3897df38b6fc7d7d9f4dcd658599d81aa2b1fb0d074829dd4e5290f7318dbca1f4af2f45acb833b95b1fe0ed4698662ab61b87e94328eb4c0a0d3435baf924 - languageName: node - linkType: hard - "uid-number@npm:0.0.5": version: 0.0.5 resolution: "uid-number@npm:0.0.5" @@ -11232,8 +11234,8 @@ __metadata: linkType: hard "vue-demi@npm:>=0.14.5": - version: 0.14.5 - resolution: "vue-demi@npm:0.14.5" + version: 0.14.6 + resolution: "vue-demi@npm:0.14.6" peerDependencies: "@vue/composition-api": ^1.0.0-rc.1 vue: ^3.0.0-0 || ^2.6.0 @@ -11243,11 +11245,11 @@ __metadata: bin: vue-demi-fix: bin/vue-demi-fix.js vue-demi-switch: bin/vue-demi-switch.js - checksum: ff44b9372b8224590514252a2f73363cced6062205f9628a6b130dccb80e2023d55cd9d1da94aeb68d5539b7ea9eedcecf88ab281a3a9ff48b8db4c5366b9643 + checksum: 424b1f340d5111fc4d4a0f8042c14ae836ba983bc968773a6d955d6846202d7e6f951993ac1525be8732b0cfe0c81d94ab88f427c97bfa86ead08db06491279b languageName: node linkType: hard -"vue-eslint-parser@npm:^9.1.1, vue-eslint-parser@npm:^9.3.0": +"vue-eslint-parser@npm:^9.1.1, vue-eslint-parser@npm:^9.3.1": version: 9.3.1 resolution: "vue-eslint-parser@npm:9.3.1" dependencies: @@ -11420,22 +11422,29 @@ __metadata: linkType: hard "webpack-bundle-analyzer@npm:^4.4.0": - version: 4.9.0 - resolution: "webpack-bundle-analyzer@npm:4.9.0" + version: 4.9.1 + resolution: "webpack-bundle-analyzer@npm:4.9.1" dependencies: "@discoveryjs/json-ext": 0.5.7 acorn: ^8.0.4 acorn-walk: ^8.0.0 - chalk: ^4.1.0 commander: ^7.2.0 + escape-string-regexp: ^4.0.0 gzip-size: ^6.0.0 - lodash: ^4.17.20 + is-plain-object: ^5.0.0 + lodash.debounce: ^4.0.8 + lodash.escape: ^4.0.1 + lodash.flatten: ^4.4.0 + lodash.invokemap: ^4.6.0 + lodash.pullall: ^4.2.0 + lodash.uniqby: ^4.7.0 opener: ^1.5.2 - sirv: ^1.0.7 + picocolors: ^1.0.0 + sirv: ^2.0.3 ws: ^7.3.1 bin: webpack-bundle-analyzer: lib/bin/analyzer.js - checksum: e439aea4e88e18bfdc16eb69782c1bb17b2e581905a5cfa8d34058dc6677f6e202f896189268e58b49fa14ae12f5ef4c25cdca9f98f3de7e6699ac62def2f0af + checksum: 7e891c28d5a903242893e55ecc714fa01d7ad6bedade143235c07091b235915349812fa048968462781d59187507962f38b6c61ed7d25fb836ba0ac0ee919a39 languageName: node linkType: hard @@ -11449,6 +11458,38 @@ __metadata: languageName: node linkType: hard +"webpack-cli@npm:^5.1.4": + version: 5.1.4 + resolution: "webpack-cli@npm:5.1.4" + dependencies: + "@discoveryjs/json-ext": ^0.5.0 + "@webpack-cli/configtest": ^2.1.1 + "@webpack-cli/info": ^2.0.2 + "@webpack-cli/serve": ^2.0.5 + colorette: ^2.0.14 + commander: ^10.0.1 + cross-spawn: ^7.0.3 + envinfo: ^7.7.3 + fastest-levenshtein: ^1.0.12 + import-local: ^3.0.2 + interpret: ^3.1.1 + rechoir: ^0.8.0 + webpack-merge: ^5.7.3 + peerDependencies: + webpack: 5.x.x + peerDependenciesMeta: + "@webpack-cli/generators": + optional: true + webpack-bundle-analyzer: + optional: true + webpack-dev-server: + optional: true + bin: + webpack-cli: bin/cli.js + checksum: 3a4ad0d0342a6815c850ee4633cc2a8a5dae04f918e7847f180bf24ab400803cf8a8943707ffbed03eb20fe6ce647f996f60a2aade87b0b4a9954da3da172ce0 + languageName: node + linkType: hard + "webpack-dev-middleware@npm:^5.3.1": version: 5.3.3 resolution: "webpack-dev-middleware@npm:5.3.3" @@ -11600,9 +11641,9 @@ __metadata: linkType: hard "whatwg-fetch@npm:^3.6.2": - version: 3.6.17 - resolution: "whatwg-fetch@npm:3.6.17" - checksum: 0a8785dc2d1515c17ee9365d3f6438cf8fd281567426652fc6c55fc99e58cc6287ae5d1add5b8b1dd665f149e38d3de4ebe3812fd7170438ba0681d03b88b4dd + version: 3.6.19 + resolution: "whatwg-fetch@npm:3.6.19" + checksum: 2896bc9ca867ea514392c73e2a272f65d5c4916248fe0837a9df5b1b92f247047bc76cf7c29c28a01ac6c5fb4314021d2718958c8a08292a96d56f72b2f56806 languageName: node linkType: hard @@ -11653,7 +11694,7 @@ __metadata: languageName: node linkType: hard -"which-typed-array@npm:^1.1.10, which-typed-array@npm:^1.1.11": +"which-typed-array@npm:^1.1.11": version: 1.1.11 resolution: "which-typed-array@npm:1.1.11" dependencies: @@ -11713,19 +11754,10 @@ __metadata: languageName: node linkType: hard -"window-size@npm:^0.1.4": - version: 0.1.4 - resolution: "window-size@npm:0.1.4" - bin: - window-size: cli.js - checksum: 409accca0b1373c69897400e3cc6a56a2acc8a6ba9009f0cd8e4adda4ebf308e50425d3bd375c0c08efb803c8f0b09d84d7266faa05422b3fadfe6ee422d0aef - languageName: node - linkType: hard - "word-wrap@npm:~1.2.3": - version: 1.2.4 - resolution: "word-wrap@npm:1.2.4" - checksum: 8f1f2e0a397c0e074ca225ba9f67baa23f99293bc064e31355d426ae91b8b3f6b5f6c1fc9ae5e9141178bb362d563f55e62fd8d5c31f2a77e3ade56cb3e35bd1 + version: 1.2.5 + resolution: "word-wrap@npm:1.2.5" + checksum: f93ba3586fc181f94afdaff3a6fef27920b4b6d9eaefed0f428f8e07adea2a7f54a5f2830ce59406c8416f033f86902b91eb824072354645eea687dff3691ccb languageName: node linkType: hard @@ -11740,16 +11772,6 @@ __metadata: languageName: node linkType: hard -"wrap-ansi@npm:^2.0.0": - version: 2.1.0 - resolution: "wrap-ansi@npm:2.1.0" - dependencies: - string-width: ^1.0.1 - strip-ansi: ^3.0.1 - checksum: 2dacd4b3636f7a53ee13d4d0fe7fa2ed9ad81e9967e17231924ea88a286ec4619a78288de8d41881ee483f4449ab2c0287cde8154ba1bd0126c10271101b2ee3 - languageName: node - linkType: hard - "wrap-ansi@npm:^3.0.1": version: 3.0.1 resolution: "wrap-ansi@npm:3.0.1" @@ -11820,8 +11842,8 @@ __metadata: linkType: hard "ws@npm:^8.13.0": - version: 8.13.0 - resolution: "ws@npm:8.13.0" + version: 8.14.1 + resolution: "ws@npm:8.14.1" peerDependencies: bufferutil: ^4.0.1 utf-8-validate: ">=5.0.2" @@ -11830,7 +11852,7 @@ __metadata: optional: true utf-8-validate: optional: true - checksum: 53e991bbf928faf5dc6efac9b8eb9ab6497c69feeb94f963d648b7a3530a720b19ec2e0ec037344257e05a4f35bd9ad04d9de6f289615ffb133282031b18c61c + checksum: 9e310be2b0ff69e1f87d8c6d093ecd17a1ed4c37f281d17c35e8c30e2bd116401775b3d503249651374e6e0e1e9905db62fff096b694371c77561aee06bc3466 languageName: node linkType: hard @@ -11881,13 +11903,6 @@ __metadata: languageName: node linkType: hard -"y18n@npm:^3.2.0": - version: 3.2.2 - resolution: "y18n@npm:3.2.2" - checksum: 6154fd7544f8bbf5b18cdf77692ed88d389be49c87238ecb4e0d6a5276446cd2a5c29cc4bdbdddfc7e4e498b08df9d7e38df4a1453cf75eecfead392246ea74a - languageName: node - linkType: hard - "y18n@npm:^4.0.0": version: 4.0.3 resolution: "y18n@npm:4.0.3" @@ -11991,21 +12006,6 @@ __metadata: languageName: node linkType: hard -"yargs@npm:^3.30.0": - version: 3.32.0 - resolution: "yargs@npm:3.32.0" - dependencies: - camelcase: ^2.0.1 - cliui: ^3.0.3 - decamelize: ^1.1.1 - os-locale: ^1.4.0 - string-width: ^1.0.1 - window-size: ^0.1.4 - y18n: ^3.2.0 - checksum: 3e0f7fc1bc2052bcaaa7354cbd33d05a86fc0f236432d107ecd088989fbd175174c562d17e762727acbf25d04e8520d43625f7581b2a6ce55ce10034e80675fc - languageName: node - linkType: hard - "yauzl@npm:^2.10.0": version: 2.10.0 resolution: "yauzl@npm:2.10.0"