Inheritance: Texture
    /// <summary>
    /// Reads from the provided file name all parameters and data for a
    /// heightmap.  If the data for the heightmap does not exist, then
    /// no data is written to the provided texture.
    /// </summary>
    /// <param name='fileName'>
    /// The file name.  This can be relative or fully-qualified.
    /// </param>
    /// <param name='no'>
    /// The <see cref="NormalOptions" /> that will store read-in parameters.
    /// </param>
    /// <param name='co'>
    /// The <see cref="CloudOptions" /> that will store read-in parameters for
    /// <see cref="CloudFractal" />.
    /// </param>
    /// <param name='wo'>
    /// The <see cref="WorleyOptions" />  that will store read-in parameters for
    /// <see cref="WorleyNoise" />.
    /// </param>
    /// <param name='tex'>
    /// The <code>Texture2D</code> containing the heightmap data.
    /// </param>
    public static void Read(string fileName, ref NormalOptions no,
	                        ref CloudOptions co, ref VoronoiOptions vo,
							ref Texture2D tex)
    {
        using(BinaryReader r = new BinaryReader(File.OpenRead(fileName)))
        {
            no.size = r.ReadInt32();
            no.seed = r.ReadInt32();
            no.cloudInf = r.ReadSingle();
            no.voronoiInf = r.ReadSingle();
            no.useThermalErosion = r.ReadBoolean();
            no.useHydroErosion = r.ReadBoolean();
            no.showSeams = r.ReadBoolean();

            co.upperLeftStart = r.ReadSingle();
            co.lowerLeftStart = r.ReadSingle();
            co.lowerRightStart = r.ReadSingle();
            co.upperRightStart = r.ReadSingle();

            vo.metric = (DistanceFunctions.DistanceMetric)r.ReadInt32();
            vo.combiner = (CombinerFunctions.CombineFunction)r.ReadInt32();
            vo.numberOfFeaturePoints = r.ReadInt32();
            vo.numberOfSubregions = r.ReadInt32();
            vo.multiplier = r.ReadSingle();

            tex.Resize(no.size, no.size);
            int bLeft = (int)(r.BaseStream.Length - r.BaseStream.Position);
            if(bLeft > 0)
                tex.LoadImage(r.ReadBytes(bLeft));
        }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="UnityGwenRenderer"/> class.
 /// </summary>
 /// <param name="target">Unity render target.</param>
 public UnityGwenRenderer()
 {
     whiteTex = new Texture2D(1, 1);
     whiteTex.SetPixel(0, 0, UnityEngine.Color.white);
     whiteTex.Apply();
     m_ViewScale = Vector2.one;
 }
Exemple #3
0
		public void OnFocus()
		{
			string[] guids = AssetDatabase.FindAssets( "About t:Texture" );
			string asset = "";

			foreach ( string guid in guids )
			{
				string path = AssetDatabase.GUIDToAssetPath( guid );
				if ( path.EndsWith( AboutImagePath ) )
				{
					asset = path;
					break;
				}
			}

			if ( !string.IsNullOrEmpty( asset ) )
			{
				TextureImporter importer = AssetImporter.GetAtPath( asset ) as TextureImporter;

				if ( importer.textureType != TextureImporterType.GUI )
				{
					importer.textureType = TextureImporterType.GUI;
					AssetDatabase.ImportAsset( asset );
				}

				m_aboutImage = AssetDatabase.LoadAssetAtPath( asset, typeof( Texture2D ) ) as Texture2D;
			}
			else
				Debug.LogWarning( "[AmplifyColor] About image not found at " + AboutImagePath );
		}
		//assign edilen objeler statik olmali
		public override void loadResources()
		{
			staticTowerObject = (GameObject)Resources.Load("3Ds/Towers/Physics/BallistaTower/TowerObject");            
			staticTowerIcon = (Texture2D)Resources.Load("3Ds/Towers/Physics/BallistaTower/GUI/towerIcon");
            staticCreateSound = (AudioClip)Resources.Load("Sound/tower_build");
			staticRangeProjector = ((GameObject)Resources.Load ("3Ds/Scenes/Game/RangeProjector")).GetComponent<Projector>();
		}
Exemple #5
0
    // Update is called once per frame
    void Update()
    {
        // new Vector2 はsource Textureでのピクセル位置

        float srcW = source.width;
        float srcH = source.height;

        // src texture uv position
        Vector2[] uvs = new Vector2[4];
        uvs[0] = new Vector2(P1.localPosition.x/2, P1.localPosition.y/1) /10;
        uvs[1] = new Vector2(P2.localPosition.x/2, P2.localPosition.y/1) /10;
        uvs[2] = new Vector2(P3.localPosition.x/2, P3.localPosition.y/1) /10;
        uvs[3] = new Vector2(P4.localPosition.x/2, P4.localPosition.y/1) /10;

        Color32[] colors = Homography.GetTransformedColors( source, dstWidth, dstHeight,
                                                    new Vector2(uvs[0].x * srcW, uvs[0].y * srcH),
                                                    new Vector2(uvs[1].x * srcW, uvs[1].y * srcH),
                                                    new Vector2(uvs[2].x * srcW, uvs[2].y * srcH),
                                                    new Vector2(uvs[3].x * srcW, uvs[3].y * srcH));
        if(target == null){
            target = new Texture2D(dstWidth, dstHeight);
        }
        target.SetPixels32(colors, 0);
        target.Apply();

        targetRender.material.mainTexture = target;
    }
Exemple #6
0
        public Monitor(Int32[] arr, UInt16 ptr, UInt16 chars, UInt16 colPtr, UInt16 modePointer)
        {
            mem = arr;
            pointer = ptr;
            charSetPtr = chars;
            colors = new Color[16];
            modePtr = modePointer;
            for (int i = 0; i < 16; ++i) {
                colors[i] = new Color();
                colors[i].a = 1.0f;
            }
            colorPointer = colPtr;

            image = new Texture2D(256, 256, TextureFormat.ARGB32, false);
            windowPos = new Rect();
            if ((windowPos.x == 0) && (windowPos.y == 0))//windowPos is used to position the GUI window, lets set it in the center of the screen
            {
                windowPos = new Rect(Screen.width / 2, Screen.height / 2, 100, 100);
            }
            //Set all the pixels to black. If you don't do this the image contains random junk.
            for (int y = 0; y < image.height; y++) {
                for (int x = 0; x < image.width; x++) {
                    image.SetPixel(x, y, Color.black);
                }
            }
            image.Apply();
        }
Exemple #7
0
    Texture2D Capture(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
    IEnumerator ScreenshotEncode()
    {
        // wait for graphics to render
        yield return new WaitForEndOfFrame();

        // create a texture to pass to encoding
        Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

        // put buffer into texture
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();

        // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy
        yield return 0;

        byte[] bytes = texture.EncodeToPNG();

        count = PlayerPrefs.GetInt("count");

        // save our test image (could also upload to WWW)
        File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".png", bytes);
        count++;

        PlayerPrefs.SetInt("count", count);

        // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots.
        DestroyObject(texture);

        Debug.Log( Application.dataPath + "/../testscreen-" + count + ".png" );
    }
    public void Generate2DTexture()
    {
        texture2D = new Texture2D(n,n,TextureFormat.ARGB32,true);
        int size = n*n;
        Color[] cols = new Color[size];
        float u,v;
        int idx = 0;
        Color c = Color.white;
        for(int i = 0; i < n; i++) {
            u = i/(float)n;
            for(int j = 0; j < n; j++, ++idx) {
              	v = j/(float)n;
                float noise = Mathf.PerlinNoise(u,v);
                c.r = c.g = c.b = noise;
                cols[idx] = c;

            }
        }

        texture2D.SetPixels(cols);
        texture2D.Apply();
        renderer.material.SetTexture("g_tex", texture2D);

        //Color[] cs = texture3D.GetPixels();
        //for(int i = 0; i < 10; i++)
        //	Debug.Log (cs[i]);
    }
Exemple #10
0
    public static BGMotionManager GetInstance()
    {
        if (instance == null) {
            print("getting lock");
            lock (_lock) {
                if (instance == null) {
                    container = new GameObject ("BGMotionManager");
                    instance = container.AddComponent (typeof(BGMotionManager)) as BGMotionManager;

                    instance.bodyTrackerKeyboard = new BGBodyTrackerKeyboard (instance);

                    monoTrackerContainer = new GameObject("monoTrackerContainer");
                    print("made mono tracker");
                    instance.bodyTrackerMono = monoTrackerContainer.AddComponent(typeof(BGBodyTrackerMono)) as BGBodyTrackerMono;
                    ((instance.bodyTrackerMono) as BGBodyTrackerMono).SetOwner(instance);

                    nativeTrackerContainer = new GameObject("nativeTrackerContainer");
                    instance.bodyTrackerNative = nativeTrackerContainer.AddComponent(typeof(BGBodyTrackerNative)) as BGBodyTrackerNative;
                    ((instance.bodyTrackerNative) as BGBodyTrackerNative).SetOwner(instance);

                    feedbackTexture = new Texture2D(256, 256, TextureFormat.ARGB32, false);
                    DontDestroyOnLoad (container);
                }
            }
        }
        return instance;
    }
Exemple #11
0
 void Start()
 {
     rend = GetComponent<Renderer>();
     noiseTex = new Texture2D(pixWidth, pixHeight);
     pix = new Color[noiseTex.width * noiseTex.height];
     rend.material.mainTexture = noiseTex;
 }
Exemple #12
0
    public BitmapData(Texture2D texture)
    {
        height = texture.height;
        width = texture.width;

        pixels = texture.GetPixels();
    }
			public MeshBakerMaterialTexture(Texture2D tx, Vector2 o, Vector2 s, Vector2 oUV, Vector2 sUV){
				t = tx;
				offset = o;
				scale = s;
				obUVoffset = oUV;
				obUVscale = sUV;
			}
Exemple #14
0
    public CQuadtree(Vector3 up, Vector3 front, CPlanet planet, Texture2D shapeTex)
    {
        m_Planet = planet;
        m_ShapeTex = shapeTex;

        m_Up = m_SUp = up;
        m_Front = m_SFront = front;
        m_Right = -Vector3.Cross(m_Up, m_Front);

        m_Parent = null;
        m_SplitLevel = 0;
        m_Size = m_Planet.m_Radius * 2;

        m_Neighbors[0].node = m_Neighbors[1].node = m_Neighbors[2].node = m_Neighbors[3].node = null;
        m_Neighbors[0].isFixed = m_Neighbors[1].isFixed = m_Neighbors[2].isFixed = m_Neighbors[3].isFixed = false;
        m_Children[0] = m_Children[1] = m_Children[2] = m_Children[3] = null;

        m_NeedsRejoinCount = 0;
        m_HasChildren = false;
        m_NeedsReedge = true;
        m_NeedsTerrain = true;
        m_GapFixMask = 15;

        m_NormalMapTex = null;

        GenVolume();

        m_Plane = new Plane(m_Volume.vertices[0], m_Volume.vertices[2], m_Volume.vertices[1]);
    }
	/// <summary>
	/// Draws and returns the value of a GUI.Button.
	/// </summary>
	/// <param name="pos">The position of the button as an interpolant between 0 and 1.</param>
	/// <returns>Whether the button was pressed.</returns>
	private bool MainScreenButton(Vector2 posLerp, Texture2D tex, ScreenPositioningData data)
	{
		return data.GUIButton(posLerp, Cellphone.MainScreen.ButtonSize,
							  new Vector2(Cellphone.MainScreen.ScreenBorder.x * data.ScreenSizeScale.x,
							 			  Cellphone.MainScreen.ScreenBorder.y * data.ScreenSizeScale.y),
							  Cellphone.ButtonStyle, tex);
	}
Exemple #16
0
 private Texture2D loadIcon(string path)
 {
     Texture2D result = new Texture2D(1, 1);
         result.LoadImage(System.IO.File.ReadAllBytes(PATH+path));
     result.Apply();
     return result;
 }
    void OnEnable()
    {
		displayManager = target as RUISDisplayManager;
		
        displays = serializedObject.FindProperty("displays");
		ruisMenuPrefab = serializedObject.FindProperty("ruisMenuPrefab");
		
		guiX = serializedObject.FindProperty("guiX");
		guiY = serializedObject.FindProperty("guiY");
		guiZ = serializedObject.FindProperty("guiZ");
		guiScaleX = serializedObject.FindProperty("guiScaleX");
		guiScaleY = serializedObject.FindProperty("guiScaleY");
		hideMouseOnPlay = serializedObject.FindProperty("hideMouseOnPlay");
		
		displayManagerLink = new SerializedObject(displayManager);
		guiDisplayChoiceLink = displayManagerLink.FindProperty("guiDisplayChoice");
		
//        allowResolutionDialog = serializedObject.FindProperty("allowResolutionDialog");
        displayPrefab = Resources.Load("RUIS/Prefabs/Main RUIS/RUISDisplay") as GameObject;

        displayBoxStyle = new GUIStyle();
        displayBoxStyle.normal.textColor = Color.white;
        displayBoxStyle.alignment = TextAnchor.MiddleCenter;
        displayBoxStyle.border = new RectOffset(2, 2, 2, 2);
        displayBoxStyle.margin = new RectOffset(1, 0, 0, 0);
        displayBoxStyle.wordWrap = true;

        monoDisplayTexture = Resources.Load("RUIS/Editor/Textures/monodisplay") as Texture2D;
        stereoDisplayTexture = Resources.Load("RUIS/Editor/Textures/stereodisplay") as Texture2D;
		
		menuCursorPrefab = serializedObject.FindProperty("menuCursorPrefab");
		menuLayer = serializedObject.FindProperty("menuLayer");
    }
Exemple #18
0
    void Start()
    {
        _img = (Texture2D)Resources.Load("bg1");
        _img2 = (Texture2D)Resources.Load("bg2");

        style = new GUIStyle();

        style.font = (Font)Resources.Load("Fonts/Arial");

        style.active.background = _img2; // not working
        style.hover.background = _img2; // not working
        style.normal.background = _img; // not working

        style.active.textColor = Color.red; // not working
        style.hover.textColor = Color.blue; // not working
        style.normal.textColor = Color.white;

        int border = 30;

        style.border.left = border; // not working, since backgrounds aren't showing
        style.border.right = border; // ---
        style.border.top = border; // ---
        style.border.bottom = border; // ---

        style.stretchWidth = true; // ---
        style.stretchHeight = true; // not working, since backgrounds aren't showing

        style.alignment = TextAnchor.MiddleCenter;
    }
    public void Resize( int _Width, int _Height )
    {
        m_Width = _Width;
        m_Height = _Height;

        if (m_Texture == null)
        {
            m_Texture = new Texture2D(m_Width, m_Height, TextureFormat.RGBA32, false);
        }
        else
        {
            m_Texture.Resize(m_Width, m_Height, TextureFormat.RGBA32, false);
            m_Texture.Apply(false, false);
        }
        //m_Texture.filterMode = FilterMode.Point;

        if (m_WebView != null)
        {
            m_WebView.Resize(m_Width, m_Height);
        }
        else
        {
            m_WebView = AwesomiumUnityWebCore.CreateWebView(m_Width, m_Height);
        }
    }
	void Update () 
	{
		if(manager && manager.IsInitialized())
		{
			foregroundTex = manager.GetUsersLblTex();
		}
	}
        public static Texture2D LoadTextureDXT( string path, TextureFormat format, bool mipmap = true )
        {
            var a = Path.Combine( GenFilePaths.CoreModsFolderPath, LoadedModManager.LoadedMods.ToList().Find( s => s.name == "LT_RedistHeat" ).name );
            var b = Path.Combine( a, "Textures" );
            var filePath = Path.Combine( b,  path + ".dds");
            var bytes = File.ReadAllBytes( filePath );

            if (format != TextureFormat.DXT1 && format != TextureFormat.DXT5)
                throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method.");

            var ddsSizeCheck = bytes[4];
            if (ddsSizeCheck != 124)
                throw new Exception("Invalid DDS DXT texture. Unable to read");  //this header byte should be 124 for DDS image files

            var height = bytes[13] * 256 + bytes[12];
            var width = bytes[17] * 256 + bytes[16];

            var dxtBytes = new byte[bytes.Length - DDSHeaderSize];
            Buffer.BlockCopy(bytes, DDSHeaderSize, dxtBytes, 0, bytes.Length - DDSHeaderSize);

            var texture = new Texture2D(width, height, format, mipmap);
            texture.LoadRawTextureData(dxtBytes);
            texture.Apply();

            return (texture);
        }
Exemple #22
0
	private void OnLargeImageLoaded(Texture2D image) {
		if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.large)) {
			profileImages.Add(FB_ProfileImageSize.large, image);
		}
		
		OnProfileImageLoaded(this);
	}
    /// <summary>
    /// Converts vector data stored within a texture using the specified basis.  Assume all calculations are performed in tangent space.
    /// </summary>
    /// <param name='basis'>
    /// Basis to multiply the vector values against.
    /// </param>
    /// <param name='vectorData'>
    /// Texture2D containing vector data.  Textures are passed by reference, so make sure to copy beforehand if you don't want to overwrite your data!
    /// </param>
    public static void ConvertTangentBasis(Matrix4x4 basis, ref Texture2D vectorData, bool recomputeZ = false)
    {
        Color[] colorData = vectorData.GetPixels();
        Texture2D tmpTexture = new Texture2D(vectorData.width, vectorData.height, TextureFormat.ARGB32, false);

        for (int i = 0; i < colorData.Length; i++)
        {
            Color vecData = new Color(colorData[i].r, colorData[i].g, colorData[i].b, 1);
            vecData.r = Vector3.Dot(new Vector3(basis.m00, basis.m01, basis.m02), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            vecData.g = Vector3.Dot(new Vector3(basis.m10, basis.m11, basis.m12), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            if (recomputeZ)
            {
                vecData.r = vecData.r * 2 - 1;
                vecData.g = vecData.g * 2 - 1;
                vecData.b = Mathf.Sqrt(1 - vecData.r * vecData.r - vecData.g * vecData.g) * 0.5f + 0.5f;
                vecData.r = vecData.r * 0.5f + 0.5f;
                vecData.g = vecData.g * 0.5f + 0.5f;
            } else {
                vecData.b = Vector3.Dot(new Vector3(basis.m20, basis.m21, basis.m22), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            }
            colorData[i] = vecData;
        }
        tmpTexture.SetPixels(colorData);
        tmpTexture.Apply();
        vectorData = tmpTexture;
    }
 // RimWorld.AreaAllowedGUI
 private static void DoZoneSelector( Rect rect, ref Zone_Stockpile zoneAllowed, Zone_Stockpile zone, Texture2D tex)
 {
     rect = rect.ContractedBy( 1f );
     GUI.DrawTexture( rect, tex );
     Text.Anchor = TextAnchor.MiddleLeft;
     string label = zone?.label ?? "Any stockpile";
     Rect innerRect = rect;
     innerRect.xMin += 3f;
     innerRect.yMin += 2f;
     Widgets.Label( innerRect, label );
     if( zoneAllowed == zone )
     {
         Widgets.DrawBox( rect, 2 );
     }
     if( Mouse.IsOver( rect ) )
     {
         if( zone != null )
         {
             if ( zone.AllSlotCellsList() != null && zone.AllSlotCellsList().Count > 0 )
                 Find.CameraDriver.JumpTo( zone.AllSlotCellsList().FirstOrDefault() );
         }
         if( Input.GetMouseButton( 0 ) &&
              zoneAllowed != zone )
         {
             zoneAllowed = zone;
             SoundDefOf.DesignateDragStandardChanged.PlayOneShotOnCamera();
         }
     }
     TooltipHandler.TipRegion( rect, label );
     Text.Anchor = TextAnchor.UpperLeft;
 }
Exemple #25
0
	private void OnNormalImageLoaded(Texture2D image) {
		if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.normal)) {
			profileImages.Add(FB_ProfileImageSize.normal, image);
		}
		
		OnProfileImageLoaded(this);
	}
Exemple #26
0
    public void setContent()
    {
        if(m_grassTex == null)
            m_grassTex = m_grassSkybox.GetComponent<GrassHandler>().GetDefaultTexs();

        if(m_grassThumbs == null){
            m_grassThumbs = m_grassSkybox.GetComponent<GrassHandler>().GetDefaultThumbs();
        }
        int i=0;
        if(m_grassThumbs.Length == m_grassTex.Length){
            int count = m_grassTex.Length;
            m_texArray = new Texture2D[count];
            Texture2D[] thumbsArray = new Texture2D[count];
            for(;i<count;i++){
                m_texArray[i] =(Texture2D) m_grassTex[i];
                thumbsArray[i] =(Texture2D) m_grassThumbs[i];
            }

            Texture2D grassTex;
            i=0;
            _matTexList = new GUIUpperList (1, 0, TextManager.GetText("Material"), "sousMenuOn", "sousMenuOff", this);
            _matTexList.setImgContent(m_texArray, thumbsArray);
            //_matTexList.display();
            visibility = true;
        }
    }
		public static bool LoadTexture2DLutFromImage( Texture2D texture, ToolSettings settings, out Texture2D lutTexture )
		{
			var width = settings.Resolution.TargetWidth;
			var height = settings.Resolution.TargetHeight;

			var size = settings.LUT.Size;
			var cols = settings.LUT.Columns;
			var rows = settings.LUT.Rows;

			var imageData = texture.GetPixels();

			var lutText = new Texture2D( size * size, size, TextureFormat.ARGB32, false );
			var lutData = new Color[ size * size * size ];


			for ( int h = 0, i = 0; h < size; h++ )
			{
				for ( int r = 0; r < rows; r++ )
				{
					for ( int w = 0; w < size * cols; w++ )
					{
						var x = w;
						var y = h + r * size;
						y = height - 1 - y;
						lutData[ i++ ] = imageData[ x + y * width ];
					}
				}
			}

			lutText.SetPixels( lutData );
			lutText.Apply();
			lutTexture = lutText;

			return true;
		}
Exemple #28
0
    // Use this for initialization
    void Start()
    {
        // カメラを列挙する
        // 使いたいカメラのインデックスをVideoIndexに入れる
        // 列挙はUnityで使うのはOpenCVだけど、インデックスは同じらしい
        var devices = WebCamTexture.devices;
        for ( int i = 0; i < devices.Length; i++ ) {
            print( string.Format( "index {0}:{1}", i, devices[i].name) );
        }

        // ビデオの設定
        video = new VideoCapture( VideoIndex );
        video.Set( CaptureProperty.FrameWidth, Width );
        video.Set( CaptureProperty.FrameHeight, Height );

        print( string.Format("{0},{1}", Width, Height) );

        // 顔検出器の作成
        cascade = new CascadeClassifier( Application.dataPath + @"/haarcascade_frontalface_alt.xml" );

        // テクスチャの作成
        texture = new Texture2D( Width, Height, TextureFormat.RGB24, false );
        renderer.material.mainTexture = texture;

        // 変換用のカメラの作成
        _Camera = GameObject.Find( Camera.name ).camera;
        print( string.Format( "({0},{1})({2},{3})", Screen.width, Screen.height, _Camera.pixelWidth, _Camera.pixelHeight ) );
    }
 public void SetSize(int w, int h)
 {
     Width = w;
     Height = h;
     Texture = new Texture2D(w, h, TextureFormat.RGB24, false);
     Texture.filterMode = FilterMode.Point;
 }
Exemple #30
0
 /// <summary>
 /// 获取某个索引的图片
 /// </summary>
 /// <param name="index">图片索引,从0开始</param>
 /// <returns>对应图片数据</returns>
 internal U3d.Texture2D this[uint index]
 {
     get
     {
         M2ImageInfo   ii     = ImageInfos[index];
         U3d.Texture2D result = new U3d.Texture2D(ii.Width, ii.Height);
         if (ii.Width == 0 && ii.Height == 0)
         {
             return(result);
         }
         byte[] pixels = null;
         lock (wzl_locker)
         {
             FS_wzl.Position = OffsetList[index] + 16;
             using (BinaryReader rwzl = new BinaryReader(FS_wzl))
             {
                 pixels = unzip(rwzl.ReadBytes(LengthList[index]));
             }
         }
         int p_index = 0;
         for (int h = 0; h < ii.Height; ++h)
         {
             for (int w = 0; w < ii.Width; ++w)
             {
                 // 跳过填充字节
                 if (w == 0)
                 {
                     p_index += Delphi.SkipBytes(8, ii.Width);
                 }
                 float[] pallete = Delphi.PALLETE[pixels[p_index++] & 0xff];
                 result.SetPixel(w, ii.Height - h, new U3d.Color(pallete[1], pallete[2], pallete[3], pallete[0]));
             }
         }
         result.Apply();
         return(result);
     }
 }
 static public int Resize(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(int), typeof(int), typeof(UnityEngine.TextureFormat), typeof(bool)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.TextureFormat a3;
             checkEnum(l, 4, out a3);
             System.Boolean a4;
             checkType(l, 5, out a4);
             System.Boolean ret = self.Resize(a1, a2, a3, a4);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, 2, typeof(int), typeof(int)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Boolean ret = self.Resize(a1, a2);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #32
0
 static public int ReadPixels(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(UnityEngine.Rect), typeof(System.Int32), typeof(System.Int32), typeof(System.Boolean)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Rect      a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Boolean a4;
             checkType(l, 5, out a4);
             self.ReadPixels(a1, a2, a3, a4);
             return(0);
         }
         else if (matchType(l, 2, typeof(UnityEngine.Rect), typeof(System.Int32), typeof(System.Int32)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Rect      a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             self.ReadPixels(a1, a2, a3);
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #33
0
 /// <summary>
 /// 获取某个索引的图片
 /// </summary>
 /// <param name="index">图片索引,从0开始</param>
 /// <returns>对应图片数据</returns>
 internal U3d.Texture2D this[uint index]
 {
     get
     {
         M2ImageInfo   ii     = ImageInfos[index];
         U3d.Texture2D result = new U3d.Texture2D(ii.Width, ii.Height);
         byte[]        pixels = null;
         lock (wis_locker)
         {
             FS_wis.Position = OffsetList[index];
             using (BinaryReader rwis = new BinaryReader(FS_wis))
             {
                 // 是否压缩(RLE)
                 byte compressFlag = rwis.ReadByte();
                 FS_wis.Position += 11;
                 pixels           = rwis.ReadBytes(LengthList[index] - 12);
                 if (compressFlag == 1)
                 {
                     // 需要解压
                     pixels = unpack(pixels, pixels.Length);
                 }
             }
         }
         int p_index = 0;
         for (int h = 0; h < ii.Height; ++h)
         {
             for (int w = 0; w < ii.Width; ++w)
             {
                 float[] pallete = Delphi.PALLETE[pixels[p_index++] & 0xff];
                 result.SetPixel(w, ii.Height - h, new U3d.Color(pallete[1], pallete[2], pallete[3], pallete[0]));
             }
         }
         result.Apply();
         return(result);
     }
 }
Exemple #34
0
 static public int CreateExternalTexture_s(IntPtr l)
 {
     try{
         System.Int32 a1;
         checkType(l, 1, out a1);
         System.Int32 a2;
         checkType(l, 2, out a2);
         UnityEngine.TextureFormat a3;
         checkEnum(l, 3, out a3);
         System.Boolean a4;
         checkType(l, 4, out a4);
         System.Boolean a5;
         checkType(l, 5, out a5);
         System.IntPtr a6;
         checkType(l, 6, out a6);
         UnityEngine.Texture2D ret = UnityEngine.Texture2D.CreateExternalTexture(a1, a2, a3, a4, a5, a6);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #35
0
        public static UnityTexture2D CreateTemporaryDuplicate(UnityTexture2D original, int width, int height)
        {
            if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original)
            {
                return(null);
            }

            RenderTexture save          = RenderTexture.active;
            var           savedViewport = ShaderUtil.rawViewportRect;

            RenderTexture tmp = RenderTexture.GetTemporary(
                width,
                height,
                0,
                RenderTextureFormat.Default,
                RenderTextureReadWrite.sRGB);

            Graphics.Blit(original, tmp, EditorGUIUtility.GUITextureBlit2SRGBMaterial);

            RenderTexture.active = tmp;

            // If the user system doesn't support this texture size, force it to use mipmap
            bool forceUseMipMap = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize;

            UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || forceUseMipMap);

            copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            copy.Apply();
            RenderTexture.ReleaseTemporary(tmp);

            EditorGUIUtility.SetRenderTextureNoViewport(save);
            ShaderUtil.rawViewportRect = savedViewport;

            copy.alphaIsTransparency = original.alphaIsTransparency;
            return(copy);
        }
Exemple #36
0
 static public int Apply(IntPtr l)
 {
     try{
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             self.Apply(a1, a2);
             return(0);
         }
         else if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             self.Apply(a1);
             return(0);
         }
         else if (argc == 1)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             self.Apply();
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #37
0
        public UnityEngine.Texture2D SaveTexture()
        {
            UnityEngine.Texture2D t = new UnityEngine.Texture2D(w, h, UnityEngine.TextureFormat.RGB24, false, true);
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    if (IsTransparent(i, j))
                    {
                        t.SetPixel(i, j, UnityEngine.Color.white);
                    }
                    else
                    {
                        t.SetPixel(i, j, UnityEngine.Color.blue);
                    }
                }
            }

            byte[] bytes = t.EncodeToPNG();
            global::System.IO.File.WriteAllBytes(UnityEngine.Application.dataPath + "/fogMap.png", bytes);
            UnityEngine.GameObject.DestroyImmediate(t);

            return(t);
        }
 static public int ReadPixels(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 4)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Rect      a1;
             checkValueType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             self.ReadPixels(a1, a2, a3);
             return(0);
         }
         else if (argc == 5)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Rect      a1;
             checkValueType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Boolean a4;
             checkType(l, 5, out a4);
             self.ReadPixels(a1, a2, a3, a4);
             return(0);
         }
         return(error(l, "No matched override function to call"));
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int Resize(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             var ret = self.Resize(a1, a2);
             pushValue(l, ret);
             return(1);
         }
         else if (argc == 5)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             UnityEngine.TextureFormat a3;
             checkEnum(l, 4, out a3);
             System.Boolean a4;
             checkType(l, 5, out a4);
             var ret = self.Resize(a1, a2, a3, a4);
             pushValue(l, ret);
             return(1);
         }
         return(error(l, "No matched override function to call"));
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #40
0
        internal void Register()
        {
            launcher    = launcher ?? (launcher = Asset.Texture2D.LoadFromFile(ICON_DIR, "ToolbarLargeIcon"));
            toolbar     = toolbar ?? (toolbar = Asset.Texture2D.LoadFromFile(ICON_DIR, "ToolbarSmallIcon"));
            this.button = Toolbar.Button.Create(this
                                                , ApplicationLauncher.AppScenes.VAB | ApplicationLauncher.AppScenes.SPH
                                                , launcher
                                                , toolbar
                                                , Version.FriendlyName
                                                );

            windowState = this.button.State.Controller.Create <WindowState>(
                new Dictionary <Toolbar.State.Status, Toolbar.State.Data> {
                { (WindowState)false, Toolbar.State.Data.Create(launcher, toolbar) }
                , { (WindowState)true, Toolbar.State.Data.Create(launcher, toolbar) }
            }
                );

            this.button.Mouse.Add(Toolbar.Button.MouseEvents.Kind.Left, this.Button_OnLeftClick);
            this.button.Mouse.Add(Toolbar.Button.MouseEvents.Kind.Right, this.Button_OnRightClick);
            this.controller.Add(this.button);
            this.controller.ButtonsActive(true, true);
            this.IsRegistered = true;
        }
