CopyPropertiesFromMaterial() private méthode

private CopyPropertiesFromMaterial ( Material mat ) : void
mat Material
Résultat void
Exemple #1
0
		// Use this for initialization
		void Start () {
			currentOutsideMaterial = new Material (dissolveMaterial.shader);
			currentOutsideMaterial.CopyPropertiesFromMaterial(dissolveMaterial);

			currentGlassMaterial = new Material (glassMaterial.shader);
			currentGlassMaterial.CopyPropertiesFromMaterial(glassMaterial);

			foreach (Transform t in outside.GetComponentsInChildren<Transform>()) {

				var renderer = t.gameObject.GetComponent<SpriteRenderer>();
				if (renderer != null) {
					
					if (t.CompareTag(Tags.Glass)){
						renderer.material = currentGlassMaterial;
					} else {
						renderer.material = currentOutsideMaterial;
					}


				}

		
			}

		}
    public override void Explode()
    {
        //try to early out if we can't draw this (not sure if this also gets us out of Unity Indie)
        if (SystemInfo.supportsImageEffects)
        {
            if ((detailThreshold > detail) || !on) return;

            if (!_delayedExplosionStarted)
            {
                _explodeDelay = explodeDelayMin + (Random.value * (explodeDelayMax - explodeDelayMin));
            }
            if (_explodeDelay <= 0)
            {
                //incoming size is based on 1, so we multiply here
                _startSize = 0f;
                _maxSize = size * 10f;

                _material = new Material(Shader.Find("HeatDistort"));
                _heatwave = GameObject.CreatePrimitive(PrimitiveType.Plane);
                Destroy(_heatwave.GetComponent(typeof(MeshCollider)));

                if (!heatwaveMaterial) heatwaveMaterial = MyDetonator().heatwaveMaterial;
                _material.CopyPropertiesFromMaterial(heatwaveMaterial);
                _heatwave.renderer.material = _material;
                _heatwave.transform.parent = this.transform;

                _delayedExplosionStarted = false;
                _explodeDelay = 0f;
            }
            else
            {
                _delayedExplosionStarted = true;
            }
        }
    }
	static void CreateMaterial (GameObject go) {
		// Create a simple material asset
		if (go.GetComponent<Renderer>() != null)
		{
			Material material = new Material(go.GetComponent<Renderer>().sharedMaterial);
			material.CopyPropertiesFromMaterial(go.GetComponent<Renderer>().sharedMaterial);
			go.GetComponent<Renderer>().sharedMaterial = material;
			MaterialPropertyBlock block = new MaterialPropertyBlock();
			go.GetComponent<Renderer>().GetPropertyBlock(block);
			#if UNITY_EDITOR
			if(!Directory.Exists("Assets/Materials")) {
				AssetDatabase.CreateFolder("Assets", "Materials");
				AssetDatabase.Refresh();
			}

			string textureName = null;
			if (block.GetTexture(0).name != null) {
				textureName = block.GetTexture(0).name;
			} else {
				textureName = material.mainTexture.name;
			}
			AssetDatabase.CreateAsset(material, "Assets/Materials/" + textureName + ".mat");
			Debug.Log("Created material " + textureName + " for " + go.name);
			#endif
		}
	}
        public static void Create ()
        {
			if (Selection.activeGameObject != null) {
				GameObject o = Selection.activeGameObject;
				SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
				SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
				if (skin == null && spriteRenderer != null) {
					Sprite thisSprite = spriteRenderer.sprite;
					SpriteMesh spriteMesh = new SpriteMesh();
					spriteMesh.spriteRenderer = spriteRenderer;
					spriteMesh.CreateSpriteMesh();
					Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);

					// Copy the sprite material
					Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
					spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
					spriteMaterial.mainTexture = spriteTexture;
					string sortLayerName = spriteRenderer.sortingLayerName;
					int sortOrder = spriteRenderer.sortingOrder;
					DestroyImmediate(spriteRenderer);
					Skin2D skin2D = o.AddComponent<Skin2D>();
					skin2D.sprite = thisSprite;
					skin = o.GetComponent<SkinnedMeshRenderer>();
					MeshFilter filter = o.GetComponent<MeshFilter>();
					skin.material = spriteMaterial;

					// Save out the material from the sprite so we have a default material
					if(!Directory.Exists("Assets/Materials")) {
						AssetDatabase.CreateFolder("Assets", "Materials");
						AssetDatabase.Refresh();
					}
					AssetDatabase.CreateAsset(spriteMaterial, "Assets/Materials/" + spriteMaterial.mainTexture.name + ".mat");
					Debug.Log("Created material " + spriteMaterial.mainTexture.name + " for " + skin.gameObject.name);
					skin2D.referenceMaterial = spriteMaterial;
					skin.sortingLayerName = sortLayerName;
					skin.sortingOrder = sortOrder;

					// Create the mesh from the selection
					filter.mesh = (Mesh)Selection.activeObject;
					if (filter.sharedMesh != null && skin.sharedMesh == null) {
						skin.sharedMesh = filter.sharedMesh;
					}
					// Recalculate the bone weights for the new mesh
					skin2D.RecalculateBoneWeights();
				}
				else
				{
					o = new GameObject ("Skin2D");
					Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
					o.AddComponent<Skin2D> ();
				}
			}
			else
			{
				GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
			}
        }
Exemple #5
0
	void UpdateTextures() {
		attackAnimationTextures = loadTextures (charName + "Attack");
		moveAnimationTextures = loadTextures (charName + "Walk");

		var clonedMaterial = new Material (Shader.Find("Standard"));
		clonedMaterial.CopyPropertiesFromMaterial (characterMaterial);
		characterMaterial = clonedMaterial;
		transform.GetChild(1).GetComponent<MeshRenderer> ().material = clonedMaterial;
		characterMaterial.SetTexture ("_MainTex", attackAnimationTextures [0]);
	}
