Exemple #1
0
        private byte[] GetInternalBuffer()
        {
            if (this._buffer == null)
            {
                this._buffer = FileStream.ReadBytes(this.name);
            }

            return(this._buffer);
        }
Exemple #2
0
        public void load(string FileName)
        {
            FileStream FileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            this.header = FileStream.ReadStruct<Header>();

            if (this.header.revision >= 3)
            {
                this.headerExtraRevision3 = FileStream.ReadStruct<HeaderRevision3>();
            }

            FileStream.ReadStructVector(ref dimensionTable, header.TableDimLength);
            FileStream.ReadStructVector(ref xAdjustTable, header.TableXAdjustLength);
            FileStream.ReadStructVector(ref yAdjustTable, header.TableYAdjustLength);
            FileStream.ReadStructVector(ref advanceTable, header.TableAdvanceLength);

            packedShadowCharMap = FileStream.ReadBytes(BitsToBytesHighAligned(header.TableShadowMapLength * header.TableShadowMapBpe));

            if (header.revision == 3)
            {
                FileStream.ReadStructVector(ref charmapCompressionTable1, headerExtraRevision3.TableCompCharMapLength1);
                FileStream.ReadStructVector(ref charmapCompressionTable2, headerExtraRevision3.TableCompCharMapLength2);
            }

            packedCharMap = FileStream.ReadBytes(BitsToBytesHighAligned(header.TableCharMapLength * header.TableCharMapBpe));
            packedCharPointerTable = FileStream.ReadBytes(BitsToBytesHighAligned(header.TableCharPointerLength * header.TableCharPointerBpe));

            /*
            int BytesLeft = (int)(FileStream.Length - FileStream.Position);
            charData = new byte[BytesLeft];
            FileStream.Read(charData, 0, BytesLeft);
            */

            charData = FileStream.ReadBytes((int)(FileStream.Length - FileStream.Position));

            var NumberOfCharacters = header.TableCharPointerLength;

            charMap = new int[header.lastGlyph + 1];
            charPointer = new int[NumberOfCharacters];
            Glyphs = new Glyph[NumberOfCharacters];
            reverseCharMap = new Dictionary<int, int>();

            foreach (var Pair in BitReader.FixedBitReader(packedShadowCharMap, header.TableShadowMapBpe))
            {
                var UnicodeIndex = (int)Pair.Key + header.firstGlyph;
                var GlyphIndex = (int)Pair.Value;
                shadowCharMap[UnicodeIndex] = GlyphIndex;
                reverseShadowCharMap[GlyphIndex] = UnicodeIndex;
            }

            foreach (var Pair in BitReader.FixedBitReader(packedCharMap, header.TableCharMapBpe))
            {
                var UnicodeIndex = (int)Pair.Key + header.firstGlyph;
                var GlyphIndex = (int)Pair.Value;
                charMap[UnicodeIndex] = GlyphIndex;
                reverseCharMap[GlyphIndex] = UnicodeIndex;
            }

            foreach (var Pair in BitReader.FixedBitReader(packedCharPointerTable, header.TableCharPointerBpe))
            {
                charPointer[Pair.Key] = (int)Pair.Value;
            }

            /*
            for (int n = 0; n < NumberOfCharacters; n++)
            {
                Glyphs[n] = new Glyph().Read(this, n);
            }
            */

            Console.WriteLine(this.header.fontName);

            /*
            Console.WriteLine(this.header.fontName);
            for (int n = 0; n < 300; n++)
            {
                Console.WriteLine(GetGlyphId((char)n));
            }
            */
        }
        private void MoveCaches(string cookedPath, string NewCache)
        {
            //DebugOutput.PrintLn( "\nMoving cache...\n");
            //Fix the GUID
            using (FileStream newCache = new FileStream(Path.Combine(cookedPath, NewCache), FileMode.Open, FileAccess.Read))
            {
                SaltPropertyReader.Property GUIDProp = properties["TFCFileGuid"];

                for (int i = 0; i < 16; i++)
                {
                    SaltPropertyReader.PropertyValue tempVal = GUIDProp.Value.Array[i];
                    tempVal.IntValue = newCache.ReadByte();
                    GUIDProp.Value.Array[i] = tempVal;
                }
            }


            //Move across any existing textures
            //using (FileStream oldCache = new FileStream(Path.Combine(cookedPath, arcName + ".tfc"), FileMode.Open, FileAccess.Read))
            using (FileStream oldCache = new FileStream(FullArcPath, FileMode.Open, FileAccess.Read))
            {
                using (FileStream newCache = new FileStream(Path.Combine(cookedPath, NewCache), FileMode.Append, FileAccess.Write))
                {
                    for (int i = 0; i < privateimgList.Count; i++)
                    {
                        ImageInfo img = privateimgList[i];

                        switch (img.storageType)
                        {
                            case storage.arcCpr:
                                byte[] buff = new byte[img.cprSize];
                                oldCache.Seek(img.offset, SeekOrigin.Begin);
                                Buffer.BlockCopy(oldCache.ReadBytes(img.cprSize), 0, buff, 0, img.cprSize);
                                img.offset = (int)newCache.Position;
                                newCache.WriteBytes(buff);
                                break;
                            case storage.arcUnc:
                                buff = new byte[img.uncSize];
                                oldCache.Seek(img.offset, SeekOrigin.Begin);
                                Buffer.BlockCopy(oldCache.ReadBytes(img.cprSize), 0, buff, 0, img.cprSize);
                                img.offset = (int)newCache.Position;
                                newCache.WriteBytes(buff);
                                break;
                            case storage.pccSto:
                                break;
                            case storage.empty:
                                break;
                            default:
                                throw new NotImplementedException("Storage type not supported yet");
                        }
                        privateimgList[i] = img;
                    }
                }
            }
        }
        public void runCrackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WriteLine("Giving ME2 DLC Entitlements");
            WriteLine("Based upon the cracks by Illiria and Loghain");
            WriteLine();
            BitConverter.IsLittleEndian = true;

            if (String.IsNullOrEmpty(ME2Directory.DLCPath) || !Directory.Exists(ME2Directory.DLCPath))
            {
                MessageBox.Show("Could not find Mass Effect 2 DLC directory.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            WriteLine("Looking for DLC...");
            StringWriter writer = new StringWriter();
            writer.WriteLine("[Hash]");
            foreach (string dlc in Directory.GetDirectories(ME2Directory.DLCPath))
            {
                string mountFile = Path.Combine(Path.Combine(dlc, "CookedPC"), "Mount.dlc");
                if (File.Exists(mountFile))
                {
                    string dlcName = null;
                    uint dlcNum;
                    using (FileStream fs = new FileStream(mountFile, FileMode.Open, FileAccess.Read))
                    {
                        fs.Seek(0xC, SeekOrigin.Begin);
                        byte[] buff = fs.ReadBytes(4);
                        dlcNum = BitConverter.ToUInt32(buff, 0);
                        fs.Seek(0x2C, SeekOrigin.Begin);
                        buff = fs.ReadBytes(4);
                        int strlen = BitConverter.ToInt32(buff, 0);
                        if (strlen > 0 && strlen < 0x100)
                        {
                            buff = fs.ReadBytes(strlen - 1);
                            dlcName = Encoding.ASCII.GetString(buff);
                        }
                    }
                    if (!String.IsNullOrEmpty(dlcName))
                        WriteLine("Found dlc: " + dlcName + " ( " + Path.GetFileName(dlc) + " ) ");
                    else
                        WriteLine("Found dlc: " + Path.GetFileName(dlc));

                    writer.WriteLine("GiveMeDLC.Mount{0}={1}", dlcNum, ComputeDLCHash(Path.Combine(dlc, "CookedPC")));
                }
                Application.DoEvents();
            }
            WriteLine();
            writer.WriteLine();
            writer.WriteLine("[Global]");
            writer.WriteLine("LastNucleusID=GiveMeDLC");
            writer.WriteLine();
            writer.WriteLine("[KeyValuePair]");
            writer.WriteLine("GiveMeDLC.Entitlement.ME2PCOffers.ONLINE_ACCESS=TRUE");
            writer.WriteLine("GiveMeDLC.Entitlement.ME2PCOffers.PC_CERBERUS_NETWORK=TRUE");
            writer.WriteLine("GiveMeDLC.Numeric.DaysSinceReg=0");
            writer.WriteLine();
            WriteLine("Saving BioPersistentEntitlementCache.ini...");
            byte[] bytes = Encoding.Unicode.GetBytes(writer.GetStringBuilder().ToString());
            byte[] magic = IPEncryptor();
            if (magic == null)
            {
                MessageBox.Show("Could not get adapter entropy.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else
            {
                bytes = DataProtection.Encrypt(bytes, magic);
                if (bytes == null)
                {
                    MessageBox.Show("Could not encrypt entitlement cache.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                else
                {
                    string str8 = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BioWare"), "Mass Effect 2"), "BIOGame"), "Config");
                    if (!Directory.Exists(str8))
                    {
                        Directory.CreateDirectory(str8);
                    }
                    string str9 = Path.Combine(str8, "BioPersistentEntitlementCache.ini");
                    if (!File.Exists(str9) || (MessageBox.Show(string.Format("Overwrite \"{0}\"?", str9), "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
                    {
                        Stream stream2 = File.Open(str9, FileMode.Create, FileAccess.Write);
                        stream2.Write(bytes, 0, bytes.Length);
                        stream2.Close();
                        WriteLine();
                        WriteLine("DONE!");
                    }
                    else
                        WriteLine("Not saved");
                }
            }
        }
Exemple #5
0
        internal static void FillLines(string fileName, IProgressHandler progressHandler, Shapefile shapefile,
            FeatureType featureType)
        {
            // Check to ensure the fileName is not null
            if (fileName == null)
            {
                throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName"));
            }
            if (shapefile == null) throw new ArgumentNullException("shapefile");

            if (File.Exists(fileName) == false)
            {
                throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName));
            }

            if (featureType != FeatureType.Line && featureType != FeatureType.Polygon)
            {
                throw new NotSupportedException();
            }

            var header = shapefile.Header;
            // Check to ensure that the fileName is the correct shape type
            switch (featureType)
            {
                case FeatureType.Line:
                    if (header.ShapeType != ShapeType.PolyLine &&
                        header.ShapeType != ShapeType.PolyLineM &&
                        header.ShapeType != ShapeType.PolyLineZ)
                    {
                        throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName));
                    }
                    break;
                case FeatureType.Polygon:
                    if (header.ShapeType != ShapeType.Polygon &&
                        header.ShapeType != ShapeType.PolygonM &&
                        header.ShapeType != ShapeType.PolygonZ)
                    {
                        throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName));
                    }
                    break;
            }

            if (new FileInfo(fileName).Length == 100)
            {
                // the file is empty so we are done reading
                return;
            }

            // Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
            var shapeHeaders = shapefile.ReadIndexFile(fileName);
            int numShapes = shapeHeaders.Count;

            bool isM = false, isZ = false;
            switch (header.ShapeType)
            {
                case ShapeType.PolyLineM:
                case ShapeType.PolygonM:
                    isM = true;
                    break;
                case ShapeType.PolyLineZ:
                case ShapeType.PolygonZ:
                    isZ = true;
                    isM = true;
                    break;
            }

            int totalPointsCount = 0;
            int totalPartsCount = 0;
            var shapeIndices = new List<ShapeRange>(numShapes);

            var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName))
            {
                StepPercent = 5
            };
            using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536))
            {
                var boundsBytes = new byte[4 * 8];
                var bounds = new double[4];
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(shp * 50.0 / numShapes);

                    // Read from the index file because some deleted records
                    // might still exist in the .shp file.
                    long offset = (shapeHeaders[shp].ByteOffset);
                    reader.Seek(offset, SeekOrigin.Begin);

                    var shape = new ShapeRange(featureType, shapefile.CoordinateType)
                    {
                        RecordNumber = reader.ReadInt32(Endian.BigEndian),
                        ContentLength = reader.ReadInt32(Endian.BigEndian),
                        ShapeType = (ShapeType)reader.ReadInt32(),
                        StartIndex = totalPointsCount
                    };
                    Debug.Assert(shape.RecordNumber == shp + 1);

                    if (shape.ShapeType != ShapeType.NullShape)
                    {
                        // Bounds
                        reader.Read(boundsBytes, 0, boundsBytes.Length);
                        Buffer.BlockCopy(boundsBytes, 0, bounds, 0, boundsBytes.Length);
                        shape.Extent.MinX = bounds[0];
                        shape.Extent.MinY = bounds[1];
                        shape.Extent.MaxX = bounds[2];
                        shape.Extent.MaxY = bounds[3];

                        // Num Parts
                        shape.NumParts = reader.ReadInt32();
                        totalPartsCount += shape.NumParts;

                        // Num Points
                        shape.NumPoints = reader.ReadInt32();
                        totalPointsCount += shape.NumPoints;
                    }

                    shapeIndices.Add(shape);
                }

                var vert = new double[totalPointsCount * 2];
                var vertInd = 0;

                var parts = new int[totalPartsCount];
                var partsInd = 0;

                double[] mArray = null, zArray = null;
                if (isM)
                {
                    mArray = new double[totalPointsCount];
                }
                int mArrayInd = 0;
                if (isZ)
                {
                    zArray = new double[totalPointsCount];
                }
                int zArrayInd = 0;

                int partsOffset = 0;
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(50 + shp * 50.0 / numShapes);

                    var shape = shapeIndices[shp];
                    if (shape.ShapeType == ShapeType.NullShape) continue;
                    reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
                    reader.Seek(3 * 4 + 32 + 2 * 4, SeekOrigin.Current); // Skip first bytes

                    // Read parts
                    var partsBytes = reader.ReadBytes(4 * shape.NumParts);
                    Buffer.BlockCopy(partsBytes, 0, parts, partsInd, partsBytes.Length);
                    partsInd += 4 * shape.NumParts;

                    // Read points
                    var pointsBytes = reader.ReadBytes(8 * 2 * shape.NumPoints);
                    Buffer.BlockCopy(pointsBytes, 0, vert, vertInd, pointsBytes.Length);
                    vertInd += 8 * 2 * shape.NumPoints;

                    // Fill parts
                    shape.Parts.Capacity = shape.NumParts;
                    for (int part = 0; part < shape.NumParts; part++)
                    {
                        int endIndex = shape.NumPoints + shape.StartIndex;
                        int startIndex = parts[partsOffset + part] + shape.StartIndex;
                        if (part < shape.NumParts - 1)
                        {
                            endIndex = parts[partsOffset + part + 1] + shape.StartIndex;
                        }
                        int count = endIndex - startIndex;
                        var partR = new PartRange(vert, shape.StartIndex, parts[partsOffset + part], featureType)
                        {
                            NumVertices = count
                        };
                        shape.Parts.Add(partR);
                    }
                    partsOffset += shape.NumParts;

                    // Fill M and Z arrays
                    switch (header.ShapeType)
                    {
                        case ShapeType.PolyLineM:
                        case ShapeType.PolygonM:
                            if (shape.ContentLength * 2 > 44 + 4 * shape.NumParts + 16 * shape.NumPoints)
                            {
                                var mExt = (IExtentM)shape.Extent;
                                mExt.MinM = reader.ReadDouble();
                                mExt.MaxM = reader.ReadDouble();

                                var mBytes = reader.ReadBytes(8 * shape.NumPoints);
                                Buffer.BlockCopy(mBytes, 0, mArray, mArrayInd, mBytes.Length);
                                mArrayInd += 8 * shape.NumPoints;
                            }
                            break;
                        case ShapeType.PolyLineZ:
                        case ShapeType.PolygonZ:
                            var zExt = (IExtentZ)shape.Extent;
                            zExt.MinZ = reader.ReadDouble();
                            zExt.MaxZ = reader.ReadDouble();

                            var zBytes = reader.ReadBytes(8 * shape.NumPoints);
                            Buffer.BlockCopy(zBytes, 0, zArray, zArrayInd, zBytes.Length);
                            zArrayInd += 8 * shape.NumPoints;


                            // These are listed as "optional" but there isn't a good indicator of how to
                            // determine if they were added.
                            // To handle the "optional" M values, check the contentLength for the feature.
                            // The content length does not include the 8-byte record header and is listed in 16-bit words.
                            if (shape.ContentLength * 2 > 60 + 4 * shape.NumParts + 24 * shape.NumPoints)
                            {
                                goto case ShapeType.PolyLineM;
                            }

                            break;
                    }
                }

                if (isM) shapefile.M = mArray;
                if (isZ) shapefile.Z = zArray;
                shapefile.ShapeIndices = shapeIndices;
                shapefile.Vertex = vert;
            }

            progressMeter.Reset();
        }