Exemple #41
0
        public void ManagedComponentWithObjectReferenceSerialize()
        {
            for (int i = 0; i != 20; i++)
            {
                var e1 = m_Manager.CreateEntity();

                UnityEngine.Texture2D tex    = new UnityEngine.Texture2D(i + 1, i + 1);
                var expectedManagedComponent = new ManagedComponentWithObjectReference {
                    Texture = tex
                };

                m_Manager.AddComponentData(e1, expectedManagedComponent);
            }

            var writer = new TestBinaryWriter();
            ReferencedUnityObjects objRefs = null;

            SerializeUtilityHybrid.Serialize(m_Manager, writer, out objRefs);

            var world  = new World("temp");
            var reader = new TestBinaryReader(writer);

            SerializeUtilityHybrid.Deserialize(world.EntityManager, reader, objRefs);

            var newWorldEntities = world.EntityManager;

            {
                var entities = newWorldEntities.GetAllEntities();
                Assert.AreEqual(20, entities.Length);

                var seenWidths  = new NativeArray <bool>(entities.Length, Allocator.Temp);
                var seenHeights = new NativeArray <bool>(entities.Length, Allocator.Temp);
                for (int i = 0; i < entities.Length; ++i)
                {
                    var e = entities[i];

                    var actualManagedComponent = newWorldEntities.GetComponentData <ManagedComponentWithObjectReference>(e);
                    Assert.NotNull(actualManagedComponent);
                    var tex = actualManagedComponent.Texture;
                    seenWidths[tex.width - 1]   = true;
                    seenHeights[tex.height - 1] = true;
                }

                for (int i = 0; i < entities.Length; ++i)
                {
                    Assert.IsTrue(seenWidths[i]);
                    Assert.IsTrue(seenHeights[i]);
                }

                seenWidths.Dispose();
                seenHeights.Dispose();

                for (int i = 0; i != 20; i++)
                {
                    newWorldEntities.DestroyEntity(entities[i]);
                }

                entities.Dispose();
            }

            Assert.IsTrue(newWorldEntities.Debug.IsSharedComponentManagerEmpty());

            world.Dispose();
            reader.Dispose();
        }
