Exemplo n.º 1
0
        private bool ReadField(ObjectReader objectReader, Dictionary <LightField, int> fieldValues, LightField field)
        {
            switch (field)
            {
            case LightField.End:
                return(false);

            case LightField.LightType:
                InfoText += $"{field}: {(LightType)objectReader.ReadByte()}\n";
                return(true);

            case LightField.CutOffAngle:
            case LightField.CutOffAnglePhi:
                InfoText += $"{field}: {Math.Round(objectReader.ReadSingle() * 180.0 / Math.PI)}\n";
                return(true);

            case LightField.Colour:
                InfoText += $"{field}: {string.Join(", ", objectReader.ReadByte(), objectReader.ReadByte(), objectReader.ReadByte())}\n";
                return(true);

            default:
                InfoText += $"{field}: {objectReader.ReadSingle()}\n";
                return(true);
            }
        }
Exemplo n.º 2
0
        private bool ReadField(ObjectReader objectReader, Dictionary <TextField, int> fieldValues, TextField field)
        {
            switch (field)
            {
            case TextField.End:
                return(false);

            case TextField.Colour:
            case TextField.BackColour:
                _infoText += $"{field}: {string.Join(", ", objectReader.ReadByte(), objectReader.ReadByte(), objectReader.ReadByte())}\n";
                objectReader.ReadByte();
                return(true);

            case TextField.Font:
                _infoText += $"{field}: {MxrObjectReader.ReadString(objectReader)}\n";
                return(true);

            case TextField.Byte22:
                _infoText += $"{field}: {objectReader.ReadByte()}\n";
                return(true);

            case TextField.String:
                var count = objectReader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    _infoText += $"{field}[{i}]: {MxrObjectReader.ReadString(objectReader)}\n";
                }
                return(true);

            default:
                _infoText += $"{field}: {objectReader.ReadInt32()}\n";
                return(true);
            }
        }
Exemplo n.º 3
0
        private ChecksumWithChildren DeserializeChecksumWithChildren(ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var kind     = (WellKnownSynchronizationKind)reader.ReadInt32();
            var checksum = Checksum.ReadFrom(reader);

            var childrenCount = reader.ReadInt32();
            var children      = new object[childrenCount];

            for (var i = 0; i < childrenCount; i++)
            {
                var childKind = reader.ReadByte();
                if (childKind == ChecksumKind)
                {
                    children[i] = Checksum.ReadFrom(reader);
                    continue;
                }

                if (childKind == ChecksumWithChildrenKind)
                {
                    children[i] = DeserializeChecksumWithChildren(reader, cancellationToken);
                    continue;
                }

                throw ExceptionUtilities.UnexpectedValue(childKind);
            }

            var checksums = s_creatorMap[kind](children);

            Contract.ThrowIfFalse(checksums.Checksum == checksum);

            return(checksums);
        }
Exemplo n.º 4
0
        internal static DeclaredSymbolInfo ReadFrom(ObjectReader reader)
        {
            try
            {
                var name = reader.ReadString();
                var immediateContainer = reader.ReadString();
                var entireContainer    = reader.ReadString();
                var kind               = (DeclaredSymbolInfoKind)reader.ReadByte();
                var spanStart          = reader.ReadInt32();
                var spanLength         = reader.ReadInt32();
                var parameterCount     = reader.ReadUInt16();
                var typeParameterCount = reader.ReadUInt16();

                var inheritanceNamesLength = reader.ReadInt32();
                var builder = ImmutableArray.CreateBuilder <string>(inheritanceNamesLength);
                for (var i = 0; i < inheritanceNamesLength; i++)
                {
                    builder.Add(reader.ReadString());
                }

                return(new DeclaredSymbolInfo(
                           name, immediateContainer, entireContainer, kind, new TextSpan(spanStart, spanLength),
                           builder.MoveToImmutable(),
                           parameterCount, typeParameterCount));
            }
            catch
            {
                return(default(DeclaredSymbolInfo));
            }
        }
Exemplo n.º 5
0
        private bool ReadField(ObjectReader objectReader, Dictionary <MovieField, int> fieldValues, MovieField field)
        {
            switch (field)
            {
            case MovieField.End:
                return(false);

            case MovieField.UnknownByte19:
            case MovieField.UnknownByte20:
            case MovieField.UnknownByte21:
            case MovieField.UnknownByte22:
            case MovieField.UnknownByte23:
            case MovieField.UnknownByte24:
                InfoText += $"{field}: {objectReader.ReadByte()}\n";
                return(true);

            case MovieField.UnknownInt16:
            case MovieField.UnknownInt17:
            case MovieField.UnknownInt18:
            case MovieField.Width:
            case MovieField.Height:
            case MovieField.UnknownInt52:
                InfoText += $"{field}: {objectReader.ReadInt32()}\n";
                return(true);

            case MovieField.UnknownArray32:
                InfoText += $"{field}: [{string.Join(", ", Enumerable.Range(0, objectReader.ReadInt32()).Select(i => objectReader.ReadByte()))}]\n";
                return(true);

            default:
                throw new NotImplementedException();
            }
        }
        private ChecksumObjectWithChildren DeserializeChecksumObjectWithChildren(ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var kind     = reader.ReadString();
            var checksum = Checksum.ReadFrom(reader);

            var childrenCount = reader.ReadInt32();
            var children      = new object[childrenCount];

            for (var i = 0; i < childrenCount; i++)
            {
                var childKind = reader.ReadByte();
                if (childKind == ChecksumKind)
                {
                    children[i] = Checksum.ReadFrom(reader);
                    continue;
                }

                if (childKind == ChecksumCollectionKind)
                {
                    children[i] = DeserializeChecksumObjectWithChildren(reader, cancellationToken);
                    continue;
                }

                throw ExceptionUtilities.UnexpectedValue(childKind);
            }

            var checksumObject = s_creatorMap[kind](this, kind, children);

            Contract.ThrowIfFalse(checksum.Equals(checksumObject.Checksum));

            return(checksumObject);
        }
