예제 #1
0
        public static void CreateMesh(GameObject gameObject, Mesh m, PbrMaterial material, string name, ITextureProvider texProvider, IMaterialProvider matProvider)
        {
            if (m == null)
            {
                return;
            }
            var mesh = m.ToUnityMesh($"{name} Mesh ({gameObject.name})");

            // apply mesh to game object
            var mf = gameObject.GetComponent <MeshFilter>();

            mf.sharedMesh = mesh;

            // apply renderer and material
            if (m.AnimationFrames.Count > 0)               // if number of animations frames are 1, the blend vertices are in the uvs are handle by the lerp shader.
            {
                var smr = gameObject.AddComponent <SkinnedMeshRenderer>();
                smr.sharedMaterial = material.ToUnityMaterial(matProvider, texProvider);
                smr.sharedMesh     = mesh;
                smr.SetBlendShapeWeight(0, m.AnimationDefaultPosition);
            }
            else
            {
                var mr = gameObject.AddComponent <MeshRenderer>();
                mr.sharedMaterial = material.ToUnityMaterial(matProvider, texProvider);
            }
        }
예제 #2
0
        public IEnumerable <MonoBehaviour> SetReferencedData(PrimitiveData primitiveData, Table table, IMaterialProvider materialProvider, ITextureProvider textureProvider)
        {
            var mf = GetComponent <MeshFilter>();
            var playfieldMeshComponent = GetComponent <PlayfieldMeshComponent>();

            if (!mf || !playfieldMeshComponent)
            {
                return(Array.Empty <MonoBehaviour>());
            }

            var updatedComponents = new List <MonoBehaviour> {
                this
            };
            var mg   = new PrimitiveMeshGenerator(primitiveData);
            var mesh = mg
                       .GetTransformedMesh(table?.TableHeight ?? 0f, primitiveData.Mesh, Origin.Original, false)
                       .Transform(mg.TransformationMatrix(PlayfieldHeight));          // apply transformation to mesh, because this is the playfield
            var material = new PbrMaterial(
                table.GetMaterial(_playfieldMaterial),
                table.GetTexture(_playfieldImage)
                );

            MeshComponent <PrimitiveData, PrimitiveComponent> .CreateMesh(gameObject, mesh, material, "playfield_mesh", textureProvider, materialProvider);

            playfieldMeshComponent.AutoGenerate = false;

            updatedComponents.Add(playfieldMeshComponent);

            return(updatedComponents);
        }
예제 #3
0
        public void ShouldCorrectlyParseMaterialNames()
        {
            var test1 = PbrMaterial.ParseId("__std_", new[] { "" }, new[] { "Töxture1", "Töxture" });

            test1[0].Should().BeEmpty();
            test1[1].Should().BeEmpty();
            test1[2].Should().BeEmpty();
            test1[3].Should().BeEmpty();

            var test2 = PbrMaterial.ParseId("__std_ toexture1", new string[] { }, new[] { "Töxture1", "Töxture" });

            test2[0].Should().BeEmpty();
            test2[1].Should().Be("Töxture1");
            test2[2].Should().BeEmpty();
            test2[3].Should().BeEmpty();

            var test3 = PbrMaterial.ParseId("mat tex normal env", new [] { "Mat" }, new[] { "Tex", "Normal", "Env" });

            test3[0].Should().Be("Mat");
            test3[1].Should().Be("Tex");
            test3[2].Should().Be("Normal");
            test3[3].Should().Be("Env");

            var test4 = PbrMaterial.ParseId("mat tex __no_normal_map env", new [] { "Mat" }, new[] { "Tex", "Normal", "Env" });

            test4[0].Should().Be("Mat");
            test4[1].Should().Be("Tex");
            test4[2].Should().BeEmpty();
            test4[3].Should().Be("Env");
        }
예제 #4
0
 public RenderObject(string name, Mesh mesh, PbrMaterial material, bool isVisible)
 {
     Name      = name;
     Mesh      = mesh;
     Material  = material;
     IsVisible = isVisible;
 }
예제 #5
0
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }

            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);


            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");

                unityMaterial.SetTexture(BumpMap, table.GetTexture(vpxMaterial.NormalMap.Name)
                                         );
            }

            return(unityMaterial);
        }