Exemple #42
0
        protected override void Serialize(UnityEngine.Object sourceAsset)
        {
            this.texture = sourceAsset as UnityEngine.Texture2D;
            //先把原始图片导出来
            this.ExportTexture();

            var path   = PathHelper.GetTexturePath(this.texture);
            var mipmap = this.texture.mipmapCount > 1;
            //
            {
                this._root.Images.Add(new Image()
                {
                    Uri = ExportSetting.instance.GetExportPath(path)
                });
            }
            //
            {
                var filterMode = this.texture.filterMode;
                var wrapMode   = this.texture.wrapMode;

                var sampler = new Sampler();
                this._root.Samplers.Add(sampler);
                if (wrapMode == TextureWrapMode.Repeat)
                {
                    sampler.WrapS = GLTF.Schema.WrapMode.Repeat;
                    sampler.WrapT = GLTF.Schema.WrapMode.Repeat;
                }
                else
                {
                    sampler.WrapS = GLTF.Schema.WrapMode.ClampToEdge;
                    sampler.WrapT = GLTF.Schema.WrapMode.ClampToEdge;
                }
                sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
                if (!mipmap)
                {
                    sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
                }
                else if (filterMode == FilterMode.Point)
                {
                    sampler.MinFilter = MinFilterMode.NearestMipmapNearest;
                }
                else if (filterMode == FilterMode.Bilinear)
                {
                    sampler.MinFilter = MinFilterMode.LinearMipmapNearest;
                }
                else if (filterMode == FilterMode.Trilinear)
                {
                    sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
                }
            }
            //
            {
                var gltfTexture = new GLTF.Schema.Texture();
                this._root.Textures.Add(gltfTexture);

                gltfTexture.Sampler    = new SamplerId();
                gltfTexture.Source     = new ImageId();
                gltfTexture.Extensions = new Dictionary <string, IExtension>()
                {
                    {
                        TextureExtension.EXTENSION_NAME,
                        new TextureExtension()
                        {
                            anisotropy = this.texture.anisoLevel,
                            format     = GetTextureFormat(),
                            levels     = mipmap ? 0 : 1
                        }
                    }
                };
            }
        }
