private static void ReplaceIfNecessary(string name, bool normalMap, bool mipmaps, bool readable, bool compressed)
        {
            if (GameDatabase.Instance.ExistsTexture(name))
            {
                GameDatabase.TextureInfo info = GameDatabase.Instance.GetTextureInfo(name);
                bool isReadable = false;
                try { info.texture.GetPixel(0, 0); isReadable = true; }
                catch { }
                bool hasMipmaps   = info.texture.mipmapCount > 0;
                bool isCompressed = (info.texture.format == TextureFormat.DXT1 || info.texture.format == TextureFormat.DXT5);
                bool isNormalMap  = info.isNormalMap;


                if (!isReadable || (isCompressed && !compressed) || (isNormalMap != normalMap))
                {
                    //Pretty ineficient to not check beforehand, but makes the logic much simpler by simply reloading the textures.
                    info.isNormalMap  = normalMap;
                    info.isReadable   = readable;
                    info.isCompressed = compressed;
                    TextureConverter.Reload(info, false, default(Vector2), null, mipmaps);
                    info.texture.name = name;
                }
                else if (isReadable != readable || isCompressed != compressed || hasMipmaps != mipmaps)
                {
                    if (compressed)
                    {
                        info.texture.Compress(true);
                    }
                    info.texture.Apply(mipmaps, !readable);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Returns an inspector for the object or null if there isn't one.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Inspector GetInspector(object obj)
        {
            switch (obj)
            {
            case Texture i:
                return(new ImageInspector(TextureConverter.ToBitmap(i, 0)));

            case string s:
                return(new StringInspector(s));

            case SongData d:
                return(new SongDataInspector(d));

            case RBMid m:
                return(new RBMidiInspector(m));

            case HxMesh m:
                return(new MeshInspector(m));

            case MiloFile mf:
                return(new PropertyInspector(mf));

            case LibForge.Fuser.FuserAsset a:
                return(new Inspectors.FuserInspector(a));

            case object o:
                return(new ObjectInspector(obj));
            }
            return(null);
        }
コード例 #3
0
        public override List <Vertices> Process(TextureContent input, ContentProcessorContext context)
        {
            BitmapContent bitmap = input.Faces[0][0];

            byte[] bytes = bitmap.GetPixelData();
            Debug.Assert(bytes.Length % 4 == 0);

            // Note(manu): If this were C/C++, we could simply reinterpret the byte-array as a uint-array...
            uint[] data = new uint[bytes.Length / 4];
            for (int dataIndex = 0; dataIndex < data.Length; dataIndex++)
            {
                int byteIndex = dataIndex * 4;
                data[dataIndex] = BitConverter.ToUInt32(bytes, byteIndex);
            }

            DateTime         vertStart        = DateTime.Now;
            TextureConverter textureConverter = new TextureConverter(data, bitmap.Width)
            {
                PolygonDetectionType    = PolygonDetectionType,
                HoleDetection           = HoleDetection,
                MultipartDetection      = MultipartDetection,
                PixelOffsetOptimization = PixelOffsetOptimization,
                Transform      = Matrix.CreateScale(UniformScale * Conversion.RenderScale), // TODO(manu): Use z=1 instead?
                AlphaTolerance = (byte)AlphaTolerance,
                HullTolerance  = HullTolerance,
            };
            List <Vertices> vertices     = textureConverter.DetectVertices();
            TimeSpan        vertDuration = DateTime.Now - vertStart;

            Diagnostic(context.Logger, $"Parsing vertices took {vertDuration.TotalSeconds.ToString("0.000")} seconds (VelcroPhysics).");

            return(vertices);
        }
コード例 #4
0
        public Bitmap GetImage(int index, PLT0Node plt)
        {
            try
            {
                if (SharesData && SourceNode != this)
                {
                    return(SourceNode.GetImage(index, plt));
                }

                if (WorkingUncompressed != DataSource.Empty)
                {
                    if (plt != null)
                    {
                        return(TextureConverter.DecodeIndexed(
                                   (VoidPtr)CommonHeader + _headerLen, _width, _height, plt.Palette, index + 1, _format));
                    }
                    else
                    {
                        return(TextureConverter.Decode(
                                   (VoidPtr)CommonHeader + _headerLen, _width, _height, index + 1, _format));
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch { return(null); }
        }
コード例 #5
0
        public override void OnRebuild(VoidPtr address, int length, bool force)
        {
            PLT0v1 *header = (PLT0v1 *)address;

            *header = new PLT0v1(Palette.Entries.Length, _format);

            TextureConverter.EncodePalette(address + 0x40, Palette, _format);
        }
コード例 #6
0
        /// <summary>
        /// Generates the bodies for each of the pieces of the sheet.
        /// </summary>
        /// <param name="levelWorld">The world to create bodies in</param>
        /// <param name="collisionCategory">The FULL category of what these bodies should collide with</param>
        public void GenerateBodies(World levelWorld, Category collisionCategory)   //TODO get scale
        {
            BodiesGenerated = true;

            int SpriteSheetSize = SpriteSheet.Width * SpriteSheet.Height;
            int IndividualSize  = ImageSize.X * ImageSize.Y;

            uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into
            SpriteSheet.GetData <uint>(TextureData);        //Gets which pixels of the texture are actually filled

            List <uint[]> IndividualData = new List <uint[]>();

            for (int Processed = 0; Processed < SpriteSheetSize && IndividualData.Count < Bodies.Length; Processed += IndividualSize)
            {
                //TODO CHECK IF THIS WORKS TESTING TO CUT OFF ARRAY ARGUMENT EXCEPTION
                uint[] TempArray = new uint[IndividualSize];

                try {
                    Array.Copy(TextureData, Processed, TempArray, 0, IndividualSize);
                } catch (ArgumentException) {
                    //At the end of textures the amount of data left might be to small
                    Array.Copy(TextureData, Processed, TempArray, 0, TextureData.Length - Processed);
                }

                IndividualData.Add(TempArray);
            }

            int BodyIndex = 0;

            for (int count = 0; count < IndividualData.Count; ++count)
            {
                uint[] I = IndividualData[count];

                Vertices        vertices   = TextureConverter.DetectVertices(I, ImageSize.X);
                List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Earclip);
                //error with bayazit and deluny
                //Siedle doesnt wortk
                //Earclip & flipcode results in glitches
                //Earclip works very well

                Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(Scale));

                foreach (Vertices vert in VertexList)
                {
                    vert.Scale(ref VertScale); //Scales the vertices to match the size we specified
                }
                Vector2 Centroid = -vertices.GetCentroid();
                vertices.Translate(ref Centroid);
                //basketOrigin = -centroid;

                //This actually creates the body
                Bodies[BodyIndex]          = BodyFactory.CreateCompoundPolygon(levelWorld, VertexList, 1, Vector2.Zero);
                Bodies[BodyIndex].BodyType = BodyType.Dynamic;
                Bodies[BodyIndex].Enabled  = false;
                //Bodies[BodyIndex].CollisionCategories = collisionCategory;
                ++BodyIndex;
            }
        }
コード例 #7
0
ファイル: UniverseSystem.cs プロジェクト: matrix4x4/Space
        // TODO in case we need this somewhere else it might be a good idea to move this to the EntityFactory
        private void CreateAsteroid(FarPosition position, IUniformRandom random, ContentManager content)
        {
            // Randomly scale and rotate it.
            var scale = (float)random.NextDouble(0.5f, 1f);
            var angle = (float)random.NextDouble() * MathHelper.TwoPi;

            // Determine shape for physics system.
            var textureName = "Textures/Asteroids/rock_" + random.NextInt32(1, 14);
            var texture     = content.Load <Texture2D>(textureName);
            var hull        = new List <Vector2>(TextureConverter.DetectVertices(texture, 8f, textureName: textureName)[0]);

            for (var k = 0; k < hull.Count; ++k)
            {
                hull[k] -= new Vector2(texture.Width / 2f, texture.Height / 2f);
                hull[k]  = XnaUnitConversion.ToSimulationUnits(hull[k]) * scale;
            }
            var polygons = EarClipDecomposer.ConvexPartition(hull);

            // Create physical representation.
            var entity = Manager.AddEntity();
            var body   = Manager.AddBody(entity, position, angle, Body.BodyType.Dynamic);

            foreach (var polygon in polygons)
            {
                Manager.AttachPolygon(body, polygon, density: 1000f, restitution: 0.2f);
            }
            // Slow down to allow reaching sleep state again.
            body.LinearDamping  = 0.05f * Space.Util.Settings.TicksPerSecond;
            body.AngularDamping = 0.025f * Space.Util.Settings.TicksPerSecond;

            // Bounds of the asteroid for rendering culling. We use the diagonal for a loose fit that
            // contains every possible rotated state of the texture.
            var width    = UnitConversion.ToSimulationUnits(texture.Width);
            var height   = UnitConversion.ToSimulationUnits(texture.Height);
            var diagonal = (float)Math.Sqrt(width * width + height * height);
            var bounds   = new FarRectangle(-diagonal / 2, -diagonal / 2, diagonal, diagonal);

            // Rendering stuff.
            Manager.AddComponent <Indexable>(entity).Initialize(bounds, CameraSystem.IndexId);
            Manager.AddComponent <Indexable>(entity).Initialize(bounds, InterpolationSystem.IndexId);
            Manager.AddComponent <SimpleTextureDrawable>(entity).Initialize(textureName, scale);

            // Auto removal.
            Manager.AddComponent <CellDeath>(entity).Initialize(true);
            Manager.AddComponent <Indexable>(entity).Initialize(CellSystem.CellDeathAutoRemoveIndexId);

            // Make it destructible.
            var health = Manager.AddComponent <Health>(entity);

            health.Value        = health.MaxValue = 200 * scale;
            health.Regeneration = 0f;

            // As they don't move on their own, start asteroids as sleeping to save performance.
            body.IsAwake = false;
        }
コード例 #8
0
        private void UpdateSize()
        {
            if (_source == null)
            {
                return;
            }

            int w = _source.Width, h = _source.Height;
            int palSize = grpPalette.Enabled ? (((int)numPaletteCount.Value * 2) + 0x40) : 0;

            lblDataSize.Text = String.Format("{0:n0}B", TextureConverter.Get((WiiPixelFormat)cboFormat.SelectedItem).GetMipOffset(ref w, ref h, (int)numLOD.Value + 1) + 0x40 + palSize);
        }
コード例 #9
0
        public void UpdateFromModel()
        {
            var material = Controller.Material;

            if (material.Diffuse.Albedo is Texture)
            {
                diffuseTexture.Image = TextureConverter.Convert(material.Diffuse.Albedo as Texture);
            }
            else
            {
                diffuseTexture.BackColor = material.Diffuse.Albedo[0, 0].ToSystemDrawing();
                diffuseTexture.Image     = null;
            }

            if (material.Emissive.Albedo is Texture)
            {
                emissiveTexture.Image = TextureConverter.Convert(material.Emissive.Albedo as Texture);
            }
            else
            {
                emissiveTexture.BackColor = material.Emissive.Albedo[0, 0].ToSystemDrawing();
                emissiveTexture.Image     = null;
            }

            if (material.Reflective.Albedo is Texture)
            {
                reflectiveTexture.Image = TextureConverter.Convert(material.Reflective.Albedo as Texture);
            }
            else
            {
                reflectiveTexture.BackColor = material.Reflective.Albedo[0, 0].ToSystemDrawing();
                reflectiveTexture.Image     = null;
            }

            if (material.Refractive.Albedo is Texture)
            {
                refractiveTexture.Image = TextureConverter.Convert(material.Refractive.Albedo as Texture);
            }
            else
            {
                refractiveTexture.BackColor = material.Refractive.Albedo[0, 0].ToSystemDrawing();
                refractiveTexture.Image     = null;
            }

            refractiveIndexUpDown.Value       = (decimal)material.Refractive.RefractiveIndex;
            reflectiveDisturbanceUpDown.Value = (decimal)material.Reflective.Disturbance;
            diffuseShareUpDown.Value          = (decimal)material.Parts.diffuse;
            reflectiveShareUpDown.Value       = (decimal)material.Parts.reflective;
            refractiveShareUpDown.Value       = (decimal)material.Parts.refractive;
            emissiveShareUpDown.Value         = (decimal)material.Parts.emissive;
            ampUpDown.Value = (decimal)material.Emissive.Amplification;
        }
コード例 #10
0
        public Bitmap GetImage(int index)
        {
            PLT0Node plt = GetPaletteNode();

            if (plt != null)
            {
                return(TextureConverter.DecodeIndexed(Header, plt.Palette, index + 1));
            }
            else
            {
                return(TextureConverter.Decode(Header, index + 1));
            }
        }
コード例 #11
0
        private void refractiveFile_Click(object sender, EventArgs e)
        {
            var texturePath = ChooseTexture();

            if (string.IsNullOrEmpty(texturePath))
            {
                return;
            }

            var texture = new Texture(texturePath);

            Controller.Material.Refractive.Albedo = texture;
            refractiveTexture.Image = TextureConverter.Convert(texture);
        }
コード例 #12
0
        /// <summary>
        /// Creates a list of vertices from a texture.
        /// </summary>
        /// <param name="texture">The texture to make a body from</param>
        /// <param name="scale">The scale of the texture</param>
        /// <param name="imageSize">The size of each individual image in the hitbox</param>
        /// <param name="density">The density of the object (Will almost always be one</param>
        /// <param name="algorithm">The decomposition algorithm to use</param>
        /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks>
        /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you
        /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as
        /// clean as the texture you give it, so avoid partically transparent areas and little edges.
        private List <Vertices>[] CreateVerticesFromTexture(Texture2D texture, float scale, Point imageSize,
                                                            float density = 1, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Earclip)
        {
            int SpriteSheetSize = texture.Width * texture.Height;
            int IndividualSize  = imageSize.X * imageSize.Y;

            uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into
            texture.GetData(TextureData);                   //Gets which pixels of the texture are actually filled

            List <uint[]> IndividualData = new List <uint[]>();

            for (int Processed = 0; Processed < SpriteSheetSize; Processed += IndividualSize)
            {
                uint[] TempArray = new uint[IndividualSize];

                try {
                    Array.Copy(TextureData, Processed, TempArray, 0, IndividualSize);
                } catch (ArgumentException) {
                    //At the end of textures the amount of data left might be to small
                    Array.Copy(TextureData, Processed, TempArray, 0, TextureData.Length - Processed);
                }


                IndividualData.Add(TempArray);
            }

            List <Vertices>[] TextureVertices = new List <Vertices> [IndividualData.Count];

            for (int count = 0; count < IndividualData.Count; ++count)
            {
                uint[] I = IndividualData[count];

                Vertices        vertices   = TextureConverter.DetectVertices(I, texture.Width);
                List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, algorithm);

                Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

                foreach (Vertices vert in VertexList)
                {
                    vert.Scale(ref VertScale); //Scales the vertices to match the size we specified
                }
                Vector2 Centroid = -vertices.GetCentroid();
                vertices.Translate(ref Centroid);
                //basketOrigin = -centroid;

                TextureVertices[count] = VertexList;
            }

            return(TextureVertices);
        }
コード例 #13
0
ファイル: GltfUpdater.cs プロジェクト: Vytek/UnityGltfTool
        public void Update(bool convertImagesToDds)
        {
            var colliderUpdater = new ColliderUpdater(gltf, colliders);

            colliderUpdater.UpdateColliders();

            if (convertImagesToDds)
            {
                var texConverter = new TextureConverter(gltfPath, gltf);
                texConverter.ConvertImagesToDds();
            }

            gltf.SaveModel(gltfPath);
        }
コード例 #14
0
        public void Replace(Bitmap bmp)
        {
            FileMap tMap;

            if (HasPlt)
            {
                tMap = TextureConverter.Get(_format).EncodeREFTTextureIndexed(bmp, LevelOfDetail, Palette.Entries.Length, PaletteFormat, QuantizationAlgorithm.MedianCut);
            }
            else
            {
                tMap = TextureConverter.Get(_format).EncodeREFTTexture(bmp, LevelOfDetail, WiiPaletteFormat.IA8);
            }
            ReplaceRaw(tMap);
        }
コード例 #15
0
ファイル: TEX0Node.cs プロジェクト: KingAtreyu/super-sawndz
 public Bitmap GetImage(int index, PLT0Node plt)
 {
     try
     {
         if (plt != null)
         {
             return(TextureConverter.DecodeIndexed(Header, plt.Palette, index + 1));
         }
         else
         {
             return(TextureConverter.Decode(Header, index + 1));
         }
     }
     catch { return(null); }
 }
コード例 #16
0
        public static void Replace(this TEX0Node tex0, Bitmap bmp, int paletteSize)
        {
            FileMap tMap, pMap;

            if (tex0.HasPalette)
            {
                PLT0Node pn = tex0.GetPaletteNode();
                tMap = TextureConverter.Get(tex0.Format).EncodeTextureIndexed(bmp, tex0.LevelOfDetail, paletteSize, pn.Format, QuantizationAlgorithm.MedianCut, out pMap);
                pn.ReplaceRaw(pMap);
            }
            else
            {
                tMap = TextureConverter.Get(tex0.Format).EncodeTEX0Texture(bmp, tex0.LevelOfDetail);
            }
            tex0.ReplaceRaw(tMap);
        }
コード例 #17
0
        public void Replace(Bitmap bmp)
        {
            FileMap tMap, pMap;

            if (HasPalette)
            {
                PLT0Node pn = this.GetPaletteNode();
                tMap = TextureConverter.Get(Format).EncodeTextureIndexed(bmp, LevelOfDetail, pn.Colors, pn.Format, QuantizationAlgorithm.MedianCut, out pMap);
                pn.ReplaceRaw(pMap);
            }
            else
            {
                tMap = TextureConverter.Get(Format).EncodeTexture(bmp, LevelOfDetail);
            }
            ReplaceRaw(tMap);
        }
コード例 #18
0
        /// <summary>
        /// Replace the MenSelmapMark texture in toReplace with the image in newBitmap, flipping the channels if the image has solid black in all four corners.
        /// </summary>
        /// <param name="newBitmap">The new texture to use</param>
        /// <param name="toReplace">The TEX0 to insert the texture in</param>
        /// <param name="createNew">If true, the format of the existing texture will not be used as a fallback, even if useExistingAsFallback is true</param>
        private void ReplaceSelmapMark(Bitmap newBitmap, TEX0Node toReplace, bool createNew)
        {
            WiiPixelFormat format =
                selmapMarkFormat != null
                                        ? selmapMarkFormat.Value
                                : useExistingAsFallback && !createNew
                                        ? toReplace.Format
                                : BitmapUtilities.HasAlpha(newBitmap)
                                        ? WiiPixelFormat.IA4
                                        : WiiPixelFormat.I4;

            Console.WriteLine(format);
            Bitmap toEncode = BitmapUtilities.HasSolidCorners(newBitmap) ? BitmapUtilities.AlphaSwap(newBitmap) : newBitmap;

            BrawlLib.IO.FileMap tMap = TextureConverter.Get(format).EncodeTEX0Texture(toEncode, 1);
            toReplace.ReplaceRaw(tMap);
        }
コード例 #19
0
        public static Vector2[] GetVerticesTexture(Texture2D texture)
        {
            // Get vertices of Texture
            uint[] texData = new uint[texture.Width * texture.Height];
            texture.GetData <uint>(texData);
            Vertices verticesList = TextureConverter.detectVertices(texData, texture.Width);

            Vector2[] verticesArray = verticesList.ToArray();

            // PolygonCollider has offset in center, so vertices does too
            for (int i = 0; i < verticesArray.Length; i++)
            {
                verticesArray[i].X -= texture.Width / 2;
                verticesArray[i].Y -= texture.Height / 2;
            }

            return(verticesArray);
        }
コード例 #20
0
 public Bitmap GetImage(int index)
 {
     try
     {
         if (HasPlt == true)
         {
             return(TextureConverter.DecodeIndexed((byte *)Header + 0x20, Width, Height, Palette, index + 1, _format));
         }
         else
         {
             return(TextureConverter.Decode((byte *)Header + 0x20, Width, Height, index + 1, _format));
         }
     }
     catch
     {
         return(null);
     }
 }
コード例 #21
0
        public TEX0v1(int width, int height, WiiPixelFormat format, int mipLevels)
        {
            _header._tag        = Tag;
            _header._size       = TextureConverter.Get(format).GetMipOffset(width, height, mipLevels + 1) + Size;
            _header._version    = 1;
            _header._bresOffset = 0;

            _headerLen      = Size;
            _stringOffset   = 0;
            _hasPalette     = ((format == WiiPixelFormat.CI4) || (format == WiiPixelFormat.CI8)) ? 1 : 0;
            _width          = (short)width;
            _height         = (short)height;
            _pixelFormat    = (int)format;
            _levelOfDetail  = mipLevels;
            _minLod         = 0;
            _maxLod         = mipLevels - 1.0f;
            _origPathOffset = 0;
        }
コード例 #22
0
        public void WriteJson_Should_InvokeMethodsProperly()
        {
            var converter    = new TextureConverter();
            var texture      = new Texture();
            var mockedWriter = new Mock <JsonWriter>();

            converter.WriteJson(mockedWriter.Object, texture, JsonSerializer.CreateDefault());

            mockedWriter.Verify(jsonWriter => jsonWriter.WriteStartObject(), Times.Once);
            mockedWriter.Verify(jsonWriter => jsonWriter.WriteEndObject(), Times.Once);

            mockedWriter.Verify(jsonWriter => jsonWriter.WritePropertyName(It.IsAny <string>()), Times.Exactly(4));
            mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <string>()), Times.Exactly(2));
            mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <int>()), Times.Exactly(2));
            mockedWriter.Verify(jsonWriter => jsonWriter.WriteValue(It.IsAny <WrappingType>()), Times.Exactly(2));

            mockedWriter.Verify(jsonWriter => jsonWriter.WriteStartArray(), Times.Exactly(2));
            mockedWriter.Verify(jsonWriter => jsonWriter.WriteEnd(), Times.Exactly(2));
        }