Exemple #6
0
        public static unsafe int Patch(string hPatchs, string hSources, string    hDests,ProgressBar pBar,Label lab,int FileID)
        {
            try
            {
                if (pBar.InvokeRequired == true)
                {
                    SetValue PSetValue = new SetValue(DoSetValue);
                    SetText LSetText = new SetText(DoSetText);
                    pBar.Invoke(PSetValue, new Object[] { pBar, 0 });
                    lab.Invoke(LSetText, new Object[] { lab, "0%" });
                }
                UInt32 BLOCKSIZE = 16384;
                UInt32 temp = 0;
                UInt32 read;
                byte[] source_md5 = new byte[16];
                byte[] patch_dest_md5 = new byte[16];
                byte[] block = new byte[BLOCKSIZE];
                int MD5Mode = 0;
                UInt32 patches = 0;
                int already_uptodate = 0,j=1;
                double blocks;
                FILETIME targetModifiedTime;
                DateTime dte = new DateTime() ;
                //write回调方法
                FileStream Patchs = new FileStream(hPatchs, FileMode.Open, FileAccess.Read, FileShare.Read);
                FileStream Sources = new FileStream(hSources, FileMode.Open, FileAccess.Read, FileShare.Read);
                FileStream Dests = new FileStream(hDests, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                Hashtable Data = Program.filehash;
                // special 'addition' for the dll: since the patch file is now
                // in a seperate file, the VPAT header might be right at the start
                // of the file, and a pointer at the end of the file is probably missing
                // (because all patch generator versions don't append it, the linker/gui
                //  does this).
                Patchs.Seek(0, SeekOrigin.Begin);
                temp = Patchs.ReadValueU32(); read = 4;
                // it's not at the start of file -> there must be a pointer at the end of
                // file then
                if (temp != 0x54415056)
                {
                    Patchs.Seek(-4, SeekOrigin.End);
                    temp = Patchs.ReadValueU32(); read = 4;
                    Patchs.Seek(temp, SeekOrigin.Begin);
                    temp = Patchs.ReadValueU32(); read = 4;
                    if (temp != 0x54415056)
                        return result.PATCH_CORRUPT;
                }

                // target file date is by default the current system time
                GetSystemTimeAsFileTime(&targetModifiedTime);

                // read the number of patches in the file
                patches = Patchs.ReadValueU32(); read = 4;
                if (Convert.ToBoolean(patches & 0x80000000)) MD5Mode = 1;
                // MSB is now reserved for future extensions, anyone wanting more than
                // 16 million patches in a single file is nuts anyway
                patches = patches & 0x00FFFFFF;

                if (!Convert.ToBoolean(MD5Mode))
                {
                    return result.PATCH_UNSUPPORTED;
                }
                else
                {
                    source_md5 = checksum.FileMD5(Sources, Data, FileID,Program.AdvMOD);
                    if (source_md5 == null)
                        return result.PATCH_ERROR;
                }

                //pBar.Maximum = Convert.ToInt32(patches);
                while (Convert.ToBoolean(patches--))
                {
                    int patch_blocks = 0, patch_size = 0;

                    // flag which needs to be set by one of the checksum checks
                    int currentPatchMatchesChecksum = 0;

                    // read the number of blocks this patch has
                    patch_blocks = Convert.ToInt32(Patchs.ReadValueU32()); blocks = patch_blocks; read = 4;
                    if (!Convert.ToBoolean(patch_blocks))
                    {
                        return result.PATCH_CORRUPT;
                    }
                    if (pBar.InvokeRequired == true)
                    {
                        SetValue PSetValue = new SetValue(DoSetMax);
                        pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(patch_blocks) });
                    }
                    // read checksums
                    if (!Convert.ToBoolean(MD5Mode))
                    {
                        return result.PATCH_UNSUPPORTED;
                    }
                    else
                    {
                        int md5index;
                        byte[] patch_source_md5 = new byte[16];
                        patch_source_md5 = Patchs.ReadBytes(16); read = 16;
                        if (patch_source_md5 == null)
                        {
                            return result.PATCH_CORRUPT;
                        }
                        patch_dest_md5 = Patchs.ReadBytes(16); read = 16;
                        if (patch_dest_md5 == null)
                        {
                            return result.PATCH_CORRUPT;
                        }
                        // check to see if it's already up-to-date for some patch
                        for (md5index = 0; md5index < 16; md5index++)
                        {
                            if (source_md5[md5index] != patch_dest_md5[md5index]) break;
                            if (md5index == 15) already_uptodate = 1;
                        }
                        for (md5index = 0; md5index < 16; md5index++)
                        {
                            if (source_md5[md5index] != patch_source_md5[md5index]) break;
                            if (md5index == 15) currentPatchMatchesChecksum = 1;
                        }
                    }
                    // read the size of the patch, we can use this to skip over it
                    patch_size = Convert.ToInt32(Patchs.ReadValueU32()); read = 4;
                    if (patch_size == null)
                    {
                        return result.PATCH_CORRUPT;
                    }

                    if (Convert.ToBoolean(currentPatchMatchesChecksum))
                    {
                        while (Convert.ToBoolean(patch_blocks--))
                        {
                            if (pBar.InvokeRequired == true)
                            {
                                SetValue PSetValue = new SetValue(DoSetValue);
                                SetText LSetText = new SetText(DoSetText);
                                pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(j++) });
                                var per = Convert.ToDouble(j-1)/Convert.ToDouble(blocks);
                                lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(Math.Ceiling(per*100)) + "%" });
                                Application.DoEvents();
                            }
                            Byte blocktype = 0;
                            UInt32 blocksize = 0;
                            blocktype = Convert.ToByte(Patchs.ReadByte()); read = 1;
                            if (blocktype==null)
                            {
                                return result.PATCH_CORRUPT;
                            }
                            switch (blocktype)
                            {
                                case 1:
                                case 2:
                                case 3:
                                    if (blocktype == 1)
                                    {
                                        Byte x;
                                        x = Convert.ToByte(Patchs.ReadByte()); read = 1;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }
                                    else if (blocktype == 2)
                                    {
                                        UInt16 x;
                                        x = Patchs.ReadValueU16(); read = 2;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }
                                    else
                                    {
                                        UInt32 x;
                                        x = Patchs.ReadValueU32(); read = 4;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }
                                    temp = Patchs.ReadValueU32(); read = 4;
                                    if (!Convert.ToBoolean(blocksize) || temp == null || read != 4)
                                        return result.PATCH_CORRUPT;
                                    Sources.Seek(temp, SeekOrigin.Begin);
                                    //SetFilePointer(hSource, temp, 0, EMoveMethod.Begin);

                                    do
                                    {
                                        Sources.Read(block, 0, Convert.ToInt32(Math.Min(BLOCKSIZE, blocksize))); read = Math.Min(BLOCKSIZE, blocksize);
                                        if (block == null)
                                        {
                                            return result.PATCH_ERROR;
                                        }
                                        //IAsyncResult writeResult = Dests.BeginWrite(block,0,Convert.ToInt32(read),writeCallBack,"Write Target File");
                                        //Dests.EndWrite(writeResult);
                                        Dests.Write(block, 0, Convert.ToInt32(read));
                                        temp = read;
                                        //WriteFile(hDest, block, read, &temp, NULL);
                                        if (temp != Math.Min(BLOCKSIZE, blocksize))
                                            return result.PATCH_ERROR;
                                        blocksize -= temp;
                                    } while (Convert.ToBoolean(temp));

                                    break;

                                case 5:
                                case 6:
                                case 7:
                                    if (blocktype == 5)
                                    {
                                        Byte x;
                                        x = Convert.ToByte(Patchs.ReadByte()); read = 1;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }
                                    else if (blocktype == 6)
                                    {
                                        UInt16 x;
                                        x = Patchs.ReadValueU16(); read = 2;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }
                                    else
                                    {
                                        UInt32 x;
                                        x = Patchs.ReadValueU32(); read = 4;
                                        blocksize = Convert.ToUInt32(Convert.ToBoolean(x) ? x : 0);
                                    }

                                    if (!Convert.ToBoolean(blocksize))
                                        return result.PATCH_CORRUPT;

                                    do
                                    {
                                        Patchs.Read(block, 0, Convert.ToInt32(Math.Min(BLOCKSIZE, blocksize))); read = Math.Min(BLOCKSIZE, blocksize);
                                        if (block == null)
                                        {
                                            return result.PATCH_CORRUPT;
                                        }
                                        //IAsyncResult writeResult = Dests.BeginWrite(block, 0, Convert.ToInt32(read), writeCallBack, "Write Target File");
                                        //Dests.EndWrite(writeResult);
                                        Dests.Write(block, 0, Convert.ToInt32(read));
                                        temp = read;
                                        //WriteFile(hDest, block, read, &temp, NULL);
                                        if (temp != Math.Min(BLOCKSIZE, blocksize))
                                            return result.PATCH_ERROR;
                                        blocksize -= temp;
                                    } while (Convert.ToBoolean(temp));

                                    break;

                                case 255:   // read the file modified time from the patch
                                    targetModifiedTime.dwLowDateTime = (int)Patchs.ReadValueU32();
                                    targetModifiedTime.dwHighDateTime = (int)Patchs.ReadValueU32();

                                    /////////////////////////////////////////////////////////////////            //from System.Runtime.InteropServices.FILETIME to System.DateTime            /////////////////////////////////////////////////////////////////
                                    long _Value = (long) targetModifiedTime.dwHighDateTime << 32 | (long)(uint)targetModifiedTime.dwLowDateTime;
                                    dte = DateTime.FromFileTimeUtc(_Value);
                                    read = Convert.ToUInt32(Marshal.SizeOf(targetModifiedTime));
                                    //if(targetModifiedTime) {
                                    //return result.PATCH_CORRUPT;
                                    //}
                                    break;

                                default:
                                    return result.PATCH_CORRUPT;
                            }
                        }
                        if (!Convert.ToBoolean(MD5Mode))
                        {
                            return result.PATCH_UNSUPPORTED;
                        }
                        else
                        {

                           //int md5index;
                            byte[] dest_md5 = new byte[16];
                            Dests.Close();
                            Patchs.Close();
                            Sources.Close();
                            File.Delete(hPatchs);
                            File.Delete(hSources);
                            File.Move(hDests, hSources);
                            File.SetLastWriteTime(hSources, dte);
                            //FileStream Dest = new FileStream(hSources, FileMode.Open, FileAccess.Read, FileShare.None);
                            //dest_md5 = checksum.FileMD5(Dest, Data, -1);
                            //Dest.Close();
                            //if (dest_md5 == null)
                            //{
                             //   return result.PATCH_ERROR;
                           // }
                            //for (md5index = 0; md5index < 16; md5index++)
                            //{
                             //   if (dest_md5[md5index] != patch_dest_md5[md5index]) return result.PATCH_ERROR;
                            //}
                        }
                        // set file time

                        //SetFileTime(hDest, NULL, NULL, &targetModifiedTime);
                        return result.PATCH_SUCCESS;
                    }
                    else
                    {
                        Patchs.Seek(patch_size, SeekOrigin.Current);
                        //SetFilePointer(hPatch, patch_size, NULL, EMoveMethod.Current);
                    }
                }

                // if already up to date, it doesn't matter that we didn't match
                if (Convert.ToBoolean(already_uptodate))
                {
                    return result.PATCH_UPTODATE;
                }
                else
                {
                    return result.PATCH_NOMATCH;
                }
            }
            catch (Exception Err)
            {
                MessageBox.Show("出现错误:" + Err.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return result.PATCH_ERROR;
            }
        }
