public void SetNewMaterial() { Renderer _renderer = GetComponent<Renderer>(); Material newMat = new Material(Shader.Find("Diffuse")); //Material newMat = new Material(renderer.sharedMaterial); bool baseMaterialHaveNormalMap = _renderer.sharedMaterial.GetTexture("_BumpMap"); bool baseMaterialHaveCubeMap = _renderer.sharedMaterial.GetTexture("_Cube"); newMat.SetTexture("_MainTex", _renderer.sharedMaterial.GetTexture("_MainTex")); newMat.SetTextureOffset("_MainTex", offset); newMat.SetTextureScale("_MainTex", scale); if (baseMaterialHaveNormalMap) { newMat.SetTexture("_BumpMap", _renderer.sharedMaterial.GetTexture("_BumpMap")); newMat.SetTextureOffset("_BumpMap", offset); newMat.SetTextureScale("_BumpMap", scale); } if (baseMaterialHaveCubeMap) { newMat.SetTexture("_Cube", _renderer.sharedMaterial.GetTexture("_Cube")); newMat.SetTextureScale("_Cube", scale); newMat.SetTextureOffset("_Cube", offset); } newMat.color = materialColor; _renderer.sharedMaterial = newMat; }
private void GenerateWireframeMeshsAndMaterials() { foreach (MeshNMaterial subObj in subObjects) { //添加AmazingWireframeGenerator subObj.gameObject.AddComponent<TheAmazingWireframeGenerator>(); for (int i = 0;i < subObj.originalMaterials.Length;i++) { Material wireframeNoTexMat = new Material( Shader.Find("VacuumShaders/The Amazing Wireframe/Unlit/NoTex")); wireframeNoTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color")); wireframeNoTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON"); wireframeNoTexMat.EnableKeyword("V_WIRE_LIGHT_ON"); subObj.wireframeNoTexMaterials[i] = wireframeNoTexMat; Material wireframeTexMat = new Material( Shader.Find("VacuumShaders/The Amazing Wireframe/Deferred/Bumped Specular")); wireframeTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color")); if (subObj.originalMaterials[i].HasProperty("_SpecColor")) wireframeTexMat.SetColor("_SpecColor", subObj.originalMaterials[i].GetColor("_SpecColor")); if (subObj.originalMaterials[i].HasProperty("_Shininess")) wireframeTexMat.SetFloat("_Shininess", subObj.originalMaterials[i].GetFloat("_Shininess")); wireframeTexMat.SetTexture("_MainTex", subObj.originalMaterials[i].GetTexture("_MainTex")); if (subObj.originalMaterials[i].HasProperty("_BumpMap")) wireframeTexMat.SetTexture("_BumpMap", subObj.originalMaterials[i].GetTexture("_BumpMap")); wireframeTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON"); wireframeTexMat.EnableKeyword("V_WIRE_LIGHT_ON"); subObj.wireframeTexMaterials[i] = wireframeTexMat; } } }
Material OnAssignMaterialModel( Material material, Renderer renderer ) { //Debug.Log( "Looking for material for " + renderer.name ); string standardMatPath = "Assets/Models/" + renderer.name + "/Materials/" + material.name + ".mat"; string standardMatDir = "Assets/Models/" + renderer.name + "/Materials/"; string standardDiffusePath = "Assets/Models/" + renderer.name + "/Textures/" + renderer.name + "_diffuse.png"; string standardNormalPath = "Assets/Models/" + renderer.name + "/Textures/" + renderer.name + "_normal.png"; if( AssetDatabase.LoadAssetAtPath( standardMatPath, typeof( Material ) ) ) { //Debug.Log( "Found standard material" ); return ( Material )AssetDatabase.LoadAssetAtPath( standardMatPath, typeof( Material ) ); } else { //Debug.Log( "Couldn't find standard material, creating new material in " + standardMatPath ); material.shader = Shader.Find( "Diffuse" ); if( AssetDatabase.LoadAssetAtPath( standardDiffusePath, typeof( Texture2D ) ) ) { //Debug.Log( "Found associated diffuse texture for " + material.name ); Texture defaultDiffuse = ( Texture2D )AssetDatabase.LoadAssetAtPath( standardDiffusePath, typeof( Texture2D ) ); material.SetTexture( "Base", defaultDiffuse ); } if( AssetDatabase.LoadAssetAtPath( standardNormalPath, typeof( Texture ) ) ) { //Debug.Log( "Found associated normal texture for " + material.name ); Texture2D defaultNormal = ( Texture2D )AssetDatabase.LoadAssetAtPath( standardNormalPath, typeof( Texture2D ) ); material.shader = Shader.Find( "Bumped Diffuse" ); material.SetTexture( "Normalmap", defaultNormal ); } Directory.CreateDirectory( standardMatDir ); AssetDatabase.CreateAsset( material, standardMatPath ); return material; } }
private void AddOverlay(TextureSet mTexture, TextureSet dTexture, float altitude, float fadeDistance, float pqsfadeDistance) { Assembly assembly = Assembly.GetExecutingAssembly(); string[] resources = assembly.GetManifestResourceNames(); StreamReader shaderStreamReader = new StreamReader(assembly.GetManifestResourceStream("CityLights.Shaders.Compiled-SphereCityLights.shader")); Log("read stream"); String shaderString = shaderStreamReader.ReadToEnd(); Material lightMaterial = new Material(shaderString); Material pqsLightMaterial = new Material(shaderString); lightMaterial.SetTexture("_MainTex", mTexture.Texture); lightMaterial.SetTexture("_DetailTex", dTexture.Texture); lightMaterial.SetFloat("_DetailScale", dTexture.Scale); lightMaterial.SetVector("_DetailOffset", dTexture.Offset); lightMaterial.SetFloat("_FadeDist", fadeDistance); lightMaterial.SetFloat("_FadeScale", 1); pqsLightMaterial.SetTexture("_MainTex", mTexture.Texture); pqsLightMaterial.SetTexture("_DetailTex", dTexture.Texture); pqsLightMaterial.SetFloat("_DetailScale", dTexture.Scale); pqsLightMaterial.SetVector("_DetailOffset", dTexture.Offset); pqsLightMaterial.SetFloat("_FadeDist", pqsfadeDistance); pqsLightMaterial.SetFloat("_FadeScale", .02f); overlayList.Add(Overlay.GeneratePlanetOverlay("Kerbin", altitude, lightMaterial, pqsLightMaterial, mTexture.StartOffset, false, true)); }
void InitMaterial(Material mat) { mat.SetTexture("_Transmittance", m_transmittance); mat.SetTexture("_Inscatter", m_inscatter); mat.SetFloat("SUN_INTENSITY", m_sunIntensity); mat.SetVector("SUN_DIR", m_sun.transform.forward*-1.0f); //Dont change this mat.SetVector("EARTH_POS", new Vector3(0.0f, 6360010.0f, 0.0f)); }
public static Material getFoodMat(int num) { Material ret; bool success = dicFoodMats.TryGetValue (num,out ret); if (!success) { ret = new Material(Shader.Find("SnakeXShader/Food")); ret.SetTexture("_MainTex", ResourceControl.getInstance().getTexture("body" + num)); ret.SetTexture("_BlendTex", ResourceControl.getInstance().getTexture("foodBlender")); dicFoodMats.Add(num,ret); } return ret; }
private void Start() { Debug.Assert(_chargeSpeed > 0f); Material mat = new Material(Shader.Find(_shaderName)); _citizenBodyRenderer.material = mat; _currThres = _bottomThres; mat.SetVector("_PlanePos", new Vector4(_planeHeight, 0, 0, 1)); mat.SetVector("_PlaneNormal", new Vector4(-1, 0, 0, 0)); mat.SetFloat("_ThresDist", _currThres); mat.SetTexture("_BeforeTex", VFXManager.Instance.RandomRiotTex()); mat.SetTexture("_AfterTex", _afterTex); }
public Material CreateMaterial( string strShaderName, Texture tex) { Shader shader = Get( strShaderName); Material mtrl = new Material( shader); if( strShaderName.Equals( "newark_shader")) mtrl.SetTexture( "_maintex", tex); else mtrl.SetTexture( "_MainTex", tex); return mtrl; }
// protected override void Start() public override void Start() { base.Start(); m_initJacobiansMat=new Material(ShaderTool.GetMatFromShader2("CompiledInitJacobians.shader")); m_whiteCapsPrecomputeMat=new Material(ShaderTool.GetMatFromShader2("CompiledWhiteCapsPrecompute.shader")); m_initJacobiansMat.SetTexture("_Spectrum01", m_spectrum01); m_initJacobiansMat.SetTexture("_Spectrum23", m_spectrum23); m_initJacobiansMat.SetTexture("_WTable", m_WTable); m_initJacobiansMat.SetVector("_Offset", m_offset); m_initJacobiansMat.SetVector("_InverseGridSizes", m_inverseGridSizes); }
public static Material createMaterial2(string colorTexturePath, string normalTexturePath, string specularTexturePath) { WWW loader; Material mat = new Material(Shader.Find("Bumped Diffuse")); loader = new WWW("file://" + colorTexturePath); mat.SetTexture("_MainTex", loader.texture); loader = new WWW("file://" + normalTexturePath); Texture2D normalTexture = NormalMap(loader.texture); mat.SetTexture("_BumpMap", normalTexture); mat.SetFloat("_BumpScale", 1.0f); return mat; }
private static void CreateUIAtlasPrefab(Object ob) { string path = AssetDatabase.GetAssetPath(ob); if (string.IsNullOrEmpty(path) || !IsTextureFile(path)) { Debug.LogError("未选中对象或者选择的对象不是图片"); return; } if (Path.GetExtension(path) == ".png" && !path.Contains("_Alpha") && !path.Contains("_RGB")) { ShowProgress(path, 0.5f); #region 第一步:根据图片创建材质对象 Material mat = new Material(Shader.Find("UI/UI_ETC")); mat.name = ob.name; AssetDatabase.CreateAsset(mat, path.Replace(".png", ".mat")); SetTextureReadable(path); SeperateRGBandAlphaChannel(path); TextureSetting(path, TextureImporterType.Default, TextureImporterFormat.ETC_RGB4, false); Texture2D _mainTex = AssetDatabase.LoadAssetAtPath(path.Replace(".png", "_RGB.png"), typeof(Texture2D)) as Texture2D; Texture2D _alphaTex = AssetDatabase.LoadAssetAtPath(path.Replace(".png", "_Alpha.png"), typeof(Texture2D)) as Texture2D; mat.SetTexture("_MainTex", _mainTex); mat.SetTexture("_AlphaTex", _alphaTex); #endregion GameObject go = null; UIAtlas uiAtlas = null; if ((go = AssetDatabase.LoadAssetAtPath(path.Replace(".png", ".prefab"), typeof(GameObject)) as GameObject) != null) { uiAtlas = SetAtlasInfo(go, path, mat); } else { go = new GameObject(ob.name); go.AddComponent<UIAtlas>(); uiAtlas = SetAtlasInfo(go, path, mat); #region 第三步:创建预设 CreatePrefab(go, ob.name, path); #endregion } AssetDatabase.SaveAssets(); EditorUtility.ClearProgressBar(); } }
private Material MakeMaterial() { Material newMaterial = new Material(Shader.Find("Standard")); newMaterial.SetFloat("_Mode", 1.0f); newMaterial.EnableKeyword("_ALPHATEST_ON"); newMaterial.EnableKeyword("_NORMALMAP"); newMaterial.SetTexture("_BumpMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_NORMALS.png")); //newMaterial.SetTexture("_SpecGlossMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_SPECULAR.png")); newMaterial.SetTexture("_ParallaxMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_DEPTH.png")); newMaterial.SetTexture("_OcclusionMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_OCCLUSION.png")); newMaterial.SetFloat("_Glossiness", 0); AssetDatabase.CreateAsset(newMaterial, "Assets/Sprites/Frogs/" + referencePath + "/" + referencePath.Replace(" ", "") + spriteName + ".mat"); return AssetDatabase.LoadAssetAtPath<Material>("Assets/Sprites/Frogs/" + referencePath + "/" + referencePath.Replace(" ", "") + spriteName + ".mat"); }
void updateSprite(SpriteRenderer spriteRenderer, AlphaMaskScript mask) { Texture2D a = mask.clipTexture; Texture2D b = spriteRenderer.sprite.texture; float w1 = (float)a.width; float h1 = (float)a.height; float w2 = (float)b.width; float h2 = (float)b.height; float xScale = h1 / h2; float yScale = w1 / w2; float adjustScale = xScale > yScale ? yScale : xScale; xScale = xScale / adjustScale / mask.scale; yScale = yScale / adjustScale / mask.scale; float xOffset = mask.xOffsetPixel / w2; float yOffset = mask.yOffsetPixel / h2; var mat = new Material(Shader.Find("Unlit/AlphaMask")); mat.name = mask.ToName(); mat.SetTexture("_ClipTex", mask.clipTexture); mat.SetFloat("_xScale", xScale); mat.SetFloat("_yScale", yScale); mat.SetFloat("_xOffset", xOffset); mat.SetFloat("_yOffset", yOffset); spriteRenderer.sharedMaterial = mat; Debug.Log(string.Format( "update alpha mask target={0}x{1} mask={2}x{3}", w1, h1, w2, h2 )); }
void Start () { spotLight = spotRotater.GetComponent<Light>(); pixels = new Color[resolution * resolution]; // Generate color map. Texture2D colorMapTexture = new Texture2D(32, 1, TextureFormat.ARGB32, false); colorMapTexture.wrapMode = TextureWrapMode.Clamp; colorMapDiagram.Fill(pixels, 32, 1); colorMapTexture.SetPixels(pixels); colorMapTexture.Apply(); terrainTexture = new Texture2D(resolution, resolution, TextureFormat.ARGB32, false); terrainTexture.wrapMode = TextureWrapMode.Repeat; terrainTexture.name = "Dynamic Terrain"; terrainMesh.Generate(resolution); // Fetch materials, set textures, and read initial settings. terrainMaterial = terrainMesh.materials[0]; waterMaterial = terrainMesh.materials[1]; waterMaterial.mainTexture = terrainMaterial.mainTexture = terrainTexture; terrainMaterial.SetTexture("_ColorMap", colorMapTexture); morphValue = heightFieldDiagram.GetInputValue("Morph"); octavesValue = heightFieldDiagram.GetInputValue("Octaves"); persistenceValue = heightFieldDiagram.GetInputValue("Persistence"); secondary = heightFieldDiagram.GetInputValue("Secondary"); }
static void Execute() { foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets)) { if (obj.name.Contains("@")) continue; if (!(obj is Texture2D)) continue; Texture2D tex = (Texture2D)obj; if (tex.name.ToLower().Contains("normal")) continue; if (!tex.name.ToLower().Contains(obj.name.ToLower())) continue; string texturePath = AssetRootPath(tex) + tex.name.ToLower() + ".mat"; if (System.IO.File.Exists(texturePath)) { System.IO.File.Delete(texturePath); } Debug.Log("Generating Material Asset : " + texturePath); string shader = "Transparent/Cutout/Diffuse"; Material material = new Material(Shader.Find(shader)); material.SetTexture("_MainTex", tex); AssetDatabase.CreateAsset(material, texturePath); //"Assets/Characters/male/Materials/"+tex.name.ToLower()+".mat"); //AssetDatabase.Refresh(); Debug.Log("Generate Material Asset Done."); } }
protected void SetGenericMaterialProperty(Material destination, string property_name, object value) { try{ ShaderUtil.ShaderPropertyType type = GetPropertyType(destination, property_name); switch(type) { case ShaderUtil.ShaderPropertyType.Color: destination.SetColor(property_name, value.UnityBridgeObjectToColor()); break; case ShaderUtil.ShaderPropertyType.Range: case ShaderUtil.ShaderPropertyType.Float: destination.SetFloat(property_name, value.UnityBridgeObjectToFloat()); break; case ShaderUtil.ShaderPropertyType.Vector: destination.SetVector(property_name, value.UnityBridgeObjectToVector()); break; case ShaderUtil.ShaderPropertyType.TexEnv: destination.SetTexture(property_name, TextureManager.Instance.ResolveMap( destination.name + "_" + property_name, value)); break; default: Debug.Log("Unknown shader type " + type.ToString()); break; } } catch(KeyNotFoundException e) { Debug.Log(e.Message); } }
// Use this for initialization protected virtual void Start() { mat = GetComponent<SpriteRenderer>().material; mat.SetTexture("_SecTex", BoardManager.instance.stars[/*UnityEngine.Random.Range(0, 5)*/5]); setInvisible(); checkLight(); }
static int SetTexture(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int), typeof(UnityEngine.Texture))) { UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); UnityEngine.Texture arg1 = (UnityEngine.Texture)ToLua.ToObject(L, 3); obj.SetTexture(arg0, arg1); return(0); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string), typeof(UnityEngine.Texture))) { UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); UnityEngine.Texture arg1 = (UnityEngine.Texture)ToLua.ToObject(L, 3); obj.SetTexture(arg0, arg1); return(0); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.SetTexture")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
// static public void Blit(RenderTexture src, RenderTexture des, Material mat, Rect rect, int pass = 0, bool clear = true) static public void Blit(RenderTexture src, RenderTexture des, Material mat, Rect rect, int pass, bool clear) { //rect must have normalized coords, ie 0 - 1 mat.SetTexture("_MainTex", src); RenderTexture oldRT = RenderTexture.active; Graphics.SetRenderTarget(des); if(clear) GL.Clear(true, true, Color.clear); GL.PushMatrix(); GL.LoadOrtho(); mat.SetPass(pass); GL.Begin(GL.QUADS); GL.TexCoord2(rect.x, rect.y); GL.Vertex3(rect.x, rect.y, 0.1f); GL.TexCoord2(rect.x+rect.width, rect.y); GL.Vertex3(rect.x+rect.width, rect.y, 0.1f); GL.TexCoord2(rect.x+rect.width, rect.y+rect.height); GL.Vertex3(rect.x+rect.width, rect.y+rect.height, 0.1f); GL.TexCoord2(rect.x, rect.y+rect.height); GL.Vertex3(rect.x, rect.y+rect.height, 0.1f); GL.End(); GL.PopMatrix(); RenderTexture.active = oldRT; }
void Start() { Application.targetFrameRate = 60; DontDestroyOnLoad(this.gameObject); Stage.Instantiate(5); Stage.inst.AddChild(new GRoot().displayObject); Stage.inst.camera.clearFlags = CameraClearFlags.Depth; Stage.inst.onKeyDown.Add(OnKeyDown); GRoot.inst.SetContentScaleFactor(1136, 640); UIPackage.AddPackage("UI/CustomMaterialDemo"); _mainView = UIPackage.CreateObject("Demo", "Main").asCom; _mainView.SetSize(GRoot.inst.width, GRoot.inst.height); _mainView.AddRelation(GRoot.inst, RelationType.Size); GRoot.inst.AddChild(_mainView); _btn0 = _mainView.GetChild("b0").asButton; _btn0.icon = "k0"; _time1 = 5; _mat0 = new Material(Shader.Find("Cooldown mask")); _mat0.SetFloat("_Progress", 0f); _mat0.SetTexture("_MaskTex", (Texture)Resources.Load("CooldownMask")); _btn0.GetChild("icon").asLoader.material = _mat0; _btn1 = _mainView.GetChild("b1").asButton; _btn1.icon = "k1"; _time2 = 10; _mat1 = new Material(Shader.Find("Cooldown mask")); _mat1.SetFloat("_Progress", 0f); _mat1.SetTexture("_MaskTex", (Texture)Resources.Load("CooldownMask")); _btn1.GetChild("icon").asLoader.material = _mat1; }
void CustomGraphicsBlit(RenderTexture source, RenderTexture dest, Material mat, int pass) { RenderTexture.active = dest; mat.SetTexture("_MainTex", source); GL.PushMatrix(); GL.LoadOrtho(); mat.SetPass (pass); GL.Begin (GL.QUADS); //This custom blit is needed as information about what corner verts relate to what frustum corners is needed //A index to the frustum corner is store in the z pos of vert GL.MultiTexCoord2(0, 0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 3.0f); // BL GL.MultiTexCoord2(0, 1.0f, 0.0f); GL.Vertex3(1.0f, 0.0f, 2.0f); // BR GL.MultiTexCoord2(0, 1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 1.0f); // TR GL.MultiTexCoord2(0, 0.0f, 1.0f); GL.Vertex3(0.0f, 1.0f, 0.0f); // TL GL.End(); GL.PopMatrix(); }
void Start () { thresDist = 80; gameObject.AddComponent<SphereCollider> (); transform.GetComponent<SphereCollider> ().radius = 1; gameObject.GetComponent<Collider> ().isTrigger = true; gameObject.AddComponent<MeshFilter> (); billMat = new Material (Shader.Find ("Unlit/Transparent")); billMat.SetTexture ("_MainTex", Resources.Load ("Textures/" + name.Substring (name.LastIndexOf ('B') + 1) + "Bill") as Texture); GetComponent<MeshFilter> ().mesh = BillBoardMesh (3, 3); GetComponent<MeshFilter> ().mesh.Optimize (); GetComponent<Renderer> ().material = billMat; scale = transform.localScale.x; objectCamDistance = (Camera.main.transform.position - transform.position).magnitude; thresCamDist = objectCamDistance - thresDist; if (objectCamDistance > thresDist) { //state = false; gameObject.GetComponent<Renderer> ().enabled = true; gameObject.GetComponent<Collider> ().enabled = true; } else if (objectCamDistance <= thresDist) { gameObject.GetComponent<Renderer> ().enabled = false; gameObject.GetComponent<Collider> ().enabled = false; } }
// Use this for initialization void Awake() { //Initalize render textures m_inputRenderTex = new RenderTexture(m_shadowSize, m_shadowSize, 0, RenderTextureFormat.ARGB32); m_middleRenderTex = new RenderTexture(m_shadowSize, 1, 0, RenderTextureFormat.ARGB32); //Initialize light material m_lightMaterial = new Material(Shader.Find("2DLighting/Deferred_Point_2")); m_lightMaterial.SetTexture("_DepthMap", m_middleRenderTex); m_lightMaterial.SetInt("_Penumbra", m_penumbra ? 1 : 0); m_lightMaterial.SetInt("_GradientFalloff", m_gradientFalloff ? 1 : 0); //Initialize phase one material phaseOneMaterial = new Material(Shader.Find("2DLighting/Deferred_Point_1")); phaseOneMaterial.SetFloat("_DistanceModifier", 0.001f); //Aquire camera component and initialize it m_camera = GetComponent<Camera>(); m_camera.enabled = true; m_camera.targetTexture = m_inputRenderTex; //Create culling mask from given occluder layers int occluders = 0; for (int i = 0; i < m_occluderLayers.Count; i++) { occluders = occluders | (1 << LayerMask.NameToLayer(m_occluderLayers[i])); } m_camera.cullingMask = occluders; //Assign mesh material m_meshRenderer.material = m_lightMaterial; }
public void CreateTextures() { if (texW == 0) texW = 1;//TODO rm if (texH == 0) texH = 1; if (texW == 0) throw new System.Exception("texW must be > 0"); if (texH == 0) throw new System.Exception("texH must be > 0"); texelSize = new Vector2(1f / texW, 1f / texH); maxTexelDistance = texelSize.magnitude; //Create textures texCur = new RenderTexture(texW, texH, 0, RenderTextureFormat.RFloat); texCur.enableRandomWrite = true; texCur.generateMips = false; texCur.Create(); texDest = new RenderTexture(texW, texH, 0, RenderTextureFormat.RFloat); texDest.enableRandomWrite = true; texDest.generateMips = false; texCur.filterMode = FilterMode.Point; texDest.Create(); //Clear textures Graphics.SetRenderTarget(texCur); GL.Clear(true, true, Color.white); Graphics.SetRenderTarget(texDest); GL.Clear(true, true, Color.white); Graphics.SetRenderTarget(null); //Instantiate material renderMaterial = new Material(visibilityOverlayMaterial); renderMaterial.SetTexture("_Mask", texCur); }
static public int SetTexture(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (matchType(l, argc, 2, typeof(int), typeof(UnityEngine.Texture))) { UnityEngine.Material self = (UnityEngine.Material)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); UnityEngine.Texture a2; checkType(l, 3, out a2); self.SetTexture(a1, a2); pushValue(l, true); return(1); } else if (matchType(l, argc, 2, typeof(string), typeof(UnityEngine.Texture))) { UnityEngine.Material self = (UnityEngine.Material)checkSelf(l); System.String a1; checkType(l, 2, out a1); UnityEngine.Texture a2; checkType(l, 3, out a2); self.SetTexture(a1, a2); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
// static public void Blit(RenderTexture src, RenderTexture des, Material mat, int pass = 0, bool clear = true) static public void Blit(RenderTexture src, RenderTexture des, Material mat, int pass, bool clear) { mat.SetTexture("_MainTex", src); RenderTexture oldRT = RenderTexture.active; Graphics.SetRenderTarget(des); if(clear) GL.Clear(true, true, Color.clear); GL.PushMatrix(); GL.LoadOrtho(); mat.SetPass(pass); GL.Begin(GL.QUADS); GL.TexCoord3(0.0f, 0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 0.1f); GL.TexCoord3(1.0f, 0.0f, 0.0f); GL.Vertex3(1.0f, 0.0f, 0.1f); GL.TexCoord3(1.0f, 1.0f, 0.0f); GL.Vertex3(1.0f, 1.0f, 0.1f); GL.TexCoord3(0.0f, 1.0f, 0.0f); GL.Vertex3(0.0f, 1.0f, 0.1f); GL.End(); GL.PopMatrix(); RenderTexture.active = oldRT; }
static void CustomGraphicsBlit(RenderTexture source, RenderTexture dest, Material fxMaterial, int passNr) { RenderTexture.active = dest; fxMaterial.SetTexture ("_MainTex", source); GL.PushMatrix (); GL.LoadOrtho (); fxMaterial.SetPass (passNr); GL.Begin (GL.QUADS); GL.MultiTexCoord2 (0, 0.0f, 0.0f); GL.Vertex3 (0.0f, 0.0f, 3.0f); // BL GL.MultiTexCoord2 (0, 1.0f, 0.0f); GL.Vertex3 (1.0f, 0.0f, 2.0f); // BR GL.MultiTexCoord2 (0, 1.0f, 1.0f); GL.Vertex3 (1.0f, 1.0f, 1.0f); // TR GL.MultiTexCoord2 (0, 0.0f, 1.0f); GL.Vertex3 (0.0f, 1.0f, 0.0f); // TL GL.End (); GL.PopMatrix (); }
protected override void UpdateMaterial() { Material material = new Material(base.GetCurrentSpriteDef().material); material.shader = Shader.Find(this.shaderName); material.SetTexture("_MaskTex", this.maskTexture); base.renderer.material = material; }
public static Material createMaterial(FacadeSkin skin) { Material mat = new Material(Shader.Find("Standard (Specular setup)")); Texture2D colortex = getTexture(skin.colorTexturePath); Texture2D normaltex = getTexture(skin.normalTexturePath); Texture2D speculartex = getTexture(skin.specularTexturePath); mat.SetTexture("_MainTex", colortex); mat.SetTexture("_BumpMap", normaltex); mat.SetFloat("_BumpScale", 1.0f); mat.SetFloat("_Glossiness", 0.1f); mat.SetTexture("_SpecGlossMap", speculartex); return mat; }
void OnEnable() { foreach(Transform child in transform) { //Search for child Loading Background to get the mesh renderer for the background texture if(child.name == "Loading Background") { m_MeshRenderer = child.GetComponent<MeshRenderer>(); } if(child.name == "Loading Percent") { m_LoadingText = child.GetComponent<TextMesh>(); } } if(m_MeshRenderer == null) { Debug.LogError("Missing a gameobject with the name \'Loading Background\' and a \'MeshRenderer\' component."); gameObject.SetActive(false); return; } if(m_LoadingText == null) { Debug.LogError("Missing a gameobject with the name \'Loading Text\' and a \'TextMesh\' component."); gameObject.SetActive(false); return; } Material material = new Material(m_MeshRenderer.sharedMaterial); material.SetTexture("_MainTex", m_TextureToDisplay); m_MeshRenderer.material = material; }
static void CustomGraphicsBlit(RenderTexture src, RenderTexture dst, Material mat, int pass) { RenderTexture.active = dst; mat.SetTexture("_MainTex", src); GL.PushMatrix(); GL.LoadOrtho(); mat.SetPass(pass); GL.Begin(GL.QUADS); GL.MultiTexCoord2(0, 0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 3.0f); // BL GL.MultiTexCoord2(0, 1.0f, 0.0f); GL.Vertex3(1.0f, 0.0f, 2.0f); // BR GL.MultiTexCoord2(0, 1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 1.0f); // TR GL.MultiTexCoord2(0, 0.0f, 1.0f); GL.Vertex3(0.0f, 1.0f, 0.0f); // TL GL.End(); GL.PopMatrix(); }
/// <summary> /// Copy Shader properties from source to destination material. /// </summary> /// <param name="source"></param> /// <returns></returns> public static void CopyMaterialProperties(Material source, Material destination) { MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source }); for (int i = 0; i < source_prop.Length; i++) { int property_ID = Shader.PropertyToID(source_prop[i].name); if (destination.HasProperty(property_ID)) { //Debug.Log(source_prop[i].name + " Type:" + ShaderUtil.GetPropertyType(source.shader, i)); switch (ShaderUtil.GetPropertyType(source.shader, i)) { case ShaderUtil.ShaderPropertyType.Color: destination.SetColor(property_ID, source.GetColor(property_ID)); break; case ShaderUtil.ShaderPropertyType.Float: destination.SetFloat(property_ID, source.GetFloat(property_ID)); break; case ShaderUtil.ShaderPropertyType.Range: destination.SetFloat(property_ID, source.GetFloat(property_ID)); break; case ShaderUtil.ShaderPropertyType.TexEnv: destination.SetTexture(property_ID, source.GetTexture(property_ID)); break; case ShaderUtil.ShaderPropertyType.Vector: destination.SetVector(property_ID, source.GetVector(property_ID)); break; } } } }
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); }
private void BuildMeshes(GameObject obj, List <int> LoD0Indices, Transform[] bones) { // Group Object GameObject meshesGroup = new GameObject("Meshes"); meshesGroup.transform.SetParent(obj.transform); // Submeshes for (int sm = 0; sm < LoD0Indices.Count; sm++) { int index = LoD0Indices[sm]; // Object GameObject submesh = new GameObject(); submesh.name = data.model.submeshes[index].name; submesh.transform.SetParent(meshesGroup.transform); // Mesh Mesh m = new Mesh(); m.SetVertices(data.model.submeshes[index].vertices); m.SetTriangles(data.model.submeshes[index].triangles, 0); m.SetNormals(data.model.submeshes[index].normals); m.SetTangents(data.model.submeshes[index].tangents); m.SetUVs(0, data.model.submeshes[index].uvs); SkinnedMeshRenderer meshRenderer = submesh.AddComponent <SkinnedMeshRenderer>(); MeshFilter meshFilter = submesh.AddComponent <MeshFilter>(); meshFilter.mesh = m; // weights m.boneWeights = data.model.submeshes[index].boneWeights; // bind poses Matrix4x4[] bindPoses = new Matrix4x4[bones.Length]; for (int b = 0; b < bindPoses.Length; b++) { bindPoses[b] = bones[b].worldToLocalMatrix * submesh.transform.localToWorldMatrix; } m.bindposes = bindPoses; meshRenderer.bones = bones; meshRenderer.sharedMesh = m; // Texture string folderPath = Path.GetDirectoryName(filePath); string textureName_ = data.model.textures[data.model.materials[data.model.submeshes[index].id].texture]; // *sweat in RP* textureName_ = PathHelper.GetFileName(textureName_); textureName_ = textureName_.Remove(textureName_.Length - 12); string diffuseTexturePath = folderPath + @"\" + textureName_ + "diffuse" + ".dds"; string emissiveTexturePath = folderPath + @"\" + textureName_ + "emissive" + ".dds"; string normalTexturePath = folderPath + @"\" + textureName_ + "normal" + ".dds"; string ormTexturePath = folderPath + @"\" + textureName_ + "orm" + ".dds"; // Material UnityEngine.Material mat = new UnityEngine.Material(defaultMaterial); if (File.Exists(diffuseTexturePath)) { Texture2D texture = DDS.ImportToTexture2D(diffuseTexturePath); mat.SetTexture("_MainTex", texture); } if (File.Exists(emissiveTexturePath)) { mat.EnableKeyword("_EMISSION"); Texture2D texture = DDS.ImportToTexture2D(emissiveTexturePath); mat.SetTexture("_EmissionMap", texture); } if (File.Exists(normalTexturePath)) { mat.EnableKeyword("_NORMALMAP"); Texture2D texture = DDS.ImportToTexture2D(normalTexturePath); mat.SetTexture("_BumpMap", texture); } if (File.Exists(ormTexturePath)) { mat.EnableKeyword("_METALLICGLOSSMAP"); Texture2D texture = DDS.ImportToTexture2D(ormTexturePath); //mat.SetTexture("_MetallicGlossMap", texture); mat.SetTexture("_ORM", texture); } mat.SetFloat("_Glossiness", 0.44f); mat.SetFloat("_GlossMapScale", 0.44f); meshRenderer.material = mat; } }
protected virtual UnityEngine.Material CreateMaterial(Material def, bool useVertexColors) { if (def.ContentsWithVC == null || def.ContentsWithoutVC == null) { Shader shader; // get the shader to use for this material try { if (def.PbrMetallicRoughness != null) { shader = _shaderCache[MaterialType.PbrMetallicRoughness]; } else if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_common") && def.CommonConstant != null) { shader = _shaderCache[MaterialType.CommonConstant]; } else { shader = _shaderCache[MaterialType.PbrMetallicRoughness]; } } catch (KeyNotFoundException e) { Debug.LogWarningFormat("No shader supplied for type of glTF material {0}, using Standard fallback", def.Name); shader = Shader.Find("Standard"); } shader.maximumLOD = MaximumLod; var material = new UnityEngine.Material(shader); if (def.AlphaMode == AlphaMode.MASK) { material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; material.SetFloat("_Cutoff", (float)def.AlphaCutoff); } else if (def.AlphaMode == AlphaMode.BLEND) { material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } else { material.SetOverrideTag("RenderType", "Opaque"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } if (def.DoubleSided) { material.SetInt("_Cull", (int)CullMode.Off); } else { material.SetInt("_Cull", (int)CullMode.Back); } if (def.PbrMetallicRoughness != null) { var pbr = def.PbrMetallicRoughness; material.SetColor("_Color", pbr.BaseColorFactor); if (pbr.BaseColorTexture != null) { var texture = pbr.BaseColorTexture.Index.Value; material.SetTexture("_MainTex", CreateTexture(texture)); } material.SetFloat("_Metallic", (float)pbr.MetallicFactor); if (pbr.MetallicRoughnessTexture != null) { var texture = pbr.MetallicRoughnessTexture.Index.Value; material.SetTexture("_MetallicRoughnessMap", CreateTexture(texture)); } material.SetFloat("_Roughness", (float)pbr.RoughnessFactor); } if (def.CommonConstant != null) { material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor); if (def.CommonConstant.LightmapTexture != null) { material.EnableKeyword("LIGHTMAP_ON"); var texture = def.CommonConstant.LightmapTexture.Index.Value; material.SetTexture("_LightMap", CreateTexture(texture)); material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord); } material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor); } if (def.NormalTexture != null) { var texture = def.NormalTexture.Index.Value; material.SetTexture("_BumpMap", CreateTexture(texture)); material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale); } if (def.OcclusionTexture != null) { var texture = def.OcclusionTexture.Index; material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); if (def.PbrMetallicRoughness != null && def.PbrMetallicRoughness.MetallicRoughnessTexture != null && def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id) { material.EnableKeyword("OCC_METAL_ROUGH_ON"); } else { material.SetTexture("_OcclusionMap", CreateTexture(texture.Value)); } } if (def.EmissiveTexture != null) { var texture = def.EmissiveTexture.Index.Value; material.EnableKeyword("EMISSION_MAP_ON"); material.SetTexture("_EmissionMap", CreateTexture(texture)); material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord); } material.SetColor("_EmissionColor", def.EmissiveFactor); def.ContentsWithoutVC = material; def.ContentsWithVC = new UnityEngine.Material(material); def.ContentsWithVC.EnableKeyword("VERTEX_COLOR_ON"); } return(def.GetContents(useVertexColors)); }
protected virtual MaterialCacheData CreateMaterial(GLTF.Schema.Material def, int materialIndex) { MaterialCacheData materialWrapper = null; if (materialIndex < 0 || _assetCache.MaterialCache[materialIndex] == null) { Shader shader; // get the shader to use for this material try { if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_pbrSpecularGlossiness")) { shader = _shaderCache[MaterialType.KHR_materials_pbrSpecularGlossiness]; } else if (def.PbrMetallicRoughness != null) { shader = _shaderCache[MaterialType.PbrMetallicRoughness]; } else if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_common") && def.CommonConstant != null) { shader = _shaderCache[MaterialType.CommonConstant]; } else { shader = _shaderCache[MaterialType.PbrMetallicRoughness]; } } catch (KeyNotFoundException) { Debug.LogWarningFormat("No shader supplied for type of glTF material {0}, using Standard fallback", def.Name); shader = Shader.Find("Standard"); } shader.maximumLOD = MaximumLod; var material = new UnityEngine.Material(shader); if (def.AlphaMode == AlphaMode.MASK) { material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; material.SetFloat("_Cutoff", (float)def.AlphaCutoff); } else if (def.AlphaMode == AlphaMode.BLEND) { material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } else { material.SetOverrideTag("RenderType", "Opaque"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } if (def.DoubleSided) { material.SetInt("_Cull", (int)CullMode.Off); } else { material.SetInt("_Cull", (int)CullMode.Back); } if (def.PbrMetallicRoughness != null) { var pbr = def.PbrMetallicRoughness; material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor()); if (pbr.BaseColorTexture != null) { var textureDef = pbr.BaseColorTexture.Index.Value; material.SetTexture("_MainTex", CreateTexture(textureDef)); ApplyTextureTransform(pbr.BaseColorTexture, material, "_MainTex"); } material.SetFloat("_Metallic", (float)pbr.MetallicFactor); if (pbr.MetallicRoughnessTexture != null) { var texture = pbr.MetallicRoughnessTexture.Index.Value; material.SetTexture("_MetallicRoughnessMap", CreateTexture(texture)); ApplyTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicRoughnessMap"); } material.SetFloat("_Roughness", (float)pbr.RoughnessFactor); } if (def.Extensions != null && def.Extensions.ContainsKey(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME)) { KHR_materials_pbrSpecularGlossinessExtension specGloss = def.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension; if (specGloss.DiffuseTexture != null) { var texture = specGloss.DiffuseTexture.Index.Value; material.SetTexture("_MainTex", CreateTexture(texture)); ApplyTextureTransform(specGloss.DiffuseTexture, material, "_MainTex"); } else { material.SetColor("_Color", specGloss.DiffuseFactor.ToUnityColor()); } if (specGloss.SpecularGlossinessTexture != null) { var texture = specGloss.SpecularGlossinessTexture.Index.Value; material.SetTexture("_SpecGlossMap", CreateTexture(texture)); material.EnableKeyword("_SPECGLOSSMAP"); ApplyTextureTransform(specGloss.SpecularGlossinessTexture, material, "_SpecGlossMap"); } else { material.SetVector("_SpecColor", specGloss.SpecularFactor.ToUnityVector3()); material.SetFloat("_Glossiness", (float)specGloss.GlossinessFactor); } } if (def.CommonConstant != null) { material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor.ToUnityColor()); if (def.CommonConstant.LightmapTexture != null) { material.EnableKeyword("LIGHTMAP_ON"); var texture = def.CommonConstant.LightmapTexture.Index.Value; material.SetTexture("_LightMap", CreateTexture(texture)); material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord); ApplyTextureTransform(def.CommonConstant.LightmapTexture, material, "_LightMap"); } material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor.ToUnityColor()); } if (def.NormalTexture != null) { var texture = def.NormalTexture.Index.Value; material.SetTexture("_BumpMap", CreateTexture(texture)); material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale); material.EnableKeyword("_NORMALMAP"); ApplyTextureTransform(def.NormalTexture, material, "_BumpMap"); } if (def.OcclusionTexture != null) { var texture = def.OcclusionTexture.Index; material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); if (def.PbrMetallicRoughness != null && def.PbrMetallicRoughness.MetallicRoughnessTexture != null && def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id) { material.EnableKeyword("OCC_METAL_ROUGH_ON"); } else { material.SetTexture("_OcclusionMap", CreateTexture(texture.Value)); ApplyTextureTransform(def.OcclusionTexture, material, "_OcclusionMap"); } } if (def.EmissiveTexture != null) { var texture = def.EmissiveTexture.Index.Value; material.EnableKeyword("EMISSION_MAP_ON"); material.EnableKeyword("_EMISSION"); material.SetTexture("_EmissionMap", CreateTexture(texture)); material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord); ApplyTextureTransform(def.EmissiveTexture, material, "_EmissionMap"); } material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor()); materialWrapper = new MaterialCacheData { UnityMaterial = material, UnityMaterialWithVertexColor = new UnityEngine.Material(material), GLTFMaterial = def }; materialWrapper.UnityMaterialWithVertexColor.EnableKeyword("VERTEX_COLOR_ON"); if (materialIndex > 0) { _assetCache.MaterialCache[materialIndex] = materialWrapper; } } return(materialIndex > 0 ? _assetCache.MaterialCache[materialIndex] : materialWrapper); }
protected virtual void CreateUnityMaterial(GLTF.Schema.Material def, int materialIndex) { Extension specularGlossinessExtension = null; bool isSpecularPBR = def.Extensions != null && def.Extensions.TryGetValue("KHR_materials_pbrSpecularGlossiness", out specularGlossinessExtension); Shader shader = isSpecularPBR ? Shader.Find("Standard (Specular setup)") : Shader.Find("Standard"); var material = new UnityEngine.Material(shader); material.hideFlags = HideFlags.DontUnloadUnusedAsset; // Avoid material to be deleted while being built material.name = def.Name; //Transparency if (def.AlphaMode == AlphaMode.MASK) { GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Cutout); material.SetFloat("_Mode", 1); material.SetFloat("_Cutoff", (float)def.AlphaCutoff); } else if (def.AlphaMode == AlphaMode.BLEND) { GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Fade); material.SetFloat("_Mode", 3); } if (def.NormalTexture != null) { var texture = def.NormalTexture.Index.Id; Texture2D normalTexture = getTexture(texture) as Texture2D; //Automatically set it to normal map TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(normalTexture)) as TextureImporter; im.textureType = TextureImporterType.NormalMap; im.SaveAndReimport(); material.SetTexture("_BumpMap", getTexture(texture)); material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale); } if (def.EmissiveTexture != null) { material.EnableKeyword("EMISSION_MAP_ON"); var texture = def.EmissiveTexture.Index.Id; material.SetTexture("_EmissionMap", getTexture(texture)); material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord); } // PBR channels if (specularGlossinessExtension != null) { KHR_materials_pbrSpecularGlossinessExtension pbr = (KHR_materials_pbrSpecularGlossinessExtension)specularGlossinessExtension; material.SetColor("_Color", pbr.DiffuseFactor.ToUnityColor().gamma); if (pbr.DiffuseTexture != null) { var texture = pbr.DiffuseTexture.Index.Id; material.SetTexture("_MainTex", getTexture(texture)); } if (pbr.SpecularGlossinessTexture != null) { var texture = pbr.SpecularGlossinessTexture.Index.Id; material.SetTexture("_SpecGlossMap", getTexture(texture)); material.SetFloat("_GlossMapScale", (float)pbr.GlossinessFactor); material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor); } else { material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor); } Vector3 specularVec3 = pbr.SpecularFactor.ToUnityVector3(); material.SetColor("_SpecColor", new Color(specularVec3.x, specularVec3.y, specularVec3.z, 1.0f)); if (def.OcclusionTexture != null) { var texture = def.OcclusionTexture.Index.Id; material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); material.SetTexture("_OcclusionMap", getTexture(texture)); } GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Specular); } else if (def.PbrMetallicRoughness != null) { var pbr = def.PbrMetallicRoughness; material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor().gamma); if (pbr.BaseColorTexture != null) { var texture = pbr.BaseColorTexture.Index.Id; material.SetTexture("_MainTex", getTexture(texture)); } material.SetFloat("_Metallic", (float)pbr.MetallicFactor); material.SetFloat("_Glossiness", 1.0f - (float)pbr.RoughnessFactor); if (pbr.MetallicRoughnessTexture != null) { var texture = pbr.MetallicRoughnessTexture.Index.Id; UnityEngine.Texture2D inputTexture = getTexture(texture) as Texture2D; List <Texture2D> splitTextures = splitMetalRoughTexture(inputTexture, def.OcclusionTexture != null, (float)pbr.MetallicFactor, (float)pbr.RoughnessFactor); material.SetTexture("_MetallicGlossMap", splitTextures[0]); if (def.OcclusionTexture != null) { material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); material.SetTexture("_OcclusionMap", splitTextures[1]); } } GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Metallic); } material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor().gamma); material = _assetManager.saveMaterial(material, materialIndex); _assetManager._parsedMaterials.Add(material); material.hideFlags = HideFlags.None; }
private UnityEngine.Material CreateMaterial(Material def, bool useVertexColors) { UnityEngine.Material material = new UnityEngine.Material(useVertexColors ? ColorMaterial : NoColorMaterial); material.shader.maximumLOD = MaximumLod; if (def.AlphaMode == AlphaMode.MASK) { material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; material.SetFloat("_Cutoff", (float)def.AlphaCutoff); } else if (def.AlphaMode == AlphaMode.BLEND) { material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } else { material.SetOverrideTag("RenderType", "Opaque"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } if (def.DoubleSided) { material.SetInt("_Cull", (int)CullMode.Off); } else { material.SetInt("_Cull", (int)CullMode.Back); } if (useVertexColors) { material.EnableKeyword("VERTEX_COLOR_ON"); } if (def.PbrMetallicRoughness != null) { var pbr = def.PbrMetallicRoughness; material.SetColor("_Color", pbr.BaseColorFactor); if (pbr.BaseColorTexture != null) { var texture = pbr.BaseColorTexture.Index.Value; material.SetTexture("_MainTex", _imageCache[texture.Source.Value]); } material.SetFloat("_Metallic", (float)pbr.MetallicFactor); if (pbr.MetallicRoughnessTexture != null) { var texture = pbr.MetallicRoughnessTexture.Index.Value; material.SetTexture("_MetallicRoughnessMap", _imageCache[texture.Source.Value]); } material.SetFloat("_Roughness", (float)pbr.RoughnessFactor); } if (def.CommonConstant != null) { material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor); if (def.CommonConstant.LightmapTexture != null) { material.EnableKeyword("LIGHTMAP_ON"); var texture = def.CommonConstant.LightmapTexture.Index.Value; material.SetTexture("_LightMap", _imageCache[texture.Source.Value]); material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord); } material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor); } if (def.NormalTexture != null) { var texture = def.NormalTexture.Index.Value; material.EnableKeyword("_NORMALMAP"); material.SetTexture("_BumpMap", _imageCache[texture.Source.Value]); material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale); } else { material.SetTexture("_BumpMap", null); material.DisableKeyword("_NORMALMAP"); } if (def.OcclusionTexture != null) { var texture = def.OcclusionTexture.Index; material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); if (def.PbrMetallicRoughness != null && def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id) { material.EnableKeyword("OCC_METAL_ROUGH_ON"); } else { material.SetTexture("_OcclusionMap", _imageCache[texture.Value.Source.Value]); } } if (def.EmissiveTexture != null) { var texture = def.EmissiveTexture.Index.Value; material.EnableKeyword("_EMISSION"); material.EnableKeyword("EMISSION_MAP_ON"); material.SetTexture("_EmissionMap", _imageCache[texture.Source.Value]); material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord); } material.SetColor("_EmissionColor", def.EmissiveFactor); return(material); }
public UnityMaterial GetUnityMaterial(string txdName) { if (loadedMaterial) { return(loadedMaterial); } using (new Timing("Creating Unity Material")) { loadedMaterial = Object.Instantiate(ResourcesHelper.BaseMaterial.Value); loadedMaterial.name = string.Format("{0}/{1}", txdName, TextureName); if (Color != Color.white) { loadedMaterial.SetColor(colorProp, Color); } if (Ambient < 1f) { loadedMaterial.SetFloat(ambientProp, Ambient); } if (Diffuse < 1f) { loadedMaterial.SetFloat(diffuseProp, Diffuse); } if (Specular < 1f) { loadedMaterial.SetFloat(specularProp, Specular); } var texture = (Texture)null; var mask = (Texture)null; if (Textured) { var txds = Loader.TxdCollection; if (txds.TextureNameOnly) { if (!string.IsNullOrEmpty(TextureName)) { texture = txds[TextureName]; } if (!string.IsNullOrEmpty(MaskName)) { mask = txds[MaskName]; } } else { if (!string.IsNullOrEmpty(TextureName)) { texture = txds[txdName, TextureName]; } if (!string.IsNullOrEmpty(MaskName)) { mask = txds[txdName, MaskName]; } } if (mask == Texture.GetMissingTexture()) { mask = texture; } loadedMaterial.SetTexture(mainTexProp, texture); loadedMaterial.SetTexture(maskTexProp, mask ?? texture); } return(loadedMaterial); } }
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); }
private static UnityEngine.Material Convert(RenderWareStream.Material src, TextureDictionary[] txds, MaterialFlags flags) { LoadedTexture diffuse; LoadedTexture mask = null; var overrideAlpha = (flags & MaterialFlags.OverrideAlpha) == MaterialFlags.OverrideAlpha; var vehicle = (flags & MaterialFlags.Vehicle) == MaterialFlags.Vehicle; if (!overrideAlpha && src.Colour.A != 255) { flags |= MaterialFlags.Alpha; } if (src.TextureCount > 0) { var tex = src.Textures[0]; diffuse = txds.GetDiffuse(tex.TextureName); if (src.TextureCount > 1) { Debug.LogFormat("Something has {0} textures!", src.TextureCount); } if (diffuse == null) { Debug.LogWarningFormat("Unable to find texture {0}", tex.TextureName); } if (!string.IsNullOrEmpty(tex.MaskName)) { mask = txds.GetAlpha(tex.MaskName) ?? diffuse; } else if (vehicle) { mask = diffuse; } if (!overrideAlpha && mask != null && mask.HasAlpha) { flags |= MaterialFlags.Alpha; } } else { diffuse = WhiteTex; } var shader = GetShader(flags); var mat = new UnityEngine.Material(shader); var clr = Types.Convert(src.Colour); if (vehicle) { var found = false; for (var i = 1; i < _sKeyColors.Length; ++i) { var key = _sKeyColors[i]; if (key.r != clr.r || key.g != clr.g || key.b != clr.b) { continue; } mat.SetInt(CarColorIndexId, i); found = true; break; } if (found) { mat.color = Color.white; } else { mat.color = clr; } } else { mat.color = clr; } if (diffuse != null) { mat.SetTexture(MainTexId, diffuse.Texture); } if (mask != null) { mat.SetTexture(MaskTexId, mask.Texture); } mat.SetFloat(MetallicId, src.Specular); mat.SetFloat(SmoothnessId, src.Smoothness); return(mat); }