Exemplo n.º 7
0
        public void TestRoundTripPrimitives()
        {
            var stream = new MemoryStream();
            var writer = new ObjectWriter(stream);

            writer.WriteBoolean(true);
            writer.WriteBoolean(false);
            writer.WriteByte(Byte.MaxValue);
            writer.WriteSByte(SByte.MaxValue);
            writer.WriteInt16(Int16.MaxValue);
            writer.WriteInt32(Int32.MaxValue);
            writer.WriteInt32(Byte.MaxValue);
            writer.WriteInt32(Int16.MaxValue);
            writer.WriteInt64(Int64.MaxValue);
            writer.WriteUInt16(UInt16.MaxValue);
            writer.WriteUInt32(UInt32.MaxValue);
            writer.WriteUInt64(UInt64.MaxValue);
            writer.WriteDecimal(Decimal.MaxValue);
            writer.WriteDouble(Double.MaxValue);
            writer.WriteSingle(Single.MaxValue);
            writer.WriteChar('X');
            writer.WriteString("YYY");
            writer.WriteCompressedUInt(Byte.MaxValue >> 2);   // 6 bits
            writer.WriteCompressedUInt(UInt16.MaxValue >> 2); // 14 bits
            writer.WriteCompressedUInt(UInt32.MaxValue >> 2); // 30 bits
            var dt = DateTime.Now;

            writer.WriteDateTime(dt);
            writer.Dispose();

            stream.Position = 0;
            var reader = new ObjectReader(stream);

            Assert.Equal(true, reader.ReadBoolean());
            Assert.Equal(false, reader.ReadBoolean());
            Assert.Equal(Byte.MaxValue, reader.ReadByte());
            Assert.Equal(SByte.MaxValue, reader.ReadSByte());
            Assert.Equal(Int16.MaxValue, reader.ReadInt16());
            Assert.Equal(Int32.MaxValue, reader.ReadInt32());
            Assert.Equal(Byte.MaxValue, reader.ReadInt32());
            Assert.Equal(Int16.MaxValue, reader.ReadInt32());
            Assert.Equal(Int64.MaxValue, reader.ReadInt64());
            Assert.Equal(UInt16.MaxValue, reader.ReadUInt16());
            Assert.Equal(UInt32.MaxValue, reader.ReadUInt32());
            Assert.Equal(UInt64.MaxValue, reader.ReadUInt64());
            Assert.Equal(Decimal.MaxValue, reader.ReadDecimal());
            Assert.Equal(Double.MaxValue, reader.ReadDouble());
            Assert.Equal(Single.MaxValue, reader.ReadSingle());
            Assert.Equal('X', reader.ReadChar());
            Assert.Equal("YYY", reader.ReadString());
            Assert.Equal((UInt32)(Byte.MaxValue >> 2), reader.ReadCompressedUInt());
            Assert.Equal((UInt32)(UInt16.MaxValue >> 2), reader.ReadCompressedUInt());
            Assert.Equal(UInt32.MaxValue >> 2, reader.ReadCompressedUInt());
            Assert.Equal(dt, reader.ReadDateTime());
            reader.Dispose();
        }
        public virtual Encoding ReadEncodingFrom(ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var serialized = reader.ReadByte();

            // portable layer doesn't support serialization
            Contract.ThrowIfFalse(serialized == NoEncodingSerialization);
            return(ReadEncodingFrom(serialized, reader, cancellationToken));
        }
Exemplo n.º 9
0
        public static Checksum ReadFrom(ObjectReader reader)
        {
            var length  = reader.ReadInt32();
            var builder = ImmutableArray.CreateBuilder <byte>(length);

            for (var i = 0; i < length; i++)
            {
                builder.Add(reader.ReadByte());
            }

            return(new Checksum(builder.MoveToImmutable()));
        }
