Exemplo n.º 1
0
        public void ArrayWithObjectWithArray()
        {
            string json = @"
            {
                ""Array"" : [
                    {
                        ""Key-1"" : [
                                1, 2, 3, 4
                            ],
                    },
                    {
                        ""Nested"" : {
                                ""NestedKey"" : ""NestedValue""
                            }
                    }
                ]
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Array:0:Key-1:0", "1", 0);
            Assertion(collection, "Array:0:Key-1:1", "2", 1);
            Assertion(collection, "Array:0:Key-1:2", "3", 2);
            Assertion(collection, "Array:0:Key-1:3", "4", 3);
            Assertion(collection, "Array:1:Nested:NestedKey", "NestedValue", 4);
        }
Exemplo n.º 2
0
 public void Identity()
 {
     foreach (var json in _jsons)
     {
         AssertIdentity(JsonTransform.Identity(), json);
     }
 }
Exemplo n.º 3
0
        public void LoadJsonAsyncWithObjectAndArray()
        {
            string json = @"
            {
                ""Simple"" : ""Value"",
                 ""RabbitMQ"" : {
                    ""Host"" : ""localhost"",
                    ""Port"" : ""5672""
                },
                ""Connections"" : [
                    1, 2, 3, 4]
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Simple", "Value", 0);
            Assertion(collection, "RabbitMQ:Host", "localhost", 1);
            Assertion(collection, "RabbitMQ:Port", "5672", 2);
            Assertion(collection, "Connections:0", "1", 3);
            Assertion(collection, "Connections:1", "2", 4);
            Assertion(collection, "Connections:2", "3", 5);
            Assertion(collection, "Connections:3", "4", 6);
        }
        public void LoadJsonAndTransformBack()
        {
            string json = @"
            {
                ""Simple"" : ""Value"",
                 ""RabbitMQ"" : {
                    ""Host"" : ""localhost"",
                    ""Port"" : ""5672""
                },
                ""Connections"" : [
                    1, 2, 3, 4]
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            OperationResult opResult   = transform.Format(collection);
            var             jsonEntity = opResult.Result as ConfigEntityJson;

            Assert.NotNull(jsonEntity);

            var token = jsonEntity.Json;

            Assert.Equal(token["Simple"], "Value");
            Assert.Equal(token["RabbitMQ:Host"], "localhost");
            Assert.Equal(token["RabbitMQ:Port"], "5672");
            Assert.Equal(token["Connections"], "1,2,3,4");
        }
Exemplo n.º 5
0
    IEnumerator Get()
    {
        WWW www;

        string url = "http://internal.mcmentos.com:62802/getTransform";

        www = new WWW(url);

        yield return(www);

        if (www.error == "" || www.error == null)
        {
            Debug.Log("Get succeeded!");
            Debug.Log(www.text);
            JsonTransform t = JsonUtility.FromJson <JsonTransform>(www.text);
            localTransform.pos = t.pos;
            localTransform.rot = t.rot;
            print("networked p" + localTransform.pos);
            print("networked r" + localTransform.rot);
            Debug.Log(localTransform.pos);
        }
        else
        {
            Debug.Log(www.error);
        }
    }
Exemplo n.º 6
0
        public void NestedObjectAndArray()
        {
            string json = @"
            {
                ""Object"" : {
                    ""Nested"" : {
                        ""Array"" : [
                            1,2,3,4
                        ],
                        ""Key"" : ""Value""
                    },
                    ""Nested2"" : {
                        ""Nested3"" : {
                            ""N-Key"" : ""N-Value""
                        }
                    }
                }
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Object:Nested:Array:0", "1", 0);
            Assertion(collection, "Object:Nested:Array:1", "2", 1);
            Assertion(collection, "Object:Nested:Array:2", "3", 2);
            Assertion(collection, "Object:Nested:Array:3", "4", 3);
            Assertion(collection, "Object:Nested:Key", "Value", 4);
            Assertion(collection, "Object:Nested2:Nested3:N-Key", "N-Value", 5);
        }
Exemplo n.º 7
0
    IEnumerator Set(Vector3 pos, Vector3 rot)
    {
        WWW www;
        Dictionary <string, string> postHeader = new Dictionary <string, string>();

        postHeader.Add("Content-Type", "application/json");

        JsonTransform t = new JsonTransform();

        t.pos = pos;
        t.rot = rot;

        string transformStr = JsonUtility.ToJson(t);

        var    formData = System.Text.Encoding.UTF8.GetBytes(transformStr);
        string url      = "http://internal.mcmentos.com:62802/setTransform";

        www = new WWW(url, formData, postHeader);

        yield return(www);

        if (www.error == "" || www.error == null)
        {
            Debug.Log("Set succeeded!");
            Debug.Log(www.text);
        }
        else
        {
            Debug.Log(www.error);
        }
    }
Exemplo n.º 8
0
        public Order CreateNewOrder(NewOrder newOrder)
        {
            var createOrderJson = JsonTransform.OrderToCreateOrder(newOrder);

            var order = SaveNewOrder(newOrder);

            _orderBroker.SendOrderMessage(createOrderJson, order.JobId.ToString());
            _logger.LogInformation($"Message send to broker.");
            return(order);
        }
Exemplo n.º 9
0
 public JsonPart(int?_parent, string _name, JsonTransform _transform, List <int> _activeConnections, List <int> _children, int?_parentCon, List <int> _childCons)
 {
     parent            = _parent;
     name              = _name;
     transform         = _transform;
     activeConnections = _activeConnections;
     children          = _children;
     parentCon         = _parentCon;
     childCons         = _childCons;
 }
Exemplo n.º 10
0
        ///<summary>
        /// load simple json file
        /// save to in Memory store
        /// and load all and print to console
        ///</summary>
        public static async Task Run(Action <object> printCallback)
        {
            var store = new InMemoryStore();
            // upload file from the current directory
            string     json      = JsonFromConfigFile();
            ITransform transform = new JsonTransform();

            OperationResult result = transform.Parse(json);

            if (result.Result is ConfigCollection collection)
            {
                foreach (var item in collection.WrappedConfigEntities)
                {
                    var request = new ConfigChangeRequest {
                        Name = item.Name, Value = item.Value
                    };
                    var context = new CommandContext(CommandTypes.Create, request, store);

                    await Factory.RunOperationAsync(context);
                }
            }
            else
            {
                throw new InvalidCastException("should have been ConfigCollection yet is " + result.Result.GetType().Name);
            }
            foreach (var item in await store.AllEntitesAsync())
            {
                printCallback($"next one is [{item.Name}] - [{item.Value}]");
            }

            printCallback("also find RabbitMQ:Port and change it to 5674");
            ConfigEntity port = await QueryRabbitPortAsync(store);

            printCallback(port.Name + " - " + port.Value);

            var updateRq = new ConfigChangeRequest {
                Name = port.Name, Value = "5674"
            };
            var update = new CommandContext(CommandTypes.UpdateValue, updateRq, store);

            OperationResult rs = await Factory.RunOperationAsync(update);

            printCallback("after the update:");
            port = await QueryRabbitPortAsync(store);

            printCallback(port.Name + " - " + port.Value);
        }
Exemplo n.º 11
0
    public JsonPart(int _parent, string _name, JsonTransform _transform, int _parentCon, int _conToParent, List <int> _activeCons, List <int> _children)
    {
        parent            = _parent;
        name              = _name;
        transform         = _transform;
        parentCon         = _parentCon;
        conToParent       = _conToParent;
        activeConnections = _activeCons;
        children          = _children;

        if (parent == -1 || parent == null)
        {
            parent      = null;
            parentCon   = null;
            conToParent = null;
        }
    }
Exemplo n.º 12
0
        public void LoadJsonAsyncSimpleOnes()
        {
            string json = @"
            {
                ""Simple"" : ""Value"",
                ""RabbitMQ"" : ""simple-2""
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Simple", "Value", 0);
            Assertion(collection, "RabbitMQ", "simple-2", 1);
            System.Console.WriteLine();
        }
Exemplo n.º 13
0
 public static IAsyncEnumerable <TElement> GraphsonDeserialize <TElement>(this IAsyncEnumerable <JToken> tokenEnumerable, JsonSerializer serializer)
 {
     return(tokenEnumerable
            .Select(token =>
     {
         try
         {
             return serializer
             .Deserialize <TElement>(new JTokenReader(token)
                                     .ToTokenEnumerable()
                                     .Apply(JsonTransform
                                            .Identity()
                                            .GraphElements()
                                            .NestedValues())
                                     .ToJsonReader());
         }
         catch (JsonReaderException ex)
         {
             throw new GraphsonMappingException($"Error mapping\r\n\r\n{token}\r\n\r\nto an object of type {typeof(TElement)}.", ex);
         }
     }));
 }
Exemplo n.º 14
0
        public void LoadJsonAsyncWithObject()
        {
            string json = @"
            {
                ""Simple"" : ""Value"",
                ""RabbitMQ"" : {
                    ""Host"" : ""localhost"",
                    ""Port"" : ""5672""
                }
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Simple", "Value", 0);
            Assertion(collection, "RabbitMQ:Host", "localhost", 1);
            Assertion(collection, "RabbitMQ:Port", "5672", 2);
            System.Console.WriteLine();
        }
Exemplo n.º 15
0
        ///<summary>
        ///setup communcation with the CLI or any other client via ZeroMQ
        ///</summary>
        public static Communication GetCommunication(string tcpConnection)
        {
            var store = new InMemoryStore();
            // upload file from the current directory
            string     json      = JsonFromConfigFile();
            ITransform transform = new JsonTransform();

            OperationResult result = transform.Parse(json);

            var socket = new RequestBus(tcpConnection);

            socket.Connect();

            return(new Communication
            {
                Storage = store,
                Socket = socket,
                JsonString = json,
                Transform = transform,
                ConfigEntities = result.Result as ConfigCollection
            });
        }
Exemplo n.º 16
0
    private JsonTransform[] GetValidRelateJsonTrans()
    {
        Vector3    selfLocalPos = _jsonLabObj.JsonLocalTransform.JsonLocalPos.ToVector3();
        Quaternion selfQuat     = Quaternion.Euler(_jsonLabObj.JsonLocalTransform.JsonLocalRot.ToVector3());

        JsonAssemblyObject[] brothersJsonLabObjs = _labObjectModule.GetBrothersJsonLabObj(ID);
        List <JsonTransform> RelateTrans_List    = new List <JsonTransform>();

        if (_jsonLabObj.ParentID != -1)
        {
            RelateTrans_List.Add(_jsonLabObj.JsonLocalTransform);
        }
        if (brothersJsonLabObjs != null)
        {
            for (int i = 0; i < brothersJsonLabObjs.Length; ++i)
            {
                int        brotherID    = brothersJsonLabObjs[i].ID;
                Transform  brotherTrans = _labObjectModule.GetTransformByID(brotherID);
                Vector3    oldDir       = selfLocalPos - brothersJsonLabObjs[i].JsonLocalTransform.JsonLocalPos.ToVector3();
                Quaternion oldQuat      = Quaternion.Euler(brothersJsonLabObjs[i].JsonLocalTransform.JsonLocalRot.ToVector3());
                Quaternion fixedQuat    = brotherTrans.localRotation * Quaternion.Inverse(oldQuat);
                Vector3    newDir       = fixedQuat * oldDir;

                Vector3    relatePos = newDir.normalized * oldDir.magnitude + brotherTrans.localPosition;
                Quaternion relateQua = fixedQuat * selfQuat;

                JsonTransform relateJosonTrans = new JsonTransform(relatePos, relateQua.eulerAngles, _jsonLabObj.JsonLocalTransform.JsonLocalScal.ToVector3());
                RelateTrans_List.Add(relateJosonTrans);
            }
        }
        if (RelateTrans_List.Count <= 0)
        {
            return(null);
        }
        else
        {
            return(RelateTrans_List.ToArray());
        }
    }
Exemplo n.º 17
0
        public void ArrayWithObjects()
        {
            string json = @"
            {
                ""Array"" : [
                    {
                        ""Key-1"" : ""Value-1"",
                    },
                    {
                        ""Key-2"" : ""Value-2"",
                    },
                    42
                ]
            }
            ";

            var transform = new JsonTransform();

            var result     = transform.Parse(json);
            var collection = (result.Result as ConfigCollection).WrappedConfigEntities;

            Assertion(collection, "Array:0:Key-1", "Value-1", 0);
            Assertion(collection, "Array:1:Key-2", "Value-2", 1);
        }
Exemplo n.º 18
0
        public string DataGridJson()
        {
            int page = Convert.ToInt32(Request.Params.Get("page"));
            int rows = Convert.ToInt32(Request.Params.Get("rows"));

            if (page == 0)
            {
                page = 1;
            }
            if (rows == 0)
            {
                rows = 20;
            }
            int    recordcount = 0;
            string order       = "ID";

            List <M> list = new List <M>();

            list = service.GetObjects <M>(rows, page, "", order, service.GetOrderType(order), ref recordcount);
            List <string> fields = new List <string>();

            typeof(M).GetProperties().ToList().ForEach(t => fields.Add(t.Name));
            return(JsonTransform.SerializeObject <M>(list, typeof(M).Name, fields.ToArray(), new List <JsonMapTable>(), recordcount));
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();

                var storageAccount = new CloudStorageAccount(new StorageCredentials("storage name", "storage key"), false);

                var outputDirectory = @"c:\temp\";
                Directory.CreateDirectory(outputDirectory);
                var startTimeInclusive = new DateTime(2016, 8, 11, 19, 0, 0);
                var endTimeExclusive   = new DateTime(2016, 8, 18, 0, 0, 0);
                var outputFile         = Path.Combine(outputDirectory, $"{startTimeInclusive:yyyy-MM-dd_HH}-{endTimeExclusive:yyyy-MM-dd_HH}.json");

                // download and merge blob data
                using (var writer = new StreamWriter(outputFile))
                {
                    AzureBlobDownloader.Download(storageAccount, startTimeInclusive, endTimeExclusive, writer, outputDirectory).Wait();
                }

                // pre-process JSON
                JsonTransform.TransformIgnoreProperties(outputFile, outputFile + ".small",
                                                        "Somefeatures");

                outputFile += ".small";
                // filter broken events
                JsonTransform.TransformFixMarginal(outputFile,
                                                   numExpectedActions: 10, // examples with different number of actions are ignored
                                                   startingNamespace: 'G', // starting namespace of the marginal features, if more than one marginal features then the next letter is used, e.g. G for the first one, H for second, and so on.
                                                   marginalProperties: new TupleList <string, string>
                {
                    // The property parent and name to create marginal features for
                    { "DVideoFeatures", "VideoId" },
                    //{ "DVideoFeatures", "VideoTitle" }, // uncomment if more marginal features are needed
                });

                outputFile += ".fixed";

                using (var reader = new StreamReader(outputFile))
                    using (var writer = new StreamWriter(new GZipStream(File.Create(outputFile + ".vw.gz"), CompressionLevel.Optimal)))
                    {
                        VowpalWabbitJsonToString.Convert(reader, writer);
                    }

                var bags = new[] { 1, 2, 4, 6, 8, 10 }.Select(a => "--bag " + a);
                var softmaxes = new[] { 0, 1, 2, 4, 8, 16, 32 }.Select(a => "--softmax --lambda " + a);
                var epsilons = new[] { .33333f, .2f, .1f, .05f }.Select(a => "--epsilon " + a);

                var arguments = Util.Expand(
                    epsilons.Union(bags).Union(softmaxes),
                    new[] { "--cb_type ips", "--cb_type mtr", "--cb_type dr" },
                    new[] { "-q AB -q UD" },
                    new[] { 0.005, 0.01, 0.02, 0.1 }.Select(l => string.Format(CultureInfo.InvariantCulture, "-l {0}", l))
                    )
                                .Select(a => $"--cb_explore_adf {a} --interact ud ")
                                .ToList();

                var sep         = "\t";
                var historyFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mwt.experiments");
                using (var historyWriter = new StreamWriter(File.Open(historyFile, FileMode.OpenOrCreate)))
                {
                    for (int i = 0; i < arguments.Count; i++)
                    {
                        var startTime              = DateTime.UtcNow;
                        var outputPredictionFile   = $"{outputFile}.prediction";
                        var outputPrediction2hFile = $"{outputFile}.{i + 1}.2h.prediction";

                        // VW training
                        OfflineTrainer.Train(arguments[i],
                                             outputFile,
                                             predictionFile: outputPrediction2hFile,
                                             reloadInterval: TimeSpan.FromHours(2),
                                             cacheFilePrefix: null); // null to use input file's name for cache, see the method documentation for more details

                        var metricResult = Metrics.Compute(outputFile, outputPredictionFile, outputPrediction2hFile);

                        historyWriter.WriteLine($"{startTime}{sep}{arguments[i]}{sep}{string.Join(sep, metricResult.Select(m => m.Name + sep + m.Value))}");
                    }
                }

                Console.WriteLine("\ndone " + stopwatch.Elapsed);
                Console.WriteLine("Run information is added to: ", historyFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}. {ex.StackTrace}");
            }

            Console.ReadKey();
        }
Exemplo n.º 20
0
    public static void LoadFromString(string jsonSr)
    {
        Dictionary <int, int> localPartIDLedger = new Dictionary <int, int>();

        Dictionary <int, PartSpawnData> spawnPartContainer = new Dictionary <int, PartSpawnData>();

        Dictionary <int, List <int> > childContainer    = new Dictionary <int, List <int> >();
        Dictionary <int, List <int> > childConContainer = new Dictionary <int, List <int> >();

        JsonAssembly assembly;

        int numParts = 0;

        Matrix4x4 transM = new Matrix4x4(new Vector4(1, 0, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 0, 1));

        assembly = JsonConvert.DeserializeObject <JsonAssembly>(jsonSr);

        foreach (KeyValuePair <string, JsonPart> dicEntry in assembly.parts)
        {
            int id;

            if (!BoltNetwork.IsRunning)
            {
                id = int.Parse(dicEntry.Key) + GlobalReferences.NumOfParts;
            }
            else
            {
                id = int.Parse(dicEntry.Key);
                int newID = Random.Range(int.MinValue, int.MaxValue);

                while (localPartIDLedger.ContainsValue(newID) || GlobalReferences.FrozenParts.ContainsKey(newID))
                {
                    newID = Random.Range(int.MinValue, int.MaxValue);
                }

                localPartIDLedger.Add(id, newID);
            }

            JsonPart part       = dicEntry.Value;
            int      templateId = GlobalReferences.TemplateIDFromName(part.name);
            if (templateId == -1)
            {
                throw new System.Exception("Couldn't find Part from Name");
            }

            Matrix4x4 m = part.transform.GetMatrix();
            m = m * Matrix4x4.TRS(-GlobalReferences.TemplateParts[templateId].GetComponent <Part>().PartOffset, Quaternion.identity, Vector3.one);

            m = transM * m;
            Vector3    scale = JsonTransform.MatrixToScale(m);
            Quaternion rot   = JsonTransform.MatrixToRotation(m);
            Vector3    pos   = JsonTransform.MatrixToPosition(m);

            string name = part.name + "_" + (id);

            int parent = -1;
            if (part.parent != null)
            {
                parent  = (int)part.parent;
                parent += GlobalReferences.NumOfParts;
            }

            int parentCon = -1;
            if (part.parentCon != null)
            {
                parentCon = (int)part.parentCon;
            }

            int con = -1;
            if (part.conToParent != null)
            {
                con = (int)part.conToParent;
            }

            if (BoltNetwork.IsRunning)
            {
                var token = new PartTokenParent();
                token.TemplateID = templateId;
                token.ID         = id;

                token.Parent = -1;

                if (part.parent != null)
                {
                    token.Parent = (int)part.parent;
                }

                token.ParentCon = parentCon;

                token.Con = con;

                int owner = 0;

                if (BoltNetwork.IsClient)
                {
                    owner = (int)BoltNetwork.Server.ConnectionId;
                }

                spawnPartContainer.Add(id, new PartSpawnData(token, pos, rot, owner));
            }
            else
            {
                GameObject go = MonoBehaviour.Instantiate(GlobalReferences.TemplateParts[templateId]);
                go.name = name;
                go.SetActive(true);

                PartsHolder.ResetPart(go, GlobalReferences.TemplateParts[templateId], id);

                Part p = go.GetComponent <Part>();


                p.Parent = parent;

                p.ParentCon = parentCon;

                p.ConToParent = con;

                go.transform.rotation = rot;
                go.transform.position = pos;


                p.FreezePart(id);


                if (!GlobalReferences.Parts.Contains(go))
                {
                    GlobalReferences.Parts.Add(go);
                }

                if (id >= numParts)
                {
                    numParts = id + 1;
                }
            }
        }

        if (BoltNetwork.IsRunning)
        {
            foreach (PartSpawnData spawnData in spawnPartContainer.Values)
            {
                //PartTokenParent token = (PartTokenParent)spawnData.Token;
                if (spawnData.parent != -1 && localPartIDLedger.ContainsKey(spawnData.parent))
                {
                    spawnData.parent = localPartIDLedger[spawnData.parent];
                }

                spawnData.id = localPartIDLedger[spawnData.id];

                NetworkPartSpawner.LoadData.data.Add(spawnData);
            }
        }
        else
        {
            foreach (GameObject go in GlobalReferences.FrozenParts.Values)
            {
                Part part = go.GetComponent <Part>();

                if (part.Parent != -1)
                {
                    Part parentPart = GlobalReferences.FrozenParts[part.Parent].GetComponent <Part>();
                    parentPart.Children.Add(part.ID);
                    parentPart.ChildCons.Add(part.ConToParent);
                }
            }

            GlobalReferences.NumOfParts = numParts;
        }
    }
Exemplo n.º 21
0
        public void Identity_NestedValues()
        {
            var transform = JsonTransform.Identity().GraphElements().NestedValues();

            foreach (var json in _jsons)
            {
                AssertIdentity(transform, json);
            }

            Assert(
                transform,
                "{ \"@type\": \"g:Vertex\", \"@value\": { \"id\": 1 } }",
                "{ \"type\": \"vertex\", \"id\": 1 }");

            Assert(
                transform,
                "{ \"@type\": \"g:Vertex\", \"@value\": { \"id\": 1, \"properties\": { \"prop\": \"val\" } } }",
                "{ \"type\": \"vertex\", \"id\": 1, \"prop\": \"val\" }");

            foreach (var json in _jsons)
            {
                Assert(
                    transform,
                    $"{{ \"@type\": \"someType\", \"@value\": {json} }}",
                    json);
            }

            foreach (var json in _jsons)
            {
                Assert(
                    transform,
                    $"[ {{ \"@type\": \"someType\", \"@value\": {json} }} ]",
                    $"[{json}]");
            }

            foreach (var json in _jsons)
            {
                Assert(
                    transform,
                    $"{{ \"p\": 1, \"v\": {{ \"@type\": \"someType\", \"@value\": {json} }} }}",
                    $"{{ \"p\": 1, \"v\": {json} }}");
            }

            foreach (var json in _jsons)
            {
                Assert(
                    transform,
                    $"{{ \"v1\": {{ \"@type\": \"someType\", \"@value\": {json} }}, \"v2\": {{ \"@type\": \"someType\", \"@value\": {json} }} }}",
                    $"{{ \"v1\": {json}, \"v2\": {json} }}");
            }

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"prop\": \"val\" } }",
                "{ \"type\": \"vertex\", \"prop\": \"val\" }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"prop1\": \"val1\", \"prop2\": \"val2\" } }",
                "{ \"type\": \"vertex\", \"prop1\": \"val1\", \"prop2\": \"val2\" }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"prop1\": [1, 2, 3], \"prop2\": [3, 4, 5] } }",
                "{ \"type\": \"vertex\", \"prop1\": [1, 2, 3], \"prop2\": [3, 4, 5] }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"prop1\": [ { } ], \"prop2\": [3, 4, 5] } }",
                "{ \"type\": \"vertex\", \"prop1\": [ { } ], \"prop2\": [3, 4, 5] }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"name\": [ { \"@type\": \"g:VertexProperty\", \"@value\": 36 } ] } }",
                "{ \"type\": \"vertex\", \"name\": [ 36 ] }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"name\": [ { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": 36 } } ] } }",
                "{ \"type\": \"vertex\", \"name\": [ { \"id\": 36 } ] }");

            Assert(
                transform,
                "{ \"type\": \"vertex\", \"properties\": { \"name\": [ { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": 36 } } ] }, \"location\": \"wherever\" }",
                "{ \"type\": \"vertex\", \"name\": [ { \"id\": 36 } ], \"location\": \"wherever\" }");

            Assert(
                transform,
                "[ { \"@type\": \"g:Vertex\", \"@value\": { \"id\": { \"@type\": \"g:Int32\", \"@value\": 1 }, \"label\": \"person\", \"properties\": { \"name\": [ { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": { \"@type\": \"g:Int64\", \"@value\": 0 }, \"value\": \"marko\", \"label\": \"name\" } } ], \"location\": [ { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": { \"@type\": \"g:Int64\", \"@value\": 6 }, \"value\": \"san diego\", \"label\": \"location\", \"properties\": { \"startTime\": { \"@type\": \"g:Int32\", \"@value\": 1997 }, \"endTime\": { \"@type\": \"g:Int32\", \"@value\": 2001 } } } }, { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": { \"@type\": \"g:Int64\", \"@value\": 7 }, \"value\": \"santa cruz\", \"label\": \"location\", \"properties\": { \"startTime\": { \"@type\": \"g:Int32\", \"@value\": 2001 }, \"endTime\": { \"@type\": \"g:Int32\", \"@value\": 2004 } } } }, { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": { \"@type\": \"g:Int64\", \"@value\": 8 }, \"value\": \"brussels\", \"label\": \"location\", \"properties\": { \"startTime\": { \"@type\": \"g:Int32\", \"@value\": 2004 }, \"endTime\": { \"@type\": \"g:Int32\", \"@value\": 2005 } } } }, { \"@type\": \"g:VertexProperty\", \"@value\": { \"id\": { \"@type\": \"g:Int64\", \"@value\": 9 }, \"value\": \"santa fe\", \"label\": \"location\", \"properties\": { \"startTime\": { \"@type\": \"g:Int32\", \"@value\": 2005 } } } } ] } } }\r\n]",
                "[ { \"type\": \"vertex\", \"id\": 1, \"label\": \"person\", \"name\": [ { \"id\": 0, \"value\": \"marko\", \"label\": \"name\" } ], \"location\": [ { \"id\": 6, \"value\": \"san diego\", \"label\": \"location\", \"properties\": { \"startTime\": 1997, \"endTime\": 2001 } }, { \"id\": 7, \"value\": \"santa cruz\", \"label\": \"location\", \"properties\": { \"startTime\": 2001, \"endTime\": 2004 } }, { \"id\": 8, \"value\": \"brussels\", \"label\": \"location\", \"properties\": { \"startTime\": 2004, \"endTime\": 2005 } }, { \"id\": 9, \"value\": \"santa fe\", \"label\": \"location\", \"properties\": { \"startTime\": 2005 } } ] } ]");

            AssertIdentity(
                transform,
                "[ { \"value\": 1540202009475,\r\n    \"label\": \"Property1\",\r\n    \"properties\": {\r\n        \"metaKey\": \"MetaValue\"\r\n    }\r\n},\r\n{\r\n\"value\": \"Some string\",\r\n\"label\": \"Property2\"\r\n},\r\n{\r\n\"value\": 36,\r\n\"label\": \"Property3\"\r\n}\r\n]");
        }
Exemplo n.º 22
0
    //Loading
    public static void Load(string path)
    {
        JsonAssembly assembly;

        string jsonSr;

        int numParts = 0;

        Matrix4x4 transM = new Matrix4x4(new Vector4(1, 0, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 0, 1));

        using (FileStream stream = new FileStream(path, FileMode.Open))
        {
            using (StreamReader sr = new StreamReader(stream))
            {
                jsonSr = sr.ReadToEnd();
            }
        }
        assembly = JsonConvert.DeserializeObject <JsonAssembly>(jsonSr);

        foreach (KeyValuePair <string, JsonPart> dicEntry in assembly.parts)
        {
            int id = int.Parse(dicEntry.Key) + GlobalReferences.NumOfParts;

            JsonPart part       = dicEntry.Value;
            int      templateId = GlobalReferences.TemplateIDFromName(part.name);
            if (templateId == -1)
            {
                throw new System.Exception("Couldn't find Part from Name");
            }

            GameObject go = MonoBehaviour.Instantiate(GlobalReferences.TemplateParts[templateId]);
            go.name = part.name + "_" + (id + GlobalReferences.NumOfParts);
            go.SetActive(true);

            PartsHolder.ResetPart(go, GlobalReferences.TemplateParts[templateId], id + GlobalReferences.NumOfParts);

            Part p = go.GetComponent <Part>();

            foreach (int child in part.children)
            {
                p.Children.Add(child + GlobalReferences.NumOfParts);
            }

            if (part.parent != null)
            {
                p.Parent = part.parent + GlobalReferences.NumOfParts;
            }
            else
            {
                p.Parent = null;
            }

            p.ParentCon = part.parentCon;

            p.ChildCons = part.childCons;

            p.ActiveConnections = part.activeConnections;

            Matrix4x4 m = part.transform.GetMatrix();

            m = transM * m;

            go.transform.localScale = JsonTransform.MatrixToScale(m);
            go.transform.rotation   = JsonTransform.MatrixToRotation(m);
            go.transform.position   = JsonTransform.MatrixToPosition(m);



            /*
             * go.transform.localScale = JsonTransform.MatrixToScale(m);
             * go.transform.rotation = JsonTransform.MatrixToRotation(m);
             * go.transform.position = JsonTransform.MatrixToPosition(m);
             * go.transform.RotateAround(Vector3.zero, Vector3.right, -90);
             * GameObject _go = new GameObject();
             * go.transform.SetParent(_go.transform);
             * _go.transform.localScale = new Vector3(1, 1, -1);
             * go.transform.SetParent(null);
             * MonoBehaviour.Destroy(_go);
             */



            p.FreezePart(id);

            CollisionVoxelContainer.StoreGameObject(go);
            if (!GlobalReferences.Parts.Contains(go))
            {
                GlobalReferences.Parts.Add(go);
            }

            if (id >= numParts)
            {
                numParts = id + GlobalReferences.NumOfParts + 1;
            }
        }

        GlobalReferences.NumOfParts = numParts;
    }