SetTextureOffset() public method

Sets the placement offset of texture propertyName.

public SetTextureOffset ( string propertyName, Vector2 offset ) : void
propertyName string
offset Vector2
return void
    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;
    }
Ejemplo n.º 2
0
        //internal void Animate(Material material, float time) {
        //    Vector2 textureOffset = new Vector2(xScrollSpeed * time % 1, yScrollSpeed * time % 1);
        //    material.SetTextureOffset(UnityConstants.MainDiffuseTexture, textureOffset);
        //    material.SetTextureOffset(UnityConstants.NormalMapTexture, textureOffset);
        //}

        internal void Animate(Material material, float deltaTime) {
            _x = (_x + (xScrollSpeed * deltaTime)) % 1;
            _y = (_y + (yScrollSpeed * deltaTime)) % 1;
            Vector2 textureOffset = new Vector2(_x, _y);
            material.SetTextureOffset(UnityConstants.MainDiffuseTexture, textureOffset);
            material.SetTextureOffset(UnityConstants.NormalMapTexture, textureOffset);
        }
        static void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            Vector2 offset = Vector2.zero;
            Vector2 scale  = Vector2.one;

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord != 0)
                {
                    Debug.LogError("Multiple UV sets are not supported!");
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    offset.x = tt.offset[0];
                    offset.y = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    scale.x = tt.scale[0];
                    scale.y = tt.scale[1];
                    material.SetTextureScale(propertyId, scale);
                }
                if (tt.rotation != 0)
                {
                    cos = Mathf.Cos(tt.rotation);
                    sin = Mathf.Sin(tt.rotation);
                    material.SetVector(StandardShaderHelper.mainTexRotatePropId, new Vector4(cos, sin, -sin, cos));
                    material.EnableKeyword(StandardShaderHelper.KW_UV_ROTATION);
                    offset.x += scale.y * sin;
                }
                offset.y -= scale.y * cos;
                material.SetTextureOffset(propertyId, offset);
            }

            if (flipY)
            {
                offset.y = 1 - offset.y;
                scale.y  = -scale.y;
            }

            material.SetTextureOffset(propertyId, offset);
            material.SetTextureScale(propertyId, scale);
        }
 public void SetCurrentToFrom()
 {
     if (_material = material)
     {
         _material.SetTextureOffset(propertyName, from);
     }
 }
 public void SetCurrentToTo()
 {
     if (_material = material)
     {
         _material.SetTextureOffset(propertyName, to);
     }
 }
 static void TrySetTextureTransform(
     Schema.TextureInfo textureInfo,
     UnityEngine.Material material,
     int propertyId
     )
 {
     if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
     {
         var tt = textureInfo.extensions.KHR_texture_transform;
         if (tt.texCoord != 0)
         {
             Debug.LogError("Multiple UV sets are not supported!");
         }
         if (tt.offset != null)
         {
             material.SetTextureOffset(propertyId, new Vector2(tt.offset[0], 1 - tt.offset[1]));
         }
         if (tt.rotation != 0)
         {
             float cos = Mathf.Cos(tt.rotation);
             float sin = Mathf.Sin(tt.rotation);
             material.SetVector(StandardShaderHelper.mainTexRotatePropId, new Vector4(cos, -sin, sin, cos));
             material.EnableKeyword(StandardShaderHelper.KW_UV_ROTATION);
         }
         if (tt.scale != null)
         {
             material.SetTextureScale(propertyId, new Vector2(tt.scale[0], -tt.scale[1]));
         }
     }
 }
Ejemplo n.º 7
0
    public void UpdateTile()
    {
        //Replace "GetNeighboursRaycast2D" with the method you want to use to find tile neirghbours
        GetNeighboursRaycast2D();

        SelectTile();

        if (!Application.isPlaying) {
            try {
                renderer.sharedMaterial.SetTextureScale("_BumpMap", new Vector2(1f/8f,1f/6f));
                renderer.sharedMaterial.SetTextureOffset("_BumpMap", new Vector2(1f/8f*sx,1f/6f*sy));
            } catch {}
        } else {
            try {
                var tempMaterial = new Material(renderer.sharedMaterial);
                tempMaterial.mainTexture=renderer.sharedMaterial.mainTexture;
                try {
                tempMaterial.SetTextureScale("_BumpMap", new Vector2(1f/8f,1f/6f));
                tempMaterial.SetTextureOffset("_BumpMap", new Vector2(1f/8f*sx,1f/6f*sy));
                } catch {}
                tempMaterial.shader=renderer.sharedMaterial.shader;
                renderer.sharedMaterial = tempMaterial;
            } catch {}
        }
    }
Ejemplo n.º 8
0
 public override void Restore()
 {
     if (null == m_Material)
     {
         return;
     }
     // end if
     if (!string.IsNullOrEmpty(m_property))
     {
         m_Material.SetTextureOffset(m_property, m_beginOffset);
     }
     else if (-1 != m_propertyID)
     {
         m_Material.SetTextureOffset(m_propertyID, m_beginOffset);
     } // end if
 }
 public override void OnRestore()
 {
     if (_material = material)
     {
         _material.SetTextureOffset(propertyName, _original);
     }
 }
		public void Apply(ConfigNode node)
		{
			//create scaled material and set proprties to defaults
			scaledMaterial = new Material (Shaders.EmissiveScaled);
			scaledMaterial.SetTextureScale ("_EmissiveMap", Vector2.one);
			scaledMaterial.SetTextureOffset ("_EmissiveMap", Vector2.zero);
			scaledMaterial.SetColor ("_Color", new Color (1f, 1f, 1f));
			scaledMaterial.SetFloat ("_Brightness", 1.25f);
			scaledMaterial.SetFloat ("_Transparency", 0.75f);
		}
Ejemplo n.º 11
0
 void AnimateTracks(Material track, Transform[] wheels, float speed)
 {
     var offset = track.mainTextureOffset;
     offset.x += speed * Time.deltaTime;
     track.mainTextureOffset = offset;
     track.SetTextureOffset ("_BumpMap", offset);
     foreach (var w in wheels) {
         w.RotateAround (w.right, speed * Time.deltaTime * wheelSpeedFactor);
     }
 }