Exemplo n.º 10
0
        private bool ReadField(ObjectReader objectReader, Dictionary <CameraField, int> fieldValues, CameraField field)
        {
            switch (field)
            {
            case CameraField.End:
                return(false);

            case CameraField.FogColour:
                InfoText += $"{field}: {string.Join(", ", objectReader.ReadByte(), objectReader.ReadByte(), objectReader.ReadByte())}\n";
                objectReader.ReadByte();
                return(true);

            case CameraField.FogEnabled:
            case CameraField.Unknown37:
                InfoText += $"{field}: {objectReader.ReadInt32()}\n";
                return(true);

            default:
                InfoText += $"{field}: {objectReader.ReadSingle()}\n";
                return(true);
            }
        }
Exemplo n.º 11
0
        private static BitArray ReadBitArray(ObjectReader reader)
        {
            // TODO: find a way to use pool
            var length = reader.ReadInt32();
            var bytes  = new byte[length];

            for (var i = 0; i < bytes.Length; i++)
            {
                bytes[i] = reader.ReadByte();
            }

            return(new BitArray(bytes));
        }
Exemplo n.º 12
0
        public static Dictionary <T, int> Read <T>(ObjectReader objectReader,
                                                   Func <ObjectReader, Dictionary <T, int>, T, bool> readField) where T : Enum
        {
            var fieldValues = new Dictionary <T, int>();

            while (true)
            {
                // Check for end of file
                if (objectReader.Position == objectReader.BaseStream.Length)
                {
                    return(fieldValues);
                }

                var fieldByte = objectReader.ReadByte();
                var field     = (T)Enum.ToObject(typeof(T), fieldByte);

                if (!readField(objectReader, fieldValues, field))
                {
                    fieldValues[field] = objectReader.ReadByte();
                    return(fieldValues);
                }
            }
        }
            public override Encoding ReadEncodingFrom(ObjectReader reader, CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var serialized = reader.ReadByte();

                if (serialized == EncodingSerialization)
                {
                    var array     = (byte[])reader.ReadValue();
                    var formatter = new BinaryFormatter();

                    return((Encoding)formatter.Deserialize(new MemoryStream(array)));
                }

                return(ReadEncodingFrom(serialized, reader, cancellationToken));
            }
Exemplo n.º 14
0
        internal static DeclaredSymbolInfo ReadFrom(ObjectReader reader)
        {
            try
            {
                var name               = reader.ReadString();
                var container          = reader.ReadString();
                var kind               = (DeclaredSymbolInfoKind)reader.ReadByte();
                var spanStart          = reader.ReadInt32();
                var spanLength         = reader.ReadInt32();
                var parameterCount     = reader.ReadUInt16();
                var typeParameterCount = reader.ReadUInt16();

                return(new DeclaredSymbolInfo(name, container, kind, new TextSpan(spanStart, spanLength), parameterCount, typeParameterCount));
            }
            catch
            {
                return(default(DeclaredSymbolInfo));
            }
        }
Exemplo n.º 15
0
        public static BitArray ReadFrom(this ObjectReader reader)
        {
            var version = reader.ReadString();

            if (!string.Equals(version, SerializationFormat, StringComparison.Ordinal))
            {
                return(null);
            }

            // TODO: find a way to use pool
            var length = reader.ReadInt32();
            var bytes  = new byte[length];

            for (var i = 0; i < bytes.Length; i++)
            {
                bytes[i] = reader.ReadByte();
            }

            return(new BitArray(bytes));
        }
Exemplo n.º 16
0
        public bool ReadField(ObjectReader objectReader, Dictionary <ScoreField, int> fieldValues, ScoreField field)
        {
            switch (field)
            {
            case ScoreField.End:
                m_Script = Encoding.UTF8.GetBytes(_infoText);
                return(false);

            case ScoreField.Index:
                _infoText += $"{field}: {objectReader.ReadInt32()}\n";
                return(true);

            case ScoreField.Name:
                m_Name = MxrObjectReader.ReadString(objectReader);
                objectReader.Position--;
                return(false);

            case ScoreField.UnknownArray33:
                if (objectReader.ReadByte() != 0)
                {
                    throw new InvalidDataException();
                }

                var bytes = Enumerable.Range(0, objectReader.ReadInt32()).Select(i => objectReader.ReadByte()).ToList();
                _infoText += $"{field}: {bytes.Count} {{\n    {string.Join(",", bytes)}\n}}\n";
                return(true);

            case ScoreField.UnknownArray34:
                var strings = new List <object>();
                for (int i = 0; objectReader.ReadUInt32() != UInt32.MaxValue; i++)
                {
                    objectReader.BaseStream.Position -= 4;
                    strings.Add($"    {objectReader.ReadInt32()}, {MxrObjectReader.ReadString(objectReader)}, {objectReader.ReadInt32()}");
                }
                _infoText += $"{field}: {strings.Count} {{\n{string.Join(Environment.NewLine, strings)}\n}}\n";
                return(true);

            default:
                throw new InvalidDataException();
            }
        }
