示例#1
0
    public static void SetSize(int width, int height)
    {
        GameViewSizeGroupType currentType = GameViewUtils.GetCurrentGroupType();
        bool addToList = false;

        if (!GameViewUtils.SizeExists(currentType, width, height))
        {
            string viewName = GetViewName(width, height);
            GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, currentType, width, height, viewName);
            addToList = true;
        }

        int index = GameViewUtils.FindSize(currentType, width, height);

        if (index < 0)
        {
            Debug.LogError("Cannot find Game View Size for width: " + width.ToString() + "  height: " + height.ToString());
        }
        else
        {
            if (addToList)
            {
                indices.Add(index);
            }

            GameViewUtils.SetSize(index);
        }
    }
示例#2
0
    private IEnumerator MakeScreenShot()
    {
        Time.timeScale = 0.1f;

        for (int i = 0; i < resolutionsToShot.Length; i++)
        {
            if (resolutionsToShot[i].MakeShot)
            {
                yield return(new WaitForEndOfFrame());

                GameViewUtils.SetSize(resolutionsToShot[i].width, resolutionsToShot[i].height);

                yield return(new WaitForEndOfFrame());

                Texture2D shot     = GetScreenShot();
                byte[]    shotData = shot.EncodeToPNG();
                Destroy(shot);

                string savePath = GetNumberedSavePath(resolutionsToShot[i].width, resolutionsToShot[i].height);

                File.WriteAllBytes(savePath, shotData);
            }
        }

        Time.timeScale = 1;
    }
示例#3
0
 void PrintSizesTillIndex()
 {
     for (int i = 0; i <= printIndex; i++)
     {
         print(i + ". " + GameViewUtils.GetViewDimentions(i));
     }
 }
        void InitAllGameviewSizes()
        {
            // Remove all resolutions not in devices
            List <string> deviceSizes = new List <string>();

            foreach (ScreenshotResolution res in m_ConfigAsset.m_Config.GetActiveResolutions())
            {
                deviceSizes.Add(m_GameviewSizeName + res.ToString());
            }
            List <string> gameviewSizes = GameViewUtils.GetAllSizeNames();

            foreach (string size in gameviewSizes)
            {
                if (size.Contains(m_GameviewSizeName) && !deviceSizes.Contains(size))
                {
                    GameViewUtils.RemoveCustomSize(GameViewUtils.FindSize(size));
                }
            }

            // Add all new devices
            foreach (ScreenshotResolution res in m_ConfigAsset.m_Config.GetActiveResolutions())
            {
                if (!gameviewSizes.Contains(m_GameviewSizeName + res.ToString()))
                {
                    GameViewUtils.AddCustomSize(GameViewUtils.SizeType.FIXED_RESOLUTION, res.ComputeTargetWidth(), res.ComputeTargetHeight(), m_GameviewSizeName + res.ToString());
                }
            }
        }
        // MAKE A PHOTO ===========================================================================
        // Делаем фотки нашего GameView
        //=========================================================================================
        private void MakeShot(bool save)
        {
            try
            {
                if (lastSnapshot != null)
                {
                    lastSnapshot.KillTexture();
                }

                if (useNativeResolution)
                {
                    gameViewRenderResult = GameViewUtils.GetRenderTextureDirect();
                }
                else
                {
                    gameViewRenderResult = GameViewUtils.GetGameViewSnapshotUnsafe(fixedResolution);
                }

                if (gameViewRenderResult != null)
                {
                    lastSnapshot = gameViewRenderResult.GetTexture2D();
                    lastSnapshot.FlipYSave();
                    if (lastSnapshot != null && save)
                    {
                        string name = namePrefix + GetTimeStr();
                        lastSnapshot.SaveTexture(path, name);
                    }
                    gameViewRenderResult.KillTexture();
                }
            }
            catch (Exception error)
            {
                Debug.LogError(error);
            }
        }
示例#6
0
    protected IEnumerator InitUIVisualTestScene(string testName)
    {
        yield return(InitScene());

        yield return(VisualTestHelpers.InitVisualTestsScene(testName));

        // Create UIScreenSpace
        UIScreenSpace screenSpace = TestHelpers.SharedComponentCreate <UIScreenSpace, UIScreenSpace.Model>(scene, CLASS_ID.UI_SCREEN_SPACE_SHAPE);

        yield return(screenSpace.routine);

        screenSpaceId = screenSpace.id;

        // The canvas has to be in ScreenSpaceCamera mode to be able to render the UI correctly for the snapshots
        screenSpace.canvas.renderMode    = RenderMode.ScreenSpaceCamera;
        screenSpace.canvas.worldCamera   = VisualTestController.i.camera;
        screenSpace.canvas.planeDistance = 1;

        // The camera should only render UI to decrease conflict chance with future ground changes, etc.
        VisualTestController.i.camera.cullingMask = 1 << LayerMask.NameToLayer("UI");

        int id = GameViewUtils.AddOrGetCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, UnityEditor.GameViewSizeGroupType.Standalone, 1280, 720, "Test Resolution");

        GameViewUtils.SetSize(id);
    }
