Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            const bool validate = true;

            CacheFile cache;
            var       fileBytes = File.ReadAllBytes(args[0]);

            using (var input = new MemoryStream(fileBytes, false))
            {
                cache = CacheFile.Load(input, validate);
            }

            RemoveStaticArraySizeUsage(cache);

            var mySourceFile = new SourceFileDefinition(@"_\gibbed\exec.script");

            cache.Definitions.Add(mySourceFile);

            AddExecCommandSTS(cache, mySourceFile);
            AddMinimapScaler(cache);

            PatchJohnnySkillChecks(cache);

            byte[] testCacheBytes;
            using (var output = new MemoryStream())
            {
                cache.Save(output);
                output.Flush();
                testCacheBytes = output.ToArray();
            }

            File.WriteAllBytes("test_patch.redscripts", testCacheBytes);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            System.IO.Directory.CreateDirectory("Red4Assembler/debug");
            System.IO.Directory.CreateDirectory("Red4Assembler/tests");

            var scriptFile = "final.redscripts";

            if (args.Length > 0 && string.IsNullOrWhiteSpace(args[0]) == false)
            {
                scriptFile = args[0];
            }

            const bool validate = true;

            CacheFile scriptCacheFile;
            var       fileBytes = File.ReadAllBytes(scriptFile);

            using (var input = new MemoryStream(fileBytes, false))
                scriptCacheFile = CacheFile.Load(input, validate);

            var functionBodyScripts =
                scriptCacheFile.Definitions
                .OfType <FunctionDefinition>()
                .Where(t => t.Flags.HasFlag(FunctionFlags.HasBody))
                .OrderBy(f => f.SourceFile?.Path)
                .ThenBy(f => f.SourceLine)
                .ToArray();

            var dism = new FunctionDissembler();

            System.IO.File.WriteAllText("Red4Assembler/tests/GetActionAnimationSlideParams.non_ref.ws", dism.Dissemble(functionBodyScripts[0]));
            System.IO.File.WriteAllText("Red4Assembler/tests/GetActionAnimationSlideParams.ref_param.ws", dism.Dissemble(functionBodyScripts[1]));

            // Console.ReadLine();
        }
Ejemplo n.º 3
0
        private KeyValuePair <CacheFile, bool> EvaluateCacheFile()
        {
            CacheFile cacheFile;
            var       newDgSpecHash = _request.DependencyGraphSpec.GetHash();
            var       noOp          = false;

            if (_request.AllowNoOp && File.Exists(_request.Project.RestoreMetadata.CacheFilePath))
            {
                cacheFile = CacheFileFormat.Load(_request.Project.RestoreMetadata.CacheFilePath, _logger);

                if (cacheFile.IsValid && StringComparer.Ordinal.Equals(cacheFile.DgSpecHash, newDgSpecHash))
                {
                    _logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpFinish, _request.Project.Name));
                    _success = true;
                    noOp     = true;
                }
                else
                {
                    cacheFile = new CacheFile(newDgSpecHash);
                    _logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpDGChanged, _request.Project.Name));
                }
            }
            else
            {
                cacheFile = new CacheFile(newDgSpecHash);
            }
            return(new KeyValuePair <CacheFile, bool>(cacheFile, noOp));
        }
Ejemplo n.º 4
0
        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_cacheFile == null)
            {
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Archive Dictonary file (*.tad)|*.tad";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string tadPath = saveFileDialog.FileName;
                m_cacheFile.Export(tadPath);

                m_tadFile = new TADFile(tadPath);
                FilenameDatabase.MapFilenamesToTAD(m_tadFile);
                DescriptionDatabase.MapDescriptionToTAD(m_tadFile);

                if (System.Diagnostics.Debugger.IsAttached)
                {
                    if (MessageBox.Show("Do you want to unpack the TAC file?", "Unpack TAC", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        tadDataTable1.SetTAD(m_tadFile);
                    }
                }

                m_cacheFile = new CacheFile(m_tadFile);
                m_cacheFile.Unpack();
                tadDataTable1.SetCache(m_cacheFile);
            }
        }