Exemplo n.º 17
0
        public override CompilationOptions ReadCompilationOptionsFrom(ObjectReader reader, CancellationToken cancellationToken)
        {
            ReadCompilationOptionsFrom(
                reader,
                out var outputKind, out var reportSuppressedDiagnostics, out var moduleName, out var mainTypeName, out var scriptClassName,
                out var optimizationLevel, out var checkOverflow, out var cryptoKeyContainer, out var cryptoKeyFile, out var cryptoPublicKey,
                out var delaySign, out var platform, out var generalDiagnosticOption, out var warningLevel, out var specificDiagnosticOptions,
                out var concurrentBuild, out var deterministic, out var publicSign, out var metadataImportOptions,
                out var xmlReferenceResolver, out var sourceReferenceResolver, out var metadataReferenceResolver, out var assemblyIdentityComparer,
                out var strongNameProvider, cancellationToken);

            var usings                 = reader.ReadArray <string>();
            var allowUnsafe            = reader.ReadBoolean();
            var nullableContextOptions = (NullableContextOptions)reader.ReadByte();

            return(new CSharpCompilationOptions(
                       outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe,
                       cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild,
                       deterministic, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, publicSign,
                       metadataImportOptions, nullableContextOptions));
        }
Exemplo n.º 18
0
 private static void TestReadingPrimitiveAPIs(ObjectReader reader)
 {
     Assert.Equal(true, reader.ReadBoolean());
     Assert.Equal(false, reader.ReadBoolean());
     Assert.Equal(Byte.MaxValue, reader.ReadByte());
     Assert.Equal(SByte.MaxValue, reader.ReadSByte());
     Assert.Equal(Int16.MaxValue, reader.ReadInt16());
     Assert.Equal(Int32.MaxValue, reader.ReadInt32());
     Assert.Equal(Byte.MaxValue, reader.ReadInt32());
     Assert.Equal(Int16.MaxValue, reader.ReadInt32());
     Assert.Equal(Int64.MaxValue, reader.ReadInt64());
     Assert.Equal(UInt16.MaxValue, reader.ReadUInt16());
     Assert.Equal(UInt32.MaxValue, reader.ReadUInt32());
     Assert.Equal(UInt64.MaxValue, reader.ReadUInt64());
     Assert.Equal(Decimal.MaxValue, reader.ReadDecimal());
     Assert.Equal(Double.MaxValue, reader.ReadDouble());
     Assert.Equal(Single.MaxValue, reader.ReadSingle());
     Assert.Equal('X', reader.ReadChar());
     Assert.Equal("YYY", reader.ReadString());
     Assert.Equal("\uD800\uDC00", reader.ReadString()); // valid surrogate pair
     Assert.Equal("\uDC00\uD800", reader.ReadString()); // invalid surrogate pair
     Assert.Equal("\uD800", reader.ReadString());       // incomplete surrogate pair
 }
Exemplo n.º 19
0
        public static string Read(ObjectReader objectReader, int frameCount)
        {
            var field       = AnimationField.FrameBits;
            var counts      = new List <int>();
            var destination = new StringBuilder();
            var frame       = 0;

            ReadBitArray(objectReader, destination, field, counts, frameCount);

            var sections = new List <AnimationField>
            {
                AnimationField.Positions,
                AnimationField.Rotations,
                AnimationField.Scales,
                AnimationField.PositionBits,
                AnimationField.RotationBits,
                AnimationField.ScaleBits
            };

            while (objectReader.BaseStream.Position < objectReader.BaseStream.Length - 1)
            {
                var frameRepeats = (int)objectReader.ReadByte();
                if (frameRepeats == 255)
                {
                    break;
                }

                if (frameRepeats == (int)sections[0] || (sections[0] == AnimationField.PositionBits && frameRepeats == 34))
                {
                    var nextByte = objectReader.ReadByte();
                    objectReader.BaseStream.Position--;

                    if (field == AnimationField.FrameBits || frame + frameRepeats > frameCount)
                    {
                        field = (AnimationField)frameRepeats;

                        while (frameRepeats != (int)sections[0])
                        {
                            sections.RemoveAt(0);
                        }

                        sections.RemoveAt(0);
                        counts.Add(0);
                        frame = 0;

                        if (field >= AnimationField.Positions)
                        {
                            destination.AppendLine(field.ToString());
                            frameRepeats = objectReader.ReadByte();
                        }
                    }
                }

                if (field == AnimationField.PositionBits)
                {
                    counts.RemoveAt(counts.Count - 1);

                    ReadBitArray(objectReader, destination, field, counts, counts[1]);
                    field = (AnimationField)objectReader.ReadByte();
                    if (field != AnimationField.RotationBits)
                    {
                        throw new InvalidDataException();
                    }
                }

                if (field == AnimationField.RotationBits)
                {
                    ReadBitArray(objectReader, destination, field, counts, counts[2]);
                    field = (AnimationField)objectReader.ReadByte();
                    if (field == AnimationField.End)
                    {
                        break;
                    }
                    if (field != AnimationField.ScaleBits)
                    {
                        throw new InvalidDataException();
                    }

                    ReadBitArray(objectReader, destination, field, counts, counts[3]);
                    field = (AnimationField)objectReader.ReadByte();
                    if (field != AnimationField.End)
                    {
                        throw new InvalidDataException();
                    }

                    break;
                }

                if (frameRepeats == 128)
                {
                    frameRepeats = objectReader.ReadInt32();
                }

                var length  = objectReader.ReadByte();
                var content = Enumerable.Range(0, length * 3)
                              .Select(i => objectReader.ReadSingle())
                              .ToArray();

                destination.AppendLine($"    Frames {frame}-{frame + frameRepeats}: " + string.Join(", ", content));
                counts[counts.Count - 1] += length;
                frame += frameRepeats + length;
            }

            return(Environment.NewLine + destination.ToString());
        }