예제 #6
0
 public UnityEngine.Material GetMaterial(PbrMaterial vpxMat)
 {
     if (_unityMaterials.ContainsKey(vpxMat))
     {
         return(_unityMaterials[vpxMat]);
     }
     return(null);
 }
        public RenderObjectGroup GetRenderObjects(Table table, Origin origin, bool asRightHanded = true)
        {
            var material = new PbrMaterial(table.GetMaterial(_data.PlayfieldMaterial), table.GetTexture(_data.Image));

            return(HasMeshAsPlayfield
                                ? _playfield.GetRenderObjects(table, origin, asRightHanded, "Table", material)
                                : new RenderObjectGroup(_data.Name, "Table", Matrix3D.Identity, GetFromTableDimensions(asRightHanded, material)));
        }
예제 #8
0
        public void AddMaterial(PbrMaterial vpxMat, UnityEngine.Material material)
        {
            UnityEngine.Material oldMaterial = null;
            _unityMaterials.TryGetValue(vpxMat, out oldMaterial);

            _unityMaterials[vpxMat] = material;
            if (oldMaterial != null)
            {
                Destroy(oldMaterial);
            }
        }
        public void SaveMaterial(PbrMaterial vpxMaterial, Material material)
        {
            _materials[vpxMaterial.Id] = material;
            var path = vpxMaterial.GetUnityFilename(_assetsMaterials);

            if (_options.SkipExistingMaterials && File.Exists(path))
            {
                return;
            }
            AssetDatabase.CreateAsset(material, path);
        }
        public static Material ToUnityMaterial(this PbrMaterial vpMat, IMaterialProvider materialProvider, Material textureMaterial)
        {
            if (materialProvider.HasMaterial(vpMat))
            {
                return(materialProvider.GetMaterial(vpMat));
            }

            var unityMaterial = RenderPipeline.Current.MaterialConverter.MergeMaterials(vpMat, textureMaterial);

            materialProvider.SaveMaterial(vpMat, unityMaterial);

            return(unityMaterial);
        }
        public static Material ToUnityMaterial(this PbrMaterial vpMat, IMaterialProvider materialProvider, ITextureProvider textureProvider, StringBuilder debug = null)
        {
            if (materialProvider.HasMaterial(vpMat))
            {
                return(materialProvider.GetMaterial(vpMat));
            }

            var unityMaterial = RenderPipeline.Current.MaterialConverter.CreateMaterial(vpMat, textureProvider, debug);

            materialProvider.SaveMaterial(vpMat, unityMaterial);

            return(unityMaterial);
        }
        public Material MergeMaterials(PbrMaterial vpxMaterial, Material texturedMaterial)
        {
            var nonTexturedMaterial = CreateMaterial(vpxMaterial, null);
            var mergedMaterial      = new Material(GetShader());

            mergedMaterial.CopyPropertiesFromMaterial(texturedMaterial);

            mergedMaterial.name = nonTexturedMaterial.name;
            mergedMaterial.SetColor(BaseColor, nonTexturedMaterial.GetColor(BaseColor));
            mergedMaterial.SetFloat(Metallic, nonTexturedMaterial.GetFloat(Metallic));
            mergedMaterial.SetFloat(Smoothness, nonTexturedMaterial.GetFloat(Smoothness));

            return(mergedMaterial);
        }
        private RenderObject GetFromTableDimensions(bool asRightHanded, PbrMaterial material)
        {
            var rgv = new[] {
                new Vertex3DNoTex2(_data.Left, _data.Top, _table.TableHeight),
                new Vertex3DNoTex2(_data.Right, _data.Top, _table.TableHeight),
                new Vertex3DNoTex2(_data.Right, _data.Bottom, _table.TableHeight),
                new Vertex3DNoTex2(_data.Left, _data.Bottom, _table.TableHeight),
            };
            var mesh = new Mesh {
                Name     = _data.Name,
                Vertices = rgv.Select(r => new Vertex3DNoTex2()).ToArray(),
                Indices  = new [] { 0, 1, 3, 0, 3, 2 }
            };

            for (var i = 0; i < 4; ++i)
            {
                rgv[i].Nx = 0;
                rgv[i].Ny = 0;
                rgv[i].Nz = 1.0f;

                rgv[i].Tv = (i & 2) > 0 ? 1.0f : 0.0f;
                rgv[i].Tu = i == 1 || i == 2 ? 1.0f : 0.0f;
            }

            var offs = 0;

            for (var y = 0; y <= 1; ++y)
            {
                for (var x = 0; x <= 1; ++x, ++offs)
                {
                    mesh.Vertices[offs].X = (x & 1) > 0 ? rgv[1].X : rgv[0].X;
                    mesh.Vertices[offs].Y = (y & 1) > 0 ? rgv[2].Y : rgv[0].Y;
                    mesh.Vertices[offs].Z = rgv[0].Z;

                    mesh.Vertices[offs].Tu = (x & 1) > 0 ? rgv[1].Tu : rgv[0].Tu;
                    mesh.Vertices[offs].Tv = (y & 1) > 0 ? rgv[2].Tv : rgv[0].Tv;

                    mesh.Vertices[offs].Nx = rgv[0].Nx;
                    mesh.Vertices[offs].Ny = rgv[0].Ny;
                    mesh.Vertices[offs].Nz = rgv[0].Nz;
                }
            }

            return(new RenderObject(
                       _data.Name,
                       asRightHanded ? mesh.Transform(Matrix3D.RightHanded) : mesh,
                       material,
                       true
                       ));
        }
        public Material GetMaterial(PbrMaterial material)
        {
            if (_materials.ContainsKey(material.Id))
            {
                return(_materials[material.Id]);
            }
            var path = material.GetUnityFilename(_assetsMaterials);

            if (File.Exists(path))
            {
                _materials[material.Id] = AssetDatabase.LoadAssetAtPath <Material>(path);
                return(_materials[material.Id]);
            }
            return(null);
        }
