public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector4[] arr, BufferViewId bufferViewId = null, bool normalized = false, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC4;

            float minX = arr[0].x;
            float minY = arr[0].y;
            float minZ = arr[0].z;
            float minW = arr[0].w;
            float maxX = arr[0].x;
            float maxY = arr[0].y;
            float maxZ = arr[0].z;
            float maxW = arr[0].w;

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur.x < minX)
                {
                    minX = cur.x;
                }
                if (cur.y < minY)
                {
                    minY = cur.y;
                }
                if (cur.z < minZ)
                {
                    minZ = cur.z;
                }
                if (cur.w < minW)
                {
                    minW = cur.w;
                }
                if (cur.x > maxX)
                {
                    maxX = cur.x;
                }
                if (cur.y > maxY)
                {
                    maxY = cur.y;
                }
                if (cur.z > maxZ)
                {
                    maxZ = cur.z;
                }
                if (cur.w > maxW)
                {
                    maxW = cur.w;
                }
            }
            accessor.Normalized = normalized;
            accessor.Min        = new List <double> {
                minX, minY, minZ, minW
            };
            accessor.Max = new List <double> {
                maxX, maxY, maxZ, maxW
            };

            var byteOffset = writer.BaseStream.Position;

            foreach (var vec in arr)
            {
                writer.Write(vec.x);
                writer.Write(vec.y);
                writer.Write(vec.z);
                writer.Write(vec.w);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }


            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
		private static void TestGLBBuffers(GLTFRoot gltfRoot)
		{
			List<Buffer> buffers = gltfRoot.Buffers;
			Assert.AreEqual(1, buffers.Count);
			Assert.AreEqual(11247948, buffers[0].ByteLength);
		}
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector3[] arr, BufferViewId bufferViewId = null, bool normalized = false, Transform rootNode = null, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC3;

            /*float minX = arr[0].x;
             * float minY = arr[0].y;
             * float minZ = arr[0].z;
             * float maxX = arr[0].x;
             * float maxY = arr[0].y;
             * float maxZ = arr[0].z;
             *
             * for (var i = 1; i < count; i++)
             * {
             *  var cur = arr[i];
             *
             *  if (cur.x < minX)
             *  {
             *      minX = cur.x;
             *  }
             *  if (cur.y < minY)
             *  {
             *      minY = cur.y;
             *  }
             *  if (cur.z < minZ)
             *  {
             *      minZ = cur.z;
             *  }
             *  if (cur.x > maxX)
             *  {
             *      maxX = cur.x;
             *  }
             *  if (cur.y > maxY)
             *  {
             *      maxY = cur.y;
             *  }
             *  if (cur.z > maxZ)
             *  {
             *      maxZ = cur.z;
             *  }
             * }*/

            accessor.Normalized = normalized;
            //accessor.Min = new List<double> { minX, minY, minZ };
            //accessor.Max = new List<double> { maxX, maxY, maxZ };

            var       byteOffset = writer.BaseStream.Position;
            Matrix4x4 mA         = rootNode != null ? rootNode.localToWorldMatrix : new Matrix4x4();
            Matrix4x4 mB         = rootNode != null ? rootNode.parent.worldToLocalMatrix : new Matrix4x4();

            foreach (var vec in arr)
            {
                writer.Write(vec.x);
                writer.Write(vec.y);
                writer.Write(vec.z);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }


            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
 public PunctualLightId(PunctualLightId id, GLTFRoot newRoot) : base(id, newRoot)
 {
 }
 public IExtension Clone(GLTFRoot root)
 {
     return(new KHR_LightsPunctualNodeExtension(LightId.Id, root));
 }
Exemple #6
0
        public void TestCopyMinGLTF()
        {
            GLTFRoot root = new GLTFRoot(_testRoot);

            Assert.IsNotNull(root);
        }
Exemple #7
0
 private static void TestAssetData(GLTFRoot gltfRoot)
 {
     Assert.AreEqual("2.0", gltfRoot.Asset.Version);
     Assert.AreEqual("glTF Tools for Unity", gltfRoot.Asset.Generator);
 }