示例#7
0
    protected IEnumerator InitUIVisualTestScene(string testName)
    {
        VisualTestHelpers.snapshotIndex   = 0;
        VisualTestHelpers.currentTestName = testName;

        yield return(InitScene());

        //NOTE(Brian): If we don't wait a frame, RenderingController.Awake sets the rendering state back to false.
        yield return(null);

        RenderProfileManifest.i.Initialize(RenderProfileManifest.i.testProfile);

        base.SetUp_Renderer();

        // Create UIScreenSpace
        UIScreenSpace screenSpace = TestHelpers.SharedComponentCreate <UIScreenSpace, UIScreenSpace.Model>(scene, CLASS_ID.UI_SCREEN_SPACE_SHAPE);

        yield return(screenSpace.routine);

        screenSpaceId = screenSpace.id;

        // The canvas has to be in ScreenSpaceCamera mode to be able to render the UI correctly for the snapshots
        screenSpace.canvas.renderMode    = RenderMode.ScreenSpaceCamera;
        screenSpace.canvas.worldCamera   = VisualTestController.i.camera;
        screenSpace.canvas.planeDistance = 1;

        // The camera should only render UI to decrease conflict chance with future ground changes, etc.
        VisualTestController.i.camera.cullingMask = 1 << LayerMask.NameToLayer("UI");

        int id = GameViewUtils.AddOrGetCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, UnityEditor.GameViewSizeGroupType.Standalone, 1280, 720, "Test Resolution");

        GameViewUtils.SetSize(id);
    }
示例#8
0
    private void Awake()
    {
        instance       = this;
        CannonBallMass = GameManager.DEFAULT_CANNON_BALL_MASS;

        // Forces the Editor to the aspect ratio that is best used to view the learning module
        GameViewUtils.SwitchToSize(new Vector2(16, 9), GameViewUtils.GameViewSizeType.AspectRatio, "Unity Physics Aspect");
    }
示例#9
0
    private void RemoveAllCustomSizes()
    {
#if UNITY_EDITOR
        foreach (ShotSize shot in shotInfo)
        {
            GameViewUtils.RemoveCustomSize(shot.width, shot.height);
        }
#endif
    }
示例#10
0
 static void EnsureSizeExists(OrientationMetadata orientationMetadata)
 {
     if (GameViewUtils.SizeExists(GROUP_TYPE, orientationMetadata.sizeName))
     {
         return;
     }
     GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, GROUP_TYPE,
                                 orientationMetadata.width,
                                 orientationMetadata.height,
                                 orientationMetadata.sizeName);
 }
        public static void SizeIsAddedAndRemovedCorrectly()
        {
            GameViewUtils.AddOrGetCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, GameViewSizeGroupType.Standalone, 123, 456, "Test size");

            int idx = GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, 123, 456);

            Assert.AreNotEqual(-1, idx);
            GameViewUtils.RemoveCustomSize(GameViewSizeGroupType.Standalone, idx);

            idx = GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, 123, 456);
            Assert.AreEqual(-1, idx);
        }
示例#12
0
    private void OnValidate()
    {
        Palette   = _palette;
        Font      = _font;
        ViewScale = _viewScale;
#if UNITY_EDITOR
        if (Instance)
        {
            GameViewUtils.InitTIC80Size((int)ViewScale);
        }
#endif
    }
示例#13
0
        void Start()
        {
            if (!Directory.Exists(ScreenshotFolder))
            {
                Debug.Log("Created directory for screenshots: " + ScreenshotFolder);
                Directory.CreateDirectory(ScreenshotFolder);
            }
            count = Directory.GetFiles(ScreenshotFolder).Length / resolutions.Length;

            currentResolution = GameViewUtils.GetMainGameViewSize();
            currentTimeScale  = Time.timeScale;
        }
示例#14
0
    //Allows switching to a size, if the size is not in the list, add and switch
    public static void SwitchToSize(Vector2 compareSize, GameViewUtils.GameViewSizeType resoType, string name)
    {
        int displayIndex = FindSize(compareSize);

        if (displayIndex < 0)
        {
            GameViewUtils.AddCustomSize(resoType, (int)compareSize.x, (int)compareSize.y, name);
            int index = FindSize(compareSize);
            GameViewUtils.SetSize(index);
        }
        else
        {
            GameViewUtils.SetSize(displayIndex);
        }
    }
示例#15
0
    // Start is called before the first frame update
    void Awake()
    {
#if UNITY_EDITOR
        GameViewUtils.Set1080p();
#endif
        //
        var simple   = this.transform.Find("Tween/text_simple");
        var easy     = this.transform.Find("Tween/text_easy");
        var powerful = this.transform.Find("Tween/text_powerful");
        //

        (simple as RectTransform).DOAnchorPosY(-40, 0.5f).SetEase(Ease.Flash);
        (easy as RectTransform).DOAnchorPosY(-180, 0.5f).SetEase(Ease.Flash).SetDelay(1f);
        (powerful as RectTransform).DOAnchorPosY(-320, 0.6f).SetEase(Ease.Flash).SetDelay(1.5f);
        this.StartCoroutine(this.WattingForClose());
    }