Exemplo n.º 20
0
        private bool ReadField(ObjectReader objectReader, Dictionary <WaveField, int> fieldValues, WaveField field)
        {
            switch (field)
            {
            case WaveField.End:
                return(false);

            case WaveField.RiffData:
                var unknown1       = objectReader.ReadBytes(6);
                var format         = objectReader.ReadUInt16();
                var channels       = objectReader.ReadUInt16();
                var samplesPerSec  = objectReader.ReadUInt32();
                var avgBytesPerSec = objectReader.ReadUInt32();
                var blockAlign     = objectReader.ReadUInt16();
                var bitsPerSample  = objectReader.ReadUInt16();
                var extraSize      = objectReader.ReadUInt16();

                var unknown2   = objectReader.ReadBytes(6);
                var fmtLength  = format == WAVE_FORMAT_PCM ? 16 : (18 + extraSize);
                var dataLength = (int)objectReader.ReadUInt32() - extraSize;

                var audioData = new MemoryStream();
                using (var destination = new BinaryWriter(audioData, Encoding.ASCII, true))
                {
                    destination.Write(Encoding.ASCII.GetBytes("RIFF"));
                    destination.Write(dataLength + 20 + fmtLength);
                    destination.Write(Encoding.ASCII.GetBytes("WAVEfmt "));
                    destination.Write(fmtLength);
                    destination.Write(format);
                    destination.Write(channels);
                    destination.Write(samplesPerSec);
                    destination.Write(avgBytesPerSec);
                    destination.Write(blockAlign);
                    destination.Write(bitsPerSample);

                    if (format == WAVE_FORMAT_DVI_ADPCM)
                    {
                        // See https://icculus.org/SDL_sound/downloads/external_documentation/wavecomp.htm
                        var samplesPerBlock = objectReader.ReadUInt16();
                        destination.Write(extraSize);
                        destination.Write(samplesPerBlock);
                        destination.Write(Encoding.ASCII.GetBytes("fact"));
                        destination.Write(4);
                        destination.Write(samplesPerBlock * dataLength / blockAlign);
                    }

                    destination.Write(Encoding.ASCII.GetBytes("data"));
                    destination.Write(dataLength);
                    destination.Write(objectReader.ReadBytes(dataLength));
                }

                m_Type      = AudioType.WAV;
                m_Size      = audioData.Length;
                m_AudioData = new ResourceReader(new BinaryReader(audioData), 0, (int)audioData.Length);
                return(true);

            case WaveField.UnknownByte:
                fieldValues.Add(field, objectReader.ReadByte());
                return(true);

            default:
                fieldValues.Add(field, objectReader.ReadInt32());
                return(true);
            }
        }