Ejemplo n.º 12
0
        public override void OnTween(float factor)
        {
            if (_material = material)
            {
                _temp = _material.GetTextureOffset(propertyName);

                if (mask.GetBit(0)) _temp.x = from.x + (to.x - from.x) * factor;
                if (mask.GetBit(1)) _temp.y = from.y + (to.y - from.y) * factor;

                _material.SetTextureOffset(propertyName, _temp);
            }
        }
Ejemplo n.º 13
0
			// Constructor
			public RendererCache(Renderer r, Material sharedOpaqueMaterial, float zTest, float stencilRef)
			{
				data = new List<Data>();
				renderer = r;
				go = r.gameObject;

				Material[] materials = r.sharedMaterials;

				if (materials != null)
				{
					for (int i = 0; i < materials.Length; i++)
					{
						Material sourceMat = materials[i];

						if (sourceMat == null) { continue; }

						Data d = new Data();
						
						string tag = sourceMat.GetTag("RenderType", true, "Opaque");
						if (tag == "Transparent" || tag == "TransparentCutout")
						{
							Material replacementMat = new Material(transparentShader);
							replacementMat.SetFloat(ShaderPropertyID._ZTest, zTest);
							replacementMat.SetFloat(ShaderPropertyID._StencilRef, stencilRef);
							if (sourceMat.HasProperty(ShaderPropertyID._MainTex))
							{
								replacementMat.SetTexture(ShaderPropertyID._MainTex, sourceMat.mainTexture);
								replacementMat.SetTextureOffset("_MainTex", sourceMat.mainTextureOffset);
								replacementMat.SetTextureScale("_MainTex", sourceMat.mainTextureScale);
							}
							
							int cutoff = ShaderPropertyID._Cutoff;
							replacementMat.SetFloat(cutoff, sourceMat.HasProperty(cutoff) ? sourceMat.GetFloat(cutoff) : transparentCutoff);

							d.material = replacementMat;
							d.transparent = true;
						}
						else
						{
							d.material = sharedOpaqueMaterial;
							d.transparent = false;
						}

						d.submeshIndex = i;
						data.Add(d);
					}
				}

				visible = IsVisible();
			}
Ejemplo n.º 14
0
        // int zTest, int stencilRef
        //
        public void Initialize(Material sharedOpaqueMaterial, Shader transparentShader)
        {
            data = new List<Data>();

            Material[] materials = r.sharedMaterials;

            if (materials != null)
            {
                for (int i = 0; i < materials.Length; i++)
                {
                    Material sourceMat = materials[i];

                    if (sourceMat == null) { continue; }

                    Data d = new Data();

                    string tag = sourceMat.GetTag(sRenderType, true, sOpaque);
                    if (tag == sTransparent || tag == sTransparentCutout)
                    {
                        Material replacementMat = new Material(transparentShader);
                        //replacementMat.SetInt(ShaderPropertyID._ZTest, zTest);
                        //replacementMat.SetInt(ShaderPropertyID._StencilRef, stencilRef);

                        // To render both sides of the Sprite
                        if (r is SpriteRenderer) { replacementMat.SetInt(ShaderPropertyID._Cull, cullOff); }

                        if (sourceMat.HasProperty(ShaderPropertyID._MainTex))
                        {
                            replacementMat.SetTexture(ShaderPropertyID._MainTex, sourceMat.mainTexture);
                            replacementMat.SetTextureOffset(sMainTex, sourceMat.mainTextureOffset);
                            replacementMat.SetTextureScale(sMainTex, sourceMat.mainTextureScale);
                        }

                        int cutoff = ShaderPropertyID._Cutoff;
                        replacementMat.SetFloat(cutoff, sourceMat.HasProperty(cutoff) ? sourceMat.GetFloat(cutoff) : transparentCutoff);

                        d.material = replacementMat;
                        d.transparent = true;
                    }
                    else
                    {
                        d.material = sharedOpaqueMaterial;
                        d.transparent = false;
                    }

                    d.submeshIndex = i;
                    data.Add(d);
                }
            }
        }
Ejemplo n.º 15
0
        public ResourceObject Parse(ByteBuffer bb)
        {
            Schema.Material _material = Schema.Material.GetRootAsMaterial(bb);

            ResourceObjectMaterial result = new ResourceObjectMaterial(_material.Shader);

            UnityEngine.Material material = result.Unity3dObject as UnityEngine.Material;
            material.name = _material.Name;

            for (int i = 0; i < _material.PropertiesLength; i++)
            {
                Schema.ShaderProperty p = _material.GetProperties(i);
                switch (p.Type)
                {
                case ShaderPropertyType.Float:
                case ShaderPropertyType.Range:
                {
                    Schema.ShaderPropertyFloat f = p.GetValue <Schema.ShaderPropertyFloat>(fObj);
                    material.SetFloat(p.Names, f.Value);
                }
                break;

                case ShaderPropertyType.Color:
                {
                    Schema.ShaderPropertyColor c = p.GetValue <Schema.ShaderPropertyColor>(cObj);
                    material.SetColor(p.Names, new UnityEngine.Color(c.Color.R, c.Color.G, c.Color.B, c.Color.A));
                }
                break;

                case ShaderPropertyType.Vector:
                {
                    Schema.ShaderPropertyVector v = p.GetValue <Schema.ShaderPropertyVector>(vObj);
                    material.SetVector(p.Names, new Vector4(v.Vector.X, v.Vector.Y, v.Vector.Z, v.Vector.W));
                }
                break;

                case ShaderPropertyType.TexEnv:
                {
                    Schema.ShaderPropertyTexture t = p.GetValue <Schema.ShaderPropertyTexture>(tObj);
                    material.SetTextureOffset(p.Names, new Vector2(t.Offset.X, t.Offset.Y));
                    material.SetTextureScale(p.Names, new Vector2(t.Scale.X, t.Scale.Y));
                    result.AddTexture(t.Name, p.Names);
                }
                break;
                }
            }

            return(result);
        }