示例#16
0
 static void Update()
 {
     if (delayedMove > 0)
     {
         delayedMove--;
     }
     else if (delayedMove == 0)
     {
         MoveGameWindow();
         //set the proper aspect/resolution
         int gameSize = GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, "Standalone");
         GameViewUtils.SetSize(gameSize);
         delayedMove--;
         EditorApplication.update -= Update;
     }
 }
示例#17
0
    void SetGameViewSize()
    {
        if (typedTarget == null)
        {
            return;
        }

        if (GameViewUtils.SizeExists(GameViewSizeGroupType.Standalone, testGameViewSize))
        {
            GameViewUtils.RemoveCustomSize(GameViewSizeGroupType.Standalone, GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, testGameViewSize));
        }

        GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, GameViewSizeGroupType.Standalone, typedTarget.ImageComparisonSettings.TargetWidth, typedTarget.ImageComparisonSettings.TargetHeight, testGameViewSize);

        GameViewUtils.SetSize(GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, testGameViewSize));
    }
示例#18
0
    private void Start()
    {
        path = (Application.dataPath.Replace("/Assets", "")) + "/" + screenshotsFolderName;
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
            print("Created folder at (" + path + ")");
        }

        for (int i = 0; i < editorScreenSizeIndices.Length; i++)
        {
            string s = GameViewUtils.GetViewDimentions(editorScreenSizeIndices[i]);
            if (Directory.Exists(path + "/" + s) == false)
            {
                Directory.CreateDirectory(path + "/" + s);
            }
        }
    }
示例#19
0
    IEnumerator EditorScreenshotRoutine()
    {
        float temp = Time.timeScale;

        Time.timeScale = 0.05f;
        path           = (Application.dataPath.Replace("/Assets", "")) + "/" + screenshotsFolderName;
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
            yield return(null);

            yield return(null);

            yield return(null);
        }
        for (int i = 0; i < editorScreenSizeIndices.Length; i++)
        {
            if (Directory.Exists(path + "/" + Screen.width + "x" + Screen.height) == false)
            {
                Directory.CreateDirectory(path + "/" + Screen.width + "x" + Screen.height);
                yield return(null);

                yield return(null);

                yield return(null);
            }
        }
        for (int i = 0; i < editorScreenSizeIndices.Length; i++)
        {
            yield return(null);

            GameViewUtils.SetSize(editorScreenSizeIndices[i]);
            yield return(null);

            yield return(null);

            yield return(null);

            print(Screen.width + ", " + Screen.height);
            ScreenCapture.CaptureScreenshot(screenshotsFolderName + "/" + Screen.width + "x" + Screen.height + "/" + "Screenshot (" + Screen.width + "x" + Screen.height + ")_ " + System.DateTime.Now.ToString("dd-mm-yyyy hh-mm-ss") + ".png", 1);
            yield return(null);
        }
        Time.timeScale = temp;
    }
示例#20
0
        public IEnumerator CaptureMultipleResolutions()
        {
            locked         = true;
            Time.timeScale = 0;
            count++;
            yield return(new WaitForEndOfFrame());

            for (int i = 0; i < resolutions.Length; i++)
            {
                if (GameViewUtils.SizeExists(resolutions[i]))
                {
                    GameViewUtils.SetSize(resolutions[i]);
                    yield return(new WaitForEndOfFrame());

                    Capture(resolutions[i]);
                }
            }
            GameViewUtils.SetSize(currentResolution);
            Time.timeScale = currentTimeScale;
            locked         = false;
        }
