Example #1
0
        public void Run()
        {
            List <Collection> collections = _sketchFabApi.GetMyCollectionsAsync(_sketchFabToken, TokenType.Token).GetAwaiter().GetResult();

            if (collections.Any(c => c.name == "Helladic Tests"))
            {
            }


            UploadModelRequest upload = new UploadModelRequest()
            {
                Description   = "TEST",// * Generated by [DEM Net Elevation API](https://elevationapi.com)\n* Helladic test upload",
                FilePath      = Path.Combine(Directory.GetCurrentDirectory(), "Sketchfab", "C1410_OsmTopo.glb"),
                IsInspectable = true,
                IsPrivate     = false,
                IsPublished   = false,
                Name          = "C1410_OsmTopo TEST",
                Options       = new ModelOptions()
                {
                    Background = SkecthFabEnvironment.Footprint_Court, Shading = ShadingType.lit
                }
            };


            var uuid = _sketchFabApi.UploadModelAsync(upload, _sketchFabToken).GetAwaiter().GetResult();
        }
        public void BatchGenerationAndUpload(string fileName, string outputDirName)
        {
            Location3DModelSettings settings = new Location3DModelSettings()
            {
                Dataset                = DEMDataSet.NASADEM,
                ImageryProvider        = ImageryProvider.ThunderForestLandscape,
                ZScale                 = 2f,
                SideSizeKm             = 1.5f,
                OsmBuildings           = true,
                DownloadMissingFiles   = false,
                GenerateTIN            = false,
                MaxDegreeOfParallelism = 1,
                OutputDirectory        = Path.Combine(Directory.GetCurrentDirectory(), outputDirName)
            };

            string currentOutFilePath = string.Concat(Path.ChangeExtension(fileName, null), $"_out.txt");
            Dictionary <string, Location3DModelRequest>  requests  = ParseInputFile(fileName);
            Dictionary <string, Location3DModelResponse> responses = ParseOutputFile(currentOutFilePath);

            // Backup file by creating a copy
            var outFilePath = string.Concat(Path.ChangeExtension(fileName, null), $"_out_{DateTime.Now:ddMMyyyy-hhmmss}.txt");

            bool append = responses.Count > 0;

            _logger.LogInformation($"Append mode: {append}");

            // Restart from previous run
            Directory.CreateDirectory(settings.OutputDirectory);
            // Filter already generated files
            int countBefore = requests.Count;

            //requests = requests.Where(r => !File.Exists(Path.Combine(settings.OutputDirectory, settings.ModelFileNameGenerator(settings, r.Value)))).ToList();
            if (requests.Count < countBefore)
            {
                _logger.LogInformation($"Skipping {countBefore - requests.Count} files already generated.");
            }


            // Generate and upload
            int sumTilesDownloaded = 0;

            using (StreamWriter sw = new StreamWriter(outFilePath, append: append, Encoding.UTF8))
            {
                sw.WriteLine(string.Join("\t", "pk", "pn", "lat", "lon", "link", "tilecount_running_total", "sketchfab_status", "sketchfab_id"));

                foreach (var request in requests.Values)
                {
                    UploadModelRequest uploadRequest;
                    try
                    {
                        bool modelExists = File.Exists(Path.Combine(settings.OutputDirectory, settings.ModelFileNameGenerator(settings, request)));
                        Location3DModelResponse response = null;
                        if (!(modelExists && responses.TryGetValue(request.Id, out response))) // check model file exist
                        {
                            try
                            {
                                //===========================
                                // Generation
                                response               = Generate3DLocationModel(request, settings);
                                sumTilesDownloaded    += response.NumTiles ?? 0;
                                response.Id            = request.Id;
                                responses[response.Id] = response;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex.Message);
                            }
                            finally
                            {
                                _logger.LogInformation("Model generated. Waiting 10s...");
                                Thread.Sleep(10000); // wait 2 sec to dive overpassAPI some breath
                            }
                        }

                        if (response != null && string.IsNullOrWhiteSpace(response.UploadedFileId))
                        {
                            try
                            {
                                //===========================
                                // Upload
                                uploadRequest = GetUploadRequest(settings, request);
                                var sfResponse = _sketchFabApi.UploadModelAsync(uploadRequest, _sketchFabToken).GetAwaiter().GetResult();
                                response.UploadedFileId = sfResponse.ModelId;
                                response.UploadStatus   = sfResponse.StatusCode == HttpStatusCode.Created ? UploadStatus.OK : UploadStatus.Error;
                                _logger.LogInformation($"Sketchfab upload ok : {response.UploadedFileId}");
                            }
                            catch (Exception ex)
                            {
                                response.UploadStatus   = UploadStatus.Error;
                                response.UploadedFileId = null;
                                _logger.LogError(ex.Message);
                            }
                            finally
                            {
                                _logger.LogInformation($"Waiting 10s...");
                                Thread.Sleep(10000); // wait 2 sec to give SkecthFab some breath
                            }
                        }

                        sw.WriteLine(string.Join("\t", request.Id, request.Title, request.Latitude, request.Longitude
                                                 , request.Description              // link
                                                 , sumTilesDownloaded               // tilecount_running_total
                                                 , response.UploadStatus.ToString() // sketchfab_status
                                                 , response.UploadedFileId          // sketchfab_id
                                                 ));

                        sw.Flush();
                        if (responses.Count > 0)
                        {
                            _logger.LogInformation($"Reponse: {responses.Last().Value.Elapsed.TotalSeconds:N3} s, Average: {responses.Average(r => r.Value.Elapsed.TotalSeconds):N3} s ({responses.Count}/{requests.Count} model(s) so far, {sumTilesDownloaded} tiles)");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message);
                    }
                }
            }
        }