Exemplo n.º 21
0
        private bool ReadField(ObjectReader objectReader, Dictionary <ModelField, int> fieldValues, ModelField field)
        {
            switch (field)
            {
            case ModelField.End:
                m_SubMeshes = _subMeshes.ToArray();
                if (_faceGroups == null)
                {
                    m_SubMeshes.Single().indices = _indices;
                }
                else
                {
                    for (int i = 0; i < _faceGroups.Length; i++)
                    {
                        foreach (var j in _indicesByFace[i])
                        {
                            var subMeshIndices = m_SubMeshes[_faceGroups[i]].indices;
                            subMeshIndices.Add(_indices[j + 0]);
                            subMeshIndices.Add(_indices[j + 1]);
                            subMeshIndices.Add(_indices[j + 2]);
                        }
                    }
                }
                return(false);

            case ModelField.UnknownMarker19:
                return(true);

            case ModelField.UnknownShort150:
                _subMesh.Properties.Add(field, objectReader.ReadInt16());
                return(true);

            case ModelField.UnknownArray22:
                var unknown22 = objectReader.ReadBytes((int)_subMesh.Properties[ModelField.VertexCount]);
                _subMesh.Properties.Add(field, unknown22.Count());
                return(true);

            case ModelField.Vertices:
                m_VertexCount = (int)_subMesh.Properties[ModelField.VertexCount];
                m_Vertices    = objectReader.ReadSingleArray(3 * m_VertexCount);
                return(true);

            case ModelField.FacesSingle:
                _subMesh.Properties[field] = objectReader.ReadByte();
                var indices = objectReader.ReadBytes((int)_subMesh.Properties[ModelField.IndexCount]);
                UnpackFaces(indices.Select(b => (ushort)b).ToArray());
                return(true);

            case ModelField.FacesDouble:
                UnpackFaces(Enumerable.Range(0, (int)_subMesh.Properties[ModelField.IndexCount])
                            .Select(i => objectReader.ReadUInt16()).ToArray());
                return(true);

            case ModelField.FaceGroups34:
                if ((int)_subMesh.Properties[ModelField.IndexCount] != 0)
                {
                    _faceGroups = Enumerable.Range(0, (int)_subMesh.Properties[ModelField.FaceCount])
                                  .Select(i => objectReader.ReadInt16())
                                  .ToArray();
                }
                return(true);

            case ModelField.FaceGroups36:
                var bitsPerItem = objectReader.ReadByte();
                var byteCount   = (int)_subMesh.Properties[ModelField.FaceCount] * bitsPerItem / 32.0;
                var faceGroups  = objectReader.ReadBytes((int)Math.Ceiling(byteCount));
                if (bitsPerItem == 16)
                {
                    faceGroups = faceGroups.SelectMany(b => new[]
                    {
                        (byte)((b & 0xF0) >> 4),
                        (byte)(b & 0x0F)
                    })
                                 .ToArray();
                }

                if (byteCount != Math.Ceiling(byteCount))
                {
                    faceGroups = faceGroups.Take(faceGroups.Length - 1).ToArray();
                }
                _faceGroups = faceGroups.Select(b => (short)b).ToArray();
                return(true);

            case ModelField.UnknownArray113:
                _subMesh.Properties.Add(field, objectReader.ReadBytes(12));
                return(true);

            case ModelField.UnknownArray115:
                _subMesh.Properties.Add(field, Enumerable.Range(0, 6)
                                        .Select(i => objectReader.ReadUInt32())
                                        .Where(i => i != uint.MaxValue)
                                        .ToArray());
                return(true);

            case ModelField.MaterialAmbient:
                _subMesh.color = Enumerable.Range(0, 4).Select(i => objectReader.ReadSingle()).ToArray();
                return(true);

            case ModelField.MaterialPower:
            case ModelField.MaterialEmissive:
            case ModelField.MaterialSpecular:
                _subMesh.Properties.Add(field, Enumerable.Range(0, 4)
                                        .Select(i => objectReader.ReadSingle())
                                        .ToArray());
                return(true);

            case ModelField.UnknownShort149:
            case ModelField.UnknownShort151:
                _subMesh.Properties.Add(field, objectReader.ReadInt16());
                return(true);

            case ModelField.FaceCount:
            case ModelField.IndexCount:
            case ModelField.VertexCount:
            case ModelField.UnknownInt21:
            case ModelField.UnknownInt23:
            case ModelField.UnknownInt112:
            case ModelField.UnknownInt114:
            case ModelField.Texture:
            case ModelField.UnknownInt129:
            case ModelField.UnknownInt130:
            case ModelField.TextureGroup:
            case ModelField.UnknownInt152:
            case ModelField.UnknownInt154:
            case ModelField.UnknownInt176:
            case ModelField.UnknownInt178:
            case ModelField.UnknownInt192:
            case ModelField.UnknownInt193:
            case ModelField.UnknownInt194:
            case ModelField.UnknownInt195:
            case ModelField.UnknownInt198:
            case ModelField.UnknownInt199:
            case ModelField.UnknownInt200:
            case ModelField.UnknownInt201:
            case ModelField.UnknownInt202:
                if (_subMesh == null || _subMesh.Properties.ContainsKey(field))
                {
                    _subMeshes.Add(_subMesh = new MxrSubMesh());
                }
                _subMesh.Properties.Add(field, objectReader.ReadInt32());
                return(true);

            case ModelField.UnknownFloat148:
            case ModelField.TextureDivisionU:
            case ModelField.TextureDivisionV:
            case ModelField.TexturePositionU:
            case ModelField.TexturePositionV:
            case ModelField.TextureRotateX:
            case ModelField.TextureRotateY:
            case ModelField.TextureRotateZ:
            case ModelField.UnknownFloat196:
            case ModelField.UnknownFloat197:
                _subMesh.Properties.Add(field, objectReader.ReadSingle());
                return(true);

            case ModelField.GroupName:
                _subMesh.Properties.Add(field, _subMeshes.Count + " " + MxrObjectReader.ReadString(objectReader));
                return(true);

            default:
                throw new NotImplementedException();
            }
        }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray <byte> cryptoPublicKey,
            out bool?delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out MetadataImportOptions metadataImportOptions,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName   = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName   = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow     = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile      = reader.ReadString();

            cryptoPublicKey = reader.ReadArray <byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List <KeyValuePair <string, ReportDiagnostic> >(count);

                for (var i = 0; i < count; i++)
                {
                    var key   = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePairUtil.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable <KeyValuePair <string, ReportDiagnostic> >();

            concurrentBuild = reader.ReadBoolean();
            deterministic   = reader.ReadBoolean();
            publicSign      = reader.ReadBoolean();

            metadataImportOptions = (MetadataImportOptions)reader.ReadByte();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver      = XmlFileResolver.Default;
            sourceReferenceResolver   = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer  = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider        = new DesktopStrongNameProvider();
        }
