Exemplo n.º 1
0
        public static void PointInstancerTest()
        {
            var scene        = USD.NET.Scene.Create();
            var stageWeakRef = new pxr.UsdStageWeakPtr(scene.Stage);
            var pi           = new PointInstancerSample();
            var cube         = new CubeSample();

            pi.prototypes.targetPaths = new string[] { "/Instancer/Cube" };

            // Three instances, all prototype index zero.
            pi.protoIndices = new int[3];
            pi.positions    = new UnityEngine.Vector3[3];
            pi.positions[0] = new UnityEngine.Vector3(-2.5f, 0, 0);
            pi.positions[1] = new UnityEngine.Vector3(0, 0, 0);
            pi.positions[2] = new UnityEngine.Vector3(2.5f, 0, 0);

            scene.Write("/Instancer", pi);
            scene.Write("/Instancer/Cube", cube);

            scene.Stage.Export("D:\\instancer-high-level.usda");

            var piSample = new PointInstancerSample();

            scene.Read("/Instancer", piSample);

            var matrices = piSample.ComputeInstanceMatrices(scene, "/Instancer");

            Console.WriteLine(String.Join(",", matrices.Select(p => p.ToString()).ToArray()));
            Console.WriteLine(String.Join(",", piSample.prototypes.targetPaths.Select(p => p.ToString()).ToArray()));
            Console.WriteLine(String.Join(",", piSample.protoIndices.Select(p => p.ToString()).ToArray()));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Read and write materials with as little code as possible.
        /// </summary>
        public static void MaterialIoTest()
        {
            var scene = Scene.Create();

            scene.Write("/Model/Geom/Cube", new CubeSample(1.0));
            scene.Write("/Model/Geom/Cube", new MaterialBindingSample("/Model/Materials/SampleMat"));
            scene.Write("/Model/Materials/SampleMat", new MaterialSample("/Model/Materials/PrevewShader.outputs:result"));

            var previewSurface = new PreviewSurfaceSample();

            previewSurface.diffuseColor.SetConnectedPath("/Model/Materials/Tex.outputs:result");
            scene.Write("/Model/Materials/PrevewShader", previewSurface);
            scene.Write("/Model/Materials/Tex", new TextureReaderSample("C:\\foo\\bar.png"));

            PrintScene(scene);

            var cube = new CubeSample();

            scene.Read("/Model/Geom/Cube", cube);
            var binding = new MaterialBindingSample();

            scene.Read("/Model/Geom/Cube", binding);
            var material = new MaterialSample();

            scene.Read(binding.binding.GetOnlyTarget(), material);
            var shader = new PreviewSurfaceSample();

            scene.Read(material.surface.GetConnectedPath(), shader);
        }
Exemplo n.º 3
0
        public static void WriteOverOnlyTest()
        {
            // Create the base scene layer.
            var strongerLayer = Scene.Create("D:\\stronger-no-sublayer.usda");

            strongerLayer.UpAxis = Scene.UpAxes.Z;

            // Create a cube for testing.
            var cubeSample = new CubeSample();

            // Write some data to the cube.
            // Set the WriteMode to "Over" and write a different /Cube value.
            strongerLayer.WriteMode = Scene.WriteModes.Over;
            cubeSample.size         = 1.1;
            strongerLayer.Write("/Cube", cubeSample);

            // Save.
            strongerLayer.Save();
        }
Exemplo n.º 4
0
        public static void WriteToUnderTest()
        {
            // Create the base scene layer.
            var strongerLayer = Scene.Create("D:\\stronger.usda");

            strongerLayer.UpAxis = Scene.UpAxes.Z;

            // Create a layer for overrides.
            var weakerLayer = Scene.Create("D:\\weaker.usda");

            weakerLayer.UpAxis = Scene.UpAxes.Z;

            // Create a cube for testing.
            var cubeSample = new CubeSample();

            // Add the subLayer to the main layer.
            strongerLayer.AddSubLayer(weakerLayer);

            // Write some data to the cube.
            // Set the WriteMode to "Over" and write a different /Cube value.
            strongerLayer.WriteMode = Scene.WriteModes.Over;
            cubeSample.size         = 1.1;
            strongerLayer.Write("/Cube", cubeSample);

            // Change the edit target.
            strongerLayer.SetEditTarget(weakerLayer);

            // Set the WriteMode to "Define" and write a different /Cube value.
            strongerLayer.WriteMode = Scene.WriteModes.Define;
            cubeSample.size         = 2.2;
            strongerLayer.Write("/Cube", cubeSample);

            // Save.
            strongerLayer.Save();
            weakerLayer.Save();
        }
Exemplo n.º 5
0
        public static void WriteToOverTest()
        {
            var cubeSample = new CubeSample();

            var sceneUnder = Scene.Create();

            sceneUnder.UpAxis = Scene.UpAxes.Z;

            var sceneOver = Scene.Create();

            sceneOver.UpAxis = Scene.UpAxes.Z;

            sceneUnder.AddSubLayer(sceneOver);

            cubeSample.size = 1.1;
            sceneUnder.Write("/Cube", cubeSample);

            sceneOver.WriteMode = Scene.WriteModes.Over;
            cubeSample.size     = 2.2;
            sceneOver.Write("/Cube", cubeSample);

            PrintScene(sceneUnder);
            PrintScene(sceneOver);
        }
Exemplo n.º 6
0
        public static void BasicTest()
        {
            var cubeSample = new CubeSample();
            var meshSample = new MeshSample();

            meshSample.visibility = Visibility.Invisible;
            var scene = Scene.Create();

            scene.Write("/Root/Cube", cubeSample);
            scene.Write("/Root/Mesh", meshSample);
            scene.Write("/Root/Mesh2", meshSample);

            foreach (var mesh in scene.ReadAll <XformableQuery>(rootPath:"/Root"))
            {
                Console.WriteLine("ReadAll Test: " + mesh.path);
            }

            foreach (var path in scene.Find <XformableQuery>(rootPath: "/Root"))
            {
                Console.WriteLine("Find Test: " + path);
            }

            try {
                Util.DiagnosticHandler.Instance.LastError = null;

                foreach (var mesh in scene.ReadAll <XformableQuery>(rootPath: "/Bogus/Root/Path"))
                {
                    Console.WriteLine("Query Test: " + mesh.path);
                }

                // TODO: for some reason, these stop working after the first exception is thrown,
                //       but it seems like *only* this code path is affected.
                if (!string.IsNullOrEmpty(Util.DiagnosticHandler.Instance.LastError))
                {
                    throw new ApplicationException(Util.DiagnosticHandler.Instance.LastError);
                }
                else
                {
                    throw new Exception("Expected exception but was not thrown.");
                }
            } catch (ApplicationException ex) {
                Console.WriteLine("Caught expected exception: " + ex.Message);
            }

            try {
                Util.DiagnosticHandler.Instance.LastError = null;

                foreach (var mesh in scene.ReadAll <BadBaseTypeQuery>(rootPath: "/Root"))
                {
                    Console.WriteLine("Query Test: " + mesh.path);
                }

                // TODO: for some reason, these stop working after the first exception is thrown,
                //       but it seems like *only* this code path is affected.
                if (!string.IsNullOrEmpty(Util.DiagnosticHandler.Instance.LastError))
                {
                    throw new ApplicationException(Util.DiagnosticHandler.Instance.LastError);
                }
                else
                {
                    throw new Exception("Expected exception but was not thrown.");
                }
            } catch (ApplicationException ex) {
                Console.WriteLine("Caught expected exception: " + ex.Message);
            }
        }
        //
        // Start generates a USD scene procedurally, containing a single cube with a material, shader
        // and texture bound. It then inspects the cube to discover the material. A Unity material is
        // constructed and the parameters are copied in a generic way. Similarly, the texture is
        // discovered and loaded as a Unity Texture2D and bound to the material.
        //
        // Also See: https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html
        //
        void Start()
        {
            // Create a scene for this test, but could also be read from disk.
            Scene usdScene = CreateSceneWithShading();

            // Read the material and shader ID.
            var    usdMaterial = new MaterialSample();
            string shaderId;

            // ReadMaterial was designed for Unity and assumes there is one "surface" shader bound.
            if (!MaterialSample.ReadMaterial(usdScene, kCubePath, usdMaterial, out shaderId))
            {
                throw new System.Exception("Failed to read material");
            }

            // Map the shader ID to the corresponding Unity/USD shader pair.
            ShaderPair shader;

            if (shaderId == null || !m_shaderMap.TryGetValue(shaderId, out shader))
            {
                throw new System.Exception("Material had no surface bound");
            }

            //
            // Read and process the shader-specific parameters.
            //

            // UsdShade requires all connections target an attribute, but we actually want to deserialize
            // the entire prim, so we get just the prim path here.
            var shaderPath = new pxr.SdfPath(usdMaterial.surface.connectedPath).GetPrimPath();

            usdScene.Read(shaderPath, shader.usdShader);

            //
            // Construct material & process the inputs, textures, and keywords.
            //

            var mat = new UnityEngine.Material(shader.unityShader);

            // Apply material keywords.
            foreach (string keyword in usdMaterial.requiredKeywords ?? new string[0])
            {
                mat.EnableKeyword(keyword);
            }

            // Iterate over all input parameters and copy values and/or construct textures.
            foreach (var param in shader.usdShader.GetInputParameters())
            {
                if (!SetMaterialParameter(mat, param.unityName, param.value))
                {
                    throw new System.Exception("Incompatible shader data type: " + param.ToString());
                }
            }

            foreach (var param in shader.usdShader.GetInputTextures())
            {
                if (string.IsNullOrEmpty(param.connectedPath))
                {
                    // Not connected to a texture.
                    continue;
                }

                // Only 2D textures are supported in this example.
                var usdTexture = new Texture2DSample();

                // Again, we want the prim path, not the attribute path.
                var texturePath = new pxr.SdfPath(param.connectedPath).GetPrimPath();
                usdScene.Read(texturePath, usdTexture);

                // This example also only supports explicit sourceFiles, they cannot be connected.
                if (string.IsNullOrEmpty(usdTexture.sourceFile.defaultValue))
                {
                    continue;
                }

                // For details, see: https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html
                foreach (string keyword in param.requiredShaderKeywords)
                {
                    mat.EnableKeyword(keyword);
                }

                var data     = System.IO.File.ReadAllBytes(usdTexture.sourceFile.defaultValue);
                var unityTex = new Texture2D(2, 2);
                unityTex.LoadImage(data);
                mat.SetTexture(param.unityName, unityTex);
                Debug.Log("Set " + param.unityName + " to " + usdTexture.sourceFile.defaultValue);

                unityTex.Apply(updateMipmaps: true, makeNoLongerReadable: false);
            }

            //
            // Create and bind the geometry.
            //

            // Create a cube and set the material.
            // Note that geometry is handled minimally here and is incomplete.
            var cubeSample = new CubeSample();

            usdScene.Read(kCubePath, cubeSample);

            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);

            go.transform.SetParent(transform, worldPositionStays: false);
            go.transform.localScale = Vector3.one * (float)cubeSample.size;
            m_cube = transform;

            go.GetComponent <MeshRenderer>().material = mat;
        }
        // ------------------------------------------------------------------------------------------ //
        // Create a USD scene for testing
        // ------------------------------------------------------------------------------------------ //
        static private Scene CreateSceneWithShading()
        {
            var scene = Scene.Create();

            var cubePath     = kCubePath;
            var materialPath = "/Model/Materials/SimpleMat";
            var shaderPath   = "/Model/Materials/SimpleMat/StandardShader";

            var albedoMapPath       = "/Model/Materials/SimpleMat/AlbedoMap";
            var normalMapPath       = "/Model/Materials/SimpleMat/NormalMap";
            var emissionMapPath     = "/Model/Materials/SimpleMat/EmissionMap";
            var metallicMapPath     = "/Model/Materials/SimpleMat/MetallicMap";
            var occlusionMapPath    = "/Model/Materials/SimpleMat/OcclusionMap";
            var parallaxMapPath     = "/Model/Materials/SimpleMat/ParallaxMap";
            var detailNormalMapPath = "/Model/Materials/SimpleMat/DetailNormalMap";
            var detailMaskPath      = "/Model/Materials/SimpleMat/DetailMask";

            var textureFilePath = @"Assets/Samples/USD/1.0.1-preview.1/ImportMaterials/Textures/";

            var cube = new CubeSample();

            cube.size      = 7;
            cube.transform = Matrix4x4.identity;

            //
            // Setup Material.
            //
            var material = new MaterialSample();

            material.surface.SetConnectedPath(shaderPath, "outputs:out");

            // Various shader keywords are required to enable the standard shader to work as intended,
            // while these can be encoded as part of the schema, often they require some logic (e.g. is
            // emission color != black?).
            material.requiredKeywords = new string[] { "_EMISSION" };

            //
            // Setup Shader.
            //
            var shader = new StandardShaderSample();

            shader.id = new pxr.TfToken("Unity.Standard");

            // Note that USD requires all connections target attributes, hence "outputs:out" appended to
            // the paths below. Think of this as a shader network graph, where a texture object could
            // be executed per pixel with a sampler,  "outputs:out" would be the sampled color.

            shader.smoothnessScale.defaultValue = 0.99f;

            shader.enableSpecularHighlights.defaultValue = true;
            shader.enableGlossyReflections.defaultValue  = true;

            shader.albedo.defaultValue = Color.white;
            shader.albedoMap.SetConnectedPath(albedoMapPath, "outputs:out");

            shader.normalMapScale.defaultValue = 0.76f;
            shader.normalMap.SetConnectedPath(normalMapPath, "outputs:out");

            shader.emission.defaultValue = Color.white * 0.3f;
            shader.emissionMap.SetConnectedPath(emissionMapPath, "outputs:out");

            shader.metallicMap.SetConnectedPath(metallicMapPath, "outputs:out");

            shader.occlusionMapScale.defaultValue = 0.65f;
            shader.occlusionMap.SetConnectedPath(occlusionMapPath, "outputs:out");

            shader.parallaxMapScale.defaultValue = 0.1f;
            shader.parallaxMap.SetConnectedPath(parallaxMapPath, "outputs:out");

            shader.detailMask.SetConnectedPath(detailMaskPath);
            shader.detailNormalMapScale.defaultValue = .05f;
            shader.detailNormalMap.SetConnectedPath(detailNormalMapPath, "outputs:out");

            //
            // Setup Textures.
            //
            var albedoTexture = new Texture2DSample();

            albedoTexture.sourceFile.defaultValue = textureFilePath + "albedoMap.png";
            albedoTexture.sRgb = true;

            var normalTexture = new Texture2DSample();

            normalTexture.sourceFile.defaultValue = textureFilePath + "normalMap.png";
            normalTexture.sRgb = true;

            var emissionTexture = new Texture2DSample();

            emissionTexture.sourceFile.defaultValue = textureFilePath + "emissionMap.png";
            emissionTexture.sRgb = true;

            var metallicTexture = new Texture2DSample();

            metallicTexture.sourceFile.defaultValue = textureFilePath + "metallicMap.png";
            metallicTexture.sRgb = true;

            var occlusionTexture = new Texture2DSample();

            occlusionTexture.sourceFile.defaultValue = textureFilePath + "occlusionMap.png";
            occlusionTexture.sRgb = true;

            var parallaxTexture = new Texture2DSample();

            parallaxTexture.sourceFile.defaultValue = textureFilePath + "parallaxMap.png";
            parallaxTexture.sRgb = true;

            var detailNormalTexture = new Texture2DSample();

            detailNormalTexture.sourceFile.defaultValue = textureFilePath + "detailMap.png";
            detailNormalTexture.sRgb = true;

            var detailMaskTexture = new Texture2DSample();

            detailMaskTexture.sourceFile.defaultValue = textureFilePath + "metallicMap.png";
            detailMaskTexture.sRgb = true;

            //
            // Write Everything.
            //
            scene.Write(cubePath, cube);
            scene.Write(materialPath, material);
            scene.Write(shaderPath, shader);

            scene.Write(albedoMapPath, albedoTexture);
            scene.Write(normalMapPath, normalTexture);
            scene.Write(emissionMapPath, emissionTexture);
            scene.Write(metallicMapPath, metallicTexture);
            scene.Write(occlusionMapPath, occlusionTexture);
            scene.Write(parallaxMapPath, parallaxTexture);
            scene.Write(detailNormalMapPath, detailNormalTexture);
            scene.Write(detailMaskPath, detailMaskTexture);

            //
            // Bind Material.
            //
            MaterialSample.Bind(scene, cubePath, materialPath);

            //
            // Write out the scene as a string, for debugging.
            //
            string s;

            scene.Stage.ExportToString(out s);
            Debug.Log("Loading:\n" + s);
            return(scene);
        }