Exemple #6
0
	IEnumerator DelayedInit() {

		yield return new WaitForSeconds (0.2f) ;
		currMaterial = new Material (hairMaterial.shader);
		currMaterial.CopyPropertiesFromMaterial (hairMaterial);

		GetComponent<Anima2D.SpriteMeshInstance>().sharedMaterial = currMaterial;
		lastPosition = transform.position;
		isInitialized = true;
	
	}
    public override void OnInspectorGUI() {
        Skin2D skin = (Skin2D)target;

        DrawDefaultInspector();

        EditorGUILayout.Separator();

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Save as Prefab")) {
            skin.SaveAsPrefab();
        }

		EditorGUILayout.Separator();

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Recalculate Bone Weights")) {
            skin.RecalculateBoneWeights();
        }

		EditorGUILayout.Separator();

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Create Control Points")) {
            ControlPoint.CreateControlPoints(skin.GetComponent<SkinnedMeshRenderer>());
        }

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Reset Control Points")) {
            skin.ResetControlPointPositions();
        }

		EditorGUILayout.Separator();

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Generate Mesh Asset")) {
            #if UNITY_EDITOR
			// Check if the Meshes directory exists, if not, create it.
			if(!Directory.Exists("Assets/Meshes")) {
				AssetDatabase.CreateFolder("Assets", "Meshes");
				AssetDatabase.Refresh();
			}
			ScriptableObjectUtility.CreateAsset(skin.GetComponent<SkinnedMeshRenderer>().sharedMesh, "Meshes/" + skin.gameObject.name + ".Mesh");
			#endif
        }

        if (skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial != null && GUILayout.Button("Generate Material Asset")) {
            #if UNITY_EDITOR
			Material material = new Material(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
			material.CopyPropertiesFromMaterial(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
			skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial = material;
			if(!Directory.Exists("Assets/Materials")) {
				AssetDatabase.CreateFolder("Assets", "Materials");
				AssetDatabase.Refresh();
			}
			AssetDatabase.CreateAsset(material, "Assets/Materials/" + material.mainTexture.name + ".mat");
			Debug.Log("Created material " + material.mainTexture.name + " for " + skin.gameObject.name);
			#endif
        }
    }
 static public int CopyPropertiesFromMaterial(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         UnityEngine.Material a1;
         checkType(l, 2, out a1);
         self.CopyPropertiesFromMaterial(a1);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
        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);
        }