Ejemplo n.º 5
0
 public RestoreResult(
     bool success,
     IEnumerable <RestoreTargetGraph> restoreGraphs,
     IEnumerable <CompatibilityCheckResult> compatibilityCheckResults,
     IEnumerable <MSBuildOutputFile> msbuildFiles,
     LockFile lockFile,
     LockFile previousLockFile,
     string lockFilePath,
     CacheFile cacheFile,
     string cacheFilePath,
     string packagesLockFilePath,
     PackagesLockFile packagesLockFile,
     string dependencyGraphSpecFilePath,
     DependencyGraphSpec dependencyGraphSpec,
     ProjectStyle projectStyle,
     TimeSpan elapsedTime)
 {
     Success                      = success;
     RestoreGraphs                = restoreGraphs;
     CompatibilityCheckResults    = compatibilityCheckResults;
     MSBuildOutputFiles           = msbuildFiles;
     LockFile                     = lockFile;
     LockFilePath                 = lockFilePath;
     PreviousLockFile             = previousLockFile;
     CacheFile                    = cacheFile;
     CacheFilePath                = cacheFilePath;
     _newPackagesLockFilePath     = packagesLockFilePath;
     _newPackagesLockFile         = packagesLockFile;
     _dependencyGraphSpecFilePath = dependencyGraphSpecFilePath;
     _dependencyGraphSpec         = dependencyGraphSpec;
     ProjectStyle                 = projectStyle;
     ElapsedTime                  = elapsedTime;
 }
Ejemplo n.º 6
0
        public override byte[] EncodeFile(CacheFile file, CacheFileInfo?info)
        {
            var data = file.HasEntries ? this.EncodeEntries(file.Entries, info) : file.Data;

            var compressionType = info?.CompressionType ?? CompressionType.Zlib;

            if (compressionType == CompressionType.Zlib)
            {
                using var encodedDataStream = new MemoryStream();
                using var encodedDataWriter = new BinaryWriter(encodedDataStream);

                encodedDataWriter.Write((byte)'Z');
                encodedDataWriter.Write((byte)'L');
                encodedDataWriter.Write((byte)'B');
                encodedDataWriter.Write((byte)0x01);
                encodedDataWriter.WriteInt32BigEndian(data.Length);
                encodedDataWriter.Write((byte)0x78);
                encodedDataWriter.Write((byte)0x9C);

                using (var compressionStream = new DeflateStream(encodedDataStream, CompressionMode.Compress))
                    using (var compressionWriter = new BinaryWriter(compressionStream))
                    {
                        compressionWriter.Write(data);
                    }

                // Info is not changed for zlib because info does not describe zlib data.

                return(encodedDataStream.ToArray());
            }

            return(this.EncodeData(data, info));
        }
Ejemplo n.º 7
0
        internal void ReconstructHack(CacheFile c, Cache.CacheFileLanguagePackResource english)
        {
            var interop = new Cache.CacheFileLanguageHandleInterop[((int)LanguageType.English) + 1];

            for (int x = 0; x < interop.Length; x++)
            {
                interop[x] = new Cache.CacheFileLanguageHandleInterop();
            }
            int total_string_buffer_size = 0;

            // For each language, get the string data referenced by this tag
            for (LanguageType lang = LanguageType.English; lang < (LanguageType.English + 1); lang++)
            {
                total_string_buffer_size = interop[(int)lang].Initialize(                //clpi.LanguagePackGet(lang),
                    english,
                    total_string_buffer_size, LanguageHandles[(int)lang]);
            }

            // Resize the string data container to have enough memory for all of our language strings
            this.StringData.Value = new byte[total_string_buffer_size];

            // For each language, copy the string data and initialize the reference blocks
            for (LanguageType lang = LanguageType.English; lang < (LanguageType.English + 1); lang++)
            {
                interop[(int)lang].ReconstructTagData(c, this, (int)lang);
            }

            // Null the handles for the extracted tag
            foreach (var handle in LanguageHandles)
            {
                handle.Value = 0;
            }
        }