Exemple #7
0
 public FileStream(string path, FileMode mode)
 {
     this._buffer = FileStream.ReadBytes(path);
     this.name    = path;
 }
        public void checkEvents(int frames)
        {
            if (HighLogic.LoadedScene != prevScene)
            {
                KSPAlternateController.print(System.Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene));
                EventSubscriptions.dispatchEvent(ws, KSPEvents.KSP_SCENE_CHANGE, new KSPSceneChangeEvent(System.Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene)).toJson());
                prevScene = HighLogic.LoadedScene;
            }

            if (HighLogic.LoadedScene == GameScenes.EDITOR && EditorLogic.fetch != null)
            {
                if (EditorLogic.FlagURL != null && EditorLogic.FlagURL != "" && prevFlag != EditorLogic.FlagURL)
                {
                    prevFlag = EditorLogic.FlagURL;
                    try
                    {
                        using (FileStream sr = new FileStream("GameData/" + EditorLogic.FlagURL + ".png", FileMode.Open, FileAccess.Read))
                        {
                            String base64Flag = System.Convert.ToBase64String(sr.ReadBytes(sr.Length));
                            EventSubscriptions.dispatchEvent(ws, KSPEvents.EDITOR_FLAG_CHANGE, new EditorFlagChange(EditorLogic.FlagURL, base64Flag).toJson());
                        }
                    }
                    catch (Exception e)
                    {
                        KSPAlternateController.print(e.Message);
                    }
                }

            }

            if (HighLogic.LoadedScene == GameScenes.FLIGHT)
            {
                if (FlightGlobals.ActiveVessel != null)
                {
                    ActiveVesselAltVelEvent vs = new ActiveVesselAltVelEvent(System.Enum.GetName(typeof(FlightUIController.SpeedDisplayModes), FlightUIController.speedDisplayMode), FlightGlobals.ship_obtVelocity.magnitude,
                                                                             FlightGlobals.ship_srfVelocity.magnitude, FlightGlobals.ship_tgtVelocity.magnitude, FlightGlobals.ship_altitude);
                    EventSubscriptions.dispatchEvent(ws, KSPEvents.ACTIVE_VESSEL_VELALT_CHANGE, vs.toJson());

                    if (prevThrot != FlightGlobals.ActiveVessel.ctrlState.mainThrottle)
                    {
                        prevThrot = FlightGlobals.ActiveVessel.ctrlState.mainThrottle;
                        ActiveVesselThrottleChange tcu = new ActiveVesselThrottleChange(FlightGlobals.ActiveVessel.ctrlState.mainThrottle);
                        EventSubscriptions.dispatchEvent(ws, KSPEvents.ACTIVE_VESSEL_THROTTLE_CHANGE, tcu.toJson());
                    }
                }
                if (FlightGlobals.ready)
                {
                    foreach (Vessel v in FlightGlobals.Vessels)
                    {
                        bool sendUpdate = false;
                        String ID = v.id.ToString();
                        List<double> altVel;
                        if (!prevVessAltVel.ContainsKey(ID))
                        {
                            sendUpdate = true;
                            altVel = new List<double> { v.altitude, v.obt_velocity.magnitude, v.srf_velocity.magnitude };
                            // Altitude, orbitVelocity, surfaceVelocity
                            prevVessAltVel.Add(ID, altVel);
                        }
                        else
                        {
                            altVel = prevVessAltVel[ID];
                            if (altVel.Count >= 3)
                            {
                                if (altVel[0] != v.altitude && altVel[1] != v.obt_velocity.magnitude && altVel[2] != v.srf_velocity.magnitude)
                                {
                                    sendUpdate = true;
                                    prevVessAltVel[ID][0] = v.altitude;
                                    prevVessAltVel[ID][1] = v.obt_velocity.magnitude;
                                    prevVessAltVel[ID][2] = v.srf_velocity.magnitude;
                                    altVel = prevVessAltVel[ID];
                                }
                            }
                        }
                        if (sendUpdate)
                        {
                            VesselAltVelChangeEvent velaltchange = new VesselAltVelChangeEvent(altVel[0], altVel[1], altVel[2], ID);
                            SubEventSubscriptions.dispatchEvent(ws, KSPEvents.VESSEL_VELALT_CHANGE, velaltchange.toJson(), ID);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Loads a .mod file from given file and returns a nullable boolean (True, null, False).
        /// </summary>
        /// <param name="file">.mod file to load.</param>
        /// <param name="modCount">REF: Total number of jobs loaded.</param>
        /// <param name="progbar">ProgressBar to increment/change during method.</param>
        /// <param name="ExternalCall">If true, certain functions are disabled/automated.</param>
        /// <returns>True if update is to be done automatically, false if not, and null if user requests to stop loading .mod.</returns>
        public static bool? LoadDotMod(string file, ref int modCount, ToolStripProgressBar progbar, bool ExternalCall)
        {
            bool AutoUpdate = false;

            // KFreon: Load from file
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                // KFreon: Attempt to get version
                fs.Seek(0, SeekOrigin.Begin);
                int versionLength = fs.ReadValueS32();
                long countOffset = fs.Seek(0, SeekOrigin.Current);  // Just in case
                string version = "";
                int count = -1;
                string ExecutingVersion = null;
                bool validVersion = false;
                if (versionLength > 20)     // KFreon: Version is definitely wrong
                    ExecutingVersion = "";
                else
                {
                    // KFreon: Do version checking
                    for (int i = 0; i < versionLength; i++)
                        version += (char)fs.ReadByte();

                    // KFreon: Get Executing Version and check validity of read .mod version
                    string vers;
                    ExecutingVersion = GetVersion(version, out vers, out validVersion);
                    version = vers;

                    count = fs.ReadValueS32();

                    // KFreon: Check if update required
                    if (version != ExecutingVersion)
                    {
                        if (ExternalCall)
                            AutoUpdate = true;
                    }
                    else   // KFreon: Reset to null to signify success
                        ExecutingVersion = null;
                }

                
                // KFreon: Ask what to do about version
                if (ExecutingVersion != null) //&& !ExternalCall) // Heff: do we want to suppress this for external calls? should they always autoupdate?
                {                                                 // Seems better to keep it the current way, so that users get prompted if they load old .mods.
                    DialogResult dr = MessageBox.Show(Path.GetFileName(file) + " is old and unsupported by this version of ME3Explorer." + Environment.NewLine + "Click Yes to update .mod now, No to continue loading .mod, or Cancel to stop loading .mod", "Ancient .mod detected.", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                    if (dr == System.Windows.Forms.DialogResult.Cancel)
                        return null;
                    else if (dr == System.Windows.Forms.DialogResult.Yes)
                        AutoUpdate = true;
                }
                /*else if (ExecutingVersion != null) // Heff: could use this for always updating if its an external call:
                    AutoUpdate = true;*/

                // KFreon: Reset stream position if necessary
                if (!validVersion)
                {
                    count = versionLength;
                    fs.Seek(countOffset, SeekOrigin.Begin);
                }

                // KFreon: Increment progress bar
                if (progbar != null)
                    progbar.GetCurrentParent().Invoke(new Action(() =>
                    {
                        progbar.Value = 0;
                        progbar.Maximum = count;
                    }));

                // KFreon: Read Data
                DebugOutput.PrintLn("Found " + count + " Jobs", true);
                modCount += count;
                for (int i = 0; i < count; i++)
                {
                    // KFreon: Read name
                    ModMaker.ModJob md = new ModMaker.ModJob();
                    int len = fs.ReadValueS32();
                    md.Name = "";
                    for (int j = 0; j < len; j++)
                        md.Name += (char)fs.ReadByte();

                    // KFreon: Read script
                    len = fs.ReadValueS32();
                    md.Script = "";
                    for (int j = 0; j < len; j++)
                        md.Script += (char)fs.ReadByte();

                    // KFreon: Read data
                    len = fs.ReadValueS32();
                    byte[] buff = fs.ReadBytes(len);
                    md.data = buff;
                    ModMaker.JobList.Add(md);
                    DebugOutput.PrintLn("Add Job \"" + md.Name + "\"", true);

                    if (progbar != null)
                        progbar.GetCurrentParent().Invoke(new Action(() => progbar.Increment(1)));
                }
            }
            return AutoUpdate;
        }
        public void clean()
        {
            using (FileStream tocStream = new FileStream(tocFilePath, FileMode.Open, FileAccess.ReadWrite), newTocStream = File.Create(tocFilePath + ".tmp"))
            {
                tocStream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = tocStream.ReadBytes(8);
                newTocStream.WriteBytes(buffer);
                int count = tocStream.ReadValueS32();

                newTocStream.Seek(12, SeekOrigin.Begin);
                int newCount = 0;
                for (int i = 0; i < count; i++)
                {
                    int offset = tocStream.ReadValueS32();
                    int nextFiles = tocStream.ReadValueS32();
                    //if (offset != 0)
                    {
                        newCount++;
                        newTocStream.WriteValueS32(offset);
                        newTocStream.WriteValueS32(nextFiles);
                    }
                }
                //MessageBox.Show("pos: " + newTocStream.Position);
                newTocStream.Seek(8, SeekOrigin.Begin);
                newTocStream.WriteValueS32(newCount);

                int newDataOffset = 12 + (newCount * 8);

                //newTocStream.Seek(12 + (newCount * 8), SeekOrigin.Begin);
                //newTocStream.Seek(12, SeekOrigin.Begin);

                int oldDataOffset = 12 + (count * 8);
                int oldChunkOffset = 16;
                int newChunkOffset = 12;
                for (int i = 0; i < count; i++)
                {
                    //MessageBox.Show("pos: " + newTocStream.Length);
                    tocStream.Seek(oldChunkOffset, SeekOrigin.Begin);
                    oldChunkOffset += 8;
                    int numOfNextFiles = tocStream.ReadValueS32();
                    //oldChunkOffset += 4;
                    //MessageBox.Show("numofnextfiles: " + numOfNextFiles + " at pos: 0x" + oldChunkOffset.ToString("X4"));

                    /*if (numOfNextFiles == 0)
                    {
                        //newChunkOffset -= 4;
                        newTocStream.Seek(newChunkOffset, SeekOrigin.Begin);
                        continue;
                    }*/

                    //newChunkOffset += 4;
                    newTocStream.Seek(newChunkOffset, SeekOrigin.Begin);
                    if(numOfNextFiles == 0)
                        newTocStream.WriteValueS32(0);
                    else
                        newTocStream.WriteValueS32((int)newTocStream.Length - newChunkOffset);
                    newTocStream.WriteValueS32(numOfNextFiles);
                    newChunkOffset = (int)newTocStream.Position;
                    newTocStream.Seek(0, SeekOrigin.End);

                    for (int j = 0; j < numOfNextFiles; j++)
                    {
                        short size;
                        tocStream.Seek(oldDataOffset, SeekOrigin.Begin);
                        size = tocStream.ReadValueS16();
                        tocStream.Seek(oldDataOffset, SeekOrigin.Begin);
                        oldDataOffset += size;
                        buffer = tocStream.ReadBytes(size);
                        newTocStream.Seek(newDataOffset, SeekOrigin.Begin);
                        newTocStream.WriteBytes(buffer);
                        newDataOffset = (int)newTocStream.Position;
                    }
                }
            }
        }