Advertisement
Guest User

Untitled

a guest
Nov 29th, 2020
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.87 KB | None | 0 0
  1. using System;
  2. using SimpleJSON;
  3. using UnityEngine;
  4. using System.Collections;
  5. using MeshVR;
  6.  
  7. public class AutoSaver : MVRScript {
  8.     // private float _autosaveRate = 60f * 5f; // default save every five minutes
  9.     private float _autosaveRate = 5f;
  10.     private UIDynamicSlider _rateSlider;
  11.     private bool _developmentMode = false;
  12.  
  13.     // How often to trigger autosave.
  14.     private JSONStorableFloat _autosaveRateJSON;
  15.    
  16.     // If autosave rate should be considered as seconds or minutes
  17.     private JSONStorableBool _secondsInsteadOfMinutesJSON;
  18.  
  19.     // Which directory to use for autosaving
  20.     private JSONStorableString _autoSavePathJSON;
  21.  
  22.     // If autosave is currently active
  23.     private JSONStorableBool _autoSaveActiveJSON;
  24.     private bool _autoSaveActive;
  25.  
  26.     // If we should capture the screenshot automatically
  27.     private JSONStorableBool _autoCaptureScreenshot;
  28.    
  29.     // If "Auto Capture Screenshot" is enabled, this toggle decides if to reuse the last position of the screenshot camera
  30.     private JSONStorableBool _reuseLastScreenshotPosition;
  31.  
  32.     public override void Init() {
  33.         // CreateTextField(new JSONStorableString("Autosave Directory", "Autosave Directory"));
  34.        
  35.        
  36.  
  37.         var defaultScenePath = SuperController.singleton.savesDir + "autosaves\\";
  38.         MVR.FileManagementSecure.FileManagerSecure.CreateDirectory(defaultScenePath);
  39.         StringTextbox(ref _autoSavePathJSON, "Path on disk to autosave to", defaultScenePath, false);
  40.  
  41.         var autoSaveDirectoryBtn = CreateButton("Select Autosave Directory", false);
  42.         autoSaveDirectoryBtn.button.onClick.AddListener(chooseDirectory);
  43.  
  44.         setupAutosaveRate("minutes");
  45.  
  46.         CreateSpacer();
  47.  
  48.         _secondsInsteadOfMinutesJSON = new JSONStorableBool("Use seconds instead of minutes", false, toggleSecondsInsteadOfMinutes);
  49.         setupJSONBool(_secondsInsteadOfMinutesJSON);
  50.  
  51.         _autoSaveActiveJSON = new JSONStorableBool("Autosaving Enabled", false, toggleAutosave);
  52.         setupJSONBool(_autoSaveActiveJSON);
  53.  
  54.         _autoCaptureScreenshot = new JSONStorableBool("Auto Capture Screenshot", true, (bool newVal) => {
  55.             _autoCaptureScreenshot.SetVal(newVal);
  56.             if (newVal) {
  57.                 log("Capturing screenshots automatically from now on");
  58.                 _reuseLastScreenshotPosition.toggle.interactable = true;
  59.             } else {
  60.                 log("Will no longer capture screenshots automatically");
  61.                 _reuseLastScreenshotPosition.SetVal(false);
  62.                 _reuseLastScreenshotPosition.toggle.interactable = false;
  63.             }
  64.         });
  65.         setupJSONBool(_autoCaptureScreenshot);
  66.  
  67.         _reuseLastScreenshotPosition = new JSONStorableBool("Reuse last screenshot position", false, (bool newVal) => {
  68.             _reuseLastScreenshotPosition.SetVal(newVal);
  69.             if (newVal) {
  70.                 log("Will always reuse last capture position from now on");
  71.             } else {
  72.                 log("Will no longer reuse last capture position automatically");
  73.             }
  74.         });
  75.         setupJSONBool(_reuseLastScreenshotPosition);
  76.  
  77.         if (_developmentMode) {
  78.             var testSaveBtn = CreateButton("Test Save JSON", true);
  79.             testSaveBtn.button.onClick.AddListener(() => { doSaveJSON(getTimestamp()); });
  80.  
  81.             var testScreenshotBtn = CreateButton("Test Screenshot", true);
  82.             testScreenshotBtn.button.onClick.AddListener(() => { doSaveScreenshot(getTimestamp()); });
  83.  
  84.             var testBtn = CreateButton("Test Save JSON & Screenshot", true);
  85.             testBtn.button.onClick.AddListener(doSave);
  86.         } else {
  87.             var text = @"<color=#000000><size=40><b>AutoSaver v0.0.1</b></size>
  88. This plugin allows you to configure VaM to automatically save your scenes on selected intervals, handy to recover from mistakes as there is no undo.</color>
  89.  
  90. <color=#0000FF><size=30><b>Select Autosave Directory</b></size></color>
  91. Brings up the Save Scene dialog so you can choose where to autosave your scene. AutoSaver will automatically assign a scene name for you.
  92.  
  93. <color=#0000FF><size=30><b>Autosave Rate</b></size></color>
  94. How often AutoSaver will try to do the saving. Can be switching between minutes and seconds.
  95.  
  96. <color=#0000FF><size=30><b>Autosaving Enabled</b></size></color>
  97. Simple, should we autosave or not?
  98.  
  99. <color=#0000FF><size=30><b>Auto Capture Screenshot</b></size></color>
  100. When enabled, AutoSaver will automatically capture the screenshot for you. When disabled, AutoSaver will wait for you to confirm the angle/position of the screenshot before saving.
  101.  
  102. <color=#0000FF><size=30><b>Reuse Last Screenshot Position</b></size></color>
  103. When enabled, AutoSaver will try to reuse the position of the last screenshot you did. If disabled, the angle/position will be your current PoV. If Auto Capture Screenshot is disabled, this setting gets disabled too.
  104. ";
  105.             JSONStorableString storable = new JSONStorableString("Info", text);
  106.             UIDynamic textfield = CreateTextField(storable, true);
  107.             textfield.height = 1200f;
  108.         }
  109.     }
  110.  
  111.     public void setupJSONBool(JSONStorableBool storable) {
  112.         RegisterBool(storable);
  113.         CreateToggle(storable);
  114.     }
  115.  
  116.     public void log(string str) {
  117.         SuperController.LogMessage($"{nameof(AutoSaver)} {str}");
  118.     }
  119.  
  120.     public void OnEnable() {
  121.         try {
  122.             if (_autoSaveActive) {
  123.                 StartCoroutine("AutosaveInterval");
  124.             } else {
  125.                 StopCoroutine("AutosaveInterval");
  126.             }
  127.         } catch (Exception e) {
  128.             SuperController.LogError($"{nameof(AutoSaver)}.{nameof(OnEnable)}: {e}");
  129.         }
  130.     }
  131.  
  132.     private void StringTextbox(ref JSONStorableString output, string name, string start, bool rhs) {
  133.         output = new JSONStorableString(name, start);
  134.  
  135.         RegisterString(output);
  136.         var textfield = CreateTextField(output, rhs);
  137.         var input = textfield.gameObject.AddComponent<UnityEngine.UI.InputField>();
  138.         input.textComponent = textfield.UItext;
  139.         output.inputField = input;
  140.     }
  141.  
  142.     IEnumerator AutosaveInterval() {
  143.         for(;;) {
  144.             float saveRate;
  145.             if (_secondsInsteadOfMinutesJSON.val) {
  146.                 saveRate = _autosaveRateJSON.val;
  147.             } else {
  148.                 saveRate = _autosaveRateJSON.val * 60f;
  149.             }
  150.             yield return new WaitForSeconds(saveRate);
  151.             doSave();
  152.         }
  153.     }
  154.  
  155.     private string getFilePath(string timestamp, string suffix) {
  156.         return _autoSavePathJSON.val + timestamp + "." + suffix;
  157.     }
  158.  
  159.     private void doSaveJSON(string timestamp) {
  160.         var saveName = getFilePath(timestamp, "json");
  161.         log($"{nameof(AutoSaver)} Saving to {saveName}");
  162.         JSONClass saveJSON = SuperController.singleton.GetSaveJSON(null, true, true);
  163.         SaveJSON(saveJSON, saveName);
  164.     }
  165.  
  166.     private void doSaveScreenshot(string timestamp) {
  167.         var saveName = getFilePath(timestamp, "jpg");
  168.         SuperController.singleton.DoSaveScreenshot(saveName);
  169.  
  170.         // If we don't wait any time, the screenshot camera won't have time to move to new position it
  171.         // seems, so we can reuse the last position if wanted.
  172.         if (_reuseLastScreenshotPosition.val) {
  173.             // log("Reusing last position");
  174.             triggerLeftSelect();
  175.         } else {
  176.             // log("New capture position");
  177.             if (_autoCaptureScreenshot.val) {
  178.                 Invoke("triggerLeftSelect", 0.01f);
  179.             }
  180.         }
  181.     }
  182.  
  183.     private void triggerLeftSelect() {
  184.         SuperController.singleton.SetLeftSelect();
  185.     }
  186.  
  187.     private string getTimestamp() {
  188.         return DateTime.Now.ToFileTime().ToString();
  189.     }
  190.  
  191.     private void doSave() {
  192.         var timestamp = getTimestamp();
  193.         doSaveJSON(timestamp);
  194.         doSaveScreenshot(timestamp);
  195.     }
  196.  
  197.     private void toggleAutosave(bool val) {
  198.         _autoSaveActiveJSON.SetVal(val);
  199.         _autoSaveActive = val;
  200.         if (val) {
  201.             log("Autosaving active");
  202.             StartCoroutine("AutosaveInterval");
  203.         } else {
  204.             log("Autosaving disabled");
  205.             StopCoroutine("AutosaveInterval");
  206.         }
  207.     }
  208.  
  209.     private void toggleSecondsInsteadOfMinutes(bool val) {
  210.         _secondsInsteadOfMinutesJSON.SetVal(val);
  211.         var dynamicSlider = _rateSlider.GetComponent<UIDynamicSlider>();
  212.         if (val) {
  213.             log("Using Seconds instead of Minutes for Autosave Rate");
  214.             dynamicSlider.labelText.text = "Autosave Rate (Seconds)";
  215.             _autosaveRateJSON.SetVal(60f);
  216.             _autosaveRate = 60f;
  217.             StopCoroutine("AutosaveInterval");
  218.             StartCoroutine("AutosaveInterval");
  219.         } else {
  220.             log("Using Minutes instead of Seconds for Autosave Rate");
  221.             dynamicSlider.labelText.text = "Autosave Rate (Minutes)";
  222.             _autosaveRateJSON.SetVal(1f);
  223.             _autosaveRate = 1f;
  224.             StopCoroutine("AutosaveInterval");
  225.             StartCoroutine("AutosaveInterval");
  226.         }
  227.     }
  228.  
  229.     private void chooseDirectory() {
  230.         SuperController.singleton.SaveSceneDialog((filePath) =>
  231.         {
  232.             if (String.IsNullOrEmpty(filePath))
  233.             {
  234.                 return;
  235.             }
  236.             string directoryPath = filePath.Remove(filePath.LastIndexOf('\\')) + "\\";
  237.             log(directoryPath + " selected for autosaving");
  238.             _autoSavePathJSON.SetVal(directoryPath);
  239.         });
  240.     }
  241.  
  242.     private void setupAutosaveRate(string intervalType) {
  243.         _autosaveRateJSON = new JSONStorableFloat("Autosave Rate ("+intervalType+")", 5f, (float newVal) => {
  244.             double rounded = Math.Round(newVal);
  245.             // if (_secondsInsteadOfMinutesJSON.val) {
  246.             //     log("Setting autosave rate to " + rounded.ToString() + " seconds");
  247.             // } else {
  248.             //     log("Setting autosave rate to " + rounded.ToString() + " minutes");
  249.             // }
  250.             _autosaveRateJSON.val = (float) rounded;
  251.             StopCoroutine("AutosaveInterval");
  252.             StartCoroutine("AutosaveInterval");
  253.         }, 1f, 60f, true, true);
  254.  
  255.         // DeregisterFloat(_autosaveRateJSON);
  256.         RegisterFloat(_autosaveRateJSON);
  257.  
  258.         // RemoveSlider(_autosaveRateJSON);
  259.         _rateSlider = CreateSlider(_autosaveRateJSON);
  260.     }
  261.  
  262.     public void OnDisable() {
  263.         try {
  264.             StopCoroutine("AutosaveInterval");
  265.         } catch (Exception e) {
  266.             SuperController.LogError($"{nameof(AutoSaver)}.{nameof(OnDisable)}: {e}");
  267.         }
  268.     }
  269.  
  270.     public void OnDestroy() {
  271.         try {
  272.             StopCoroutine("AutosaveInterval");
  273.         } catch (Exception e) {
  274.             SuperController.LogError($"{nameof(AutoSaver)}.{nameof(OnDestroy)}: {e}");
  275.         }
  276.     }
  277. }
  278.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement