public CursorProvider(ModData modData) { var sequenceFiles = modData.Manifest.Cursors; cursors = new Dictionary<string, CursorSequence>(); palettes = new Cache<string, PaletteReference>(CreatePaletteReference); var sequences = new MiniYaml(null, sequenceFiles.Select(s => MiniYaml.FromFile(s)).Aggregate(MiniYaml.MergeLiberal)); var shadowIndex = new int[] { }; if (sequences.NodesDict.ContainsKey("ShadowIndex")) { Array.Resize(ref shadowIndex, shadowIndex.Length + 1); Exts.TryParseIntegerInvariant(sequences.NodesDict["ShadowIndex"].Value, out shadowIndex[shadowIndex.Length - 1]); } palette = new HardwarePalette(); foreach (var p in sequences.NodesDict["Palettes"].Nodes) palette.AddPalette(p.Key, new Palette(GlobalFileSystem.Open(p.Value.Value), shadowIndex), false); var spriteLoader = new SpriteLoader(new string[0], new SheetBuilder(SheetType.Indexed)); foreach (var s in sequences.NodesDict["Cursors"].Nodes) LoadSequencesForCursor(spriteLoader, s.Key, s.Value); palette.Initialize(); }
public PreReleaseWarningPrompt(Widget widget, World world, ModData modData) { if (!promptAccepted && modData.Manifest.Metadata.Version != "{DEV_VERSION}") widget.Get<ButtonWidget>("CONTINUE_BUTTON").OnClick = () => ShowMainMenu(world); else ShowMainMenu(world); }
public void Run(ModData modData, string[] args) { Game.ModData = modData; map = new Map(modData, modData.ModFiles.OpenPackage(args[1])); Console.WriteLine("Resizing map {0} from {1} to {2},{3}", map.Title, map.MapSize, width, height); map.Resize(width, height); var forRemoval = new List<MiniYamlNode>(); foreach (var kv in map.ActorDefinitions) { var actor = new ActorReference(kv.Value.Value, kv.Value.ToDictionary()); var location = actor.InitDict.Get<LocationInit>().Value(null); if (!map.Contains(location)) { Console.WriteLine("Removing actor {0} located at {1} due being outside of the new map boundaries.".F(actor.Type, location)); forRemoval.Add(kv); } } foreach (var kv in forRemoval) map.ActorDefinitions.Remove(kv); map.Save((IReadWritePackage)map.Package); }
protected override string GetSpriteSrc(ModData modData, TileSet tileSet, string sequence, string animation, string sprite, Dictionary<string, MiniYaml> d) { var loader = (TilesetSpecificSpriteSequenceLoader)Loader; var spriteName = sprite ?? sequence; if (LoadField<bool>(d, "UseTilesetCode", false)) { string code; if (loader.TilesetCodes.TryGetValue(ResolveTilesetId(tileSet, d), out code)) spriteName = spriteName.Substring(0, 1) + code + spriteName.Substring(2, spriteName.Length - 2); } if (LoadField<bool>(d, "AddExtension", true)) { var useTilesetExtension = LoadField<bool>(d, "UseTilesetExtension", false); string tilesetExtension; if (useTilesetExtension && loader.TilesetExtensions.TryGetValue(ResolveTilesetId(tileSet, d), out tilesetExtension)) return spriteName + tilesetExtension; return spriteName + loader.DefaultSpriteExtension; } return spriteName; }
static void ProcessYaml(ModData modData, Map map, MiniYaml yaml, int engineDate, UpgradeAction processYaml) { if (yaml == null) return; if (yaml.Value != null) { var files = FieldLoader.GetValue<string[]>("value", yaml.Value); foreach (var filename in files) { var fileNodes = MiniYaml.FromStream(map.Open(filename), filename); processYaml(modData, engineDate, ref fileNodes, null, 0); // HACK: Obtain the writable save path using knowledge of the underlying filesystem workings var packagePath = filename; var package = map.Package; if (filename.Contains("|")) modData.DefaultFileSystem.TryGetPackageContaining(filename, out package, out packagePath); ((IReadWritePackage)package).Update(packagePath, Encoding.ASCII.GetBytes(fileNodes.WriteToString())); } } processYaml(modData, engineDate, ref yaml.Nodes, null, 1); }
public void Run(ModData modData, string[] args) { for (int i = 1; i < args.Length;) { var parts = args[i].Split(Comma, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 3) { foreach (var c in parts) Console.Write(byte.Parse(c).ToString("X2")); } else { Console.Write(byte.Parse(parts[1]).ToString("X2")); Console.Write(byte.Parse(parts[2]).ToString("X2")); Console.Write(byte.Parse(parts[3]).ToString("X2")); var alpha = byte.Parse(parts[0]); if (alpha < 255) Console.Write(alpha.ToString("X2")); } if (++i != args.Length) Console.Write(", "); else Console.WriteLine(); } }
public ScrollItemWidget(ModData modData) : base(modData) { IsVisible = () => false; VisualHeight = 0; IgnoreChildMouseOver = true; }
public CursorProvider(ModData modData) { var fileSystem = modData.DefaultFileSystem; var sequenceYaml = MiniYaml.Merge(modData.Manifest.Cursors.Select( s => MiniYaml.FromStream(fileSystem.Open(s), s))); var shadowIndex = new int[] { }; var nodesDict = new MiniYaml(null, sequenceYaml).ToDictionary(); if (nodesDict.ContainsKey("ShadowIndex")) { Array.Resize(ref shadowIndex, shadowIndex.Length + 1); Exts.TryParseIntegerInvariant(nodesDict["ShadowIndex"].Value, out shadowIndex[shadowIndex.Length - 1]); } var palettes = new Dictionary<string, ImmutablePalette>(); foreach (var p in nodesDict["Palettes"].Nodes) palettes.Add(p.Key, new ImmutablePalette(fileSystem.Open(p.Value.Value), shadowIndex)); Palettes = palettes.AsReadOnly(); var frameCache = new FrameCache(fileSystem, modData.SpriteLoaders); var cursors = new Dictionary<string, CursorSequence>(); foreach (var s in nodesDict["Cursors"].Nodes) foreach (var sequence in s.Value.Nodes) cursors.Add(sequence.Key, new CursorSequence(frameCache, sequence.Key, s.Key, s.Value.Value, sequence.Value)); Cursors = cursors.AsReadOnly(); }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; try { Log.AddChannel("debug", null); Log.AddChannel("perf", null); // bind some nonfatal error handling into FieldLoader, so we don't just *explode*. ObjectCreator.MissingTypeAction = s => EmitError("Missing Type: {0}".F(s)); FieldLoader.UnknownFieldAction = (s, f) => EmitError("FieldLoader: Missing field `{0}` on `{1}`".F(s, f.Name)); IEnumerable<Map> maps; if (args.Length < 2) { Game.ModData.MapCache.LoadMaps(); maps = Game.ModData.MapCache .Where(m => m.Status == MapStatus.Available) .Select(m => m.Map); } else maps = new[] { new Map(args[1]) }; foreach (var testMap in maps) { Console.WriteLine("Testing map: {0}".F(testMap.Title)); testMap.PreloadRules(); foreach (var customPassType in Game.ModData.ObjectCreator .GetTypesImplementing<ILintPass>()) { try { var customPass = (ILintPass)Game.ModData.ObjectCreator .CreateBasic(customPassType); customPass.Run(EmitError, EmitWarning, testMap); } catch (Exception e) { EmitError("{0} failed with exception: {0}".F(customPassType, e)); } } } if (errors > 0) { Console.WriteLine("Errors: {0}", errors); Environment.Exit(1); } } catch (Exception e) { EmitError("Failed with exception: {0}".F(e)); Environment.Exit(1); } }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; var package = modData.ModFiles.OpenWritablePackage(args[1]); var engineDate = Exts.ParseIntegerInvariant(args[2]); UpgradeMap(modData, package, engineDate); }
public MultiplayerLogic(Widget widget, ModData modData, Action onStart, Action onExit, string directConnectHost, int directConnectPort) { this.modData = modData; this.onStart = onStart; this.onExit = onExit; incompatibleVersionColor = ChromeMetrics.Get<Color>("IncompatibleVersionColor"); incompatibleGameColor = ChromeMetrics.Get<Color>("IncompatibleGameColor"); incompatibleProtectedGameColor = ChromeMetrics.Get<Color>("IncompatibleProtectedGameColor"); protectedGameColor = ChromeMetrics.Get<Color>("ProtectedGameColor"); waitingGameColor = ChromeMetrics.Get<Color>("WaitingGameColor"); incompatibleWaitingGameColor = ChromeMetrics.Get<Color>("IncompatibleWaitingGameColor"); gameStartedColor = ChromeMetrics.Get<Color>("GameStartedColor"); incompatibleGameStartedColor = ChromeMetrics.Get<Color>("IncompatibleGameStartedColor"); LoadBrowserPanel(widget); LoadDirectConnectPanel(widget); LoadCreateServerPanel(widget); // Filter and refresh buttons act on the browser panel, // but remain visible (disabled) on the other panels var refreshButton = widget.Get<ButtonWidget>("REFRESH_BUTTON"); refreshButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser; var filtersButton = widget.Get<DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON"); filtersButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser; var browserTab = widget.Get<ButtonWidget>("BROWSER_TAB"); browserTab.IsHighlighted = () => panel == PanelType.Browser; browserTab.OnClick = () => panel = PanelType.Browser; var directConnectTab = widget.Get<ButtonWidget>("DIRECTCONNECT_TAB"); directConnectTab.IsHighlighted = () => panel == PanelType.DirectConnect; directConnectTab.OnClick = () => panel = PanelType.DirectConnect; var createServerTab = widget.Get<ButtonWidget>("CREATE_TAB"); createServerTab.IsHighlighted = () => panel == PanelType.CreateServer; createServerTab.OnClick = () => panel = PanelType.CreateServer; widget.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); }; Game.LoadWidget(null, "GLOBALCHAT_PANEL", widget.Get("GLOBALCHAT_ROOT"), new WidgetArgs()); RefreshServerList(); if (directConnectHost != null) { // The connection window must be opened at the end of the tick for the widget hierarchy to // work out, but we also want to prevent the server browser from flashing visible for one tick. widget.Visible = false; Game.RunAfterTick(() => { ConnectionLogic.Connect(directConnectHost, directConnectPort, "", OpenLobby, DoNothing); widget.Visible = true; }); } }
public ReplayBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart) { panel = widget; this.modData = modData; this.onStart = onStart; Game.BeforeGameStart += OnGameStart; playerList = panel.Get<ScrollPanelWidget>("PLAYER_LIST"); playerHeader = playerList.Get<ScrollItemWidget>("HEADER"); playerTemplate = playerList.Get<ScrollItemWidget>("TEMPLATE"); playerList.RemoveChildren(); panel.Get<ButtonWidget>("CANCEL_BUTTON").OnClick = () => { cancelLoadingReplays = true; Ui.CloseWindow(); onExit(); }; replayList = panel.Get<ScrollPanelWidget>("REPLAY_LIST"); var template = panel.Get<ScrollItemWidget>("REPLAY_TEMPLATE"); var mod = modData.Manifest; var dir = Platform.ResolvePath("^", "Replays", mod.Id, mod.Metadata.Version); if (Directory.Exists(dir)) ThreadPool.QueueUserWorkItem(_ => LoadReplays(dir, template)); var watch = panel.Get<ButtonWidget>("WATCH_BUTTON"); watch.IsDisabled = () => selectedReplay == null || selectedReplay.GameInfo.MapPreview.Status != MapStatus.Available; watch.OnClick = () => { WatchReplay(); }; panel.Get("REPLAY_INFO").IsVisible = () => selectedReplay != null; var preview = panel.Get<MapPreviewWidget>("MAP_PREVIEW"); preview.SpawnOccupants = () => selectedSpawns; preview.Preview = () => selectedReplay != null ? selectedReplay.GameInfo.MapPreview : null; var titleLabel = panel.GetOrNull<LabelWidget>("MAP_TITLE"); if (titleLabel != null) { titleLabel.IsVisible = () => selectedReplay != null; var font = Game.Renderer.Fonts[titleLabel.Font]; var title = new CachedTransform<MapPreview, string>(m => WidgetUtils.TruncateText(m.Title, titleLabel.Bounds.Width, font)); titleLabel.GetText = () => title.Update(selectedReplay.GameInfo.MapPreview); } var type = panel.GetOrNull<LabelWidget>("MAP_TYPE"); if (type != null) { var mapType = new CachedTransform<MapPreview, string>(m => m.Categories.FirstOrDefault() ?? ""); type.GetText = () => mapType.Update(selectedReplay.GameInfo.MapPreview); } panel.Get<LabelWidget>("DURATION").GetText = () => WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds); SetupFilters(); SetupManagement(); }
public void Run(ModData modData, string[] args) { Game.modData = modData; var table = ActorStatsExport.GenerateTable(); var filename = "{0}-mod-dps.csv".F(Game.modData.Manifest.Mod.Id); using (var outfile = new StreamWriter(filename)) outfile.Write(table.ToCharacterSeparatedValues(";", true)); Console.WriteLine("{0} has been saved.".F(filename)); Console.WriteLine("Open as values separated by semicolon."); }
public CncMainMenuLogic(Widget widget, World world, ModData modData) : base(widget, world, modData) { var shellmapDecorations = widget.Get("SHELLMAP_DECORATIONS"); shellmapDecorations.IsVisible = () => menuType != MenuType.None && Game.Settings.Game.ShowShellmap; shellmapDecorations.Get<ImageWidget>("RECBLOCK").IsVisible = () => world.WorldTick / 25 % 2 == 0; var shellmapDisabledDecorations = widget.Get("SHELLMAP_DISABLED_DECORATIONS"); shellmapDisabledDecorations.IsVisible = () => !Game.Settings.Game.ShowShellmap; }
public void Init(ModData modData, Dictionary<string, string> info) { var res = Game.Renderer.Resolution; bounds = new Rectangle(0, 0, res.Width, res.Height); using (var stream = modData.DefaultFileSystem.Open(info["Image"])) { var sheet = new Sheet(SheetType.BGRA, stream); sprite = new Sprite(sheet, new Rectangle(0, 0, 1024, 480), TextureChannel.Alpha); } }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.modData = modData; var rules = Game.modData.RulesetCache.LoadDefaultRules(); var map = LegacyMapImporter.Import(args[1], modData.Manifest.Mod.Id, rules, e => Console.WriteLine(e)); var dest = map.Title + ".oramap"; map.Save(dest); Console.WriteLine(dest + " saved."); }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.modData = modData; Game.modData.MapCache.LoadMaps(); var engineDate = Exts.ParseIntegerInvariant(args[1]); Console.WriteLine("Processing Rules:"); foreach (var filename in Game.modData.Manifest.Rules) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeActorRules(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Weapons:"); foreach (var filename in Game.modData.Manifest.Weapons) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeWeaponRules(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Tilesets:"); foreach (var filename in Game.modData.Manifest.TileSets) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeTileset(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Maps:"); var maps = Game.modData.MapCache .Where(m => m.Status == MapStatus.Available) .Select(m => m.Map); foreach (var map in maps) { Console.WriteLine("\t" + map.Path); UpgradeRules.UpgradeActorRules(engineDate, ref map.RuleDefinitions, null, 0); UpgradeRules.UpgradeWeaponRules(engineDate, ref map.WeaponDefinitions, null, 0); map.Save(map.Path); } }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.modData = modData; var map = new Map(args[1]); var engineDate = Exts.ParseIntegerInvariant(args[2]); UpgradeRules.UpgradeWeaponRules(engineDate, ref map.WeaponDefinitions, null, 0); UpgradeRules.UpgradeActorRules(engineDate, ref map.RuleDefinitions, null, 0); map.Save(args[1]); }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; var rules = Game.ModData.RulesetCache.Load(); var map = LegacyMapImporter.Import(args[1], modData.Manifest.Mod.Id, rules, Console.WriteLine); var fileName = Path.GetFileNameWithoutExtension(args[1]); var dest = fileName + ".oramap"; map.Save(dest); Console.WriteLine(dest + " saved."); }
void IUtilityCommand.Run(ModData modData, string[] args) { Game.ModData = modData; var map = new Map(modData, modData.ModFiles.OpenPackage(args[1])); MergeAndPrint(map, "Rules", map.RuleDefinitions); MergeAndPrint(map, "Sequences", map.SequenceDefinitions); MergeAndPrint(map, "VoxelSequences", map.VoxelSequenceDefinitions); MergeAndPrint(map, "Weapons", map.WeaponDefinitions); MergeAndPrint(map, "Voices", map.VoiceDefinitions); MergeAndPrint(map, "Music", map.MusicDefinitions); MergeAndPrint(map, "Notifications", map.NotificationDefinitions); }
public void Run(ModData modData, string[] args) { var files = args.Skip(1); foreach (var f in files) { var src = modData.DefaultFileSystem.Open(f); if (src == null) throw new InvalidOperationException("File not found: {0}".F(f)); var data = src.ReadAllBytes(); File.WriteAllBytes(f, data); Console.WriteLine(f + " saved."); } }
public TilesetSpecificSpriteSequenceLoader(ModData modData) : base(modData) { var metadata = modData.Manifest.Get<SpriteSequenceFormat>().Metadata; MiniYaml yaml; if (metadata.TryGetValue("DefaultSpriteExtension", out yaml)) DefaultSpriteExtension = yaml.Value; if (metadata.TryGetValue("TilesetExtensions", out yaml)) TilesetExtensions = yaml.ToDictionary(kv => kv.Value); if (metadata.TryGetValue("TilesetCodes", out yaml)) TilesetCodes = yaml.ToDictionary(kv => kv.Value); }
public void Run(ModData modData, string[] args) { Game.ModData = modData; var map = new Map(args[1]); GlobalFileSystem.UnmountAll(); foreach (var dir in Game.ModData.Manifest.Folders) GlobalFileSystem.Mount(dir); var minimap = Minimap.RenderMapPreview(map.Rules.TileSets[map.Tileset], map, true); var dest = Path.GetFileNameWithoutExtension(args[1]) + ".png"; minimap.Save(dest); Console.WriteLine(dest + " saved."); }
public void Run(ModData modData, string[] args) { var inputFiles = GlobArgs(args).OrderBy(a => a).ToList(); var dest = inputFiles[0].Split('-').First() + ".shp"; var frames = inputFiles.Select(a => PngLoader.Load(a)); var size = frames.First().Size; if (frames.Any(f => f.Size != size)) throw new InvalidOperationException("All frames must be the same size"); using (var destStream = File.Create(dest)) ShpTDSprite.Write(destStream, size, frames.Select(f => ToBytes(f))); Console.WriteLine(dest + " saved."); }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; var rules = Ruleset.LoadDefaultsForTileSet(modData, "ARRAKIS"); var map = D2kMapImporter.Import(args[1], modData.Manifest.Mod.Id, args[2], rules); if (map == null) return; var dest = Path.GetFileNameWithoutExtension(args[1]) + ".oramap"; var package = new ZipFile(modData.DefaultFileSystem, dest, true); map.Save(package); Console.WriteLine(dest + " saved."); }
public ButtonWidget(ModData modData) { ModRules = modData.DefaultRules; GetText = () => Text; GetColor = () => TextColor; GetColorDisabled = () => TextColorDisabled; GetContrastColor = () => ContrastColor; OnMouseUp = _ => OnClick(); OnKeyPress = _ => OnClick(); IsDisabled = () => Disabled; IsHighlighted = () => Highlighted; GetTooltipText = () => TooltipText; tooltipContainer = Exts.Lazy(() => Ui.Root.Get<TooltipContainerWidget>(TooltipContainer)); }
public void Run(ModData modData, string[] args) { var remap = new Dictionary<int, int>(); /* the first 4 entries are fixed */ for (var i = 0; i < 4; i++) remap[i] = i; var srcMod = args[1].Split(':')[0]; Game.ModData = new ModData(srcMod); GlobalFileSystem.LoadFromManifest(Game.ModData.Manifest); var srcRules = Game.ModData.RulesetCache.Load(); var srcPaletteInfo = srcRules.Actors["player"].TraitInfo<PlayerColorPaletteInfo>(); var srcRemapIndex = srcPaletteInfo.RemapIndex; var destMod = args[2].Split(':')[0]; Game.ModData = new ModData(destMod); GlobalFileSystem.LoadFromManifest(Game.ModData.Manifest); var destRules = Game.ModData.RulesetCache.Load(); var destPaletteInfo = destRules.Actors["player"].TraitInfo<PlayerColorPaletteInfo>(); var destRemapIndex = destPaletteInfo.RemapIndex; var shadowIndex = new int[] { }; // the remap range is always 16 entries, but their location and order changes for (var i = 0; i < 16; i++) remap[PlayerColorRemap.GetRemapIndex(srcRemapIndex, i)] = PlayerColorRemap.GetRemapIndex(destRemapIndex, i); // map everything else to the best match based on channel-wise distance var srcPalette = new ImmutablePalette(args[1].Split(':')[1], shadowIndex); var destPalette = new ImmutablePalette(args[2].Split(':')[1], shadowIndex); for (var i = 0; i < Palette.Size; i++) if (!remap.ContainsKey(i)) remap[i] = Enumerable.Range(0, Palette.Size) .Where(a => !remap.ContainsValue(a)) .MinBy(a => ColorDistance(destPalette[a], srcPalette[i])); using (var s = File.OpenRead(args[3])) using (var destStream = File.Create(args[4])) { var srcImage = new ShpTDSprite(s); ShpTDSprite.Write(destStream, srcImage.Size, srcImage.Frames.Select(im => im.Data.Select(px => (byte)remap[px]).ToArray())); } }
public void Run(ModData modData, string[] args) { Console.WriteLine(".TH OPENRA 6"); Console.WriteLine(".SH NAME"); Console.WriteLine("openra \\- An Open Source modernization of the early 2D Command & Conquer games."); Console.WriteLine(".SH SYNOPSIS"); Console.WriteLine(".B openra"); Console.WriteLine("[\\fB\\Game.Mod=\\fR\\fImodchooser\\fR]"); Console.WriteLine(".SH DESCRIPTION"); Console.WriteLine(".B openra"); Console.WriteLine("starts the game."); Console.WriteLine(".SH OPTIONS"); var sections = Game.Settings.Sections; sections.Add("Launch", new LaunchArguments(new Arguments(new string[0]))); foreach (var section in sections.OrderBy(s => s.Key)) { var fields = section.Value.GetType().GetFields(); foreach (var field in fields) { if (!field.HasAttribute<DescAttribute>()) continue; Console.WriteLine(".TP"); Console.Write(".BR {0}.{1}=".F(section.Key, field.Name)); var value = field.GetValue(section.Value); if (value != null && !value.ToString().StartsWith("System.")) Console.WriteLine("\\fI{0}\\fR".F(value)); else Console.WriteLine(); var lines = field.GetCustomAttributes<DescAttribute>(false).SelectMany(d => d.Lines); foreach (var line in lines) Console.WriteLine(line); } } Console.WriteLine(".SH FILES"); Console.WriteLine("Settings are stored in the ~/.openra user folder."); Console.WriteLine(".SH BUGS"); Console.WriteLine("Known issues are tracked at http://bugs.openra.net"); Console.WriteLine(".SH COPYRIGHT"); Console.WriteLine("Copyright 2007-2015 The OpenRA Developers (see AUTHORS)"); Console.WriteLine("This manual is part of OpenRA, which is free software. It is GNU GPL v3 licensed. See COPYING for details."); }
static void Main(string[] args) { if (args.Length == 0) { PrintUsage(null); return; } AppDomain.CurrentDomain.AssemblyResolve += GlobalFileSystem.ResolveAssembly; Log.AddChannel("perf", null); Log.AddChannel("debug", null); var modName = args[0]; if (!ModMetadata.AllMods.Keys.Contains(modName)) { PrintUsage(null); return; } Game.InitializeSettings(Arguments.Empty); var modData = new ModData(modName); args = args.Skip(1).ToArray(); var actions = new Dictionary<string, Action<ModData, string[]>>(); foreach (var commandType in modData.ObjectCreator.GetTypesImplementing<IUtilityCommand>()) { var command = (IUtilityCommand)Activator.CreateInstance(commandType); actions.Add(command.Name, command.Run); } try { var action = Exts.WithDefault((a, b) => PrintUsage(actions), () => actions[args[0]]); action(modData, args); } catch (Exception e) { Log.AddChannel("utility", "utility.log"); Log.Write("utility", "Received args: {0}", args.JoinWith(" ")); Log.Write("utility", "{0}", e); Console.WriteLine("Error: Utility application crashed. See utility.log for details"); throw; } }
public void Run(ModData modData, string[] args) { var replay = ReplayMetadata.Read(args[1]); var info = replay.GameInfo; var lines = FieldSaver.Save(info).ToLines(replay.FilePath); foreach (var line in lines) Console.WriteLine(line); Console.WriteLine("\tPlayers:"); var playerCount = 0; foreach (var p in info.Players) { var playerLines = FieldSaver.Save(p).ToLines("{0}".F(playerCount++)); foreach (var line in playerLines) Console.WriteLine("\t\t" + line); } }
public DropDownButtonWidget(ModData modData) : base(modData) { }
public override void enter(ModData e = null) { sceneMgr = GameManager.Instance.root.CreateSceneManager(Mogre.SceneType.ST_GENERIC, "ModChooserSceneMgr"); ColourValue cvAmbineLight = new ColourValue(0.7f, 0.7f, 0.7f); sceneMgr.AmbientLight = cvAmbineLight; camera = sceneMgr.CreateCamera("ModChooserCam"); camera.SetPosition(0, 25, -50); Mogre.Vector3 vectorCameraLookat = new Mogre.Vector3(0, 0, 0); camera.LookAt(vectorCameraLookat); camera.NearClipDistance = 1; camera.AspectRatio = GameManager.Instance.viewport.ActualWidth / GameManager.Instance.viewport.ActualHeight; GameManager.Instance.viewport.Camera = camera; modDisplayDataList.Clear(); mods = ModManager.Instance.GetInstalledMods(); foreach (var pair in mods) { if (pair.Value.MetaData.DisplayInChooser) { ModDisplayData modDisplayData = new ModDisplayData(pair.Key); modDisplayData.Name = pair.Value.MetaData.Name; modDisplayData.Desc = pair.Value.MetaData.Description; modDisplayData.Thumb = pair.Value.MetaData.Thumb; modDisplayDataList.Add(modDisplayData); } } UIManager.Instance.DestroyAllWidgets(); modTitle = UIManager.Instance.CreateLabel(UIWidgetLocation.TL_CENTER, "ModTitle", "Mod Info"); modTitle.setCaption("Mod Info"); modDescBox = UIManager.Instance.CreateTextBox(UIWidgetLocation.TL_CENTER, "ModInfo", "Mod Info", 250, 208); modDescBox.setCaption("Mod Info"); modChooserMenu = UIManager.Instance.CreateThickSelectMenu(UIWidgetLocation.TL_CENTER, "SelMod", "Select Mod", 250, 10); modChooserMenu.setCaption("Select Mod"); modChooserMenu.SetItems(modDisplayDataList.Select(o => o.Name).ToList()); modSlider = UIManager.Instance.CreateThickSlider(UIWidgetLocation.TL_CENTER, "ModSlider", "Slider Mods", 250, 80, 0, 0, 0); modSlider.setCaption("Slider Mods"); if (modDisplayDataList.Count > 0) { modTitle.setCaption(modChooserMenu.getSelectedItem()); } UIManager.Instance.CreateSeparator(UIWidgetLocation.TL_RIGHT, "LogoSep"); var btnPlay = UIManager.Instance.CreateButton(UIWidgetLocation.TL_RIGHT, "Play", LocateSystem.Instance.GetLocalizedString(Localization.LocateFileType.GameString, "str_play"), 160); var btnMods = UIManager.Instance.CreateButton(UIWidgetLocation.TL_RIGHT, "Mods", LocateSystem.Instance.GetLocalizedString(Localization.LocateFileType.GameString, "str_mods"), 160); var btnQuit = UIManager.Instance.CreateButton(UIWidgetLocation.TL_RIGHT, "Quit", LocateSystem.Instance.GetLocalizedString(Localization.LocateFileType.GameString, "str_quit"), 160); btnPlay.OnClick += (o) => { string modID = modDisplayDataList.Where(a => a.Name == selectedModName).First().ID; GameManager.Instance.loadingData = new LoadingData(LoadingType.LOADING_MOD, "Loading Mod...Please wait", modID, "MainMenu"); changeAppState(findByName("Loading")); }; btnMods.OnClick += (o) => { ScreenManager.Instance.ChangeScreen("ModBrowser"); }; btnQuit.OnClick += (o) => { isQuit = true; }; setupModMenu(); GameManager.Instance.mouse.MouseMoved += Mouse_MouseMoved; GameManager.Instance.mouse.MousePressed += Mouse_MousePressed; GameManager.Instance.mouse.MouseReleased += Mouse_MouseReleased; GameManager.Instance.root.FrameRenderingQueued += FrameRenderingQueued; }
public Server(IPEndPoint endpoint, ServerSettings settings, ModData modData, bool dedicated) { Log.AddChannel("server", "server.log"); listener = new TcpListener(endpoint); listener.Start(); var localEndpoint = (IPEndPoint)listener.LocalEndpoint; Ip = localEndpoint.Address; Port = localEndpoint.Port; Dedicated = dedicated; Settings = settings; Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name); ModData = modData; playerDatabase = modData.Manifest.Get <PlayerDatabase>(); randomSeed = (int)DateTime.Now.ToBinary(); if (UPnP.Status == UPnPStatus.Enabled) { UPnP.ForwardPort(Settings.ListenPort, Settings.ListenPort).Wait(); } foreach (var trait in modData.Manifest.ServerTraits) { serverTraits.Add(modData.ObjectCreator.CreateObject <ServerTrait>(trait)); } serverTraits.TrimExcess(); LobbyInfo = new Session { GlobalSettings = { RandomSeed = randomSeed, Map = settings.Map, ServerName = settings.Name, EnableSingleplayer = settings.EnableSingleplayer || !dedicated, GameUid = Guid.NewGuid().ToString(), Dedicated = dedicated } }; new Thread(_ => { foreach (var t in serverTraits.WithInterface <INotifyServerStart>()) { t.ServerStarted(this); } Log.Write("server", "Initial mod: {0}", ModData.Manifest.Id); Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map); var timeout = serverTraits.WithInterface <ITick>().Min(t => t.TickTimeout); for (;;) { var checkRead = new List <Socket>(); if (State == ServerState.WaitingPlayers) { checkRead.Add(listener.Server); } checkRead.AddRange(Conns.Select(c => c.Socket)); checkRead.AddRange(PreConns.Select(c => c.Socket)); var localTimeout = waitingForAuthenticationCallback > 0 ? 100000 : timeout; if (checkRead.Count > 0) { Socket.Select(checkRead, null, null, localTimeout); } if (State == ServerState.ShuttingDown) { EndGame(); break; } foreach (var s in checkRead) { if (s == listener.Server) { AcceptConnection(); continue; } var preConn = PreConns.SingleOrDefault(c => c.Socket == s); if (preConn != null) { preConn.ReadData(this); continue; } var conn = Conns.SingleOrDefault(c => c.Socket == s); if (conn != null) { conn.ReadData(this); } } delayedActions.PerformActions(0); foreach (var t in serverTraits.WithInterface <ITick>()) { t.Tick(this); } if (State == ServerState.ShuttingDown) { EndGame(); if (UPnP.Status == UPnPStatus.Enabled) { UPnP.RemovePortForward().Wait(); } break; } } foreach (var t in serverTraits.WithInterface <INotifyServerShutdown>()) { t.ServerShutdown(this); } PreConns.Clear(); Conns.Clear(); try { listener.Stop(); } catch { } }) { IsBackground = true }.Start(); }
static void ApplyRules(ModData modData, IEnumerable <UpdateRule> rules, bool skipMaps) { Console.WriteLine(); var logWriter = File.CreateText("update.log"); logWriter.AutoFlush = true; var externalFilenames = new HashSet <string>(); foreach (var rule in rules) { var manualSteps = new List <string>(); var allFiles = new YamlFileSet(); LogLine(logWriter, "{0}: {1}", rule.GetType().Name, rule.Name); try { Log(logWriter, " Updating mod... "); manualSteps.AddRange(UpdateUtils.UpdateMod(modData, rule, out allFiles, externalFilenames)); LogLine(logWriter, "COMPLETE"); } catch (Exception ex) { Console.WriteLine("FAILED"); LogLine(logWriter); LogLine(logWriter, " The automated changes for this rule were not applied because of an error."); LogLine(logWriter, " After the issue reported below is resolved you should run the updater"); LogLine(logWriter, " with SOURCE set to {0} to retry these changes", rule.GetType().Name); LogLine(logWriter); LogLine(logWriter, " The exception reported was:"); LogLine(logWriter, " " + ex.ToString().Replace("\n", "\n ")); continue; } Log(logWriter, " Updating system maps... "); if (!skipMaps) { var mapsFailed = false; var mapExternalFilenames = new HashSet <string>(); foreach (var package in modData.MapCache.EnumerateMapPackagesWithoutCaching()) { try { YamlFileSet mapFiles; var mapSteps = UpdateUtils.UpdateMap(modData, package, rule, out mapFiles, mapExternalFilenames); allFiles.AddRange(mapFiles); if (mapSteps.Any()) { manualSteps.Add("Map: " + package.Name + ":\n" + UpdateUtils.FormatMessageList(mapSteps)); } } catch (Exception ex) { LogLine(logWriter, "FAILED"); LogLine(logWriter); LogLine(logWriter, " The automated changes for this rule were not applied because of an error."); LogLine(logWriter, " After the issue reported below is resolved you should run the updater"); LogLine(logWriter, " with SOURCE set to {0} to retry these changes", rule.GetType().Name); LogLine(logWriter); LogLine(logWriter, " The map that caused the error was:"); LogLine(logWriter, " " + package.Name); LogLine(logWriter); LogLine(logWriter, " The exception reported was:"); LogLine(logWriter, " " + ex.ToString().Replace("\n", "\n ")); mapsFailed = true; break; } } if (mapsFailed) { continue; } LogLine(logWriter, "COMPLETE"); } else { LogLine(logWriter, "SKIPPED"); } // Files are saved after each successful automated rule update allFiles.Save(); if (manualSteps.Any()) { LogLine(logWriter, " Manual changes are required to complete this update:"); LogLine(logWriter, UpdateUtils.FormatMessageList(manualSteps, 1)); } LogLine(logWriter); } if (externalFilenames.Any()) { LogLine(logWriter, "The following external mod files have been ignored:"); LogLine(logWriter, UpdateUtils.FormatMessageList(externalFilenames)); LogLine(logWriter, "These files should be updated by running --update-mod on the referenced mod(s)"); LogLine(logWriter); } Console.WriteLine("Semi-automated update complete."); Console.WriteLine("Please review the messages above for any manual actions that must be applied."); Console.WriteLine("These messages have also been written to an update.log file in the current directory."); }
public void Run(ModData modData, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = modData; Game.ModData.MapCache.LoadMaps(); var engineDate = Exts.ParseIntegerInvariant(args[1]); Console.WriteLine("Processing Rules:"); foreach (var filename in Game.ModData.Manifest.Rules) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeActorRules(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Weapons:"); foreach (var filename in Game.ModData.Manifest.Weapons) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeWeaponRules(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Tilesets:"); foreach (var filename in Game.ModData.Manifest.TileSets) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeTileset(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Cursors:"); foreach (var filename in Game.ModData.Manifest.Cursors) { Console.WriteLine("\t" + filename); var yaml = MiniYaml.FromFile(filename); UpgradeRules.UpgradeCursors(engineDate, ref yaml, null, 0); using (var file = new StreamWriter(filename)) file.WriteLine(yaml.WriteToString()); } Console.WriteLine("Processing Maps:"); var maps = Game.ModData.MapCache .Where(m => m.Status == MapStatus.Available) .Select(m => m.Map); foreach (var map in maps) { Console.WriteLine("\t" + map.Path); UpgradeRules.UpgradeActorRules(engineDate, ref map.RuleDefinitions, null, 0); UpgradeRules.UpgradeWeaponRules(engineDate, ref map.WeaponDefinitions, null, 0); UpgradeRules.UpgradePlayers(engineDate, ref map.PlayerDefinitions, null, 0); UpgradeRules.UpgradeActors(engineDate, ref map.ActorDefinitions, null, 0); map.Save(map.Path); } }
public override IEnumerable <string> BeforeUpdate(ModData modData) { updated = false; yield break; }
public MuteHotkeyLogic(Widget widget, ModData modData, Dictionary <string, MiniYaml> logicArgs) : base(widget, modData, "MuteAudioKey", "GLOBAL_KEYHANDLER", logicArgs) { }
protected virtual string GetSpriteSrc(ModData modData, TileSet tileSet, string sequence, string animation, string sprite, Dictionary <string, MiniYaml> d) { return(sprite ?? sequence); }
public DefaultSpriteSequence(ModData modData, TileSet tileSet, SpriteCache cache, ISpriteSequenceLoader loader, string sequence, string animation, MiniYaml info) { Name = animation; Loader = loader; var d = info.ToDictionary(); try { Start = LoadField(d, "Start", 0); ShadowStart = LoadField(d, "ShadowStart", -1); ShadowZOffset = LoadField(d, "ShadowZOffset", DefaultShadowSpriteZOffset).Length; ZOffset = LoadField(d, "ZOffset", WDist.Zero).Length; ZRamp = LoadField(d, "ZRamp", 0); Tick = LoadField(d, "Tick", 40); transpose = LoadField(d, "Transpose", false); Frames = LoadField <int[]>(d, "Frames", null); useClassicFacingFudge = LoadField(d, "UseClassicFacingFudge", false); var flipX = LoadField(d, "FlipX", false); var flipY = LoadField(d, "FlipY", false); Facings = LoadField(d, "Facings", 1); if (Facings < 0) { reverseFacings = true; Facings = -Facings; } if (useClassicFacingFudge && Facings != 32) { throw new InvalidOperationException( "{0}: Sequence {1}.{2}: UseClassicFacingFudge is only valid for 32 facings" .F(info.Nodes[0].Location, sequence, animation)); } var offset = LoadField(d, "Offset", float3.Zero); var blendMode = LoadField(d, "BlendMode", BlendMode.Alpha); MiniYaml combine; if (d.TryGetValue("Combine", out combine)) { var combined = Enumerable.Empty <Sprite>(); foreach (var sub in combine.Nodes) { var sd = sub.Value.ToDictionary(); // Allow per-sprite offset, flipping, start, and length var subStart = LoadField(sd, "Start", 0); var subOffset = LoadField(sd, "Offset", float3.Zero); var subFlipX = LoadField(sd, "FlipX", false); var subFlipY = LoadField(sd, "FlipY", false); var subSrc = GetSpriteSrc(modData, tileSet, sequence, animation, sub.Key, sd); var subSprites = cache[subSrc].Select( s => new Sprite(s.Sheet, FlipRectangle(s.Bounds, subFlipX, subFlipY), ZRamp, new float3(subFlipX ? -s.Offset.X : s.Offset.X, subFlipY ? -s.Offset.Y : s.Offset.Y, s.Offset.Z) + subOffset + offset, s.Channel, blendMode)); var subLength = 0; MiniYaml subLengthYaml; if (sd.TryGetValue("Length", out subLengthYaml) && subLengthYaml.Value == "*") { subLength = subSprites.Count() - subStart; } else { subLength = LoadField(sd, "Length", 1); } combined = combined.Concat(subSprites.Skip(subStart).Take(subLength)); } sprites = combined.ToArray(); } else { // Apply offset to each sprite in the sequence // Different sequences may apply different offsets to the same frame var src = GetSpriteSrc(modData, tileSet, sequence, animation, info.Value, d); sprites = cache[src].Select( s => new Sprite(s.Sheet, FlipRectangle(s.Bounds, flipX, flipY), ZRamp, new float3(flipX ? -s.Offset.X : s.Offset.X, flipY ? -s.Offset.Y : s.Offset.Y, s.Offset.Z) + offset, s.Channel, blendMode)).ToArray(); } var depthSprite = LoadField <string>(d, "DepthSprite", null); if (!string.IsNullOrEmpty(depthSprite)) { var depthSpriteFrame = LoadField(d, "DepthSpriteFrame", 0); var depthOffset = LoadField(d, "DepthSpriteOffset", float2.Zero); var depthSprites = cache.AllCached(depthSprite) .Select(s => s[depthSpriteFrame]); sprites = sprites.Select(s => { // The depth sprite must live on the same sheet as the main sprite var ds = depthSprites.FirstOrDefault(dss => dss.Sheet == s.Sheet); if (ds == null) { // The sequence has probably overflowed onto a new sheet. // Allocating a new depth sprite on this sheet will almost certainly work ds = cache.Reload(depthSprite)[depthSpriteFrame]; depthSprites = cache.AllCached(depthSprite) .Select(ss => ss[depthSpriteFrame]); // If that doesn't work then we may be referencing a cached sprite from an earlier sheet // TODO: We could try and reallocate the main sprite, but that requires more complicated code and a perf hit // We'll only cross that bridge if this becomes a problem in reality if (ds.Sheet != s.Sheet) { throw new SheetOverflowException("Cross-sheet depth sprite reference: {0}.{1}: {2}"); } } var cw = (ds.Bounds.Left + ds.Bounds.Right) / 2 + (int)(s.Offset.X + depthOffset.X); var ch = (ds.Bounds.Top + ds.Bounds.Bottom) / 2 + (int)(s.Offset.Y + depthOffset.Y); var w = s.Bounds.Width / 2; var h = s.Bounds.Height / 2; var r = Rectangle.FromLTRB(cw - w, ch - h, cw + w, ch + h); return(new SpriteWithSecondaryData(s, r, ds.Channel)); }).ToArray(); } MiniYaml length; if (d.TryGetValue("Length", out length) && length.Value == "*") { Length = sprites.Length - Start; } else { Length = LoadField(d, "Length", 1); } // Plays the animation forwards, and then in reverse if (LoadField(d, "Reverses", false)) { var frames = Frames ?? Exts.MakeArray(Length, i => Start + i); Frames = frames.Concat(frames.Skip(1).Take(frames.Length - 2).Reverse()).ToArray(); Length = 2 * Length - 2; } Stride = LoadField(d, "Stride", Length); if (Length > Stride) { throw new InvalidOperationException( "{0}: Sequence {1}.{2}: Length must be <= stride" .F(info.Nodes[0].Location, sequence, animation)); } if (Frames != null && Length > Frames.Length) { throw new InvalidOperationException( "{0}: Sequence {1}.{2}: Length must be <= Frames.Length" .F(info.Nodes[0].Location, sequence, animation)); } if (Start < 0 || Start + Facings * Stride > sprites.Length) { throw new InvalidOperationException( "{5}: Sequence {0}.{1} uses frames [{2}..{3}], but only 0..{4} actually exist" .F(sequence, animation, Start, Start + Facings * Stride - 1, sprites.Length - 1, info.Nodes[0].Location)); } if (ShadowStart + Facings * Stride > sprites.Length) { throw new InvalidOperationException( "{5}: Sequence {0}.{1}'s shadow frames use frames [{2}..{3}], but only [0..{4}] actually exist" .F(sequence, animation, ShadowStart, ShadowStart + Facings * Stride - 1, sprites.Length - 1, info.Nodes[0].Location)); } var boundSprites = SpriteBounds(sprites, Frames, Start, Facings, Length); if (ShadowStart > 0) { boundSprites = boundSprites.Concat(SpriteBounds(sprites, Frames, ShadowStart, Facings, Length)); } if (boundSprites.Any()) { Bounds = boundSprites.First(); foreach (var b in boundSprites.Skip(1)) { Bounds = Rectangle.Union(Bounds, b); } } } catch (FormatException f) { throw new FormatException("Failed to parse sequences for {0}.{1} at {2}:\n{3}".F(sequence, animation, info.Nodes[0].Location, f)); } }
public DefaultSpriteSequenceLoader(ModData modData) { }
public virtual ISpriteSequence CreateSequence(ModData modData, TileSet tileSet, SpriteCache cache, string sequence, string animation, MiniYaml info) { return(new DefaultSpriteSequence(modData, tileSet, cache, this, sequence, animation, info)); }
public ScrollItemWidget(ModData modData) : base(modData) { IsVisible = () => false; VisualHeight = 0; }
public CheckboxWidget(ModData modData) : base(modData) { GetCheckType = () => CheckType; }
public Server(IPEndPoint endpoint, ServerSettings settings, ModData modData) { Log.AddChannel("server", "server.log"); internalState = ServerState.WaitingPlayers; listener = new TcpListener(endpoint); listener.Start(); var localEndpoint = (IPEndPoint)listener.LocalEndpoint; Ip = localEndpoint.Address; Port = localEndpoint.Port; Settings = settings; ModData = modData; randomSeed = (int)DateTime.Now.ToBinary(); if (Settings.AllowPortForward) { UPnP.ForwardPort(); } foreach (var trait in modData.Manifest.ServerTraits) { serverTraits.Add(modData.ObjectCreator.CreateObject <ServerTrait>(trait)); } LobbyInfo = new Session(); LobbyInfo.GlobalSettings.RandomSeed = randomSeed; LobbyInfo.GlobalSettings.Map = settings.Map; LobbyInfo.GlobalSettings.ServerName = settings.Name; LobbyInfo.GlobalSettings.Dedicated = settings.Dedicated; FieldLoader.Load(LobbyInfo.GlobalSettings, modData.Manifest.LobbyDefaults); foreach (var t in serverTraits.WithInterface <INotifyServerStart>()) { t.ServerStarted(this); } Log.Write("server", "Initial mod: {0}", ModData.Manifest.Mod.Id); Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map); new Thread(_ => { var timeout = serverTraits.WithInterface <ITick>().Min(t => t.TickTimeout); for (;;) { var checkRead = new List <Socket>(); checkRead.Add(listener.Server); foreach (var c in Conns) { checkRead.Add(c.socket); } foreach (var c in PreConns) { checkRead.Add(c.socket); } Socket.Select(checkRead, null, null, timeout); if (State == ServerState.ShuttingDown) { EndGame(); break; } foreach (var s in checkRead) { if (s == listener.Server) { AcceptConnection(); } else if (PreConns.Count > 0) { var p = PreConns.SingleOrDefault(c => c.socket == s); if (p != null) { p.ReadData(this); } } else if (Conns.Count > 0) { var conn = Conns.SingleOrDefault(c => c.socket == s); if (conn != null) { conn.ReadData(this); } } } foreach (var t in serverTraits.WithInterface <ITick>()) { t.Tick(this); } if (State == ServerState.ShuttingDown) { EndGame(); if (Settings.AllowPortForward) { UPnP.RemovePortforward(); } break; } } foreach (var t in serverTraits.WithInterface <INotifyServerShutdown>()) { t.ServerShutdown(this); } PreConns.Clear(); Conns.Clear(); try { listener.Stop(); } catch { } }) { IsBackground = true }.Start(); }
public GameSaveBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart, bool isSavePanel, World world) { panel = widget; this.modData = modData; this.onStart = onStart; this.onExit = onExit; this.isSavePanel = isSavePanel; Game.BeforeGameStart += OnGameStart; panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); }; gameList = panel.Get <ScrollPanelWidget>("GAME_LIST"); var gameTemplate = panel.Get <ScrollItemWidget>("GAME_TEMPLATE"); var newTemplate = panel.Get <ScrollItemWidget>("NEW_TEMPLATE"); var mod = modData.Manifest; baseSavePath = Platform.ResolvePath(Platform.SupportDirPrefix, "Saves", mod.Id, mod.Metadata.Version); // Avoid filename conflicts when creating new saves if (isSavePanel) { panel.Get("SAVE_TITLE").IsVisible = () => true; defaultSaveFilename = world.Map.Title; var filenameAttempt = 0; while (true) { if (!File.Exists(Path.Combine(baseSavePath, defaultSaveFilename + ".orasav"))) { break; } defaultSaveFilename = world.Map.Title + " ({0})".F(++filenameAttempt); } var saveButton = panel.Get <ButtonWidget>("SAVE_BUTTON"); saveButton.OnClick = () => { Save(world); }; saveButton.IsVisible = () => true; var saveWidgets = panel.Get("SAVE_WIDGETS"); saveTextField = saveWidgets.Get <TextFieldWidget>("SAVE_TEXTFIELD"); gameList.Bounds.Height -= saveWidgets.Bounds.Height; saveWidgets.IsVisible = () => true; } else { panel.Get("LOAD_TITLE").IsVisible = () => true; var loadButton = panel.Get <ButtonWidget>("LOAD_BUTTON"); loadButton.IsVisible = () => true; loadButton.IsDisabled = () => selectedSave == null; loadButton.OnClick = () => { Load(); }; } if (Directory.Exists(baseSavePath)) { LoadGames(gameTemplate, newTemplate); } var renameButton = panel.Get <ButtonWidget>("RENAME_BUTTON"); renameButton.IsDisabled = () => selectedSave == null; renameButton.OnClick = () => { var initialName = Path.GetFileNameWithoutExtension(selectedSave); var invalidChars = Path.GetInvalidFileNameChars(); ConfirmationDialogs.TextInputPrompt( "Rename Save", "Enter a new file name:", initialName, onAccept: newName => Rename(initialName, newName), onCancel: null, acceptText: "Rename", cancelText: null, inputValidator: newName => { if (newName == initialName) { return(false); } if (string.IsNullOrWhiteSpace(newName)) { return(false); } if (newName.IndexOfAny(invalidChars) >= 0) { return(false); } if (File.Exists(Path.Combine(baseSavePath, newName))) { return(false); } return(true); }); }; var deleteButton = panel.Get <ButtonWidget>("DELETE_BUTTON"); deleteButton.IsDisabled = () => selectedSave == null; deleteButton.OnClick = () => { ConfirmationDialogs.ButtonPrompt( title: "Delete selected game save?", text: "Delete '{0}'?".F(Path.GetFileNameWithoutExtension(selectedSave)), onConfirm: () => { Delete(selectedSave); if (!games.Any() && !isSavePanel) { Ui.CloseWindow(); onExit(); } else { SelectFirstVisible(); } }, confirmText: "Delete", onCancel: () => { }); }; var deleteAllButton = panel.Get <ButtonWidget>("DELETE_ALL_BUTTON"); deleteAllButton.IsDisabled = () => !games.Any(); deleteAllButton.OnClick = () => { ConfirmationDialogs.ButtonPrompt( title: "Delete all game saves?", text: "Delete {0} game saves?".F(games.Count), onConfirm: () => { foreach (var s in games.ToList()) { Delete(s); } Ui.CloseWindow(); onExit(); }, confirmText: "Delete All", onCancel: () => { }); }; SelectFirstVisible(); }
public ModContentLogic(Widget widget, ModData modData, Manifest mod, ModContent content, Action onCancel) { this.content = content; var panel = widget.Get("CONTENT_PANEL"); var modObjectCreator = new ObjectCreator(mod, Game.Mods); var modPackageLoaders = modObjectCreator.GetLoaders <IPackageLoader>(mod.PackageFormats, "package"); var modFileSystem = new FS(mod.Id, Game.Mods, modPackageLoaders); modFileSystem.LoadFromManifest(mod); var sourceYaml = MiniYaml.Load(modFileSystem, content.Sources, null); foreach (var s in sourceYaml) { sources.Add(s.Key, new ModContent.ModSource(s.Value)); } var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null); foreach (var d in downloadYaml) { downloads.Add(d.Key, new ModContent.ModDownload(d.Value)); } modFileSystem.UnmountAll(); scrollPanel = panel.Get <ScrollPanelWidget>("PACKAGES"); template = scrollPanel.Get <ContainerWidget>("PACKAGE_TEMPLATE"); var headerTemplate = panel.Get <LabelWidget>("HEADER_TEMPLATE"); var headerLines = !string.IsNullOrEmpty(content.HeaderMessage) ? content.HeaderMessage.Replace("\\n", "\n").Split('\n') : new string[0]; var headerHeight = 0; foreach (var l in headerLines) { var line = (LabelWidget)headerTemplate.Clone(); line.GetText = () => l; line.Bounds.Y += headerHeight; panel.AddChild(line); headerHeight += headerTemplate.Bounds.Height; } panel.Bounds.Height += headerHeight; panel.Bounds.Y -= headerHeight / 2; scrollPanel.Bounds.Y += headerHeight; var discButton = panel.Get <ButtonWidget>("CHECK_DISC_BUTTON"); discButton.Bounds.Y += headerHeight; discButton.IsVisible = () => discAvailable; discButton.OnClick = () => Ui.OpenWindow("DISC_INSTALL_PANEL", new WidgetArgs { { "afterInstall", () => { } }, { "sources", sources }, { "content", content } }); var backButton = panel.Get <ButtonWidget>("BACK_BUTTON"); backButton.Bounds.Y += headerHeight; backButton.OnClick = () => { Ui.CloseWindow(); onCancel(); }; PopulateContentList(); Game.RunAfterTick(Ui.ResetTooltips); }
public override IEnumerable <string> BeforeUpdate(ModData modData) { harvesters.Clear(); yield break; }
protected void Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = ModData = utility.ModData; var filename = args[1]; using (var stream = File.OpenRead(filename)) { var file = new IniFile(stream); var basic = file.GetSection("Basic"); var player = basic.GetValue("Player", string.Empty); if (!string.IsNullOrEmpty(player)) { singlePlayer = !player.StartsWith("Multi"); } var mapSection = file.GetSection("Map"); var format = GetMapFormatVersion(basic); ValidateMapFormat(format); // The original game isn't case sensitive, but we are. var tileset = GetTileset(mapSection).ToUpperInvariant(); if (!ModData.DefaultTileSets.ContainsKey(tileset)) { throw new InvalidDataException("Unknown tileset {0}".F(tileset)); } Map = new Map(ModData, ModData.DefaultTileSets[tileset], MapSize, MapSize) { Title = basic.GetValue("Name", Path.GetFileNameWithoutExtension(filename)), Author = "Westwood Studios", }; Map.RequiresMod = ModData.Manifest.Id; SetBounds(Map, mapSection); ReadPacks(file, filename); ReadTrees(file); LoadVideos(file, "BASIC"); LoadBriefing(file); ReadActors(file); LoadSmudges(file, "SMUDGE"); var waypoints = file.GetSection("Waypoints"); LoadWaypoints(waypoints); // Create default player definitions only if there are no players to import MapPlayers = new MapPlayers(Map.Rules, Players.Count == 0 ? spawnCount : 0); foreach (var p in Players) { LoadPlayer(file, p); } Map.PlayerDefinitions = MapPlayers.ToMiniYaml(); } Map.FixOpenAreas(); var dest = Path.GetFileNameWithoutExtension(args[1]) + ".oramap"; Map.Save(ZipFileLoader.Create(dest, new Folder("."))); Console.WriteLine(dest + " saved."); }
void ILintRulesPass.Run(Action <string> emitError, Action <string> emitWarning, ModData modData, Ruleset rules) { Run(emitError, modData, rules); }
void ILintServerMapPass.Run(Action <string> emitError, Action <string> emitWarning, ModData modData, MapPreview map, Ruleset mapRules) { Run(emitError, modData, mapRules); }