Exemplo n.º 23
0
        private bool ReadField(ObjectReader objectReader, Dictionary <TextureField, int> fieldValues, TextureField field)
        {
            switch (field)
            {
            case TextureField.End:
                return(false);

            case TextureField.JpegData:
                using (var jpeg = new Bitmap(new MemoryStream(objectReader.ReadBytes(objectReader.ReadInt32()))))
                {
                    m_Width  = jpeg.Width;
                    m_Height = jpeg.Height;

                    var data    = jpeg.LockBits(new Rectangle(0, 0, m_Width, m_Height), ImageLockMode.ReadOnly, jpeg.PixelFormat);
                    var strides = new byte[data.Stride * jpeg.Height];
                    Marshal.Copy(data.Scan0, strides, 0, strides.Length);
                    jpeg.UnlockBits(data);

                    var rgb   = new byte[m_Width * m_Height * 4];
                    var index = 0;
                    for (int row = 0; row < m_Height; row++)
                    {
                        for (int column = 0; column < m_Width; column++)
                        {
                            var offset = (m_Height - row - 1) * data.Stride;

                            switch (jpeg.PixelFormat)
                            {
                            case PixelFormat.Format24bppRgb:
                                offset      += column * 3;
                                rgb[index++] = strides[offset++];
                                rgb[index++] = strides[offset++];
                                rgb[index++] = strides[offset];
                                rgb[index++] = 255;
                                break;

                            case PixelFormat.Format8bppIndexed:
                                var colour = jpeg.Palette.Entries[strides[offset + column]];
                                rgb[index++] = colour.B;
                                rgb[index++] = colour.G;
                                rgb[index++] = colour.R;
                                rgb[index++] = colour.A;
                                break;

                            default:
                                throw new NotImplementedException();
                            }
                        }
                    }

                    _pixels    = new MemoryStream(rgb);
                    image_data = new ResourceReader(new BinaryReader(_pixels), 0, rgb.Length);
                }
                return(true);

            case TextureField.BmpColourTable:
                _colours = objectReader.ReadUInt32Array(fieldValues[TextureField.Colours]);
                return(true);

            case TextureField.Tranparent:
                _transparent = objectReader.ReadUInt32() | 0xff000000;
                return(true);

            case TextureField.BmpPixelData:
                using (var memoryWriter = new BinaryWriter(_pixels = new MemoryStream(), Encoding.Default, true))
                {
                    m_Width  = fieldValues[TextureField.Width];
                    m_Height = fieldValues[TextureField.Height];

                    var bitsPerPixel = fieldValues[TextureField.BitsPerPixel];
                    var rowBytes     = (int)Math.Ceiling((m_Width * bitsPerPixel) / 8.0) % 4;

                    for (int row = 0; row < m_Height; row++)
                    {
                        for (int column = 0; column < m_Width; column++)
                        {
                            switch (bitsPerPixel)
                            {
                            case 4:
                                var b = objectReader.ReadByte();
                                WriteColour(memoryWriter, _colours[b >> 4]);
                                if (++column < m_Width)
                                {
                                    WriteColour(memoryWriter, _colours[b & 0x0f]);
                                }
                                break;

                            case 8:
                                WriteColour(memoryWriter, _colours[objectReader.ReadByte()]);
                                break;

                            case 24:
                                WriteColour(memoryWriter, objectReader.ReadUInt32());
                                objectReader.Position--;
                                break;

                            default:
                                throw new NotImplementedException();
                            }
                        }

                        // Align rows to multiples of 32 bits
                        if (rowBytes != 0)
                        {
                            objectReader.ReadBytes(4 - rowBytes);
                        }
                    }

                    image_data = new ResourceReader(new BinaryReader(_pixels), 0, (int)_pixels.Length);
                }
                return(true);

            case TextureField.BitsPerPixel:
            case TextureField.UnknownShort31:
                fieldValues.Add(field, objectReader.ReadUInt16());
                InfoText += $"{field}: {fieldValues[field]}\n";
                return(true);

            case TextureField.UnknownByte22:
            case TextureField.UnknownByte27:
            case TextureField.UnknownByte128:
            case TextureField.UnknownByte129:
                fieldValues.Add(field, objectReader.ReadByte());
                InfoText += $"{field}: {fieldValues[field]}\n";
                return(true);

            case TextureField.UnknownArray99:
                fieldValues.Add(field, objectReader.ReadInt32());
                InfoText += $"{field}: {fieldValues[field]} [{string.Join(", ", Enumerable.Range(0, 12).Select(i => objectReader.ReadByte()))}]\n";
                return(true);

            case TextureField.AlphaMap:
                fieldValues.Add(field, objectReader.ReadInt32());
                var alphaMap = new BitArray(objectReader.ReadBytes(fieldValues[field]));
                var stride   = alphaMap.Length / m_Height;
                for (int row = 0; row < m_Height; row++)
                {
                    for (int column = 0; column < m_Width; column++)
                    {
                        var endianColumn = 8 * (column / 8);
                        endianColumn += 7 - (column % 8);

                        if (!alphaMap[(row * stride) + endianColumn])
                        {
                            _pixels.Position = ((row * m_Width) + column) * 4 + 3;
                            _pixels.WriteByte(0);
                        }
                    }
                }
                return(true);

            default:
                fieldValues.Add(field, objectReader.ReadInt32());
                InfoText += $"{field}: {fieldValues[field]}\n";
                return(true);
            }
        }