コード例 #23
0
ファイル: Inspector.cs プロジェクト: PikminGuts92/LibForge
        /// <summary>
        /// Returns an inspector for the object or null if there isn't one.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Inspector GetInspector(object obj)
        {
            switch (obj)
            {
            case Texture i:
                return(new ImageInspector(TextureConverter.ToBitmap(i, 0)));

            case string s:
                return(new StringInspector(s));

            case SongData d:
                return(new SongDataInspector(d));

            case RBMid m:
                return(new RBMidiInspector(m));

            case object o:
                return(new ObjectInspector(obj));
            }
            return(null);
        }
コード例 #24
0
        public Body CreatePolygonFromTexture(Texture2D tex, World world, float density, Vector2 position, float scale, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Bayazit)
        {
            uint[] texData = new uint[tex.Width * tex.Height];
            tex.GetData <uint>(texData);

            Vertices        vertices   = TextureConverter.DetectVertices(texData, tex.Width);
            List <Vertices> vertexList = Triangulate.ConvexPartition(vertices, algorithm);

            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

            foreach (Vertices vert in vertexList)
            {
                vert.Scale(ref vertScale);
            }

            Vector2 centroid = vertices.GetCentroid();

            vertices.Translate(ref centroid);
            //basketOrigin = -centroid;
            return(BodyFactory.CreateCompoundPolygon(world, vertexList, density, position, 100));
        }