Exemple #43
0
 public PreviewTexture2D(UnityTexture2D t, int width, int height)
     : base(t)
 {
     m_ActualWidth  = width;
     m_ActualHeight = height;
 }
    static int _CreateUnityEngine_Texture2D(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2)
            {
                int arg0 = (int)LuaDLL.luaL_checkinteger(L, 1);
                int arg1 = (int)LuaDLL.luaL_checkinteger(L, 2);
                UnityEngine.Texture2D obj = new UnityEngine.Texture2D(arg0, arg1);
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else if (count == 4 && TypeChecker.CheckTypes <UnityEngine.TextureFormat, bool>(L, 3))
            {
                int arg0 = (int)LuaDLL.luaL_checkinteger(L, 1);
                int arg1 = (int)LuaDLL.luaL_checkinteger(L, 2);
                UnityEngine.TextureFormat arg2 = (UnityEngine.TextureFormat)ToLua.ToObject(L, 3);
                bool arg3 = LuaDLL.lua_toboolean(L, 4);
                UnityEngine.Texture2D obj = new UnityEngine.Texture2D(arg0, arg1, arg2, arg3);
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else if (count == 4 && TypeChecker.CheckTypes <UnityEngine.Experimental.Rendering.DefaultFormat, UnityEngine.Experimental.Rendering.TextureCreationFlags>(L, 3))
            {
                int arg0 = (int)LuaDLL.luaL_checkinteger(L, 1);
                int arg1 = (int)LuaDLL.luaL_checkinteger(L, 2);
                UnityEngine.Experimental.Rendering.DefaultFormat        arg2 = (UnityEngine.Experimental.Rendering.DefaultFormat)ToLua.ToObject(L, 3);
                UnityEngine.Experimental.Rendering.TextureCreationFlags arg3 = (UnityEngine.Experimental.Rendering.TextureCreationFlags)ToLua.ToObject(L, 4);
                UnityEngine.Texture2D obj = new UnityEngine.Texture2D(arg0, arg1, arg2, arg3);
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else if (count == 4 && TypeChecker.CheckTypes <UnityEngine.Experimental.Rendering.GraphicsFormat, UnityEngine.Experimental.Rendering.TextureCreationFlags>(L, 3))
            {
                int arg0 = (int)LuaDLL.luaL_checkinteger(L, 1);
                int arg1 = (int)LuaDLL.luaL_checkinteger(L, 2);
                UnityEngine.Experimental.Rendering.GraphicsFormat       arg2 = (UnityEngine.Experimental.Rendering.GraphicsFormat)ToLua.ToObject(L, 3);
                UnityEngine.Experimental.Rendering.TextureCreationFlags arg3 = (UnityEngine.Experimental.Rendering.TextureCreationFlags)ToLua.ToObject(L, 4);
                UnityEngine.Texture2D obj = new UnityEngine.Texture2D(arg0, arg1, arg2, arg3);
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else if (count == 5)
            {
                int arg0 = (int)LuaDLL.luaL_checkinteger(L, 1);
                int arg1 = (int)LuaDLL.luaL_checkinteger(L, 2);
                UnityEngine.TextureFormat arg2 = (UnityEngine.TextureFormat)ToLua.CheckObject(L, 3, TypeTraits <UnityEngine.TextureFormat> .type);
                bool arg3 = LuaDLL.luaL_checkboolean(L, 4);
                bool arg4 = LuaDLL.luaL_checkboolean(L, 5);
                UnityEngine.Texture2D obj = new UnityEngine.Texture2D(arg0, arg1, arg2, arg3, arg4);
                ToLua.PushSealed(L, obj);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.Texture2D.New"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
            // Build voxel object
            public virtual float Build(Storage voxels, Bounds bounds)
            {
                // Check for given array
                if (voxels != null)
                {
                    if (!building)
                    {
                        int existingIndex;
                        int x, y, z;

                        // Get iterator
                        if (iterator == null)
                        {
                            iterator        = voxels.GetIterator();
                            currentIndex    = 0;
                            currentProgress = 0;
                        }

                        if (colorAssignments == null)
                        {
                            // Create empty list to color assignments to
                            colorAssignments = new Dictionary <Color, int>();
                        }
                        else
                        {
                            // Get current color index from existing hash map
                            currentIndex = colorAssignments.Count;
                        }

                        // Process voxels in steps
                        for (int number = 0; number < 256; ++number)
                        {
                            // Retrieve color and coordinate for current cell
                            Color color = iterator.GetNextColor(out x, out y, out z);

                            // Check for valid voxel
                            if (color.a > 0)
                            {
                                // Add assignment between color and vertex index, if it is not already included
                                if (!colorAssignments.TryGetValue(color, out existingIndex))
                                {
                                    colorAssignments.Add(color, currentIndex++);
                                }
                            }
                            else
                            {
                                iterator = null;
                                break;
                            }
                        }

                        // Return current progress when building has not been finished
                        if (iterator != null)
                        {
                            return(currentProgress = (float)iterator.Number / (float)(voxels.Count + 1) * 0.5f);
                        }
                        else
                        {
                            building = true;
                            texture  = null;
                        }
                    }

                    if (colorAssignments != null)
                    {
                        CoordinateAssignment assignment;
                        int column = 0, line = 0;

                        // Compute resolution to fit all voxels into a 2D surface
                        int textureWidth  = (int)Math.Pow(2, Math.Ceiling(Math.Log(Math.Sqrt(colorAssignments.Count)) / Math.Log(2)));
                        int textureHeight = (int)Math.Ceiling((double)colorAssignments.Count / (double)textureWidth);

                        // Make height 2^n, too, if flag is set
                        if (powerOfTwo)
                        {
                            textureHeight = (int)Math.Pow(2, Math.Ceiling(Math.Log((float)textureHeight) / Math.Log(2)));
                        }

                        //// Change resolution, if current does not match the required resolution
                        //if (texture != null && ((texture.width != textureWidth) || (texture.height != textureHeight)))
                        //{
                        //    try
                        //    {
                        //        texture.Resize(textureWidth, textureHeight, TextureFormat.ARGB32, false);

                        //        // Fill texture and calculate texture coordinates
                        //        foreach (KeyValuePair<Color, int> currentPixel in colorAssignments)
                        //        {
                        //            texture.SetPixel(column = currentPixel.Value % texture.width, line = currentPixel.Value / texture.width, currentPixel.Key);
                        //        }

                        //        iterator = null;
                        //    }
                        //    catch (System.Exception)
                        //    {
                        //        texture = null;
                        //    }
                        //}

                        if (texture == null)
                        {
                            if (textureWidth != 0 && textureHeight != 0)
                            {
                                // Create new texture instance
                                texture = new UnityEngine.Texture2D(textureWidth, textureHeight, TextureFormat.ARGB32, false);
                                if (texture != null)
                                {
                                    texture.filterMode = FilterMode.Point;
                                    texture.wrapMode   = TextureWrapMode.Clamp;
                                }
                            }

                            iterator = null;
                        }

                        if (texture != null)
                        {
                            // Check for non-empty array
                            if (voxels.Count > 0)
                            {
                                // Get iterator
                                if (iterator == null)
                                {
                                    iterator        = voxels.GetIterator();
                                    currentIndex    = 0;
                                    currentProgress = 0;

                                    // Create array to store coordinates to
                                    coordinateAssignments = new CoordinateAssignment[voxels.Count];
                                }

                                // Process voxels in steps
                                for (int number = 0; number < texture.width; ++number)
                                {
                                    // Retrieve color and coordinate for current cell
                                    int   index = iterator.Number;
                                    Color color = iterator.GetNextColor(out assignment.source.x, out assignment.source.y, out assignment.source.z);

                                    // Check for valid voxel
                                    if (color.a > 0)
                                    {
                                        // Get index for current color
                                        if (colorAssignments.TryGetValue(color, out currentIndex))
                                        {
                                            // Store color as pixel
                                            texture.SetPixel(column = currentIndex % texture.width, line = currentIndex / texture.width, color);

                                            // Calculate coordinate for center of the current texel
                                            assignment.target.x = ((float)column + 0.5f) / (float)texture.width;
                                            assignment.target.y = ((float)line + 0.5f) / (float)texture.height;

                                            // Store assigned coordinates to array
                                            coordinateAssignments[index] = assignment;
                                        }
                                    }
                                    else
                                    {
                                        iterator = null;
                                        break;
                                    }
                                }

                                // Return current progress when building has not been finished
                                if (iterator != null)
                                {
                                    return(currentProgress = (float)iterator.Number / (float)(voxels.Count + 1) * 0.5f + 0.5f);
                                }

                                // Unset remaining texels
                                for (column = colorAssignments.Count % texture.width, line = colorAssignments.Count / texture.width; line < texture.height; ++line)
                                {
                                    for (; column < texture.width; ++column)
                                    {
                                        texture.SetPixel(column, line, Color.clear);
                                    }

                                    column = 0;
                                }
                            }
                        }
                    }
                }

                // Check for texture and color array
                if (texture != null)
                {
                    // Apply color changes on texture
                    texture.Apply();
                }

                // Reset current processing data
                currentIndex     = 0;
                iterator         = null;
                colorAssignments = null;
                building         = false;

                return(currentProgress = 1);
            }
 public void Serialize(string inKey, ref SerializedType ioData, TextureOptions inTextureOptions = TextureOptions.Default, FieldOptions inOptions = FieldOptions.None)
 {
     DoSerializeUnity <SerializedType>(inKey, ref ioData, inOptions, Read_Texture2D, GetTextureWriter(inTextureOptions));
 }
 /// <summary>
 /// Read the data using the reader.
 /// </summary>
 /// <param name="reader">Reader.</param>
 public override object Read(ISaveGameReader reader)
 {
     UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(0, 0);
     ReadInto(texture2D, reader);
     return(texture2D);
 }
        /// <summary>
        /// Read the data into the specified value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="reader">Reader.</param>
        public override void ReadInto(object value, ISaveGameReader reader)
        {
            UnityEngine.Texture2D texture2D = (UnityEngine.Texture2D)value;
            foreach (string property in reader.Properties)
            {
                switch (property)
                {
                case "width":
                    reader.ReadProperty <System.Int32>();
                    break;

                case "height":
                    reader.ReadProperty <System.Int32>();
                    break;

                case "rawTextureData":
                    texture2D.LoadImage(reader.ReadProperty <byte[]>());
                    texture2D.Apply();
                    break;

                case "dimension":
                    reader.ReadProperty <UnityEngine.Rendering.TextureDimension>();
                    break;

                case "filterMode":
                    texture2D.filterMode = reader.ReadProperty <UnityEngine.FilterMode>();
                    break;

                case "anisoLevel":
                    texture2D.anisoLevel = reader.ReadProperty <System.Int32>();
                    break;

                case "wrapMode":
                    texture2D.wrapMode = reader.ReadProperty <UnityEngine.TextureWrapMode>();
                    break;

                case "wrapModeU":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeU = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "wrapModeV":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeV = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "wrapModeW":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeW = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "mipMapBias":
                    texture2D.mipMapBias = reader.ReadProperty <System.Single>();
                    break;

                case "name":
                    texture2D.name = reader.ReadProperty <System.String>();
                    break;

                case "hideFlags":
                    texture2D.hideFlags = reader.ReadProperty <UnityEngine.HideFlags>();
                    break;
                }
            }
        }
    static int Create(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 3)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                UnityEngine.Sprite  o    = UnityEngine.Sprite.Create(arg0, arg1, arg2);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 4)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                float arg3           = (float)LuaDLL.luaL_checknumber(L, 4);
                UnityEngine.Sprite o = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 5)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                float arg3           = (float)LuaDLL.luaL_checknumber(L, 4);
                uint  arg4           = (uint)LuaDLL.luaL_checknumber(L, 5);
                UnityEngine.Sprite o = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 6)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                float arg3 = (float)LuaDLL.luaL_checknumber(L, 4);
                uint  arg4 = (uint)LuaDLL.luaL_checknumber(L, 5);
                UnityEngine.SpriteMeshType arg5 = (UnityEngine.SpriteMeshType)ToLua.CheckObject(L, 6, typeof(UnityEngine.SpriteMeshType));
                UnityEngine.Sprite         o    = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4, arg5);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 7)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                float arg3 = (float)LuaDLL.luaL_checknumber(L, 4);
                uint  arg4 = (uint)LuaDLL.luaL_checknumber(L, 5);
                UnityEngine.SpriteMeshType arg5 = (UnityEngine.SpriteMeshType)ToLua.CheckObject(L, 6, typeof(UnityEngine.SpriteMeshType));
                UnityEngine.Vector4        arg6 = ToLua.ToVector4(L, 7);
                UnityEngine.Sprite         o    = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 8)
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                UnityEngine.Rect      arg1 = StackTraits <UnityEngine.Rect> .Check(L, 2);

                UnityEngine.Vector2 arg2 = ToLua.ToVector2(L, 3);
                float arg3 = (float)LuaDLL.luaL_checknumber(L, 4);
                uint  arg4 = (uint)LuaDLL.luaL_checknumber(L, 5);
                UnityEngine.SpriteMeshType arg5 = (UnityEngine.SpriteMeshType)ToLua.CheckObject(L, 6, typeof(UnityEngine.SpriteMeshType));
                UnityEngine.Vector4        arg6 = ToLua.ToVector4(L, 7);
                bool arg7            = LuaDLL.luaL_checkboolean(L, 8);
                UnityEngine.Sprite o = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Sprite.Create"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemple #50