Exemple #8
0
        public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
        {
            var extension = new Sein_physicBodyExtension();
            var tmpGo     = new GameObject();

            List <Collider> colliders = new List <Collider>();
            var             rigidBody = tmpGo.AddComponent <SeinRigidBody>();

            if (extensionToken.Value["mass"] != null)
            {
                rigidBody.mass         = (float)extensionToken.Value["mass"];
                rigidBody.friction     = (float)extensionToken.Value["friction"];
                rigidBody.restitution  = (float)extensionToken.Value["restitution"];
                rigidBody.unControl    = (bool)extensionToken.Value["unControl"];
                rigidBody.physicStatic = (bool)extensionToken.Value["physicStatic"];
                rigidBody.sleeping     = (bool)extensionToken.Value["sleeping"];
            }

            foreach (JContainer collider in extensionToken.Value["colliders"])
            {
                var type = (string)collider["type"];

                switch (type)
                {
                case ("SPHERE"):
                    var sc = tmpGo.AddComponent <SphereCollider>();
                    sc.radius = (float)collider["radius"];
                    sc.center = new  UnityEngine.Vector3(
                        (float)collider["offset"][0],
                        (float)collider["offset"][1],
                        (float)collider["offset"][2]
                        );

                    if (collider["isTrigger"] != null)
                    {
                        sc.isTrigger = (bool)collider["isTrigger"];
                    }

                    colliders.Add(sc);
                    break;

                case ("BOX"):
                    var bc = tmpGo.AddComponent <BoxCollider>();
                    bc.size = new UnityEngine.Vector3(
                        (float)collider["size"][0],
                        (float)collider["size"][1],
                        (float)collider["size"][2]
                        );

                    bc.center = new UnityEngine.Vector3(
                        (float)collider["offset"][0],
                        (float)collider["offset"][1],
                        (float)collider["offset"][2]
                        );

                    if (collider["isTrigger"] != null)
                    {
                        bc.isTrigger = (bool)collider["isTrigger"];
                    }

                    colliders.Add(bc);
                    break;

                default:
                    Debug.LogWarning("In current time, Sein only supports shpere and box collider !");
                    break;
                }
            }

            extension.rigidBody = rigidBody;
            extension.colliders = colliders;
            extension.go        = tmpGo;

            return(extension);
        }
Exemple #9
0
 public IExtension Clone(GLTFRoot root)
 {
     return(new Functions
     {
     });
 }
        // todo undo