コード例 #25
0
        public void WriteJson_Should_OutputCorrectValues()
        {
            var converter = new TextureConverter();
            var texture   = new Texture()
            {
                UUID    = "testUuid",
                ImageId = "testImageId",
                WrapS   = WrappingType.MirroredRepeat,
                WrapT   = WrappingType.ClampToEdge,
                Repeat  = new Tuple <int, int>(1, 1)
            };
            var stringBuilder = new StringBuilder();
            var stringWriter  = new StringWriter(stringBuilder);
            var jsonWriter    = new JsonTextWriter(stringWriter);

            converter.WriteJson(jsonWriter, texture, JsonSerializer.CreateDefault());

            string expected = "{\"uuid\":\"testUuid\",\"image\":\"testImageId\",\"wrap\":[1002,1001],\"repeat\":[1,1]}";

            Assert.Equal(expected, stringBuilder.ToString());
        }
コード例 #26
0
ファイル: TEX0Node.cs プロジェクト: soopercool101/brawltools2
 public Bitmap GetImage(int index, PLT0Node plt)
 {
     try
     {
         if (WorkingUncompressed != DataSource.Empty)
         {
             if (plt != null)
             {
                 return(TextureConverter.DecodeIndexed(Header1, plt.Palette, index + 1));
             }
             else
             {
                 return(TextureConverter.Decode(Header1, index + 1));
             }
         }
         else
         {
             return(null);
         }
     }
     catch { return(null); }
 }