예제 #15
0
        public RenderObjectGroup GetRenderObjects(Table.Table table, Origin origin, bool asRightHanded = true,
                                                  string parent = null, PbrMaterial material = null)
        {
            var postMatrix = GetPostMatrix(table, origin);

            return(new RenderObjectGroup(_data.Name, parent ?? "Primitives", postMatrix, new RenderObject(
                                             _data.Name,
                                             GetTransformedMesh(table, origin, asRightHanded),
                                             material ?? new PbrMaterial(
                                                 table.GetMaterial(_data.Material),
                                                 table.GetTexture(_data.Image),
                                                 table.GetTexture(_data.NormalMap)
                                                 ),
                                             _data.IsVisible
                                             )));
        }
        private static void CopyMaterialName(MeshRenderer mr, string[] materialNames, string[] textureNames,
                                             ref string materialName, ref string mapName, ref string normalMapName, ref string envMapName)
        {
            if (!mr || materialNames == null || textureNames == null || mr.sharedMaterial == null)
            {
                return;
            }
            var result = PbrMaterial.ParseId(mr.sharedMaterial.name, materialNames, textureNames);

            if (materialName != null && !string.IsNullOrEmpty(result[0]))
            {
                materialName = result[0];
            }
            if (mapName != null)
            {
                var tex = mr.sharedMaterial.mainTexture;
                if (tex != null)
                {
                    mapName = tex.name;
                }
                else if (!string.IsNullOrEmpty(result[1]))
                {
                    mapName = result[1];
                }
            }
            if (normalMapName != null)
            {
                var tex = mr.sharedMaterial.GetTexture(RenderPipeline.Current.MaterialConverter.NormalMapProperty);
                if (tex != null)
                {
                    normalMapName = tex.name;
                }
                else if (!string.IsNullOrEmpty(result[2]))
                {
                    normalMapName = result[2];
                }
            }
            if (envMapName != null && !string.IsNullOrEmpty(result[3]))
            {
                envMapName = result[3];
            }
        }