Ejemplo n.º 16
0
 static public int SetTextureOffset(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector2 a2;
         checkType(l, 3, out a2);
         self.SetTextureOffset(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 17
0
 static int SetTextureOffset(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         UnityEngine.Material obj = (UnityEngine.Material)ToLua.CheckObject(L, 1, typeof(UnityEngine.Material));
         string arg0 = ToLua.CheckString(L, 2);
         UnityEngine.Vector2 arg1 = ToLua.ToVector2(L, 3);
         obj.SetTextureOffset(arg0, arg1);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 18
0
 static public int SetTextureOffset(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector2 a2;
         checkType(l, 3, out a2);
         self.SetTextureOffset(a1, a2);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Ejemplo n.º 19
0
        protected virtual void ApplyTextureTransform(GLTF.Schema.TextureInfo def, UnityEngine.Material mat, string texName)
        {
            GLTF.Schema.Extension extension;
            if (_root.ExtensionsUsed != null &&
                _root.ExtensionsUsed.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME) &&
                def.Extensions != null &&
                def.Extensions.TryGetValue(ExtTextureTransformExtensionFactory.EXTENSION_NAME, out extension))
            {
                ExtTextureTransformExtension ext = (ExtTextureTransformExtension)extension;

                Vector2 temp = ext.Offset.ToUnityVector2();
                temp = new Vector2(temp.x, -temp.y);
                mat.SetTextureOffset(texName, temp);

                mat.SetTextureScale(texName, ext.Scale.ToUnityVector2());
            }
        }
Ejemplo n.º 20
0
 public static void ApplyValueLerp(AMMaterialTrack.ValueType valueType, string prop, int propId, Material mat, AMMaterialKey fromKey, AMMaterialKey toKey, float t)
 {
     switch(valueType) {
         case AMMaterialTrack.ValueType.Float:
         case AMMaterialTrack.ValueType.Range:
             mat.SetFloat(propId, Mathf.Lerp(fromKey.val, toKey.val, t));
             break;
         case AMMaterialTrack.ValueType.Vector:
             mat.SetVector(propId, Vector4.Lerp(fromKey.vector, toKey.vector, t));
             break;
         case AMMaterialTrack.ValueType.Color:
             mat.SetColor(propId, Color.Lerp(fromKey.color, toKey.color, t));
             break;
         case AMMaterialTrack.ValueType.TexOfs:
             mat.SetTextureOffset(prop, Vector2.Lerp(fromKey.texOfs, toKey.texOfs, t));
             break;
         case AMMaterialTrack.ValueType.TexScale:
             mat.SetTextureScale(prop, Vector2.Lerp(fromKey.texScale, toKey.texScale, t));
             break;
     }
 }
    private void InitDefaultVariables()
    {
        currentRenderer = GetComponent<Renderer>();
        if (currentRenderer==null)
            throw new Exception("UvTextureAnimator can't get renderer");
        if (!currentRenderer.enabled)
            currentRenderer.enabled = true;
        allCount = 0;
        animationStoped = false;
        animationLifeTime = TilesX * TilesY / AnimationFPS;
        count = TilesY * TilesX;
        index = TilesX - 1;
        var offset = Vector3.zero;
        StartFrameOffset = StartFrameOffset - (StartFrameOffset / count) * count;
        var size = new Vector2(1f / TilesX, 1f / TilesY);

        if (currentRenderer!=null) {
            instanceMaterial = currentRenderer.material;
            instanceMaterial.SetTextureScale("_MainTex", size);
            instanceMaterial.SetTextureOffset("_MainTex", offset);
        }
    }
        public void SetTextures(Material material)
        {
            material.SetTexture("_YTex", m_ChannelTextures[0]);
            material.SetTexture("_CbTex", m_ChannelTextures[1]);
			material.SetTexture("_CrTex", m_ChannelTextures[2]);

            material.SetTextureScale("_YTex", m_uvYScale);
            material.SetTextureOffset("_YTex", m_uvYOffset);

            material.SetTextureScale("_CbTex", m_uvCrCbScale);
            material.SetTextureOffset("_CbTex", m_uvCrCbOffset);
        }
		// Constructor
		public HighlightingRendererCache(Renderer rend, Material[] mats, Material sharedOpaqueMaterial, bool writeDepth)
		{
			rendererCached = rend;
			goCached = rend.gameObject;
			sourceMaterials = mats;
			replacementMaterials = new Material[mats.Length];
			transparentMaterialIndexes = new List<int>();
			
			for (int i = 0; i < mats.Length; i++)
			{
				Material sourceMat = mats[i];
				if (sourceMat == null)
				{
					continue;
				}
				string tag = sourceMat.GetTag("RenderType", true);
				if (tag == "Transparent" || tag == "TransparentCutout")
				{
					Material replacementMat = new Material(writeDepth ? transparentZShader : transparentShader);
					if (sourceMat.HasProperty("_MainTex"))
					{
						replacementMat.SetTexture("_MainTex", sourceMat.mainTexture);
						replacementMat.SetTextureOffset("_MainTex", sourceMat.mainTextureOffset);
						replacementMat.SetTextureScale("_MainTex", sourceMat.mainTextureScale);
					}
					
					replacementMat.SetFloat("_Cutoff", sourceMat.HasProperty("_Cutoff") ? sourceMat.GetFloat("_Cutoff") : transparentCutoff);
					
					replacementMaterials[i] = replacementMat;
					transparentMaterialIndexes.Add(i);
				}
				else
				{
					replacementMaterials[i] = sharedOpaqueMaterial;
				}
			}
		}
Ejemplo n.º 24
0
 // Use this for initialization
 void Start()
 {
     characterSheet = renderer.material;
     characterSheet.SetTextureOffset("_MainTex", new Vector2(xOffset, yOffset));
 }
        Rect[] __CreateAtlasesMBTexturePackerFast(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<ShaderTextureProperty> texPropertyNames, bool[] allTexturesAreNullAndSameColor, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding)
        {
            Rect[] uvRects;
            if (distinctMaterialTextures.Count == 1){
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
                uvRects = new Rect[1];
                uvRects[0] = new Rect(0f,0f,1f,1f);
                for (int i = 0; i < numAtlases; i++){
                    MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
                    atlases[i] = dmt.t;
                    resultMaterial.SetTexture(texPropertyNames[i].name,atlases[i]);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,dmt.scale);
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name,dmt.offset);
                }
            } else {
                List<Vector2> imageSizes = new List<Vector2>();
                for (int i = 0; i < distinctMaterialTextures.Count; i++){
                    imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));
                }
                MB2_TexturePacker tp = new MB2_TexturePacker();
                tp.doPowerOfTwoTextures = _meshBakerTexturePackerForcePowerOfTwo;
                int atlasSizeX = 1;
                int atlasSizeY = 1;

                //todo add sanity warnings for huge atlasesr
                int atlasMaxDimension = _maxAtlasSize;

                //if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();

                uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");

                //create a game object
                GameObject renderAtlasesGO = new GameObject("MBrenderAtlasesGO");
                MB3_AtlasPackerRenderTexture atlasRenderTexture = renderAtlasesGO.AddComponent<MB3_AtlasPackerRenderTexture>();
                for (int i = 0; i < numAtlases; i++){
                    Texture2D atlas = null;
                    if (allTexturesAreNullAndSameColor[i]){
                        atlas = null;
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Not creating atlas for " + texPropertyNames[i].name + " because textures are null and default value parameters are the same.");
                    } else {
                        GC.Collect();
                        if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i].name + "'", .01f);
                        // ===========
                        // configure it
                        atlasRenderTexture.width = atlasSizeX;
                        atlasRenderTexture.height = atlasSizeY;
                        atlasRenderTexture.padding = _padding;
                        atlasRenderTexture.rects = uvRects;
                        atlasRenderTexture.textureSets = distinctMaterialTextures;
                        atlasRenderTexture.indexOfTexSetToRender = 0;
                        // call render on it
                        atlas = atlasRenderTexture.OnRenderAtlas();
                        // destroy it
                        // =============
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i].name + " w=" + atlas.width + " h=" + atlas.height);
                    }
                    atlases[i] = atlas;
                    if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i].name + "'", .04f);
                    if (_saveAtlasesAsAssets && textureEditorMethods != null){
                        textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
                    } else {
                        resultMaterial.SetTexture(texPropertyNames[i].name, atlases[i]);
                    }
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name, Vector2.zero);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,Vector2.one);
                    _destroyTemporaryTextures(); // need to save atlases before doing this
                }
            }
            return uvRects;
        }