コード例 #27
0
    private void DrawParameters(int method)
    {
        ParameterInfo[] mParameters = currentPreset.conversionMethods [currentPreset.chosenMethods [method]].GetParameters();
        int             paramLength = mParameters.Length;

        foreach (var item in mParameters)
        {
            if (item.ParameterType == typeof(UnityEngine.Vector2))
            {
                paramLength++;
            }
        }
        if (paramLength != currentPreset.chosenMethodsParameters [method].Length)
        {
            TextureConverter.LoadMethodParameters(currentPreset, method);
        }
        int iOffset = 0;

        for (int i = 0; i < mParameters.Length; i++)
        {
            if (mParameters [i].ParameterType == typeof(UnityEngine.Vector2))
            {
//				Undo.RecordObject (currentPreset, "TextureConvereter Preset Change");
                currentPreset.chosenMethodsParameters [method] [i + iOffset] = TextureConverterDrawUtility.DrawParameterInput(typeof(PositionOrValue), currentPreset.chosenMethodsParameters [method] [i + iOffset]);
                if ((PositionOrValue)currentPreset.chosenMethodsParameters [method] [i + iOffset] == PositionOrValue.UseValue)
                {
//					Undo.RecordObject (currentPreset, "TextureConvereter Preset Change");
                    currentPreset.chosenMethodsParameters [method] [i + iOffset + 1] = TextureConverterDrawUtility.DrawParameterInput(mParameters [i].ParameterType, currentPreset.chosenMethodsParameters [method] [i + iOffset + 1]);
                }
                iOffset++;
            }
            else
            {
//				Undo.RecordObject (currentPreset, "TextureConvereter Preset Change");
                currentPreset.chosenMethodsParameters [method] [i + iOffset] = TextureConverterDrawUtility.DrawParameterInput(mParameters [i].ParameterType, currentPreset.chosenMethodsParameters [method] [i + iOffset]);
            }
        }
    }