示例#21
0
    public void OnEnable()
    {
        if (this.enabled)
        {
            var scripts = GetComponents <Tic80> ();
            foreach (var item in scripts)
            {
                if (item != this)
                {
                    item.enabled = false;
                }
            }
        }

        Application.targetFrameRate = Tic80Config.FRAMERATE;
        QualitySettings.vSyncCount  = 0;
        Screen.SetResolution(Tic80Config.SCREEN_AND_BORDER_WIDTH, Tic80Config.SCREEN_AND_BORDER_HEIGHT, false);

        screenTexture = View.Instance.GetScreenTexture();
        borderTexture = View.Instance.GetBorderTexture();

        tic80Config = GetComponent <Tic80Config> ();
        if (!isInited)
        {
            tic80Config.OnFontChange += OnFontChange;
        }
        if (!isInited)
        {
            tic80Config.OnPaletteChange += OnPaletteChange;
        }

#if UNITY_EDITOR
        GameViewUtils.InitTIC80Size((int)tic80Config.ViewScale);
#endif

        Invoke("init", 0f);
        border();

        isInited = true;
    }
    private async Task PerformShot()
    {
        if (this.bundleType == ScreenshotBundleType.None)
        {
            int width  = resWidth * scale;
            int height = resHeight * scale;
            this.Capture(width, height, ScreenShotName(width, height));
        }
        else
        {
            var screenshotBundle = ScreenshotBundle.ByType(this.bundleType);
            foreach (var screenshotDefinition in screenshotBundle.definitions)
            {
                int width  = screenshotDefinition.width * scale;
                int height = screenshotDefinition.height * scale;

                if (GameViewUtils.FindSize(GameViewUtils.GetCurrentGroupType(), width, height) == -1)
                {
                    GameViewUtils.AddCustomSize(GameViewSizeType.FixedResolution, GameViewUtils.GetCurrentGroupType(), width, height, screenshotDefinition.suffix);
                }
                GameViewUtils.SetSize(GameViewUtils.FindSize(GameViewUtils.GetCurrentGroupType(), width, height));

                await Task.Delay(ShutterDelay);

                var directory = screenshotBundle.GetDirectory(screenshotDefinition);
                this.PrepareDirectory(path + "/", directory);
                var fullPath = $"{path}/{directory}";

                var fileName = string.Format("{0}{1}_{2}.png",
                                             fullPath,
                                             screenshotDefinition.Name,
                                             System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
                this.Capture(width, height, fileName);
            }
        }
    }
示例#23
0
        private static IEnumerator TakeAndSave_(int w, int h)
        {
            GameViewSizeGroupType type;

            if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
            {
                type = GameViewSizeGroupType.Android;
            }
            else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
            {
                type = GameViewSizeGroupType.iOS;
            }
            else
            {
                throw new Exception(
                          $"Target platform must be Android or iOS, it is {EditorUserBuildSettings.activeBuildTarget}");
            }


            int size = GameViewUtils.FindSize(type, w, h);

            if (size < 0)
            {
                GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution, type,
                                            w, h, $"SS_{w}x{h}");

                Debug.Log("Add size " + $"SS_{w}x{h}");

                EditorApplication.Step();

                size = GameViewUtils.FindSize(type, w, h);
            }

            if (size < 0)
            {
                throw new Exception("Cannot find size (1)");
            }

            GameViewUtils.SetSize(size);

            yield return(null);

            AssetDatabase.Refresh();


            var path = Application.dataPath.Replace("Assets", "") +
                       $"Screenshots/{w}x{h}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}" + ".png";

            ScreenCapture.CaptureScreenshot(path, 1);

            yield return(null);

            AssetDatabase.Refresh();


            /*
             * yield return null;
             *
             * w = _w;
             * h = _h;
             * Debug.Log(size);
             * size = GameViewUtils.FindSize(type, w, h);
             * GameViewUtils.SetSize(size);
             */
        }
