using System.IO; using System.Collections.Generic; using SimpleJSON; using UnityEngine; namespace dlu { public class JSONHandler { private JSONHandler() { // Note that these are static! JSONNode.VectorContainerType = JSONContainerType.Object; JSONNode.QuaternionContainerType = JSONContainerType.Object; } private static JSONHandler _instance = null; public static JSONHandler instance { get { if (JSONHandler._instance == null) { JSONHandler._instance = new JSONHandler(); JSONHandler._instance.RefreshSemanticLabels(); } return JSONHandler._instance; } } private Dictionary _sceneDict; public Dictionary sceneDict { get { return this._sceneDict; } private set { this._sceneDict = value; } } private SemanticBehaviour[] _semanticBehaviours; [HideInInspector] public SemanticBehaviour[] semanticBehaviours { get { return this._semanticBehaviours; } set { sceneDict = new Dictionary(); foreach (SemanticBehaviour sb in value) { sceneDict[sb.GetComponent().name] = sb.gameObject; } this._semanticBehaviours = value; } } public void RefreshSemanticLabels() { JSONHandler._instance.semanticBehaviours = GameObject.FindObjectsOfType(); } public JSONArray LoadInstruction(string json) { return JSON.Parse(File.ReadAllText(json)) as JSONArray; } public JSONNode GenerateContextJSON() { string screenShotPath = $"{Application.persistentDataPath}/context.png"; ScreenCapture.CaptureScreenshot(screenShotPath, 3); Dictionary sceneDict = new Dictionary(); JSONArray sceneArray = new JSONArray(); foreach (SemanticBehaviour sb in this.semanticBehaviours) { JSONObject jsonObject = null; string name = sb.GetComponent().name; if (!sceneDict.ContainsKey(name)) { jsonObject = new JSONObject(); jsonObject.Add("name", name); jsonObject.Add("is_a", new JSONArray()); jsonObject.Add("components", new JSONObject()); sceneDict[name] = jsonObject; sceneArray.Add(sceneDict[name]); } jsonObject = sceneDict[name]; jsonObject["is_a"].Add(sb.is_a); sb.WriteTo(jsonObject); } JSONObject metaObject = new JSONObject(); metaObject.Add("image", screenShotPath); JSONObject contextObject = new JSONObject(); contextObject.Add("meta", metaObject); contextObject.Add("context", sceneArray); return contextObject; } } }