Exemple #10
0
 static public int CopyPropertiesFromMaterial(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         UnityEngine.Material a1;
         checkType(l, 2, out a1);
         self.CopyPropertiesFromMaterial(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static int CopyPropertiesFromMaterial(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Material obj  = (UnityEngine.Material)ToLua.CheckObject(L, 1, typeof(UnityEngine.Material));
         UnityEngine.Material arg0 = (UnityEngine.Material)ToLua.CheckUnityObject(L, 2, typeof(UnityEngine.Material));
         obj.CopyPropertiesFromMaterial(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Exemple #12
0
	// Use this for initialization
	void Start () {
		this.charName = characterNames [Random.Range (0, characterNames.Length)];

		attackAnimationTextures = loadTextures (charName + "Attack");
		moveAnimationTextures = loadTextures (charName + "Walk");

		var clonedMaterial = new Material (Shader.Find("Standard"));
		clonedMaterial.CopyPropertiesFromMaterial (characterMaterial);
		characterMaterial = clonedMaterial;
		transform.GetChild(1).GetComponent<MeshRenderer> ().material = clonedMaterial;
		characterMaterial.SetTexture ("_MainTex", attackAnimationTextures [0]);

		characters.Add (this);
		Spawn ();
	}
        public static void Create ()
        {
			if (Selection.activeGameObject != null) {
				GameObject o = Selection.activeGameObject;
				SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
				SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
				if (skin == null && spriteRenderer != null) {
					Sprite thisSprite = spriteRenderer.sprite;
					SpriteMesh spriteMesh = new SpriteMesh();
					spriteMesh.spriteRenderer = spriteRenderer;
					spriteMesh.CreateSpriteMesh();
					Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);
					Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
					spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
					spriteMaterial.mainTexture = spriteTexture;
					string sortLayerName = spriteRenderer.sortingLayerName;
					int sortOrder = spriteRenderer.sortingOrder;
					DestroyImmediate(spriteRenderer);
					Skin2D skin2D = o.AddComponent<Skin2D>();
					skin2D.sprite = thisSprite;
					skin = o.GetComponent<SkinnedMeshRenderer>();
					MeshFilter filter = o.GetComponent<MeshFilter>();
					skin.material = spriteMaterial;
					skin.sortingLayerName = sortLayerName;
					skin.sortingOrder = sortOrder;
					filter.mesh = (Mesh)Selection.activeObject;
					if (filter.sharedMesh != null && skin.sharedMesh == null) {
						skin.sharedMesh = filter.sharedMesh;
					}
					// Recalculate the bone weights for the new mesh
					skin2D.RecalculateBoneWeights();
				}
				else
				{
					o = new GameObject ("Skin2D");
					Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
					o.AddComponent<Skin2D> ();
				}
			}
			else
			{
				GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
			}
        }
Exemple #14
0
        void AssignNewMaterial(GameObject grass)
        {
            currMaterial = new Material (grassMaterial.shader);
            currMaterial.CopyPropertiesFromMaterial (grassMaterial);

            Color color = new Color ( Random.Range(minColor.r , maxColor.r) ,  Random.Range(minColor.g , maxColor.g) , Random.Range(minColor.b , maxColor.b) , Random.Range(minColor.a , maxColor.a) );

            currMaterial.color = color;
            //			MeshRenderer meshRenderer = grass.GetComponent<MeshRenderer>();
            //			meshRenderer.material = currMaterial;
            //			meshRenderer.materials[0] = currMaterial;
            currMaterial.SetColor ( "_GrassColor" , color);

            Anima2D.SpriteMeshInstance spriteMI = grass.GetComponent<Anima2D.SpriteMeshInstance>();
            spriteMI.sharedMaterial = currMaterial;

            grass.GetComponent<Grass>().myMaterial = currMaterial;
        }
	public Dictionary<string, UITextureInfo> textureDetails; // texture details loaded from the TexturePacker config file

	#endregion;


	#region MonoBehaviour Functions

	virtual protected void Awake()
	{
		_meshFilter = gameObject.AddComponent<MeshFilter>();
		_meshRenderer = gameObject.AddComponent<MeshRenderer>();
		
		// Duplicate the standard material so that we're not changing the
		// supplied one - it may be used by more than one UIToolkit object
		Material duplicateMaterial = new Material (material.shader);
		duplicateMaterial.CopyPropertiesFromMaterial(material);
		material = duplicateMaterial;
		
		_meshRenderer.renderer.material = material;
		_mesh = _meshFilter.mesh;

		// Move the object to the origin so the objects drawn will not be offset from the objects they are intended to represent.
		// Offset on z axis according to the specified layer
		transform.position = new Vector3(0, 0, layer);
		transform.rotation = Quaternion.identity;
	}
    public override void Explode()
    {
        //try to early out if we can't draw this (not sure if this also gets us out of Unity Indie)
        if (SystemInfo.supportsImageEffects)
        {
            if ((detailThreshold > detail) || !on) return;

            if (!_delayedExplosionStarted)
            {
                _explodeDelay = explodeDelayMin + (Random.value * (explodeDelayMax - explodeDelayMin));
            }
            if (_explodeDelay <= 0)
            {
                //incoming size is based on 1, so we multiply here
                _startSize = 0f;
                _maxSize = size * 10f;

                _material = new Material(Shader.Find("HeatDistort"));
                _heatwave = GameObject.CreatePrimitive(PrimitiveType.Plane);
                _heatwave.name = "Heatwave";
                _heatwave.transform.parent = this.transform;
                // billboard it so it always faces the camera - can't use regular lookat because the built in Unity plane is lame
                _heatwave.transform.rotation = Quaternion.FromToRotation(Vector3.up, Camera.main.transform.position - _heatwave.transform.position);
                Destroy(_heatwave.GetComponent(typeof(MeshCollider)));

                if (!heatwaveMaterial) heatwaveMaterial = MyDetonator().heatwaveMaterial;
                _material.CopyPropertiesFromMaterial(heatwaveMaterial);
                _heatwave.GetComponent<Renderer>().material = _material;
                _heatwave.transform.parent = this.transform;

                _delayedExplosionStarted = false;
                _explodeDelay = 0f;
            }
            else
            {
                _delayedExplosionStarted = true;
            }
        }
    }
Exemple #17
0
 public static IEnumerator GetAssetFromBundles( string bundlePath )
 {
     EditorWww www = EditorWww.Create( bundlePath );
     while( !www.Finished ){
         yield return null;
     }
     Object asset = www.GetAsset();
     if( asset ){
         string assetPath = Path.ChangeExtension( bundlePath, Defines.AssetExt.UnityAsset );
         if( asset is Material ){
             var old = asset as Material;
             Shader shader = Shader.Find( old.shader.name );
             if( shader ){
                 var newMaterial = new Material( shader );
                 newMaterial.CopyPropertiesFromMaterial( old );
                 AssetDatabase.CreateAsset( newMaterial, assetPath );
             }
             else{
                 EditorUtility.DisplayDialog( "错误", string.Format( "Shader:{0} 不存在于本地资源", old.shader.name ), "确定" );
             }
         }
         else if( asset is ScriptableObject ){
             Object scriptableObject = ScriptableObject.CreateInstance( asset.GetType() );
             EditorUtility.CopySerialized( asset, scriptableObject );
             AssetDatabase.CreateAsset( scriptableObject, assetPath );
         }
         else if( asset is GameObject ){
             Object[] all = www.AssetBundle.LoadAllAssets();//LoadAll() change in unity5
             Debug.Log( all.Length );
             Object.Instantiate( asset );
         }
         AssetDatabase.SaveAssets();
         AssetDatabase.Refresh();
     }
     else{
         Debug.Log( "Error: " + bundlePath );
     }
     www.Unload();
 }
Exemple #18
0
 /// <summary>
 /// Rebuild the draw call's material.
 /// </summary>
 public void RebuildMaterial()
 {
     NGUITools.DestroyImmediate(mMat);
     mMat = new Material(mSharedMat);
     mMat.hideFlags = HideFlags.DontSave;
     mMat.CopyPropertiesFromMaterial(mSharedMat);
     mMat.renderQueue = mSharedMat.renderQueue + mRenderQueue;
 }
Exemple #19
0
    public void loadTextureAndPrepareForUse()
    {
        Debug.Log("loadTextureAndPrepareForUse");

        if (_meshRendererPUBLIC == null)
        {
            Awake();
        }

        // Duplicate the standard material so that we're not changing the
        // supplied one - it may be used by more than one UIToolkit object
        Material duplicateMaterial = new Material (material.shader);
        duplicateMaterial.CopyPropertiesFromMaterial(material);
        material = duplicateMaterial;

        // load our texture, at 2x if necessary
        if( UI.isHD )
            texturePackerConfigName = texturePackerConfigName + UI.instance.hdExtension;

        var texture = (Texture)Resources.Load( texturePackerConfigName, typeof(Texture) );
        if( texture == null )
            Debug.Log( "UI texture is being autoloaded and it doesn't exist.  Cannot find texturePackerConfigName: " + texturePackerConfigName );
        material.mainTexture = texture;
        // assign the duplicate material to the mesh renderer
        if (_meshRendererPUBLIC != null)
            Debug.Log("_meshRendererPUBLIC != null");

        if (_meshRendererPUBLIC.renderer != null)
            Debug.Log("_meshRendererPUBLIC.renderer != null");

        if (_meshRendererPUBLIC.renderer.material != null)
            Debug.Log("_meshRendererPUBLIC.renderer.material != null");

        _meshRendererPUBLIC.renderer.material = material;

        // Cache our texture size
        var t = material.mainTexture;
        textureSize = new Vector2( t.width, t.height );

        // load up the config file
        textureDetails = loadTexturesFromTexturePackerJSON( texturePackerConfigName, textureSize );
    }
Exemple #20
0
	void Start () {
		// Copy the skybox material to a new instance so the original skybox material is not modified and saved by accident
		skyboxInstance = new Material(skybox.shader);
		skyboxInstance.CopyPropertiesFromMaterial(skybox);
	}
        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);
        }
        void updateMaterial(int archive, int record, int frame, Texture2D albedoMap, Texture2D normalMap, Texture2D metallicGlossMap)
        {
            CachedMaterial cmat;
            if (dfUnity.MaterialReader.GetCachedMaterial(archive, record, frame, out cmat))
            {
                Material newMat;
                if (useDeferredReflections)
                {
                    newMat = cmat.material;
                    //newMat = new Material(Shader.Find("Standard (Specular setup)"));
                    //newMat.CopyPropertiesFromMaterial(cmat.material);
                }
                else
                {
                    newMat = new Material(Shader.Find("Daggerfall/ReflectionsMod/FloorMaterialWithReflections"));
                    newMat.CopyPropertiesFromMaterial(cmat.material);
                    newMat.name = cmat.material.name;
                }

                if (texReflectionGround)
                {
                    newMat.SetTexture("_ReflectionGroundTex", texReflectionGround);
                }
                if (texReflectionLowerLevel)
                {
                    newMat.SetTexture("_ReflectionLowerLevelTex", texReflectionLowerLevel);
                }

                newMat.EnableKeyword("_METALLICGLOSSMAP");
                //newMat.EnableKeyword("_SPECGLOSSMAP");
                newMat.DisableKeyword("_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A");
                newMat.SetTexture("_MetallicGlossMap", metallicGlossMap);

                if (albedoMap != null)
                {
                    newMat.SetTexture("_MainTex", albedoMap);
                }

                if (normalMap != null)
                {
                    newMat.SetTexture("_BumpMap", normalMap);
                }

                cmat.material = newMat;
                dfUnity.MaterialReader.SetCachedMaterial(archive, record, frame, cmat);
            }
        }
        private IEnumerator UpdateTerrainsTransitionRing()
        {
            for (int i = 0; i < terrainTransitionRingArray.Length; i++)
            {
                if (terrainTransitionRingArray[i].terrainDesc.active)
                {

                    if (terrainTransitionRingArray[i].terrainDesc.updateData)
                    {
                        PlaceTerrainOfTransitionRing(i);
                        //UpdateTerrainData(terrainTransitionRingArray[i]);
                        terrainTransitionRingArray[i].terrainDesc.updateData = false;

                        yield return new WaitForEndOfFrame();
                    }
                    
                    if (terrainTransitionRingArray[i].terrainDesc.updateNature)
                    {
                        streamingWorld.UpdateTerrainNature(terrainTransitionRingArray[i].terrainDesc);
                        terrainTransitionRingArray[i].terrainDesc.updateNature = false;

                        MeshRenderer meshRenderer = terrainTransitionRingArray[i].terrainDesc.billboardBatchObject.GetComponent<MeshRenderer>();
                        Material[] rendererMaterials = meshRenderer.materials;
                        for (int m = 0; m < rendererMaterials.Length; m++)
                        {
                            Material newMaterial = new Material(Shader.Find("Daggerfall/BillboardBatchFaded"));
                            newMaterial.CopyPropertiesFromMaterial(rendererMaterials[m]);
                            newMaterial.SetInt("_TerrainDistance", streamingWorld.TerrainDistance);
                            newMaterial.SetFloat("_TerrainBlockSize", (MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale));
                            rendererMaterials[m] = newMaterial;
                        }
                        meshRenderer.materials = rendererMaterials;

                        //if (!terrainTransitionRingUpdateRunning) //(!transitionRingUpdateFinished)
                        yield return new WaitForEndOfFrame();
                    }

                    terrainTransitionRingArray[i].ready = true;
                }
            }

            UpdateNeighboursTransitionRing();

            terrainMaterial.SetInt("_TerrainDistance", streamingWorld.TerrainDistance); // after of transition ring update - restore far terrain rendering to streamingWorld.TerrainDistance

            terrainTransitionRingUpdateRunning = false;
            transitionRingAllBlocksReady = true;
        }
        void InjectMaterialPropertiesIndoor()
        {
            List<TextureRecord> listInjectedTextures = new List<TextureRecord>();

            // mages guild 4 floors debuging worldpos: 704,337
            IniParser.Model.IniData textureInjectionData = iniData;
            if (iniData != null)
            {
                foreach (IniParser.Model.SectionData section in iniData.Sections)
                {
                    int textureArchive = int.Parse(textureInjectionData[section.SectionName]["textureArchive"]);
                    int textureRecord = int.Parse(textureInjectionData[section.SectionName]["textureRecord"]);
                    int textureFrame = int.Parse(textureInjectionData[section.SectionName]["textureFrame"]);

                    TextureRecord texRecord = new TextureRecord();
                    texRecord.archive = textureArchive;
                    texRecord.record = textureRecord;
                    texRecord.frame = textureFrame;
                    texRecord.albedoMap = null;
                    texRecord.normalMap = null;
                    texRecord.useMetallicGlossMap = false;
                    texRecord.metallicGlossMap = null;
                    texRecord.reflectivity = 0.0f;
                    texRecord.smoothness = 0.0f;

                    Texture2D albedoTexture = null;
                    if (textureInjectionData[section.SectionName].ContainsKey("filenameAlbedoMap"))
                    {
                        string fileAlbedoMap = textureInjectionData[section.SectionName]["filenameAlbedoMap"];
                        albedoTexture = Resources.Load(fileAlbedoMap) as Texture2D;
                        texRecord.albedoMap = albedoTexture;
                    }

                    Texture2D normalTexture = null;
                    if (textureInjectionData[section.SectionName].ContainsKey("filenameNormalMap"))
                    {
                        string fileNormalMap = textureInjectionData[section.SectionName]["filenameNormalMap"];
                        normalTexture = Resources.Load(fileNormalMap) as Texture2D;
                        texRecord.normalMap = normalTexture;
                    }

                    bool useMetallicGlossMap = bool.Parse(textureInjectionData[section.SectionName]["useMetallicGlossMap"]);

                    texRecord.useMetallicGlossMap = useMetallicGlossMap;

                    if (useMetallicGlossMap)
                    {
                        string fileNameMetallicGlossMap = textureInjectionData[section.SectionName]["filenameMetallicGlossMap"];
                        Texture2D metallicGlossMapTexture = Resources.Load(fileNameMetallicGlossMap) as Texture2D;
                        updateMaterial(textureArchive, textureRecord, textureFrame, albedoTexture, normalTexture, metallicGlossMapTexture);
                        texRecord.metallicGlossMap = metallicGlossMapTexture;
                    }
                    else
                    {
                        float reflectivity = float.Parse(textureInjectionData[section.SectionName]["reflectivity"]);
                        float smoothness = float.Parse(textureInjectionData[section.SectionName]["smoothness"]);
                        updateMaterial(textureArchive, textureRecord, textureFrame, albedoTexture, normalTexture, reflectivity, smoothness);
                        texRecord.reflectivity = reflectivity;
                        texRecord.smoothness = smoothness;
                    }

                    listInjectedTextures.Add(texRecord);
                }
            }

            // force update to textures loaded in current interior/dungeon models
            Renderer[] renderers = null;
            if (GameManager.Instance.IsPlayerInsideBuilding)
            {
                renderers = gameObjectInterior.GetComponentsInChildren<Renderer>();
            }
            else if (GameManager.Instance.IsPlayerInsideDungeon || GameManager.Instance.IsPlayerInsidePalace)
            {
                renderers = gameObjectDungeon.GetComponentsInChildren<Renderer>();
            }
            if (renderers != null)
            {
                //Debug.Log(String.Format("renderers: {0}", renderers.Length));
                foreach (Renderer r in renderers)
                {
                    Material[] mats = r.sharedMaterials;
                    for (int i = 0; i < mats.Length; i++)
                    {
                        Material m = mats[i];
                        try
                        {
                            // name is in format TEXTURE.xxx [Index=y] - if atlas texture - different format then exception will be thrown - so everything is in try-catch block
                            string[] parts = m.name.Split('.');
                            parts = parts[1].Split(' ');
                            int archive = Convert.ToInt32(parts[0]);
                            string tmp = parts[1].Replace("[Index=", "").Replace("]", "");
                            //Debug.Log(String.Format("archive: {0}, record: {1}", parts[0], tmp));
                            int record = Convert.ToInt32(tmp);
                            int frame = 0;

                            if (listInjectedTextures.Exists(x => (x.archive == archive) && (x.record == record) && (x.frame == frame)))
                            {
                                TextureRecord? texRecord = listInjectedTextures.Find(x => (x.archive == archive) && (x.record == record) && (x.frame == frame));
                                if (texRecord.HasValue)
                                {
                                    CachedMaterial cmat;
                                    if (dfUnity.MaterialReader.GetCachedMaterial(archive, record, frame, out cmat))
                                    {
                                        if (!texRecord.Value.useMetallicGlossMap)
                                        {
                                            if (useDeferredReflections)
                                            {
                                                updateMaterial(archive, record, frame, texRecord.Value.albedoMap, texRecord.Value.normalMap, texRecord.Value.reflectivity, texRecord.Value.smoothness);
                                            }
                                            else
                                            {
                                                Material newMat = new Material(Shader.Find("Daggerfall/ReflectionsMod/FloorMaterialWithReflections"));
                                                newMat.CopyPropertiesFromMaterial(cmat.material);
                                                newMat.name = cmat.material.name;
                                                if (texReflectionGround)
                                                {
                                                    newMat.SetTexture("_ReflectionGroundTex", texReflectionGround);
                                                }
                                                if (texReflectionLowerLevel)
                                                {
                                                    newMat.SetTexture("_ReflectionLowerLevelTex", texReflectionLowerLevel);
                                                }
                                                newMat.SetFloat("_Metallic", texRecord.Value.reflectivity);
                                                newMat.SetFloat("_Smoothness", texRecord.Value.smoothness);

                                                if (texRecord.Value.albedoMap != null)
                                                {
                                                    newMat.SetTexture("_MainTex", texRecord.Value.albedoMap);
                                                }

                                                if (texRecord.Value.normalMap != null)
                                                {
                                                    newMat.SetTexture("_BumpMap", texRecord.Value.normalMap);
                                                }

                                                m = newMat;
                                            }
                                        }
                                        else
                                        {
                                            if (useDeferredReflections)
                                            {
                                                updateMaterial(archive, record, frame, texRecord.Value.albedoMap, texRecord.Value.normalMap, texRecord.Value.metallicGlossMap);
                                            }
                                            else
                                            {
                                                Material newMat = new Material(Shader.Find("Daggerfall/ReflectionsMod/FloorMaterialWithReflections"));
                                                newMat.CopyPropertiesFromMaterial(cmat.material);
                                                newMat.name = cmat.material.name;
                                                if (texReflectionGround)
                                                {
                                                    newMat.SetTexture("_ReflectionGroundTex", texReflectionGround);
                                                }
                                                if (texReflectionLowerLevel)
                                                {
                                                    newMat.SetTexture("_ReflectionLowerLevelTex", texReflectionLowerLevel);
                                                }
                                                newMat.EnableKeyword("USE_METALLICGLOSSMAP");
                                                newMat.SetTexture("_MetallicGlossMap", texRecord.Value.metallicGlossMap);

                                                if (texRecord.Value.albedoMap != null)
                                                {
                                                    newMat.SetTexture("_MainTex", texRecord.Value.albedoMap);
                                                }

                                                if (texRecord.Value.normalMap != null)
                                                {
                                                    newMat.SetTexture("_BumpMap", texRecord.Value.normalMap);
                                                }

                                                m = newMat;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        mats[i] = m;
                    }
                    r.sharedMaterials = mats;
                }
            }
        }
        void updateMaterial(int archive, int record, int frame, Texture2D albedoMap, Texture2D normalMap, float reflectivity, float smoothness)
        {
            CachedMaterial cmat;
            if (dfUnity.MaterialReader.GetCachedMaterial(archive, record, frame, out cmat))
            {
                Material newMat;
                if (useDeferredReflections)
                {
                    newMat = cmat.material;
                    //newMat = new Material(Shader.Find("Standard (Specular setup)"));
                    //newMat.CopyPropertiesFromMaterial(cmat.material);
                }
                else
                {
                    newMat = new Material(Shader.Find("Daggerfall/ReflectionsMod/FloorMaterialWithReflections"));
                    newMat.CopyPropertiesFromMaterial(cmat.material);
                    newMat.name = cmat.material.name;
                }

                if (texReflectionGround)
                {
                    newMat.SetTexture("_ReflectionGroundTex", texReflectionGround);
                }
                if (texReflectionLowerLevel)
                {
                    newMat.SetTexture("_ReflectionLowerLevelTex", texReflectionLowerLevel);
                }
                newMat.SetFloat("_Metallic", reflectivity);
                //newMat.SetColor("_SpecColor", new Color(reflectivity, reflectivity, reflectivity));
                newMat.SetFloat("_Glossiness", smoothness);

                if (albedoMap != null)
                {
                    newMat.SetTexture("_MainTex", albedoMap);
                }

                if (normalMap != null)
                {
                    newMat.SetTexture("_BumpMap", normalMap);
                }

                cmat.material = newMat;
                dfUnity.MaterialReader.SetCachedMaterial(archive, record, frame, cmat);
            }
        }
Exemple #26
0
    void Start()
    {
        // Calculate last things
        numOfPoints = resolution + 2;
        splittingIndex = Random.Range((int)((numOfPoints/2) - (numOfPoints/4)), (int)((numOfPoints/2) + (numOfPoints/4)));
        splittingDistance += Vector3.Distance(nodeA.transform.position, nodeB.transform.position);

        // Setup line renderer
        lineA = nodeA.AddComponent<LineRenderer>();
        lineB = nodeB.AddComponent<LineRenderer>();
        lineA.SetVertexCount(splittingIndex + 1);
        lineB.SetVertexCount(numOfPoints - splittingIndex);

        // Make copy of material and tile it according to length of vine (Approx.)
        Material mat = new Material(Shader.Find("Unlit/Transparent"));
        mat.CopyPropertiesFromMaterial(lineMaterials[(int)Random.Range(0, lineMaterials.Length)]);
        mat.mainTextureScale = new Vector2(Vector3.Distance(nodeA.transform.position, nodeB.transform.position) * 3, 1);
        lineA.material = mat;
        lineB.material = mat;

        // Instantiate Rigid points between the nodes
        rigidPoints = new GameObject[numOfPoints];	// resolution + node A & B
        rigidPoints[0] = nodeA;
        rigidPoints[numOfPoints-1] = nodeB;
        for(int i = 1; i < numOfPoints-1; i++) {
            // Instantiate Object and its position
            rigidPoints[i] = new GameObject();
            rigidPoints[i].name = "RigidPoint_"+i;
            rigidPoints[i].transform.position = Vector3.Lerp(nodeA.transform.position, nodeB.transform.position, (1f / (numOfPoints-1)) * i);
            rigidPoints[i].transform.parent = transform;

            // Add components
            rigidPoints[i].AddComponent<Rigidbody>();
            rigidPoints[i].AddComponent<SpringJoint>();
            rigidPoints[i].GetComponent<SpringJoint>().connectedBody = rigidPoints[i-1].GetComponent<Rigidbody>();
            rigidPoints[i].GetComponent<SpringJoint>().spring = 512f;
            rigidPoints[i].GetComponent<SpringJoint>().damper = 1f;
            rigidPoints[i].GetComponent<SpringJoint>().minDistance = 0.00125f;
            rigidPoints[i].GetComponent<SpringJoint>().maxDistance = 0.005f;

        }
        nodeA.GetComponent<FixedJoint>().connectedBody = rigidPoints[1].GetComponent<Rigidbody>();
        nodeB.GetComponent<FixedJoint>().connectedBody = rigidPoints[numOfPoints-2].GetComponent<Rigidbody>();

        if(transformA)
            nodeA.transform.parent = transformA;
        if(transformB)
            nodeB.transform.parent = transformB;

        isSplit = false;
    }
 public static Material CloneMaterial(Material original)
 {
     if(original == null) return null;
     Material material = new Material(original.shader);
     material.CopyPropertiesFromMaterial(original);
     return material;
 }
Exemple #28
0
    /// <summary>
    /// Rebuild the draw call's material.
    /// </summary>
    public void RebuildMaterial()
    {
        NGUITools.DestroyImmediate(mMat);
        mMat = new Material(mSharedMat);
        mMat.hideFlags = HideFlags.DontSave;
        mMat.CopyPropertiesFromMaterial(mSharedMat);

        // Automatically replace "GUI/Text Shader" with "Unlit/Text"
        if (mMat.shader != null && mMat.shader.name == "GUI/Text Shader")
        {
            Shader shader = Shader.Find("Unlit/Text");
            if (shader != null) mMat.shader = shader;
        }
        mMat.renderQueue = mSharedMat.renderQueue + mRenderQueue;
    }
Exemple #29
0
using UnityEngine;
using System.Collections;
	/// <summary>
	/// Create an appropriate material for the draw call.
	/// </summary>

	void CreateMaterial ()
	{
		const string alpha = " (AlphaClip)";
		const string soft = " (SoftClip)";
		string shaderName = (mShader != null) ? mShader.name :
			((mMaterial != null) ? mMaterial.shader.name : "Unlit/Transparent Colored");

		// Figure out the normal shader's name
		shaderName = shaderName.Replace("GUI/Text Shader", "Unlit/Text");
		shaderName = shaderName.Replace(alpha, "");
		shaderName = shaderName.Replace(soft, "");

		// Try to find the new shader
		Shader shader;

		if (mClipping == Clipping.SoftClip)
		{
			shader = Shader.Find(shaderName + soft);
		}
		else if (mClipping == Clipping.AlphaClip)
		{
			shader = Shader.Find(shaderName + alpha);
		}
		else // No clipping
		{
			shader = (mShader != null) ? mShader : Shader.Find(shaderName);
		}

		if (mMaterial != null)
		{
			mDynamicMat = new Material(mMaterial);
			mDynamicMat.hideFlags = HideFlags.DontSave;
			mDynamicMat.CopyPropertiesFromMaterial(mMaterial);

			// If there is a valid shader, assign it to the custom material
			if (shader != null)
			{
				mDynamicMat.shader = shader;
			}
			else if (mClipping != Clipping.None)
			{
				Debug.LogError(shaderName + " doesn't have a clipped shader version for " + mClipping);
				mClipping = Clipping.None;
			}
		}
		else
		{
			mDynamicMat = new Material(shader);
			mDynamicMat.hideFlags = HideFlags.DontSave;
		}
	}
Exemple #31
0
 void GetMats()
 {
     Transform par = transform.parent;
     if (!par)
         return;
     Renderer[] rds = par.GetComponentsInChildren<Renderer>();
     mats = new List<Material>();
     foreach (Renderer rd in rds)
     {
         if (rd is ParticleSystemRenderer || rd is ParticleRenderer)
             continue;
         foreach (Material mat in rd.materials)
         {
             if (!IsThisMatSupportMatFx(mat))
                 continue;
             mats.Add(mat);
         }
     }
     oriMaterials = new Material[mats.Count];
     for (int i = 0; i < oriMaterials.Length; i++)
     {
         Material oriMat = new Material(mats[i]);
         oriMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
         oriMat.CopyPropertiesFromMaterial(mats[i]);
         oriMaterials[i] = oriMat;
     }
 }
	public static void ConfigureNewMaterialToMatchOld(Material newMat, Material original){
		if (original == null){
			Debug.LogWarning("Original material is null, could not copy properties to " + newMat + ". Setting shader to " + newMat.shader);
			return;
		}
		newMat.shader = original.shader;					
		newMat.CopyPropertiesFromMaterial(original);
		ShaderTextureProperty[] texPropertyNames = MB3_TextureCombiner.shaderTexPropertyNames;
		for (int j = 0; j < texPropertyNames.Length; j++){
			Vector2 scale = Vector2.one;
			Vector2 offset = Vector2.zero;
			if (newMat.HasProperty(texPropertyNames[j].name)){
				newMat.SetTextureOffset(texPropertyNames[j].name,offset);
				newMat.SetTextureScale(texPropertyNames[j].name,scale);
			}
		}
	}
Exemple #33
0
    public static void Create()
    {
        if (Selection.activeGameObject != null) {
                GameObject o = Selection.activeGameObject;
                SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
                SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
                if (skin == null && spriteRenderer != null) {
                    Sprite thisSprite = spriteRenderer.sprite;
                    SpriteMesh.CreateSpriteMeshAsset(spriteRenderer.transform, thisSprite);
                    Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);
                    Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
                    spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
                    spriteMaterial.mainTexture = spriteTexture;
                    DestroyImmediate(spriteRenderer);
                    Skin2D skin2D = o.AddComponent<Skin2D>();
                    skin2D.sprite = thisSprite;
                    skin = o.GetComponent<SkinnedMeshRenderer>();
                    MeshFilter filter = o.GetComponent<MeshFilter>();
                    skin.material = spriteMaterial;
                    filter.mesh = (Mesh)Selection.activeObject;
                    if (filter.sharedMesh != null && skin.sharedMesh == null) {
                        skin.sharedMesh = filter.sharedMesh;
                    }
                    Skeleton skeleton = o.transform.root.GetComponent<Skeleton>();
                    if (skeleton != null)
                    {
                        // Generate the mesh and calculate the weights if the root transform has a skeleton
                        skeleton.CalculateWeights(true);
                        // Debug.Log("Calculated weights for " + o.name);

                        // Try to initialize the parent bone to this skin
                        Bone bone = o.transform.parent.GetComponent<Bone>();
                        if (bone != null)
                        {
                            Mesh m = skin.sharedMesh.Clone();
                            List<BoneWeight> weights = m.boneWeights.ToList();

                            for (int i = 0; i < m.vertices.Length; i++) {
                                BoneWeight bw = weights[i];
                                bw = bw.SetWeight(bone.index, 1);
                                weights[i] = bw.Clone();
                            }

                            skin.sharedMesh.boneWeights = weights.ToArray();
                            EditorUtility.SetDirty(skin.gameObject);
                            if (PrefabUtility.GetPrefabType(skin.gameObject) != PrefabType.None) {
                                AssetDatabase.SaveAssets();
                            }
                        }
                    }
                }
                else
                {
                    o = new GameObject ("Skin2D");
                    Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                    o.AddComponent<Skin2D> ();
                }
            }
            else
            {
                GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
            }
    }
Exemple #34
0
        /* ********************************************************* */
        //! Change Texture in Material-table

        /*!
         * @param	tableMaterial
         *      Material-Table
         * @param	indexCellMap
         *      index of CellMap
         * @param	texture
         *      Texture
         * @param	flagMaterialNew
         *      Whether make a new material or overwrite<br>
         *      true == Create new material<br>
         *      false == Overwrite exist material
         * @retval	Return-Value
         *      true == Success<br>
         *      false == Failure(Error)
         *
         * Change materials' texture corresponding to specified CellMap in Material-Table.<br>
         * When "flagMaterialNew" is set true, new materials are created.<br>
         * When false, materials are overwritten.
         */
        public static bool TextureSet(UnityEngine.Material[] tableMaterial, int indexCellMap, Texture2D texture, bool flagMaterialNew)
        {
            int indexTop = IndexGetTable(indexCellMap, Library_SpriteStudio6.KindOperationBlendEffect.INITIATOR, Library_SpriteStudio6.KindMasking.THROUGH);

            if (0 > indexTop)
            {
                return(false);
            }

            UnityEngine.Material material;
            int index;

            for (int i = (int)Library_SpriteStudio6.KindMasking.THROUGH; i < (int)Library_SpriteStudio6.KindMasking.TERMINATOR; i++)
            {
                for (int j = (int)Library_SpriteStudio6.KindOperationBlendEffect.INITIATOR; j < (int)Library_SpriteStudio6.KindOperationBlendEffect.TERMINATOR; j++)
                {
                    index  = IndexGetTable(0, (Library_SpriteStudio6.KindOperationBlendEffect)j, (Library_SpriteStudio6.KindMasking)i);
                    index += indexTop;

                    material = tableMaterial[index];
                    if (true == flagMaterialNew)
                    {                           /* Create Material */
#if false
                        /* MEMO: Before Ver.1.0.26 */
                        if (null == material)
                        {
                            material = new UnityEngine.Material(Library_SpriteStudio6.Data.Shader.ShaderGetEffect((Library_SpriteStudio6.KindOperationBlendEffect)j,
                                                                                                                  (Library_SpriteStudio6.KindMasking)i
                                                                                                                  )
                                                                );
                        }
                        else
                        {
                            material = new UnityEngine.Material(material);
                        }
#else
                        /* MEMO: After Ver.1.0.26 */
                        if (null == material)
                        {
                            material = Library_SpriteStudio6.Data.Shader.MaterialCreateEffect((Library_SpriteStudio6.KindOperationBlendEffect)j,
                                                                                              (Library_SpriteStudio6.KindMasking)i
                                                                                              );
                        }
                        else
                        {
                            UnityEngine.Material materialNew = new UnityEngine.Material(material);
                            if (null != materialNew)
                            {
                                materialNew.CopyPropertiesFromMaterial(material);
                            }
                            material = materialNew;
                        }
#endif
                    }
                    else
                    {                           /* Overwrite Material */
#if false
                        /* MEMO: Before Ver.1.0.26 */
                        if (null == material)
                        {
                            material = new UnityEngine.Material(Library_SpriteStudio6.Data.Shader.ShaderGetEffect((Library_SpriteStudio6.KindOperationBlendEffect)j,
                                                                                                                  (Library_SpriteStudio6.KindMasking)i
                                                                                                                  )
                                                                );
                        }
#else
                        /* MEMO: After Ver.1.0.26 */
                        if (null == material)
                        {
                            material = Library_SpriteStudio6.Data.Shader.MaterialCreateEffect((Library_SpriteStudio6.KindOperationBlendEffect)j,
                                                                                              (Library_SpriteStudio6.KindMasking)i
                                                                                              );
                        }
#endif
                    }
                    material.mainTexture = texture;
                    tableMaterial[index] = material;
                }
            }

            return(true);
        }
Exemple #35
0
    /// <summary>
    /// Update the renderer's materials.
    /// </summary>
    void UpdateMaterials()
    {
        bool useClipping = (mClipping != Clipping.None);

        // Create a temporary material
        if (mMat == null)
        {
            mMat = new Material(mSharedMat);
            mMat.hideFlags = HideFlags.DontSave;
            mMat.CopyPropertiesFromMaterial(mSharedMat);
            mMat.renderQueue = mSharedMat.renderQueue + mDepth;
        }

        // If clipping should be used, we need to find a replacement shader
        if (useClipping && mClipping != Clipping.None)
        {
            Shader shader = null;
            const string alpha	= " (AlphaClip)";
            const string soft	= " (SoftClip)";

            // Figure out the normal shader's name
            string shaderName = mSharedMat.shader.name;
            shaderName = shaderName.Replace(alpha, "");
            shaderName = shaderName.Replace(soft, "");

            // Try to find the new shader
            if (mClipping == Clipping.HardClip ||
                mClipping == Clipping.AlphaClip) shader = Shader.Find(shaderName + alpha);
            else if (mClipping == Clipping.SoftClip) shader = Shader.Find(shaderName + soft);

            // If there is a valid shader, assign it to the custom material
            if (shader != null)
            {
                mMat.shader = shader;
            }
            else
            {
                mClipping = Clipping.None;
                Debug.LogError(shaderName + " doesn't have a clipped shader version for " + mClipping);
            }
        }

        // If depth pass should be used, create the depth material
        if (mUseDepth)
        {
            if (mDepthMat == null)
            {
                Shader shader = Shader.Find("Unlit/Depth Cutout");
                mDepthMat = new Material(shader);
                mDepthMat.hideFlags = HideFlags.DontSave;
            }
            mDepthMat.mainTexture = mSharedMat.mainTexture;
        }
        else if (mDepthMat != null)
        {
            NGUITools.Destroy(mDepthMat);
            mDepthMat = null;
        }

        if (mDepthMat != null)
        {
            // If we're already using this material, do nothing
            if (mRen.sharedMaterials != null && mRen.sharedMaterials.Length == 2 && mRen.sharedMaterials[1] == mMat) return;

            // Set the double material
            mRen.sharedMaterials = new Material[] { mDepthMat, mMat };
        }
        else if (mRen.sharedMaterial != mMat)
        {
            mRen.sharedMaterials = new Material[] { mMat };
        }
    }
        void updateMaterial(int archive, int record, int frame, Texture2D albedoMap, Texture2D normalMap, Texture2D metallicGlossMap)
        {
            CachedMaterial cmat;
            if (dfUnity.MaterialReader.GetCachedMaterial(archive, record, frame, out cmat))
            {
                Material newMat = new Material(Shader.Find("Daggerfall/FloorMaterialWithReflections"));
                newMat.CopyPropertiesFromMaterial(cmat.material);
                newMat.name = cmat.material.name;
                Texture tex = GameObject.Find("ReflectionPlaneBottom").GetComponent<MirrorReflection>().m_ReflectionTexture;
                if (tex)
                {
                    newMat.SetTexture("_ReflectionGroundTex", tex);
                }
                tex = GameObject.Find("ReflectionPlaneSeaLevel").GetComponent<MirrorReflection>().m_ReflectionTexture;
                if (tex)
                {
                    newMat.SetTexture("_ReflectionLowerLevelTex", tex);
                }
                newMat.EnableKeyword("USE_METALLICGLOSSMAP");
                newMat.SetTexture("_MetallicGlossMap", metallicGlossMap);

                if (albedoMap != null)
                {
                    newMat.SetTexture("_MainTex", albedoMap);
                }

                if (normalMap != null)
                {
                    newMat.SetTexture("_BumpMap", normalMap);
                }

                cmat.material = newMat;
                dfUnity.MaterialReader.SetCachedMaterial(archive, record, frame, cmat);
            }
        }