private void LoadResourcePacks(GraphicsDevice device, IProgressReceiver progress, string[] resourcePacks) { var countBefore = ActiveResourcePacks.Count; var first = ActiveResourcePacks.First.Value; ActiveResourcePacks.Clear(); ActiveResourcePacks.AddFirst(first); if (_hasInit) { PreloadCallback?.Invoke(first.FontBitmap, McResourcePack.BitmapFontCharacters.ToList()); Atlas.Reset(); } foreach (string file in resourcePacks) { try { string resourcePackPath = Path.Combine(ResourcePackDirectory.FullName, file); if (File.Exists(resourcePackPath)) { Log.Info($"Loading resourcepack {file}..."); using (FileStream stream = new FileStream(resourcePackPath, FileMode.Open)) { var pack = LoadResourcePack(progress, stream, true, null); if (pack.Manifest != null && string.IsNullOrWhiteSpace(pack.Manifest.Name)) { pack.Manifest.Name = Path.GetFileNameWithoutExtension(file); } ActiveResourcePacks.AddLast(pack); } } } catch (Exception e) { Log.Warn(e, $"Could not load resourcepack {file}: {e.ToString()}"); } } bool isFirst = true; isFirst = true; foreach (var resourcePack in ActiveResourcePacks) { LoadModels(progress, resourcePack, !isFirst, isFirst); if (isFirst) { //Only load models for vanilla until above we fix blockstate replacement issues. isFirst = false; break; } } isFirst = true; foreach (var resourcePack in ActiveResourcePacks) { Alex.GuiRenderer.LoadLanguages(resourcePack, progress); LoadTextures(device, progress, resourcePack, isFirst); if (isFirst) { isFirst = false; } } progress?.UpdateProgress(50, "Loading language..."); if (!Alex.GuiRenderer.SetLanguage(Options.AlexOptions.MiscelaneousOptions.Language.Value)) { Alex.GuiRenderer.SetLanguage(CultureInfo.InstalledUICulture.Name); } var f = ActiveResourcePacks.LastOrDefault(x => x.FontBitmap != null); if (f != null) { PreloadCallback?.Invoke(f.FontBitmap, McResourcePack.BitmapFontCharacters.ToList()); } }
public async Task <string> EnsureTargetReleaseAsync(string targetRelease, IProgressReceiver progressReceiver) { var targetVersion = targetRelease; //manifest.Latest.Release; string assetsZipSavePath = Path.Combine("assets", $"java-{targetVersion}.zip"); if (_storage.Exists(assetsZipSavePath)) { Log.Info("Java assets already up to date!"); return(assetsZipSavePath); } if (_storage.TryReadString(CurrentVersionStorageKey, out var currentVersion)) { if (currentVersion == targetVersion) { if (_storage.Exists(assetsZipSavePath)) { Log.Info("MCJava Assets Up to date!"); return(assetsZipSavePath); } } } if (_storage.Exists(assetsZipSavePath)) { _storage.Delete(assetsZipSavePath); } progressReceiver?.UpdateProgress(0, "Downloading assets..."); var manifest = await GetManifestAsync(); // not latest, update Log.Info($"Downloading MCJava {targetVersion} Assets."); var version = manifest.Versions.FirstOrDefault(v => string.Equals(v.Id, targetVersion, StringComparison.InvariantCultureIgnoreCase)); if (version == null) { Log.Error("Version not found in versions? wut?"); return(assetsZipSavePath); } LauncherMeta launcherMeta; AssetIndex assetIndex; var dirpath = Path.Combine("assets", $"java-{targetVersion}_cache"); if (!_storage.TryGetDirectory(dirpath, out var dir)) { if (_storage.TryCreateDirectory(dirpath)) { if (!_storage.TryGetDirectory(dirpath, out dir)) { return(assetsZipSavePath); } } } // fetch version's json thing using (var httpClient = new HttpClient()) { var launcherMetaJson = await httpClient.GetStringAsync(version.Url); launcherMeta = LauncherMeta.FromJson(launcherMetaJson); // download client, prob usefil? var clientJar = await httpClient.GetByteArrayAsync(launcherMeta.Downloads.Client.Url); using (var clientMs = new MemoryStream(clientJar)) using (ZipArchive clientJarZip = new ZipArchive(clientMs, ZipArchiveMode.Read)) { foreach (var entry in clientJarZip.Entries) { if (!entry.FullName.StartsWith("assets") && entry.FullName != "pack.mcmeta") { continue; } var localpath = Path.Combine(dir.FullName, entry.FullName); if (!_storage.TryGetDirectory(Path.GetDirectoryName(localpath), out _)) { _storage.TryCreateDirectory(Path.GetDirectoryName(localpath)); // Directory.CreateDirectory(Path.GetDirectoryName(localpath)); } entry.ExtractToFile(localpath, true); Log.Debug($"Extracted Asset '{entry.Name}' (Size: {entry.Length})"); } } // now we only care about asset index soooo... grab that var assetIndexJson = await httpClient.GetStringAsync(launcherMeta.LauncherMetaAssetIndex.Url); assetIndex = AssetIndex.FromJson(assetIndexJson); int target = assetIndex.Objects.Count; int done = 0; foreach (var assetIndexObject in assetIndex.Objects) { // Skip ogg files if (assetIndexObject.Key.EndsWith(".ogg", StringComparison.InvariantCultureIgnoreCase)) { continue; } var assetUrl = AssetResourceUri .Replace("{hash_sub2}", assetIndexObject.Value.Hash.Substring(0, 2)) .Replace("{hash}", assetIndexObject.Value.Hash); progressReceiver?.UpdateProgress(done * (target / 100), "Downloading assets...", assetIndexObject.Key); try { var fileBytes = await httpClient.GetByteArrayAsync(assetUrl); var filename = Path.Combine("assets", assetIndexObject.Key); var localpath = Path.Combine(dir.FullName, filename); if (!_storage.TryGetDirectory(Path.GetDirectoryName(localpath), out _)) { _storage.TryCreateDirectory(Path.GetDirectoryName(localpath)); // Directory.CreateDirectory(Path.GetDirectoryName(localpath)); } // File.WriteAllBytes(localpath, fileBytes); _storage.TryWriteBytes(localpath, fileBytes); Log.Debug($"Downloaded asset '{assetIndexObject.Key}' (Hash: {assetIndexObject.Value.Hash})"); } catch (Exception ex) { Log.Error(ex, $"Failed to download asset '{assetIndexObject.Key}' (Hash: {assetIndexObject.Value.Hash})"); continue; } done++; } } // make new zip m8 using (var ms = new MemoryStream()) { using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var file in dir.EnumerateFiles("*", SearchOption.AllDirectories)) { zip.CreateEntryFromFile(file.FullName, Path.GetRelativePath(dir.FullName, file.FullName)); } } // saving zip m8 ms.Seek(0, SeekOrigin.Begin); var allBytes = ms.ToArray(); _storage.TryWriteBytes(assetsZipSavePath, allBytes); Log.Info($"Written Archive to '{assetsZipSavePath}' (Size: {allBytes.Length})"); } _storage.TryWriteString(CurrentVersionStorageKey, targetVersion); Thread.Sleep(500); dir.Delete(true); return(assetsZipSavePath); }
public bool CheckResources(GraphicsDevice device, IProgressReceiver progressReceiver, McResourcePack.McResourcePackPreloadCallback preloadCallback) { LoadHWID(); PreloadCallback = preloadCallback; Log.Info($"Loading registries..."); progressReceiver?.UpdateProgress(0, "Loading registries..."); Registries = JsonConvert.DeserializeObject <Registries>(ReadStringResource("Alex.Resources.registries.json")); progressReceiver?.UpdateProgress(100, "Loading registries..."); byte[] defaultResources; byte[] defaultBedrock; if (!CheckJavaAssets(progressReceiver, out defaultResources)) { return(false); } Log.Info($"Loading vanilla resources..."); progressReceiver?.UpdateProgress(0, "Loading vanilla resources..."); using (MemoryStream stream = new MemoryStream(defaultResources)) { var vanilla = LoadResourcePack(progressReceiver, stream, false, preloadCallback); vanilla.Manifest.Name = "Vanilla"; ActiveResourcePacks.AddFirst(vanilla); } if (!CheckBedrockAssets(progressReceiver, out defaultBedrock)) { return(false); } var bedrockPath = Path.Combine("assets", "bedrock"); DirectoryInfo directory; if (!Storage.TryGetDirectory(bedrockPath, out directory) && !Storage.TryCreateDirectory(bedrockPath)) { Log.Warn($"The bedrock resources required to play this game are not set-up correctly!"); Console.ReadLine(); Environment.Exit(1); return(false); } if (directory.GetFileSystemInfos().Length == 0) { Log.Info($"Extracting required resources..."); progressReceiver?.UpdateProgress(50, "Extracting resources..."); byte[] zipped = defaultBedrock; //ReadResource("Alex.Resources.resources.zip"); using (MemoryStream ms = new MemoryStream(zipped)) { using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Read)) { archive.ExtractToDirectory(directory.FullName); } } } Log.Info($"Loading bedrock resources..."); progressReceiver?.UpdateProgress(0, "Loading bedrock resources..."); BedrockResourcePack = new BedrockResourcePack(directory, (percentage, file) => { progressReceiver?.UpdateProgress(percentage, null, file); }); EntityFactory.LoadModels(this, device, true, progressReceiver); Log.Info($"Loading known entity data..."); EntityFactory.Load(this, progressReceiver); Storage.TryGetDirectory(Path.Combine("assets", "resourcepacks"), out DirectoryInfo root); ResourcePackDirectory = root; LoadRegistries(progressReceiver); LoadResourcePacks(device, progressReceiver, Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Value); ItemFactory.Init(RegistryManager, this, ResourcePack, progressReceiver); BlockEntityFactory.LoadResources(device, ResourcePack); if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out DirectoryInfo info)) { SkinPackDirectory = info; LoadBedrockPacks(progressReceiver, info); } else { if (Storage.TryCreateDirectory(Path.Combine("assets", "bedrockpacks"))) { if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out var dirInfo)) { SkinPackDirectory = dirInfo; } } } Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Bind(ResourcePacksChanged); _hasInit = true; return(true); }
private static int LoadModels(IRegistryManager registryManager, ResourceManager resources, bool replace, bool reportMissing, IProgressReceiver progressReceiver) { Stopwatch sw = Stopwatch.StartNew(); var raw = ResourceManager.ReadStringResource("Alex.Resources.blockmap.json"); var mapping = JsonConvert.DeserializeObject <BlockMap>(raw); var blockRegistry = registryManager.GetRegistry <Block>(); //var blockStateRegistry = registryManager.GetRegistry<BlockState>(); var data = BlockData.FromJson(ResourceManager.ReadStringResource("Alex.Resources.NewBlocks.json")); int total = data.Count; int done = 0; int importCounter = 0; void LoadEntry(KeyValuePair <string, BlockData> entry) { done++; if (!resources.TryGetBlockState(entry.Key, out var blockStateResource)) { if (reportMissing) { Log.Warn($"Could not find blockstate with key: {entry.Key}"); } return; } //double percentage = 100D * ((double) done / (double) total);blockstate variants progressReceiver.UpdateProgress(done, total, $"Importing block models...", entry.Key); var location = new ResourceLocation(entry.Key); var variantMap = new BlockStateVariantMapper(); var defaultState = new BlockState { Name = entry.Key, VariantMapper = variantMap }; defaultState = defaultState.WithLocation(location).Value; if (entry.Value.Properties != null) { foreach (var property in entry.Value.Properties) { defaultState = (BlockState)defaultState.WithPropertyNoResolve(property.Key, property.Value.FirstOrDefault(), false); } } defaultState.ModelData = ResolveVariant(blockStateResource, defaultState); variantMap.Model = ResolveModel(resources, blockStateResource, out bool isMultipartModel); variantMap.IsMultiPart = isMultipartModel; if (variantMap.Model == null) { Log.Warn($"No model found for {entry.Key}[{variantMap.ToString()}]"); } foreach (var s in entry.Value.States) { if (!replace && RegisteredBlockStates.TryGetValue(s.ID, out BlockState st)) { Log.Warn($"Duplicate blockstate id (Existing: {st.Name}[{st.ToString()}]) "); continue; } BlockState variantState = (BlockState)(defaultState).CloneSilent(); variantState.ID = s.ID; variantState.Name = entry.Key; if (s.Properties != null) { foreach (var property in s.Properties) { //if (property.Key.ToLower() == "waterlogged")continue; variantState = (Blocks.State.BlockState)variantState.WithPropertyNoResolve(property.Key, property.Value, false); } } IRegistryEntry <Block> registryEntry; if (!blockRegistry.TryGet(location, out registryEntry)) { registryEntry = new UnknownBlock(); registryEntry = registryEntry.WithLocation(location); // = entry.Key; } else { registryEntry = registryEntry.WithLocation(location); } var block = registryEntry.Value; if (string.IsNullOrWhiteSpace(block.DisplayName)) { block.DisplayName = entry.Key; } variantState.ModelData = ResolveVariant(blockStateResource, variantState); variantState.Block = block.Value; block.BlockState = variantState; // if (variantState.IsMultiPart) multipartBased++; variantState.Default = s.Default; if (variantMap.TryAdd(variantState)) { if (!RegisteredBlockStates.TryAdd(variantState.ID, variantState)) { if (replace) { RegisteredBlockStates[variantState.ID] = variantState; importCounter++; } else { Log.Warn($"Failed to add blockstate (variant), key already exists! ({variantState.ID} - {variantState.Name})"); } } else { importCounter++; } } else { Log.Warn($"Could not add variant to variant map: {variantState.Name}[{variantState.ToString()}]"); } } if (!BlockStateByName.TryAdd(location, variantMap)) { if (replace) { BlockStateByName[location] = variantMap; } else { Log.Warn($"Failed to add blockstate, key already exists! ({defaultState.Name})"); } } } if (resources.Asynchronous) { Parallel.ForEach(data, LoadEntry); } else { foreach (var entry in data) { LoadEntry(entry); } } var blockStateTime = sw.Elapsed; var mappings = mapping.GroupBy(x => x.Value.BedrockIdentifier).ToArray(); int counter = 1; sw.Restart(); Parallel.ForEach( mappings, (m) => { progressReceiver?.UpdateProgress(counter, mapping.Count, "Mapping blockstates...", m.Key); var mapper = new BlockStateVariantMapper(); bool first = true; foreach (var state in m) { var match = _blockMappingRegex.Match(state.Key); var keyMatch = match.Groups["key"]; var dataMatch = match.Groups["data"]; if (!keyMatch.Success) { Log.Warn($"Entry without key!"); continue; } BlockState pcVariant = GetBlockState(keyMatch.Value); if (pcVariant != null) { pcVariant = pcVariant.Clone(); if (dataMatch.Success) { var properties = BlockState.ParseData(dataMatch.Value); var p = properties.ToArray(); for (var i = 0; i < p.Length; i++) { var prop = p[i]; if (i == p.Length - 1) { pcVariant = pcVariant.WithProperty(prop.Key, prop.Value); } else { pcVariant = pcVariant.WithPropertyNoResolve(prop.Key, prop.Value, false); } } } } if (pcVariant == null) { Log.Warn($"Map failed: {match.Groups["key"].Value} -> {state.Value.BedrockIdentifier}"); continue; } pcVariant = pcVariant.CloneSilent(); PeBlockState bedrockState = new PeBlockState(pcVariant); bedrockState.Name = state.Value.BedrockIdentifier; bedrockState.VariantMapper = mapper; //bedrockState.AppliedModels = pcVariant.AppliedModels; // bedrockState.IsMultiPart = pcVariant.IsMultiPart; // bedrockState.MultiPartHelper = pcVariant.MultiPartHelper; // bedrockState.ResolveModel = pcVariant.ResolveModel; //bedrockState.Model = pcVariant.Model; bedrockState.Block = pcVariant.Block; bedrockState.ID = (uint)Interlocked.Increment(ref counter); bedrockState.Default = first; first = false; if (state.Value.BedrockStates != null && state.Value.BedrockStates.Count > 0) { foreach (var bs in state.Value.BedrockStates) { bedrockState.Values[bs.Key] = bs.Value.ToString(); } } if (!mapper.TryAdd(bedrockState.WithLocation(bedrockState.Name).Value)) { Log.Warn($"Failed to add bedrockstate: {state.Value.BedrockIdentifier}"); } } BedrockStates[m.Key] = mapper; }); //Log.Info($"Loaded {multipartBased} multi-part blockstates!"); Log.Info($"Loaded {BedrockStates.Count} mappings in {sw.ElapsedMilliseconds}ms..."); return(importCounter); }
private void InitializeGame(IProgressReceiver progressReceiver) { progressReceiver.UpdateProgress(0, "Initializing..."); API.Extensions.Init(GraphicsDevice); MCPacketFactory.Load(); //ConfigureServices(); var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { eventDispatcher.LoadFrom(assembly); } var options = Services.GetService <IOptionsProvider>(); string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); var pluginDir = options.AlexOptions.ResourceOptions.PluginDirectory; if (!string.IsNullOrWhiteSpace(pluginDir)) { pluginDirectoryPaths = pluginDir; } else { if (!string.IsNullOrWhiteSpace(LaunchSettings.WorkDir) && Directory.Exists(LaunchSettings.WorkDir)) { pluginDirectoryPaths = LaunchSettings.WorkDir; } } foreach (string dirPath in pluginDirectoryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { string directory = dirPath; if (!Path.IsPathRooted(directory)) { directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dirPath); } PluginManager.DiscoverPlugins(directory); } var profileManager = Services.GetService <ProfileManager>(); // Log.Info($"Loading resources..."); if (!Resources.CheckResources(GraphicsDevice, progressReceiver, OnResourcePackPreLoadCompleted)) { Console.WriteLine("Press enter to exit..."); Console.ReadLine(); Exit(); return; } profileManager.LoadProfiles(progressReceiver); //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null); AnvilWorldProvider.LoadBlockConverter(); PluginManager.EnablePlugins(); var storage = Services.GetRequiredService <IStorageSystem>(); if (storage.TryReadJson("skin.json", out EntityModel model)) { PlayerModel = model; } if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
private void InitializeGame(IProgressReceiver progressReceiver) { progressReceiver.UpdateProgress(0, "Initializing..."); API.Extensions.Init(GraphicsDevice); MCPacketFactory.Load(); //ConfigureServices(); var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { eventDispatcher.LoadFrom(assembly); } //var options = Services.GetService<IOptionsProvider>(); // Log.Info($"Loading resources..."); if (!Resources.CheckResources(GraphicsDevice, progressReceiver, OnResourcePackPreLoadCompleted)) { Console.WriteLine("Press enter to exit..."); Console.ReadLine(); Exit(); return; } var profileManager = Services.GetService <ProfileManager>(); profileManager.LoadProfiles(progressReceiver); //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null); AnvilWorldProvider.LoadBlockConverter(); PluginManager.EnablePlugins(); var storage = Services.GetRequiredService <IStorageSystem>(); if (storage.TryReadString("skin.json", out var str, Encoding.UTF8)) { if (GeometryModel.TryParse(str, null, out var geometryModel)) { var model = geometryModel.FindGeometry("geometry.humanoid.custom"); if (model == null) { model = geometryModel.FindGeometry("geometry.humanoid.customSlim"); } if (model != null) { PlayerModel = model; Log.Debug($"Player model loaded..."); } } } if (PlayerModel == null) { if (ModelFactory.TryGetModel("geometry.humanoid.customSlim", out var model)) { //model.Name = "geometry.humanoid.customSlim"; PlayerModel = model; } } if (PlayerModel != null) { //Log.Info($"Player model loaded..."); } if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
public static string ReadStringResource(string resource, IProgressReceiver progressReceiver = null) { return(Encoding.UTF8.GetString(ReadResource(resource, progressReceiver))); }
private void LoadResourcePacks(GraphicsDevice device, IProgressReceiver progress, string[] resourcePacks) { var countBefore = ActiveResourcePacks.Count; var first = ActiveResourcePacks.First.Value; var before = ActiveResourcePacks.ToArray(); foreach (var item in before.Skip(1)) { item.Dispose(); } ActiveResourcePacks.Clear(); ActiveResourcePacks.AddFirst(first); if (_hasInit) { PreloadCallback?.Invoke(first.FontBitmap, McResourcePack.BitmapFontCharacters.ToList()); Atlas.Reset(); } foreach (string file in resourcePacks) { try { string resourcePackPath = Path.Combine(ResourcePackDirectory.FullName, file); if (File.Exists(resourcePackPath)) { //Log.Info($"Loading resourcepack {file}..."); //using (FileStream stream = new FileStream(resourcePackPath, FileMode.Open)) { // using (ZipFileSystem zipFileSystem = ) { var pack = LoadResourcePack(progress, new ZipFileSystem(new FileStream(resourcePackPath, FileMode.Open), Path.GetFileNameWithoutExtension(resourcePackPath)), null); if (pack is McResourcePack javaPack) { if (pack.Info != null && string.IsNullOrWhiteSpace(pack.Info.Name)) { pack.Info.Name = Path.GetFileNameWithoutExtension(file); } ActiveResourcePacks.AddLast(javaPack); } else if (pack is BedrockResourcePack bedrockPack) { ActiveBedrockResourcePacks.AddLast(bedrockPack); } } } } } catch (Exception e) { Log.Warn(e, $"Could not load resourcepack {file}: {e.ToString()}"); } } var active = ActiveResourcePacks.ToArray(); bool isFirst = true; foreach (var resourcePack in active) { Alex.GuiRenderer.LoadLanguages(resourcePack, progress); LoadModels(progress, resourcePack, !isFirst, isFirst); if (isFirst) { //Only load models for vanilla until above we fix blockstate replacement issues. isFirst = false; // break; } } Stopwatch sw = Stopwatch.StartNew(); MeasureProfiler.StartCollectingData(); var imported = BlockFactory.LoadBlockstates(RegistryManager, this, false, false, progress); MeasureProfiler.SaveData(); MeasureProfiler.StopCollectingData(); Log.Info($"Imported {imported} blockstates from resourcepack in {sw.ElapsedMilliseconds}ms!"); var textures = new Dictionary <ResourceLocation, AtlasGenerator.ImageEntry>(); for (var index = 0; index < active.Length; index++) { var resourcePack = active[index]; progress?.UpdateProgress(0, $"Loading textures: {resourcePack.Info?.Name ?? "Unknown"}"); Atlas.LoadResourcePackOnTop(device, textures, resourcePack, progress, index == active.Length - 1); //LoadTextures(device, progress, resourcePack, ref textures, index == active.Length - 1); } foreach (var resourcePack in ActiveBedrockResourcePacks) { LoadEntityModels(resourcePack, progress); int modelCount = EntityFactory.LoadModels(resourcePack, this, device, true, progress); Log.Info($"Imported {modelCount} entity models..."); } progress?.UpdateProgress(0, $"Loading UI textures..."); Alex.GuiRenderer.LoadResourcePackTextures(this, progress); progress?.UpdateProgress(50, "Loading language..."); if (!Alex.GuiRenderer.SetLanguage(Options.AlexOptions.MiscelaneousOptions.Language.Value)) { Alex.GuiRenderer.SetLanguage(CultureInfo.InstalledUICulture.Name); } progress?.UpdateProgress(100, "Loading language..."); var f = ActiveResourcePacks.LastOrDefault(x => x.FontBitmap != null); if (f != null) { PreloadCallback?.Invoke(f.FontBitmap, McResourcePack.BitmapFontCharacters.ToList()); } }
public bool Asynchronous => true; //ActiveResourcePacks.All(x => x.Asynchronous); public bool CheckResources(GraphicsDevice device, IProgressReceiver progressReceiver, McResourcePack.McResourcePackPreloadCallback preloadCallback) { LoadHWID(); PreloadCallback = preloadCallback; Log.Info($"Loading registries..."); progressReceiver?.UpdateProgress(0, "Loading registries..."); Registries = JsonConvert.DeserializeObject <Registries>(ReadStringResource("Alex.Resources.registries.json")); progressReceiver?.UpdateProgress(100, "Loading registries..."); string defaultResources; string defaultBedrock; if (!CheckJavaAssets(progressReceiver, out defaultResources)) { return(false); } if (!CheckBedrockAssets(progressReceiver, out defaultBedrock)) { return(false); } progressReceiver?.UpdateProgress(0, "Loading vanilla resources..."); var vanilla = LoadResourcePack(progressReceiver, new DiskFileSystem(defaultResources), preloadCallback); if (vanilla.Info != null) { vanilla.Info.Name = "Vanilla"; } ActiveResourcePacks.AddFirst((McResourcePack)vanilla); Alex.AudioEngine.Initialize((McResourcePack)vanilla); // Log.Info($"Loading bedrock resources..."); progressReceiver?.UpdateProgress(0, "Loading bedrock resources..."); var vanillaBedrock = LoadResourcePack(progressReceiver, new DiskFileSystem(defaultBedrock)); ActiveBedrockResourcePacks.AddFirst((BedrockResourcePack)vanillaBedrock); //Log.Info($"Loading known entity data..."); Storage.TryGetDirectory(Path.Combine("assets", "resourcepacks"), out DirectoryInfo root); ResourcePackDirectory = root; LoadRegistries(progressReceiver); LoadResourcePacks( device, progressReceiver, Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Value); EntityFactory.Load(this, progressReceiver); ItemFactory.Init(RegistryManager, this, progressReceiver); BlockEntityFactory.LoadResources(device, this); if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out DirectoryInfo info)) { SkinPackDirectory = info; LoadBedrockPacks(progressReceiver, info); } else { if (Storage.TryCreateDirectory(Path.Combine("assets", "bedrockpacks"))) { if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out var dirInfo)) { SkinPackDirectory = dirInfo; } } } BlockMapper.Init(progressReceiver); Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Bind(ResourcePacksChanged); _hasInit = true; var data = ReadResource("Alex.Resources.nethergames.png"); NethergamesLogo = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, Image.Load(data)); return(true); }
private static int LoadModels(IRegistryManager registryManager, ResourceManager resources, McResourcePack resourcePack, bool replace, bool reportMissing, IProgressReceiver progressReceiver) { long idCounter = 0; var blockRegistry = registryManager.GetRegistry <Block>(); var blockModelRegistry = registryManager.GetRegistry <BlockModel>(); var data = BlockData.FromJson(ResourceManager.ReadStringResource("Alex.Resources.NewBlocks.json")); int total = data.Count; int done = 0; int importCounter = 0; int multipartBased = 0; uint c = 0; foreach (var entry in data) { double percentage = 100D * ((double)done / (double)total); progressReceiver.UpdateProgress((int)percentage, $"Importing block models...", entry.Key); var variantMap = new BlockStateVariantMapper(); var defaultState = new BlockState { Name = entry.Key, VariantMapper = variantMap }; if (entry.Value.Properties != null) { foreach (var property in entry.Value.Properties) { // if (property.Key.Equals("waterlogged")) // continue; defaultState = (BlockState)defaultState.WithPropertyNoResolve(property.Key, property.Value.FirstOrDefault(), false); } } foreach (var s in entry.Value.States) { var id = s.ID; BlockState variantState = (BlockState)(defaultState).CloneSilent(); variantState.ID = id; variantState.Name = entry.Key; if (s.Properties != null) { foreach (var property in s.Properties) { //if (property.Key.Equals("waterlogged")) // continue; variantState = (Blocks.State.BlockState)variantState.WithPropertyNoResolve(property.Key, property.Value, false); } } if (!replace && RegisteredBlockStates.TryGetValue(id, out BlockState st)) { Log.Warn( $"Duplicate blockstate id (Existing: {st.Name}[{st.ToString()}] | New: {entry.Key}[{variantState.ToString()}]) "); continue; } var cachedBlockModel = GetOrCacheModel(resources, resourcePack, variantState, id, replace); if (cachedBlockModel == null) { if (reportMissing) { Log.Warn($"Missing blockmodel for blockstate {entry.Key}[{variantState.ToString()}]"); } cachedBlockModel = UnknownBlockModel; } if (variantState.IsMultiPart) { multipartBased++; } string displayName = entry.Key; IRegistryEntry <Block> registryEntry; if (!blockRegistry.TryGet(entry.Key, out registryEntry)) { registryEntry = new UnknownBlock(id); displayName = $"(MISSING) {displayName}"; registryEntry = registryEntry.WithLocation(entry.Key); // = entry.Key; } else { registryEntry = registryEntry.WithLocation(entry.Key); } var block = registryEntry.Value; variantState.Model = cachedBlockModel; variantState.Default = s.Default; if (string.IsNullOrWhiteSpace(block.DisplayName) || !block.DisplayName.Contains("minet", StringComparison.InvariantCultureIgnoreCase)) { block.DisplayName = displayName; } variantState.Block = block; block.BlockState = variantState; if (variantMap.TryAdd(variantState)) { if (!RegisteredBlockStates.TryAdd(variantState.ID, variantState)) { if (replace) { RegisteredBlockStates[variantState.ID] = variantState; importCounter++; } else { Log.Warn( $"Failed to add blockstate (variant), key already exists! ({variantState.ID} - {variantState.Name})"); } } else { importCounter++; } } else { Log.Warn( $"Could not add variant to variant map: {variantState.Name}[{variantState.ToString()}]"); } } if (!BlockStateByName.TryAdd(defaultState.Name, variantMap)) { if (replace) { BlockStateByName[defaultState.Name] = variantMap; } else { Log.Warn($"Failed to add blockstate, key already exists! ({defaultState.Name})"); } } done++; } Log.Info($"Got {multipartBased} multi-part blockstate variants!"); return(importCounter); }