0
    /// <summary>
    /// 合并图片
    /// </summary>
    /// <param name="filePaths"></param>
    /// <param name="texPath"></param>
    private static void CombineTexture(string[] filePaths, string texPath)
    {
        if (filePaths == null || filePaths.Length <= 0)
        {
            return;
        }

        m_IconDic.Clear();
        // 自适应图集大小
        int sqrt = (int)(Mathf.Sqrt(filePaths.Length));

        if (filePaths.Length - sqrt * sqrt > 0)
        {
            ++sqrt;
        }
        int count = 1;

        while (count < sqrt)
        {
            count *= 2;
        }
        int size = count * ICON_SIZE;
        var tex  = CreateTexture2D(size, size);

        // 将散图写入整图中,从上往下,从左往右
        int widthOffset  = 0;
        int heightOffset = size - ICON_SIZE;    //左下角为0,0

        for (int i = 0; i < filePaths.Length; i++)
        {
            int start = filePaths[i].IndexOf("Assets/");
            if (start < 0)
            {
                continue;
            }
            UnityTexture2D texture = AssetDatabase.LoadAssetAtPath <UnityTexture2D>(filePaths[i].Substring(start, filePaths[i].Length - start));
            if (texture == null)
            {
                continue;
            }
            m_IconDic[i] = texture.name;
            //var temp = CreateTemporaryDuplicate(texs[i], ICON_SIZE, ICON_SIZE, RenderTextureFormat.ARGB32);
            if (texture.isReadable == false)
            {
                Debug.LogError("isReadable == false", texture);
                continue;
            }

            var temp = texture;
            if (widthOffset + ICON_SIZE > size)
            {
                heightOffset -= ICON_SIZE;
                widthOffset   = 0;
            }
            for (int w = 0; w < temp.width; w++)
            {
                for (int h = 0; h < temp.height; h++)
                {
                    Color color = temp.GetPixel(w, h);
                    tex.SetPixel(w + widthOffset, h + heightOffset, color);
                }
            }
            widthOffset += ICON_SIZE;
        }
        tex.Apply();

        int    index    = texPath.Replace("\\", "/").LastIndexOf('/') + 1;
        string savePath = texPath.Substring(index, texPath.Length - index);
        var    dirPath  = Path.Combine(Directory.GetCurrentDirectory(), savePath);

        if (Directory.Exists(dirPath) == false)
        {
            Directory.CreateDirectory(dirPath);
        }
        File.WriteAllBytes(texPath, tex.EncodeToPNG());

        AssetDatabase.Refresh();

        // 修改Android和iOS的图片格式
        TextureImporter importer = AssetImporter.GetAtPath(texPath) as TextureImporter;
        TextureImporterPlatformSettings iphone = new TextureImporterPlatformSettings()
        {
            name           = "iPhone",
            overridden     = true,
            maxTextureSize = 2048,
            format         = importer.DoesSourceTextureHaveAlpha() ? TextureImporterFormat.ASTC_RGBA_5x5 : TextureImporterFormat.ASTC_RGB_5x5,
        };

        importer.SetPlatformTextureSettings(iphone);
        TextureImporterPlatformSettings android = new TextureImporterPlatformSettings()
        {
            name           = "Android",
            overridden     = true,
            maxTextureSize = 2048,
            format         = importer.DoesSourceTextureHaveAlpha() ? TextureImporterFormat.ETC2_RGBA8 : TextureImporterFormat.ETC_RGB4,
        };

        importer.SetPlatformTextureSettings(android);

        importer.textureType = TextureImporterType.Sprite;
        // 修改模式为Multiple,才能使用裁剪
        importer.spriteImportMode = SpriteImportMode.Multiple;
        AssetDatabase.ImportAsset(texPath);
    }