Ejemplo n.º 26
0
 public static void SetMainTextureScaleOffset(this Material _this, Vector4 st)
 {
     _this.SetTextureScale(PropId_MainTexture, new Vector2(st.x, st.y));
     _this.SetTextureOffset(PropId_MainTexture, new Vector2(st.z, st.w));
 }
		Rect[] __CreateAtlasesUnityTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<string> texPropertyNames, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding){
			Rect[] uvRects;
			if (distinctMaterialTextures.Count == 1){
				if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
				uvRects = new Rect[1];
				uvRects[0] = new Rect(0f,0f,1f,1f);
				for (int i = 0; i < numAtlases; i++){
					MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
					atlases[i] = dmt.t;
					resultMaterial.SetTexture(texPropertyNames[i],atlases[i]);
					resultMaterial.SetTextureScale(texPropertyNames[i],dmt.scale);
					resultMaterial.SetTextureOffset(texPropertyNames[i],dmt.offset);
				}
			} else {
				long estArea = 0;
				int atlasSizeX = 1;
				int atlasSizeY = 1;
				uvRects = null;
				for (int i = 0; i < numAtlases; i++){ //i is an atlas "MainTex", "BumpMap" etc...
					if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Beginning loop " + i + " num temporary textures " + _temporaryTextures.Count);
					for(int j = 0; j < distinctMaterialTextures.Count; j++){ //j is a distinct set of textures one for each of "MainTex", "BumpMap" etc...
						MB_TexSet txs = distinctMaterialTextures[j];
						
						int tWidth = txs.idealWidth;
						int tHeight = txs.idealHeight;
		
						Texture2D tx = txs.ts[i].t;
						if (tx == null) tx = txs.ts[i].t = _createTemporaryTexture(tWidth,tHeight,TextureFormat.ARGB32, true);
		
						if (progressInfo != null)
							progressInfo("Adjusting for scale and offset " + tx, .01f);	
						if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(tx, true, true); 
						tx = getAdjustedForScaleAndOffset2(txs.ts[i]);				
						
						//create a resized copy if necessary
						if (tx.width != tWidth || tx.height != tHeight) {
							if (progressInfo != null) progressInfo("Resizing texture '" + tx + "'", .01f);
							if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Copying and resizing texture " + texPropertyNames[i] + " from " + tx.width + "x" + tx.height + " to " + tWidth + "x" + tHeight);
							if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag((Texture2D) tx, true, true);
							tx = _resizeTexture((Texture2D) tx,tWidth,tHeight);
						}
						txs.ts[i].t = tx;
					}
		
					Texture2D[] texToPack = new Texture2D[distinctMaterialTextures.Count];
					for (int j = 0; j < distinctMaterialTextures.Count;j++){
						Texture2D tx = distinctMaterialTextures[j].ts[i].t;
						estArea += tx.width * tx.height;
						texToPack[j] = tx;
					}
					
					if (textureEditorMethods != null) textureEditorMethods.CheckBuildSettings(estArea);
			
					if (Math.Sqrt(estArea) > 3500f){
						if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("The maximum possible atlas size is 4096. Textures may be shrunk");
					}
					atlases[i] = new Texture2D(1,1,TextureFormat.ARGB32,true);
					if (progressInfo != null)
						progressInfo("Packing texture atlas " + texPropertyNames[i], .25f);	
					if (i == 0){
						if (progressInfo != null)
							progressInfo("Estimated min size of atlases: " + Math.Sqrt(estArea).ToString("F0"), .1f);			
						if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("Estimated atlas minimum size:" + Math.Sqrt(estArea).ToString("F0"));
						
						_addWatermark(texToPack);			
						
						if (distinctMaterialTextures.Count == 1){ //don't want to force power of 2 so tiling will still work
							uvRects = new Rect[1] {new Rect(0f,0f,1f,1f)};
							atlases[i] = _copyTexturesIntoAtlas(texToPack,_padding,uvRects,texToPack[0].width,texToPack[0].height);
						} else {
							int maxAtlasSize = 4096;
							uvRects = atlases[i].PackTextures(texToPack,_padding,maxAtlasSize,false);
						}
						
						if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("After pack textures atlas size " + atlases[i].width + " " + atlases[i].height);
						atlasSizeX = atlases[i].width;
						atlasSizeY = atlases[i].height;	
						atlases[i].Apply();
					} else {
						if (progressInfo != null)
							progressInfo("Copying Textures Into: " + texPropertyNames[i], .1f);					
						atlases[i] = _copyTexturesIntoAtlas(texToPack,_padding,uvRects, atlasSizeX, atlasSizeY);
					}
					
					if (saveAtlasesAsAssets && textureEditorMethods != null){
						textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
					} else {
						resultMaterial.SetTexture(texPropertyNames[i], atlases[i]);
					}
					resultMaterial.SetTextureOffset(texPropertyNames[i], Vector2.zero);
					resultMaterial.SetTextureScale(texPropertyNames[i],Vector2.one);
					
					_destroyTemporaryTextures(); // need to save atlases before doing this
					GC.Collect();
				}
			}
			return uvRects;
		}	