コード例 #28
0
        /// <summary>
        /// Creates a polygon from a texture. This is the important function here.
        /// </summary>
        /// <param name="texture">The texture to make a body from</param>
        /// <param name="density">The density of the object (Will almost always be one</param>
        /// <param name="position">The position (in meters) of the object in the world</param>
        /// <param name="scale">The scale of the object (how much to change its size)</param>
        /// <param name="algorithm">The decomposition algorithm to use</param>
        /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks>
        /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you
        /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as
        /// clean as the texture you give it, so avoid partically transparent areas and little edges.
        private Body CreatePolygonFromTexture(Texture2D texture, float density, Vector2 position, float scale,
                                              TriangulationAlgorithm algorithm = TriangulationAlgorithm.Bayazit)
        {
            uint[] TextureData = new uint[texture.Width * texture.Height]; //Array to copy texture info into
            texture.GetData <uint>(TextureData);                           //Gets which pixels of the texture are actually filled

            Vertices        vertices   = TextureConverter.DetectVertices(TextureData, texture.Width);
            List <Vertices> vertexList = Triangulate.ConvexPartition(vertices, algorithm);

            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

            foreach (Vertices vert in vertexList)
            {
                vert.Scale(ref vertScale); //Scales the vertices to match the size we specified
            }
            Vector2 centroid = -vertices.GetCentroid();

            vertices.Translate(ref centroid);
            //basketOrigin = -centroid;

            //This actually creates the body
            return(BodyFactory.CreateCompoundPolygon(LevelWorld, vertexList, density, position));
        }