Ejemplo n.º 8
0
        public void WhenNoOpRestoreResult_LogMessagesAreSourcedFromTheCacheFile()
        {
            // Arrange
            var expectedLogLevel = NuGetLogCode.NU1500;
            var assetsLogMessage = new AssetsLogMessage(LogLevel.Error, NuGetLogCode.NU1501, "a");
            var cacheLogMessage  = new AssetsLogMessage(LogLevel.Error, expectedLogLevel, "a");

            var lockFile = new LockFile();

            lockFile.LogMessages.Add(assetsLogMessage);

            var cacheFile = new CacheFile("hash")
            {
                Success     = true,
                LogMessages = new List <IAssetsLogMessage>()
                {
                    cacheLogMessage
                },
            };

            // Act
            var result = new NoOpRestoreResult(
                success: true,
                lockFilePath: "project.assets.json",
                new Lazy <LockFile>(() => lockFile),
                cacheFile: cacheFile,
                cacheFilePath: "cachepath",
                projectStyle: ProjectStyle.PackageReference,
                elapsedTime: TimeSpan.MinValue);

            // Assert
            result.LogMessages.Should().NotBeNull();
            result.LogMessages.Should().HaveCount(1);
            result.LogMessages.Single().Code.Should().Be(expectedLogLevel);
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            const bool validate = true;

            CacheFile cache;
            var       fileBytes = File.ReadAllBytes(args[0]);

            using (var input = new MemoryStream(fileBytes, false))
            {
                cache = CacheFile.Load(input, validate);
            }

            byte[] testCacheBytes;
            using (var output = new MemoryStream())
            {
                cache.Save(output);
                output.Flush();
                testCacheBytes = output.ToArray();
            }

            File.WriteAllBytes("test_roundtrip.redscripts", testCacheBytes);
            CacheFile testCache;

            using (var input = new MemoryStream(testCacheBytes, false))
            {
                testCache = CacheFile.Load(input, validate);
            }

            DumpExecCallableFunctions(cache);
            DumpFunctions(cache, validate);
            DumpEnumerations(cache);
        }
Ejemplo n.º 10
0
        public void InitialScan()
        {
            CacheFile loadedCache = null;

            if (File.Exists(cachePath))
            {
                try
                {
                    loadedCache = JsonConvert.DeserializeObject <CacheFile>(File.ReadAllText(cachePath));
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Warning: problem reading scanner cache: {0}", ex);
                    loadedCache = null;
                }
            }

            if (loadedCache != null)
            {
                cache = loadedCache;
            }

            Rescan();

            Trace.TraceInformation("Initial scan done");
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            if (args[0].Length == 0)
            {
                throw new ArgumentException("You must provide a final.redscripts file!");
            }

            byte[] fileBytes = File.ReadAllBytes(args[0]);

            using MemoryStream input  = new MemoryStream(fileBytes, false);
            using MemoryStream output = new MemoryStream();

            cache = CacheFile.Load(input, false);
            cg    = new CodeGenerator();

            CreateNatives();
            CreateFunctions();

            ApplyPatches();

            cache.Save(output);
            output.Flush();

            File.WriteAllBytes("output.redscripts", output.ToArray());
        }
Ejemplo n.º 12
0
 public static T GetDefinition <T>(this CacheFile cache, string name)
     where T : Definition
 {
     return(cache.Definitions
            .OfType <T>()
            .Single(d => d.Name == name));
 }
Ejemplo n.º 13
0
        private static void RemoveStaticArraySizeUsage(CacheFile cache)
        {
            foreach (var function in cache.Definitions
                     .OfType <FunctionDefinition>()
                     .Where(fd => (fd.Flags & FunctionFlags.HasCode) != 0))
            {
                for (int i = 0; i < function.Code.Count;)
                {
                    if (function.Code[i].Opcode != Opcode.StaticArraySize)
                    {
                        i++;
                        continue;
                    }

                    var staticArrayType = (NativeDefinition)function.Code[i].Argument;
                    if (staticArrayType.NativeType != NativeType.StaticArray)
                    {
                        throw new InvalidOperationException();
                    }

                    // replace StaticArraySize with int constant
                    var staticArraySize = staticArrayType.ArraySize;
                    function.Code[i] = staticArraySize switch
                    {
                        0 => new Instruction(Opcode.Int32Zero),
                        1 => new Instruction(Opcode.Int32One),
                        _ => new Instruction(Opcode.Int32Const, staticArraySize)
                    };
                    // replace referencing of static array with a nop
                    function.Code[i + 1] = new Instruction(Opcode.Nop);
                    i += 2;
                }
            }
        }