Ejemplo n.º 28
0
			// Constructor
			public HighlightingRendererCache(Renderer rend, Material[] mats, Material sharedOpaqueMaterial, int renderQueue, float zTest, float stencilRef)
			{
				rendererCached = rend;
				goCached = rend.gameObject;
				sourceMaterials = mats;
				replacementMaterials = new Material[mats.Length];
				transparentMaterialIndexes = new List<int>();
				
				for (int i = 0; i < mats.Length; i++)
				{
					Material sourceMat = mats[i];
					if (sourceMat == null) { continue; }
					
					string tag = sourceMat.GetTag("RenderType", true, "Opaque");
					if (tag == "Transparent" || tag == "TransparentCutout")
					{
						Material replacementMat = new Material(transparentShader);
						replacementMat.renderQueue = renderQueue;
						replacementMat.SetFloat(ShaderPropertyID._ZTest, zTest);
						replacementMat.SetFloat(ShaderPropertyID._StencilRef, stencilRef);
						if (sourceMat.HasProperty(ShaderPropertyID._MainTex))
						{
							replacementMat.SetTexture(ShaderPropertyID._MainTex, sourceMat.mainTexture);
							replacementMat.SetTextureOffset("_MainTex", sourceMat.mainTextureOffset);
							replacementMat.SetTextureScale("_MainTex", sourceMat.mainTextureScale);
						}
						
						int cutoff = ShaderPropertyID._Cutoff;
						replacementMat.SetFloat(cutoff, sourceMat.HasProperty(cutoff) ? sourceMat.GetFloat(cutoff) : transparentCutoff);
						
						replacementMaterials[i] = replacementMat;
						transparentMaterialIndexes.Add(i);
					}
					else
					{
						replacementMaterials[i] = sharedOpaqueMaterial;
					}
				}
			}
Ejemplo n.º 29
0
	public void SetValues(Material m, IEnumerable<StoredValue> values)
	{
		foreach(var v in values)
		{
			switch(v.Property.type)
			{
			case MaterialProperty.PropertyType.color:
				m.SetColor(v.Property.name, (Color)v.Value);
				break;
			case MaterialProperty.PropertyType.real:
				m.SetFloat(v.Property.name, (float)v.Value);
				break;
			case MaterialProperty.PropertyType.texture:
				m.SetTexture(v.Property.name, (Texture)v.Value);
				break;
			case MaterialProperty.PropertyType.vector:
				m.SetVector(v.Property.name, (Vector4)v.Value);
				break;
			case MaterialProperty.PropertyType.textureOffset:
				m.SetTextureOffset(v.Property.name, (Vector2)v.Value);
				break;
			case MaterialProperty.PropertyType.textureScale:
				m.SetTextureScale(v.Property.name, (Vector2)v.Value);
				break;
			case MaterialProperty.PropertyType.matrix:
				m.SetMatrix(v.Property.name, (Matrix4x4)v.Value);
				break;
			}
		}
	}
Ejemplo n.º 30
0
 private void _SetMatTex(Material mat, string matPropName, Texture tex, Vector2 tiling, Vector2 offset)
     // 设置材质指定属性的纹理
 {
     //if (!string.IsNullOrEmpty(texturePath))
     //{
     //    Texture tex;
     //if (CachedTextures.TryGetValue(texturePath, out tex))
     {
         mat.SetTexture(matPropName, tex);
         mat.SetTextureScale(matPropName, tiling);
         mat.SetTextureOffset(matPropName, offset);
     }
     //else
     //    Logger.LogError("找不到纹理: {0}", texturePath);
     //}
 }
Ejemplo n.º 31
0
        void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            // Scale (x,y) and Transform (z,w)
            float4 textureST = new float4(
                1, 1, // scale
                0, 0  // transform
                );

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord != 0)
                {
                    logger?.Error(LogCode.UVMulti);
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    textureST.z = tt.offset[0];
                    textureST.w = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    textureST.x = tt.scale[0];
                    textureST.y = tt.scale[1];
                }
                if (tt.rotation != 0)
                {
                    cos = math.cos(tt.rotation);
                    sin = math.sin(tt.rotation);

                    var newRot = new Vector2(textureST.x * sin, textureST.y * -sin);
                    material.SetVector(mainTexRotation, newRot);
                    textureST.x *= cos;
                    textureST.y *= cos;

                    material.EnableKeyword(KW_UV_ROTATION);
                    textureST.z -= newRot.y; // move offset to move rotation point (horizontally)
                }

                textureST.w -= textureST.y * cos; // move offset to move flip axis point (vertically)
            }

            if (flipY)
            {
                textureST.z = 1 - textureST.z; // flip offset in Y
                textureST.y = -textureST.y;    // flip scale in Y
            }

            if (material.HasProperty(mainTexPropId))
            {
                material.SetTextureOffset(mainTexPropId, textureST.zw);
                material.SetTextureScale(mainTexPropId, textureST.xy);
            }
            material.SetTextureOffset(propertyId, textureST.zw);
            material.SetTextureScale(propertyId, textureST.xy);
            material.SetVector(mainTexScaleTransform, textureST);
        }
    void CreateSkybox(List<string> data)
    {
        string skyname = data[data.FindIndex(n => n == "skyname") + 1];
        Material SkyMaterial = new Material(Shader.Find("Mobile/Skybox"));

        foreach (string alpString in new string[] { "_FrontTex", "_BackTex", "_LeftTex", "_RightTex", "_UpTex" })
        {
            SkyMaterial.SetTextureScale(alpString, new Vector2(1, -1));
            SkyMaterial.SetTextureOffset(alpString, new Vector2(0, 1));
        }

        Texture2D FrontTex = TextureLoader.Load("skybox/" + skyname + "rt");
        FrontTex.wrapMode = TextureWrapMode.Clamp;

        Texture2D BackTex = TextureLoader.Load("skybox/" + skyname + "lf");
        BackTex.wrapMode = TextureWrapMode.Clamp;

        Texture2D LeftTex = TextureLoader.Load("skybox/" + skyname + "ft");
        LeftTex.wrapMode = TextureWrapMode.Clamp;

        Texture2D RightTex = TextureLoader.Load("skybox/" + skyname + "bk");
        RightTex.wrapMode = TextureWrapMode.Clamp;

        Texture2D UpTex = TextureLoader.Load("skybox/" + skyname + "up");
        UpTex.wrapMode = TextureWrapMode.Clamp;

        SkyMaterial.SetTexture("_FrontTex", FrontTex);
        SkyMaterial.SetTexture("_BackTex", BackTex);
        SkyMaterial.SetTexture("_LeftTex", LeftTex);
        SkyMaterial.SetTexture("_RightTex", RightTex);
        SkyMaterial.SetTexture("_UpTex", UpTex);

        RenderSettings.skybox = SkyMaterial;
    }
