public FormFind(FormMain main, SCIPackage package, SCIPackage translate) { InitializeComponent(); _package = package; _translate = translate; _main = main; }
protected async Task CheckDecompress(string mapPath, string uncompDir, Func <Resource, bool> match = null) { var package = SCIPackage.Load(mapPath); foreach (var r in package.Resources) { if (match != null && !match(r)) { continue; } var unpack = r.GetContent(false); var filePath = Path.Combine(uncompDir, r.FileName); var target = await File.ReadAllBytesAsync(filePath); int offset = Resource.GetResourceOffsetInFile(target[1]); // Первые 2 байта - тип ресурса var trimmed = new byte[target.Length - 2 - offset]; Array.Copy(target, 2 + offset, trimmed, 0, trimmed.Length); Assert.AreEqual(trimmed, unpack, $"Decompress error in {r.FileName}"); } }
protected override Task Execute() { var package = SCIPackage.Load(SourceDir); package.Pack(DestDir); return(Task.CompletedTask); }
protected override async Task Execute() { package = SCIPackage.Load(GameDir); if (!string.IsNullOrEmpty(TranslateDir)) { translate = SCIPackage.Load(TranslateDir); } await Do(); }
private void CheckPackage(SCIPackage package) { foreach (var res in package.Scripts) { var scr = res.GetScript() as Script; Assert.IsNotNull(scr); CheckScriptValid(scr); } }
/// <summary> /// Загружает исходный текст с переводом в кингу /// </summary> /// <param name="package"></param> /// <returns></returns> public async Task Upload(SCIPackage package) { await CreateContext(); await ReadVolumes(); var document = await GetDocumentAsync(_bookUrl); Console.WriteLine("Getting strings"); var resources = package.GetTextResources(); List <ResStrings> resStrings = new List <ResStrings>(); foreach (var res in resources) { var en = res.GetStrings(false); if (en == null || en.Length == 0) { continue; } if (!en.Any(s => s.Length > 0)) { continue; // Full empty resource } var tr = res.GetStrings(true); resStrings.Add(new ResStrings { Resource = res, En = en, Tr = tr }); } resStrings = resStrings.OrderBy(r => r.Resource.Type) .ThenBy(r => r.Resource.Number) .ToList(); resStrings = resStrings.Take(10).ToList(); // DEBUG!! Console.WriteLine($"Create {resStrings.Count} volumes"); foreach (var res in resStrings) { var vol = Volumes.FirstOrDefault(v => v.Name.Equals(res.Resource.FileName, StringComparison.OrdinalIgnoreCase)); if (vol != null) { res.Url = vol.URL; } else { res.Url = await CreateVolume(document, res.Resource.FileName); } } var tasks = resStrings .Select(r => UploadRes(r)) .ToArray(); await Task.WhenAll(tasks); }
public void ParseAndBack() { SCIPackage package = Utils.LoadPackage(); foreach (var res in package.Scripts) { var bytes = res.GetContent(); var newbytes = res.GetScript().GetBytes(); CollectionAssert.AreEqual(bytes, newbytes); } }
public void Init(SCIPackage package, ResType type, ushort number, byte resNum, int offset) { Package = package; Type = type; Number = number; if (type == ResType.Message && package.ExternalMessages) { Volumes.Add(new VolumeOffset(resNum, offset, "RESOURCE.MSG")); } else { Volumes.Add(new VolumeOffset(resNum, offset)); } }
public void Init(SCIPackage package, ResType type, ushort number, byte resNum, ResourceFileInfo info) { Package = package; Type = type; Number = number; if (type == ResType.Message && package.ExternalMessages) { Volumes.Add(new VolumeOffset(resNum, -1, "RESOURCE.MSG")); } else { Volumes.Add(new VolumeOffset(resNum, -1)); } _info = info; }
public FormMain(SCIPackage package, SCIPackage translate) { _package = package; _translate = translate; InitializeComponent(); Text = package.GameDirectory; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); sc.Panel2.Controls.Add(hexViewer = new HexViewer()); sc.Panel2.Controls.Add(textViewer = new TextViewer()); sc.Panel2.Controls.Add(fontView = new FontView()); sc.Panel2.Controls.Add(scriptView = new ScriptView()); sc.Panel2.Controls.Add(vocabView = new VocabView()); sc.Panel2.Controls.Add(msgView = new MsgView()); sc.Panel2.Controls.Add(picView = new PicView()); foreach (ResType resType in Enum.GetValues(typeof(ResType))) { var resources = package.GetResources(resType); if (!resources.Any()) { continue; } TreeNode tnRes = tv.Nodes.Add(ResTypeName(resType)); tnRes.ImageKey = "folder"; tnRes.SelectedImageKey = tnRes.ImageKey; foreach (var res in resources) { TreeNode tnRec = tnRes.Nodes.Add(res.ToString()); tnRec.ImageKey = ResTypeKey(resType); tnRec.SelectedImageKey = tnRec.ImageKey; tnRec.Tag = res; } } if (_translate == null) { tsbTranslated.Checked = false; tsbTranslated.Visible = false; tsbSave.Visible = false; } }
public Form1() { InitializeComponent(); var args = Environment.GetCommandLineArgs(); if (args.Length < 2) { MessageBox.Show("Path to game dir must be in command line arguments"); Environment.Exit(1); } var package = SCIPackage.Load(args[1]); cbFont.DataSource = package.GetResouces <ResFont>().ToList(); cbFont.SelectedItem = package.GetResouce <ResFont>(300); }
/// <summary> /// Загружает исходный текст с переводом в кингу /// </summary> /// <param name="package"></param> /// <returns></returns> public async Task Upload(SCIPackage package, string resourceName) { await CreateContext(); await ReadVolumes(); var document = await GetDocumentAsync(_bookUrl); Console.WriteLine("Getting strings"); var res = package.GetResouce(resourceName); List <ResStrings> resStrings = new List <ResStrings>(); var en = res.GetStrings(false); if (en == null || en.Length == 0) { return; } if (!en.Any(s => s.Length > 0)) { return; // Full empty resource } var tr = res.GetStrings(true); var str = new ResStrings { Resource = res, En = en, Tr = tr }; resStrings.Add(str); Console.WriteLine($"Create {resStrings.Count} volumes"); var vol = Volumes.FirstOrDefault(v => v.Name.Equals(res.FileName, StringComparison.OrdinalIgnoreCase)); if (vol != null) { str.Url = vol.URL; } else { str.Url = await CreateVolume(document, res.FileName); } var tasks = resStrings .Select(r => UploadRes(r)) .ToArray(); await Task.WhenAll(tasks); }
public void Pack() { var package = Utils.LoadPackage(); package.Pack(tmp); package = Utils.LoadPackage(); var packed = SCIPackage.Load(tmp); foreach (var r in package.Resources) { var r2 = packed.GetResouce(r.FileName); Assert.IsNotNull(r2); Assert.AreEqual(r.Number, r2.Number, $"{r.FileName}"); var i = r.GetInfo(); var i2 = r2.GetInfo(); Assert.AreEqual(i.ResT, i2.ResT, $"{r.FileName}"); Assert.AreEqual(i.ResNr, i2.ResNr, $"{r.FileName}"); Assert.AreEqual(i.Method, i2.Method, $"{r.FileName}"); if (i.Method != 0) { Assert.Less(i2.CompSize - 4, i2.DecompSize, $"Compressed size error {r.FileName}"); } if (r.Type != ResType.View) { var data = r.GetContent(false); var data2 = r2.GetContent(false); Assert.AreEqual(data, data2, $"{r.FileName}"); if (r2.Volumes.Count > 1) { for (int n = 1; n < r2.Volumes.Count; n++) { var dataExt = r2.GetContent(false, n); Assert.AreEqual(data, dataExt, $"{r.FileName}"); } } } } }
public void RefsLifeCycle() { SCIPackage package = Utils.LoadPackage(); foreach (var res in package.Scripts) { var scr = res.GetScript() as Script; scr.GetBytes(); foreach (var r in scr.AllRefs) { var descr = $"{res} {r.Address:x4} {r.Source}"; Assert.IsTrue(r.IsSetup, descr); Assert.IsTrue(r.IsWrited, descr); Assert.IsTrue(r.IsOffsetWrited, descr); } } }
public void SetAddressOnWrite() { SCIPackage package = Utils.LoadPackage(); foreach (var r in package.Scripts) { var scr = r.GetScript() as Script; foreach (var e in scr.AllElements) { e.IsAddressSet = false; } scr.GetBytes(); foreach (var e in scr.AllElements) { Assert.IsTrue(e.IsAddressSet, $"{e}"); } } }
private void OnExecute() { Console.WriteLine(Translate("It is heavily fortified and filled with his men, as corrupt a band of rogues as I have ever seen.")); string destFile = "ytrans.json"; List <GameTranslate> translatedList = new List <GameTranslate>(); Dictionary <string, string> translations = new Dictionary <string, string>(); if (File.Exists(destFile)) { translatedList = JsonConvert.DeserializeObject <List <GameTranslate> >(File.ReadAllText(destFile)); translations = translatedList.ToDictionary(t => t.en, t => t.ru); } SCIPackage package = new SCIPackage(GameDir); var texts = package.Texts; var scripts = package.Scripts; foreach (var r in texts) { Console.WriteLine(r); bool isChanged = false; var enLines = r.GetText(false); // Оригинальный текст var ruLines = r.GetText(true); // Уже переведенный текст if (enLines.Length != ruLines.Length) { Console.WriteLine($"{r} Lines count error"); continue; } for (int i = 0; i < enLines.Length; i++) { var en = enLines[i]; var ru = ruLines[i]; if (en.Trim().Length == 0) { continue; // Пустые строки } if (en.Contains("%")) { continue; // Системные сообщения } if (!ru.Equals(en)) { continue; // Пропускаем уже готовый перевод } if (!translations.TryGetValue(en, out string tr)) { try { Console.WriteLine($"ERR: {en}"); tr = Translate(en); } catch { continue; } translatedList.Add(new GameTranslate { en = en, ru = tr }); translations.Add(en, tr); } ruLines[i] = tr; isChanged = true; } if (isChanged) { r.SetText(ruLines, false); } } foreach (var r in scripts) { Console.WriteLine(r); bool isChanged = false; var enScr = r.GetScript(false); var ruScr = r.GetScript(true); var enStrings = enScr.AllStrings.Where(s => !s.IsClassName).ToArray(); var ruStrings = ruScr.AllStrings.Where(s => !s.IsClassName).ToArray(); for (int i = 0; i < enStrings.Length; i++) { var en = enStrings[i].Value; if (en.Trim().Length == 0) { continue; // Пустые строки } var ru = ruStrings[i].Value; if (!ru.Equals(en)) { continue; // Пропускаем уже готовый перевод } if (!translations.TryGetValue(en, out string tr)) { try { tr = Translate(en); } catch { Console.WriteLine($"ERR: {en}"); continue; } translatedList.Add(new GameTranslate { en = en, ru = tr }); translations.Add(en, tr); } ruStrings[i].Value = tr; isChanged = true; } if (isChanged) { r.SaveTranslate(ruScr.GetBytes()); } } File.WriteAllText(destFile, JsonConvert.SerializeObject(translatedList, Formatting.None)); Console.WriteLine("Completed"); }
private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); string gameDir, translateDir; Encoding enc = null; if (args.Length == 0) { var form = new FormSelectDir(); RegistryKey key = Registry.CurrentUser.CreateSubKey("SCI_Translator"); form.GameDir = key.GetValue("LastGameDir")?.ToString(); form.TranslateDir = key.GetValue("LastTranslateDir")?.ToString(); var lastEnc = key.GetValue("LastEncoding"); if (lastEnc != null) { form.Encoding = Encoding.GetEncoding(int.Parse(lastEnc.ToString())); } key.Close(); if (form.ShowDialog() != DialogResult.OK) { return; } gameDir = form.GameDir; translateDir = form.TranslateDir; if (translateDir.Length == 0) { translateDir = null; } enc = form.Encoding; } else { gameDir = args[0]; translateDir = args.Length > 1 ? args[1] : null; if (args.Length > 2) { enc = Encoding.GetEncoding(int.Parse(args[2])); } } SCIPackage package; try { package = SCIPackage.Load(gameDir, translateDir, enc); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } Application.Run(new FormMain(package)); }
protected override Task Do() { package2 = SCIPackage.Load(SecondGameDir, SecondTranslateDir); Console.WriteLine("Translate gathering..."); Dictionary <string, string> translates = new Dictionary <string, string>(); Dictionary <string, string> translatesSimple = new Dictionary <string, string>(); foreach (var mess in package.Messages) { var enMess = mess.GetMessages(false); var ruMess = mess.GetMessages(true); if (enMess.Count != ruMess.Count) { Console.WriteLine($"{mess.FileName} Lines mismatch"); continue; } for (int i = 0; i < enMess.Count; i++) { var en = enMess[i].Text; var ru = ruMess[i].Text; if (en.Equals(ru)) { continue; // Пропускаем строки без перевода } /*if (translates.TryGetValue(en, out var tr) && !tr.Equals(ru)) * { * Console.WriteLine($"Multiple tr: {en} {mess.FileName}"); * Console.WriteLine("===================="); * Console.WriteLine(tr); * Console.WriteLine("===================="); * Console.WriteLine(ru); * Console.WriteLine(); * }*/ translates[en] = ru; translatesSimple[Simple(en)] = ru; } } Console.WriteLine("Translating..."); foreach (var txt in package2.Texts) { var enTxt = txt.GetText(false); var ruTxt = txt.GetText(true); bool hasTranslate = false; for (int i = 0; i < enTxt.Length; i++) { var en = enTxt[i]; if (translates.TryGetValue(en, out var tr)) { ruTxt[i] = tr; hasTranslate = true; } else { // Пытаемся найти без учета регистра и пробелов по краям if (translatesSimple.TryGetValue(Simple(en), out tr)) { ruTxt[i] = tr; hasTranslate = true; /*Console.WriteLine($"{txt.FileName}"); * Console.WriteLine(en); * Console.WriteLine("==============="); * Console.WriteLine(res); * Console.WriteLine();*/ } } } if (hasTranslate) { txt.SetTranslate(ruTxt); } } return(Task.CompletedTask); }
public SCIPackage GetPackage() { return(SCIPackage.Load(_gameDir, _translateDir)); }
public static SCIPackage LoadPackage() { return(SCIPackage.Load(ConquestPath)); }
public SCIPackage GetPackage() { return(SCIPackage.Load(GameDir, TranslateDir)); }
protected override async Task Execute() { package = SCIPackage.Load(GameDir, TranslateDir); await Do(); }
private async Task OnExecute() { var book = new NbBook(NotabenoidLogin, NotabenoidPassword, BookId); var dict = await book.GetDict(); glossary = new GlossaryConfig { GlossaryData = new GlossaryData { GlossaryPairs = dict.Where(kv => !kv.Key.StartsWith('-')) .Select(kv => new GlossaryPair { SourceText = kv.Key, TranslatedText = kv.Value }) .ToArray() } }; rest = new RestClient("https://translate.api.cloud.yandex.net/translate/v2/translate"); rest.UseNewtonsoftJson(); rest.AddDefaultHeader("Authorization", "Api-Key " + YandexApiKey); //var test = await Translate("That was foolish of me and good of Tuck."); //Console.WriteLine(test); string destFile = "ytrans.json"; List <GameTranslate> translatedList = new List <GameTranslate>(); Dictionary <string, string> translations = new Dictionary <string, string>(); if (File.Exists(destFile)) { translatedList = GameTranslate.Load(destFile); translations = translatedList.ToDictionary(t => t.en, t => t.ru); } SCIPackage package = SCIPackage.Load(GameDir); var texts = package.Texts; var scripts = package.Scripts; Console.WriteLine("Gathering english"); HashSet <string> toTranslate = new HashSet <string>(); // Множество всех оригинальных фраз foreach (var r in texts) { var enLines = r.GetText(false); // Оригинальный текст var ruLines = r.GetText(true); // Уже переведенный текст if (enLines.Length != ruLines.Length) { Console.WriteLine($"{r} Lines count error"); continue; } for (int i = 0; i < enLines.Length; i++) { var en = enLines[i]; var ru = ruLines[i]; if (en.Trim().Length == 0) { continue; // Пустые строки } if (en.Contains("%")) { continue; // Системные сообщения } //if (!ru.Equals(en)) continue; // Пропускаем уже готовый перевод if (!translations.ContainsKey(en) && !toTranslate.Contains(en)) { toTranslate.Add(en); } } } foreach (var r in scripts) { var enScr = r.GetScript(false); var ruScr = r.GetScript(true); var enStrings = enScr.AllStrings.Where(s => !s.IsClassName).ToArray(); var ruStrings = ruScr.AllStrings.Where(s => !s.IsClassName).ToArray(); for (int i = 0; i < enStrings.Length; i++) { var en = enStrings[i].Value; var ru = ruStrings[i].Value; if (en.Trim().Length == 0) { continue; // Пустые строки } if (en.Contains("%")) { continue; // Системные сообщения } //if (!ru.Equals(en)) continue; // Пропускаем уже готовый перевод if (!translations.ContainsKey(en) && !toTranslate.Contains(en)) { toTranslate.Add(en); } } } Console.WriteLine("Translate"); async Task TranslatePart(List <string> txt) { var tr = await Translate(txt.ToArray()); if (txt.Count != tr.Length) { Console.WriteLine("Translate Error"); } for (int n = 0; n < tr.Length; n++) { translations[txt[n]] = tr[n]; translatedList.Add(new GameTranslate { en = txt[n], ru = tr[n] }); } } var arr = toTranslate.ToArray(); int len = 0; List <string> txt = new List <string>(); for (int i = 0; i < arr.Length; i++) { var val = arr[i].Trim(); //var escaped = JsonConvert.ToString(val); if (len + val.Length > 10000) { await TranslatePart(txt); txt.Clear(); len = 0; } len += val.Length; txt.Add(val); if (i == arr.Length - 1) { await TranslatePart(txt); } } if (Apply) { Console.WriteLine("Apply translate"); foreach (var r in texts) { bool isChanged = false; var enLines = r.GetText(false); // Оригинальный текст var ruLines = r.GetText(true); // Уже переведенный текст if (enLines.Length != ruLines.Length) { continue; } for (int i = 0; i < enLines.Length; i++) { var en = enLines[i]; var ru = ruLines[i]; if (en.Trim().Length == 0) { continue; // Пустые строки } if (en.Contains("%")) { continue; // Системные сообщения } if (!ru.Equals(en)) { continue; // Пропускаем уже готовый перевод } if (translations.TryGetValue(en, out string tr)) { ruLines[i] = tr; isChanged = true; } } if (isChanged) { r.SetTranslate(ruLines); } } foreach (var r in scripts) { bool isChanged = false; var enScr = r.GetScript(false); var ruScr = r.GetScript(true); var enStrings = enScr.AllStrings.Where(s => !s.IsClassName).ToArray(); var ruStrings = ruScr.AllStrings.Where(s => !s.IsClassName).ToArray(); for (int i = 0; i < enStrings.Length; i++) { var en = enStrings[i].Value; var ru = ruStrings[i].Value; if (en.Trim().Length == 0) { continue; // Пустые строки } if (en.Contains("%")) { continue; // Системные сообщения } if (!ru.Equals(en)) { continue; // Пропускаем уже готовый перевод } if (translations.TryGetValue(en, out string tr)) { ruStrings[i].Value = tr; isChanged = true; } } if (isChanged) { r.SaveTranslate(ruScr.GetBytes()); } } } File.WriteAllText(destFile, JsonConvert.SerializeObject(translatedList, Formatting.None)); Console.WriteLine("Completed"); }
protected override Task Do() { package2 = SCIPackage.Load(SecondGameDir); translate2 = SCIPackage.Load(SecondTranslateDir); Console.WriteLine("Translate gathering..."); Dictionary <string, string> translates = new Dictionary <string, string>(); Dictionary <string, string> translatesSimple = new Dictionary <string, string>(); foreach (var mess in package.Messages) { var enMess = mess.GetMessages(); var trMess = translate.Get(mess).GetMessages(); if (enMess.Count != trMess.Count) { Console.WriteLine($"{mess.FileName} Lines mismatch"); continue; } for (int i = 0; i < enMess.Count; i++) { var en = enMess[i].Text; var tr = trMess[i].Text; if (en.Equals(tr)) { continue; // Skipping not translated strings } /*if (translates.TryGetValue(en, out var tr) && !tr.Equals(ru)) * { * Console.WriteLine($"Multiple tr: {en} {mess.FileName}"); * Console.WriteLine("===================="); * Console.WriteLine(tr); * Console.WriteLine("===================="); * Console.WriteLine(ru); * Console.WriteLine(); * }*/ translates[en] = tr; translatesSimple[Simple(en)] = tr; } } Console.WriteLine("Translating..."); foreach (var txt in package2.Texts) { var enTxt = txt.GetStrings(); var trTxt = translate2.Get(txt).GetStrings(); bool hasTranslate = false; for (int i = 0; i < enTxt.Length; i++) { var en = enTxt[i]; if (translates.TryGetValue(en, out var tr)) { trTxt[i] = tr; hasTranslate = true; } else { // Found similar if (translatesSimple.TryGetValue(Simple(en), out tr)) { trTxt[i] = tr; hasTranslate = true; /*Console.WriteLine($"{txt.FileName}"); * Console.WriteLine(en); * Console.WriteLine("==============="); * Console.WriteLine(res); * Console.WriteLine();*/ } } } if (hasTranslate) { txt.SetStrings(trTxt); txt.SavePatch(); } } return(Task.CompletedTask); }
public SCIView(SCIPackage package) { Package = package; }
public FormFind(FormMain main, SCIPackage package) { InitializeComponent(); _package = package; _main = main; }