Ejemplo n.º 14
0
        private static BitmapTextureInteropResource GetResourceDefinition(CacheFile cache, DatumIndex handle)
        {
            var resourceEntry  = cache.ResourceGestalt.TagResources[handle.Index];
            var definitionData = cache.ResourceGestalt.FixupInformation.Skip(resourceEntry.FixupInformationOffset).Take(resourceEntry.FixupInformationLength).ToArray();
            BitmapTextureInteropResource definition;

            using (var definitionStream = new MemoryStream(definitionData, true))
                using (var definitionReader = new EndianReader(definitionStream, EndianFormat.BigEndian))
                    using (var definitionWriter = new EndianWriter(definitionStream, EndianFormat.BigEndian))
                    {
                        foreach (var fixup in resourceEntry.ResourceFixups)
                        {
                            var newFixup = new TagResourceGen3.ResourceFixup
                            {
                                BlockOffset = (uint)fixup.BlockOffset,
                                Address     = new CacheAddress(CacheAddressType.Definition, fixup.Offset)
                            };

                            definitionStream.Position = newFixup.BlockOffset;
                            definitionWriter.Write(newFixup.Address.Value);
                        }

                        var dataContext = new DataSerializationContext(definitionReader, definitionWriter, CacheAddressType.Definition);
                        definitionStream.Position = resourceEntry.DefinitionAddress.Offset;
                        definition = cache.Deserializer.Deserialize <BitmapTextureInteropResource>(dataContext);
                    }
            return(definition);
        }
Ejemplo n.º 15
0
    /**
     * Create mesh by tile map data
     */
    private IEnumerator CreateMeshByTileMapFile()
    {
        string sampleURL = GetURL();
        // Start a download of the given URL
        WWW www = CacheFile.LoadOrDownLoad(sampleURL, new TileMapUrlParse(Settings.TILE_MAP_FILE_FOLDER), this);

        // Wait for download to complete
        yield return(www);

        if (www.error == null)
        {
            //Get HeigtMap
            int multiplier = 1;
            IHeightMapReader heightMapReader;
            if (!IsUseToggle)
            {
                heightMapReader = new TextHeightMapReader(www.text);
                multiplier      = 10;
            }
            else
            {
                Texture2D texture2D = new Texture2D(www.texture.width, www.texture.height);
                www.LoadImageIntoTexture(texture2D);
                heightMapReader = new TextureHeightMapReader(texture2D);
            }

            //Get height map
            HeightMap = heightMapReader.Read(multiplier, ZoomLevel);
            //Create mesh action
            CreateMeshByHeightMap();
        }
    }
Ejemplo n.º 16
0
        private static bool HasSecondaryResource(CacheFile cache, DatumIndex handle)
        {
            var resourceEntry = cache.ResourceGestalt.TagResources[handle.Index];
            var segmentIndex  = resourceEntry.SegmentIndex;
            var segment       = cache.ResourceLayoutTable.Segments[segmentIndex];

            return(segment.OptionalPageIndex != -1);
        }
Ejemplo n.º 17
0
        private static bool HasPrimaryResource(CacheFile cache, int handle)
        {
            var resourceEntry = cache.ResourceGestalt.TagResources[handle & ushort.MaxValue];
            var segmentIndex  = resourceEntry.SegmentIndex;
            var segment       = cache.ResourceLayoutTable.Segments[segmentIndex];

            return(segment.RequiredPageIndex != -1);
        }
Ejemplo n.º 18
0
        public static IEnumerable <Group> GroupCode(CacheFile cache, FunctionDefinition function)
        {
            var instance = new InstructionGrouper(cache, function);

            foreach (var group in instance.GroupCode())
            {
                yield return(group);
            }
        }
