Ejemplo n.º 1
0
        public void Init()
        {
            if (!Debugger.IsAttached || EDDConfig.Options.TraceLog)
            {
                TraceLog.LogFileWriterException += ex =>
                {
                    LogLineHighlight($"Log Writer Exception: {ex}");
                };
            }

            backgroundWorker = new Thread(BackgroundWorkerThread);
            backgroundWorker.IsBackground = true;
            backgroundWorker.Name         = "Background Worker Thread";
            backgroundWorker.Start();

            galacticMapping = new GalacticMapping();

            EdsmSync = new EDSMSync(this);

            EdsmLogFetcher = new EDSMLogFetcher(EDCommander.CurrentCmdrID, LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EliteDangerous.EDJournalClass(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;

            history.CommanderId = EDCommander.CurrentCmdrID;
        }
Ejemplo n.º 2
0
        public void Init()      // ED Discovery calls this during its init
        {
            if (!Debugger.IsAttached || EDDOptions.Instance.TraceLog)
            {
                TraceLog.LogFileWriterException += ex =>
                {
                    LogLineHighlight($"Log Writer Exception: {ex}");
                };
            }

            backgroundWorker = new Thread(BackgroundWorkerThread);
            backgroundWorker.IsBackground = true;
            backgroundWorker.Name         = "Background Worker Thread";
            backgroundWorker.Start();

            galacticMapping = new GalacticMapping();

            EdsmSync = new EDSMSync(Logger);

            EdsmLogFetcher = new EDSMLogFetcher(LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EDJournalClass(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;
        }
Ejemplo n.º 3
0
        public void Init()      // ED Discovery calls this during its init
        {
            if (!Debugger.IsAttached || EDDOptions.Instance.TraceLog)
            {
                TraceLog.LogFileWriterException += ex =>
                {
                    LogLineHighlight($"Log Writer Exception: {ex}");
                };
            }

            Icons.IconSet.ResetIcons();     // start with a clean slate loaded up from default icons

            string path = EDDOptions.Instance.IconsPath ?? (EDDOptions.Instance.AppDataDirectory + "\\Icons\\*.zip");

            Icons.IconSet.LoadIconPack(path, EDDOptions.Instance.AppDataDirectory, AppDomain.CurrentDomain.BaseDirectory);

            backgroundWorker = new Thread(BackgroundWorkerThread);
            backgroundWorker.IsBackground = true;
            backgroundWorker.Name         = "Background Worker Thread";
            backgroundWorker.Start();

            galacticMapping = new GalacticMapping();

            EdsmLogFetcher = new EDSMLogFetcher(LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EDJournalClass(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;
            journalmonitor.OnNewUIEvent      += NewUIEvent;
        }
Ejemplo n.º 4
0
        public static ISystem FindSystem(List <VisitedSystemsClass> visitedSystems, GalacticMapping glist, string name)         // in system or name
        {
            EDDiscovery2.DB.ISystem ds1 = SystemClass.GetSystem(name);

            if (ds1 == null)
            {
                VisitedSystemsClass vs = VisitedSystemsClass.FindByName(visitedSystems, name);

                if (vs != null && vs.HasTravelCoordinates)
                {
                    ds1 = vs.curSystem;
                }
                else
                {
                    GalacticMapObject gmo = glist.Find(name, true, true);

                    if (gmo != null && gmo.points.Count > 0)
                    {
                        return(new SystemClass(gmo.name, gmo.points[0].X, gmo.points[0].Y, gmo.points[0].Z));        // fudge it into a system
                    }
                }
            }

            return(ds1);
        }
Ejemplo n.º 5
0
        public void Init()                           // ED Discovery calls this during its init
        {
            TraceLog.LogFileWriterException += ex => // now we can attach the log writing highter into it
            {
                LogLineHighlight($"Log Writer Exception: {ex}");
            };

            galacticMapping = new GalacticMapping();

            EdsmLogFetcher = new EDSMLogFetcher(LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EDJournalClass(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;
            journalmonitor.OnNewUIEvent      += NewUIEvent;
        }
Ejemplo n.º 6
0
        public void Init()                           // ED Discovery calls this during its init
        {
            TraceLog.LogFileWriterException += ex => // now we can attach the log writing highter into it
            {
                LogLineHighlight($"Log Writer Exception: {ex}");
            };

            galacticMapping = new GalacticMapping();

            EdsmLogFetcher = new EDSMLogFetcher(LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EDJournalUIScanner(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;
            journalmonitor.OnNewUIEvent      += NewUIEvent;

            FrontierCAPI = new CAPI.CompanionAPI(EDDOptions.Instance.CAPIDirectory(), CAPI.CapiClientIdentity.id, EDDApplicationContext.UserAgent, "eddiscovery");
            DDEServer    = new BaseUtils.DDE.DDEServer();       // will be started in shown
        }
// TBD why two inits - remove PostInit_Shown, call this instead, remove readyforinitialload.

        public void Init()                           // ED Discovery calls this during its init
        {
            TraceLog.LogFileWriterException += ex => // now we can attach the log writing highter into it
            {
                LogLineHighlight($"Log Writer Exception: {ex}");
            };

            backgroundWorker = new Thread(BackgroundWorkerThread);
            backgroundWorker.IsBackground = true;
            backgroundWorker.Name         = "Background Worker Thread";
            backgroundWorker.Start();                                   // TBD later, get rid of readyforInitialLoad, and start this thread at PostInit_Shown

            galacticMapping = new GalacticMapping();

            EdsmLogFetcher = new EDSMLogFetcher(LogLine);
            EdsmLogFetcher.OnDownloadedSystems += () => RefreshHistoryAsync();

            journalmonitor = new EDJournalClass(InvokeAsyncOnUiThread);
            journalmonitor.OnNewJournalEntry += NewEntry;
            journalmonitor.OnNewUIEvent      += NewUIEvent;
        }
        /// ////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Closed += ShaderTest_Closed;

            edsmmapping = new GalacticMapping();
            string text = System.Text.Encoding.UTF8.GetString(Properties.Resources.galacticmapping);

            edsmmapping.ParseJson(text);                            // at this point, gal map data has been uploaded - get it into memory

            eliteRegions = new GalacticMapping();
            text         = System.Text.Encoding.UTF8.GetString(Properties.Resources.EliteGalacticRegions);
            eliteRegions.ParseJson(text);                            // at this point, gal map data has been uploaded - get it into memory

            mapdefaults = new MapSaverTest();
            mapdefaults.ReadFromDisk(@"c:\code\mapdef.txt");

            map = new Map();
            map.Start(glwfc, edsmmapping, eliteRegions);
            //map.LoadState(mapdefaults);

            systemtimer.Start();
        }
Ejemplo n.º 9
0
        public List <IData3DCollection> AddGalMapObjectsToDataset(GalacticMapping galmap, Bitmap target, float widthly, float heightly, Vector3 rotation, bool namethem, Color textc, int gmosel)
        {
            var datasetbks = Data3DCollection <TexturedQuadData> .Create("galobj", Color.White, 1f);

            if (galmap != null && galmap.Loaded)
            {
                long gmotarget = TargetClass.GetTargetGMO();

                foreach (GalacticMapObject gmo in galmap.GalacticMapObjects)
                {
                    bool enabled = (gmosel & (1 << gmo.GalMapType.Index)) != 0;         // if selected
                    if (enabled && gmo.GalMapType.VisibleType.HasValue)
                    {
                        Bitmap touse = GalMapTypeIcons[gmo.GalMapType.VisibleType.Value] as Bitmap; // under our control, so must have it

                        if (touse != null && gmo.Points.Count > 0)                                  // if it has an image its a point object , and has co-ord
                        {
                            Vector3          pd          = gmo.Points[0].Convert();
                            string           tucachename = "GalMapType:" + gmo.GalMapType.TypeName;
                            TexturedQuadData tubasetex   = null;

                            if (_cachedTextures.ContainsKey(tucachename))
                            {
                                tubasetex = _cachedTextures[tucachename];
                            }
                            else
                            {
                                tubasetex = TexturedQuadData.FromBitmap(touse, pd, rotation, widthly, heightly);
                                _cachedTextures[tucachename] = tubasetex;
                            }


                            TexturedQuadData newtexture = TexturedQuadData.FromBaseTexture(tubasetex, pd, rotation, widthly, heightly);
                            newtexture.Tag  = gmo;
                            newtexture.Tag2 = 0;
                            datasetbks.Add(newtexture);

                            if (gmo.ID == gmotarget)
                            {
                                TexturedQuadData ntag = TexturedQuadData.FromBitmap(target, pd, rotation, widthly, heightly, 0, heightly * gmotargetoff);
                                ntag.Tag  = gmo;
                                ntag.Tag2 = 2;
                                datasetbks.Add(ntag);
                            }
                        }
                    }
                }

                if (namethem)
                {
                    bool useaggregate = true;

                    if (useaggregate)
                    {
                        foreach (GalMapType t in GalMapType.GalTypes)
                        {
                            bool enabled = (gmosel & (1 << t.Index)) != 0;         // if selected
                            if (enabled)
                            {
                                Bitmap                  bmp      = null;
                                TexturedQuadData        nbasetex = null;
                                List <TexturedQuadData> ntex     = new List <TexturedQuadData>();

                                string ncachename = "GalMapNames:" + t.TypeName + textc.ToString();
                                if (_cachedBitmaps.ContainsKey(ncachename) && _cachedTextures.ContainsKey(ncachename))
                                {
                                    bmp      = _cachedBitmaps[ncachename];
                                    nbasetex = _cachedTextures[ncachename];
                                    ntex     = nbasetex.Children.ToList();
                                }
                                else
                                {
                                    List <GalacticMapObject> tgmos = galmap.GalacticMapObjects.Where(o => o.GalMapType.TypeName == t.TypeName && o.Points.Count > 0).ToList();

                                    float            maxheight = 32;
                                    List <Rectangle> bounds    = new List <Rectangle>();
                                    List <float>     widths    = new List <float>();

                                    Bitmap stringstarmeasurebitmap = new Bitmap(1, 1);
                                    using (Graphics g = Graphics.FromImage(stringstarmeasurebitmap))
                                    {
                                        foreach (GalacticMapObject gmo in tgmos)
                                        {
                                            SizeF sz = g.MeasureString(gmo.Name, gmostarfont);
                                            if (sz.Height > maxheight)
                                            {
                                                maxheight = sz.Height;
                                            }
                                            widths.Add(sz.Width);
                                        }
                                    }

                                    int textheight = (int)(maxheight + 4);

                                    int x = 0;
                                    int y = 0;

                                    foreach (float twidth in widths)
                                    {
                                        int w = (int)(twidth + 4);

                                        if ((w + x) > 1024)
                                        {
                                            x = 0;
                                            y = y + textheight;

                                            if (((y + textheight) % 1024) < (y % 1024))
                                            {
                                                y = y + ((1024 - y) % 1024);
                                            }
                                        }

                                        bounds.Add(new Rectangle(x, y, w, textheight));
                                        x = x + w;
                                    }

                                    y = y + textheight;

                                    bmp      = new Bitmap(1024, y);
                                    nbasetex = new TexturedQuadData(null, null, bmp);

                                    using (Graphics g = Graphics.FromImage(bmp))
                                    {
                                        for (int i = 0; i < tgmos.Count; i++)
                                        {
                                            GalacticMapObject gmo       = tgmos[i];
                                            string            cachename = gmo.Name + textc.ToString();
                                            Vector3           pd        = gmo.Points[0].Convert();
                                            Rectangle         clip      = bounds[i];
                                            Point             pos       = clip.Location;
                                            g.SetClip(clip);
                                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
                                            using (Brush br = new SolidBrush(textc))
                                                g.DrawString(gmo.Name, gmostarfont, br, pos);
                                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;

                                            TexturedQuadData tex = TexturedQuadData.FromBaseTexture(nbasetex, pd, rotation, clip,
                                                                                                    (widthly / 10 * gmo.Name.Length),
                                                                                                    (heightly / 3),
                                                                                                    0, heightly * gmonameoff);
                                            tex.Tag  = gmo;
                                            tex.Tag2 = 1;
                                            _cachedTextures[cachename] = tex;
                                            ntex.Add(tex);
                                        }
                                    }

                                    _cachedBitmaps[ncachename]  = bmp;
                                    _cachedTextures[ncachename] = nbasetex;
                                }

                                foreach (TexturedQuadData tex in ntex)
                                {
                                    datasetbks.Add(tex);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (GalacticMapObject gmo in galmap.GalacticMapObjects)
                        {
                            bool enabled = (gmosel & (1 << gmo.GalMapType.Index)) != 0;         // if selected
                            if (enabled && gmo.Points.Count > 0)
                            {
                                Vector3 pd        = gmo.Points[0].Convert();
                                Bitmap  map       = null;
                                string  cachename = gmo.Name + textc.ToString();

                                if (_cachedBitmaps.ContainsKey(cachename))      // cache them, they take a long time to compute..
                                {
                                    map = _cachedBitmaps[cachename];
                                }
                                else
                                {
                                    map = DrawString(gmo.Name, textc, gmostarfont);
                                    _cachedBitmaps.Add(cachename, map);
                                }

                                TexturedQuadData ntext = TexturedQuadData.FromBitmap(map, pd, rotation,
                                                                                     (widthly / 10 * gmo.Name.Length),
                                                                                     (heightly / 3),
                                                                                     0, heightly * gmonameoff);
                                ntext.Tag  = gmo;
                                ntext.Tag2 = 1;
                                datasetbks.Add(ntext);
                            }
                        }
                    }
                }
            }

            _datasets.Add(datasetbks);

            return(_datasets);
        }
Ejemplo n.º 10
0
        public List <IData3DCollection> AddGalMapRegionsToDataset(GalacticMapping galmap, bool colourregions, int gmosel)
        {
            var polydataset    = new PolygonCollection("regpolys", Color.White, 1f, OpenTK.Graphics.OpenGL.PrimitiveType.Triangles);   // ORDER AND NUMBER v.Important
            var outlinedataset = new PolygonCollection("reglines", Color.White, 1f, OpenTK.Graphics.OpenGL.PrimitiveType.LineLoop);    // DrawStars picks them out in a particular order
            var datasetbks     = Data3DCollection <TexturedQuadData> .Create("regtext", Color.White, 1f);

            if (galmap != null && galmap.Loaded)
            {
                long gmotarget = TargetClass.GetTargetGMO();

                int cindex = 0;
                foreach (GalacticMapObject gmo in galmap.GalacticMapObjects)
                {
                    bool enabled = (gmosel & (1 << gmo.GalMapType.Index)) != 0;         // if selected

                    if (enabled && gmo.GalMapType.Group == GalMapType.GroupType.Regions)
                    {
                        string name = gmo.Name;

                        Color[] array = new Color[] { Color.Red, Color.Green, Color.Blue,
                                                      Color.Brown, Color.Crimson, Color.Coral,
                                                      Color.Aqua, Color.Yellow, Color.Violet,
                                                      Color.Sienna, Color.Silver, Color.Salmon,
                                                      Color.Pink, Color.AntiqueWhite, Color.Beige,
                                                      Color.DarkCyan, Color.DarkGray, Color.ForestGreen, Color.LightSkyBlue,
                                                      Color.Lime, Color.Maroon, Color.Olive, Color.SteelBlue };
                        Color c = array[cindex++ % array.Length];

                        List <Vector2> polygonxz = new List <Vector2>();                              // needs it in x/z and in vector2's
                        foreach (var pd in gmo.Points)
                        {
                            polygonxz.Add(new Vector2((float)pd.X, (float)pd.Z));                   // can be concave and wound the wrong way..
                        }
                        Vector2 size, avg;
                        Vector2 centre = PolygonTriangulator.Centre(polygonxz, out size, out avg);        // default geographic centre (min x/z + max x/z/2) used in case poly triangulate fails (unlikely)

                        List <List <Vector2> > polys = PolygonTriangulator.Triangulate(polygonxz, false); // cut into convex polygons first - because we want the biggest possible area for naming purposes
                        //Console.WriteLine("Region {0} decomposed to {1} ", name, polys.Count);

                        Vector2 bestpos  = centre;
                        Vector2 bestsize = new Vector2(250, 250 / 5);

                        if (polys.Count > 0)                                                     // just in case..
                        {
                            centre = PolygonTriangulator.Centroids(polys);                       // weighted mean of the centroids
                            //Bitmap map3 = DrawString(String.Format("O{0}", cindex - 1), Color.White, gmostarfont); TexturedQuadData ntext3 = TexturedQuadData.FromBitmap(map3, new PointData(centre.X, 0, centre.Y), TexturedQuadData.NoRotation, 2000, 500); datasetbks.Add(ntext3);

                            float mindist = float.MaxValue;

                            foreach (List <Vector2> points in polys)                         // now for every poly
                            {
                                if (colourregions)
                                {
                                    Color regcol = Color.FromArgb(64, c.R, c.G, c.B);

                                    if (points.Count == 3)                                    // already a triangle..
                                    {
                                        polydataset.Add(new Polygon(points, 1, regcol));
                                        //outlinedataset.Add(new Polygon(points, 1, Color.FromArgb(255, 255, 255, 0))); //DEBUG
                                    }
                                    else
                                    {
                                        List <List <Vector2> > polytri = PolygonTriangulator.Triangulate(points, true);    // cut into triangles not polygons

                                        foreach (List <Vector2> pt in polytri)
                                        {
                                            polydataset.Add(new Polygon(pt, 1, regcol));
                                            // outlinedataset.Add(new Polygon(pt, 1, Color.FromArgb(255, 255, 255, 0))); // DEBUG
                                        }
                                    }
                                }

                                //float area; Vector2 polycentrepos = PolygonTriangulator.Centroid(points,out area); Bitmap map2 = DrawString(String.Format("X") , Color.White, gmostarfont);  TexturedQuadData ntext2 = TexturedQuadData.FromBitmap(map2, new PointData(polycentrepos.X, 0, polycentrepos.Y), TexturedQuadData.NoRotation, 1000, 200); datasetbks.Add(ntext2);

                                PolygonTriangulator.FitInsideConvexPoly(points, centre, new Vector2(3000, 3000 / 5), new Vector2(200, 200),
                                                                        ref mindist, ref bestpos, ref bestsize, bestsize.X / 2);
                            }
                        }

                        Bitmap           map       = DrawString(gmo.Name, Color.White, gmostarfont);
                        PointData        bitmappos = new PointData(bestpos.X, 0, bestpos.Y);
                        TexturedQuadData ntext     = TexturedQuadData.FromBitmap(map, bitmappos, TexturedQuadData.NoRotation,
                                                                                 bestsize.X, bestsize.Y);

                        datasetbks.Add(ntext);

                        outlinedataset.Add(new Polygon(polygonxz, 1, Color.FromArgb(255, 128, 128, 128)));
                    }
                }
            }

            _datasets.Add(polydataset);
            _datasets.Add(outlinedataset);
            _datasets.Add(datasetbks);
            return(_datasets);
        }
Ejemplo n.º 11
0
        public void Start(GLOFC.WinForm.GLWinFormControl glwfc, GalacticMapping edsmmapping, GalacticMapping eliteregions)
        {
            this.glwfc        = glwfc;
            this.edsmmapping  = edsmmapping;
            this.elitemapping = eliteregions;

            hptimer.Start();

            items.Add(new GLMatrixCalcUniformBlock(), "MCUB");     // create a matrix uniform block

            int lyscale = 1;
            int front = -20000 / lyscale, back = front + 90000 / lyscale, left = -45000 / lyscale, right = left + 90000 / lyscale, vsize = 2000 / lyscale;

            if (false)     // debug bounding box
            {
                Vector4[] displaylines = new Vector4[]
                {
                    new Vector4(left, -vsize, front, 1), new Vector4(left, +vsize, front, 1),
                    new Vector4(left, +vsize, front, 1), new Vector4(right, +vsize, front, 1),
                    new Vector4(right, +vsize, front, 1), new Vector4(right, -vsize, front, 1),
                    new Vector4(right, -vsize, front, 1), new Vector4(left, -vsize, front, 1),

                    new Vector4(left, -vsize, back, 1), new Vector4(left, +vsize, back, 1),
                    new Vector4(left, +vsize, back, 1), new Vector4(right, +vsize, back, 1),
                    new Vector4(right, +vsize, back, 1), new Vector4(right, -vsize, back, 1),
                    new Vector4(right, -vsize, back, 1), new Vector4(left, -vsize, back, 1),

                    new Vector4(left, -vsize, front, 1), new Vector4(left, -vsize, back, 1),
                    new Vector4(left, +vsize, front, 1), new Vector4(left, +vsize, back, 1),
                    new Vector4(right, -vsize, front, 1), new Vector4(right, -vsize, back, 1),
                    new Vector4(right, +vsize, front, 1), new Vector4(right, +vsize, back, 1),
                };

                GLRenderState rl = GLRenderState.Lines(1);

                items.Add(new GLShaderPipeline(new GLPLVertexShaderWorldCoord(), new GLPLFragmentShaderFixedColor(Color.Yellow)), "LINEYELLOW");
                rObjects.Add(items.Shader("LINEYELLOW"),
                             GLRenderableItem.CreateVector4(items, PrimitiveType.Lines, rl, displaylines));

                items.Add(new GLColorShaderWorld(), "COS-1L");

                float h = 0;

                int   dist = 1000 / lyscale;
                Color cr   = Color.FromArgb(100, Color.White);
                rObjects.Add(items.Shader("COS-1L"),    // horizontal
                             GLRenderableItem.CreateVector4Color4(items, PrimitiveType.Lines, rl,
                                                                  GLShapeObjectFactory.CreateLines(new Vector3(left, h, front), new Vector3(left, h, back), new Vector3(dist, 0, 0), (back - front) / dist + 1),
                                                                  new OpenTK.Graphics.Color4[] { cr })
                             );

                rObjects.Add(items.Shader("COS-1L"),
                             GLRenderableItem.CreateVector4Color4(items, PrimitiveType.Lines, rl,
                                                                  GLShapeObjectFactory.CreateLines(new Vector3(left, h, front), new Vector3(right, h, front), new Vector3(0, 0, dist), (right - left) / dist + 1),
                                                                  new OpenTK.Graphics.Color4[] { cr })
                             );

                rObjects.Add(new GLOperationClearDepthBuffer());
            }

            int ctrlo = 2048 | 32 | 64;

            ctrlo = -1;

            if ((ctrlo & 1) != 0) // galaxy
            {
                volumetricboundingbox = new Vector4[]
                {
                    new Vector4(left, -vsize, front, 1),
                    new Vector4(left, vsize, front, 1),
                    new Vector4(right, vsize, front, 1),
                    new Vector4(right, -vsize, front, 1),

                    new Vector4(left, -vsize, back, 1),
                    new Vector4(left, vsize, back, 1),
                    new Vector4(right, vsize, back, 1),
                    new Vector4(right, -vsize, back, 1),
                };


                const int gnoisetexbinding = 3;     //tex bindings are attached per shaders so are not global
                const int gdisttexbinding  = 4;
                const int galtexbinding    = 1;

                volumetricblock = new GLVolumetricUniformBlock(volumenticuniformblock);
                items.Add(volumetricblock, "VB");

                int         sc      = 1;
                GLTexture3D noise3d = new GLTexture3D(1024 * sc, 64 * sc, 1024 * sc, OpenTK.Graphics.OpenGL4.SizedInternalFormat.R32f);                           // red channel only
                items.Add(noise3d, "Noise");
                ComputeShaderNoise3D csn = new ComputeShaderNoise3D(noise3d.Width, noise3d.Height, noise3d.Depth, 128 * sc, 16 * sc, 128 * sc, gnoisetexbinding); // must be a multiple of localgroupsize in csn
                csn.StartAction += (A, m) => { noise3d.BindImage(gnoisetexbinding); };
                csn.Run();                                                                                                                                        // compute noise
                csn.Dispose();

                GLTexture1D gaussiantex = new GLTexture1D(1024, OpenTK.Graphics.OpenGL4.SizedInternalFormat.R32f); // red channel only
                items.Add(gaussiantex, "Gaussian");

                // set centre=width, higher widths means more curve, higher std dev compensate.
                // fill the gaussiantex with data
                ComputeShaderGaussian gsn = new ComputeShaderGaussian(gaussiantex.Width, 2.0f, 2.0f, 1.4f, gdisttexbinding);
                gsn.StartAction += (A, m) => { gaussiantex.BindImage(gdisttexbinding); };
                gsn.Run();      // compute noise
                gsn.Dispose();

                GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);

                // load one upside down and horz flipped, because the volumetric co-ords are 0,0,0 bottom left, 1,1,1 top right
                GLTexture2D galtex = new GLTexture2D(Properties.Resources.Galaxy_L180, SizedInternalFormat.Rgba8);
                items.Add(galtex, "galtex");
                galaxyshader = new GalaxyShader(volumenticuniformblock, galtexbinding, gnoisetexbinding, gdisttexbinding);
                items.Add(galaxyshader, "Galaxy-sh");
                // bind the galaxy texture, the 3dnoise, and the gaussian 1-d texture for the shader
                galaxyshader.StartAction += (a, m) => { galtex.Bind(galtexbinding); noise3d.Bind(gnoisetexbinding); gaussiantex.Bind(gdisttexbinding); };      // shader requires these, so bind using shader

                GLRenderState rt = GLRenderState.Tri();
                galaxyrenderable = GLRenderableItem.CreateNullVertex(OpenTK.Graphics.OpenGL4.PrimitiveType.Points, rt);   // no vertexes, all data from bound volumetric uniform, no instances as yet
                rObjects.Add(galaxyshader, "galshader", galaxyrenderable);
            }

            if ((ctrlo & 2) != 0)
            {
                var corr = new GalMapRegions.ManualCorrections[] {          // nerf the centeroid position slightly
                    new GalMapRegions.ManualCorrections("The Galactic Aphelion", y: -2000),
                    new GalMapRegions.ManualCorrections("The Abyss", y: +3000),
                    new GalMapRegions.ManualCorrections("Eurus", y: -3000),
                    new GalMapRegions.ManualCorrections("The Perseus Transit", x: -3000, y: -3000),
                    new GalMapRegions.ManualCorrections("Zephyrus", x: 0, y: 2000),
                };

                edsmgalmapregions = new GalMapRegions();
                edsmgalmapregions.CreateObjects("edsmregions", items, rObjects, edsmmapping, 8000, corr: corr);
            }

            if ((ctrlo & 4) != 0)
            {
                elitemapregions = new GalMapRegions();
                elitemapregions.CreateObjects("eliteregions", items, rObjects, eliteregions, 8000);
                EliteRegionsEnable = false;
            }

            if ((ctrlo & 8) != 0)
            {
                int    gran = 8;
                Bitmap img  = Properties.Resources.Galaxy_L180;
                Bitmap heat = img.Function(img.Width / gran, img.Height / gran, mode: GLOFC.Utils.BitMapHelpers.BitmapFunction.HeatMap);
                heat.Save(@"c:\code\heatmap.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                Random rnd = new Random(23);

                GLBuffer buf = items.NewBuffer(16 * 350000, false); // since RND is fixed, should get the same number every time.
                buf.StartWrite(0);                                  // get a ptr to the whole schebang

                int xcw = (right - left) / heat.Width;
                int zch = (back - front) / heat.Height;

                int points = 0;

                for (int x = 0; x < heat.Width; x++)
                {
                    for (int z = 0; z < heat.Height; z++)
                    {
                        int i = heat.GetPixel(x, z).R;
                        if (i > 32)
                        {
                            int gx = left + x * xcw;
                            int gz = front + z * zch;

                            float  dx = (float)Math.Abs(gx) / 45000;
                            float  dz = (float)Math.Abs(25889 - gz) / 45000;
                            double d  = Math.Sqrt(dx * dx + dz * dz); // 0 - 0.1412
                            d = 1 - d;                                // 1 = centre, 0 = unit circle
                            d = d * 2 - 1;                            // -1 to +1
                            double dist = ObjectExtensionsNumbersBool.GaussianDist(d, 1, 1.4);

                            int c = Math.Min(Math.Max(i * i * i / 120000, 1), 40);
                            //int c = Math.Min(Math.Max(i * i * i / 24000000, 1), 40);

                            dist *= 2000 / lyscale;
                            //System.Diagnostics.Debug.WriteLine("{0} {1} : dist {2} c {3}", x, z, dist, c);
                            //System.Diagnostics.Debug.Write(c);
                            GLPointsFactory.RandomStars4(buf, c, gx, gx + xcw, gz, gz + zch, (int)dist, (int)-dist, rnd, w: 0.8f);
                            points += c;
                            System.Diagnostics.Debug.Assert(points < buf.Length / 16);
                        }
                    }
                    //System.Diagnostics.Debug.WriteLine(".");
                }

                buf.StopReadWrite();

                stardots = new GalaxyStarDots();
                items.Add(stardots);
                GLRenderState rc = GLRenderState.Points(1);
                rc.DepthTest = false; // note, if this is true, there is a wierd different between left and right in view.. not sure why
                rObjects.Add(stardots, "stardots", GLRenderableItem.CreateVector4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Points, rc, buf, points));
                System.Diagnostics.Debug.WriteLine("Stars " + points);
            }

            rObjects.Add(new GLOperationClearDepthBuffer()); // clear depth buffer and now use full depth testing on the rest

            if ((ctrlo & 16) != 0)
            {
                items.Add(new GLTexture2D(Properties.Resources.StarFlare2, SizedInternalFormat.Rgba8), "lensflare");
                items.Add(new GLPointSpriteShader(items.Tex("lensflare"), 64, 40), "PS");
                var p = GLPointsFactory.RandomStars4(1000, 0, 25899 / lyscale, 10000 / lyscale, 1000 / lyscale, -1000 / lyscale);

                GLRenderState rps = GLRenderState.PointSprites();

                rObjects.Add(items.Shader("PS"), "starsprites", GLRenderableItem.CreateVector4Color4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Points, rps, p, new Color4[] { Color.White }));
            }

            if ((ctrlo & 32) != 0)
            {
                gridvertshader = new DynamicGridVertexShader(Color.Cyan);
                //items.Add(gridvertshader, "PLGRIDVertShader");
                var frag = new GLPLFragmentShaderVSColor();
                //items.Add(frag, "PLGRIDFragShader");

                GLRenderState rl = GLRenderState.Lines(1);

                items.Add(new GLShaderPipeline(gridvertshader, frag), "DYNGRID");

                gridrenderable = GLRenderableItem.CreateNullVertex(OpenTK.Graphics.OpenGL4.PrimitiveType.Lines, rl, drawcount: 2);

                rObjects.Add(items.Shader("DYNGRID"), "DYNGRIDRENDER", gridrenderable);
            }

            if ((ctrlo & 64) != 0)
            {
                gridbitmapvertshader = new DynamicGridCoordVertexShader();
                var frag = new GLPLFragmentShaderTexture2DIndexed(0);

                GLRenderState rl = GLRenderState.Tri(cullface: false);

                GLTexture2DArray gridtexcoords = new GLTexture2DArray();
                items.Add(gridtexcoords, "PLGridBitmapTextures");

                GLShaderPipeline sp = new GLShaderPipeline(gridbitmapvertshader, frag);
                items.Add(sp, "DYNGRIDBitmap");

                rObjects.Add(items.Shader("DYNGRIDBitmap"), "DYNGRIDBitmapRENDER", GLRenderableItem.CreateNullVertex(OpenTK.Graphics.OpenGL4.PrimitiveType.TriangleStrip, rl, drawcount: 4, instancecount: 9));
            }

            GLStorageBlock findresults = items.NewStorageBlock(findblock);

            float sunsize = .5f;

            if ((ctrlo & 128) != 0)
            {
                Random rnd = new Random(52);
                List <HistoryEntry> pos    = new List <HistoryEntry>();
                DateTime            start  = new DateTime(2020, 1, 1);
                Color[]             colors = new Color[] { Color.Red, Color.Green, Color.Blue, Color.White, Color.Black, Color.Purple, Color.Yellow };
                for (int j = 0; j <= 200; j++)
                {
                    Color  jc   = colors[j % colors.Length];
                    int    i    = j * 10;
                    string name = "Kyli Flyuae AA-B h" + j.ToString();
                    if (i < 30000)
                    {
                        pos.Add(new HistoryEntry(start, name, i + rnd.Next(50), rnd.Next(50), i, jc));
                    }
                    else if (i < 60000)
                    {
                        pos.Add(new HistoryEntry(start, name, 60000 - i + rnd.Next(50), rnd.Next(50), i, jc));
                    }
                    else if (i < 90000)
                    {
                        pos.Add(new HistoryEntry(start, name, -(i - 60000) + rnd.Next(50), rnd.Next(50), 120000 - i, jc));
                    }
                    else
                    {
                        pos.Add(new HistoryEntry(start, name, -30000 + (i - 90000) + rnd.Next(50), rnd.Next(50), -i + 120000, jc));
                    }

                    start = start.AddDays(1);
                }

                // tested to 50k stars

                travelpath = new TravelPath(1000);
                travelpath.Create(items, rObjects, pos, sunsize, sunsize, findresults, true);
                travelpath.SetSystem(0);
            }

            if ((ctrlo & 256) != 0)
            {
                galmapobjects = new GalMapObjects();
                galmapobjects.CreateObjects(items, rObjects, edsmmapping, findresults, true);
            }

            if ((ctrlo & 512) != 0)
            {
                //  galaxystars = new GalaxyStars(items, rObjects, sunsize, findresults);
            }

            if ((ctrlo & 1024) != 0)
            {
                rightclickmenu = new GLContextMenu("RightClickMenu",
                                                   new GLMenuItem("RCMInfo", "Information")
                {
                    MouseClick = (s, e) => {
                        var nl = NameLocationDescription(rightclickmenu.Tag);
                        System.Diagnostics.Debug.WriteLine($"Info {nl.Item1} {nl.Item2}");
                        // logical name is important as menu uses it to close down
                        GLMessageBox msg = new GLMessageBox("InfoBoxForm-1", displaycontrol, e.WindowLocation,
                                                            nl.Item3, $"{nl.Item1} @ {nl.Item2.X:#.#},{nl.Item2.Y:#.#},{nl.Item2.Z:#.#}", GLMessageBox.MessageBoxButtons.OK, null,
                                                            Color.FromArgb(220, 60, 60, 70), Color.DarkOrange);
                    }
                },
                                                   new GLMenuItem("RCMZoomIn", "Goto Zoom In")
                {
                    MouseClick = (s1, e1) => {
                        var nl = NameLocationDescription(rightclickmenu.Tag);
                        gl3dcontroller.SlewToPositionZoom(nl.Item2, 100, -1);
                    }
                },
                                                   new GLMenuItem("RCMGoto", "Goto Position")
                {
                    MouseClick = (s1, e1) => {
                        var nl = NameLocationDescription(rightclickmenu.Tag);
                        System.Diagnostics.Debug.WriteLine($"Goto {nl.Item1} {nl.Item2}");
                        gl3dcontroller.SlewToPosition(nl.Item2, -1);
                    }
                },
                                                   new GLMenuItem("RCMLookAt", "Look At")
                {
                    MouseClick = (s1, e1) => {
                        var nl = NameLocationDescription(rightclickmenu.Tag);
                        gl3dcontroller.PanTo(nl.Item2, -1);
                    }
                }
                                                   );
            }

            if ((ctrlo & 2048) != 0)
            {
                bookmarks = new Bookmarks();
                var syslist = new List <SystemClass> {
                    new SystemClass("bk1", 1000, 0, 0), new SystemClass("bk1", 1000, 0, 2000),
                };
                bookmarks.Create(items, rObjects, syslist, 10, findresults, false);
            }
            // Matrix calc holding transform info

            matrixcalc = new GLMatrixCalc();
            matrixcalc.PerspectiveNearZDistance = 1f;
            matrixcalc.PerspectiveFarZDistance  = 120000f / lyscale;
            matrixcalc.InPerspectiveMode        = true;
            matrixcalc.ResizeViewPort(this, glwfc.Size);          // must establish size before starting

            // menu system

            displaycontrol           = new GLControlDisplay(items, glwfc, matrixcalc, true, 0.00001f, 0.00001f); // hook form to the window - its the master
            displaycontrol.Font      = new Font("Arial", 10f);
            displaycontrol.Focusable = true;                                                                     // we want to be able to focus and receive key presses.
            displaycontrol.SetFocus();

            // 3d controller

            gl3dcontroller = new Controller3D();
            gl3dcontroller.PosCamera.ZoomMax     = 600; // gives 5ly
            gl3dcontroller.ZoomDistance          = 3000F / lyscale;
            gl3dcontroller.PosCamera.ZoomMin     = 0.1f;
            gl3dcontroller.PosCamera.ZoomScaling = 1.1f;
            gl3dcontroller.YHoldMovement         = true;
            gl3dcontroller.PaintObjects          = Controller3DDraw;
            gl3dcontroller.KeyboardTravelSpeed   = (ms, eyedist) =>
            {
                double eyedistr = Math.Pow(eyedist, 1.0);
                float  v        = (float)Math.Max(eyedistr / 1200, 0);
                //System.Diagnostics.Debug.WriteLine("Speed " + eyedistr + " "+ v);
                return((float)ms * v);
            };

            // hook gl3dcontroller to display control - its the slave. Do not register mouse UI, we will deal with that.
            gl3dcontroller.Start(matrixcalc, displaycontrol, new Vector3(0, 0, 0), new Vector3(140.75f, 0, 0), 0.5F, false, true);
            //gl3dcontroller.Start(matrixcalc, displaycontrol, new Vector3(0, 0, 0), new Vector3(90F, 0, 0), 0.5F, false, true);

            if (displaycontrol != null)
            {
                displaycontrol.Paint += (o, ts) =>        // subscribing after start means we paint over the scene, letting transparency work
                {
                    // MCUB set up by Controller3DDraw which did the work first
                    galaxymenu.UpdateCoords(gl3dcontroller.MatrixCalc, gl3dcontroller.PosCamera.ZoomFactor);
                    // debug this galaxymenu.DebugStatusText(gl3dcontroller.PosCamera.StringPositionCamera);  gl3dcontroller.PosCamera.SetPositionCamera(gl3dcontroller.PosCamera.StringPositionCamera);
                    displaycontrol.Animate(glwfc.ElapsedTimems);
                    displaycontrol.Render(glwfc.RenderState, ts);
                };
            }

            displaycontrol.MouseClick += MouseClickOnMap;
            displaycontrol.MouseUp    += MouseUpOnMap;
            displaycontrol.MouseDown  += MouseDownOnMap;
            displaycontrol.MouseMove  += MouseMoveOnMap;
            displaycontrol.MouseWheel += MouseWheelOnMap;

            galaxymenu = new MapMenu(this);

            // Autocomplete text box at top for searching

            GLTextBoxAutoComplete tbac = ((GLTextBoxAutoComplete)displaycontrol[MapMenu.EntryTextName]);

            tbac.PerformAutoCompleteInUIThread = (s, a, set) =>
            {
                System.Diagnostics.Debug.Assert(Application.MessageLoop);       // must be in UI thread
                var           glist = edsmmapping.galacticMapObjects.Where(x => s.Length < 3 ? x.name.StartsWith(s, StringComparison.InvariantCultureIgnoreCase) : x.name.Contains(s, StringComparison.InvariantCultureIgnoreCase)).Select(x => x).ToList();
                List <string> list  = glist.Select(x => x.name).ToList();
                list.AddRange(travelpath.CurrentList.Where(x => s.Length < 3 ? x.System.Name.StartsWith(s, StringComparison.InvariantCultureIgnoreCase) : x.System.Name.Contains(s, StringComparison.InvariantCultureIgnoreCase)).Select(x => x.System.Name));
                foreach (var x in list)
                {
                    set.Add(x);
                }
            };

            tbac.SelectedEntry = (a) =>                                   // in UI thread
            {
                System.Diagnostics.Debug.Assert(Application.MessageLoop); // must be in UI thread
                System.Diagnostics.Debug.WriteLine("Selected " + tbac.Text);
                var gmo = edsmmapping.galacticMapObjects.Find(x => x.name.Equals(tbac.Text, StringComparison.InvariantCultureIgnoreCase));
                if (gmo != null)
                {
                    System.Diagnostics.Debug.WriteLine("Move to gmo " + gmo.points[0]);
                    gl3dcontroller.SlewToPosition(new Vector3((float)gmo.points[0].X, (float)gmo.points[0].Y, (float)gmo.points[0].Z), -1);
                }
                else
                {
                    var he = travelpath.CurrentList.Find(x => x.System.Name.Equals(tbac.Text, StringComparison.InvariantCultureIgnoreCase));
                    if (he != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Move to sys " + he.System.Name);
                        gl3dcontroller.SlewToPosition(new Vector3((float)he.System.X, (float)he.System.Y, (float)he.System.Z), -1);
                    }
                    else
                    {
                        tbac.InErrorCondition = true;
                    }
                }
            };

            if (galaxystars != null)
            {
                galaxystars.Start();
            }

            if (false)         // enable for debug buffer
            {
                debugbuffer = new GLStorageBlock(31, true);
                debugbuffer.AllocateBytes(32000, OpenTK.Graphics.OpenGL4.BufferUsageHint.DynamicCopy);       // set size of vec buffer
            }

            if (false)          // enable for debug
            {
                items.Add(new GLColorShaderObjectTranslation(), "COSOT");
                GLRenderState rc = GLRenderState.Tri(cullface: false);
                rc.DepthTest = false;

                Vector3[] markers = new Vector3[] { new Vector3(0, 0, 0), new Vector3(0, -5, 0), new Vector3(0, -5 - 3.125f / 2f, 0) };

                for (int i = 0; i < markers.Length; i++)
                {
                    rObjects.Add(items.Shader("COSOT"), "marker" + i,
                                 GLRenderableItem.CreateVector4Color4(items, PrimitiveType.Triangles, rc,
                                                                      GLCubeObjectFactory.CreateSolidCubeFromTriangles(0.5f),
                                                                      new Color4[] { Color4.Red, Color4.Green, Color4.Blue, Color4.White, Color4.Cyan, Color4.Orange },
                                                                      new GLRenderDataTranslationRotation(markers[i])
                                                                      ));
                }
            }
        }
Ejemplo n.º 12
0
        public void CreateObjects(GLItemsList items, GLRenderProgramSortedList rObjects, GalacticMapping galmap, GLStorageBlock findbufferresults, bool depthtest)
        {
            this.galmap = galmap;

            // first gets the images and make a 2d array texture for them

            Bitmap[] images = galmap.RenderableMapTypes.Select(x => x.Image as Bitmap).ToArray();
            // 256 is defined normal size
            var        objtex   = new GLTexture2DArray(images, bmpmipmaplevels: 1, wantedmipmaplevels: 3, texturesize: new Size(256, 256), internalformat: OpenTK.Graphics.OpenGL4.SizedInternalFormat.Rgba8, alignment: ContentAlignment.BottomCenter);
            IGLTexture texarray = items.Add(objtex, "GalObjTex");

            // now build the shaders

            const int texbindingpoint = 1;
            var       vert            = new GLPLVertexScaleLookat(rotatetoviewer: dorotate, rotateelevation: doelevation, // a look at vertex shader
                                                                  autoscale: 500, autoscalemin: 1f, autoscalemax: 20f);   // below 500, 1f, above 500, scale up to 20x
            var tcs = new GLPLTesselationControl(40f);

            tes = new GLPLTesselationEvaluateSinewave(1f, 2f);                  // this uses the world position from the vertex scaler to position the image, w controls image + animation (b16)
            var frag = new GLPLFragmentShaderTexture2DDiscard(texbindingpoint); // binding - takes image pos from tes. imagepos < 0 means discard

            objectshader = new GLShaderPipeline(vert, tcs, tes, null, frag);
            items.Add(objectshader);

            objectshader.StartAction += (s, m) =>
            {
                texarray.Bind(texbindingpoint);   // bind tex array to, matching above
            };

            // now the RenderControl for the objects

            GLRenderState rt = GLRenderState.Patches(4);

            rt.DepthTest = depthtest;

            // create a quad and all entries of the renderable map objects, zero at this point, with a zero instance count. UpdateEnables will fill it in later
            // but we need to give it the maximum buffer length at this point

            const float objsize = 10.0f;        // size of object on screen

            ridisplay = GLRenderableItem.CreateVector4Vector4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Patches, rt,
                                                              GLShapeObjectFactory.CreateQuadTriStrip(objsize, objsize), // quad2 4 vertexts
                                                              new Vector4[galmap.RenderableMapObjects.Length],           // world positions
                                                              ic: 0, seconddivisor: 1);

            modelworldbuffer = items.LastBuffer();
            int modelpos = modelworldbuffer.Positions[0];

            worldpos = modelworldbuffer.Positions[1];

            rObjects.Add(objectshader, "galmapobj", ridisplay);

            // add a find shader to look them up

            var geofind = new GLPLGeoShaderFindTriangles(findbufferresults, 16);

            findshader = items.NewShaderPipeline(null, vert, tcs, tes, geofind, null, null, null);


            // hook to modelworldbuffer, at modelpos and worldpos.  UpdateEnables will fill in instance count
            rifind = GLRenderableItem.CreateVector4Vector4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Patches, GLRenderState.Patches(4), modelworldbuffer, modelpos, ridisplay.DrawCount,
                                                           modelworldbuffer, worldpos, null, ic: 0, seconddivisor: 1);

            GLStatics.Check();

            // Text renderer for the labels

            textrenderer = new GLBitmaps("bm-galmapobjects", rObjects, new Size(128, 40), depthtest: depthtest, cullface: false, textureformat: OpenTK.Graphics.OpenGL4.SizedInternalFormat.Rgba8);
            items.Add(textrenderer);

            // now make the text up for all the objects above

            using (Font fnt = new Font("Arial", 8.5F))
            {
                using (StringFormat fmt = new StringFormat())
                {
                    fmt.Alignment = StringAlignment.Center;

                    var renderablegalmapobjects = galmap.RenderableMapObjects; // list of enabled entries

                    List <Vector3> posset = new List <Vector3>();

                    float offscale = objsize * (0.5f + (float)textrenderer.BitmapSize.Height / (float)textrenderer.BitmapSize.Width / 2);       // this is the nominal centre of the text bitmap, offset in Y to the object

                    for (int i = 0; i < renderablegalmapobjects.Length; i++)
                    {
                        var   o      = renderablegalmapobjects[i];
                        float offset = -offscale;

                        for (int j = 0; j < i; j++)     // look up previous ones and see if we labeled it before
                        {
                            var d1   = new Vector3(o.points[0].X, o.points[0].Y + offset, o.points[0].Z);
                            var d2   = posset[j];   // where it was placed.
                            var diff = d1 - d2;

                            if (diff.Length < offscale) // close
                            {
                                if (offset > 0)         // if offset is positive, flip below and increase again
                                {
                                    offset = -offset - offscale;
                                }
                                else
                                {
                                    offset *= -1;       // flip over top
                                }
                                // System.Diagnostics.Debug.WriteLine($"close {renderablegalmapobjects[i].name} {d1} to {renderablegalmapobjects[j].name} {d2} {diff} select {offset}");
                            }
                        }

                        Vector3 pos = new Vector3(o.points[0].X, o.points[0].Y + offset, o.points[0].Z);
                        posset.Add(pos);
                        //System.Diagnostics.Debug.WriteLine($"{renderablegalmapobjects[i].name} at {pos} {offset}");

                        textrenderer.Add(o.id, o.name, fnt,
                                         Color.White, Color.FromArgb(0, 255, 0, 255),
                                         pos,
                                         new Vector3(objsize, 0, 0), new Vector3(0, 0, 0), textformat: fmt, rotatetoviewer: dorotate, rotateelevation: doelevation,
                                         alphafadescalar: -100, alphafadepos: 500); // fade in, alpha = 0 at >500, 1 at 400
                    }
                }
            }

            UpdateEnables();      // fill in worldpos's and update instance count, taking into
        }
        public void CreateObjects(string name, GLItemsList items, GLRenderProgramSortedList rObjects, GalacticMapping galmap, float sizeofname = 5000, ManualCorrections[] corr = null)
        {
            List <Vector4> vertexcolourregions      = new List <Vector4>();
            List <Vector4> vertexregionsoutlines    = new List <Vector4>();
            List <ushort>  vertexregionoutlineindex = new List <ushort>();

            Size bitmapsize = new Size(250, 22);

            textrenderer = new GLBitmaps(name + "-bitmaps", rObjects, bitmapsize, depthtest: false, yfixed: true);
            items.Add(textrenderer);

            StringFormat fmt = new StringFormat(StringFormatFlags.NoWrap)
            {
                Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
            };
            Font fnt = new Font("MS Sans Serif", 12F);

            int cindex = 0;

            foreach (GalacticMapObject gmo in galmap.galacticMapObjects)
            {
                if (gmo.galMapType.Group == GalMapType.GalMapGroup.Regions)
                {
                    string gmoname = gmo.name;

                    List <Vector2> polygonxz = new List <Vector2>();                              // needs it in x/z and in vector2's
                    foreach (var pd in gmo.points)
                    {
                        polygonxz.Add(new Vector2((float)pd.X, (float)pd.Z));                   // can be concave and wound the wrong way..
                        vertexregionoutlineindex.Add((ushort)(vertexregionsoutlines.Count));
                        vertexregionsoutlines.Add(new Vector4((float)pd.X, 0, (float)pd.Z, 1));
                    }

                    vertexregionoutlineindex.Add(0xffff);                                             // primitive restart to break polygon

                    List <List <Vector2> > polys = PolygonTriangulator.Triangulate(polygonxz, false); // cut into convex polygons first - because we want the biggest possible area for naming purposes

                    Vector2 avgcentroid    = new Vector2(0, 0);
                    int     pointsaveraged = 0;

                    if (polys.Count > 0)                                                 // just in case..
                    {
                        foreach (List <Vector2> points in polys)                         // now for every poly
                        {
                            List <List <Vector2> > polytri;
                            if (points.Count == 3)                                    // already a triangle..
                            {
                                polytri = new List <List <Vector2> >()
                                {
                                    new List <Vector2>()
                                    {
                                        points[0], points[1], points[2]
                                    }
                                }
                            }
                            ;
                            else
                            {
                                polytri = PolygonTriangulator.Triangulate(points, true);    // cut into triangles not polygons
                            }
                            foreach (List <Vector2> pt in polytri)
                            {
                                vertexcolourregions.Add(pt[0].ToVector4XZ(w: cindex));
                                vertexcolourregions.Add(pt[2].ToVector4XZ(w: cindex));
                                vertexcolourregions.Add(pt[1].ToVector4XZ(w: cindex));

                                var cx = (pt[0].X + pt[1].X + pt[2].X) / 3;
                                var cy = (pt[0].Y + pt[1].Y + pt[2].Y) / 3;
                                avgcentroid = new Vector2(avgcentroid.X + cx, avgcentroid.Y + cy);
                                pointsaveraged++;

                                //foreach (var pd in pt) // debug
                                //{
                                //    vertexregionoutlineindex.Add((ushort)(vertexregionsoutlines.Count));
                                //    vertexregionsoutlines.Add(new Vector4((float)pd.X, 0, (float)pd.Y, 1));
                                //}
                                //vertexregionoutlineindex.Add(0xffff);       // primitive restart to break polygon
                            }
                        }

                        cindex = (cindex + 1) % array.Length;

                        Vector2 centeroid = PolygonTriangulator.WeightedCentroids(polys);

                        if (corr != null)   // allows the centeroid to be nerfed slightly
                        {
                            var entry = Array.Find(corr, x => gmo.name.Contains(x.name, StringComparison.InvariantCultureIgnoreCase));
                            if (entry != null)
                            {
                                centeroid = new Vector2(centeroid.X + entry.x, centeroid.Y + entry.y);
                            }
                        }

                        var final = PolygonTriangulator.FitInsideConvexPoly(polys, centeroid, new Vector2(sizeofname, sizeofname * (float)bitmapsize.Height / (float)bitmapsize.Width));

                        Vector3 bestpos  = new Vector3(final.Item1.X, 0, final.Item1.Y);
                        Vector3 bestsize = new Vector3(final.Item2.X, 1, final.Item2.Y);

                        textrenderer.Add(null, gmo.name, fnt, Color.White, Color.Transparent, bestpos, bestsize, new Vector3(0, 0, 0), fmt, alphafadescalar: 5000, alphafadepos: 500);
                    }
                }
            }

            fmt.Dispose();
            fnt.Dispose();

            // regions

            var vertregion = new GLPLVertexShaderWorldPalletColor(array.ToVector4(0.1f), true);
            var fragregion = new GLPLFragmentShaderVSColor();

            regionshader = new GLShaderPipeline(vertregion, fragregion, null, null);
            items.Add(regionshader);

            GLRenderState rt = GLRenderState.Tri();

            rt.DepthTest = false;
            var ridisplay = GLRenderableItem.CreateVector4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.Triangles, rt, vertexcolourregions.ToArray());

            rObjects.Add(regionshader, name + "-regions", ridisplay);

            // outlines

            var vertoutline = new GLPLVertexShaderWorldCoord(true);
            var fragoutline = new GLPLFragmentShaderFixedColor(Color.Cyan);

            outlineshader = new GLShaderPipeline(vertoutline, fragoutline, null, null);
            items.Add(outlineshader);

            GLRenderState ro = GLRenderState.Lines();

            ro.DepthTest        = false;
            ro.PrimitiveRestart = 0xffff;
            var rioutline = GLRenderableItem.CreateVector4(items, OpenTK.Graphics.OpenGL4.PrimitiveType.LineStrip, ro, vertexregionsoutlines.ToArray());

            rioutline.CreateElementIndexUShort(items.NewBuffer(), vertexregionoutlineindex.ToArray());

            rObjects.Add(outlineshader, name + "-outlines", rioutline);

            renderstate = 7;
        }