Ejemplo n.º 33
0
	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);
			}
		}
	}
Ejemplo n.º 34
0
 internal void Animate(Material material, float time) {
     Vector2 textureOffset = new Vector2(xScrollSpeed * time % 1, yScrollSpeed * time % 1);
     material.SetTextureOffset(UnityConstants.MainDiffuseTexture, textureOffset);
     material.SetTextureOffset(UnityConstants.NormalMapTexture, textureOffset);
 }
Ejemplo n.º 35
0
	public bool LoadMovie (string moviePath)
	{
		this.BinkSetup ();
		
		if (moviePath.Length == 0) {
			return false;
		}
	
		if (BinkRenderQueueCreateShaders ()) {
			_LoadMovie (moviePath);
			
			if (Movie.Bink == IntPtr.Zero) {
				return false;
			}
			if (Movie.Bink != IntPtr.Zero) {
				
				if (Type == BinkPluginType.CPUTexture) {
					// Create texture that will be updated in the plugin
					m_Texture = new Texture2D (Movie.BinkWidth, Movie.BinkHeight, TextureFormat.ARGB32, false);
					// Create the pixel array for the plugin to write into at startup    
					m_Pixels = m_Texture.GetPixels32 (0);
					// "pin" the array in memory, so we can pass direct pointer to it's data to the plugin,
					// without costly marshaling of array of structures.
					m_PixelsHandle = GCHandle.Alloc (m_Pixels, GCHandleType.Pinned);
	
					//Assign texture to ourselves.
					if (renderer) {
						renderer.material.mainTexture = m_Texture;
					} else {
						UnityEngine.Debug.Log ("Game object has no renderer to assign the texture to!");
					}
				}


				if (Type == BinkPluginType.GPUTexture) {						
					if (usingOpenGL()) {
						// Create texture that will be updated in the plugin. Note, the textureformat doesn't really matter here, 
						// as we'll be managing the texels ourselves in the fragment shader. 
						m_yTexture = new Texture2D (Movie.BinkWidth, Movie.BinkHeight, TextureFormat.ARGB32, false);
						m_cBTexture = new Texture2D (Movie.BinkWidth / 2, Movie.BinkHeight / 2, TextureFormat.RGBA32, false);
						m_cRTexture = new Texture2D (Movie.BinkWidth / 2, Movie.BinkHeight / 2, TextureFormat.RGBA32, false);

						if (UseAlpha) {
							//You only really want to do this if your movie have alpha and you want to use it. 
							m_aTexture = new Texture2D (Movie.BinkWidth, Movie.BinkHeight, TextureFormat.RGBA32, false);
						}
					}


					if (usingOpenGL() && renderer) {
						renderer.material.SetTexture ("yTexture", m_yTexture);
						renderer.material.SetTexture ("cBTexture", m_cBTexture);
						renderer.material.SetTexture ("cRTexture", m_cRTexture);
						
						if (UseAlpha) {
							renderer.material.SetTexture ("aTexture", m_aTexture);				
						}
					} else {
						//Hook the material up to our textures
						Material m = new Material (Shader.Find ("RAD/BinkShader"));
						m.SetTexture ("yTexture", m_yRenderTexture);
						m.SetTexture ("cBTexture", m_cBRenderTexture);
						m.SetTexture ("cRTexture", m_cRRenderTexture);
						if (UseAlpha) {
							m.SetTexture ("aTexture", m_ARenderTexture);				
						}

						//Disable rendering GPUTextured objects until the plugin, running on the 
						//render thread, has a chance to fill out the texture
						if (renderer) {
							renderer.enabled = false;
						}

						//Adjust UV's since D3D gpu texturing oversizes the texture's vertical component so that it's a multiple of 8 on bink1
						//Note we also use texScale.x = -1 and texOffset.x = 1 to flip the image vertically since Unity's texture up is the opposite of binks
						Vector2 texScale = new Vector2 (1.0f, -((float)Movie.BinkHeight) / (float)m_yRenderTexture.height);
						Vector2 texOffset = new Vector2 (0.0f, 1.0f);
						m.SetTextureScale ("yTexture", texScale);
						m.SetTextureOffset ("yTexture", texOffset);

						m.SetTextureScale ("cBTexture", texScale);
						m.SetTextureOffset ("cBTexture", texOffset);

						m.SetTextureScale ("cRTexture", texScale);
						m.SetTextureOffset ("cRTexture", texOffset);

						if (UseAlpha) {
							m.SetTextureScale ("aTexture", texScale);
							m.SetTextureOffset ("aTexture", texOffset);
						}
						this.rt = new RenderTexture (Movie.BinkWidth, Movie.BinkHeight, 0, RenderTextureFormat.Default);
						this.rt.wrapMode = TextureWrapMode.Repeat;
						this.BinkMaterial = m;
					}

				}
			}
		}
		return true;
	}
Ejemplo n.º 36
0
 public override void Apply(Material mat)
 {
     if (_hole0Texture!=null) {
         mat.SetTexture("_Hole0Tex",_hole0Texture);
         mat.SetTextureOffset("_Hole0Tex",_hole0Offset);
     }
 }