Ejemplo n.º 19
0
 public static CommandContext Create(CommandContext parent, OpenTagCache info, CacheFile blamCache)
 {
     var context = new CommandContext(parent, blamCache.Build);
     context.AddCommand(new PortShaderCommand(info, blamCache));
     context.AddCommand(new PortModelCommand(info, blamCache));
     context.AddCommand(new ListBitmapsCommand(info, blamCache));
     context.AddCommand(new PortBspCommand(info, blamCache));
     return context;
 }
Ejemplo n.º 20
0
 public RenderGeometryConverter(HaloOnlineCacheContext cacheContext, CacheFile blamCache)
 {
     CacheContext          = cacheContext;
     BlamCache             = blamCache;
     OriginalBufferOffsets = new List <long>();
     Unknown1BIndices      = new List <ushort>();
     WaterData             = new List <WaterConversionData>();
     CurrentWaterBuffer    = 0;
 }
Ejemplo n.º 21
0
        async void LoadScaleFromWave(string filePath)
        {
            PauseAudio();

            MainView.Progress = 0.0;
            Lock = true;
            MainView.MessageText = LangResources.ProgressMessage_LoadScale;

            await Task.Run(() =>
            {
                try
                {
                    var wave             = Wavefile.Read(filePath);
                    var selectedOperator = SelectedOperator;
                    var aac = CacheFile.FindCache <AnalyzedAudioCache>(wave.Hash + selectedOperator.GetType().FullName)
                              .GetOrElse(() =>
                    {
                        var aa = selectedOperator.Analyze(new Plugin.WaveData(wave.Data, wave.Fs), ApplicationSettings.Setting.PitchOperation.FramePeriod, (p) =>
                        {
                            Dispatcher.Invoke(() =>
                            {
                                MainView.Progress = p * 0.75 + 25.0;
                            });
                        });
                        var result = new AnalyzedAudioCache(selectedOperator.GetType(), aa, wave.Data.Length, wave.Fs, wave.Hash);
                        CacheFile.SaveCache(result, wave.Hash + selectedOperator.GetType().FullName);
                        return(result);
                    });

                    Dispatcher.Invoke(() =>
                    {
                        MainView.Progress = 1000.0;
                        ApplyScale(aac.AnalyzedAudio.F0);
                        Lock = false;
                    });
                }
                catch (InvalidDataException)
                {
                    MessageBox.ShowWarning(LangResources.Error_UnsupportedWaveFile, LangResources.MessageBoxTitle_CannotLoadWaveFile);

                    Dispatcher.Invoke(() =>
                    {
                        Lock = false;
                    });
                }
                catch (Exception e)
                {
                    MessageBox.ShowWarning(LangResources.Error_CannodLoadWaveFile, exception: e);

                    Dispatcher.Invoke(() =>
                    {
                        Lock = false;
                    });
                }
            });
        }
Ejemplo n.º 22
0
 public PortModelCommand(OpenTagCache info, CacheFile blamCache)
     : base(CommandFlags.Inherit,
           "portmodel",
           "",
           "portmodel [new] <blam tag path> <eldorado tag index>",
           "")
 {
     Info = info;
     BlamCache = blamCache;
 }
Ejemplo n.º 23
0
 public MultiplayerScenarioTagCollector(CacheFile blamCache, Scenario blamScnr,
                                        int desiredZoneSetIndex, BspFlags desiredBsps, MultiplayerScenarioConversionFlags conversionFlags)
 {
     this.BlamCache           = blamCache;
     this.BlamScnr            = blamScnr;
     this.DesiredZoneSetIndex = desiredZoneSetIndex;
     this.DesiredBsps         = desiredBsps;
     this.ConversionFlags     = conversionFlags;
     this.Tags = new List <IndexItem>();
 }
Ejemplo n.º 24
0
 public ListBitmapsCommand(OpenTagCache info, CacheFile blamCache)
     : base(CommandFlags.None,
           "listbitmaps",
           "",
           "listbitmaps <blam tag path>",
           "")
 {
     Info = info;
     BlamCache = blamCache;
 }
Ejemplo n.º 25
0
 public PortShaderCommand(OpenTagCache info, CacheFile blamCache)
     : base(CommandFlags.None,
           "portshader",
           "",
           "portshader <blam tag path>",
           "")
 {
     Info = info;
     BlamCache = blamCache;
 }
