Exemplo n.º 1
0
        public void FirstTileSetJsonTests()
        {
            // arrange
            var zUpBoxes              = BBTestDataReader.GetTestData("testfixtures/zupboxes_actual.txt");
            var tree                  = TileCutter.ConstructTree(zUpBoxes, 50, 2000.0);
            var translation           = new double[] { 141584.2745, 471164.637, 15.81555842685751 };
            var s                     = File.ReadAllText(@"./testfixtures/tileset_json_expected.json");
            var tileset_json_expected = JsonConvert.DeserializeObject <TileSet>(s);

            // act
            var tileset_json_actual = TreeSerializer.ToTileset(tree, translation);
            var actual_json         = JsonConvert.SerializeObject(tileset_json_actual, Formatting.Indented, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            //File.WriteAllText("d:/aaa/sample_tileset_actual.json", actual_json);

            // assert
            Assert.IsTrue(tileset_json_actual.asset.version == "1.0");
            Assert.IsTrue(tileset_json_actual.geometricError == 500);

            var all_children_actual   = GetAllChildren(tileset_json_actual.root);
            var all_children_expected = GetAllChildren(tileset_json_expected.root);
            var res = AreSimilar(all_children_actual, all_children_expected);

            var sim = IsSimilar(tileset_json_expected.root, tileset_json_actual.root);

            Assert.IsTrue(sim);
            Assert.IsTrue(tileset_json_actual.root.refine == "ADD");        // 500
            Assert.IsTrue(tileset_json_actual.root.geometricError == 500);  // 500
            Assert.IsTrue(tileset_json_actual.root.transform.Length == 16); // 500
            Assert.IsTrue(tileset_json_actual.root.boundingVolume.box.Length == 12);
            Assert.IsTrue(tileset_json_actual.root.children.Count == 1);
        }
Exemplo n.º 2
0
        private static void CalculateBoundingBoxes(double[] translation, List <Tile> tiles, double minZ, double maxZ)
        {
            foreach (var t in tiles)
            {
                var bb          = t.BoundingBox;
                var bvol        = new BoundingBox3D(bb.XMin, bb.YMin, minZ, bb.XMax, bb.YMax, maxZ);
                var bvolRotated = BoundingBoxCalculator.TranslateRotateX(bvol, Reverse(translation), Math.PI / 2);

                if (t.Children != null)
                {
                    CalculateBoundingBoxes(translation, t.Children, minZ, maxZ);
                }
                t.Boundingvolume = TileCutter.GetBoundingvolume(bvolRotated);
            }
        }
Exemplo n.º 3
0
        protected override void Run(Workbench workbench, ILogger logger)
        {
            int palNum  = FindNamedParameter("--palette-number").Values[0].ToInt32();
            int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32();
            int x       = FindNamedParameter("--x").Values[0].ToInt32();
            int y       = FindNamedParameter("--y").Values[0].ToInt32();
            int w       = FindNamedParameter("--width").Values[0].ToInt32();
            int h       = FindNamedParameter("--height").Values[0].ToInt32();

            if (palNum < -1)
            {
                logger?.Log("Invalid palette number.", LogLevel.Error);
                return;
            }
            if (palSize == 0 || palSize < -1)
            {
                logger?.Log("Invalid palette size.", LogLevel.Error);
                return;
            }

            int tw = workbench.Tileset.TileWidth;
            int th = workbench.Tileset.TileHeight;

            TileCutter cutter        = new TileCutter(tw, th);
            int        ti            = 0;
            int        addedPalettes = 0;
            int        addedColors   = 0;
            Palette    pal           = null;

            using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, logger)) {
                foreach (Tile tile in cutter.CutTiles(bmp))
                {
                    // Get all the unique colors in the tile.
                    List <int> tileColors = tile.EnumerateTile().Distinct().ToList();

                    if (palSize != -1 && tileColors.Count > palSize)
                    {
                        logger?.Log("Tile " + ti + " has " + tileColors.Count + " colors, which is more than the " + palSize + " colors allowed by the palette.", LogLevel.Error);
                        return;
                    }

                    int bestPal = -1;
                    int bestAdd = int.MaxValue;

                    // Find palettes we can add to.
                    for (int i = 0; i < workbench.PaletteSet.Count; i++)
                    {
                        pal = workbench.PaletteSet[i].Palette;

                        // See if we can add to this palette.
                        int newSize = pal.Union(tileColors).Count();
                        if ((pal.MaximumSize >= 0 && newSize > pal.MaximumSize))
                        {
                            // Cannot add to this palette.
                            continue;
                        }

                        // Add to palette that would result in least new colors.
                        int add = newSize - pal.Count;
                        if (add < bestAdd)
                        {
                            bestPal = i;
                            bestAdd = add;
                        }
                    }

                    // Could not find a suitable palette, so have to make a new one.
                    if (bestPal < 0)
                    {
                        pal = new Palette(workbench.BitmapFormat, palSize);
                        if (palNum >= 0)
                        {
                            while (workbench.PaletteSet.ContainsPalette(palNum))
                            {
                                palNum++;
                            }
                            workbench.PaletteSet.Add(pal, palNum++);
                        }
                        else
                        {
                            workbench.PaletteSet.Add(pal);
                        }

                        addedPalettes++;

                        bestPal = workbench.PaletteSet.Count - 1;
                        bestAdd = tileColors.Count;
                    }
                    else
                    {
                        pal = workbench.PaletteSet[bestPal].Palette;
                    }

                    // Add the new colors to the palette.
                    foreach (int color in tileColors.Where(c => !pal.Contains(c)))
                    {
                        pal.Add(color);
                        addedColors++;
                    }

                    ti++;
                }

                logger?.Log("Added " + addedPalettes + " new palettes, " + addedColors + " colors total.");
            }
        }