예제 #17
0
        public static Material ToUnityMaterial(this PbrMaterial vpxMaterial, TableAuthoring table, StringBuilder debug = null)
        {
            if (table != null)
            {
                var existingMat = table.GetMaterial(vpxMaterial);
                if (existingMat != null)
                {
                    return(existingMat);
                }
            }

            var unityMaterial = MaterialConverter.CreateMaterial(vpxMaterial, table, debug);

            if (table != null)
            {
                table.AddMaterial(vpxMaterial, unityMaterial);
            }

            return(unityMaterial);
        }
예제 #18
0
        public static void Run()
        {
            // ExStart:ApplyPBRMaterialToBox
            // initialize a scene
            Scene scene = new Scene();
            // initialize PBR material object
            PbrMaterial mat = new PbrMaterial();

            // an almost metal material
            mat.MetallicFactor = 0.9;
            // material surface is very rough
            mat.RoughnessFactor = 0.9;
            // create a box to which the material will be applied
            var boxNode = scene.RootNode.CreateChildNode("box", new Box());

            boxNode.Material = mat;
            // save 3d scene into STL format
            scene.Save(RunExamples.GetOutputFilePath("PBR_Material_Box_Out.stl"), FileFormat.STLASCII);
            // ExEnd:ApplyPBRMaterialToBox
        }
예제 #19
0
    private async Task <Remote.Material> InitializePhysicalMaterial(
        RemoteMaterial material)
    {
        var remoteMaterial = RemoteManagerUnity.CurrentSession?.Actions.CreateMaterial(MaterialType.Pbr);

        remoteMaterial.Name = material.name;

        PbrMaterial pbrMaterial = remoteMaterial as PbrMaterial;

        pbrMaterial.AlbedoColor        = material.AlbedoColor.toRemoteColor4();
        pbrMaterial.AlphaClipThreshold = material.AlphaClipThreshold;
        pbrMaterial.AOScale            = material.AOScale;
        pbrMaterial.FadeOut            = material.FadeOut;
        pbrMaterial.Metalness          = material.Metalness;
        pbrMaterial.PbrFlags           = material.PbrFlags.toRemote();
        pbrMaterial.PbrVertexAlphaMode = material.VertexAlphaMode;
        pbrMaterial.Roughness          = material.Roughness;
        pbrMaterial.TexCoordOffset     = material.TexCoordOffset.toRemote();
        pbrMaterial.TexCoordScale      = material.TexCoordScale.toRemote();

        Task <Texture>[] textureLoads = new Task <Texture>[]
        {
            LoadTextureFromCache(material.AlbedoTextureUrl),
            LoadTextureFromCache(material.AOMapUrl),
            LoadTextureFromCache(material.MetalnessMapUrl),
            LoadTextureFromCache(material.NormalMapUrl),
            LoadTextureFromCache(material.RoughnessMapUrl)
        };

        Texture[] textures = await Task.WhenAll(textureLoads);

        int textureIndex = 0;

        pbrMaterial.AlbedoTexture = textures[textureIndex++];
        pbrMaterial.AOMap         = textures[textureIndex++];
        pbrMaterial.MetalnessMap  = textures[textureIndex++];
        pbrMaterial.NormalMap     = textures[textureIndex++];
        pbrMaterial.RoughnessMap  = textures[textureIndex++];

        return(remoteMaterial);
    }
예제 #20
0
        public RenderObject GetRenderObject(int frame, Table.Table table, string id, Origin origin, bool asRightHanded)
        {
            Init(table);
            var material = new PbrMaterial(table.GetMaterial(_data.Material), table.GetTexture(_data.Image));

            switch (id)
            {
            case Flat:
                var flatMesh = BuildFlatMesh(frame);
                return(new RenderObject(
                           id,
                           asRightHanded ? flatMesh.Transform(Matrix3D.RightHanded) : flatMesh,
                           material,
                           true
                           ));

            case Rod:
                CalculateArraySizes();
                var rodMesh = BuildRodMesh(frame);
                return(new RenderObject(
                           id,
                           asRightHanded ? rodMesh.Transform(Matrix3D.RightHanded) : rodMesh,
                           material,
                           true
                           ));

            case Spring:
                CalculateArraySizes();
                var springMesh = BuildSpringMesh(frame);
                return(new RenderObject(
                           id,
                           asRightHanded ? springMesh.Transform(Matrix3D.RightHanded) : springMesh,
                           material,
                           true
                           ));

            default:
                throw new ArgumentException("Unknown plunger mesh \"" + id + "\".");
            }
        }