Ejemplo n.º 26
0
 public PortBspCommand(OpenTagCache info, CacheFile blamCache)
     : base(CommandFlags.Inherit,
           "portbsp",
           "",
           "portbsp <blam tag path> <Halo Online tag index>",
           "")
 {
     Info = info;
     BlamCache = blamCache;
 }
        public CacheSerializationContext(ref CacheFile blamCache, CacheFile.IndexItem blamTag)
        {
            if (blamCache.Version < CacheVersion.Halo3Retail)
            {
                var oldBlamCache = blamCache;
                var oldBlamTag   = blamTag;

                if (blamTag.External)
                {
                    try
                    {
                        blamCache = CacheFileGen2.MainMenuCache;
                        blamTag   = blamCache.IndexItems[blamTag.GroupTag, blamTag.Name];
                    }
                    catch (KeyNotFoundException)
                    {
                        blamCache = oldBlamCache;
                        blamTag   = oldBlamTag;
                    }
                }
                if (blamTag.External)
                {
                    try
                    {
                        blamCache = CacheFileGen2.SharedCache;
                        blamTag   = blamCache.IndexItems[blamTag.GroupTag, blamTag.Name];
                    }
                    catch (KeyNotFoundException)
                    {
                        blamCache = oldBlamCache;
                        blamTag   = oldBlamTag;
                    }
                }
                if (blamTag.External)
                {
                    try
                    {
                        blamCache = CacheFileGen2.SinglePlayerSharedCache;
                        blamTag   = blamCache.IndexItems[blamTag.GroupTag, blamTag.Name];
                    }
                    catch (KeyNotFoundException)
                    {
                        blamCache = oldBlamCache;
                        blamTag   = oldBlamTag;
                    }
                }
                if (blamTag.External)
                {
                    throw new KeyNotFoundException($"[{blamTag.GroupTag}] {blamTag.Name}");
                }
            }

            BlamCache = blamCache;
            BlamTag   = blamTag;
        }
Ejemplo n.º 28
0
        public void Write_WhenVersionIsCurrentVersion_WritesCorrectly()
        {
            using (var workingDir = TestDirectory.Create())
            {
                var projectFullPath = Path.Combine(workingDir, "E6E7F0F96EBE438887ED7D0B9FC88AFA");

                var file1 = Path.Combine(workingDir, "DA9707B5FCFB4DA8B8BB77AD527C778C");
                var file2 = Path.Combine(workingDir, "C78CE6D18C604A55BECD845F4F694A4B");

                var v          = "2";
                var dgSpecHash = "LhkXQGGI+FQMy9dhLYjG5sWcHX3z/copzi4hjjBiY3Fotv0i7zQCikMZQ+rOKJ03gtx0hoHwIx5oKkM7sVHu7g==";
                var success    = "true";
                var expected   = $@"{{
  ""version"": {v},
  ""dgSpecHash"": ""{dgSpecHash}"",
  ""success"": {success},
  ""projectFilePath"": {JsonConvert.ToString(projectFullPath)},
  ""expectedPackageFiles"": [
    {JsonConvert.ToString(file1)},
    {JsonConvert.ToString(file2)}
  ],
  ""logs"": [
    {{
      ""code"": ""NU1000"",
      ""level"": ""Information"",
      ""message"": ""Test""
    }}
  ]
}}";

                var cacheFile = new CacheFile(dgSpecHash)
                {
                    Success                  = bool.Parse(success),
                    ProjectFilePath          = projectFullPath,
                    ExpectedPackageFilePaths = new List <string>
                    {
                        file1,
                        file2
                    },
                    LogMessages = new List <IAssetsLogMessage>
                    {
                        new AssetsLogMessage(LogLevel.Information, NuGetLogCode.NU1000, "Test")
                    }
                };

                using (var stream = new MemoryStream())
                {
                    CacheFileFormat.Write(stream, cacheFile);
                    var actual = Encoding.UTF8.GetString(stream.ToArray());

                    Assert.Equal(expected, actual);
                }
            }
        }