#if !WINDOWS_UWP
        IEnumerator Start()
        {
            var     fullPath0 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset0Path;
            ILoader loader0   = new FileLoader(URIHelper.GetDirectoryName(fullPath0));

            var     fullPath1 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset1Path;
            ILoader loader1   = new FileLoader(URIHelper.GetDirectoryName(fullPath1));

            yield return(loader0.LoadStream(Path.GetFileName(asset0Path)));

            var      asset0Stream = loader0.LoadedStream;
            GLTFRoot asset0Root   = null;

            GLTFParser.ParseJson(asset0Stream, ref asset0Root);

            yield return(loader1.LoadStream(Path.GetFileName(asset1Path)));

            var      asset1Stream = loader1.LoadedStream;
            GLTFRoot asset1Root   = null;

            GLTFParser.ParseJson(asset0Stream, ref asset1Root);

            string newPath = "../../" + URIHelper.GetDirectoryName(asset0Path);

            int previousBufferCount  = asset1Root.Buffers.Count;
            int previousImageCount   = asset1Root.Images.Count;
            int previousSceneCounter = asset1Root.Scenes.Count;

            GLTFHelpers.MergeGLTF(asset1Root, asset0Root);

            for (int i = previousBufferCount; i < asset1Root.Buffers.Count; ++i)
            {
                GLTF.Schema.GLTFBuffer buffer = asset1Root.Buffers[i];
                if (!URIHelper.IsBase64Uri(buffer.Uri))
                {
                    buffer.Uri = newPath + buffer.Uri;
                }
            }

            for (int i = previousImageCount; i < asset1Root.Images.Count; ++i)
            {
                GLTFImage image = asset1Root.Images[i];
                if (!URIHelper.IsBase64Uri(image.Uri))
                {
                    image.Uri = newPath + image.Uri;
                }
            }

            foreach (NodeId node in asset1Root.Scenes[asset0Root.Scene.Id + previousSceneCounter].Nodes)
            {
                node.Value.Translation.X += 5f;
                asset1Root.Scene.Value.Nodes.Add(node);
            }
            GLTFSceneImporter importer = new GLTFSceneImporter(
                asset1Root,
                loader1
                );

            importer.MaximumLod      = MaximumLod;
            importer.isMultithreaded = Multithreaded;
            yield return(importer.LoadScene(-1));
        }
 public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
 {
     return(new AnimationExtension());
 }
 public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
 {
     return(new KHR_materials_unlitExtension());
 }
 public IExtension Clone(GLTFRoot root)
 {
     return(new CoordinateSystemExtension(this.coordinateDir, this.coordinateUnit));
 }
 public IExtension Clone(GLTFRoot root)
 {
     return(new KHR_materials_unlit());
 }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, UnityEngine.Color[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.ComponentType = GLTFComponentType.Float;
            accessor.Count         = count;
            accessor.Type          = GLTFAccessorAttributeType.VEC4;

            float minR = arr[0].r;
            float minG = arr[0].g;
            float minB = arr[0].b;
            float minA = arr[0].a;
            float maxR = arr[0].r;
            float maxG = arr[0].g;
            float maxB = arr[0].b;
            float maxA = arr[0].a;

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur.r < minR)
                {
                    minR = cur.r;
                }
                if (cur.g < minG)
                {
                    minG = cur.g;
                }
                if (cur.b < minB)
                {
                    minB = cur.b;
                }
                if (cur.a < minA)
                {
                    minA = cur.a;
                }
                if (cur.r > maxR)
                {
                    maxR = cur.r;
                }
                if (cur.g > maxG)
                {
                    maxG = cur.g;
                }
                if (cur.b > maxB)
                {
                    maxB = cur.b;
                }
                if (cur.a > maxA)
                {
                    maxA = cur.a;
                }
            }

            accessor.Normalized = true;
            accessor.Min        = new List <double> {
                minR, minG, minB, minA
            };
            accessor.Max = new List <double> {
                maxR, maxG, maxB, maxA
            };

            var byteOffset = writer.BaseStream.Position;

            foreach (var color in arr)
            {
                writer.Write(color.r);
                writer.Write(color.g);
                writer.Write(color.b);
                writer.Write(color.a);
            }

            var byteLength = writer.BaseStream.Position - byteOffset;

            if (bufferViewId != null)
            {
                accessor.BufferView = bufferViewId;
                accessor.ByteOffset = (int)byteOffset;
            }
            else
            {
                accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);
            }

            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
Exemple #16
0
        public static GLTFRoot ExportModel(string path)
        {
            using var stream = File.OpenRead(path);
            var pokemonModel   = PokemonModel.GetRootAsPokemonModel(stream.ToByteBuffer());
            var bufferRoot     = Path.GetDirectoryName(path);
            var bufferRootFile = Path.Combine(bufferRoot, $"{Path.GetFileNameWithoutExtension(path)}.mdlbin");

            using var buffer = File.OpenWrite(bufferRootFile);
            buffer.SetLength(0);

            var gltfRoot = new GLTFRoot
            {
                Asset = new GLTFAsset
                {
                    Generator = "GFLX",
                    Copyright = "2019 GameFreak - Pokemon Company",
                    Version   = "2.0"
                }
            };
            var gltfBuffer = gltfRoot.Buffers.Count;
            var materials  = DeconstructMaterials(pokemonModel, gltfRoot);

            var scene = new GLTFScene();

            for (var i = 0; i < pokemonModel.VisualGroupLength; ++i)
            {
                var group      = pokemonModel.VisualGroup(i).GetValueOrDefault();
                var mesh       = pokemonModel.Meshes((int)group.MeshId).GetValueOrDefault();
                var bone       = pokemonModel.Bones((int)group.BoneId).GetValueOrDefault();
                var attributes = DeconstructVbo(mesh, gltfRoot, buffer, gltfBuffer);
                var node       = new GLTFMesh
                {
                    Name = bone.Name
                };
                for (var j = 0; j < mesh.IndiceBufferLength; ++j)
                {
                    var primitive = mesh.IndiceBuffer(j).GetValueOrDefault();
                    node.Primitives.Add(new GLTFMeshPrimitive
                    {
                        Attributes = attributes,
                        Indices    = gltfRoot.Accessors.Count,
                        Mode       = GLTFDrawMode.Triangles,
                        Material   = materials[primitive.MaterialId]
                    });
                    gltfRoot.Accessors.Add(new GLTFAccessor
                    {
                        BufferView    = gltfRoot.BufferViews.Count,
                        ByteOffset    = 0,
                        ComponentType = GLTFComponentType.UnsignedShort,
                        Count         = (uint)primitive.IndicesLength,
                        Type          = GLTFAccessorAttributeType.SCALAR
                    });
                    var targetBuffer = MemoryMarshal.Cast <ushort, byte>(primitive.GetIndicesBytes());
                    gltfRoot.BufferViews.Add(new GLTFBufferView
                    {
                        Buffer     = gltfBuffer,
                        ByteOffset = (uint)buffer.Position,
                        ByteLength = (uint)targetBuffer.Length
                    });
                    buffer.Write(targetBuffer);
                }

                scene.Nodes.Add(gltfRoot.Nodes.Count);
                gltfRoot.Nodes.Add(new GLTFNode
                {
                    Mesh = gltfRoot.Meshes.Count,
                    Name = node.Name
                });
                gltfRoot.Meshes.Add(node);
            }

            gltfRoot.Scenes.Add(scene);
            gltfRoot.Buffers.Add(new GLTFBuffer
            {
                Uri        = Path.GetFileName(bufferRootFile),
                ByteLength = (uint)buffer.Length
            });

            return(gltfRoot);
        }