예제 #21
0
        public void SaveMaterial(PbrMaterial material, Material unityMaterial)
        {
            var path = material.GetUnityFilename(_materialFolder);

            AssetDatabase.CreateAsset(unityMaterial, path);
        }
예제 #22
0
 public Material LoadMaterial(PbrMaterial material)
 {
     return(AssetDatabase.LoadAssetAtPath <Material>(material.GetUnityFilename(_materialFolder)));
 }
        public Material CreateMaterial(PbrMaterial vpxMaterial, ITextureProvider textureProvider, StringBuilder debug = null)
        {
            Material defaultMaterial = GetDefaultMaterial(vpxMaterial.MapBlendMode);

            var unityMaterial = new Material(GetShader(vpxMaterial));

            unityMaterial.CopyPropertiesFromMaterial(defaultMaterial);
            unityMaterial.name = vpxMaterial.Id;

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }


            if (vpxMaterial.MapBlendMode == BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }
            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            float metallicValue = 0f;

            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                metallicValue = 1f;
                debug?.AppendLine("Metallic set to 1.");
            }

            unityMaterial.SetFloat(Metallic, metallicValue);

            // roughness / glossiness
            SetSmoothness(unityMaterial, vpxMaterial.Roughness);

            // map
            if (vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseMap, textureProvider.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                unityMaterial.SetTexture(NormalMap, textureProvider.GetTexture(vpxMaterial.NormalMap.Name));
            }

            return(unityMaterial);
        }
예제 #24
0
        public void CreateScene(int width, int height, FloatColor color, bool useAntialiasing)
        {
            var renderTarget = new Framebuffer(width, height);

            renderTarget.Clear(color);
            var objects = new List <IHittable>();

            var sierpinsky = Texture.CreateFrom(FractalGenerator.SierpinskyCarpet(100, 100, Color.White, Color.Black))
                             .ToInfo();
            var reflectiveMaterial  = new ReflectiveMaterial(FloatColor.White, 0.4f, 1, 300, 1f, sierpinsky);
            var transparentMaterial = new TransparentMaterial(FloatColor.White, 0.1f, 0, 0.3f, 1.05f, 0.9f);

            var circuitryMaterial = new PbrMaterial(FloatColor.White,
                                                    Texture.LoadFrom(@"_Resources/Textures/circuitry-albedo.png").ToInfo(0.25f),
                                                    Texture.LoadFrom(@"_Resources/Textures/circuitry-emission.png").ToInfo(0.25f),
                                                    Texture.LoadFrom(@"_Resources/Textures/circuitry-smoothness.png").ToInfo(0.25f),
                                                    Texture.LoadFrom(@"_Resources/Textures/circuitry-normals.png").ToInfo(0.25f))
            {
                EmissionFactor     = 2,
                DiffuseCoefficient = 1,
                Specular           = 10,
                SpecularExponent   = 50,
                AmbientPower       = 1
            };

            var greenLavaMaterial = new PbrMaterial(FloatColor.White,
                                                    Texture.LoadFrom(@"_Resources/Textures/lava-albedo-smoothness-green.png").ToInfo(3),
                                                    Texture.LoadFrom(@"_Resources/Textures/lava-emission-green.png").ToInfo(3),
                                                    Texture.LoadFrom(@"_Resources/Textures/lava-albedo-smoothness.png").ToInfo(3),
                                                    Texture.LoadFrom(@"_Resources/Textures/lava-normals.png").ToInfo(3))
            {
                EmissionFactor     = 4,
                DiffuseCoefficient = 1,
                Specular           = 10,
                SpecularExponent   = 50,
                AmbientPower       = 1
            };

            var reflectiveSphere  = new Sphere(new Vector3(2f, -1f, 4), 1f, reflectiveMaterial);
            var transparentSphere = new Sphere(new Vector3(0f, -1f, 2), 1f, transparentMaterial);
            var textureSphere     = new Sphere(new Vector3(-1.5f, -1.5f, 3), 0.5f, greenLavaMaterial);

            objects.Add(reflectiveSphere);
            objects.Add(transparentSphere);
            objects.Add(textureSphere);
            objects.Add(new Plane(new Vector3(5, -2f, 0), new Vector3(0, 1, 0), circuitryMaterial));

            var sampler = new Sampler(new JitteredGenerator(0), new SquareDistributor(), 16, 32);
            var camera  = new PerspectiveCamera(renderTarget, new Vector3(0f, 0, -5), Vector3.Forward, Vector3.Up)
            {
                Sampler  = sampler,
                MaxDepth = 6,
            };

            Scene = new Scene(objects, camera,
                              new List <Light>
            {
                new PointLight
                {
                    Position = new Vector3(1, 1, 0),
                    Color    = FloatColor.White,
                },
                new PointLight
                {
                    Position = new Vector3(-1, 1, 0),
                    Color    = FloatColor.White,
                },
                new PointLight
                {
                    Position  = new Vector3(-2, 2, 15),
                    Color     = FloatColor.White,
                    Intensity = 1
                },
                new PointLight
                {
                    Position = new Vector3(1, 1f, 0),
                    Color    = FloatColor.Green,
                },
                new PointLight
                {
                    Position = new Vector3(-2, -1f, 0),
                    Color    = FloatColor.Red,
                },
            },
                              FloatColor.Black);
        }