Ejemplo n.º 29
0
 public static T GetDefinition <T>(this CacheFile cache, string name, Func <T, bool> predicate)
     where T : Definition
 {
     if (predicate == null)
     {
         throw new ArgumentNullException(nameof(predicate));
     }
     return(cache.Definitions
            .OfType <T>()
            .Single(d => d.Name == name && predicate(d) == true));
 }
Ejemplo n.º 30
0
 public static IEnumerable <T> GetDefinitions <T>(this CacheFile cache, Func <T, bool> predicate)
     where T : Definition
 {
     if (predicate == null)
     {
         throw new ArgumentNullException(nameof(predicate));
     }
     return(cache.Definitions
            .OfType <T>()
            .Where(d => predicate(d) == true));
 }
Ejemplo n.º 31
0
        public void SetTAD(TADFile tadFile)
        {
            button_Refresh.Enabled = false;
            m_tadFile   = tadFile;
            m_cacheFile = null;
            TADStatistic statistic = m_tadFile.GetStatistic();

            label_Statistic.Text = String.Format(StatisticFormat, statistic.FilesCovered, statistic.FileCount, statistic.FileCoverage);
            m_sortedEntries      = tadFile.FileEntries;
            UpdateView();
        }
Ejemplo n.º 32
0
        public ExtractBitmapCommand(CacheFile blamCache) :
            base(true,

                 "ExtractBitmap",
                 "Extracts a unmodified Bitmap from selected tag.",

                 "ExtractBitmap <tag name> [output directory] ",

                 "Extracts a unmodified Bitmap from selected tag.")
        {
            BlamCache = blamCache;
        }
Ejemplo n.º 33
0
            private async void HandleDownloaded(CacheFile file)
            {
                List <CacheValue> pending = file.GetAllPendingNotifies();

                var tasks = new List <Task> ();

                foreach (CacheValue value in pending)
                {
                    tasks.Add(value.HandleDownloaded(file, this.HandleFileLoaded));
                }
                await Task.WhenAll(tasks);
            }
        public PortMultiplayerEventsCommand(HaloOnlineCacheContext cacheContext, CacheFile blamCache) :
            base(true,

                 "PortMultiplayerEvents",
                 "Ports events from multiplayer_globals.",

                 "PortMultiplayerEvents",
                 "Ports events from multiplayer_globals.")
        {
            CacheContext = cacheContext;
            BlamCache    = blamCache;
        }
Ejemplo n.º 35
0
        public NameBlamTagCommand(HaloOnlineCacheContext cacheContext, CacheFile blamCache) :
            base(true,

                 "NameBlamTag",
                 "Sets the name of the specified tag in the current external cache.",

                 "NameBlamTag <Tag> <Name>",

                 "Sets the name of the specified tag in the current external cache.")
        {
            CacheContext = cacheContext;
            BlamCache    = blamCache;
        }