示例#24
0
    /// <summary>
    /// Updates by positioning the camera over the current model
    /// and capture a screenshot to be used as a 2D tile for that model.
    /// Another perspective camera is used to capture the screenshot for the
    /// 3D preview tile. This function also handles rotating all models once
    /// the current rotaion is completed for all of them. All tiles are captured
    /// as 3D preview in addition to top-view with 0, 90, 180 and 270 degrees rotations.
    /// File name format is height-tileObjectName_Rotation.png.
    /// When tile generation is done, the current object is saved as a prefab with collection
    /// name in "Assets/Prefabs" folder
    /// </summary>
    void Update()
    {
        if (transform.childCount == 0)
        {
            Debug.LogWarning("Warning: '" + gameObject.name + "' has no children to build tiles from. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
            return;
        }

        if (prevCam == null)
        {
            return;
        }

        if (!GameViewUtils.SizeExists(GameViewSizeGroupType.Standalone, tileSize, tileSize))
        {
            GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution,
                                        GameViewSizeGroupType.Standalone, tileSize, tileSize,
                                        tileSize + "*" + tileSize + " tile generation");
        }

        GameViewUtils.SetSize(GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, tileSize, tileSize));

        if (string.IsNullOrEmpty(collectionName.Trim()))
        {
            Debug.LogWarning("Warning: collection name cannot be empty. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
            return;
        }

        string tilesPath = Application.dataPath + "/" + TILES_FOLDER + "/" + collectionName;

        if (rot > 270)
        {
            SetTextureAlpha();
            GenerateTilesetFile();
            Debug.Log("Done!! your sprites are in " + tilesPath);
            try
            {
                string atlasesFullPath = Application.dataPath + "/Resources/" + ATLASES_FOLDER;
                if (!Directory.Exists(atlasesFullPath))
                {
                    Directory.CreateDirectory(atlasesFullPath);
                }
                //Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/" + ATLASES_FOLDER + "/" + collectionName + ".prefab");
                //PrefabUtility.ReplacePrefab(gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
                PrefabUtility.SaveAsPrefabAssetAndConnect(gameObject, "Assets/Resources/" + ATLASES_FOLDER + "/" + collectionName + ".prefab", InteractionMode.AutomatedAction);

                Debug.Log("Your tile collection was saved as " + atlasesFullPath + "/" + collectionName + ".prefab");
            }
            catch
            {
                Debug.LogError("Error: unable to save atlas prefab");
            }

            UnityEditor.EditorApplication.isPlaying        = false;
            EditorScriptsController.enableSpriteImporter2D = true;
            AssetDatabase.Refresh();
            EditorScriptsController.enableSpriteImporter2D = false;
            return;
        }

        MoveToNext();

        if (Time.frameCount < 5)
        {
            return;
        }

        string rotString = "_000";

        if (index == transform.childCount - 1)
        {
            //Special case of last tile
            if (rot == 0)
            {
                rotString = "_090";
            }
            else if (rot == 90)
            {
                rotString = "_180";
            }
            else if (rot == 180)
            {
                rotString = "_270";
            }
        }
        else
        {
            if (rot == 90)
            {
                rotString = "_090";
            }
            else if (rot == 180)
            {
                rotString = "_180";
            }
            else if (rot == 270)
            {
                rotString = "_270";
            }
        }

        currentTile = current.GetComponent <Tile3D>();

        string fullPath;

        if (rot != -90)
        {
            fullPath = tilesPath + "/" + currentTile.height.ToString("F2") + "-" + current.name + rotString + ".png";
        }
        else
        {
            fullPath = tilesPath + "/" + currentTile.height.ToString("F2") + "-" + current.name + "__PRV" + ".png";
        }
        generatedPaths.Add(fullPath);

        if (!Directory.Exists(tilesPath))
        {
            Directory.CreateDirectory(tilesPath);
        }

        try
        {
            ScreenCapture.CaptureScreenshot(fullPath);
        }
        catch
        {
            Debug.LogError("Error: unable to save 2D tile sprite '" + fullPath + "'. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
        }

        index++;
        if (index == transform.childCount)
        {
            index = 0;
            rot  += 90;
            if (rot != 0)
            {
                for (int i = 0; i < transform.childCount; i++)
                {
                    Transform t = transform.GetChild(i);

                    t.Rotate(0, 90, 0, Space.World);
                }
            }
        }
    }
示例#25
0
    public override void OnInspectorGUI()
    {
        ScreenshotHelper myTarget = (ScreenshotHelper)target;

        RenderTextureToggleAndWarning(myTarget);

        myTarget.SSHTextureFormat = (ScreenshotHelper.tSSHTextureFormat)EditorGUILayout.EnumPopup("Texture Format", myTarget.SSHTextureFormat);

        CameraSolidColorTransparencyWarning(myTarget);

        MakeSpace(1);

        EditorGUI.BeginChangeCheck();

        myTarget.keyToHold  = (KeyCode)EditorGUILayout.EnumPopup("Key to hold:", myTarget.keyToHold);
        myTarget.keyToPress = (KeyCode)EditorGUILayout.EnumPopup("Key to press:", myTarget.keyToPress);
        if (myTarget.keyToPress == KeyCode.None)
        {
            EditorGUILayout.HelpBox("If you don't assign a key to press then you will not be able to take screenshots with a key press.", MessageType.Warning, true);
        }

        MakeSpace(1);
        myTarget.orientation = (SSHOrientation)EditorGUILayout.EnumPopup("Orientation", myTarget.orientation);

        if (EditorGUI.EndChangeCheck())
        {
            myTarget.UpdateDimensions();
        }

        //sizes header
        MakeSpace(1);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Screen Shot Sizes", EditorStyles.boldLabel);
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.HelpBox("Expand each to edit", MessageType.None, true);
        EditorGUILayout.EndHorizontal();
        MakeSpace(1);

        SetSizesSubs(myTarget);

        //add a size
        EditorGUILayout.Space();
        if (GUILayout.Button("Add a size"))
        {
            myTarget.shotInfo.Add(new ShotSize(0, 0));
        }


        MakeSpace(3);

        EditorGUILayout.HelpBox("In-editor Save location: " + myTarget.savePath, MessageType.None);
        if (GUILayout.Button("Set in-editor save location"))
        {
            myTarget.savePath = GameViewUtils.SelectFileFolder(Directory.GetCurrentDirectory(), "");
            PathChange(myTarget.savePath);
        }

        MakeSpace(1);

        EditorGUILayout.HelpBox("Build Save location example: " + myTarget.BuildSaveLocation(), MessageType.None);
        if (GUILayout.Button("Set build save location"))
        {
            ScreenshotHelperBuildSaveLocationWindow.ShowWindow(myTarget);
        }


        MakeSpace(2);

        if (GUILayout.Button("Save Presets"))
        {
            string newConfig = SavePreset(myTarget);
            if (!string.IsNullOrEmpty(newConfig))
            {
                myTarget.configFile = newConfig;
            }
        }

        LoadPresetsButton(myTarget);

        MakeSpace(2);

        if (GUILayout.Button("Load Defaults"))
        {
            myTarget.SetDefaults();
            myTarget.configFile = "";
        }

        MakeSpace(1);
    }
示例#26
0
    void OnGUI()
    {
        EditorGUILayout.LabelField("Resolution", EditorStyles.boldLabel);
//		resWidth = EditorGUILayout.IntField ("Width", resWidth);
//		resHeight = EditorGUILayout.IntField ("Height", resHeight);

        EditorGUILayout.Space();

        for (int i = 0; i < resolutions.Length; i++)
        {
            resolutions[i] = EditorGUILayout.Vector2Field("size -> ", resolutions[i]);
        }

        EditorGUILayout.Space();

//        scale = EditorGUILayout.IntSlider("Scale", scale, 1, 15);

//        EditorGUILayout.HelpBox(
//            "The default mode of screenshot is crop - so choose a proper width and height. The scale is a factor " +
//            "to multiply or enlarge the renders without loosing quality.", MessageType.None);


//        EditorGUILayout.Space();


        GUILayout.Label("Save Path", EditorStyles.boldLabel);

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.TextField(path, GUILayout.ExpandWidth(false));
        if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
        {
            path = EditorUtility.SaveFolderPanel("Path to Save Images", path, Application.dataPath);
        }

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.HelpBox("Choose the folder in which to save the screenshots ", MessageType.None);
        EditorGUILayout.Space();


        //isTransparent = EditorGUILayout.Toggle(isTransparent,"Transparent Background");


        GUILayout.Label("Select Camera", EditorStyles.boldLabel);


        myCamera = EditorGUILayout.ObjectField(myCamera, typeof(Camera), true, null) as Camera;


        if (myCamera == null)
        {
            myCamera = Camera.main;
        }

        isTransparent = EditorGUILayout.Toggle("Transparent Background", isTransparent);


        EditorGUILayout.HelpBox(
            "Choose the camera of which to capture the render. You can make the background transparent using the transparency option.",
            MessageType.None);

        EditorGUILayout.Space();
//        EditorGUILayout.BeginVertical();
//        EditorGUILayout.LabelField("Default Options", EditorStyles.boldLabel);
//
//
//        if (GUILayout.Button("Set To Screen Size")) {
//            resHeight = (int) Handles.GetMainGameViewSize().y;
//            resWidth = (int) Handles.GetMainGameViewSize().x;
//        }
//
//
//        if (GUILayout.Button("Default Size")) {
//            resHeight = 1440;
//            resWidth = 2560;
//            scale = 1;
//        }
//
//
//        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();
//        EditorGUILayout.LabelField(
//            "Screenshot will be taken at " + resWidth * scale + " x " + resHeight * scale + " px",
//            EditorStyles.boldLabel);

        if (GUILayout.Button("Take Screenshot", GUILayout.MinHeight(60)))
        {
            if (path == "")
            {
                path = EditorUtility.SaveFolderPanel("Path to Save Images", path, Application.dataPath);
//                Debug.Log("Path Set");
                TakeHiResShot();
            }
            else
            {
                TakeHiResShot();
            }
        }

        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal();

//        if (GUILayout.Button("Open Last Screenshot", GUILayout.MaxWidth(160), GUILayout.MinHeight(40))) {
//            if (lastScreenshot != "") {
//                Application.OpenURL("file://" + lastScreenshot);
//                Debug.Log("Opening File " + lastScreenshot);
//            }
//        }

        if (GUILayout.Button("Open Folder", GUILayout.MaxWidth(100), GUILayout.MinHeight(40)))
        {
            Application.OpenURL("file://" + path);
        }

        EditorGUILayout.EndHorizontal();

//        if (!takeHiResShot) {
//            Event e = Event.current;
//            switch (e.type)
//            {
//                case EventType.KeyDown:
//                {
//                    if (Event.current.keyCode == (KeyCode.S))
//                    {
//                        Debug.Log("Take screenshot");
//                        TakeHiResShot();
//                    }
//                    break;
//                }
//            }
//        }

        if (takeHiResShot)
        {
            Debug.Log("take hit -> " + takeHiResShot);
//            for (int i = 0; i < resolutions.Length; i++) {
//                Screen.SetResolution((int)resolutions[i].x, (int)resolutions[i].y, false);
            var sizeIndex = GameViewUtils.FindSize(GameViewSizeGroupType.iOS, (int)resolutions[tickResolutionIndex].x,
                                                   (int)resolutions[tickResolutionIndex].y);
            if (sizeIndex != -1 && prevIndexSize != sizeIndex)
            {
//                int resWidthN = (int)resolutions[tickResolutionIndex].x;
//                int resHeightN = (int)resolutions[tickResolutionIndex].y;

                GameViewUtils.SetSize(sizeIndex);
                prevIndexSize = sizeIndex;
                Debug.Log("size Index -> " + sizeIndex);

//                var pathToFolder = path + "/" + resWidthN + "x" + resHeightN;
////                if (!AssetDatabase.IsValidFolder(path + "/" + resWidthN + "x" + resHeightN)) {
////                    AssetDatabase.CreateFolder(path, resWidthN + "x" + resHeightN);
////                }
//
//                if (!Directory.Exists(pathToFolder)) {
////                    AssetDatabase.CreateFolder(path, resWidthN + "x" + resHeightN);
//                    Directory.CreateDirectory(pathToFolder);
//                }
//
//                RenderTexture rt = new RenderTexture(resWidthN, resHeightN, 24);
//                myCamera.targetTexture = rt;
//
//                TextureFormat tFormat;
//                if (isTransparent)
//                    tFormat = TextureFormat.ARGB32;
//                else
//                    tFormat = TextureFormat.RGB24;
//
//
//                Texture2D screenShot = new Texture2D(resWidthN, resHeightN, tFormat, false);
//                myCamera.Render();
//                RenderTexture.active = rt;
//                screenShot.ReadPixels(new Rect(0, 0, resWidthN, resHeightN), 0, 0);
//                myCamera.targetTexture = null;
//                RenderTexture.active = null;
//                byte[] bytes = screenShot.EncodeToPNG();
//                string filename = ScreenShotName(resWidthN, resHeightN);
//
//                System.IO.File.WriteAllBytes(filename, bytes);
            }
//            }

//			Application.OpenURL(filename);
        }

//        EditorGUILayout.HelpBox(
//            "In case of any error, make sure you have Unity Pro as the plugin requires Unity Pro to work.",
//            MessageType.Info);
    }
示例#27
0
    IEnumerator TakeScreenShots()
    {
        #if UNITY_EDITOR
        if (!Directory.Exists(savePath))
        {
            string newPath = GameViewUtils.SelectFileFolder(System.IO.Directory.GetCurrentDirectory(), "");
            if (!string.IsNullOrEmpty(newPath))
            {
                savePath = newPath;
                if (PathChange != null)
                {
                    PathChange(newPath);
                }
            }
        }
        #endif


        if (!Directory.Exists(savePath))
        {
            Directory.CreateDirectory(savePath);
        }

        float timeScaleStart = Time.timeScale;
        Time.timeScale = 0f;

        #pragma warning disable 0219
        ShotSize initialRes = new ShotSize(Screen.width, Screen.height);
        #pragma warning restore 0219

        if (isTakingShots)
        {
            yield break;
        }

        isTakingShots = true;
        string fileName = "";

        #if UNITY_EDITOR
        int currentIndex = GameViewUtils.GetCurrentSizeIndex();
        //Maximize game view seems to cause crashes
        //GameViewUtils.MaximizeGameView(true);
        #endif

        foreach (var shot in shotInfo)
        {
            fileName = GetScreenShotName(shot);



            #if UNITY_EDITOR
            GameViewUtils.SetSize(shot.width, shot.height);
            if (OnScreenChanged != null)
            {
                yield return(new WaitForEndOfFrame());

                OnScreenChanged();
                yield return(new WaitForEndOfFrame());
            }
            Canvas.ForceUpdateCanvases();
            #else
            float          ratio   = (1f * shot.width) / (1f * shot.height);
            SSH_IntVector2 thisRes = new SSH_IntVector2(shot.width, shot.height);


            if (shot.height > maxRes.height)
            {
                thisRes.width  = Mathf.FloorToInt(maxRes.height * ratio);
                thisRes.height = maxRes.height;
            }

            Screen.SetResolution(thisRes.width, thisRes.height, false);
            Canvas.ForceUpdateCanvases();
            yield return(new WaitForEndOfFrame());

            int attempts = 0;
            while (Screen.width != thisRes.width && attempts < 10)
            {
                Screen.SetResolution(thisRes.width, thisRes.height, false);
                Canvas.ForceUpdateCanvases();
                yield return(new WaitForEndOfFrame());

                attempts++;
            }
            #endif

            yield return(new WaitForEndOfFrame());

            yield return(new WaitForEndOfFrame());

            Texture2D tex = null;
            if (useRenderTexture)
            {
                RenderTexture rt = new RenderTexture(shot.width, shot.height, Depth);
                Camera.main.targetTexture = rt;
                tex = new Texture2D(shot.width, shot.height, TextureFormat.RGB24, false);
                Camera.main.Render();
                RenderTexture.active = rt;
                tex.ReadPixels(new Rect(0, 0, shot.width, shot.height), 0, 0);
                Camera.main.targetTexture = null;
                RenderTexture.active      = null;
                Destroy(rt);
            }
            else
            {
                tex = new Texture2D(Screen.width, Screen.height, textureFormat, false);
                Vector2 camUpperLeft = Camera.main.pixelRect.min; //lower left
                camUpperLeft.y = Camera.main.pixelRect.min.y;

                float offsetX = 0f; //0.5f * Screen.width;
                float offsetY = 0f; //0.5f * Screen.height;
#if UNITY_EDITOR
                //Vector2 gameViewSize = GameViewUtils.GetMainGameViewSize();
                //offsetX = 338f;
                //offsetY = gameViewSize.y;
#endif
                // Was in while there was an issue in Unity when taking screenshots from editor.
                //Debug.LogFormat("screen: ({0},{1}) -- shot: ({2},{3}) -- offset: ({4},{5})", Screen.width, Screen.height, shot.width, shot.height, offsetX, offsetY);
                tex.ReadPixels(new Rect(offsetX, offsetY, Screen.width, Screen.height), 0, 0);
                tex.Apply();
                TextureScale.Bilinear(tex, shot.width, shot.height);
            }

            if (tex != null)
            {
                byte[] screenshot   = tex.EncodeToPNG();
                var    file         = File.Open(Path.Combine(savePath, fileName), FileMode.Create);
                var    binaryWriter = new BinaryWriter(file);
                binaryWriter.Write(screenshot);
                file.Close();
                Destroy(tex);
            }
            else
            {
                SSHDebug.LogError("Something went wrong! Texture is null");
            }
        }

        #if UNITY_EDITOR
        //causes crash
        //GameViewUtils.MaximizeGameView(false);
        GameViewUtils.SetSize(currentIndex);
        if (OnScreenChanged != null)
        {
            yield return(new WaitForEndOfFrame());

            OnScreenChanged();
            yield return(new WaitForEndOfFrame());
        }
        RemoveAllCustomSizes();
        #else
        Screen.SetResolution(initialRes.width, initialRes.height, false);
        #endif


        SSHDebug.Log("Screenshots saved to " + savePath);
        Application.OpenURL(savePath);
        isTakingShots  = false;
        Time.timeScale = timeScaleStart;
    }
    public void OnGUI()
    {
        scrollPos = GUILayout.BeginScrollView(scrollPos);

        GUIStyle hStyle = GetHeadingStyle();
        GUIStyle pStyle = GetParagraphStyle();
        GUIStyle bStyle = GetButtonStyle();

        GUILayout.Label("Unity Video Editor Template", hStyle);
        GUILayout.Label("Thank you for downloading the Video Editor Template.", pStyle);

        GUILayout.Label("The template is centered around Timeline. So we recommend you use a specific Window Layout to reflect this. Press the button below to set the best Window Layout.", pStyle);
        if (GUILayout.Button("Set VE Window Layout", bStyle))
        {
            LayoutUtility.LoadLayout(VideoEditorConstants.WindowLayoutPath);
        }

        GUILayout.Label("To set the resolution of the output video, change the resolution in the 'Game' window. Or use the button below:", pStyle);
        GUILayout.BeginHorizontal();
        GUILayout.BeginVertical(GUILayout.Width(60));
        GUILayout.Label("Width:");
        GUILayout.Label("Height:");
        GUILayout.EndVertical();
        GUILayout.BeginVertical();
        width  = EditorGUILayout.IntField(width);
        height = EditorGUILayout.IntField(height);
        GUILayout.EndVertical();
        if (GUILayout.Button("Set Resolution", SetResButtonStyle(), GUILayout.Height(42)))
        {
            GameViewUtils.AddSetSize(width, height);
        }
        GUILayout.EndHorizontal();


        GUILayout.Label("See the sample scene for example use. Specifically look at the 'GlobalTimeline' object. To export the video simply enter playmode and wait. You do not need to build anything! To see the video output settings look at the RecorderClip on in the Timeline of the 'GlobalTimeline' object.", pStyle);

        GUILayout.Label("Note: The template uses the 'Unity Recorder' package which is in alpha at the time of writing (June 2020). You may wish to update the package through PackageManager.", pStyle);

        GUILayout.Label("Also Note: The template includes the 'Default Playables' package from the Asset Store. But this has been heavily modified, so don't update/remove it.", pStyle);

        GUILayout.Label("Resources", hStyle);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("YouTube Tutorials", bStyle))
        {
            Application.OpenURL(VideoEditorConstants.WindowLayoutPath);
        }
        if (GUILayout.Button("Blog Post (written documentation)", bStyle))
        {
            Application.OpenURL(VideoEditorConstants.BlogLink);
        }
        GUILayout.EndHorizontal();

        GUILayout.Label("Need More Support?", hStyle);
        GUILayout.Label("If you need more support consider opening an issue on the GitHub repository. You can also contact us by completing a contact form on our website.", pStyle);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("GitHub Repo", bStyle))
        {
            Application.OpenURL(VideoEditorConstants.GitHubLink);
        }
        if (GUILayout.Button("Support Website", bStyle))
        {
            Application.OpenURL(VideoEditorConstants.SupportWebsiteLink);
        }
        GUILayout.EndHorizontal();

        GUILayout.Label("Support Us", hStyle);
        GUILayout.Label("If you found this useful and would like to support us, consider purchasing our other Unity Assets from the Asset Store:", pStyle);
        if (GUILayout.Button("See our Unity Assets", bStyle))
        {
            Application.OpenURL(VideoEditorConstants.SolutionStudiosLink);
        }

        GUILayout.Label("Contributions", hStyle);
        GUILayout.Label("All contributions are welcome. Please open a Pull Request on GitHub. Thank you.", pStyle);
        GUILayout.EndScrollView();
    }