Exemple #17
0
 public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
 {
     return(null);
 }
Exemple #18
0
        private static int[] DeconstructMaterials(PokemonModel pokemonModel, GLTFRoot gltfRoot)
        {
            var materials = new int[pokemonModel.MaterialsLength];

            for (var i = 0; i < pokemonModel.MaterialsLength; ++i)
            {
                var material     = pokemonModel.Materials(i).GetValueOrDefault();
                var gltfMaterial = new GLTFMaterial
                {
                    PbrMetallicRoughness = new GLTFPBRMetallicRoughness(),
                    Name      = material.Name,
                    AlphaMode = GLTFAlphaMode.BLEND
                };

                for (var j = 0; j < material.TexturesLength; ++j)
                {
                    var texture     = material.Textures(j).GetValueOrDefault();
                    var textureName = $"{pokemonModel.Textures(texture.Id)}.png";
                    var mapping     = texture.Mapping.GetValueOrDefault();
                    var textureInfo = new GLTFTextureInfo
                    {
                        Index = FindOrCreateTexture(gltfRoot, textureName, mapping)
                    };

                    switch (texture.Channel)
                    {
                    case "Col0Tex":
                        gltfMaterial.PbrMetallicRoughness.BaseColorTexture = textureInfo;
                        break;

                    case "EmissionMaskTex":
                        gltfMaterial.EmissiveTexture = textureInfo;
                        gltfMaterial.EmissiveFactor  = new Vector3(1, 1, 1);
                        ;
                        break;

                    case "AmbientTex":
                        gltfMaterial.OcclusionTexture = textureInfo;
                        break;

                    case "NormalMapTex":
                        gltfMaterial.NormalTexture = textureInfo;
                        break;
                    }
                }

                var colorUVScale      = new Vector2(1, 1);
                var colorUVTransation = new Vector2();
                var normalUVScale     = new Vector2();
                for (var j = 0; j < material.ValuesLength; ++j)
                {
                    var value = material.Values(j).GetValueOrDefault();
                    if (string.IsNullOrWhiteSpace(value.Name))
                    {
                        continue;
                    }
                    switch (value.Name)
                    {
                    case "ColorUVScaleU":
                        colorUVScale.X = value.Value;
                        break;

                    case "ColorUVScaleV":
                        colorUVScale.Y = value.Value;
                        break;

                    case "ColorUVTranslateU":
                        colorUVTransation.X += value.Value;
                        break;

                    case "ColorUVTranslateV":
                        colorUVTransation.Y += value.Value;
                        break;

                    case "ColorBaseU":
                        colorUVTransation.X += value.Value;
                        break;

                    case "ColorBaseY":
                        colorUVTransation.Y += value.Value;
                        break;

                    case "NormalMapUVScaleU":
                        normalUVScale.X += value.Value;
                        break;

                    case "NormalMapUVScaleV":
                        normalUVScale.Y += value.Value;
                        break;
                    }
                }

                var colorTransform = new KHRTextureTransform
                {
                    Offset = colorUVTransation,
                    Scale  = colorUVScale
                };
                var normalTransform = new KHRTextureTransform
                {
                    Offset = normalUVScale
                };
                //colorTransform.Insert(gltfMaterial.OcclusionTexture, gltfRoot);
                colorTransform.Insert(gltfMaterial.PbrMetallicRoughness.MetallicRoughnessTexture, gltfRoot);
                //colorTransform.Insert(gltfMaterial.EmissiveTexture, gltfRoot);
                normalTransform.Insert(gltfMaterial.NormalTexture, gltfRoot);

                materials[i] = gltfRoot.Materials.Count;
                gltfRoot.Materials.Add(gltfMaterial);
            }

            return(materials);
        }
 private void LoadFile(int sceneIndex = -1)
 {
     _glTFData = File.ReadAllBytes(_glTFPath);
     _root     = GLTFParser.ParseJson(_glTFData);
 }
        public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
        {
            var extension = new Sein_audioSourceExtension();

            if (extensionToken != null)
            {
                extension.defaultClip  = (string)extensionToken.Value["defaultClip"];
                extension.needAutoPlay = (bool)extensionToken.Value["needAutoPlay"];
                extension.isSpaceAudio = (bool)extensionToken.Value["isSpaceAudio"];
                foreach (var pair in (JObject)extensionToken.Value["clips"])
                {
                    extension.clips.Add(new KeyValuePair <string, int>(pair.Key, (int)pair.Value));
                }

                if (extension.needAutoPlay)
                {
                    extension.autoPlayOptions       = new SeinAudioSourceAutoPlayOptions();
                    extension.autoPlayOptions.start = (float)extensionToken.Value["autoPlayOptions"]["start"];
                    extension.autoPlayOptions.end   = (float)extensionToken.Value["autoPlayOptions"]["end"];
                    extension.autoPlayOptions.loop  = (bool)extensionToken.Value["autoPlayOptions"]["loop"];
                }

                if (extension.isSpaceAudio)
                {
                    extension.spaceOptions                = new SeinAudioSourceSpaceOptions();
                    extension.spaceOptions.rotatable      = (bool)extensionToken.Value["spaceOptions"]["rotatable"];
                    extension.spaceOptions.refDistance    = (float)extensionToken.Value["spaceOptions"]["refDistance"];
                    extension.spaceOptions.maxDistance    = (float)extensionToken.Value["spaceOptions"]["maxDistance"];
                    extension.spaceOptions.rolloffFactor  = (float)extensionToken.Value["spaceOptions"]["rolloffFactor"];
                    extension.spaceOptions.coneInnerAngle = (float)extensionToken.Value["spaceOptions"]["coneInnerAngle"];
                    extension.spaceOptions.coneOuterAngle = (float)extensionToken.Value["spaceOptions"]["coneOuterAngle"];
                    extension.spaceOptions.coneOuterGain  = (float)extensionToken.Value["spaceOptions"]["coneOuterGain"];

                    var pm = (string)extensionToken.Value["spaceOptions"]["panningModel"];
                    if (pm == "equalpower")
                    {
                        extension.spaceOptions.panningModel = ESeinAudioPanningModelType.equalpower;
                    }
                    else
                    {
                        extension.spaceOptions.panningModel = ESeinAudioPanningModelType.HRTF;
                    }

                    var dm = (string)extensionToken.Value["spaceOptions"]["distanceModel"];
                    if (pm == "linear")
                    {
                        extension.spaceOptions.distanceModel = ESeinAudioDistanceModelType.linear;
                    }
                    else if (pm == "inverse")
                    {
                        extension.spaceOptions.distanceModel = ESeinAudioDistanceModelType.inverse;
                    }
                    else
                    {
                        extension.spaceOptions.distanceModel = ESeinAudioDistanceModelType.exponential;
                    }
                }
            }

            return(extension);
        }
