void SelectMap(Map map) { StopVideo(); selectedMapPreview = Game.modData.MapCache[map.Uid]; // Cache the rules on a background thread to avoid jank new Thread(selectedMapPreview.CacheRules).Start(); var video = selectedMapPreview.Map.PreviewVideo; var videoVisible = video != null; var videoDisabled = !(videoVisible && GlobalFileSystem.Exists(video)); startVideoButton.IsVisible = () => videoVisible && !showVideoPlayer; startVideoButton.IsDisabled = () => videoDisabled; startVideoButton.OnClick = () => { showVideoPlayer = true; videoPlayer.Load(video); videoPlayer.PlayThen(StopVideo); // Mute other distracting sounds cachedSoundVolume = Sound.SoundVolume; cachedMusicVolume = Sound.MusicVolume; Sound.SoundVolume = Sound.MusicVolume = 0; }; var text = map.Description != null?map.Description.Replace("\\n", "\n") : ""; text = WidgetUtils.WrapText(text, description.Bounds.Width, descriptionFont); description.Text = text; description.Bounds.Height = descriptionFont.Measure(text).Y; descriptionPanel.ScrollToTop(); descriptionPanel.Layout.AdjustChildren(); }
void StartMissionClicked() { StopVideo(videoPlayer); if (selectedMapPreview.RuleStatus != MapRuleStatus.Cached) { return; } var gameStartVideo = selectedMapPreview.Map.Videos.GameStart; if (gameStartVideo != null && GlobalFileSystem.Exists(gameStartVideo)) { var fsPlayer = fullscreenVideoPlayer.Get <VqaPlayerWidget>("PLAYER"); fullscreenVideoPlayer.Visible = true; PlayVideo(fsPlayer, gameStartVideo, PlayingVideo.GameStart, () => { StopVideo(fsPlayer); StartMission(); }); } else { StartMission(); } }
// TODO: The package should be mounted into its own context to avoid name collisions with installed files public static bool ExtractFromPackage(string srcPath, string package, string[] files, string destPath, Action <string> onProgress, Action <string> onError) { if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } if (!GlobalFileSystem.Exists(srcPath)) { onError("Cannot find " + package); return(false); } GlobalFileSystem.Mount(srcPath); if (!GlobalFileSystem.Exists(package)) { onError("Cannot find " + package); return(false); } GlobalFileSystem.Mount(package); foreach (string s in files) { var destFile = Path.Combine(destPath, s); using (var sourceStream = GlobalFileSystem.Open(s)) using (var destStream = File.Create(destFile)) { onProgress("Extracting " + s); destStream.Write(sourceStream.ReadAllBytes()); } } return(true); }
public MusicInfo(string key, MiniYaml value) { Title = value.Value; var nd = value.ToDictionary(); if (nd.ContainsKey("Hidden")) { bool.TryParse(nd["Hidden"].Value, out Hidden); } var ext = nd.ContainsKey("Extension") ? nd["Extension"].Value : "aud"; Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key) + "." + ext; if (!GlobalFileSystem.Exists(Filename)) { return; } Exists = true; using (var s = GlobalFileSystem.Open(Filename)) { if (Filename.ToLowerInvariant().EndsWith("wav")) { Length = (int)WavLoader.WaveLength(s); } else { Length = (int)AudLoader.SoundLength(s); } } }
public void Reload() { if (!GlobalFileSystem.Exists(Filename)) { return; } Exists = true; Length = (int)AudLoader.SoundLength(GlobalFileSystem.Open(Filename)); }
void SelectMap(Map map) { selectedMapPreview = Game.ModData.MapCache[map.Uid]; // Cache the rules on a background thread to avoid jank new Thread(selectedMapPreview.CacheRules).Start(); var briefingVideo = selectedMapPreview.Map.Videos.Briefing; var briefingVideoVisible = briefingVideo != null; var briefingVideoDisabled = !(briefingVideoVisible && GlobalFileSystem.Exists(briefingVideo)); var infoVideo = selectedMapPreview.Map.Videos.BackgroundInfo; var infoVideoVisible = infoVideo != null; var infoVideoDisabled = !(infoVideoVisible && GlobalFileSystem.Exists(infoVideo)); startBriefingVideoButton.IsVisible = () => briefingVideoVisible && playingVideo != PlayingVideo.Briefing; startBriefingVideoButton.IsDisabled = () => briefingVideoDisabled || playingVideo != PlayingVideo.None; startBriefingVideoButton.OnClick = () => PlayVideo(videoPlayer, briefingVideo, PlayingVideo.Briefing, () => StopVideo(videoPlayer)); startInfoVideoButton.IsVisible = () => infoVideoVisible && playingVideo != PlayingVideo.Info; startInfoVideoButton.IsDisabled = () => infoVideoDisabled || playingVideo != PlayingVideo.None; startInfoVideoButton.OnClick = () => PlayVideo(videoPlayer, infoVideo, PlayingVideo.Info, () => StopVideo(videoPlayer)); var text = map.Description != null?map.Description.Replace("\\n", "\n") : ""; text = WidgetUtils.WrapText(text, description.Bounds.Width, descriptionFont); description.Text = text; description.Bounds.Height = descriptionFont.Measure(text).Y; descriptionPanel.ScrollToTop(); descriptionPanel.Layout.AdjustChildren(); difficultyButton.IsVisible = () => map.Options.Difficulties.Any(); if (!map.Options.Difficulties.Any()) { return; } difficulty = map.Options.Difficulties.First(); difficultyButton.OnMouseDown = _ => { var options = map.Options.Difficulties.Select(d => new DropDownOption { Title = d, IsSelected = () => difficulty == d, OnClick = () => difficulty = d }); Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) => { var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick); item.Get <LabelWidget>("LABEL").GetText = () => option.Title; return(item); }; difficultyButton.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem); }; }
public void Load() { if (!GlobalFileSystem.Exists(Filename)) return; Exists = true; using (var s = GlobalFileSystem.Open(Filename)) { if (Filename.ToLowerInvariant().EndsWith("wav")) Length = (int)WavLoader.WaveLength(s); else Length = (int)AudLoader.SoundLength(s); } }
static ISoundSource LoadSound(string filename) { if (!GlobalFileSystem.Exists(filename)) { Log.Write("sound", "LoadSound, file does not exist: {0}", filename); return(null); } if (filename.ToLowerInvariant().EndsWith("wav")) { return(LoadWave(new WavLoader(GlobalFileSystem.Open(filename)))); } return(LoadSoundRaw(AudLoader.LoadSound(GlobalFileSystem.Open(filename)))); }
public MusicInfo(string key, MiniYaml value) { Title = value.Value; var nd = value.NodesDict; var ext = nd.ContainsKey("Extension") ? nd["Extension"].Value : "aud"; Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key) + "." + ext; if (!GlobalFileSystem.Exists(Filename)) { return; } Exists = true; Length = (int)AudLoader.SoundLength(GlobalFileSystem.Open(Filename)); }
static string ResolveFilename(string name, TileSet tileSet) { var ssl = Game.ModData.SpriteSequenceLoader as TilesetSpecificSpriteSequenceLoader; var extensions = ssl != null ? new[] { ssl.TilesetExtensions[tileSet.Id], ssl.DefaultSpriteExtension }.Append(LegacyExtensions) : LegacyExtensions.AsEnumerable(); foreach (var e in extensions) { if (GlobalFileSystem.Exists(name + e)) { return(name + e); } } return(name); }
void TestAndContinue() { Ui.ResetAll(); if (!info["TestFiles"].Split(',').All(f => GlobalFileSystem.Exists(f.Trim()))) { var args = new WidgetArgs() { { "continueLoading", () => TestAndContinue() }, { "installData", info } }; Ui.OpenWindow(info["InstallerMenuWidget"], args); } else { Game.LoadShellMap(); } }
public static void TestAndContinue() { Ui.ResetAll(); var installData = modData.Manifest.ContentInstaller; if (!installData.TestFiles.All(f => GlobalFileSystem.Exists(f))) { var args = new WidgetArgs() { { "continueLoading", () => InitializeMod(Game.Settings.Game.Mod, null) }, }; if (installData.InstallerBackgroundWidget != null) { Ui.LoadWidget(installData.InstallerBackgroundWidget, Ui.Root, args); } Ui.OpenWindow(installData.InstallerMenuWidget, args); } else { LoadShellMap(); } }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.modData = modData; GlobalFileSystem.LoadFromManifest(Game.modData.Manifest); var file = new IniFile(File.Open(args[1], FileMode.Open)); var templateIndex = 0; var extension = "tem"; var terrainTypes = new Dictionary <int, string>() { { 1, "Clear" }, // Desert sand(?) { 5, "Road" }, // Paved road { 6, "Rail" }, // Monorail track { 7, "Impassable" }, // Building { 9, "Water" }, // Deep water(?) { 10, "Water" }, // Shallow water { 11, "Road" }, // Paved road (again?) { 12, "DirtRoad" }, // Dirt road { 13, "Clear" }, // Regular clear terrain { 14, "Rough" }, // Rough terrain (cracks etc) { 15, "Cliff" }, // Cliffs }; // Loop over template sets try { for (var tilesetGroupIndex = 0; ; tilesetGroupIndex++) { var section = file.GetSection("TileSet{0:D4}".F(tilesetGroupIndex)); var sectionCount = int.Parse(section.GetValue("TilesInSet", "1")); var sectionFilename = section.GetValue("FileName", ""); var sectionCategory = section.GetValue("SetName", ""); // Loop over templates for (var i = 1; i <= sectionCount; i++, templateIndex++) { var templateFilename = "{0}{1:D2}.{2}".F(sectionFilename, i, extension); if (!GlobalFileSystem.Exists(templateFilename)) { continue; } using (var s = GlobalFileSystem.Open(templateFilename)) { Console.WriteLine("\tTemplate@{0}:", templateIndex); Console.WriteLine("\t\tCategory: {0}", sectionCategory); Console.WriteLine("\t\tId: {0}", templateIndex); Console.WriteLine("\t\tImage: {0}{1:D2}", sectionFilename, i); var templateWidth = s.ReadUInt32(); var templateHeight = s.ReadUInt32(); /* var tileWidth = */ s.ReadInt32(); /* var tileHeight = */ s.ReadInt32(); var offsets = new uint[templateWidth * templateHeight]; for (var j = 0; j < offsets.Length; j++) { offsets[j] = s.ReadUInt32(); } Console.WriteLine("\t\tSize: {0}, {1}", templateWidth, templateHeight); Console.WriteLine("\t\tTiles:"); for (var j = 0; j < offsets.Length; j++) { if (offsets[j] == 0) { continue; } s.Position = offsets[j] + 40; /* var height = */ s.ReadUInt8(); var terrainType = s.ReadUInt8(); /* var rampType = */ s.ReadUInt8(); /* var height = */ s.ReadUInt8(); if (!terrainTypes.ContainsKey(terrainType)) { throw new InvalidDataException("Unknown terrain type {0} in {1}".F(terrainType, templateFilename)); } Console.WriteLine("\t\t\t{0}: {1}", j, terrainTypes[terrainType]); // Console.WriteLine("\t\t\t\tHeight: {0}", height); // Console.WriteLine("\t\t\t\tTerrainType: {0}", terrainType); // Console.WriteLine("\t\t\t\tRampType: {0}", rampType); // Console.WriteLine("\t\t\t\tLeftColor: {0},{1},{2}", s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8()); // Console.WriteLine("\t\t\t\tRightColor: {0},{1},{2}", s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8()); } } } } } catch (InvalidOperationException) { // GetSection will throw when we run out of sections to import } }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; GlobalFileSystem.LoadFromManifest(Game.ModData.Manifest); var file = new IniFile(File.Open(args[1], FileMode.Open)); var extension = args[2]; var templateIndex = 0; var terrainTypes = new string[] { "Clear", "Clear", // Note: sometimes "Ice" "Ice", "Ice", "Ice", "Road", // TS defines this as "Tunnel", but we don't need this "Rail", "Impassable", // TS defines this as "Rock", but also uses it for buildings "Impassable", "Water", "Water", // TS defines this as "Beach", but uses it for water...? "Road", "DirtRoad", // TS defines this as "Road", but we may want different speeds "Clear", "Rough", "Cliff" // TS defines this as "Rock" }; // Loop over template sets try { for (var tilesetGroupIndex = 0;; tilesetGroupIndex++) { var section = file.GetSection("TileSet{0:D4}".F(tilesetGroupIndex)); var sectionCount = int.Parse(section.GetValue("TilesInSet", "1")); var sectionFilename = section.GetValue("FileName", ""); var sectionCategory = section.GetValue("SetName", ""); // Loop over templates for (var i = 1; i <= sectionCount; i++, templateIndex++) { var templateFilename = "{0}{1:D2}.{2}".F(sectionFilename, i, extension); if (!GlobalFileSystem.Exists(templateFilename)) { continue; } using (var s = GlobalFileSystem.Open(templateFilename)) { Console.WriteLine("\tTemplate@{0}:", templateIndex); Console.WriteLine("\t\tCategory: {0}", sectionCategory); Console.WriteLine("\t\tId: {0}", templateIndex); var images = new List <string>(); images.Add("{0}{1:D2}.{2}".F(sectionFilename, i, extension)); for (var v = 'a'; v <= 'z'; v++) { var variant = "{0}{1:D2}{2}.{3}".F(sectionFilename, i, v, extension); if (GlobalFileSystem.Exists(variant)) { images.Add(variant); } } Console.WriteLine("\t\tImage: {0}", images.JoinWith(", ")); var templateWidth = s.ReadUInt32(); var templateHeight = s.ReadUInt32(); /* var tileWidth = */ s.ReadInt32(); /* var tileHeight = */ s.ReadInt32(); var offsets = new uint[templateWidth * templateHeight]; for (var j = 0; j < offsets.Length; j++) { offsets[j] = s.ReadUInt32(); } Console.WriteLine("\t\tSize: {0}, {1}", templateWidth, templateHeight); Console.WriteLine("\t\tTiles:"); for (var j = 0; j < offsets.Length; j++) { if (offsets[j] == 0) { continue; } s.Position = offsets[j] + 40; var height = s.ReadUInt8(); var terrainType = s.ReadUInt8(); var rampType = s.ReadUInt8(); if (terrainType >= terrainTypes.Length) { throw new InvalidDataException("Unknown terrain type {0} in {1}".F(terrainType, templateFilename)); } Console.WriteLine("\t\t\t{0}: {1}", j, terrainTypes[terrainType]); if (height != 0) { Console.WriteLine("\t\t\t\tHeight: {0}", height); } if (rampType != 0) { Console.WriteLine("\t\t\t\tRampType: {0}", rampType); } Console.WriteLine("\t\t\t\tLeftColor: {0},{1},{2}", s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8()); Console.WriteLine("\t\t\t\tRightColor: {0},{1},{2}", s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8()); } } } } } catch (InvalidOperationException) { // GetSection will throw when we run out of sections to import } }
public AssetBrowserLogic(Widget widget, Action onExit, World world) { this.world = world; panel = widget; assetSource = GlobalFileSystem.MountedFolders.First(); var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = assetSource != null?assetSource.Name.Replace(Platform.SupportDir, "^") : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteWidget.GetPalette = () => currentPalette; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var colorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("COLOR_MANAGER"); if (colorPreview != null) { colorPreview.Color = Game.Settings.Player.Color; } var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => currentPalette != colorPreview.Palette; colorDropdown.OnMouseDown = _ => ShowColorDropDown(colorDropdown, colorPreview, world); panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color.RGB; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnEnterKey = () => LoadAsset(filenameInput.Text); var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => currentSprites != null && currentSprites.Length > 1; } frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); frameSlider.OnChange += x => { currentFrame = (int)Math.Round(x); }; frameSlider.GetValue = () => currentFrame; var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => "{0} / {1}".F(currentFrame + 1, currentSprites.Length); } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.OnClick = () => animateFrames = true; playButton.IsVisible = () => !animateFrames; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.OnClick = () => animateFrames = false; pauseButton.IsVisible = () => animateFrames; } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.OnClick = () => { frameSlider.Value = 0; currentFrame = 0; animateFrames = false; }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.OnClick = SelectNextFrame; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.OnClick = SelectPreviousFrame; } var loadButton = panel.GetOrNull <ButtonWidget>("LOAD_BUTTON"); if (loadButton != null) { loadButton.OnClick = () => LoadAsset(filenameInput.Text); } assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } } void AddAsset(ScrollPanelWidget list, string filepath, ScrollItemWidget template) { var filename = Path.GetFileName(filepath); var item = ScrollItemWidget.Setup(template, () => currentFilename == filename, () => { filenameInput.Text = filename; LoadAsset(filename); }); item.Get <LabelWidget>("TITLE").GetText = () => filepath; list.AddChild(item); } bool LoadAsset(string filename) { if (string.IsNullOrEmpty(filename)) { return(false); } if (!GlobalFileSystem.Exists(filename)) { return(false); } currentFilename = filename; currentSprites = world.Map.SequenceProvider.SpriteLoader.LoadAllSprites(filename); currentFrame = 0; frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { Func <IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => source != null?source.Name.Replace(Platform.SupportDir, "^") : "All Packages"; return(item); }; // TODO: Re-enable "All Packages" once list generation is done in a background thread // var sources = new[] { (IFolder)null }.Concat(GlobalFileSystem.MountedFolders); var sources = GlobalFileSystem.MountedFolders; dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); availableShps.Clear(); // TODO: This is too slow to run in the main thread // var files = AssetSource != null ? AssetSource.AllFileNames() : // GlobalFileSystem.MountedFolders.SelectMany(f => f.AllFileNames()); if (assetSource == null) { return; } var files = assetSource.AllFileNames().OrderBy(s => s); foreach (var file in files) { if (AllowedExtensions.Any(ext => file.EndsWith(ext, true, CultureInfo.InvariantCulture))) { AddAsset(assetList, file, template); availableShps.Add(file); } } } bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world) { Func <PaletteFromFile, ScrollItemWidget, ScrollItemWidget> setupItem = (palette, itemTemplate) => { var name = palette.Name; var item = ScrollItemWidget.Setup(itemTemplate, () => currentPalette == name, () => currentPalette = name); item.Get <LabelWidget>("LABEL").GetText = () => name; return(item); }; var palettes = world.WorldActor.TraitsImplementing <PaletteFromFile>(); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, palettes, setupItem); return(true); }
public void StartGame(Arguments args) { Ui.ResetAll(); Game.Settings.Save(); // Check whether the mod content is installed // TODO: The installation code has finally been beaten into shape, so we can // finally move it all into the planned "Manage Content" panel in the modchooser mod. var installData = Game.ModData.Manifest.Get <ContentInstaller>(); var installModContent = !installData.TestFiles.All(f => GlobalFileSystem.Exists(f)); var installModMusic = args != null && args.Contains("Install.Music"); if (installModContent || installModMusic) { var widgetArgs = new WidgetArgs() { { "continueLoading", () => Game.InitializeMod(Game.Settings.Game.Mod, args) }, }; if (installData.BackgroundWidget != null) { Ui.LoadWidget(installData.BackgroundWidget, Ui.Root, widgetArgs); } var menu = installModContent ? installData.MenuWidget : installData.MusicMenuWidget; Ui.OpenWindow(menu, widgetArgs); return; } // Join a server directly var connect = string.Empty; if (args != null) { if (args.Contains("Launch.Connect")) { connect = args.GetValue("Launch.Connect", null); } if (args.Contains("Launch.URI")) { connect = args.GetValue("Launch.URI", null); if (connect != null) { connect = connect.Replace("openra://", ""); connect = connect.TrimEnd('/'); } } } if (!string.IsNullOrEmpty(connect)) { var parts = connect.Split(':'); if (parts.Length == 2) { var host = parts[0]; var port = Exts.ParseIntegerInvariant(parts[1]); Game.LoadShellMap(); Game.RemoteDirectConnect(host, port); return; } } // Load a replay directly var replayFilename = args != null?args.GetValue("Launch.Replay", null) : null; if (!string.IsNullOrEmpty(replayFilename)) { var replayMeta = ReplayMetadata.Read(replayFilename); if (ReplayUtils.PromptConfirmReplayCompatibility(replayMeta, Game.LoadShellMap)) { Game.JoinReplay(replayFilename); } if (replayMeta != null) { var mod = replayMeta.GameInfo.Mod; if (mod != null && mod != Game.ModData.Manifest.Mod.Id && ModMetadata.AllMods.ContainsKey(mod)) { Game.InitializeMod(mod, args); } } return; } Game.LoadShellMap(); Game.Settings.Save(); }
public AssetBrowserLogic(Widget widget, Action onExit, World world) { this.world = world; panel = widget; assetSource = GlobalFileSystem.MountedFolders.First(); var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = assetSource != null?Platform.UnresolvePath(assetSource.Name) : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteWidget.GetPalette = () => currentPalette; spriteWidget.IsVisible = () => !isVideoLoaded; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var colorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("COLOR_MANAGER"); if (colorPreview != null) { colorPreview.Color = Game.Settings.Player.Color; } var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => currentPalette != colorPreview.PaletteName; colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorPreview, world); panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color.RGB; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(filenameInput.Text); filenameInput.OnEscKey = filenameInput.YieldKeyboardFocus; var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => (currentSprites != null && currentSprites.Length > 1) || (isVideoLoaded && player != null && player.Video != null && player.Video.Frames > 1); } frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); if (frameSlider != null) { frameSlider.OnChange += x => { if (!isVideoLoaded) { currentFrame = (int)Math.Round(x); } }; frameSlider.GetValue = () => isVideoLoaded ? player.Video.CurrentFrame : currentFrame; frameSlider.IsDisabled = () => isVideoLoaded; } var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => isVideoLoaded ? "{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) : "{0} / {1}".F(currentFrame, currentSprites.Length - 1); } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.Key = new Hotkey(Keycode.SPACE, Modifiers.None); playButton.OnClick = () => { if (isVideoLoaded) { player.Play(); } else { animateFrames = true; } }; playButton.IsVisible = () => isVideoLoaded ? player.Paused : !animateFrames; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.Key = new Hotkey(Keycode.SPACE, Modifiers.None); pauseButton.OnClick = () => { if (isVideoLoaded) { player.Pause(); } else { animateFrames = false; } }; pauseButton.IsVisible = () => isVideoLoaded ? !player.Paused : animateFrames; } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.Key = new Hotkey(Keycode.RETURN, Modifiers.None); stopButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } else { frameSlider.Value = 0; currentFrame = 0; animateFrames = false; } }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.Key = new Hotkey(Keycode.RIGHT, Modifiers.None); nextButton.OnClick = () => { if (!isVideoLoaded) { nextButton.OnClick = SelectNextFrame; } }; nextButton.IsVisible = () => !isVideoLoaded; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.Key = new Hotkey(Keycode.LEFT, Modifiers.None); prevButton.OnClick = () => { if (!isVideoLoaded) { SelectPreviousFrame(); } }; prevButton.IsVisible = () => !isVideoLoaded; } assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } } Dictionary <string, bool> assetVisByName = new Dictionary <string, bool>(); bool FilterAsset(string filename) { var filter = filenameInput.Text; if (string.IsNullOrWhiteSpace(filter)) { return(true); } if (filename.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) { return(true); } return(false); } void ApplyFilter(string filename) { assetVisByName.Clear(); assetList.Layout.AdjustChildren(); assetList.ScrollToTop(); // Select the first visible var firstVisible = assetVisByName.FirstOrDefault(kvp => kvp.Value); if (firstVisible.Key != null) { LoadAsset(firstVisible.Key); } } void AddAsset(ScrollPanelWidget list, string filepath, ScrollItemWidget template) { var filename = Path.GetFileName(filepath); var item = ScrollItemWidget.Setup(template, () => currentFilename == filename, () => { LoadAsset(filename); }); item.Get <LabelWidget>("TITLE").GetText = () => filepath; item.IsVisible = () => { bool visible; if (assetVisByName.TryGetValue(filepath, out visible)) { return(visible); } visible = FilterAsset(filepath); assetVisByName.Add(filepath, visible); return(visible); }; list.AddChild(item); } bool LoadAsset(string filename) { if (isVideoLoaded) { player.Stop(); player = null; isVideoLoaded = false; } if (string.IsNullOrEmpty(filename)) { return(false); } if (!GlobalFileSystem.Exists(filename)) { return(false); } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vqa") { player = panel.Get <VqaPlayerWidget>("PLAYER"); currentFilename = filename; player.Load(filename); player.DrawOverlay = false; isVideoLoaded = true; frameSlider.MaximumValue = (float)player.Video.Frames - 1; frameSlider.Ticks = 0; return(true); } else { currentFilename = filename; currentSprites = world.Map.SequenceProvider.SpriteCache[filename]; currentFrame = 0; frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; } return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { Func <IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => source != null?Platform.UnresolvePath(source.Name) : "All Packages"; return(item); }; // TODO: Re-enable "All Packages" once list generation is done in a background thread // var sources = new[] { (IFolder)null }.Concat(GlobalFileSystem.MountedFolders); var sources = GlobalFileSystem.MountedFolders; dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); availableShps.Clear(); // TODO: This is too slow to run in the main thread // var files = AssetSource != null ? AssetSource.AllFileNames() : // GlobalFileSystem.MountedFolders.SelectMany(f => f.AllFileNames()); if (assetSource == null) { return; } var files = assetSource.AllFileNames().OrderBy(s => s); foreach (var file in files) { if (AllowedExtensions.Any(ext => file.EndsWith(ext, true, CultureInfo.InvariantCulture))) { AddAsset(assetList, file, template); availableShps.Add(file); } } } bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world) { Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (name, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => currentPalette == name, () => currentPalette = name); item.Get <LabelWidget>("LABEL").GetText = () => name; return(item); }; var palettes = world.WorldActor.TraitsImplementing <IProvidesAssetBrowserPalettes>() .SelectMany(p => p.PaletteNames); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, palettes, setupItem); return(true); } }