コード例 #29
0
ファイル: TEX0.cs プロジェクト: soopercool101/brawltools1
        public TEX0(int width, int height, WiiPixelFormat format, int mipLevels)
        {
            _header._tag        = Tag;
            _header._size       = TextureConverter.Get(format).GetMipOffset(width, height, mipLevels + 1) + Size;
            _header._version    = 1;
            _header._bresOffset = 0;

            _headerLen     = Size;
            _stringOffset  = 0;
            _hasPalette    = ((format == WiiPixelFormat.CI4) || (format == WiiPixelFormat.CI8)) ? 1 : 0;
            _width         = (short)width;
            _height        = (short)height;
            _pixelFormat   = (int)format;
            _levelOfDetail = mipLevels;
            _unknown       = 0;
            _lodBias       = mipLevels - 1.0f;

            fixed(uint *p = _padding)
            for (int i = 0; i < 4; i++)
            {
                p[i] = 0;
            }
        }
コード例 #30
0
        /// <summary>
        /// Creates a list of vertices from a texture.
        /// </summary>
        /// <param name="texture">The texture to make a body from</param>
        /// <param name="scale">The scale of the texture</param>
        /// <param name="algorithm">The decomposition algorithm to use</param>
        /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks>
        /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you
        /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as
        /// clean as the texture you give it, so avoid partically transparent areas and little edges.
        private List <Vertices> CreateVerticesFromTexture(Texture2D texture, float scale,
                                                          TriangulationAlgorithm algorithm = TriangulationAlgorithm.Earclip)
        {
            int SpriteSheetSize = texture.Width * texture.Height;

            uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into
            texture.GetData(TextureData);                   //Gets which pixels of the texture are actually filled

            Vertices        vertices   = TextureConverter.DetectVertices(TextureData, texture.Width);
            List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, algorithm);

            Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

            foreach (Vertices vert in VertexList)
            {
                vert.Scale(ref VertScale); //Scales the vertices to match the size we specified
            }
            Vector2 Centroid = -vertices.GetCentroid();

            vertices.Translate(ref Centroid);
            //basketOrigin = -centroid;

            return(VertexList);
        }