Exemple #21
0
 public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
 {
     return(new Sein_imageBasedLightingExtension());
 }
        public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
        {
            var extension = new Sein_customMaterialExtension();

            if (extensionToken != null)
            {
                extension.className = (string)extensionToken.Value["className"];
                if (extensionToken.Value["renderOrder"] != null)
                {
                    extension.renderOrder = (int)extensionToken.Value["renderOrder"];
                }
                if (extensionToken.Value["cloneForInst"] != null)
                {
                    extension.cloneForInst = (bool)extensionToken.Value["cloneForInst"];
                }

                if (extensionToken.Value["uniforms"] != null)
                {
                    var uniforms            = (JObject)extensionToken.Value["uniforms"];
                    var uniformsTexture     = new List <SeinMaterialUniformTexture>();
                    var uniformsCubeTexture = new List <SeinMaterialUniformCubeTexture>();
                    var uniformsFloat       = new List <SeinMaterialUniformFloat>();
                    var uniformsFloatVec2   = new List <SeinMaterialUniformFloatVec2>();
                    var uniformsFloatVec3   = new List <SeinMaterialUniformFloatVec3>();
                    var uniformsFloatVec4   = new List <SeinMaterialUniformFloatVec4>();
                    var uniformsColor       = new List <SeinMaterialUniformColor>();
                    var uniformsFloatMat2   = new List <SeinMaterialUniformFloatMat2>();
                    var uniformsFloatMat3   = new List <SeinMaterialUniformFloatMat3>();
                    var uniformsFloatMat4   = new List <SeinMaterialUniformFloatMat4>();
                    var uniformsInt         = new List <SeinMaterialUniformInt>();
                    var uniformsIntVec2     = new List <SeinMaterialUniformIntVec2>();
                    var uniformsIntVec3     = new List <SeinMaterialUniformIntVec3>();
                    var uniformsIntVec4     = new List <SeinMaterialUniformIntVec4>();

                    foreach (var pair in uniforms)
                    {
                        var name    = pair.Key;
                        var uniform = pair.Value;
                        var typex   = uniform.Value <int>("type");
                        var type    = (ESeinMaterialUniformType)typex;

                        switch (type)
                        {
                        case (ESeinMaterialUniformType.FLOAT):
                            uniformsFloat.Add(new SeinMaterialUniformFloat {
                                name = name, value = uniform.Value <float>("value")
                            });
                            break;

                        case (ESeinMaterialUniformType.INT):
                            uniformsInt.Add(new SeinMaterialUniformInt {
                                name = name, value = uniform.Value <int>("value")
                            });
                            break;

                        case (ESeinMaterialUniformType.SAMPLER_2D):
                            var tex = (int)uniform.Value <JObject>("value")["index"];
                            uniformsTexture.Add(new SeinMaterialUniformTexture {
                                name = name, id = new TextureId {
                                    Id = tex, Root = root
                                }
                            });
                            break;

                        // todo: support cubemap
                        case (ESeinMaterialUniformType.SAMPLER_CUBE):
                            break;

                        case (ESeinMaterialUniformType.INT_VEC2):
                            var iv2 = uniform.Value <JArray>("value");
                            uniformsIntVec2.Add(new SeinMaterialUniformIntVec2 {
                                name = name, value = new Vector2Int((int)iv2[0], (int)iv2[1])
                            });
                            break;

                        case (ESeinMaterialUniformType.INT_VEC3):
                            var iv3 = uniform.Value <JArray>("value");
                            uniformsIntVec3.Add(new SeinMaterialUniformIntVec3 {
                                name = name, value = new Vector3Int((int)iv3[0], (int)iv3[1], (int)iv3[2])
                            });
                            break;

                        case (ESeinMaterialUniformType.INT_VEC4):
                            var iv4 = uniform.Value <JArray>("value");
                            uniformsIntVec4.Add(new SeinMaterialUniformIntVec4 {
                                name = name, value = new Vector4((int)iv4[0], (int)iv4[1], (int)iv4[2], (int)iv4[3])
                            });
                            break;

                        case (ESeinMaterialUniformType.FLOAT_VEC2):
                            var fv2 = uniform.Value <JArray>("value");
                            uniformsFloatVec2.Add(new SeinMaterialUniformFloatVec2 {
                                name = name, value = new Vector2((float)fv2[0], (float)fv2[1])
                            });
                            break;

                        case (ESeinMaterialUniformType.FLOAT_VEC3):
                            var fv3 = uniform.Value <JArray>("value");
                            uniformsFloatVec3.Add(new SeinMaterialUniformFloatVec3 {
                                name = name, value = new Vector3((float)fv3[0], (float)fv3[1], (float)fv3[2])
                            });
                            break;

                        case (ESeinMaterialUniformType.FLOAT_VEC4):
                            var fv4 = uniform.Value <JArray>("value");
                            if (uniform.Value <bool>("isColor"))
                            {
                                var value = new Color((float)fv4[0], (float)fv4[1], (float)fv4[2], (float)fv4[3]);
                                if (PlayerSettings.colorSpace == ColorSpace.Linear)
                                {
                                    value = value.gamma;
                                }
                                uniformsColor.Add(new SeinMaterialUniformColor {
                                    name = name, value = value
                                });
                            }
                            else
                            {
                                uniformsFloatVec4.Add(new SeinMaterialUniformFloatVec4 {
                                    name = name, value = new Vector4((float)fv4[0], (float)fv4[1], (float)fv4[2], (float)fv4[3])
                                });
                            }

                            break;

                        case (ESeinMaterialUniformType.FLOAT_MAT2):
                            var fm2 = uniform.Value <JArray>("value");
                            var vm2 = new Matrix4x4();
                            vm2.m00 = (float)fm2[0];
                            vm2.m01 = (float)fm2[1];
                            vm2.m10 = (float)fm2[2];
                            vm2.m11 = (float)fm2[3];
                            uniformsFloatMat2.Add(new SeinMaterialUniformFloatMat2 {
                                name = name, value = vm2
                            });
                            break;

                        case (ESeinMaterialUniformType.FLOAT_MAT3):
                            var fm3 = uniform.Value <JArray>("value");
                            var vm3 = new Matrix4x4();
                            vm3.m00 = (float)fm3[0];
                            vm3.m01 = (float)fm3[1];
                            vm3.m02 = (float)fm3[2];
                            vm3.m10 = (float)fm3[3];
                            vm3.m11 = (float)fm3[4];
                            vm3.m12 = (float)fm3[5];
                            vm3.m20 = (float)fm3[6];
                            vm3.m21 = (float)fm3[7];
                            vm3.m22 = (float)fm3[8];
                            uniformsFloatMat3.Add(new SeinMaterialUniformFloatMat3 {
                                name = name, value = vm3
                            });
                            break;

                        case (ESeinMaterialUniformType.FLOAT_MAT4):
                            var fm4 = uniform.Value <JArray>("value");
                            uniformsFloatMat4.Add(new SeinMaterialUniformFloatMat4
                            {
                                name  = name,
                                value = new Matrix4x4(
                                    new Vector4((float)fm4[0], (float)fm4[4], (float)fm4[8], (float)fm4[12]),
                                    new Vector4((float)fm4[1], (float)fm4[5], (float)fm4[9], (float)fm4[13]),
                                    new Vector4((float)fm4[2], (float)fm4[6], (float)fm4[10], (float)fm4[14]),
                                    new Vector4((float)fm4[3], (float)fm4[7], (float)fm4[11], (float)fm4[15])
                                    )
                            });
                            break;

                        default:
                            break;
                        }
                    }

                    extension.uniformsColor       = uniformsColor.ToArray();
                    extension.uniformsTexture     = uniformsTexture.ToArray();
                    extension.uniformsCubeTexture = uniformsCubeTexture.ToArray();
                    extension.uniformsFloat       = uniformsFloat.ToArray();
                    extension.uniformsFloatVec2   = uniformsFloatVec2.ToArray();
                    extension.uniformsFloatVec3   = uniformsFloatVec3.ToArray();
                    extension.uniformsFloatVec4   = uniformsFloatVec4.ToArray();
                    extension.uniformsFloatMat2   = uniformsFloatMat2.ToArray();
                    extension.uniformsFloatMat3   = uniformsFloatMat3.ToArray();
                    extension.uniformsFloatMat4   = uniformsFloatMat4.ToArray();
                    extension.uniformsInt         = uniformsInt.ToArray();
                    extension.uniformsIntVec2     = uniformsIntVec2.ToArray();
                    extension.uniformsIntVec3     = uniformsIntVec3.ToArray();
                    extension.uniformsIntVec4     = uniformsIntVec4.ToArray();
                }
            }

            return(extension);
        }
 public KHR_LightsPunctualNodeExtension(PunctualLightId lightId, GLTFRoot gltfRoot)
 {
     LightId = lightId;
 }
        public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, int[] arr, bool isIndices = false, BinaryWriter writer = null)
        {
            var count = arr.Length;

            if (count == 0)
            {
                MyLog.LogError("Accessors can not have a count of 0.");
            }

            var accessor = new Accessor();

            accessor.Count = count;
            accessor.Type  = GLTFAccessorAttributeType.SCALAR;

            int min = arr[0];
            int max = arr[0];

            for (var i = 1; i < count; i++)
            {
                var cur = arr[i];

                if (cur < min)
                {
                    min = cur;
                }
                if (cur > max)
                {
                    max = cur;
                }
            }

            var byteOffset = writer.BaseStream.Position;

            if (max <= byte.MaxValue && min >= byte.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedByte;

                foreach (var v in arr)
                {
                    writer.Write((byte)v);
                }
            }
            else if (max <= sbyte.MaxValue && min >= sbyte.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.Byte;

                foreach (var v in arr)
                {
                    writer.Write((sbyte)v);
                }
            }
            else if (max <= short.MaxValue && min >= short.MinValue && !isIndices)
            {
                accessor.ComponentType = GLTFComponentType.Short;

                foreach (var v in arr)
                {
                    writer.Write((short)v);
                }
            }
            else if (max <= ushort.MaxValue && min >= ushort.MinValue)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedShort;

                foreach (var v in arr)
                {
                    writer.Write((ushort)v);
                }
            }
            else if (min >= uint.MinValue)
            {
                accessor.ComponentType = GLTFComponentType.UnsignedInt;

                foreach (var v in arr)
                {
                    writer.Write((uint)v);
                }
            }
            else
            {
                accessor.ComponentType = GLTFComponentType.Float;

                foreach (var v in arr)
                {
                    writer.Write((float)v);
                }
            }

            accessor.Min = new List <double> {
                min
            };
            accessor.Max = new List <double> {
                max
            };

            var byteLength = writer.BaseStream.Position - byteOffset;

            accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength);

            var id = new AccessorId
            {
                Id   = root.Accessors.Count,
                Root = root
            };

            root.Accessors.Add(accessor);

            return(id);
        }