Exemple #51
0
 public void SetPreviewTexture(UnityTexture2D texture, int width, int height)
 {
     m_Texture        = new PreviewTexture2D(texture, width, height);
     m_Zoom           = -1;
     m_ScrollPosition = Vector2.zero;
 }
Exemple #52
0
 static public int GetPixels(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 6)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             System.Int32 a5;
             checkType(l, 6, out a5);
             var ret = self.GetPixels(a1, a2, a3, a4, a5);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 5)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             var ret = self.GetPixels(a1, a2, a3, a4);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             var ret = self.GetPixels(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 1)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             var ret = self.GetPixels();
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #53
0
 static public int SetPixels32(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 7)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             UnityEngine.Color32[] a5;
             checkArray(l, 6, out a5);
             System.Int32 a6;
             checkType(l, 7, out a6);
             self.SetPixels32(a1, a2, a3, a4, a5, a6);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 6)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Int32          a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             UnityEngine.Color32[] a5;
             checkArray(l, 6, out a5);
             self.SetPixels32(a1, a2, a3, a4, a5);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Color32[] a1;
             checkArray(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             self.SetPixels32(a1, a2);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             UnityEngine.Color32[] a1;
             checkArray(l, 2, out a1);
             self.SetPixels32(a1);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 private void Write_Texture2DJPG(ref SerializedType ioData)
 {
     byte[] png = ioData.EncodeToJPG();
     Write_ByteArray(ref png);
 }
Exemple #55
0
    static int Create(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(UnityEngine.Vector2)))
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                UnityEngine.Rect      arg1 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                UnityEngine.Vector2   arg2 = ToLua.ToVector2(L, 3);
                UnityEngine.Sprite    o    = UnityEngine.Sprite.Create(arg0, arg1, arg2);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(UnityEngine.Vector2), typeof(float)))
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                UnityEngine.Rect      arg1 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                UnityEngine.Vector2   arg2 = ToLua.ToVector2(L, 3);
                float arg3           = (float)LuaDLL.lua_tonumber(L, 4);
                UnityEngine.Sprite o = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 5 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(UnityEngine.Vector2), typeof(float), typeof(uint)))
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                UnityEngine.Rect      arg1 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                UnityEngine.Vector2   arg2 = ToLua.ToVector2(L, 3);
                float arg3           = (float)LuaDLL.lua_tonumber(L, 4);
                uint  arg4           = (uint)LuaDLL.lua_tonumber(L, 5);
                UnityEngine.Sprite o = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 6 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(UnityEngine.Vector2), typeof(float), typeof(uint), typeof(UnityEngine.SpriteMeshType)))
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                UnityEngine.Rect      arg1 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                UnityEngine.Vector2   arg2 = ToLua.ToVector2(L, 3);
                float arg3 = (float)LuaDLL.lua_tonumber(L, 4);
                uint  arg4 = (uint)LuaDLL.lua_tonumber(L, 5);
                UnityEngine.SpriteMeshType arg5 = (UnityEngine.SpriteMeshType)ToLua.ToObject(L, 6);
                UnityEngine.Sprite         o    = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4, arg5);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 7 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(UnityEngine.Rect), typeof(UnityEngine.Vector2), typeof(float), typeof(uint), typeof(UnityEngine.SpriteMeshType), typeof(UnityEngine.Vector4)))
            {
                UnityEngine.Texture2D arg0 = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                UnityEngine.Rect      arg1 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                UnityEngine.Vector2   arg2 = ToLua.ToVector2(L, 3);
                float arg3 = (float)LuaDLL.lua_tonumber(L, 4);
                uint  arg4 = (uint)LuaDLL.lua_tonumber(L, 5);
                UnityEngine.SpriteMeshType arg5 = (UnityEngine.SpriteMeshType)ToLua.ToObject(L, 6);
                UnityEngine.Vector4        arg6 = ToLua.ToVector4(L, 7);
                UnityEngine.Sprite         o    = UnityEngine.Sprite.Create(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
                ToLua.Push(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Sprite.Create"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
        protected virtual void CreateUnityMaterial(GLTF.Schema.Material def, int materialIndex)
        {
            Extension specularGlossinessExtension = null;
            bool      isSpecularPBR = def.Extensions != null && def.Extensions.TryGetValue("KHR_materials_pbrSpecularGlossiness", out specularGlossinessExtension);

            Shader shader = isSpecularPBR ? Shader.Find("Standard (Specular setup)") : Shader.Find("Standard");

            var material = new UnityEngine.Material(shader);

            material.hideFlags = HideFlags.DontUnloadUnusedAsset;             // Avoid material to be deleted while being built
            material.name      = def.Name;

            //Transparency
            if (def.AlphaMode == AlphaMode.MASK)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Cutout);
                material.SetFloat("_Mode", 1);
                material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
            }
            else if (def.AlphaMode == AlphaMode.BLEND)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Fade);
                material.SetFloat("_Mode", 3);
            }

            if (def.NormalTexture != null)
            {
                var       texture       = def.NormalTexture.Index.Id;
                Texture2D normalTexture = getTexture(texture) as Texture2D;

                //Automatically set it to normal map
                TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(normalTexture)) as TextureImporter;
                im.textureType = TextureImporterType.NormalMap;
                im.SaveAndReimport();
                material.SetTexture("_BumpMap", getTexture(texture));
                material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
            }

            if (def.EmissiveTexture != null)
            {
                material.EnableKeyword("EMISSION_MAP_ON");
                var texture = def.EmissiveTexture.Index.Id;
                material.SetTexture("_EmissionMap", getTexture(texture));
                material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
            }

            // PBR channels
            if (specularGlossinessExtension != null)
            {
                KHR_materials_pbrSpecularGlossinessExtension pbr = (KHR_materials_pbrSpecularGlossinessExtension)specularGlossinessExtension;
                material.SetColor("_Color", pbr.DiffuseFactor.ToUnityColor().gamma);
                if (pbr.DiffuseTexture != null)
                {
                    var texture = pbr.DiffuseTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                if (pbr.SpecularGlossinessTexture != null)
                {
                    var texture = pbr.SpecularGlossinessTexture.Index.Id;
                    material.SetTexture("_SpecGlossMap", getTexture(texture));
                    material.SetFloat("_GlossMapScale", (float)pbr.GlossinessFactor);
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }
                else
                {
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }

                Vector3 specularVec3 = pbr.SpecularFactor.ToUnityVector3();
                material.SetColor("_SpecColor", new Color(specularVec3.x, specularVec3.y, specularVec3.z, 1.0f));

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index.Id;
                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                    material.SetTexture("_OcclusionMap", getTexture(texture));
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Specular);
            }
            else if (def.PbrMetallicRoughness != null)
            {
                var pbr = def.PbrMetallicRoughness;

                material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor().gamma);
                if (pbr.BaseColorTexture != null)
                {
                    var texture = pbr.BaseColorTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                material.SetFloat("_Metallic", (float)pbr.MetallicFactor);
                material.SetFloat("_Glossiness", 1.0f - (float)pbr.RoughnessFactor);

                if (pbr.MetallicRoughnessTexture != null)
                {
                    var texture = pbr.MetallicRoughnessTexture.Index.Id;
                    UnityEngine.Texture2D inputTexture  = getTexture(texture) as Texture2D;
                    List <Texture2D>      splitTextures = splitMetalRoughTexture(inputTexture, def.OcclusionTexture != null, (float)pbr.MetallicFactor, (float)pbr.RoughnessFactor);
                    material.SetTexture("_MetallicGlossMap", splitTextures[0]);

                    if (def.OcclusionTexture != null)
                    {
                        material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                        material.SetTexture("_OcclusionMap", splitTextures[1]);
                    }
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Metallic);
            }

            material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor().gamma);
            material = _assetManager.saveMaterial(material, materialIndex);
            _assetManager._parsedMaterials.Add(material);
            material.hideFlags = HideFlags.None;
        }
 /// <summary>
 /// Call this to capture a screenshot Automatic size
 /// </summary>
 /// <returns></returns>
 public static byte[] CaptureScreenshot()
 {
     UnityEngine.Texture2D textured = new UnityEngine.Texture2D(UnityEngine.Screen.width, UnityEngine.Screen.height, UnityEngine.TextureFormat.RGB24, false, false);
     textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)UnityEngine.Screen.width, (float)UnityEngine.Screen.height), 0, 0);
     return(textured.EncodeToPNG());
 }