Ejemplo n.º 37
0
        void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int texturePropertyId,
            int scaleTransformPropertyId = -1,
            int rotationPropertyId       = -1,
            int uvChannelPropertyId      = -1,
            bool flipY = false
            )
        {
            // Scale (x,y) and Transform (z,w)
            float4 textureST = new float4(
                1, 1, // scale
                0, 0  // transform
                );

            var texCoord = textureInfo.texCoord;

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord >= 0)
                {
                    texCoord = tt.texCoord;
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    textureST.z = tt.offset[0];
                    textureST.w = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    textureST.x = tt.scale[0];
                    textureST.y = tt.scale[1];
                }
                if (tt.rotation != 0)
                {
                    cos = math.cos(tt.rotation);
                    sin = math.sin(tt.rotation);

                    var newRot = new Vector2(textureST.x * sin, textureST.y * -sin);

                    Assert.IsTrue(rotationPropertyId >= 0, "Texture rotation property invalid!");
                    material.SetVector(rotationPropertyId, newRot);

                    textureST.x *= cos;
                    textureST.y *= cos;

                    material.EnableKeyword(KW_UV_ROTATION);
                    textureST.z -= newRot.y; // move offset to move rotation point (horizontally)
                }
                else
                {
                    // In case _UV_ROTATION keyword is set (because another texture is rotated),
                    // make sure the rotation is properly nulled
                    material.SetVector(rotationPropertyId, Vector4.zero);
                }

                textureST.w -= textureST.y * cos; // move offset to move flip axis point (vertically)
            }

            if (texCoord != 0)
            {
                if (uvChannelPropertyId >= 0 && texCoord < 2f)
                {
                    material.EnableKeyword(KW_UV_CHANNEL_SELECT);
                    material.SetFloat(uvChannelPropertyId, texCoord);
                }
                else
                {
                    logger?.Error(LogCode.UVMulti, texCoord.ToString());
                }
            }

            if (flipY)
            {
                textureST.w = 1 - textureST.w; // flip offset in Y
                textureST.y = -textureST.y;    // flip scale in Y
            }

            material.SetTextureOffset(texturePropertyId, textureST.zw);
            material.SetTextureScale(texturePropertyId, textureST.xy);
            Assert.IsTrue(scaleTransformPropertyId >= 0, "Texture scale/transform property invalid!");
            material.SetVector(scaleTransformPropertyId, textureST);
        }
		Rect[] __CreateAtlasesMBTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<string> texPropertyNames, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding){
			Rect[] uvRects;
			if (distinctMaterialTextures.Count == 1){
				if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
				uvRects = new Rect[1];
				uvRects[0] = new Rect(0f,0f,1f,1f);
				for (int i = 0; i < numAtlases; i++){
					MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
					atlases[i] = dmt.t;
					resultMaterial.SetTexture(texPropertyNames[i],atlases[i]);
					resultMaterial.SetTextureScale(texPropertyNames[i],dmt.scale);
					resultMaterial.SetTextureOffset(texPropertyNames[i],dmt.offset);
				}
			} else {
				List<Vector2> imageSizes = new List<Vector2>();
				for (int i = 0; i < distinctMaterialTextures.Count; i++){
					imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));	
				}
				MB2_TexturePacker tp = new MB2_TexturePacker();
				int atlasSizeX = 1;
				int atlasSizeY = 1;
				
				//todo add sanity warnings for huge atlasesr
				int atlasMaxDimension = 4096;
				
				if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();
				
				uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
				if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");
				for (int i = 0; i < numAtlases; i++){
					GC.Collect();
					if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i] + "'", .01f);
					Color[] atlasPixels = new Color[atlasSizeX * atlasSizeY];//atlas.GetPixels();
					for (int j = 0; j < atlasPixels.Length; j++) atlasPixels[j] = Color.clear;
					for (int j = 0; j < distinctMaterialTextures.Count; j++){
						if (LOG_LEVEL >= MB2_LogLevel.trace) MB2_Log.Trace("Adding texture {0} to atlas {1}", distinctMaterialTextures[j].ts[i].t == null ? "null" : distinctMaterialTextures[j].ts[i].t.ToString(),texPropertyNames[i]);
						Rect r = uvRects[j];
						Texture2D t = distinctMaterialTextures[j].ts[i].t;
						int x = Mathf.RoundToInt(r.x * atlasSizeX);
						int y = Mathf.RoundToInt(r.y * atlasSizeY);
						int ww = Mathf.RoundToInt(r.width * atlasSizeX);
						int hh = Mathf.RoundToInt(r.height * atlasSizeY);
						if (ww == 0 || hh == 0) Debug.LogError("Image in atlas has no height or width");
						if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(t, true, true);
						if (progressInfo != null) progressInfo("Copying to atlas: '" + distinctMaterialTextures[j].ts[i].t + "'", .02f);
						CopyScaledAndTiledToAtlas(distinctMaterialTextures[j].ts[i],x,y,ww,hh,fixOutOfBoundsUVs,maxTilingBakeSize,atlasPixels,atlasSizeX,progressInfo);
					}
					if (progressInfo != null) progressInfo("Applying changes to atlas: '" + texPropertyNames[i] + "'", .03f);
					Texture2D atlas = new Texture2D(atlasSizeX, atlasSizeY,TextureFormat.ARGB32, true);
					atlas.SetPixels(atlasPixels);
					atlas.Apply();
					if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i] + " w=" + atlas.width + " h=" + atlas.height);
					atlases[i] = atlas;
					if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i] + "'", .04f);
					if (saveAtlasesAsAssets && textureEditorMethods != null){
						textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
					} else {
						resultMaterial.SetTexture(texPropertyNames[i], atlases[i]);
					}
					resultMaterial.SetTextureOffset(texPropertyNames[i], Vector2.zero);
					resultMaterial.SetTextureScale(texPropertyNames[i],Vector2.one);
					_destroyTemporaryTextures(); // need to save atlases before doing this				
				}
			}
			return uvRects;
		}
        Rect[] __CreateAtlasesMBTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<ShaderTextureProperty> texPropertyNames, bool[] allTexturesAreNullAndSameColor, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding)
        {
            Rect[] uvRects;
            if (distinctMaterialTextures.Count == 1){
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
                uvRects = new Rect[1];
                uvRects[0] = new Rect(0f,0f,1f,1f);
                for (int i = 0; i < numAtlases; i++){
                    MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
                    atlases[i] = dmt.t;
                    resultMaterial.SetTexture(texPropertyNames[i].name,atlases[i]);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,dmt.scale);
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name,dmt.offset);
                }
            } else {
                List<Vector2> imageSizes = new List<Vector2>();
                for (int i = 0; i < distinctMaterialTextures.Count; i++){
                    imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));
                }
                MB2_TexturePacker tp = new MB2_TexturePacker();
                tp.doPowerOfTwoTextures = _meshBakerTexturePackerForcePowerOfTwo;
                int atlasSizeX = 1;
                int atlasSizeY = 1;

                //todo add sanity warnings for huge atlasesr
                int atlasMaxDimension = _maxAtlasSize;

                //if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();

                uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");
                for (int i = 0; i < numAtlases; i++){
                    Texture2D atlas = null;
                    if (allTexturesAreNullAndSameColor[i]){
                        atlas = null;
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Not creating atlas for " + texPropertyNames[i].name + " because textures are null and default value parameters are the same.");
                    } else {
                        GC.Collect();
                        if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i].name + "'", .01f);
                        //use a jagged array because it is much more efficient in memory
                        Color[][] atlasPixels = new Color[atlasSizeY][];
                        for (int j = 0; j < atlasPixels.Length; j++){
                            atlasPixels[j] = new Color[atlasSizeX];
                        }
                        bool isNormalMap = false;
                        if (texPropertyNames[i].isNormalMap) isNormalMap = true;
            //						for (int j = 0; j < atlasPixels.Length; j++) {
            //							for (int k = 0; k < atlasSizeX; k++){
            //								atlasPixels[j][k] = GetColorIfNoTexture(
            //								if (isNormalMap){
            //									atlasPixels[j][k] = new Color(.5f,.5f,1f); //neutral bluish for normal maps
            //								} else {
            //									atlasPixels[j][k] = Color.clear;
            //								}
            //							}
            //						}
                        for (int j = 0; j < distinctMaterialTextures.Count; j++){
                            if (LOG_LEVEL >= MB2_LogLevel.trace) MB2_Log.Trace("Adding texture {0} to atlas {1}", distinctMaterialTextures[j].ts[i].t == null ? "null" : distinctMaterialTextures[j].ts[i].t.ToString(),texPropertyNames[i]);
                            Rect r = uvRects[j];
                            Texture2D t = distinctMaterialTextures[j].ts[i].t;
                            int x = Mathf.RoundToInt(r.x * atlasSizeX);
                            int y = Mathf.RoundToInt(r.y * atlasSizeY);
                            int ww = Mathf.RoundToInt(r.width * atlasSizeX);
                            int hh = Mathf.RoundToInt(r.height * atlasSizeY);
                            if (ww == 0 || hh == 0) Debug.LogError("Image in atlas has no height or width");
                            if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(t, true, true);
                            if (progressInfo != null) progressInfo("Copying to atlas: '" + distinctMaterialTextures[j].ts[i].t + "'", .02f);
                            CopyScaledAndTiledToAtlas(distinctMaterialTextures[j].ts[i],x,y,ww,hh,_fixOutOfBoundsUVs,_maxTilingBakeSize,atlasPixels,atlasSizeX,isNormalMap,progressInfo);
                        }
                        if (progressInfo != null) progressInfo("Applying changes to atlas: '" + texPropertyNames[i].name + "'", .03f);
                        atlas = new Texture2D(atlasSizeX, atlasSizeY,TextureFormat.ARGB32, true);
                        for (int j = 0; j < atlasPixels.Length; j++){
                            atlas.SetPixels(0,j,atlasSizeX,1,atlasPixels[j]);
                        }
                        atlas.Apply();
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i].name + " w=" + atlas.width + " h=" + atlas.height);
                    }
                    atlases[i] = atlas;
                    if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i].name + "'", .04f);
                    if (_saveAtlasesAsAssets && textureEditorMethods != null){
                        textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
                    } else {
                        resultMaterial.SetTexture(texPropertyNames[i].name, atlases[i]);
                    }
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name, Vector2.zero);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,Vector2.one);
                    _destroyTemporaryTextures(); // need to save atlases before doing this
                }
            }
            return uvRects;
        }