Exemple #25
0
 public VertexShadedGltfImporter(Material templateMaterial, GLTFRoot root, Stream stream, ImportOptions options)
     : base(root, stream, options)
 {
     _templateMaterial = templateMaterial;
 }
Exemple #26
0
        public override Extension Deserialize(GLTFRoot root, JProperty extensionToken)
        {
            var extension = new KHR_lights_punctualExtension();

            if (extensionToken == null)
            {
                return(null);
            }

            extension.isGlobal = extensionToken.Value["lights"] != null;

            if (extension.isGlobal)
            {
                foreach (var light in extensionToken.Value["lights"])
                {
                    var l = new KHR_lights_punctualExtension.Light();

                    var type = light.Value <string>("type");
                    l.name      = light.Value <string>("name");
                    l.intensity = light.Value <float>("intensity");
                    var c = light.Value <JArray>("color");
                    l.color = new Color((float)c[0], (float)c[1], (float)c[2]);

                    if (type == "directional")
                    {
                        l.type = LightType.Directional;
                    }
                    else if (type == "point")
                    {
                        l.type  = LightType.Point;
                        l.range = light.Value <float>("range");
                    }
                    else if (type == "spot")
                    {
                        l.type           = LightType.Spot;
                        l.range          = light.Value <float>("range");
                        l.innerConeAngle = light.Value <float>("innerConeAngle");
                        l.outerConeAngle = light.Value <float>("outerConeAngle");
                    }
                    else if (type == "area")
                    {
                        l.mode = light.Value <string>("mode");
                        if (l.mode == "rect")
                        {
                            l.type = LightType.Rectangle;
                        }
                        else
                        {
                            l.type = LightType.Disc;
                        }
                        var size = light.Value <JArray>("size");
                        l.size = new Vector2((float)size[0], (float)size[1]);
                    }

                    extension.lights.Add(l);
                }
            }
            else
            {
                extension.lightIndex = (int)extensionToken.Value["light"];
            }

            return(extension);
        }