예제 #25
0
 public RenderObjectGroup GetRenderObjects(Table.Table table, Origin origin, bool asRightHanded, string parent, PbrMaterial material) =>
 _meshGenerator.GetRenderObjects(table, origin, asRightHanded, parent, material);
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == Engine.VPT.BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }
            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);

            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseColorMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                unityMaterial.SetInt(NormalMapSpace, 0);                 // 0 = TangentSpace, 1 = ObjectSpace
                unityMaterial.SetFloat(NormalScale, 0f);                 // TODO FIXME: setting the scale to 0 for now. anything above 0 makes the entire unity editor window become black which is more likely a unity bug

                unityMaterial.SetTexture(NormalMap, table.GetTexture(vpxMaterial.NormalMap.Name));
            }

            // GI hack. This is a necessary step, see respective code in BaseUnlitGUI.cs of the HDRP source
            SetupMainTexForAlphaTestGI(unityMaterial, "_BaseColorMap", "_BaseColor");

            return(unityMaterial);
        }
예제 #27
0
        public void CreateScene(int width, int height, FloatColor color, bool useAntialiasing)
        {
            var renderTarget = new Framebuffer(width, height);

            var reflectiveFloor = new ReflectiveMaterial(FloatColor.White, 0.4f, 1, 300, 0.5f);

            var crystalMaterial = new PbrMaterial(FloatColor.White,
                                                  Texture.LoadFrom(@"_Resources/Textures/crystal-green.png").ToInfo(1),
                                                  Texture.LoadFrom(@"_Resources/Textures/crystal-green.png").ToInfo(1),
                                                  Texture.LoadFrom(@"_Resources/Textures/crystal-roughness.png").ToInfo(1),
                                                  Texture.LoadFrom(@"_Resources/Textures/crystal-normals.png").ToInfo(1))
            {
                EmissionFactor     = 1,
                DiffuseCoefficient = 1,
                Specular           = 10,
                SpecularExponent   = 50,
                AmbientPower       = 1
            };

            var reflectiveCrystal  = new ReflectiveMaterial(FloatColor.White, 0.7f, 0.5f, 1000, 0.6f);
            var transparentCrystal = new TransparentMaterial(FloatColor.White, 0.1f, 0, 0.3f, 1.05f, 0.9f);
            var transparentSphere  = new TransparentMaterial(FloatColor.White, 0.1f, 0, 0.3f, 1.05f, 0.9f);

            var crystal  = Model.LoadFromFile("_Resources/Models/crystal.obj", crystalMaterial, 1.5f);
            var crystal2 = Model.LoadFromFile("_Resources/Models/crystal.obj", reflectiveCrystal, 1.5f,
                                              Vector3.Left * 1.5f, Vector3.Forward, 45);
            var crystal3 = Model.LoadFromFile("_Resources/Models/crystal.obj", transparentCrystal, 1.5f,
                                              Vector3.Right * 1.5f, Vector3.Forward, -45);

            renderTarget.Clear(color);

            var objects = new List <IHittable>
            {
                new Plane(new Vector3(-2, 0, 0), new Vector3(1, 0, 0), reflectiveFloor),
                new Plane(new Vector3(2, 0, 0), new Vector3(-1, 0, 0), reflectiveFloor),
                new Plane(new Vector3(5, -2f, 0), new Vector3(0, 1, 0), reflectiveFloor),
                new Plane(new Vector3(5, 2f, 0), new Vector3(0, -1, 0), reflectiveFloor),
                new Plane(new Vector3(0, 2, 6), new Vector3(0, 0, -1), reflectiveFloor),
                new Plane(new Vector3(0, 2, -8), new Vector3(0, 0, 1), reflectiveFloor),
                new Sphere(Vector3.Zero, 1, transparentSphere)
            };

            objects.Add(crystal);
            objects.Add(crystal2);
            objects.Add(crystal3);

            var sampler = new Sampler(new RegularGenerator(), new SquareDistributor(), 25, 1);
            var camera  = new PerspectiveCamera(renderTarget, new Vector3(0f, 0, -5), Vector3.Forward, Vector3.Up)
            {
                Sampler  = sampler,
                MaxDepth = 5,
            };

            Scene = new Scene(objects, camera,
                              new List <Light>
            {
                new PointLight
                {
                    Position  = new Vector3(0, 0, 5),
                    Color     = FloatColor.White,
                    Intensity = 1
                }
            },
                              FloatColor.Black);
        }