Ejemplo n.º 40
0
 public void ApplyValue(AMMaterialTrack.ValueType valueType, string prop, int propId, Material mat)
 {
     switch(valueType) {
         case AMMaterialTrack.ValueType.Float:
         case AMMaterialTrack.ValueType.Range:
             mat.SetFloat(propId, val);
             break;
         case AMMaterialTrack.ValueType.Vector:
             mat.SetVector(propId, vector);
             break;
         case AMMaterialTrack.ValueType.Color:
             mat.SetColor(propId, color);
             break;
         case AMMaterialTrack.ValueType.TexEnv:
             mat.SetTexture(propId, texture);
             break;
         case AMMaterialTrack.ValueType.TexOfs:
             mat.SetTextureOffset(prop, texOfs);
             break;
         case AMMaterialTrack.ValueType.TexScale:
             mat.SetTextureScale(prop, texScale);
             break;
     }
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Restores the material values
 /// </summary>
 /// <param name="m">Material</param>
 /// <param name="values">Set of values</param>
 public void SetValues(Material m, IEnumerable<StoredValue> values)
 {
     foreach (var v in values) {
         switch (v.property.type) {
             case MaterialProperty.PropertyType.Color:
                 m.SetColor(v.property.name, (Color)v.value[0]);
                 Debug.Log(v.property.name);
                 break;
             case MaterialProperty.PropertyType.Float:
                 m.SetFloat(v.property.name, (float)v.value[0]);
                 break;
             case MaterialProperty.PropertyType.Range:
                 m.SetFloat(v.property.name, (float)v.value[0]);
                 break;
             case MaterialProperty.PropertyType.TexEnv:
                 m.SetTexture(v.property.name, (Texture)v.value[0]);
                 m.SetTextureOffset(v.property.name, (Vector2)v.value[1]);
                 m.SetTextureScale(v.property.name, (Vector2)v.value[2]);
                 break;
             case MaterialProperty.PropertyType.Vector:
                 m.SetVector(v.property.name, (Vector4)v.value[0]);
                 break;
             default:
                 Debug.LogError("Unsupported type: " + v.property.type.ToString());
                 break;
         }
     }
 }