Exemple #58
0
 public TextureInfoWrapper(UrlDir.UrlFile file, UnityEngine.Texture2D newTex, bool nrmMap, bool readable, bool compress)
     : base(file, newTex, nrmMap, readable, compress)
 {
 }
        public UnityEngine.Material GenerateMaterial(Schema.Material gltfMaterial, Schema.Texture[] textures, Texture2D[] images, List <UnityEngine.Object> additionalResources)
        {
            var material = Material.Instantiate <Material>(GetDefaultMaterial());

            material.name = gltfMaterial.name;

            material.mainTextureScale  = TEXTURE_SCALE;
            material.mainTextureOffset = TEXTURE_OFFSET;

            //added support for KHR_materials_pbrSpecularGlossiness
            if (gltfMaterial.extensions != null)
            {
                Schema.PbrSpecularGlossiness specGloss = gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness;
                if (specGloss != null)
                {
                    if (!specularSetupShader)
                    {
                        specularSetupShader = Shader.Find("Standard (Specular setup)");
                    }
                    material.shader = specularSetupShader;
                    var diffuseTexture = GetTexture(specGloss.diffuseTexture, textures, images);
                    if (diffuseTexture != null)
                    {
                        material.mainTexture = diffuseTexture;
                    }
                    else
                    {
                        material.color = specGloss.diffuseColor;
                    }
                    var specGlossTexture = GetTexture(specGloss.specularGlossinessTexture, textures, images);
                    if (specGlossTexture != null)
                    {
                        material.SetTexture(StandardShaderHelper.specGlossMapPropId, specGlossTexture);
                        material.EnableKeyword("_SPECGLOSSMAP");
                    }
                    else
                    {
                        material.SetVector(StandardShaderHelper.specColorPropId, specGloss.specularColor);
                        material.SetFloat(StandardShaderHelper.glossinessPropId, (float)specGloss.glossinessFactor);
                    }
                }

                Schema.MaterialUnlit unlitMaterial = gltfMaterial.extensions.KHR_materials_unlit;
                if (unlitMaterial != null)
                {
                    if (gltfMaterial.pbrMetallicRoughness != null)
                    {
                        if (!unlitShader)
                        {
                            unlitShader = Shader.Find("Unlit/Color");
                        }
                        material.shader = unlitShader;
                    }
                }
            }

            if (gltfMaterial.pbrMetallicRoughness != null)
            {
                material.color = gltfMaterial.pbrMetallicRoughness.baseColor;
                material.SetFloat(StandardShaderHelper.metallicPropId, gltfMaterial.pbrMetallicRoughness.metallicFactor);
                material.SetFloat(StandardShaderHelper.glossinessPropId, 1 - gltfMaterial.pbrMetallicRoughness.roughnessFactor);

                var mainTxt = GetTexture(gltfMaterial.pbrMetallicRoughness.baseColorTexture, textures, images);
                if (mainTxt != null)
                {
                    mainTxt.wrapMode     = TextureWrapMode.Clamp;
                    material.mainTexture = mainTxt;
                }

                var metallicRoughnessTxt = GetTexture(gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture, textures, images);
                if (metallicRoughnessTxt != null)
                {
                    Profiler.BeginSample("ConvertMetallicRoughnessTexture");
                    // todo: Avoid this conversion by switching to a shader that accepts the given layout.
                    Debug.LogWarning("Convert MetallicRoughnessTexture structure to fit Unity Standard Shader (slow operation).");
                    var newmrt = new UnityEngine.Texture2D(metallicRoughnessTxt.width, metallicRoughnessTxt.height);
#if DEBUG
                    newmrt.name = string.Format("{0}_metal_smooth", metallicRoughnessTxt.name);
#endif
                    var buf = metallicRoughnessTxt.GetPixels32();
                    for (int i = 0; i < buf.Length; i++)
                    {
                        // TODO: Reassure given space (linear) is correct (no gamma conversion needed).
                        var color = buf[i];
                        color.a = (byte)(255 - color.g);
                        color.r = color.g = color.b;
                        buf[i]  = color;
                    }
                    newmrt.SetPixels32(buf);
                    newmrt.Apply();
                    Profiler.EndSample();

                    material.SetTexture(StandardShaderHelper.metallicGlossMapPropId, newmrt);
                    material.EnableKeyword("_METALLICGLOSSMAP");

                    additionalResources.Add(newmrt);
                }
            }

            var normalTxt = GetTexture(gltfMaterial.normalTexture, textures, images);
            if (normalTxt != null)
            {
                material.SetTexture(StandardShaderHelper.bumpMapPropId, normalTxt);
                material.EnableKeyword("_NORMALMAP");
            }

            var occlusionTxt = GetTexture(gltfMaterial.occlusionTexture, textures, images);
            if (occlusionTxt != null)
            {
                Profiler.BeginSample("ConvertOcclusionTexture");
                // todo: Avoid this conversion by switching to a shader that accepts the given layout.
                Debug.LogWarning("Convert OcclusionTexture structure to fit Unity Standard Shader (slow operation).");
                var newOcclusionTxt = new UnityEngine.Texture2D(occlusionTxt.width, occlusionTxt.height);
#if DEBUG
                newOcclusionTxt.name = string.Format("{0}_occlusion", occlusionTxt.name);
#endif
                var buf = occlusionTxt.GetPixels32();
                for (int i = 0; i < buf.Length; i++)
                {
                    var color = buf[i];
                    color.g = color.b = color.r;
                    color.a = 1;
                    buf[i]  = color;
                }
                newOcclusionTxt.SetPixels32(buf);
                newOcclusionTxt.Apply();
                Profiler.EndSample();

                material.SetTexture(StandardShaderHelper.occlusionMapPropId, newOcclusionTxt);

                additionalResources.Add(newOcclusionTxt);
            }

            var emmissiveTxt = GetTexture(gltfMaterial.emissiveTexture, textures, images);
            if (emmissiveTxt != null)
            {
                material.SetTexture(StandardShaderHelper.emissionMapPropId, emmissiveTxt);
                material.EnableKeyword("_EMISSION");
            }

            if (gltfMaterial.alphaModeEnum == AlphaMode.MASK)
            {
                material.SetFloat(StandardShaderHelper.cutoffPropId, gltfMaterial.alphaCutoff);
                StandardShaderHelper.SetAlphaModeMask(material, gltfMaterial);
            }
            else if (gltfMaterial.alphaModeEnum == AlphaMode.BLEND)
            {
                StandardShaderHelper.SetAlphaModeBlend(material);
            }
            else
            {
                StandardShaderHelper.SetOpaqueMode(material);
            }

            if (gltfMaterial.emissive != Color.black)
            {
                material.SetColor("_EmissionColor", gltfMaterial.emissive);
                material.EnableKeyword("_EMISSION");
            }

            if (gltfMaterial.doubleSided)
            {
                Debug.LogWarning("Double sided shading is not supported!");
            }
            return(material);
        }
    private GLexTexture(Texture2D texture)
        : base()
    {
        mTexture = texture;
        mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL);

        // texture need to be readable for export
        if (!mImporter.isReadable) {
            Debug.LogWarning("GLexTexture.Construct: Setting texture " + Name + " as Readable, or export will fail!");

            mImporter.isReadable = true;
            AssetDatabase.ImportAsset(OriginalURL);
            mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL);
        }

        if (IsARGB32orRGB24) {
            _dataBytes = mTexture.EncodeToPNG();
        }
        else {
            _dataBytes = new JPGEncoder(mTexture, GLexConfig.JPEGQuality).GetBytes();
        }
        _dataBinaryKeystring = NamesUtil.GenerateBinaryId(_dataBytes, GLex.Instance.UserName);

        mTextures.Add(this);
    }