public void StartGame(Arguments args) { Launch = new LaunchArguments(args); Ui.ResetAll(); Game.Settings.Save(); if (Launch.Benchmark) { Log.AddChannel("cpu", "cpu.csv"); Log.Write("cpu", "tick;time [ms]"); Log.AddChannel("render", "render.csv"); Log.Write("render", "frame;time [ms]"); Console.WriteLine("Saving benchmark data into {0}".F(Path.Combine(Platform.SupportDir, "Logs"))); Game.BenchmarkMode = true; } // Join a server directly var connect = Launch.GetConnectAddress(); 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 if (!string.IsNullOrEmpty(Launch.Replay)) { var replayMeta = ReplayMetadata.Read(Launch.Replay); if (ReplayUtils.PromptConfirmReplayCompatibility(replayMeta, Game.LoadShellMap)) { Game.JoinReplay(Launch.Replay); } 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 void TestMethod2() { var modSearchPaths = new string[] { "C:\\work\\games\\OpenRAModMaker\\OpenRA\\mods" }; var explicitModPaths = new string[] { "ra" }; Log.AddChannel("debug", "c:\\temp\\openra.log"); Log.AddChannel("perf", "c:\\temp\\openra-perf.log"); var currentDirectory = "C:\\work\\games\\OpenRAModMaker\\OpenRA"; Environment.CurrentDirectory = currentDirectory; Directory.SetCurrentDirectory(currentDirectory); Game.Settings = new Settings(Platform.ResolvePath(Path.Combine(Platform.SupportDirPrefix, "settings.yaml")), new Arguments { }); var mods = new InstalledMods(modSearchPaths, explicitModPaths); var raMod = mods["ra"]; var modData = new ModData(raMod, mods, true); var sequences = modData.DefaultSequences; var snowSeqProv = sequences["SNOW"]; var harv = snowSeqProv.GetSequence("harv", "icon"); int[] ChannelMasks = { 2, 1, 0, 3 }; var palette = new ImmutablePalette("C:\\work\\games\\OpenRAModMaker\\OpenRA\\mods\\cnc\\bits\\snow.pal", new int[0]); //png.Save($"C:\\temp\\harv\\harv-0.png"); for (int i = 0; i < 50; i++) { var sprite = harv.GetSprite(i); var sheet = sprite.Sheet; sheet.AsPng((TextureChannel)ChannelMasks[2], palette).Save($"C:\\temp\\harv\\harv-{i}.png"); } }
static void Main(string[] args) { if (args.Length == 0) { PrintUsage(); return; } AppDomain.CurrentDomain.AssemblyResolve += GlobalFileSystem.ResolveAssembly; Log.LogPath = Platform.SupportDir + "Logs" + Path.DirectorySeparatorChar; Log.AddChannel("perf", null); try { var action = Exts.WithDefault(_ => PrintUsage(), () => Actions[args[0]]); action(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; } }
static void Main(string[] args) { var actions = new Dictionary <string, Action <string[]> >() { { "--settings-value", Command.Settings }, { "--shp", Command.ConvertPngToShp }, { "--png", Command.ConvertShpToPng }, { "--fromd2", Command.ConvertFormat2ToFormat80 }, { "--extract", Command.ExtractFiles }, { "--tmp-png", Command.ConvertTmpToPng }, { "--remap", Command.RemapShp }, }; if (args.Length == 0) { PrintUsage(); return; } Log.LogPath = Platform.SupportDir + "Logs" + Path.DirectorySeparatorChar; try { var action = Exts.WithDefault(_ => PrintUsage(), () => actions[args[0]]); action(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; } }
bool LoadUnit(string unitname) { if (isVideoLoaded) { player.Stop(); player = null; isVideoLoaded = false; } if (string.IsNullOrEmpty(unitname)) { return(false); } isLoadError = false; try { currentUnitname = unitname; currentVoxel = (Voxel)world.ModelCache.GetModelSequence(currentUnitname, "idle"); } catch (Exception ex) { isLoadError = true; Log.AddChannel("vxlbrowser", "vxlbrowser.log"); Log.Write("vxlbrowser", "Error reading {0}:{3} {1}{3}{2}", unitname, ex.Message, ex.StackTrace, Environment.NewLine); return(false); } return(true); }
public LuaScriptContext() { Log.AddChannel("lua", "lua.log"); Log.Write("lua", "Creating Lua script context"); Lua = new Lua(); Lua.HookException += OnLuaException; functionCache = new Cache <string, LuaFunction>(Lua.GetFunction); }
internal void DumpSyncReport(int frame, IEnumerable <FrameData.ClientOrder> orders) { var reportName = "syncreport-" + DateTime.UtcNow.ToString("yyyy-MM-ddTHHmmssZ", CultureInfo.InvariantCulture) + ".log"; Log.AddChannel("sync", reportName); foreach (var r in syncReports) { if (r.Frame == frame) { var mod = Game.ModData.Manifest.Metadata; Log.AddChannel("sync", "syncreport.log"); Log.Write("sync", "Player: {0} ({1} {2} {3})", Game.Settings.Player.Name, Platform.CurrentPlatform, Environment.OSVersion, Platform.RuntimeVersion); Log.Write("sync", "Game ID: {0} (Mod: {1} at Version {2})", orderManager.LobbyInfo.GlobalSettings.GameUid, mod.Title, mod.Version); Log.Write("sync", "Sync for net frame {0} -------------", r.Frame); Log.Write("sync", "SharedRandom: {0} (#{1})", r.SyncedRandom, r.TotalCount); Log.Write("sync", "Synced Traits:"); foreach (var a in r.Traits) { Log.Write("sync", "\t {0} {1} {2} {3} ({4})".F(a.ActorID, a.Type, a.Owner, a.Trait, a.Hash)); var nvp = a.NamesValues; for (int i = 0; i < nvp.First.Length; i++) { if (nvp.Second[i] != null) { Log.Write("sync", "\t\t {0}: {1}".F(nvp.First[i], nvp.Second[i])); } } } Log.Write("sync", "Synced Effects:"); foreach (var e in r.Effects) { Log.Write("sync", "\t {0} ({1})", e.Name, e.Hash); var nvp = e.NamesValues; for (int i = 0; i < nvp.First.Length; i++) { if (nvp.Second[i] != null) { Log.Write("sync", "\t\t {0}: {1}".F(nvp.First[i], nvp.Second[i])); } } } Log.Write("sync", "Orders Issued:"); foreach (var o in orders) { Log.Write("sync", "\t {0}", o.ToString()); } return; } } Log.Write("sync", "No sync report available!"); }
static void Main(string[] args) { Log.AddChannel("perf", null); Application.CurrentCulture = CultureInfo.InvariantCulture; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1(args)); }
static void Main(string[] args) { var arguments = new Arguments(args); Log.AddChannel("debug", "dedicated-debug.log"); Log.AddChannel("perf", "dedicated-perf.log"); Log.AddChannel("server", "dedicated-server.log"); Log.AddChannel("nat", "dedicated-nat.log"); // Special case handling of Game.Mod argument: if it matches a real filesystem path // then we use this to override the mod search path, and replace it with the mod id var modArgument = arguments.GetValue("Game.Mod", null); var explicitModPaths = new string[0]; if (modArgument != null && (File.Exists(modArgument) || Directory.Exists(modArgument))) { explicitModPaths = new[] { modArgument }; arguments.ReplaceValue("Game.Mod", Path.GetFileNameWithoutExtension(modArgument)); } // HACK: The engine code assumes that Game.Settings is set. // This isn't nearly as bad as ModData, but is still not very nice. Game.InitializeSettings(arguments); var settings = Game.Settings.Server; var mod = Game.Settings.Game.Mod; var modSearchPaths = new[] { Path.Combine(".", "mods"), Path.Combine("^", "mods") }; var mods = new InstalledMods(modSearchPaths, explicitModPaths); // HACK: The engine code *still* assumes that Game.ModData is set var modData = Game.ModData = new ModData(mods[mod], mods); modData.MapCache.LoadMaps(); settings.Map = modData.MapCache.ChooseInitialMap(settings.Map, new MersenneTwister()); Console.WriteLine("[{0}] Starting dedicated server for mod: {1}", DateTime.Now.ToString(settings.TimestampFormat), mod); while (true) { var server = new Server(new IPEndPoint(IPAddress.Any, settings.ListenPort), settings, modData, true); while (true) { Thread.Sleep(1000); if (server.State == ServerState.GameStarted && server.Conns.Count < 1) { Console.WriteLine("[{0}] No one is playing, shutting down...", DateTime.Now.ToString(settings.TimestampFormat)); server.Shutdown(); break; } } Console.WriteLine("[{0}] Starting a new server instance...", DateTime.Now.ToString(settings.TimestampFormat)); } }
public static void WriteGraphicsLog(string message) { Log.AddChannel("graphics", "graphics.log"); Log.Write("graphics", message); Log.Write("graphics", ""); Log.Write("graphics", "OpenGL Information:"); Log.Write("graphics", "Vendor: {0}", Gl.glGetString(Gl.GL_VENDOR)); Log.Write("graphics", "Renderer: {0}", Gl.glGetString(Gl.GL_RENDERER)); Log.Write("graphics", "GL Version: {0}", Gl.glGetString(Gl.GL_VERSION)); Log.Write("graphics", "Shader Version: {0}", Gl.glGetString(Gl.GL_SHADING_LANGUAGE_VERSION)); Log.Write("graphics", "Available extensions:"); Log.Write("graphics", Gl.glGetString(Gl.GL_EXTENSIONS)); }
public void Write() { foreach (var sample in samples) { var name = sample.Key; Log.AddChannel(name, $"{prefix}{name}.csv"); Log.Write(name, "tick,time [ms]"); foreach (var point in sample.Value) { Log.Write(name, $"{point.Tick},{point.Value}"); } } }
public void Write() { foreach (var sample in samples) { var name = sample.Key; Log.AddChannel(name, "{0}{1}.csv".F(prefix, name)); Log.Write(name, "tick,time [ms]"); foreach (var point in sample.Value) { Log.Write(name, "{0},{1}".F(point.Tick, point.Value)); } } }
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; } }
private void Initialize() { var tempPath = Path.GetTempPath(); Log.AddChannel("debug", $"{tempPath}\\openra.log"); Log.AddChannel("perf", $"{tempPath}\\openra-perf.log"); Environment.CurrentDirectory = workingDirectoryPath; palette = new ImmutablePalette(palettePath, new int[0]); Game.Settings = new Settings(Platform.ResolvePath(Path.Combine(Platform.SupportDirPrefix, "settings.yaml")), new Arguments { }); var mods = new InstalledMods(new string[] { modsDirectoryPath }, new string[] { modId }); var mod = mods[modId]; modData = new ModData(mod, mods, true); }
public void TestMethod3() { var modSearchPaths = new string[] { "C:\\work\\games\\OpenRAModMaker\\OpenRA\\mods" }; var explicitModPaths = new string[] { "ra" }; Log.AddChannel("debug", "c:\\temp\\openra.log"); Log.AddChannel("perf", "c:\\temp\\openra-perf.log"); var currentDirectory = "C:\\work\\games\\OpenRAModMaker\\OpenRA"; Environment.CurrentDirectory = currentDirectory; Directory.SetCurrentDirectory(currentDirectory); var palette = new ImmutablePalette("C:\\work\\games\\OpenRAModMaker\\OpenRA\\mods\\cnc\\bits\\snow.pal", new int[0]); int[] ChannelMasks = { 2, 1, 0, 3 }; Game.Settings = new Settings(Platform.ResolvePath(Path.Combine(Platform.SupportDirPrefix, "settings.yaml")), new Arguments { }); var mods = new InstalledMods(modSearchPaths, explicitModPaths); var raMod = mods["ra"]; var modData = new ModData(raMod, mods, true); var defaultSequences = modData.DefaultSequences; var sequences = defaultSequences["SNOW"]; var harv = sequences.GetSequence("harv", "harvest"); sequences.Preload(); for (int i = 0; i < harv.Length; i++) { var sprite = harv.GetSprite(i); byte[] spriteBytes = new byte[sprite.Bounds.Width * sprite.Bounds.Height]; GetSpriteData(sprite, spriteBytes); var bitmap = ToBitmap(spriteBytes, sprite.Bounds.Width, sprite.Bounds.Height, palette); bitmap.Save("c:\\temp\\harv\\to-bmp.bmp"); //var png = new Png(pngBytes, sprite.Bounds.Width, sprite.Bounds.Height); //var png = ToPng(pngBytes, sprite.Bounds.Width, sprite.Bounds.Height); //var png = ToPng(pngBytes, sprite.Bounds.Width, sprite.Bounds.Height, sprite.Channel, palette); //png.Save($"c:\\temp\\harv\\from-raw-bytes-{i}.png"); //Assert.IsNotNull(png); } }
public InstallFromDiscLogic(Widget widget, ModContent content, Dictionary <string, ModContent.ModSource> sources, Action afterInstall) { this.content = content; this.sources = sources; Log.AddChannel("install", "install.log"); // this.afterInstall = afterInstall; panel = widget.Get("DISC_INSTALL_PANEL"); titleLabel = panel.Get <LabelWidget>("TITLE"); primaryButton = panel.Get <ButtonWidget>("PRIMARY_BUTTON"); secondaryButton = panel.Get <ButtonWidget>("SECONDARY_BUTTON"); // Progress view progressContainer = panel.Get("PROGRESS"); progressContainer.IsVisible = () => visible == Mode.Progress; progressBar = panel.Get <ProgressBarWidget>("PROGRESS_BAR"); progressLabel = panel.Get <LabelWidget>("PROGRESS_MESSAGE"); progressLabel.IsVisible = () => visible == Mode.Progress; // Message view messageContainer = panel.Get("MESSAGE"); messageContainer.IsVisible = () => visible == Mode.Message; messageLabel = messageContainer.Get <LabelWidget>("MESSAGE_MESSAGE"); // List view listContainer = panel.Get("LIST"); listContainer.IsVisible = () => visible == Mode.List; listPanel = listContainer.Get <ScrollPanelWidget>("LIST_PANEL"); listHeaderTemplate = listPanel.Get("LIST_HEADER_TEMPLATE"); listTemplate = listPanel.Get <LabelWidget>("LIST_TEMPLATE"); listPanel.RemoveChildren(); listLabel = listContainer.Get <LabelWidget>("LIST_MESSAGE"); DetectContentDisks(); }
static void Main(string[] args) { Log.AddChannel("debug", "dedicated-debug.log"); Log.AddChannel("perf", "dedicated-perf.log"); Log.AddChannel("server", "dedicated-server.log"); Log.AddChannel("nat", "dedicated-nat.log"); // HACK: The engine code assumes that Game.Settings is set. // This isn't nearly as bad as ModData, but is still not very nice. Game.InitializeSettings(new Arguments(args)); var settings = Game.Settings.Server; // HACK: The engine code *still* assumes that Game.ModData is set var mod = Game.Settings.Game.Mod; var modData = Game.ModData = new ModData(mod, false); modData.MapCache.LoadMaps(); settings.Map = modData.MapCache.ChooseInitialMap(settings.Map, new MersenneTwister()); Console.WriteLine("[{0}] Starting dedicated server for mod: {1}", DateTime.Now.ToString(settings.TimestampFormat), mod); while (true) { var server = new Server(new IPEndPoint(IPAddress.Any, settings.ListenPort), settings, modData, true); while (true) { Thread.Sleep(1000); if (server.State == ServerState.GameStarted && server.Conns.Count < 1) { Console.WriteLine("[{0}] No one is playing, shutting down...", DateTime.Now.ToString(settings.TimestampFormat)); server.Shutdown(); break; } } Console.WriteLine("[{0}] Starting a new server instance...", DateTime.Now.ToString(settings.TimestampFormat)); } }
public DownloadPackageLogic(Widget widget, ModContent.ModDownload download, Action onSuccess) { this.download = download; this.onSuccess = onSuccess; Log.AddChannel("install", "install.log"); panel = widget.Get("PACKAGE_DOWNLOAD_PANEL"); progressBar = panel.Get <ProgressBarWidget>("PROGRESS_BAR"); var statusLabel = panel.Get <LabelWidget>("STATUS_LABEL"); var statusFont = Game.Renderer.Fonts[statusLabel.Font]; var status = new CachedTransform <string, string>(s => WidgetUtils.TruncateText(s, statusLabel.Bounds.Width, statusFont)); statusLabel.GetText = () => status.Update(getStatusText()); var text = "Downloading {0}".F(download.Title); panel.Get <LabelWidget>("TITLE").Text = text; ShowDownloadDialog(); }
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(3600); } 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>(); if (State == ServerState.WaitingPlayers) { checkRead.Add(listener.Server); } foreach (var c in Conns) { checkRead.Add(c.Socket); } foreach (var c in PreConns) { checkRead.Add(c.Socket); } if (checkRead.Count > 0) { 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 AssetBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs) { this.world = world; this.modData = modData; panel = widget; 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); var sourceName = new CachedTransform <IReadOnlyPackage, string>(GetSourceDisplayName); sourceDropdown.GetText = () => sourceName.Update(assetSource); } 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 && !isLoadError && currentSprites != null; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded && !isLoadError; } var modelWidget = panel.GetOrNull <ModelWidget>("VOXEL"); if (modelWidget != null) { modelWidget.GetVoxel = () => currentVoxel; currentPalette = modelWidget.Palette; modelWidget.GetPalette = () => currentPalette; modelWidget.GetPlayerPalette = () => currentPalette; modelWidget.GetRotation = () => modelOrientation; modelWidget.IsVisible = () => !isVideoLoaded && !isLoadError && currentVoxel != null; } var errorLabelWidget = panel.GetOrNull("ERROR"); if (errorLabelWidget != null) { errorLabelWidget.IsVisible = () => isLoadError; } 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; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(); 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.GetOrNull <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.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.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.OnClick = () => { if (isVideoLoaded) { player.Stop(); } else { if (frameSlider != null) { frameSlider.Value = 0; } currentFrame = 0; animateFrames = false; } }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.OnClick = () => { if (!isVideoLoaded) { nextButton.OnClick = SelectNextFrame; } }; nextButton.IsVisible = () => !isVideoLoaded; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.OnClick = () => { if (!isVideoLoaded) { SelectPreviousFrame(); } }; prevButton.IsVisible = () => !isVideoLoaded; } var voxelContainer = panel.GetOrNull("VOXEL_SELECTOR"); if (voxelContainer != null) { voxelContainer.IsVisible = () => currentVoxel != null; } var rollSlider = panel.GetOrNull <SliderWidget>("ROLL_SLIDER"); if (rollSlider != null) { rollSlider.OnChange += x => { var roll = (int)x; modelOrientation = modelOrientation.WithRoll(new WAngle(roll)); }; rollSlider.GetValue = () => modelOrientation.Roll.Angle; } var pitchSlider = panel.GetOrNull <SliderWidget>("PITCH_SLIDER"); if (pitchSlider != null) { pitchSlider.OnChange += x => { var pitch = (int)x; modelOrientation = modelOrientation.WithPitch(new WAngle(pitch)); }; pitchSlider.GetValue = () => modelOrientation.Pitch.Angle; } var yawSlider = panel.GetOrNull <SliderWidget>("YAW_SLIDER"); if (yawSlider != null) { yawSlider.OnChange += x => { var yaw = (int)x; modelOrientation = modelOrientation.WithYaw(new WAngle(yaw)); }; yawSlider.GetValue = () => modelOrientation.Yaw.Angle; } var assetBrowserModData = modData.Manifest.Get <AssetBrowser>(); allowedExtensions = assetBrowserModData.SupportedExtensions; acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); 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() { assetVisByName.Clear(); assetList.Layout.AdjustChildren(); assetList.ScrollToTop(); // Select the first visible var firstVisible = assetVisByName.FirstOrDefault(kvp => kvp.Value); if (firstVisible.Key != null && modData.DefaultFileSystem.TryGetPackageContaining(firstVisible.Key, out var package, out var filename)) { LoadAsset(package, filename); } } void AddAsset(ScrollPanelWidget list, string filepath, IReadOnlyPackage package, ScrollItemWidget template) { var item = ScrollItemWidget.Setup(template, () => currentFilename == filepath && currentPackage == package, () => { LoadAsset(package, filepath); }); var label = item.Get <LabelWithTooltipWidget>("TITLE"); WidgetUtils.TruncateLabelToTooltip(label, filepath); item.IsVisible = () => { if (assetVisByName.TryGetValue(filepath, out var visible)) { return(visible); } visible = FilterAsset(filepath); assetVisByName.Add(filepath, visible); return(visible); }; list.AddChild(item); } bool LoadAsset(IReadOnlyPackage package, string filename) { if (isVideoLoaded) { player.Stop(); player = null; isVideoLoaded = false; } if (string.IsNullOrEmpty(filename)) { return(false); } if (!package.Contains(filename)) { return(false); } isLoadError = false; try { currentPackage = package; currentFilename = filename; var prefix = ""; var fs = modData.DefaultFileSystem as OpenRA.FileSystem.FileSystem; if (fs != null) { prefix = fs.GetPrefix(package); if (prefix != null) { prefix += "|"; } } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vqa") { player = panel.Get <VqaPlayerWidget>("PLAYER"); player.Load(prefix + filename); player.DrawOverlay = false; isVideoLoaded = true; if (frameSlider != null) { frameSlider.MaximumValue = (float)player.Video.Frames - 1; frameSlider.Ticks = 0; } return(true); } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vxl") { var voxelName = Path.GetFileNameWithoutExtension(filename); currentVoxel = world.ModelCache.GetModel(voxelName); currentSprites = null; } else { currentSprites = world.Map.Rules.Sequences.SpriteCache[prefix + filename]; currentFrame = 0; if (frameSlider != null) { frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; } currentVoxel = null; } } catch (Exception ex) { isLoadError = true; Log.AddChannel("assetbrowser", "assetbrowser.log"); Log.Write("assetbrowser", "Error reading {0}:{3} {1}{3}{2}", filename, ex.Message, ex.StackTrace, Environment.NewLine); return(false); } return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { var sourceName = new CachedTransform <IReadOnlyPackage, string>(GetSourceDisplayName); Func <IReadOnlyPackage, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => sourceName.Update(source); return(item); }; var sources = new[] { (IReadOnlyPackage)null }.Concat(acceptablePackages); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); var files = new SortedList <string, List <IReadOnlyPackage> >(); if (assetSource != null) { foreach (var content in assetSource.Contents) { files.Add(content, new List <IReadOnlyPackage> { assetSource }); } } else { foreach (var mountedPackage in modData.ModFiles.MountedPackages) { foreach (var content in mountedPackage.Contents) { if (!files.ContainsKey(content)) { files.Add(content, new List <IReadOnlyPackage> { mountedPackage }); } else { files[content].Add(mountedPackage); } } } } foreach (var file in files.OrderBy(s => s.Key)) { if (!allowedExtensions.Any(ext => file.Key.EndsWith(ext, true, CultureInfo.InvariantCulture))) { continue; } foreach (var package in file.Value) { AddAsset(assetList, file.Key, package, template); } } } 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); } string GetSourceDisplayName(IReadOnlyPackage source) { if (source == null) { return("All Packages"); } // Packages that are explicitly mounted in the filesystem use their explicit mount name var fs = (OpenRA.FileSystem.FileSystem)modData.DefaultFileSystem; var name = fs.GetPrefix(source); // Fall back to the path relative to the mod, engine, or support dir if (name == null) { name = source.Name; var compare = Platform.CurrentPlatform == PlatformType.Windows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (name.StartsWith(modData.Manifest.Package.Name, compare)) { name = "$" + modData.Manifest.Id + "/" + name.Substring(modData.Manifest.Package.Name.Length + 1); } else if (name.StartsWith(Platform.EngineDir, compare)) { name = "./" + name.Substring(Platform.EngineDir.Length); } else if (name.StartsWith(Platform.SupportDir, compare)) { name = "^" + name.Substring(Platform.SupportDir.Length); } } if (name.Length > 18) { name = "..." + name.Substring(name.Length - 15); } return(name); } }
static void Main(string[] args) { var arguments = new Arguments(args); var supportDirArg = arguments.GetValue("Engine.SupportDir", null); if (!string.IsNullOrEmpty(supportDirArg)) { Platform.OverrideSupportDir(supportDirArg); } Log.AddChannel("debug", "dedicated-debug.log", true); Log.AddChannel("perf", "dedicated-perf.log", true); Log.AddChannel("server", "dedicated-server.log", true); Log.AddChannel("nat", "dedicated-nat.log", true); Log.AddChannel("geoip", "dedicated-geoip.log", true); // Special case handling of Game.Mod argument: if it matches a real filesystem path // then we use this to override the mod search path, and replace it with the mod id var modID = arguments.GetValue("Game.Mod", null); var explicitModPaths = new string[0]; if (modID != null && (File.Exists(modID) || Directory.Exists(modID))) { explicitModPaths = new[] { modID }; modID = Path.GetFileNameWithoutExtension(modID); } if (modID == null) { throw new InvalidOperationException("Game.Mod argument missing or mod could not be found."); } // HACK: The engine code assumes that Game.Settings is set. // This isn't nearly as bad as ModData, but is still not very nice. Game.InitializeSettings(arguments); var settings = Game.Settings.Server; var envModSearchPaths = Environment.GetEnvironmentVariable("MOD_SEARCH_PATHS"); var modSearchPaths = !string.IsNullOrWhiteSpace(envModSearchPaths) ? FieldLoader.GetValue <string[]>("MOD_SEARCH_PATHS", envModSearchPaths) : new[] { Path.Combine(".", "mods") }; var mods = new InstalledMods(modSearchPaths, explicitModPaths); Console.WriteLine("[{0}] Starting dedicated server for mod: {1}", DateTime.Now.ToString(settings.TimestampFormat), modID); while (true) { // HACK: The engine code *still* assumes that Game.ModData is set var modData = Game.ModData = new ModData(mods[modID], mods); modData.MapCache.LoadMaps(); settings.Map = modData.MapCache.ChooseInitialMap(settings.Map, new MersenneTwister()); var endpoints = new List <IPEndPoint> { new IPEndPoint(IPAddress.IPv6Any, settings.ListenPort), new IPEndPoint(IPAddress.Any, settings.ListenPort) }; var server = new Server(endpoints, settings, modData, ServerType.Dedicated); GC.Collect(); while (true) { Thread.Sleep(1000); if (server.State == ServerState.GameStarted && server.Conns.Count < 1) { Console.WriteLine("[{0}] No one is playing, shutting down...", DateTime.Now.ToString(settings.TimestampFormat)); server.Shutdown(); break; } } modData.Dispose(); Console.WriteLine("[{0}] Starting a new server instance...", DateTime.Now.ToString(settings.TimestampFormat)); } }
public Server(List <IPEndPoint> endpoints, ServerSettings settings, ModData modData, ServerType type) { Log.AddChannel("server", "server.log", true); SocketException lastException = null; var checkReadServer = new List <Socket>(); foreach (var endpoint in endpoints) { var listener = new TcpListener(endpoint); try { try { listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 1); } catch (Exception ex) { if (ex is SocketException || ex is ArgumentException) { Log.Write("server", "Failed to set socket option on {0}: {1}", endpoint.ToString(), ex.Message); } else { throw; } } listener.Start(); listeners.Add(listener); checkReadServer.Add(listener.Server); } catch (SocketException ex) { lastException = ex; Log.Write("server", "Failed to listen on {0}: {1}", endpoint.ToString(), ex.Message); } } if (listeners.Count == 0) { throw lastException; } Type = type; Settings = settings; Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name); ModData = modData; playerDatabase = modData.Manifest.Get <PlayerDatabase>(); randomSeed = (int)DateTime.Now.ToBinary(); if (type != ServerType.Local && settings.EnableGeoIP) { GeoIP.Initialize(); } 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 || Type != ServerType.Dedicated, EnableSyncReports = settings.EnableSyncReports, GameUid = Guid.NewGuid().ToString(), Dedicated = Type == ServerType.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); while (true) { var checkRead = new List <Socket>(); if (State == ServerState.WaitingPlayers) { checkRead.AddRange(checkReadServer); } checkRead.AddRange(Conns.Select(c => c.Socket)); checkRead.AddRange(PreConns.Select(c => c.Socket)); // Block for at most 1 second in order to guarantee a minimum tick rate for ServerTraits // Decrease this to 100ms to improve responsiveness if we are waiting for an authentication query var localTimeout = waitingForAuthenticationCallback > 0 ? 100000 : 1000000; if (checkRead.Count > 0) { Socket.Select(checkRead, null, null, localTimeout); } if (State == ServerState.ShuttingDown) { EndGame(); break; } foreach (var s in checkRead) { var serverIndex = checkReadServer.IndexOf(s); if (serverIndex >= 0) { AcceptConnection(listeners[serverIndex]); continue; } var preConn = PreConns.SingleOrDefault(c => c.Socket == s); if (preConn != null) { preConn.ReadData(this); continue; } var conn = Conns.SingleOrDefault(c => c.Socket == s); conn?.ReadData(this); } delayedActions.PerformActions(0); // PERF: Dedicated servers need to drain the action queue to remove references blocking the GC from cleaning up disposed objects. if (Type == ServerType.Dedicated) { Game.PerformDelayedActions(); } 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(); foreach (var listener in listeners) { try { listener.Stop(); } catch { } } }) { IsBackground = true }.Start(); }
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)); var maps = new List <Map>(); if (args.Length < 2) { Console.WriteLine("Testing mod: {0}".F(modData.Manifest.Mod.Title)); // Run all rule checks on the default mod rules. CheckRules(modData, modData.DefaultRules); // Run all generic (not mod-level) checks here. foreach (var customPassType in modData.ObjectCreator.GetTypesImplementing <ILintPass>()) { try { var customPass = (ILintPass)modData.ObjectCreator.CreateBasic(customPassType); customPass.Run(EmitError, EmitWarning, modData); } catch (Exception e) { EmitError("{0} failed with exception: {1}".F(customPassType, e)); } } modData.MapCache.LoadMaps(); maps.AddRange(modData.MapCache .Where(m => m.Status == MapStatus.Available) .Select(m => new Map(modData, m.Package))); } else { maps.Add(new Map(modData, modData.ModFiles.OpenPackage(args[1]))); } foreach (var testMap in maps) { Console.WriteLine("Testing map: {0}".F(testMap.Title)); // Run all rule checks on the map if it defines custom rules. if (testMap.RuleDefinitions != null || testMap.VoiceDefinitions != null || testMap.WeaponDefinitions != null) { CheckRules(modData, testMap.Rules, testMap); } // Run all map-level checks here. foreach (var customMapPassType in modData.ObjectCreator.GetTypesImplementing <ILintMapPass>()) { try { var customMapPass = (ILintMapPass)modData.ObjectCreator.CreateBasic(customMapPassType); customMapPass.Run(EmitError, EmitWarning, testMap); } catch (Exception e) { EmitError("{0} failed with exception: {1}".F(customMapPassType, 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 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; randomSeed = (int)DateTime.Now.ToBinary(); if (Settings.AllowPortForward) { UPnP.ForwardPort(Settings.ListenPort, Settings.ExternalPort).Wait(); } foreach (var trait in modData.Manifest.ServerTraits) { serverTraits.Add(modData.ObjectCreator.CreateObject <ServerTrait>(trait)); } LobbyInfo = new Session { GlobalSettings = { RandomSeed = randomSeed, Map = settings.Map, ServerName = settings.Name, EnableSingleplayer = settings.EnableSingleplayer || !dedicated, GameUid = Guid.NewGuid().ToString() } }; 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)); if (checkRead.Count > 0) { Socket.Select(checkRead, null, null, timeout); } 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); } } foreach (var t in serverTraits.WithInterface <ITick>()) { t.Tick(this); } if (State == ServerState.ShuttingDown) { EndGame(); if (Settings.AllowPortForward) { 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(); }
public ScriptContext(World world, WorldRenderer worldRenderer, IEnumerable <string> scripts) { runtime = new MemoryConstrainedLuaRuntime(); Log.AddChannel("lua", "lua.log"); World = world; WorldRenderer = worldRenderer; knownActorCommands = Game.ModData.ObjectCreator .GetTypesImplementing <ScriptActorProperties>() .ToArray(); ActorCommands = new Cache <ActorInfo, Type[]>(FilterActorCommands); var knownPlayerCommands = Game.ModData.ObjectCreator .GetTypesImplementing <ScriptPlayerProperties>() .ToArray(); PlayerCommands = FilterCommands(world.Map.Rules.Actors["player"], knownPlayerCommands); runtime.Globals["GameDir"] = Platform.GameDir; runtime.DoBuffer(File.Open(Platform.ResolvePath(".", "lua", "scriptwrapper.lua"), FileMode.Open, FileAccess.Read).ReadAllText(), "scriptwrapper.lua").Dispose(); tick = (LuaFunction)runtime.Globals["Tick"]; // Register globals using (var fn = runtime.CreateFunctionFromDelegate((Action <string>)FatalError)) runtime.Globals["FatalError"] = fn; runtime.Globals["MaxUserScriptInstructions"] = MaxUserScriptInstructions; using (var registerGlobal = (LuaFunction)runtime.Globals["RegisterSandboxedGlobal"]) { using (var fn = runtime.CreateFunctionFromDelegate((Action <string>)LogDebugMessage)) registerGlobal.Call("print", fn).Dispose(); // Register global tables var bindings = Game.ModData.ObjectCreator.GetTypesImplementing <ScriptGlobal>(); foreach (var b in bindings) { var ctor = b.GetConstructors(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(c => { var p = c.GetParameters(); return(p.Length == 1 && p.First().ParameterType == typeof(ScriptContext)); }); if (ctor == null) { throw new InvalidOperationException("{0} must define a constructor that takes a ScriptContext context parameter".F(b.Name)); } var binding = (ScriptGlobal)ctor.Invoke(new[] { this }); using (var obj = binding.ToLuaValue(this)) registerGlobal.Call(binding.Name, obj).Dispose(); } } // System functions do not count towards the memory limit runtime.MaxMemoryUse = runtime.MemoryUse + MaxUserScriptMemory; using (var loadScript = (LuaFunction)runtime.Globals["ExecuteSandboxedScript"]) { foreach (var s in scripts) { loadScript.Call(s, world.Map.Open(s).ReadAllText()).Dispose(); } } }
public AssetBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs) { this.world = world; this.modData = modData; panel = widget; 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 && !isLoadError; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded && !isLoadError; } var errorLabelWidget = panel.GetOrNull("ERROR"); if (errorLabelWidget != null) { errorLabelWidget.IsVisible = () => isLoadError; } 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; } if (logicArgs.ContainsKey("SupportedFormats")) { allowedExtensions = FieldLoader.GetValue <string[]>("SupportedFormats", logicArgs["SupportedFormats"].Value); } else { allowedExtensions = new string[0]; } acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); 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 (!modData.DefaultFileSystem.Exists(filename)) { return(false); } isLoadError = false; try { 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); } currentFilename = filename; currentSprites = world.Map.Rules.Sequences.SpriteCache[filename]; currentFrame = 0; frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; } catch (Exception ex) { isLoadError = true; Log.AddChannel("assetbrowser", "assetbrowser.log"); Log.Write("assetbrowser", "Error reading {0}:{3} {1}{3}{2}", filename, ex.Message, ex.StackTrace, Environment.NewLine); return(false); } return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { Func <IReadOnlyPackage, 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); }; var sources = new[] { (IReadOnlyPackage)null }.Concat(acceptablePackages); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); availableShps.Clear(); var files = assetSource != null ? assetSource.Contents : modData.ModFiles.MountedPackages.SelectMany(f => f.Contents).Distinct(); foreach (var file in files.OrderBy(s => s)) { 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); } }
static int Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: OpenRA.Lint.exe MOD [MAP] [--verbose]"); return(0); } try { Log.AddChannel("perf", null); var options = args.Where(a => a.StartsWith("-")); var mod = args.Where(a => !options.Contains(a)).First(); var map = args.Where(a => !options.Contains(a)).Skip(1).FirstOrDefault(); var verbose = options.Contains("-v") || options.Contains("--verbose"); // 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)); AppDomain.CurrentDomain.AssemblyResolve += GlobalFileSystem.ResolveAssembly; Game.modData = new ModData(mod); IEnumerable <Map> maps; if (string.IsNullOrEmpty(map)) { Game.modData.MapCache.LoadMaps(); maps = Game.modData.MapCache .Where(m => m.Status == MapStatus.Available) .Select(m => m.Map); } else { maps = new[] { new Map(map) } }; foreach (var testMap in maps) { if (verbose) { 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); return(1); } return(0); } catch (Exception e) { EmitError("Failed with exception: {0}".F(e)); return(1); } }
static IrcClient() { Log.AddChannel("irc", "irc.log"); InstanceInitialize(); }
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, EnableSyncReports = settings.EnableSyncReports, 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); while (true) { 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)); // Block for at most 1 second in order to guarantee a minimum tick rate for ServerTraits // Decrease this to 100ms to improve responsiveness if we are waiting for an authentication query var localTimeout = waitingForAuthenticationCallback > 0 ? 100000 : 1000000; 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(); }
void IUtilityCommand.Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. var modData = Game.ModData = utility.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)); var maps = new List <Map>(); if (args.Length < 2) { Console.WriteLine("Testing mod: {0}".F(modData.Manifest.Metadata.Title)); // Run all rule checks on the default mod rules. CheckRules(modData, modData.DefaultRules); // Run all generic (not mod-level) checks here. foreach (var customPassType in modData.ObjectCreator.GetTypesImplementing <ILintPass>()) { try { var customPass = (ILintPass)modData.ObjectCreator.CreateBasic(customPassType); customPass.Run(EmitError, EmitWarning, modData); } catch (Exception e) { EmitError("{0} failed with exception: {1}".F(customPassType, e)); } } // Use all system maps for lint checking maps = modData.MapCache.EnumerateMapsWithoutCaching().ToList(); } else { maps.Add(new Map(modData, new Folder(".").OpenPackage(args[1], modData.ModFiles))); } foreach (var testMap in maps) { Console.WriteLine("Testing map: {0}".F(testMap.Title)); // Lint tests can't be trusted if the map rules are bogus // so report that problem then skip the tests if (testMap.InvalidCustomRules) { EmitError(testMap.InvalidCustomRulesException.ToString()); continue; } // Run all rule checks on the map if it defines custom rules. if (testMap.RuleDefinitions != null || testMap.VoiceDefinitions != null || testMap.WeaponDefinitions != null) { CheckRules(modData, testMap.Rules, testMap); } // Run all map-level checks here. foreach (var customMapPassType in modData.ObjectCreator.GetTypesImplementing <ILintMapPass>()) { try { var customMapPass = (ILintMapPass)modData.ObjectCreator.CreateBasic(customMapPassType); customMapPass.Run(EmitError, EmitWarning, modData, testMap); } catch (Exception e) { EmitError("{0} failed with exception: {1}".F(customMapPassType, 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); } }