Exemplo n.º 9
0
        public static void MaterialBindTest()
        {
            // Game plan:
            //   1. Create a cube
            //   2. Create a material
            //   3. Create a shader
            //   4. Create a texture
            //   5. Connect the material to the shader's output
            //   6. Connect the shader's albedo parameter to the texture's output
            //   7. Connect the texture to the source file on disk
            //   8. Write all values
            //   9. Bind the cube to the material
            var scene = Scene.Create();

            var cubePath     = "/Model/Geom/Cube";
            var materialPath = "/Model/Materials/SimpleMat";
            var shaderPath   = "/Model/Materials/SimpleMat/StandardShader";
            var texturePath  = "/Model/Materials/SimpleMat/AlbedoTexture";

            var cube = new CubeSample();

            cube.size = 1;

            var material = new MaterialSample();

            material.surface.SetConnectedPath(shaderPath, "outputs:out");

            var shader = new StandardShaderSample();

            shader.albedo.defaultValue = Color.white;
            shader.albedo.SetConnectedPath(texturePath, "outputs:out");
            AssertEqual(shader.albedo.connectedPath, texturePath + ".outputs:out");

            var texture = new Texture2DSample();

            texture.sourceFile.defaultValue = @"C:\A\Bogus\Texture\Path.png";
            texture.sRgb = true;

            scene.Write("/Model", new XformSample());
            scene.Write("/Model/Geom", new XformSample());
            scene.Write("/Model/Materials", new XformSample());
            scene.Write(cubePath, cube);
            scene.Write(materialPath, material);
            scene.Write(shaderPath, shader);
            scene.Write(texturePath, texture);

            MaterialSample.Bind(scene, cubePath, materialPath);

            var material2 = new MaterialSample();
            var shader2   = new StandardShaderSample();
            var texture2  = new Texture2DSample();

            scene.Read(materialPath, material2);
            scene.Read(shaderPath, shader2);
            scene.Read(texturePath, texture2);

            var param = shader2.GetInputParameters().First();

            AssertEqual(shader.albedo.connectedPath, param.connectedPath);
            AssertEqual("albedo", param.usdName);
            AssertEqual(shader.albedo.defaultValue, param.value);
            AssertEqual("_Color", param.unityName);

            var paramTex = shader2.GetInputTextures().First();

            AssertEqual(shader.albedoMap.connectedPath, paramTex.connectedPath);
            AssertEqual("albedoMap", paramTex.usdName);
            AssertEqual(shader.albedoMap.defaultValue, paramTex.value);
            AssertEqual("_MainTex", paramTex.unityName);

            AssertEqual(material.surface.defaultValue, material2.surface.defaultValue);
            AssertEqual(material.surface.connectedPath, material2.surface.connectedPath);
            AssertEqual(shader.albedo.defaultValue, shader2.albedo.defaultValue);
            AssertEqual(shader.albedo.connectedPath, shader2.albedo.connectedPath);
            AssertEqual(shader.id, shader2.id);
            AssertEqual(texture.sourceFile.defaultValue, texture2.sourceFile.defaultValue);
            AssertEqual(texture.sRgb, texture2.sRgb);

            PrintScene(scene);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Copy cube data from USD to Unity with the given import options.
        /// </summary>
        /// <param name="skinnedMesh">
        /// Whether the Cube to build is skinned or not. This will allow to determine which Renderer to create
        /// on the GameObject (MeshRenderer or SkinnedMeshRenderer). Default value is false (not skinned).
        /// </param>
        public static void BuildCube(CubeSample usdCube,
                                     GameObject go,
                                     SceneImportOptions options,
                                     bool skinnedMesh = false)
        {
            Material mat = null;

            var cubeGo    = GameObject.CreatePrimitive(PrimitiveType.Cube);
            var unityMesh = cubeGo.GetComponent <MeshFilter>().sharedMesh;

            GameObject.DestroyImmediate(cubeGo);

            // Because Unity only handle a cube with a default size, the custom size of it is define by the localScale
            // transform. This also need to be taken into account while computing the Unity extent of the mesh (see bellow).
            // This is doable because xformable data are always handled before mesh data, so go.transform already
            // contains any transform of the geometry.
            float size = (float)usdCube.size;

            go.transform.localScale = go.transform.localScale * size;

            bool changeHandedness = options.changeHandedness == BasisTransformation.SlowAndSafe;
            bool hasBounds        = usdCube.extent.size.x > 0 ||
                                    usdCube.extent.size.y > 0 ||
                                    usdCube.extent.size.z > 0;

            if (ShouldImport(options.meshOptions.boundingBox) && hasBounds)
            {
                if (changeHandedness)
                {
                    usdCube.extent.center = UnityTypeConverter.ChangeBasis(usdCube.extent.center);

                    // Divide the extent by the size of the cube. A custom size of the extent is define by
                    // the localScale transform (see above).
                    usdCube.extent.extents = UnityTypeConverter.ChangeBasis(usdCube.extent.extents) / size;
                }

                unityMesh.bounds = usdCube.extent;
            }
            else if (ShouldCompute(options.meshOptions.boundingBox))
            {
                unityMesh.RecalculateBounds();
            }

            if (usdCube.colors != null && ShouldImport(options.meshOptions.color))
            {
                // NOTE: The following color conversion assumes PlayerSettings.ColorSpace == Linear.
                // For best performance, convert color space to linear off-line and skip conversion.

                if (usdCube.colors.Length == 1)
                {
                    // Constant color can just be set on the material.
                    mat = options.materialMap.InstantiateSolidColor(usdCube.colors[0].gamma);
                    Debug.Log("constant colors assigned");
                }
                else if (usdCube.colors.Length == 6)
                {
                    // Uniform colors to verts.
                    // Note that USD cubes have 6 uniform colors and Unity cube mesh has 24 (6*4)
                    // TODO: move the conversion to C++ and use the color management API.
                    Debug.Log(unityMesh.vertexCount);
                    for (int i = 0; i < usdCube.colors.Length; i++)
                    {
                        usdCube.colors[i] = usdCube.colors[i];
                    }

                    var unityColors = new Color[24];
                    // Front:0, Back:1, Top:2, Bottom:3, Right:4, Left:5
                    unityColors[0] = usdCube.colors[0];  // front bottom right
                    unityColors[1] = usdCube.colors[0];  // front bottom left
                    unityColors[2] = usdCube.colors[0];  // front top right
                    unityColors[3] = usdCube.colors[0];  // front top left

                    unityColors[4] = usdCube.colors[2];  // top back right
                    unityColors[5] = usdCube.colors[2];  // top back left
                    unityColors[6] = usdCube.colors[1];  // back bottom right
                    unityColors[7] = usdCube.colors[1];  // back bottom left

                    unityColors[8]  = usdCube.colors[2]; // top front right
                    unityColors[9]  = usdCube.colors[2]; // top front left
                    unityColors[10] = usdCube.colors[1]; // back top right
                    unityColors[11] = usdCube.colors[1]; // back top left

                    unityColors[12] = usdCube.colors[3]; // Bottom back right
                    unityColors[13] = usdCube.colors[3]; // Bottom front right
                    unityColors[14] = usdCube.colors[3]; // Bottom front left
                    unityColors[15] = usdCube.colors[3]; // Bottom back left

                    unityColors[16] = usdCube.colors[5]; // left front bottom
                    unityColors[17] = usdCube.colors[5]; // left front top
                    unityColors[18] = usdCube.colors[5]; // left back top
                    unityColors[19] = usdCube.colors[5]; // left back bottom

                    unityColors[20] = usdCube.colors[4]; // right back bottom
                    unityColors[21] = usdCube.colors[4]; // right back top
                    unityColors[22] = usdCube.colors[4]; // right front top
                    unityColors[23] = usdCube.colors[4]; // right front bottom

                    unityMesh.colors = unityColors;
                }
                else if (usdCube.colors.Length == 24)
                {
                    // Face varying colors to verts.
                    // Note that USD cubes have 24 face varying colors and Unity cube mesh has 24 (6*4)
                    // TODO: move the conversion to C++ and use the color management API.
                    Debug.Log(unityMesh.vertexCount);
                    for (int i = 0; i < usdCube.colors.Length; i++)
                    {
                        usdCube.colors[i] = usdCube.colors[i];
                    }

                    // USD order: front, back, top, bottom, right, left
                    var unityColors = new Color[24];
                    unityColors[0] = usdCube.colors[3];       // front bottom right
                    unityColors[1] = usdCube.colors[2];       // front bottom left
                    unityColors[2] = usdCube.colors[0];       // front top right
                    unityColors[3] = usdCube.colors[1];       // front top left

                    unityColors[4] = usdCube.colors[8 + 1];   // top back right
                    unityColors[5] = usdCube.colors[8 + 2];   // top back left
                    unityColors[6] = usdCube.colors[4 + 3];   // back bottom right
                    unityColors[7] = usdCube.colors[4 + 0];   // back bottom left

                    unityColors[8]  = usdCube.colors[8 + 0];  // top front right
                    unityColors[9]  = usdCube.colors[8 + 3];  // top front left
                    unityColors[10] = usdCube.colors[4 + 2];  // back top right
                    unityColors[11] = usdCube.colors[4 + 1];  // back top left

                    unityColors[12] = usdCube.colors[12 + 1]; // Bottom back right
                    unityColors[13] = usdCube.colors[12 + 2]; // Bottom front right
                    unityColors[14] = usdCube.colors[12 + 3]; // Bottom front left
                    unityColors[15] = usdCube.colors[12 + 0]; // Bottom back left

                    unityColors[16] = usdCube.colors[20 + 1]; // left front bottom
                    unityColors[17] = usdCube.colors[20 + 2]; // left front top
                    unityColors[18] = usdCube.colors[20 + 3]; // left back top
                    unityColors[19] = usdCube.colors[20 + 0]; // left back bottom

                    unityColors[20] = usdCube.colors[16 + 2]; // right back bottom
                    unityColors[21] = usdCube.colors[16 + 3]; // right back top
                    unityColors[22] = usdCube.colors[16 + 0]; // right front top
                    unityColors[23] = usdCube.colors[16 + 1]; // right front bottom

                    unityMesh.colors = unityColors;
                }
                else if (usdCube.colors.Length == 8)
                {
                    // Vertex colors map on to verts.
                    // Note that USD cubes have 8 verts but Unity cube mesh has 24 (6*4)
                    // TODO: move the conversion to C++ and use the color management API.
                    Debug.Log(unityMesh.vertexCount);
                    for (int i = 0; i < usdCube.colors.Length; i++)
                    {
                        usdCube.colors[i] = usdCube.colors[i];
                    }

                    // USD order: front (top-right -> ccw)
                    //            back (bottom-left -> ccw (from back perspective))
                    var unityColors = new Color[24];
                    unityColors[0] = usdCube.colors[3];  // front bottom right
                    unityColors[1] = usdCube.colors[2];  // front bottom left
                    unityColors[2] = usdCube.colors[0];  // front top right
                    unityColors[3] = usdCube.colors[1];  // front top left

                    unityColors[4] = usdCube.colors[6];  // top back right
                    unityColors[5] = usdCube.colors[5];  // top back left
                    unityColors[6] = usdCube.colors[7];  // back bottom right
                    unityColors[7] = usdCube.colors[4];  // back bottom left

                    unityColors[8]  = usdCube.colors[0]; // top front right
                    unityColors[9]  = usdCube.colors[1]; // top front left
                    unityColors[10] = usdCube.colors[6]; // back top right
                    unityColors[11] = usdCube.colors[5]; // back top left

                    unityColors[12] = usdCube.colors[7]; // Bottom back right
                    unityColors[13] = usdCube.colors[3]; // Bottom front right
                    unityColors[14] = usdCube.colors[2]; // Bottom front left
                    unityColors[15] = usdCube.colors[4]; // Bottom back left

                    unityColors[16] = usdCube.colors[2]; // left front bottom
                    unityColors[17] = usdCube.colors[1]; // left front top
                    unityColors[18] = usdCube.colors[5]; // left back top
                    unityColors[19] = usdCube.colors[4]; // left back bottom

                    unityColors[20] = usdCube.colors[7]; // right back bottom
                    unityColors[21] = usdCube.colors[6]; // right back top
                    unityColors[22] = usdCube.colors[0]; // right front top
                    unityColors[23] = usdCube.colors[3]; // right front bottom

                    unityMesh.colors = unityColors;
                    Debug.Log("vertex colors assigned");
                }
                else
                {
                    // FaceVarying and uniform both require breaking up the mesh and are not yet handled in
                    // this example.
                    Debug.LogWarning("Uniform (color per face) and FaceVarying (color per vert per face) "
                                     + "display color not supported in this example");
                }
            }

            if (mat == null)
            {
                mat = options.materialMap.InstantiateSolidColor(Color.white);
            }

            // Create Unity mesh.
            Renderer renderer;

            if (skinnedMesh)
            {
                SkinnedMeshRenderer skinnedRenderer = ImporterBase.GetOrAddComponent <SkinnedMeshRenderer>(go);

                if (skinnedRenderer.sharedMesh == null)
                {
                    skinnedRenderer.sharedMesh = Mesh.Instantiate(unityMesh);
                }

                renderer = skinnedRenderer;
            }
            else
            {
                renderer = ImporterBase.GetOrAddComponent <MeshRenderer>(go);
                MeshFilter meshFilter = ImporterBase.GetOrAddComponent <MeshFilter>(go);

                if (meshFilter.sharedMesh == null)
                {
                    meshFilter.sharedMesh = Mesh.Instantiate(unityMesh);
                }
            }

            if (unityMesh.subMeshCount == 1)
            {
                renderer.sharedMaterial = mat;
            }
            else
            {
                var mats = new Material[unityMesh.subMeshCount];
                for (int i = 0; i < mats.Length; i++)
                {
                    mats[i] = mat;
                }

                renderer.sharedMaterials = mats;
            }
        }
Exemplo n.º 11
0
        public static void ReadWriteTest()
        {
            // Game plan:
            //   1. Create a cube
            //   2. Create a material
            //   3. Create a shader
            //   4. Create a texture
            //   5. Connect the material to the shader's output
            //   6. Connect the shader's albedo parameter to the texture's output
            //   7. Connect the texture to the source file on disk
            //   8. Write all values
            //   9. Bind the cube to the material
            var scene = Scene.Create();

            var cubePath          = "/Model/Geom/Cube";
            var materialPath      = "/Model/Materials/SimpleMat";
            var shaderPath        = "/Model/Materials/SimpleMat/PreviewMaterial";
            var texturePath       = "/Model/Materials/SimpleMat/TextureReader";
            var primvarReaderPath = "/Model/Materials/SimpleMat/UvReader";

            var cube = new CubeSample();

            cube.size = 1;

            var material = new MaterialSample();

            material.surface.SetConnectedPath(shaderPath, "outputs:result");

            var shader = new PreviewSurfaceSample();

            shader.diffuseColor.defaultValue = Vector3.one;
            shader.diffuseColor.SetConnectedPath(texturePath, "outputs:rgb");

            var texture = new TextureReaderSample();

            texture.file.defaultValue = new SdfAssetPath(@"C:\A\Bogus\Texture\Path.png");

            var primvarReader = new PrimvarReaderSample <Vector2>();

            primvarReader.varname.defaultValue = new TfToken("st");

            scene.Write("/Model", new XformSample());
            scene.Write("/Model/Geom", new XformSample());
            scene.Write("/Model/Materials", new XformSample());
            scene.Write(cubePath, cube);
            scene.Write(materialPath, material);
            scene.Write(shaderPath, shader);
            scene.Write(texturePath, texture);
            scene.Write(primvarReaderPath, primvarReader);

            MaterialSample.Bind(scene, cubePath, materialPath);

            var material2      = new MaterialSample();
            var shader2        = new PreviewSurfaceSample();
            var texture2       = new TextureReaderSample();
            var primvarReader2 = new PrimvarReaderSample <Vector2>();

            scene.Read(materialPath, material2);
            scene.Read(shaderPath, shader2);
            scene.Read(texturePath, texture2);
            scene.Read(primvarReaderPath, primvarReader2);

            var param = shader2.GetInputParameters().First();

            AssertEqual(shader.diffuseColor.connectedPath, param.connectedPath);
            AssertEqual("diffuseColor", param.usdName);
            AssertEqual(shader.diffuseColor.defaultValue, param.value);
            AssertEqual("_DiffuseColor", param.unityName);

            AssertEqual(material.surface.defaultValue, material2.surface.defaultValue);
            AssertEqual(material.surface.connectedPath, material2.surface.connectedPath);
            AssertEqual(shader.diffuseColor.defaultValue, shader2.diffuseColor.defaultValue);
            AssertEqual(shader.diffuseColor.connectedPath, shader2.diffuseColor.connectedPath);
            AssertEqual(shader.id, shader2.id);
            AssertEqual(texture.file.defaultValue, texture2.file.defaultValue);
            AssertEqual(primvarReader.varname.defaultValue, primvarReader.varname.defaultValue);

            PrintScene(scene);
        }