예제 #28
0
 public static string GetUnityFilename(this PbrMaterial vpMat, string folderName)
 {
     return($"{folderName}/{vpMat.Id}.mat");
 }
예제 #29
0
        public RenderObjectGroup GetRenderObjects(int frame, Table.Table table, Origin origin, bool asRightHanded = true)
        {
            Init(table);

            // todo
            var translationMatrix = Matrix3D.Identity;
            var material          = new PbrMaterial(table.GetMaterial(_data.Material), table.GetTexture(_data.Image));

            // flat plunger
            if (_data.Type == PlungerType.PlungerTypeFlat)
            {
                var flatMesh = BuildFlatMesh(frame);
                return(new RenderObjectGroup(_data.Name, "Plungers", translationMatrix,
                                             new RenderObject(
                                                 FlatName,
                                                 asRightHanded ? flatMesh.Transform(Matrix3D.RightHanded) : flatMesh,
                                                 material,
                                                 true
                                                 )
                                             )
                {
                    ForceChild = true
                });
            }

            CalculateArraySizes();
            var rodMesh = BuildRodMesh(frame);

            // custom plunger
            if (_data.Type == PlungerType.PlungerTypeCustom)
            {
                var springMesh = BuildSpringMesh(frame);

                return(new RenderObjectGroup(_data.Name, "Plungers", translationMatrix,
                                             new RenderObject(
                                                 RodName,
                                                 asRightHanded ? rodMesh.Transform(Matrix3D.RightHanded) : rodMesh,
                                                 material,
                                                 true
                                                 ),
                                             new RenderObject(
                                                 SpringName,
                                                 asRightHanded ? springMesh.Transform(Matrix3D.RightHanded) : springMesh,
                                                 material,
                                                 true
                                                 )
                                             ));
            }

            // modern plunger
            return(new RenderObjectGroup(_data.Name, "Plungers", translationMatrix,
                                         new RenderObject(
                                             RodName,
                                             asRightHanded ? rodMesh.Transform(Matrix3D.RightHanded) : rodMesh,
                                             material,
                                             true
                                             )
                                         )
            {
                ForceChild = true
            });
        }
        public Material MergeMaterials(string vpxMaterial, Material textureMaterial)
        {
            var pbrMaterial = new PbrMaterial(_sourceTable.GetMaterial(vpxMaterial), id: $"{vpxMaterial.ToNormalizedName()} __textured");

            return(pbrMaterial.ToUnityMaterial(this, textureMaterial));
        }