Ejemplo n.º 36
0
            public static ModelData Create(CacheFile file)
            {
                var ret = new ModelData {Name = ShortenName(file.Name)};
                var rows = file.GetRows();
                ret.Rows = rows;
                if (rows.Count() == 0)
                    throw new InvalidDataException("Cache is empty");
                var singleRow = rows.First();
                ret.SingleRow = singleRow;

                // we need to go through all rows to find the maximum size type of all columns
                var fieldTypes = new FieldType[singleRow.Columns.Count];
                for (int i = 0; i < singleRow.Columns.Count; i++)
                    fieldTypes[i] = singleRow.Columns[i].Type;
                foreach (var row in rows)
                    for (int i = 0; i < row.Columns.Count; i++)
                        if (FieldTypeHelper.GetTypeBits(row.Columns[i].Type) > FieldTypeHelper.GetTypeBits(fieldTypes[i]))
                            fieldTypes[i] = row.Columns[i].Type;
                ret.FieldTypes = fieldTypes;

                // now build the creation query - fields, primary key, indices, cleanup
                var query = new StringBuilder();
                query.AppendLine("DROP TABLE IF EXISTS " + ret.Name + ";");
                query.AppendLine("CREATE TABLE " + ret.Name + " (");

                bool createAutoIncrement = !IsColumnUnique(rows, 0);
                string autoIncrementName = createAutoIncrement ? (singleRow.Columns.Any(c => c.Name == "id") ? "index" : "id") : "";
                if (createAutoIncrement)
                    query.AppendLine(Indention + autoIncrementName + " INT AUTO_INCREMENT,");

                for (int i = 0; i < singleRow.Columns.Count; i++)
                    query.AppendLine(Indention + singleRow.Columns[i].Name + " " + GetSQLType(fieldTypes[i]) + ",");

                if (createAutoIncrement)
                    query.AppendLine(Indention + "PRIMARY KEY (" + autoIncrementName + "),");
                else
                    query.AppendLine(Indention + "PRIMARY KEY (" + singleRow.Columns[0].Name + "),");

                for (int i = 1; i < singleRow.Columns.Count; i++)
                    if (singleRow.Columns[i].Name.EndsWith("ID"))
                        query.AppendLine(Indention + "INDEX " + singleRow.Columns[i].Name + " (" + singleRow.Columns[i].Name + "),");

                if (query[query.Length - 1] == '\n' && query[query.Length - 2] == '\r' && query[query.Length - 3] == ',')
                    query.Remove(query.Length - 3, 1);
                query.AppendLine(");");

                ret.CreationQuery = query.ToString();
                return ret;
            }
Ejemplo n.º 37
0
		public CacheTagDatabase(CacheFile cf, Blam.CacheIndex.Item root_tag) : base(root_tag) { cacheFile = cf; }
        public void InitialScan()
        {
            CacheFile loadedCache = null;
            if (File.Exists(cachePath))
            {
                try
                {
                    loadedCache = JsonConvert.DeserializeObject<CacheFile>(File.ReadAllText(cachePath));
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Warning: problem reading scanner cache: {0}", ex);
                    loadedCache = null;
                }
            }

            if (loadedCache != null) cache = loadedCache;

            Rescan();

            Trace.TraceInformation("Initial scan done");
        }
Ejemplo n.º 39
0
		bool Reconstruct(int index, CacheFile c, out byte[] data)
		{
			geometry_block_resource_block gbr = Resources[index];

			// seek to the actual data
			c.InputStream.Seek(GetBlockOffset().Offset + 
				8 +
				GetSectionSize() +
				gbr.Offset);
			
			// read all of the geometry resource block data
			data = c.InputStream.ReadBytes(gbr.Size);

			return true;
		}
Ejemplo n.º 40
0
		public CacheTagDatabase(CacheFile cf) : base() { cacheFile = cf; }
Ejemplo n.º 41
0
 private void Load()
 {
     lock (cache) {
         if (loaded) return;
         if (File.Exists(PhysicalCacheFile)) {
             using (var fs = new FileStream(PhysicalCacheFile, FileMode.Open, FileAccess.Read)) {
                 cache = ProtoBuf.Serializer.Deserialize<CacheFile>(fs);
                 //Todo- implement cross-process sync
             }
         }
         lastFlush = DateTime.UtcNow;
         loaded = true;
     }
 }
 public XboxSerializationContext(CacheFile.IndexItem tag)
 {
     _tag = tag;
 }
Ejemplo n.º 43
0
        public void InitialScan()
        {
            CacheFile loadedCache = null;
            if (File.Exists(cachePath))
            {
                try
                {
                   loadedCache = JsonConvert.DeserializeObject<CacheFile>(File.ReadAllText(cachePath));
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Warning: problem reading scanner cache: {0}", ex);
                    loadedCache = null;
                }
            }

            if (loadedCache != null) cache = loadedCache;

            var foundFiles = new Dictionary<string, bool>();

            InitialFolderScan("games", foundFiles);
            InitialFolderScan("maps", foundFiles);
            InitialFolderScan("packages", foundFiles);

            Dictionary<string, CacheItem> copy;
            lock (cache) copy = new Dictionary<string, CacheItem>(cache.ShortPathIndex);
            foreach (var pair in copy) if (!foundFiles.ContainsKey(pair.Key)) CacheItemRemove(pair.Value);


            Trace.TraceInformation("Initial scan done");
        }