コード例 #31
0
        /// <summary>
        /// Detects the vertices of the supplied texture data.
        /// </summary>
        /// <param name="data">The texture data.</param>
        /// <param name="width">The texture width.</param>
        /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param>
        /// <param name="hullTolerance">The hull tolerance.</param>
        /// <param name="alphaTolerance">The alpha tolerance.</param>
        /// <param name="multiPartDetection">if set to <c>true</c> it will perform multi part detection.</param>
        /// <returns></returns>
        public static List<Vertices> DetectVertices(uint[] data, int width, float hullTolerance, byte alphaTolerance, bool multiPartDetection, bool holeDetection)
        {
            TextureConverter tc =
                new TextureConverter(data, width)
                {
                    HullTolerance = hullTolerance,
                    AlphaTolerance = alphaTolerance,
                    MultipartDetection = multiPartDetection,
                    HoleDetection = holeDetection
                };

            List<Vertices> detectedVerticesList = tc.DetectVertices();
            List<Vertices> result = new List<Vertices>();

            for (int i = 0; i < detectedVerticesList.Count; i++)
            {
                result.Add(detectedVerticesList[i]);
            }

            return result;
        }
コード例 #32
0
        /// <summary>
        /// Detects the vertices of the supplied texture data.
        /// </summary>
        /// <param name="data">The texture data.</param>
        /// <param name="width">The texture width.</param>
        /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param>
        /// <returns></returns>
        public static Vertices DetectVertices(uint[] data, int width, bool holeDetection)
        {
            TextureConverter tc =
                new TextureConverter(data, width)
                {
                    HoleDetection = holeDetection
                };

            List<Vertices> detectedVerticesList = tc.DetectVertices();

            return detectedVerticesList[0];
        }