Exemplo n.º 4
0
        protected override void Run(Workbench workbench, ILogger logger)
        {
            int palNum  = FindNamedParameter("--palette-number").Values[0].ToInt32();
            int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32();

            if (palNum < -1)
            {
                logger?.Log("Invalid palette number.", LogLevel.Error);
                return;
            }
            if (palSize == 0 || palSize < -1)
            {
                logger?.Log("Invalid palette size.", LogLevel.Error);
                return;
            }

            TileCutter cutter        = new TileCutter(8, 8);
            int        ti            = 0;
            int        addedColors   = 0;
            int        addedPalettes = 0;
            Palette    pal           = null;

            foreach (Tile tile in cutter.CutTiles(workbench.Bitmap))
            {
                // Grab color from tile.
                int color = tile[0, 0];
                foreach (int otherColor in tile.EnumerateTile().Skip(1))
                {
                    if (otherColor != color)
                    {
                        logger?.Log("Palette tile " + ti + " is not a single color.", LogLevel.Error);
                        return;
                    }
                }

                // Create new palette if needed.
                if (pal == null)
                {
                    pal = new Palette(workbench.BitmapFormat, palSize);
                }

                // Add finished palette to palette set.
                pal.Add(color, workbench.BitmapFormat);
                addedColors++;

                // Add finished palette to palette set.
                if (palSize != -1 && pal.Count >= palSize)
                {
                    if (palNum >= 0)
                    {
                        while (workbench.PaletteSet.ContainsPalette(palNum))
                        {
                            palNum++;
                        }
                        workbench.PaletteSet.Add(pal, palNum++);
                    }
                    else
                    {
                        workbench.PaletteSet.Add(pal);
                    }
                    addedPalettes++;
                    pal = null;
                }

                ti++;
            }
            if (pal != null)
            {
                if (palNum >= 0)
                {
                    while (workbench.PaletteSet.ContainsPalette(palNum))
                    {
                        palNum++;
                    }
                    workbench.PaletteSet.Add(pal, palNum++);
                }
                else
                {
                    workbench.PaletteSet.Add(pal);
                }
                addedPalettes++;
            }

            logger?.Log("Read " + addedPalettes + " palettes with " + addedColors + " colors total.");
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var version = Assembly.GetEntryAssembly().GetName().Version;

            Console.WriteLine($"tool: pg2b3dm {version}");

            Parser.Default.ParseArguments <Options>(args).WithParsed(o => {
                o.User     = string.IsNullOrEmpty(o.User) ? Environment.UserName : o.User;
                o.Database = string.IsNullOrEmpty(o.Database) ? Environment.UserName : o.Database;

                var connectionString = $"Host={o.Host};Username={o.User};Database={o.Database};Port={o.Port}";
                var istrusted        = TrustedConnectionChecker.HasTrustedConnection(connectionString);

                if (!istrusted)
                {
                    Console.Write($"Password for user {o.User}: ");
                    password          = PasswordAsker.GetPassword();
                    connectionString += $";password={password}";
                    Console.WriteLine();
                }

                Console.WriteLine($"Start processing....");

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                var output      = o.Output;
                var outputTiles = output + "/tiles";
                if (!Directory.Exists(output))
                {
                    Directory.CreateDirectory(output);
                }
                if (!Directory.Exists(outputTiles))
                {
                    Directory.CreateDirectory(outputTiles);
                }

                var geometryTable  = o.GeometryTable;
                var geometryColumn = o.GeometryColumn;
                var idcolumn       = o.IdColumn;
                Console.WriteLine("Calculating bounding boxes...");
                var conn = new NpgsqlConnection(connectionString);
                conn.Open();
                var bbox3d = BoundingBoxRepository.GetBoundingBox3D(conn, geometryTable, geometryColumn);

                var translation = bbox3d.GetCenter().ToVector();
                var zupBoxes    = GetZupBoxes(conn, geometryTable, geometryColumn, idcolumn, translation);
                var tree        = TileCutter.ConstructTree(zupBoxes, o.FeaturesPerTile, o.ExtentTile);

                Console.WriteLine("Writing tileset.json...");
                WiteTilesetJson(translation, tree, o.Output);

                Console.WriteLine($"Writing {Counter.Instance.Count} tiles...");
                WriteTiles(conn, geometryTable, geometryColumn, idcolumn, translation, tree, o.Output, o.RoofColorColumn, o.AttributesColumn);
                conn.Close();
                stopWatch.Stop();
                Console.WriteLine();
                Console.WriteLine($"Elapsed: {stopWatch.ElapsedMilliseconds / 1000} seconds");
                Console.WriteLine("Program finished.");
            });
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var version = Assembly.GetEntryAssembly().GetName().Version;

            Console.WriteLine($"tool: pg2b3dm {version}");

            Parser.Default.ParseArguments <Options>(args).WithParsed(o => {
                o.User     = string.IsNullOrEmpty(o.User) ? Environment.UserName : o.User;
                o.Database = string.IsNullOrEmpty(o.Database) ? Environment.UserName : o.Database;

                var connectionString = $"Host={o.Host};Username={o.User};Database={o.Database};Port={o.Port}";
                var istrusted        = TrustedConnectionChecker.HasTrustedConnection(connectionString);

                if (!istrusted)
                {
                    Console.Write($"password for user {o.User}: ");
                    password          = PasswordAsker.GetPassword();
                    connectionString += $";password={password}";
                    Console.WriteLine();
                }

                Console.WriteLine($"start processing....");

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                var output      = o.Output;
                var outputTiles = $"{output}{Path.DirectorySeparatorChar}tiles";
                if (!Directory.Exists(output))
                {
                    Directory.CreateDirectory(output);
                }
                if (!Directory.Exists(outputTiles))
                {
                    Directory.CreateDirectory(outputTiles);
                }

                Console.WriteLine($"input table:  {o.GeometryTable}");
                if (o.Query != String.Empty)
                {
                    Console.WriteLine($"query:  {o.Query}");
                }
                Console.WriteLine($"input geometry column:  {o.GeometryColumn}");

                Console.WriteLine($"output directory:  {outputTiles}");

                var geometryTable   = o.GeometryTable;
                var geometryColumn  = o.GeometryColumn;
                var idcolumn        = o.IdColumn;
                var lodcolumn       = o.LodColumn;
                var query           = o.Query;
                var geometricErrors = Array.ConvertAll(o.GeometricErrors.Split(','), double.Parse);;

                var conn = new NpgsqlConnection(connectionString);

                var lods = (lodcolumn != string.Empty ? LodsRepository.GetLods(conn, geometryTable, lodcolumn, query) : new List <int> {
                    0
                });
                if ((geometricErrors.Length != lods.Count + 1) && lodcolumn == string.Empty)
                {
                    Console.WriteLine($"lod levels: [{ String.Join(',', lods)}]");
                    Console.WriteLine($"geometric errors: {o.GeometricErrors}");

                    Console.WriteLine("error: parameter -g --geometricerrors is wrongly specified...");
                    Console.WriteLine("end of program...");
                    Environment.Exit(0);
                }
                if (lodcolumn != String.Empty)
                {
                    Console.WriteLine($"lod levels: {String.Join(',', lods)}");

                    if (lods.Count >= geometricErrors.Length)
                    {
                        Console.WriteLine($"calculating geometric errors starting from {geometricErrors[0]}");
                        geometricErrors = GeometricErrorCalculator.GetGeometricErrors(geometricErrors[0], lods);
                    }
                }
                ;
                Console.WriteLine("geometric errors: " + String.Join(',', geometricErrors));

                var bbox3d = BoundingBoxRepository.GetBoundingBox3DForTable(conn, geometryTable, geometryColumn, query);
                // Console.WriteLine($"3D Boundingbox {geometryTable}.{geometryColumn}: [{bbox3d.XMin}, {bbox3d.YMin}, {bbox3d.ZMin},{bbox3d.XMax},{bbox3d.YMax}, {bbox3d.ZMax}]");
                var translation = bbox3d.GetCenter().ToVector();
                //  Console.WriteLine($"translation {geometryTable}.{geometryColumn}: [{string.Join(',', translation) }]");
                var boundingboxAllFeatures = BoundingBoxCalculator.TranslateRotateX(bbox3d, Reverse(translation), Math.PI / 2);
                var box = boundingboxAllFeatures.GetBox();
                var sr  = SpatialReferenceRepository.GetSpatialReference(conn, geometryTable, geometryColumn, query);
                Console.WriteLine($"spatial reference: {sr}");
                var tiles = TileCutter.GetTiles(0, conn, o.ExtentTile, geometryTable, geometryColumn, bbox3d, sr, 0, lods, geometricErrors.Skip(1).ToArray(), lodcolumn, query);
                Console.WriteLine();
                var nrOfTiles = RecursiveTileCounter.CountTiles(tiles.tiles, 0);
                Console.WriteLine($"tiles with features: {nrOfTiles} ");
                CalculateBoundingBoxes(translation, tiles.tiles, bbox3d.ZMin, bbox3d.ZMax);
                Console.WriteLine("writing tileset.json...");
                var json = TreeSerializer.ToJson(tiles.tiles, translation, box, geometricErrors[0], o.Refinement);
                File.WriteAllText($"{o.Output}/tileset.json", json);

                WriteTiles(conn, geometryTable, geometryColumn, idcolumn, translation, tiles.tiles, sr, o.Output, 0, nrOfTiles, o.RoofColorColumn, o.AttributesColumn, o.LodColumn, query);

                stopWatch.Stop();
                Console.WriteLine();
                Console.WriteLine($"elapsed: {stopWatch.ElapsedMilliseconds / 1000} seconds");
                Console.WriteLine("program finished.");
            });
        }