public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; _fileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory); IniDataContext = new IniDataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, _fileSystem, game, this); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); // TODO: Defer subsystem loading until necessary SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); break; case SageGame.Cnc3: SubsystemLoader.Load(Subsystem.Core); break; default: break; } TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, sageGame); FontManager = new FontManager(); WndImageLoader = AddDisposable(new WndImageLoader(this, game.AssetStore)); } }
public void LanguageUtilsTest() { CultureInfo cinfo; cinfo = LanguageUtility.SetCulture("en"); cinfo = LanguageUtility.SetCulture("ja"); }
public void SetCurrentLanguage(int languageSelected) { if (languageSelected == LanguageUtility.GetCurrentLanguage()) { return; } localeManager = FindObjectOfType <LocalizationManager>() as LocalizationManager; LanguageUtility.Language selected = (LanguageUtility.Language)languageSelected; foreach (var item in selectedColors) { item.enabled = false; } switch (selected) { case LanguageUtility.Language.Finnish: selectedColors[0].enabled = true; LanguageUtility.SetCurrentLanguage((int)selected); localeManager.LoadLocale("localizedText_fi.json"); break; case LanguageUtility.Language.English: selectedColors[1].enabled = true; LanguageUtility.SetCurrentLanguage((int)selected); localeManager.LoadLocale("localizedText_en.json"); break; default: break; } }
public void InitPageLanguage() { if (Request.QueryString["language"] == null) { Page.Response.Redirect("/" + LanguageSetting.Setting.DefaultLanguage.Substring(0, 2) + PageDefinition.FE_HOME); } var language = Request.QueryString["language"]; if (language.Equals(LanguageUtility.GetCurrentLanguage().Substring(0, 2))) { return; } if (language.Equals(LanguageSetting.Setting.DefaultLanguage.Substring(0, 2))) { LanguageUtility.SetCurrentUILanguage(LanguageSetting.Setting.DefaultLanguage); LanguageUtility.SetCurrentLanguage(LanguageSetting.Setting.DefaultLanguage); Page.Response.Redirect(Request.Url.AbsolutePath, true); } else { LanguageUtility.SetCurrentUILanguage(LanguageSetting.Setting.SecondLanguage); LanguageUtility.SetCurrentLanguage(LanguageSetting.Setting.SecondLanguage); Page.Response.Redirect(Request.Url.AbsolutePath, true); } }
private void Awake() { originalLanguage = LanguageUtility.GetCurrentLanguage(); selectedColors[LanguageUtility.GetCurrentLanguage()].enabled = true; if (PlayerPrefs.GetInt("FirstTimeCompleted") != 1) { GetComponent <Canvas>().enabled = true; } }
private void ChangeInstallation(GameInstallation installation) { _selectedInstallation = installation; _imGuiRenderer.ClearCachedImageResources(); RemoveAndDispose(ref _contentView); _files = null; RemoveAndDispose(ref _game); RemoveAndDispose(ref _gamePanel); RemoveAndDispose(ref _fileSystem); RemoveAndDispose(ref _launcherImage); if (installation == null) { _files = new List <FileSystemEntry>(); return; } _fileSystem = AddDisposable(installation.CreateFileSystem()); var launcherImagePath = installation.Game.LauncherImagePath; if (launcherImagePath != null) { var prefixLang = installation.Game.LauncherImagePrefixLang; if (prefixLang) { var lang = LanguageUtility.ReadCurrentLanguage(installation.Game, _fileSystem.RootDirectory); launcherImagePath = lang + launcherImagePath; } var launcherImageEntry = _fileSystem.GetFile(launcherImagePath); if (launcherImageEntry != null) { _launcherImage = AddDisposable(new ImageSharpTexture(launcherImageEntry.Open()).CreateDeviceTexture( _gameWindow.GraphicsDevice, _gameWindow.GraphicsDevice.ResourceFactory)); } } _files = _fileSystem.Files.OrderBy(x => x.FilePath).ToList(); _currentFile = -1; _gamePanel = AddDisposable(new ImGuiGamePanel(_gameWindow)); _gamePanel.EnsureFrame(new Mathematics.Rectangle(0, 0, 100, 100)); _game = AddDisposable(GameFactory.CreateGame( installation, _fileSystem, _gamePanel)); //InstallationChanged?.Invoke(this, new InstallationChangedEventArgs(installation, _fileSystem)); }
private void Awake() { Language = LanguageUtility.GetCurrentLanguage(); if (GameObject.Find("Spawner").GetComponent <LajitteluSpawner>().GetHard()) { Hard(); } else { Easy(); } }
public void ConfirmSelection() { if ((originalLanguage == LanguageUtility.GetCurrentLanguage()) && (PlayerPrefs.GetInt("FirstTimeCompleted") == 1)) { GetComponent <Canvas>().enabled = false; return; } PlayerPrefs.SetInt("FirstTimeCompleted", 1); originalLanguage = LanguageUtility.GetCurrentLanguage(); CreateAndEnableFirebaseInstance(); GetComponent <Canvas>().enabled = false; }
public void DownloadWithNewLanguage() { #if !UNITY_EDITOR EnableLoadingIndicator(); if (!IsNetworkReachable()) { ShowNetworkError(); return; } #endif if (LanguageUtility.GetCurrentLanguage() == ((int)LanguageUtility.Language.Finnish)) { DownloadDataFromDatabase("finnish_language"); } else { DownloadDataFromDatabase("english_language"); } }
/// <summary> /// Sets the <see cref="P:System.Web.UI.Page.Culture"/> and <see cref="P:System.Web.UI.Page.UICulture"/> for the current thread of the page. /// </summary> protected override void InitializeCulture() { var culture = LanguageUtility.GetCurrentUILanguage(); UILanguageId = culture; if (String.IsNullOrEmpty(culture)) { culture = "Auto"; } Page.UICulture = culture; Page.Culture = culture; if (culture != "Auto") { var ci = new System.Globalization.CultureInfo(culture); System.Threading.Thread.CurrentThread.CurrentCulture = ci; System.Threading.Thread.CurrentThread.CurrentUICulture = ci; } base.InitializeCulture(); }
public AdvancedSettingsPage() { InitializeComponent(); ShowStatusBarToggleSwitch.IsOn = AppSettingsService.ShowStatusBar; EnableSmartCopyToggleSwitch.IsOn = AppSettingsService.IsSmartCopyEnabled; // Disable session snapshot toggle for shadow windows if (!App.IsFirstInstance) { EnableSessionSnapshotToggleSwitch.IsOn = false; EnableSessionSnapshotToggleSwitch.IsEnabled = false; } else { EnableSessionSnapshotToggleSwitch.IsOn = AppSettingsService.IsSessionSnapshotEnabled; } AlwaysOpenNewWindowToggleSwitch.IsOn = AppSettingsService.AlwaysOpenNewWindow; if (App.IsGameBarWidget) { // these settings don't make sense for Game Bar, there can be only one SessionSnapshotSettingsTitle.Visibility = Visibility.Collapsed; SessionSnapshotSettingsControls.Visibility = Visibility.Collapsed; LaunchPreferenceSettingsTitle.Visibility = Visibility.Collapsed; LaunchPreferenceSettingsControls.Visibility = Visibility.Collapsed; } #if DEBUG SupportedLanguages = LanguageUtility.GetSupportedLanguageItems(); FindName("LanguagePreferenceSettingsPanel"); // Lazy loading LanguagePicker.SelectedItem = SupportedLanguages .FirstOrDefault(language => language.ID == ApplicationLanguages.PrimaryLanguageOverride); #endif Loaded += AdvancedSettings_Loaded; Unloaded += AdvancedSettings_Unloaded; }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { //Validation of parameters and user have been successful. We may now proceed to read from the database var adoLanguage = new Language_ADO(Ado); LanguageUtility lu = new LanguageUtility(); var languageFileNames = lu.GetLanguageCodes(); if (!languageFileNames.Contains(DTO.LngIsoCode)) { //This language exists already, we can't proceed Log.Instance.Debug("You must create a language file in resources for language " + DTO.LngIsoName); Response.error = Label.Get("error.settings.language-json-invalid"); return(false); } //First we must check if the language exists already (we can't have duplicates) if (adoLanguage.Exists(DTO.LngIsoCode)) { //This language exists already, we can't proceed Log.Instance.Debug("The ISO Code '" + DTO.LngIsoCode + "' exists already."); Response.error = Label.Get("error.duplicate"); return(false); } //Create the language - and retrieve the newly created Id int newId = adoLanguage.Create(DTO, SamAccountName); if (newId == 0) { Log.Instance.Debug("Can't Create Language"); Response.error = Label.Get("error.create"); return(false); } Response.data = JSONRPC.success; return(true); }
static void LoadStrings(IGameInstance sriv) { var results = sriv.SearchForFiles("*.le_strings"); foreach (var result in results) { string filename = result.Value.Filename.ToLowerInvariant(); filename = Path.GetFileNameWithoutExtension(filename); string[] pieces = filename.Split('_'); string languageCode = pieces.Last(); Language language = LanguageUtility.GetLanguageFromCode(languageCode); if (!languageStrings.ContainsKey(language)) { languageStrings.Add(language, new Dictionary <uint, string>()); } Dictionary <uint, string> strings = languageStrings[language]; using (Stream s = sriv.OpenPackfileFile(result.Value.Filename, result.Value.Packfile)) { StringFile file = new StringFile(s, language, sriv); foreach (var hash in file.GetHashes()) { if (strings.ContainsKey(hash)) { continue; } strings.Add(hash, file.GetString(hash)); } } } }
/// <summary> /// 媒体名称节点的打分函数(越大越好) /// </summary> /// <param name="Nodes"></param> /// <param name="Pattern"></param> /// <param name="Strategy"></param> /// <param name="BaseItemCount"></param> /// <returns></returns> internal static double MediaNodeRelPatternScore(IEnumerable <HtmlNode> Nodes, ListStrategy Strategy, int BaseItemCount, int PathLevel, bool PathUsingName) { double AvgPossibility = 0; foreach (HtmlNode Node in Nodes) { string Text = TextCleaner.FullClean(XPathUtility.InnerTextNonDescendants(Node)); if (Text.Length > Strategy.MaxLenMedia) { continue; } double Posibility = Strategy.MediaType == MediaType.WebNews ? 0.1 : 0; //检查是否命中日期或点击数的特殊字符,还不能全部排除,可能有特殊的报纸名称哦,本节点的可能性记为0继续下一个 if (TextCleaner.CountCharInSet(Text, FrequentCharSet_MustNotMediaAuthorDate, false) > 1) { Posibility = 0.2; } //是否是日期时间 if (TextCleaner.CountCharInSet(Text, FrequentCharSet_Dates, false) > Text.Length * 0.6) { Posibility *= 0.3; } //检查开头 Match PrefixMatch = Regex.Match(Text, MediaPrefixRegex); if (PrefixMatch.Success) { Text = Text.Substring(PrefixMatch.Index + PrefixMatch.Length).TrimStart(':', ':', ']', '】', ' '); Posibility = 1; } //禁用词替换 Text = TextCleaner.RemoveStopWords(Text, StopWords); //检查结尾 if (Regex.IsMatch(Text, @"[报台网刊]")) { if (Posibility > 0) { Posibility = Math.Max(1, Posibility * 1.5); } else { Posibility = 0.8; } } //根据class和id是否有特殊字样加权 bool IDClassNameMatched; double IDClassScore = IDClassNameScore(Node, MediaClassNames_Must, MediaClassNames_MustNot, out IDClassNameMatched); if (IDClassNameMatched) { Posibility = (Posibility == 0 ? 1 : Posibility) * IDClassScore; } //长度检查 if (Text.Length * 3 < Strategy.List_BestAvgMediaLen || Text.Length > Strategy.List_BestAvgMediaLen * 3) { Posibility /= 3; //超过3倍降权到1/3 } else { //Rate在1-3之间 double Rate = Text.Length >= Strategy.List_BestAvgMediaLen ? Text.Length / (double)Strategy.List_BestAvgMediaLen : Strategy.List_BestAvgMediaLen / (double)Text.Length; //随着Rate提高降低 Posibility *= (0.4 + 0.35 * (3 - Rate)); } //非名称分隔符(包含空格)出现,6折 if (TextCleaner.CountCharInSet(Text, NoneNameSeperatorSet, true) > 0) { Posibility *= 0.6; } //英文出现,再6折 if (LanguageUtility.DetectedLanguage(Text) == Enums.Language.ENGLISH) { Posibility *= 0.6; } //累加节点的可能性 AvgPossibility += Posibility; } //微调1:级别约小的越好,2级以上每多一个级别扣10%可能性 if (PathLevel > 1) { AvgPossibility *= (1 - 0.1 * (PathLevel - 1)); } //微调2:用ID和class的好于用序号的,增加20%可能性 if (PathUsingName) { AvgPossibility *= 1.2; } //论坛媒体减分 if (Strategy.MediaType == Enums.MediaType.Forum) { AvgPossibility /= 2; } return(AvgPossibility / Nodes.Count()); }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame, WndCallbackResolver wndCallbackResolver) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; _fileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory); IniDataContext = new IniDataContext(fileSystem, sageGame); DataContext = new DataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, _fileSystem, IniDataContext); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); // TODO: Move this somewhere else. // Subsystem.Core should load mouse and water config, but that isn't the case with at least BFME2. IniDataContext.LoadIniFile(@"Data\INI\Mouse.ini"); IniDataContext.LoadIniFile(@"Data\INI\Water.ini"); IniDataContext.LoadIniFile(@"Data\INI\AudioSettings.ini"); break; default: break; } // TODO: Defer subsystem loading until necessary switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); break; default: break; } _contentLoaders = new Dictionary <Type, ContentLoader> { { typeof(Model), AddDisposable(new ModelLoader()) }, { typeof(Scene3D), AddDisposable(new MapLoader()) }, { typeof(Texture), AddDisposable(new TextureLoader(graphicsDevice)) }, { typeof(Window), AddDisposable(new WindowLoader(this, wndCallbackResolver, Language)) }, { typeof(AptWindow), AddDisposable(new AptLoader()) }, }; _cachedObjects = new Dictionary <string, object>(); TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, sageGame); _cachedFonts = new Dictionary <FontKey, Font>(); var linearClampSamplerDescription = SamplerDescription.Linear; linearClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp; linearClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp; linearClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp; LinearClampSampler = AddDisposable( graphicsDevice.ResourceFactory.CreateSampler(ref linearClampSamplerDescription)); var pointClampSamplerDescription = SamplerDescription.Point; pointClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp; pointClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp; pointClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp; PointClampSampler = AddDisposable( graphicsDevice.ResourceFactory.CreateSampler(ref pointClampSamplerDescription)); NullTexture = AddDisposable(graphicsDevice.ResourceFactory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled))); _cachedNullStructuredBuffers = new Dictionary <uint, DeviceBuffer>(); SolidWhiteTexture = AddDisposable(graphicsDevice.CreateStaticTexture2D( 1, 1, 1, new TextureMipMapData( new byte[] { 255, 255, 255, 255 }, 4, 4, 1, 1), PixelFormat.R8_G8_B8_A8_UNorm)); ShaderResources = AddDisposable(new ShaderResourceManager(graphicsDevice, SolidWhiteTexture)); WndImageLoader = AddDisposable(new WndImageLoader(this, new MappedImageLoader(this))); _fallbackFonts = new FontCollection(); var assembly = Assembly.GetExecutingAssembly(); var fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Regular.ttf"); _fallbackFonts.Install(fontStream); fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Bold.ttf"); _fallbackFonts.Install(fontStream); } }
public static void Language(string?locale = null) { LanguageUtility.SetCulture(locale); }
public static void DefaultCulture(string?locale = null) { CultureInfo.DefaultThreadCurrentCulture = LanguageUtility.GetCulture(locale); }
public static void CurrentUICulture(string?locale = null) { CultureInfo.CurrentUICulture = LanguageUtility.GetCulture(locale); }
static void Vf3ToXml(Options options) { Dictionary <char, char> charMap = null; using (Stream cStream = File.OpenRead(options.Charlist)) { charMap = LanguageUtility.GetDecodeCharMapFromStream(cStream); } using (Stream s = File.OpenRead(options.Source)) { FontFile font = new FontFile(s); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\r\n"; using (XmlWriter xml = XmlWriter.Create(options.Output, settings)) { xml.WriteStartDocument(); xml.WriteStartElement("font"); xml.WriteAttributeString("id", font.Header.ID.ToString()); xml.WriteAttributeString("version", font.Header.Version.ToString()); xml.WriteAttributeString("first_ascii", font.Header.FirstAscii.ToString()); xml.WriteAttributeString("width", font.Header.Width.ToString()); xml.WriteAttributeString("height", font.Header.Height.ToString()); xml.WriteAttributeString("render_height", font.Header.RenderHeight.ToString()); xml.WriteAttributeString("baseline_offset", font.Header.BaselineOffset.ToString()); xml.WriteAttributeString("character_spacing", font.Header.CharacterSpacing.ToString()); xml.WriteAttributeString("vertical_offset", font.Header.VerticalOffset.ToString()); xml.WriteAttributeString("peg_name", font.Header.PegName); xml.WriteAttributeString("bitmap_name", font.Header.BitmapName); xml.WriteStartElement("characters"); for (int i = 0; i < font.Characters.Count; i++) { FontCharacter c = font.Characters[i]; int u = font.U[i]; int v = font.V[i]; xml.WriteStartElement("character"); int charValue = font.Header.FirstAscii + i; char actualChar = DecodeChar(font.Header, charMap, i); xml.WriteAttributeString("spacing", c.Spacing.ToString()); xml.WriteAttributeString("byte_width", c.ByteWidth.ToString()); xml.WriteAttributeString("offset", c.Offset.ToString()); xml.WriteAttributeString("kerning_entry", c.KerningEntry.ToString()); xml.WriteAttributeString("user_data", c.UserData.ToString()); xml.WriteAttributeString("u", u.ToString()); xml.WriteAttributeString("v", v.ToString()); xml.WriteAttributeString("char_value", charValue.ToString()); xml.WriteAttributeString("actual_char", actualChar.ToString()); xml.WriteEndElement(); // character } xml.WriteEndElement(); // characters xml.WriteStartElement("kerning_pairs"); for (int i = 0; i < font.KerningPairs.Count; i++) { FontKerningPair pair = font.KerningPairs[i]; xml.WriteStartElement("kerning_pair"); char char1 = DecodeChar(font.Header, charMap, pair.Char1); char char2 = DecodeChar(font.Header, charMap, pair.Char2); xml.WriteAttributeString("char1", char1.ToString()); xml.WriteAttributeString("char2", char2.ToString()); xml.WriteAttributeString("offset", pair.Offset.ToString()); xml.WriteAttributeString("padding", pair.Padding.ToString()); xml.WriteEndElement(); // kerning_pair } xml.WriteEndElement(); // kerning_pairs xml.WriteEndElement(); // font xml.WriteEndDocument(); } } }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; FileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem); TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, game.Definition); LocaleSpecificEncoding = Encoding.GetEncoding(TranslationManager.CurrentLanguage.TextInfo.ANSICodePage); void OnLanguageChanged(object sender, EventArgs e) { //throw new NotImplementedException("Encoding change on LanguageChanged not implemented yet"); } TranslationManager.LanguageChanged += OnLanguageChanged; AddDisposeAction(() => TranslationManager.LanguageChanged -= OnLanguageChanged); IniDataContext = new IniDataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, FileSystem, game, this); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. // TODO: Defer subsystem loading until necessary case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: SubsystemLoader.Load(Subsystem.Core); SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Sciences); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); SubsystemLoader.Load(Subsystem.Damage); SubsystemLoader.Load(Subsystem.SpecialPower); SubsystemLoader.Load(Subsystem.InGameUI); SubsystemLoader.Load(Subsystem.Rank); SubsystemLoader.Load(Subsystem.Animation2D); break; case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Sciences); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); SubsystemLoader.Load(Subsystem.Damage); SubsystemLoader.Load(Subsystem.SpecialPower); SubsystemLoader.Load(Subsystem.InGameUI); SubsystemLoader.Load(Subsystem.Rank); SubsystemLoader.Load(Subsystem.Animation2D); SubsystemLoader.Load(Subsystem.ExperienceLevels); SubsystemLoader.Load(Subsystem.AttributeModifiers); break; case SageGame.Cnc3: case SageGame.Ra3: SubsystemLoader.Load(Subsystem.Core); break; default: break; } UpgradeManager.Initialize(_game.AssetStore); FontManager = new FontManager(Language, StringComparer.Create(TranslationManager.CurrentLanguage, true)); } }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; FileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory); TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, sageGame); LocaleSpecificEncoding = Encoding.GetEncoding(TranslationManager.CurrentLanguage.TextInfo.ANSICodePage); TranslationManager.LanguageChanged += (sender, e) => throw new NotImplementedException("Encoding change on LanguageChanged not implemented yet"); IniDataContext = new IniDataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, FileSystem, game, this); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); // TODO: Defer subsystem loading until necessary SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); break; case SageGame.Cnc3: SubsystemLoader.Load(Subsystem.Core); break; default: break; } FontManager = new FontManager(Language, StringComparer.Create(TranslationManager.CurrentLanguage, true)); } }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame, WndCallbackResolver wndCallbackResolver) { _game = game; _fileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; string language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory); IniDataContext = new IniDataContext(fileSystem); IniDataContext.LoadIniFiles(@"Data\INI\Default\Object.ini"); IniDataContext.LoadIniFiles(@"Data\INI\Object"); IniDataContext.LoadIniFiles(@"Data\INI\multiplayer.ini"); IniDataContext.LoadIniFile(@"Data\INI\PlayerTemplate.ini"); IniDataContext.LoadIniFile(@"maps\MapCache.ini"); _contentLoaders = new Dictionary <Type, ContentLoader> { { typeof(Model), AddDisposable(new ModelLoader()) }, { typeof(Scene3D), AddDisposable(new MapLoader()) }, { typeof(Texture), AddDisposable(new TextureLoader(graphicsDevice)) }, { typeof(Window), AddDisposable(new WindowLoader(this, wndCallbackResolver, language)) }, { typeof(AptWindow), AddDisposable(new AptLoader()) }, { typeof(WavFile), AddDisposable(new WavLoader()) }, }; _cachedObjects = new Dictionary <string, object>(); EffectLibrary = AddDisposable(new EffectLibrary(graphicsDevice)); TranslationManager = new TranslationManager(fileSystem, sageGame, language); _cachedFonts = new Dictionary <FontKey, Font>(); var linearClampSamplerDescription = SamplerDescription.Linear; linearClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp; linearClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp; linearClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp; LinearClampSampler = AddDisposable( graphicsDevice.ResourceFactory.CreateSampler(ref linearClampSamplerDescription)); var pointClampSamplerDescription = SamplerDescription.Point; pointClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp; pointClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp; pointClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp; PointClampSampler = AddDisposable( graphicsDevice.ResourceFactory.CreateSampler(ref pointClampSamplerDescription)); NullTexture = AddDisposable(graphicsDevice.ResourceFactory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled))); _cachedNullStructuredBuffers = new Dictionary <uint, DeviceBuffer>(); SolidWhiteTexture = AddDisposable(graphicsDevice.CreateStaticTexture2D( 1, 1, new TextureMipMapData( new byte[] { 255, 255, 255, 255 }, 4, 4, 1, 1), PixelFormat.R8_G8_B8_A8_UNorm)); WndImageLoader = AddDisposable(new WndImageLoader(this, new MappedImageLoader(this))); _fallbackFonts = new FontCollection(); var assembly = Assembly.GetExecutingAssembly(); var fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Regular.ttf"); _fallbackFonts.Install(fontStream); fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Bold.ttf"); _fallbackFonts.Install(fontStream); }
public static void Main(string[] args) { Options options = null; try { options = CommandLine.Parse <Options>(); } catch (CommandLineException exception) { Console.WriteLine(exception.ArgumentHelp.Message); Console.WriteLine(); Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth)); #if DEBUG Console.ReadLine(); #endif return; } string outputFile = options.Output != null ? options.Output : Path.ChangeExtension(options.Input, ".le_strings"); Console.WriteLine("Packing {0} and creating {1}...", options.Input, outputFile); XDocument xml = null; using (Stream s = File.OpenRead(options.Input)) { xml = XDocument.Load(s); } var stringsNode = xml.Descendants("Strings").First(); string languageString = stringsNode.Attribute("Language").Value; string gameString = stringsNode.Attribute("Game").Value; Language language = LanguageUtility.GetLanguageFromCode(languageString); IGameInstance instance = GameInstance.GetFromString(gameString); StringFile stringFile = new StringFile(language, instance); var stringNodes = stringsNode.Descendants("String"); foreach (var stringNode in stringNodes) { uint hash; var nameAttribute = stringNode.Attribute("Name"); if (nameAttribute != null) { hash = Hashes.CrcVolition(nameAttribute.Value); } else { hash = uint.Parse(stringNode.Attribute("Hash").Value, System.Globalization.NumberStyles.HexNumber); } string value = stringNode.Value; if (stringFile.ContainsKey(hash)) { Console.WriteLine("You are attempting to add a duplicate key to the strings file."); Console.WriteLine("Name: \"{0}\", Hash: {1}, Value: {2}", nameAttribute != null ? nameAttribute.Value : "", hash, value); Console.WriteLine("Other value: {0}", stringFile.GetString(hash)); return; } stringFile.AddString(hash, value); } using (Stream s = File.Create(outputFile)) { stringFile.Save(s); } Console.WriteLine("Done."); #if DEBUG Console.ReadLine(); #endif }
public AudioMetadata(Stream stream, IGameInstance instance) { Instance = instance; Header = stream.ReadStruct <AudioMetadataHeader>(); if (Header.LipsyncSize > 0) { stream.Seek(0x24 + Header.LipsyncOffset, SeekOrigin.Begin); LipsyncData = new byte[Header.LipsyncSize]; stream.Read(LipsyncData, 0, LipsyncData.Length); } if (Header.SubtitleSize > 0) { stream.Seek(0x24 + Header.SubtitleOffset, SeekOrigin.Begin); SubtitleHeader = stream.ReadStruct <AudioMetadataSubtitleHeader>(); long subtitleOffset = stream.Position; for (int i = 0; i < SubtitleHeader.LocalizedVoiceSubtitleHeaders.Length; i++) { LocalizedVoiceSubtitleHeader localizedVoiceSubtitleHeader = SubtitleHeader.LocalizedVoiceSubtitleHeaders[i]; Language language = (Language)i; if (localizedVoiceSubtitleHeader.Length == 0) { Subtitles.Add(language, ""); continue; } long offset = subtitleOffset + localizedVoiceSubtitleHeader.Offset; stream.Seek(offset, SeekOrigin.Begin); byte[] subtitleData = new byte[localizedVoiceSubtitleHeader.Length]; stream.Read(subtitleData, 0, (int)localizedVoiceSubtitleHeader.Length); var map = LanguageUtility.GetDecodeCharMap(instance, language); StringBuilder subtitleBuilder = new StringBuilder(); for (int pos = 0; pos < subtitleData.Length; pos += 2) { char src = BitConverter.ToChar(subtitleData, pos); char value = src; if (map.ContainsKey(src)) { value = map[src]; } if (value == 0x00) { continue; } subtitleBuilder.Append(value); } string subtitle = subtitleBuilder.ToString(); Subtitles.Add(language, subtitle); } } }
public StringFile(Stream stream, Language language, IGameInstance instance) { GameInstance = instance; Language = language; Header = stream.ReadStruct <StringHeader>(); var map = LanguageUtility.GetDecodeCharMap(GameInstance, Language); StringBuilder sb = new StringBuilder(); for (int i = 0; i < Header.BucketCount; i++) { // Seek to the start of our new bucket stream.Seek(Marshal.SizeOf(typeof(StringHeader)) + (i * Marshal.SizeOf(typeof(StringBucket))), SeekOrigin.Begin); StringBucket bucket = stream.ReadStruct <StringBucket>(); Dictionary <UInt32, string> bucketData = new Dictionary <uint, string>(); for (int j = 0; j < bucket.StringCount; j++) { stream.Seek(bucket.StringOffset + (sizeof(UInt32) * j), SeekOrigin.Begin); UInt32 stringOffset = stream.ReadUInt32(); stream.Seek(stringOffset, SeekOrigin.Begin); UInt32 stringHash = stream.ReadUInt32(); if (FileIsSaintsRow2) { stringHash = stringHash.Swap(); } sb.Clear(); int length = 0; while (true) { UInt16 charValue = stream.ReadUInt16(); if (charValue == 0x0000) { break; } if (FileIsSaintsRow2) { charValue = charValue.Swap(); } char src = (char)charValue; char value = src; if (map.ContainsKey(src)) { value = map[src]; } sb.Append(value); length++; } string text = sb.ToString(); bucketData.Add(stringHash, text); } Buckets.Add(bucketData); } }
public void Save(Stream stream) { var map = LanguageUtility.GetEncodeCharMap(GameInstance, Language); int total = 0; foreach (var bucket in Buckets) { total += bucket.Count; } Header.StringCount = (UInt32)total; stream.WriteStruct <StringHeader>(Header); int nextBucketData = Buckets.Count * Marshal.SizeOf(typeof(StringBucket)) + Marshal.SizeOf(typeof(StringHeader)); int nextStringPos = Buckets.Count * Marshal.SizeOf(typeof(StringBucket)) + Marshal.SizeOf(typeof(StringHeader)) + Marshal.SizeOf(typeof(UInt32)) * total; foreach (var bucket in Buckets) { long bucketPos = stream.Position; StringBucket strBucket = new StringBucket(); strBucket.StringCount = (UInt32)bucket.Count; strBucket.StringOffset = (UInt32)nextBucketData; foreach (var pair in bucket) { stream.Seek(nextBucketData, SeekOrigin.Begin); stream.WriteUInt32((UInt32)nextStringPos); nextBucketData = (int)stream.Position; stream.Seek(nextStringPos, SeekOrigin.Begin); UInt32 hash = FileIsSaintsRow2 ? pair.Key.Swap() : pair.Key; stream.WriteUInt32(hash); using (MemoryStream ms = new MemoryStream()) { for (int i = 0; i < pair.Value.Length; i++) { char src = pair.Value[i]; char value = src; if (map.ContainsKey(src)) { value = map[src]; } UInt16 charValue = (UInt16)value; if (FileIsSaintsRow2) { charValue = charValue.Swap(); } ms.WriteUInt16(charValue); } ms.WriteInt16(0); ms.Seek(0, SeekOrigin.Begin); ms.CopyTo(stream); } nextStringPos = (int)stream.Position; } stream.Seek(bucketPos, SeekOrigin.Begin); stream.WriteStruct(strBucket); } }
public void Save(Stream stream) { Header.Signature = 0x56414d44; Header.LipsyncOffset = 0; if (LipsyncData != null) { Header.LipsyncSize = (uint)LipsyncData.Length; stream.Seek(0x24, SeekOrigin.Begin); stream.Write(LipsyncData, 0, LipsyncData.Length); } else { Header.LipsyncSize = 0; } Header.SubtitleOffset = Header.LipsyncSize; uint startOfSubtitles = 0x24 + Header.LipsyncSize + 0x74; uint nextSubtitleOffset = 0; if (Subtitles.Count != 0) { SubtitleHeader = new AudioMetadataSubtitleHeader(); SubtitleHeader.Version = 3; SubtitleHeader.LocalizedVoiceSubtitleHeaders = new LocalizedVoiceSubtitleHeader[14]; for (int i = 0; i < SubtitleHeader.LocalizedVoiceSubtitleHeaders.Length; i++) { Language language = (Language)i; string subtitle = Subtitles[language]; if (subtitle == "") { SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Offset = nextSubtitleOffset; SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Length = 0; } else { var map = LanguageUtility.GetEncodeCharMap(Instance, language); byte[] subtitleData; using (MemoryStream ms = new MemoryStream()) { for (int pos = 0; pos < subtitle.Length; pos++) { char src = subtitle[pos]; char value = src; if (map.ContainsKey(src)) { value = map[src]; } byte[] data = BitConverter.GetBytes(value); ms.Write(data, 0, data.Length); } ms.WriteUInt16(0); subtitleData = ms.ToArray(); } SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Offset = nextSubtitleOffset; SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Length = (uint)subtitleData.Length; stream.Seek(startOfSubtitles + nextSubtitleOffset, SeekOrigin.Begin); stream.Write(subtitleData, 0, subtitleData.Length); nextSubtitleOffset += (uint)subtitleData.Length; } } Header.SubtitleSize = nextSubtitleOffset + 0x74; stream.Seek(0x24 + Header.SubtitleOffset, SeekOrigin.Begin); stream.WriteStruct(SubtitleHeader); } else { Header.SubtitleSize = 0; } stream.Seek(0, SeekOrigin.Begin); stream.WriteStruct(Header); }
static void Main(string[] args) { Options options = null; try { options = CommandLine.Parse <Options>(); } catch (CommandLineException exception) { Console.WriteLine(exception.ArgumentHelp.Message); Console.WriteLine(); Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth)); #if DEBUG Console.ReadLine(); #endif return; } if (options.Output == null) { options.Output = "output"; } if (!Directory.Exists(options.Output)) { Directory.CreateDirectory(options.Output); } FontFile font = null; using (Stream s = File.OpenRead(options.Source)) { font = new FontFile(s); } Dictionary <char, char> charMap = new Dictionary <char, char>(); using (Stream s = File.OpenRead(options.Charmap)) { charMap = LanguageUtility.GetDecodeCharMapFromStream(s); } string indicatedPegPath = Path.Combine(Path.GetDirectoryName(options.Source), font.Header.BitmapName); string[] pegExtensions = new string[] { ".cpeg_pc", ".cvbm_pc" }; string[] gpegExtensions = new string[] { ".gpeg_pc", ".gvbm_pc" }; bool foundPeg = false; string pegPath = null; string gpegPath = null; for (int i = 0; i < pegExtensions.Length; i++) { string pegExtension = pegExtensions[i]; string gpegExtension = gpegExtensions[i]; string candidatePath = Path.ChangeExtension(indicatedPegPath, pegExtension); if (File.Exists(candidatePath)) { foundPeg = true; pegPath = candidatePath; gpegPath = Path.ChangeExtension(pegPath, gpegExtension); break; } } if (!foundPeg) { Console.WriteLine("Couldn't find {0}! Extension may be \".cpeg_pc\" or \".cvbm_pc\".", indicatedPegPath); return; } Bitmap fontBitmap = null; using (Stream pegStream = File.OpenRead(pegPath)) { PegFile peg = new PegFile(pegStream); PegEntry entry = null; foreach (PegEntry e in peg.Entries) { if (e.Filename == font.Header.BitmapName) { entry = e; break; } } if (entry == null) { Console.WriteLine("Couldn't find bitmap {0} in font peg!", font.Header.BitmapName); return; } byte[] bitmapData = null; using (Stream gpegStream = File.OpenRead(gpegPath)) { bitmapData = entry.GetData(gpegStream); } byte[] uncompressed = null; switch (entry.Data.BitmapFormat) { case PegBitmapFormat.D3DFMT_DXT3: uncompressed = ManagedSquish.Squish.DecompressImage(bitmapData, entry.Data.Width, entry.Data.Height, ManagedSquish.SquishFlags.Dxt3); break; case PegBitmapFormat.D3DFMT_DXT5: uncompressed = ManagedSquish.Squish.DecompressImage(bitmapData, entry.Data.Width, entry.Data.Height, ManagedSquish.SquishFlags.Dxt5); break; default: throw new Exception(); } fontBitmap = new Bitmap(entry.Data.Width, entry.Data.Height, PixelFormat.Format32bppArgb); BitmapData data = fontBitmap.LockBits(new Rectangle(0, 0, fontBitmap.Width, fontBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(uncompressed, 0, data.Scan0, uncompressed.Length); fontBitmap.UnlockBits(data); } using (StreamWriter sw = new StreamWriter(Path.Combine(options.Output, "out.txt"))) { for (int i = 0; i < font.Characters.Count; i++) { FontCharacter c = font.Characters[i]; int u = font.U[i]; int v = font.V[i]; int charValue = font.Header.FirstAscii + i; if (c.ByteWidth == 0) { continue; } char actualChar = '\0'; char rawChar = (char)charValue; if (charMap.ContainsKey(rawChar)) { actualChar = charMap[rawChar]; sw.WriteLine("{0} \"{1}\"", charValue, actualChar); } else { sw.WriteLine("{0} \"\"", charValue); } using (Bitmap bm = new Bitmap(c.ByteWidth, font.Header.RenderHeight)) { using (Graphics g = Graphics.FromImage(bm)) { g.Clear(Color.Black); g.DrawImage(fontBitmap, 0, 0, new Rectangle(u, v, c.ByteWidth, font.Header.RenderHeight), GraphicsUnit.Pixel); g.Flush(); } string bmName = String.Format("{0}.png", charValue); string bmPath = Path.Combine(options.Output, bmName); bm.Save(bmPath, ImageFormat.Png); } } } }
static void Main(string[] args) { Options options = null; try { options = CommandLine.Parse <Options>(); } catch (CommandLineException exception) { Console.WriteLine(exception.ArgumentHelp.Message); Console.WriteLine(); Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth)); #if DEBUG Console.ReadLine(); #endif return; } if (options.Output == null) { options.Output = options.NewName; } string outputFolder = options.Output; Directory.CreateDirectory(outputFolder); IGameInstance sriv = GameInstance.GetFromSteamId(GameSteamID.SaintsRowIV); LoadStrings(sriv); IAssetAssemblerFile newAsm; using (Stream newAsmStream = File.OpenRead(Path.Combine("templates", "template_customize_item.asm_pc"))) { newAsm = AssetAssemblerFile.FromStream(newAsmStream); } XDocument customizationItem = null; using (Stream itemsTemplateStream = File.OpenRead(Path.Combine("templates", "template_customization_items.xtbl"))) { customizationItem = XDocument.Load(itemsTemplateStream); } var customizationItemTable = customizationItem.Descendants("Table").First(); XElement itemNode = FindCustomizationItem(options.Source, sriv); if (itemNode == null) { Console.WriteLine("Couldn't find {0}.", options.Source); #if DEBUG Console.ReadLine(); #endif return; } string itemName = itemNode.Element("Name").Value; itemNode.Element("Name").Value = options.NewName; string originalDisplayName = itemNode.Element("DisplayName").Value; uint originalStringCrc = Hashes.CrcVolition(originalDisplayName); string newDisplayName = "DUPLICATED_" + options.NewName.ToUpperInvariant(); itemNode.Element("DisplayName").Value = newDisplayName; List <string> str2Names = new List <string>(); bool found = false; var dlcElement = itemNode.Element("Is_DLC"); if (dlcElement != null) { string isDLCString = dlcElement.Value; // Remove Is_DLC element so DLC items show up in SRIV dlcElement.Remove(); } var wearOptionsNode = itemNode.Element("Wear_Options"); int wearOption = 0; foreach (var wearOptionNode in wearOptionsNode.Descendants("Wear_Option")) { var meshInformationNode = wearOptionNode.Element("Mesh_Information"); var maleMeshFilenameNode = meshInformationNode.Element("Male_Mesh_Filename"); var filenameNode = maleMeshFilenameNode.Element("Filename"); string maleMeshFilename = filenameNode.Value; string newMaleMeshFilename = (wearOption == 0) ? String.Format("cm_{0}.cmeshx", options.NewName) : String.Format("cm_{0}_{1}.cmeshx", options.NewName, wearOption); filenameNode.Value = newMaleMeshFilename; var femaleMeshFilenameNode = meshInformationNode.Element("Female_Mesh_Filename"); filenameNode = femaleMeshFilenameNode.Element("Filename"); string femaleMeshFilename = filenameNode.Value; string newFemaleMeshFilename = (wearOption == 0) ? String.Format("cf_{0}.cmeshx", options.NewName) : String.Format("cf_{0}_{1}.cmeshx", options.NewName, wearOption); filenameNode.Value = newFemaleMeshFilename; Console.WriteLine("Mapping mesh {0} -> {1}", maleMeshFilename, newMaleMeshFilename); Console.WriteLine("Mapping mesh {0} -> {1}", femaleMeshFilename, newFemaleMeshFilename); string clothSimFilename = null; var clothSimFilenameNode = meshInformationNode.Element("Cloth_Sim_Filename"); if (clothSimFilenameNode != null) { filenameNode = clothSimFilenameNode.Element("Filename"); string xmlClothSimFilename = filenameNode.Value; clothSimFilename = Path.ChangeExtension(xmlClothSimFilename, ".sim_pc"); string newClothSimFilename = (wearOption == 0) ? String.Format("cm_{0}.simx", options.NewName) : String.Format("cm_{0}_{1}.simx", options.NewName, wearOption); filenameNode.Value = newClothSimFilename; Console.WriteLine("Mapping cloth sim {0} -> {1}", xmlClothSimFilename, newClothSimFilename); } var variantNodes = itemNode.Element("Variants").Descendants("Variant"); foreach (var variantNode in variantNodes) { var meshVariantInfoNode = variantNode.Element("Mesh_Variant_Info"); var variantIdNode = meshVariantInfoNode.Element("VariantID"); uint variantId = uint.Parse(variantIdNode.Value); int crc = Hashes.CustomizationItemCrc(itemName, maleMeshFilename, variantId); string maleStr2 = String.Format("custmesh_{0}.str2_pc", crc); string femaleStr2 = String.Format("custmesh_{0}f.str2_pc", crc); int newCrc = Hashes.CustomizationItemCrc(options.NewName, newMaleMeshFilename, variantId); string newMaleStr2 = String.Format("custmesh_{0}.str2_pc", newCrc); string newFemaleStr2 = String.Format("custmesh_{0}f.str2_pc", newCrc); string newMaleName = (wearOption == 0) ? String.Format("cm_{0}", options.NewName) : String.Format("cm_{0}_{1}", options.NewName, wearOption); string newFemaleName = (wearOption == 0) ? String.Format("cf_{0}", options.NewName) : String.Format("cf_{0}_{1}", options.NewName, wearOption); bool foundMale = ClonePackfile(sriv, maleStr2, clothSimFilename, options.Output, newAsm, itemName, newMaleName, Path.Combine(outputFolder, newMaleStr2)); bool foundFemale = ClonePackfile(sriv, femaleStr2, clothSimFilename, options.Output, newAsm, itemName, newFemaleName, Path.Combine(outputFolder, newFemaleStr2)); if (foundMale || foundFemale) { found = true; } } wearOption++; } if (found) { customizationItemTable.Add(itemNode); } using (Stream xtblOutStream = File.Create(Path.Combine(outputFolder, "customization_items.xtbl"))) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Encoding = new UTF8Encoding(false); settings.NewLineChars = "\r\n"; settings.Indent = true; settings.IndentChars = "\t"; using (XmlWriter writer = XmlWriter.Create(xtblOutStream, settings)) { customizationItem.Save(writer); } } using (Stream asmOutStream = File.Create(Path.Combine(outputFolder, "customize_item.asm_pc"))) { newAsm.Save(asmOutStream); } string stringXmlFolder = Path.Combine(outputFolder, "stringxml"); Directory.CreateDirectory(stringXmlFolder); foreach (var pair in languageStrings) { Language language = pair.Key; Dictionary <uint, string> strings = pair.Value; StringFile file = new StringFile(language, sriv); string newString = "CLONE: " + options.NewName; if (strings.ContainsKey(originalStringCrc)) { string originalString = strings[originalStringCrc]; newString = "CLONE: " + originalString; } else { Console.WriteLine("Warning: original language string could not be found for {0}.", language); } file.AddString(newDisplayName, newString); string newFilename = Path.Combine(outputFolder, String.Format("{0}_{1}.le_strings", options.NewName, LanguageUtility.GetLanguageCode(language))); string newXmlFilename = Path.Combine(stringXmlFolder, String.Format("{0}_{1}.xml", options.NewName, LanguageUtility.GetLanguageCode(language))); using (Stream s = File.Create(newFilename)) { file.Save(s); } XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\r\n"; using (XmlWriter xml = XmlTextWriter.Create(newXmlFilename, settings)) { xml.WriteStartDocument(); xml.WriteStartElement("Strings"); xml.WriteAttributeString("Language", language.ToString()); xml.WriteAttributeString("Game", sriv.Game.ToString()); xml.WriteStartElement("String"); xml.WriteAttributeString("Name", newDisplayName); xml.WriteString(newString); xml.WriteEndElement(); // String xml.WriteEndElement(); // Strings xml.WriteEndDocument(); } } Console.WriteLine("Finished cloning customization item {0} to {1}!", options.Source, options.NewName); #if DEBUG Console.ReadLine(); #endif }
public static void Main(string[] args) { Options options = null; try { options = CommandLine.Parse <Options>(); } catch (CommandLineException exception) { Console.WriteLine(exception.ArgumentHelp.Message); Console.WriteLine(); Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth)); #if DEBUG Console.ReadLine(); #endif return; } IGameInstance instance = GameInstance.GetFromString(options.Game); string filename = Path.GetFileNameWithoutExtension(options.Input); string languageCode = filename.Remove(0, filename.Length - 2); Language language = LanguageUtility.GetLanguageFromCode(languageCode); Dictionary <UInt32, string> hashLookup = new Dictionary <UInt32, string>(); if (options.LoadXtbls) { Console.WriteLine("Loading XTBL files..."); Dictionary <string, FileSearchResult> results = instance.SearchForFiles("*.xtbl"); int i = 0; foreach (var pair in results) { i++; Console.WriteLine("[{0}/{1}] Loading xtbl: {2}", i, results.Count, pair.Key); string xtbl = null; using (StreamReader reader = new StreamReader(pair.Value.GetStream())) { xtbl = reader.ReadToEnd(); } Regex regex = new Regex("<Name>(.*?)</Name>", RegexOptions.Compiled); foreach (Match m in regex.Matches(xtbl)) { uint hash = Hashes.CrcVolition(m.Groups[1].Value); if (!hashLookup.ContainsKey(hash)) { hashLookup.Add(hash, m.Groups[1].Value); } } } } string outputFile = (options.Output != null) ? options.Output : Path.ChangeExtension(options.Input, ".xml"); Console.WriteLine("Extracting {0} to {1}...", options.Input, outputFile); StringFile stringFile = null; using (Stream stream = File.OpenRead(options.Input)) { stringFile = new StringFile(stream, language, instance); } XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\r\n"; Dictionary <string, string> stringsWithName = new Dictionary <string, string>(); Dictionary <uint, string> stringsWithHash = new Dictionary <uint, string>(); foreach (uint hash in stringFile.GetHashes()) { string text = stringFile.GetString(hash); if (hashLookup.ContainsKey(hash)) { stringsWithName.Add(hashLookup[hash], text); } else { stringsWithHash.Add(hash, text); } } using (XmlWriter xml = XmlTextWriter.Create(outputFile, settings)) { xml.WriteStartDocument(); xml.WriteStartElement("Strings"); xml.WriteAttributeString("Language", language.ToString()); xml.WriteAttributeString("Game", instance.Game.ToString()); foreach (var pair in stringsWithName.OrderBy(x => x.Key)) { xml.WriteStartElement("String"); xml.WriteAttributeString("Name", pair.Key); xml.WriteString(pair.Value); xml.WriteEndElement(); // String } foreach (var pair in stringsWithHash) { xml.WriteStartElement("String"); xml.WriteAttributeString("Hash", pair.Key.ToString("X8")); xml.WriteString(pair.Value); xml.WriteEndElement(); // String } xml.WriteEndElement(); // Strings xml.WriteEndDocument(); } Console.WriteLine("Done."); #if DEBUG Console.ReadLine(); #endif }