Exemplo n.º 24
0
        private bool ReadField(ObjectReader objectReader, Dictionary <TrackField, int> fieldValues, TrackField field)
        {
            string value = null;

            switch (field)
            {
            case TrackField.End:
                m_Script = Encoding.UTF8.GetBytes(_infoText);
                objectReader.Position--;
                return(false);

            case TrackField.Frames:
                fieldValues[field] = objectReader.ReadInt32();
                if (fieldValues[field] == 0)
                {
                    if (objectReader.ReadByte() != 255)
                    {
                        objectReader.BaseStream.Position--;
                    }
                }
                else if (!fieldValues.ContainsKey(TrackField.UnknownByte41))
                {
                    if (objectReader.ReadByte() != 32)
                    {
                        throw new InvalidDataException();
                    }

                    value = MxrAnimation.Read(objectReader, fieldValues[TrackField.Frames]);
                }
                break;

            case TrackField.Start:
                if (objectReader.ReadByte() != 1)
                {
                    throw new InvalidDataException();
                }
                return(true);

            case TrackField.UnknownByte41:
                fieldValues[field] = objectReader.ReadByte();
                break;

            case TrackField.UnknownByte48:
            case TrackField.UnknownByte49:
                string unknown48 = string.Empty;
                if (fieldValues.ContainsKey(TrackField.UnknownByte41))
                {
                    fieldValues.TryGetValue(TrackField.Type, out var resourceType);
                    while (true)
                    {
                        var objectType = (int)objectReader.ReadByte();
                        if (objectType == 255)
                        {
                            break;
                        }

                        if (objectType == 128)
                        {
                            objectType = objectReader.ReadInt32();
                        }

                        var objectCount = objectReader.ReadByte();
                        unknown48 += $"Unknown{objectType}[{objectCount}] = " + string.Join(", ",
                                                                                            Enumerable.Range(0, resourceType * objectCount).Select(e => objectReader.ReadSingle())) + Environment.NewLine;
                    }

                    value = unknown48.Length.ToString();
                    fieldValues[field] = unknown48.Length;
                }
                else
                {
                    fieldValues[field] = objectReader.ReadByte();
                }

                break;

            case TrackField.Name:
                value = MxrObjectReader.ReadString(objectReader);
                break;

            case TrackField.UnknownArray33:
            case TrackField.UnknownArray34:
            case TrackField.UnknownArray35:
            case TrackField.UnknownArray37:
            case TrackField.UnknownArray38:
            case TrackField.UnknownArray42:
                if (objectReader.ReadByte() != 0)
                {
                    throw new InvalidDataException();
                }
                var ints = Enumerable.Range(0, objectReader.ReadInt32())
                           .Select(i => (field == TrackField.UnknownArray34 || field == TrackField.UnknownArray35) ?
                                   objectReader.ReadInt32() : objectReader.ReadInt64())
                           .ToList();
                value = ints.Any() ? $"{ints.Count} {{\n    {string.Join(", ", ints)}\n}}" : "{ }";
                break;

            case TrackField.Type:
                fieldValues[field] = objectReader.ReadInt32();
                if (fieldValues.ContainsKey(TrackField.UnknownByte41))
                {
                    if (objectReader.ReadByte() != 255)
                    {
                        objectReader.BaseStream.Position--;
                    }
                }
                else
                {
                    if (objectReader.ReadByte() != (byte)TrackField.Index)
                    {
                        throw new InvalidDataException();
                    }

                    m_Name = ((MxrClassIDType)fieldValues[field]).ToString();
                    var objectIndex = objectReader.ReadInt32();

                    if (_objectsDic.TryGetValue(MxrSerializedFile.GetPathID(fieldValues[field], objectIndex), out var namedObject))
                    {
                        m_Name += $" {objectIndex} ({((NamedObject)namedObject).m_Name})";
                    }
                    else if (objectIndex != -1)
                    {
                        m_Name += $" {objectIndex}";
                    }

                    value = m_Name;
                }
                break;

            default:
                fieldValues[field] = objectReader.ReadInt32();
                break;
            }

            _infoText += $"{field} = {value ?? fieldValues[field].ToString()}\n";
            return(true);
        }