Exemplo n.º 1
0
 public static JSONClass ConvertVector2(Vector2 convert)
 {
     JSONClass vector = new JSONClass();
     vector.Add("x", new JSONData(convert.x));
     vector.Add("y", new JSONData(convert.y));
     return vector;
 }
Exemplo n.º 2
0
 public static JSONClass ToJSON(MonoHelper helper)
 {
     JSONClass componentData = new JSONClass();
     componentData.Add("hash", new JSONData(helper.monoID));
     componentData.Add("fields", GetFields(helper));
     return componentData;
 }
 public void Serialize(JSONClass cls)
 {
     foreach (var item in Positions)
     {
         cls.Add(item.Key, item.Value.Serialize());
     }
 }
Exemplo n.º 4
0
 public void Serialize(JSONClass cls)
 {
     foreach (var item in _dict)
     {
         cls.Add(item.Key, new JSONData(item.Value));
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Binds a key to active an InputCommand and saves it to PlayerPrefs.
 /// Note that it will not save to PlayerPrefs if the build is a debug build.
 /// </summary>
 /// <param name="a">The command to bind.</param>
 /// <param name="k">The key to bind the command to.</param>
 public static void BindKey(InputCommand a, KeyCode k)
 {
     Console.Log("Binding " + k + " to " + a);
     a.keyPress = k;
     if (keysPressed.ContainsKey(k))
     {
         keysPressed[k] = a;
     }
     else
     {
         keysPressed.Add(k, a);
     }
     JSONClass bindings = new JSONClass();
     foreach (KeyValuePair<KeyCode, InputCommand> kvp in keysPressed)
     {
         bindings.Add(kvp.Key.ToString(), new JSONData(kvp.Value.ToString()));
     }
     if (!Debug.isDebugBuild)
     {
         PlayerPrefs.SetString("bindings", bindings.ToString());
         PlayerPrefs.Save();
     }
 }
        private static void SerializeClip(AtomAnimationClip clip, JSONClass clipJSON)
        {
            if (clip.animationPattern != null)
            {
                clipJSON.Add("AnimationPattern", clip.animationPattern.containingAtom.uid);
            }

            var controllersJSON = new JSONArray();

            clipJSON.Add("Controllers", controllersJSON);
            foreach (var controller in clip.targetControllers)
            {
                var controllerJSON = new JSONClass
                {
                    { "Controller", controller.controller.name },
                    { "ControlPosition", controller.controlPosition ? "1" : "0" },
                    { "ControlRotation", controller.controlRotation ? "1" : "0" },
                    { "X", SerializeCurve(controller.x) },
                    { "Y", SerializeCurve(controller.y) },
                    { "Z", SerializeCurve(controller.z) },
                    { "RotX", SerializeCurve(controller.rotX) },
                    { "RotY", SerializeCurve(controller.rotY) },
                    { "RotZ", SerializeCurve(controller.rotZ) },
                    { "RotW", SerializeCurve(controller.rotW) }
                };
                if (controller.parentRigidbodyId != null)
                {
                    controllerJSON["Parent"] = new JSONClass {
                        { "Atom", controller.parentAtomId },
                        { "Rigidbody", controller.parentRigidbodyId }
                    };
                }
                if (controller.weight != 1f)
                {
                    controllerJSON["Weight"] = controller.weight.ToString(CultureInfo.InvariantCulture);
                }
                controllersJSON.Add(controllerJSON);
            }

            var paramsJSON = new JSONArray();

            clipJSON.Add("FloatParams", paramsJSON);
            foreach (var target in clip.targetFloatParams)
            {
                var paramJSON = new JSONClass
                {
                    { "Storable", target.storableId },
                    { "Name", target.floatParamName },
                    { "Value", SerializeCurve(target.value) }
                };
                paramsJSON.Add(paramJSON);
            }

            var triggersJSON = new JSONArray();

            clipJSON.Add("", triggersJSON);
            clipJSON.Add("Triggers", triggersJSON);
            foreach (var target in clip.targetTriggers)
            {
                var triggerJSON = new JSONClass
                {
                    { "Name", target.name }
                };
                var entriesJSON = new JSONArray();
                foreach (var x in target.triggersMap.OrderBy(kvp => kvp.Key))
                {
                    entriesJSON.Add(x.Value.GetJSON());
                }
                triggerJSON["Triggers"] = entriesJSON;
                triggersJSON.Add(triggerJSON);
            }
        }
Exemplo n.º 7
0
        public void ReportMessage(string channelId, string message, string messageId, IFizzLanguageCode lang, string userId, string offense, string description, Action <string, FizzException> callback)
        {
            IfOpened(() =>
            {
                if (string.IsNullOrEmpty(channelId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_CHANNEL_ID, callback);
                    return;
                }
                if (string.IsNullOrEmpty(message))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_MESSAGE, callback);
                    return;
                }
                if (string.IsNullOrEmpty(messageId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_MESSAGE_ID, callback);
                    return;
                }
                if (lang == null)
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_LANGUAGE, callback);
                    return;
                }
                if (string.IsNullOrEmpty(userId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_USER_ID, callback);
                    return;
                }
                if (string.IsNullOrEmpty(offense))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_OFFENCE, callback);
                    return;
                }

                try
                {
                    JSONClass json     = new JSONClass();
                    json["channel_id"] = channelId;
                    json["message"]    = message;
                    json["message_id"] = messageId;
                    json["language"]   = lang.Code;
                    json["user_id"]    = userId;
                    json["offense"]    = offense.ToString();
                    json.Add("time", new JSONData(FizzUtils.Now() / 1000));

                    if (!string.IsNullOrEmpty(description))
                    {
                        json["description"] = description;
                    }

                    _restClient.Post(FizzConfig.API_BASE_URL, FizzConfig.API_PATH_REPORTS, json.ToString(), (response, ex) =>
                    {
                        if (ex != null)
                        {
                            FizzUtils.DoCallback <string> (null, ex, callback);
                        }
                        else
                        {
                            try
                            {
                                JSONNode responseJson    = JSONNode.Parse(response);
                                string reportedMessageId = responseJson["id"];

                                FizzUtils.DoCallback <string> (reportedMessageId, null, callback);
                            }
                            catch
                            {
                                FizzUtils.DoCallback <string> (null, ERROR_INVALID_RESPONSE_FORMAT, callback);
                            }
                        }
                    });
                }
                catch (FizzException ex)
                {
                    FizzUtils.DoCallback <string> (null, ex, callback);
                }
            });
        }
        private void Get(NetworkingPlayer player, JSONNode data)
        {
            // Pull the game id and the filters from request
            string gameId    = data["id"];
            string gameType  = data["type"];
            string gameMode  = data["mode"];
            int    playerElo = data["elo"].AsInt;

            if (_playerRequests.ContainsKey(player.Ip))
            {
                _playerRequests[player.Ip]++;
            }
            else
            {
                _playerRequests.Add(player.Ip, 1);
            }

            int delta = _playerRequests[player.Ip];

            // Get only the list that has the game ids
            List <Host> filter = (from host in hosts where host.Id == gameId select host).ToList();

            // If "any" is supplied use all the types for this game id otherwise select only matching types
            if (gameType != "any")
            {
                filter = (from host in filter where host.Type == gameType select host).ToList();
            }

            // If "all" is supplied use all the modes for this game id otherwise select only matching modes
            if (gameMode != "all")
            {
                filter = (from host in filter where host.Mode == gameMode select host).ToList();
            }

            // Prepare the data to be sent back to the client
            JSONNode  sendData    = JSONNode.Parse("{}");
            JSONArray filterHosts = new JSONArray();

            foreach (Host host in filter)
            {
                if (host.UseElo)
                {
                    if (host.PlayerCount >= host.MaxPlayers)                     //Ignore servers with max capacity
                    {
                        continue;
                    }

                    if (_eloRangeSet && (playerElo > host.Elo - (EloRange * delta) &&
                                         playerElo < host.Elo + (EloRange * delta)))
                    {
                        continue;
                    }
                }

                JSONClass hostData = new JSONClass();
                hostData.Add("name", host.Name);
                hostData.Add("address", host.Address);
                hostData.Add("port", new JSONData(host.Port));
                hostData.Add("comment", host.Comment);
                hostData.Add("type", host.Type);
                hostData.Add("mode", host.Mode);
                hostData.Add("players", new JSONData(host.PlayerCount));
                hostData.Add("maxPlayers", new JSONData(host.MaxPlayers));
                hostData.Add("protocol", host.Protocol);
                hostData.Add("elo", new JSONData(host.Elo));
                hostData.Add("useElo", new JSONData(host.UseElo));
                hostData.Add("eloDelta", new JSONData(delta));
                filterHosts.Add(hostData);
            }

            if (filterHosts.Count > 0)
            {
                _playerRequests.Remove(player.Ip);
            }

            sendData.Add("hosts", filterHosts);

            // Send the list of hosts (if any) back to the requesting client
            server.Send(player.TcpClientHandle, Text.CreateFromString(server.Time.Timestep, sendData.ToString(), false, Receivers.Target, MessageGroupIds.MASTER_SERVER_GET, true));
        }
    public IEnumerator IeHostPartySubmit()
    {
        DecorItemPropties.Clear();
        RoomPropties.Clear();
        var encoding = new System.Text.UTF8Encoding();

        Dictionary <string, string> postHeader = new Dictionary <string, string> ();
        var jsonElement = new Simple_JSON.JSONClass();

        jsonElement ["player_id"]        = PlayerPrefs.GetInt("PlayerId").ToString();
        jsonElement ["party_name"]       = partyName;
        jsonElement ["party_desc"]       = partyDiscription;
        jsonElement ["max_no_of_guests"] = TotelGuest.ToString();

//		string eTime = ExtensionMethods.GetTimeStringFromFloat (PartyTime);
//		DateTime EndTime = Convert.ToDateTime (eTime);


        if (PrivateParty)
        {
            jsonElement ["party_type"] = "2";
        }
        else
        {
            jsonElement ["party_type"] = "1";
        }
        var      PEndTime = DateTime.Now.AddSeconds(PartyTime);
        DateTime EndTime  = PEndTime;

        jsonElement ["party_end_time"]       = EndTime.ToString();
        jsonElement ["no_of_present_member"] = "0";
        jsonElement ["no_of_rooms"]          = RoomPurchaseManager.Instance.flats.Count.ToString();


        for (int i = 0; i < DecorController.Instance.PlacedDecors.Count; i++)
        {
            GameItemPropties tempObj = new GameItemPropties(DecorController.Instance.PlacedDecors [i].GetComponent <Decor3DView> ().decorInfo.Id,
                                                            "Decor" + "/" + DecorController.Instance.PlacedDecors [i].GetComponent <Decor3DView> ().decorInfo.Name.Trim('/').Trim('"'),
                                                            SerializeVector3Array(DecorController.Instance.PlacedDecors [i].GetComponent <Decor3DView> ().transform.position).Trim('|') +
                                                            "/" + DecorController.Instance.PlacedDecors [i].GetComponent <Decor3DView> ().direction
                                                            );
            DecorItemPropties.Add(tempObj);
        }
        for (int j = 0; j < RoomPurchaseManager.Instance.Addedflats.Count; j++)
        {
            GameItemPropties tempRomm = new GameItemPropties(0, RoomPurchaseManager.Instance.flats [j].x.ToString() + ":"
                                                             + RoomPurchaseManager.Instance.flats [j].y.ToString() + "/" + RoomPurchaseManager.Instance.Addedflats [j].GetComponent <Flat3D> ().WallColourNames + "/" +
                                                             RoomPurchaseManager.Instance.Addedflats [j].GetComponent <Flat3D> ().GroundTextureName,
                                                             SerializeVector3Array(RoomPurchaseManager.Instance.Addedflats [j].GetComponent <Flat3D> ().transform.position));
            RoomPropties.Add(tempRomm);
        }

        for (int a = 0; a < DecorItemPropties.Count; a++)
        {
            var jsonarray = new JSONClass();
            jsonarray.Add("item_id", DecorItemPropties [a].id.ToString());
            jsonarray.Add("item_type", DecorItemPropties [a].types.ToString());
            jsonarray.Add("properties", DecorItemPropties [a].propties.ToString());

            jsonElement ["items"].Add(jsonarray);
        }

//		foreach (var item in DecorItemPropties) {
//			var jsonarray = new JSONClass ();
//			jsonarray.Add ("item_id", item.id.ToString ());
//			jsonarray.Add ("item_type", item.types.ToString ());
//			jsonarray.Add ("properties", item.propties.ToString ());
//
//			jsonElement ["items"].Add (jsonarray);
//		}

        for (int b = 0; b < RoomPropties.Count; b++)
        {
            var jsonarray = new JSONClass();
            jsonarray.Add("item_id", RoomPropties [b].id.ToString() + "Room");
            jsonarray.Add("item_type", RoomPropties [b].types.ToString());
            jsonarray.Add("properties", RoomPropties [b].propties.ToString());

            jsonElement ["items"].Add(jsonarray);
        }
//		foreach (var item in RoomPropties) {
//			var jsonarray = new JSONClass ();
//			jsonarray.Add ("item_id", item.id.ToString () + "Room");
//			jsonarray.Add ("item_type", item.types.ToString ());
//			jsonarray.Add ("properties", item.propties.ToString ());
//
//			jsonElement ["items"].Add (jsonarray);
//		}


        postHeader.Add("Content-Type", "application/json");
        postHeader.Add("Content-Length", jsonElement.Count.ToString());

        WWW www = new WWW(HostPartyLink, encoding.GetBytes(jsonElement.ToString()), postHeader);

        print(" flat party jsonDtat is ==>> " + jsonElement.ToString());
        yield return(www);

        if (www.error == null)
        {
            JSONNode _jsnode = Simple_JSON.JSON.Parse(www.text);
            print("_jsnode ==>> " + _jsnode.ToString());
            if (isPaid)
            {
//				if (_jsnode ["status"].ToString ().Contains ("200") && _jsnode ["description"].ToString ().Contains ("Your flat party has been updated successfully")) {
//					int HostedPartyId = 0;
//					int.TryParse (_jsnode ["party_id"], out HostedPartyId);
//					PlayerPrefs.SetInt ("HostedPartyId", HostedPartyId);
//					print (HostedPartyId.ToString () + " this is party id");
////					if (PlayerPrefs.GetInt ("Tutorial_Progress") >= 26)
////						AchievementsManager.Instance.CheckAchievementsToUpdate ("hostFlatParties");
//
//					OnMyFlatPartySubmited (EndTime, HostedPartyId);
//				} else
                if (_jsnode ["status"].ToString().Contains("200") && _jsnode ["description"].ToString().Contains("Your flat party has saved successfully"))
                {
                    int HostedPartyId = 0;
                    int.TryParse(_jsnode ["party_id"], out HostedPartyId);
                    PlayerPrefs.SetInt("HostedPartyId", HostedPartyId);
                    print(HostedPartyId.ToString() + " this is party id");
                    OnMyFlatPartySubmited(EndTime, HostedPartyId);
                    if (PlayerPrefs.GetInt("Tutorial_Progress") >= 26)
                    {
                        AchievementsManager.Instance.CheckAchievementsToUpdate("hostFlatParties");
                    }
                }
                else if (_jsnode == null)
                {
                    print("Somthing went wrong!!!");
                }
            }
        }
    }
Exemplo n.º 10
0
            public void Add <T>(string key, List <T> list)
                where T : IJsonable
            {
                if (list.Count > 0)
                {
                    var array = new JSONArray();

                    foreach (var element in list)
                    {
                        var n = element.ToJSON();
                        if (n?.Impl != null)
                        {
                            array.Add(n.Impl);
                        }
                    }

                    c_?.Add(key, array);
                }
            }
 public void Serialize(JSONClass cls)
 {
     cls.Add("CodeGenDisabled", new JSONData(CodeGenDisabled));
     cls.Add("SnapSize", new JSONData(_snapSize));
     cls.Add("Snap", new JSONData(_snap));
     cls.Add("CodePathStrategyName", new JSONData(_codePathStrategyName));
     cls.Add("GridLinesColor", SerializeColor(GridLinesColor));
     cls.Add("GridLinesColorSecondary", SerializeColor(GridLinesColorSecondary));
     cls.Add("AssociationLinkColor", SerializeColor(_associationLinkColor));
     cls.Add("DefinitionLinkColor", SerializeColor(_definitionLinkColor));
     cls.Add("InheritanceLinkColor", SerializeColor(_inheritanceLinkColor));
     cls.Add("SceneManagerLinkColor", SerializeColor(_sceneManagerLinkColor));
     cls.Add("SubSystemLinkColor", SerializeColor(_subSystemLinkColor));
     cls.Add("TransitionLinkColor", SerializeColor(_transitionLinkColor));
     cls.Add("ViewLinkColor", SerializeColor(_viewLinkColor));
     
     cls.Add("RootNamespace", new JSONData(RootNamespace));
 }
Exemplo n.º 12
0
        private static JSONClass SerializeMutation(Mutation mutation)
        {
            var newJson = new JSONClass();

            newJson.Add("IsActive", new JSONData(mutation.IsActive.ToString()));
            //newJson.Add("ImageExternalPath", new JSONData(mutation.ImageExternalPath));
            newJson.Add("AtomName", new JSONData(mutation.AtomName));
            newJson.Add("AtomType", new JSONData(mutation.AtomType));
            newJson.Add("ScenePathToOpen", SerializeString(mutation.ScenePathToOpen));

            JSONArray morphSet = new JSONArray();

            mutation.FaceGenMorphSet.Select(i => SerializeMorphSet(i)).ToList().ForEach(morphSet.Add);
            newJson.Add("MorphSet", morphSet);

            JSONArray clothinItems = new JSONArray();

            mutation.ClothingItems.Select(i => SerializeClothingMutation(i)).ToList().ForEach(clothinItems.Add);
            newJson.Add("ClothingItems", clothinItems);

            JSONArray hairItems = new JSONArray();

            mutation.HairItems.Select(i => SerializeHairMutation(i)).ToList().ForEach(hairItems.Add);
            newJson.Add("HairItems", hairItems);

            JSONArray activeMorphs = new JSONArray();

            mutation.ActiveMorphs.Select(i => SerializeActiveMorphMutation(i)).ToList().ForEach(activeMorphs.Add);
            newJson.Add("ActiveMorphs", activeMorphs);

            JSONArray poseMorphs = new JSONArray();

            mutation.PoseMorphs.Select(i => SerializePoseMorphMutation(i)).ToList().ForEach(poseMorphs.Add);
            newJson.Add("PoseMorphs", poseMorphs);

            JSONArray storables = new JSONArray();

            mutation.Storables.ForEach(storables.Add);
            newJson.Add("Storables", storables);

            JSONArray storedAtoms = new JSONArray();

            mutation.StoredAtoms.ForEach(i => storedAtoms.Add(SerializeStoredAtom(i)));
            newJson.Add("StoredAtoms", storedAtoms);

            JSONArray storedActions = new JSONArray();

            mutation.StoredActions.ForEach(i => storedActions.Add(SerializeStoredAction(i)));
            newJson.Add("StoredActions", storedActions);

            //newJson.Add("Img_RGB24_W1000H1000_64bEncoded", new JSONData(mutation.Img_RGB24_W1000H1000_64bEncoded));
            return(newJson);
        }
Exemplo n.º 13
0
        public static void AddProgressionEvent(EGAProgressionStatus progressionStatus, string progression01, string progression02, string progression03, double score, bool sendScore)
        {
            string progressionStatusString = ProgressionStatusToString(progressionStatus);

            // Validate event params
            if (!GAValidator.ValidateProgressionEvent(progressionStatus, progression01, progression02, progression03))
            {
                GAHTTPApi.Instance.SendSdkErrorEvent(EGASdkErrorType.Rejected);
                return;
            }

            // Create empty eventData
            JSONClass eventDict = new JSONClass();

            // Progression identifier
            string progressionIdentifier;

            if (string.IsNullOrEmpty(progression02))
            {
                progressionIdentifier = progression01;
            }
            else if (string.IsNullOrEmpty(progression03))
            {
                progressionIdentifier = progression01 + ":" + progression02;
            }
            else
            {
                progressionIdentifier = progression01 + ":" + progression02 + ":" + progression03;
            }

            // Append event specifics
            eventDict["category"] = CategoryProgression;
            eventDict["event_id"] = progressionStatusString + ":" + progressionIdentifier;

            // Attempt
            double attempt_num = 0;

            // Add score if specified and status is not start
            if (sendScore && progressionStatus != EGAProgressionStatus.Start)
            {
                eventDict.Add("score", new JSONData(score));
            }

            // Count attempts on each progression fail and persist
            if (progressionStatus == EGAProgressionStatus.Fail)
            {
                // Increment attempt number
                GAState.IncrementProgressionTries(progressionIdentifier);
            }

            // increment and add attempt_num on complete and delete persisted
            if (progressionStatus == EGAProgressionStatus.Complete)
            {
                // Increment attempt number
                GAState.IncrementProgressionTries(progressionIdentifier);

                // Add to event
                attempt_num = GAState.GetProgressionTries(progressionIdentifier);
                eventDict.Add("attempt_num", new JSONData(attempt_num));

                // Clear
                GAState.ClearProgressionTries(progressionIdentifier);
            }

            // Add custom dimensions
            AddDimensionsToEvent(eventDict);

            // Log
            GALogger.I("Add PROGRESSION event: {status:" + progressionStatusString + ", progression01:" + progression01 + ", progression02:" + progression02 + ", progression03:" + progression03 + ", score:" + score + ", attempt:" + attempt_num + "}");

            // Send to store
            AddEventToStore(eventDict);
        }
Exemplo n.º 14
0
        private static void TextMessageReceived(NetworkingPlayer player, Text frame, NetWorker sender)
        {
            try
            {
                var json = JSON.Parse(frame.ToString());

                if (json["register"] != null)
                {
                    string address = player.IPEndPointHandle.Address.ToString();
                    ushort port    = json["register"]["port"].AsUShort;

                    if (!hosts.ContainsKey(address))
                    {
                        hosts.Add(address, new List <Host>());
                    }

                    for (int i = hosts[address].Count - 1; i >= 0; i--)
                    {
                        // This host is already registered. Let's remove it so it can be refreshed.
                        if (hosts[address][i].port == port)
                        {
                            hosts[address].Remove(hosts[address][i]);
                        }
                    }

                    System.Console.Write("Hosted Server received: ");
                    System.Console.Write(address);
                    System.Console.Write(":");
                    System.Console.Write(port);
                    System.Console.Write(" received");
                    System.Console.Write(System.Environment.NewLine);

                    hosts[address].Add(new Host(player, address, port));
                }
                else if (json["host"] != null && json["port"] != null)
                {
                    server.Disconnect(player, false);

                    string addresss      = json["host"];
                    ushort port          = json["port"].AsUShort;
                    ushort listeningPort = json["clientPort"].AsUShort;

                    addresss = NetWorker.ResolveHost(addresss, port).Address.ToString();

                    if (!hosts.ContainsKey(addresss))
                    {
                        return;
                    }

                    Host foundHost = new Host();
                    foreach (Host iHost in hosts[addresss])
                    {
                        if (iHost.port == port)
                        {
                            foundHost = iHost;
                            break;
                        }
                    }


                    if (string.IsNullOrEmpty(foundHost.host))
                    {
                        return;
                    }

                    JSONNode obj = JSONNode.Parse("{}");
                    obj.Add("host", new JSONData(player.IPEndPointHandle.Address.ToString().Split(':')[0]));
                    obj.Add("port", new JSONData(listeningPort));

                    JSONClass sendObj = new JSONClass();
                    sendObj.Add("nat", obj);

                    Text notifyFrame = Text.CreateFromString(server.Time.Timestep, sendObj.ToString(), false, Receivers.Target, MessageGroupIds.NAT_ROUTE_REQUEST, false);

                    server.Send(foundHost.player, notifyFrame, true);
                }
            }
            catch
            {
                server.Disconnect(player, true);
            }
        }
Exemplo n.º 15
0
    public string ToJSON()
    {
        JSONClass json = new JSONClass();

        json.Add("gravity", new JSONData(GravityMult));
        json.Add("jumpmult", new JSONData(JumpForceMult));
        json.Add("bouncemult", new JSONData(BounceMult));
        json.Add("scalemult", new JSONData(ScaleMult));
        json.Add("frictionmult", new JSONData(FrictionMult));

        json.Add("rollX", new JSONData(RollForceMult.x));
        json.Add("rollY", new JSONData(RollForceMult.y));

        json.Add("airX", new JSONData(AirForceMult.x));
        json.Add("airY", new JSONData(AirForceMult.y));

        json.Add("canblast", new JSONData(CanBlast));
        json.Add("airjumps", new JSONData(AirJumps));

        return(json.ToString());
    }
Exemplo n.º 16
0
 public void Serialize(JSONClass cls)
 {
     cls.Add("OutputIdentifier", OutputIdentifier ?? string.Empty);
     cls.Add("InputIdentifier", InputIdentifier ?? string.Empty);
 }
Exemplo n.º 17
0
 public override void Add(string aKey, JSONNode aItem)
 {
     var tmp = new JSONClass();
     tmp.Add(aKey, aItem);
     Set(tmp);
 }
Exemplo n.º 18
0
    public void Refresh()
    {
        ClearServers();

        if (lan)
        {
            NetWorker.RefreshLocalUdpListings(ushort.Parse(portNumber.text));
            return;
        }

        // The Master Server communicates over TCP
        TCPMasterClient client = new TCPMasterClient();

        // Once this client has been accepted by the master server it should sent it's get request
        client.serverAccepted += x =>
        {
            try
            {
                // The overall game id to select from
                string gameId = "myGame";

                // The game type to choose from, if "any" then all types will be returned
                string gameType = "any";

                // The game mode to choose from, if "all" then all game modes will be returned
                string gameMode = "all";

                // Create the get request with the desired filters
                JSONNode  sendData = JSONNode.Parse("{}");
                JSONClass getData  = new JSONClass();

                // The id of the game to get
                getData.Add("id", gameId);
                getData.Add("type", gameType);
                getData.Add("mode", gameMode);

                sendData.Add("get", getData);

                // Send the request to the server
                client.Send(BeardedManStudios.Forge.Networking.Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
            }
            catch
            {
                // If anything fails, then this client needs to be disconnected
                client.Disconnect(true);
                client = null;
            }
        };

        // An event that is raised when the server responds with hosts
        client.textMessageReceived += (player, frame, sender) =>
        {
            try
            {
                // Get the list of hosts to iterate through from the frame payload
                JSONNode data = JSONNode.Parse(frame.ToString());
                if (data["hosts"] != null)
                {
                    // Create a C# object for the response from the master server
                    MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);

                    if (response != null && response.serverResponse.Count > 0)
                    {
                        // Go through all of the available hosts and add them to the server browser
                        foreach (MasterServerResponse.Server server in response.serverResponse)
                        {
                            Debug.Log("Found server " + server.Name);

                            // Update UI

                            MainThreadManager.Run(() =>
                            {
                                AddServer(server.Name, server.Address, server.PlayerCount, server.Mode);
                            });
                        }
                    }
                }
            }
            finally
            {
                if (client != null)
                {
                    // If we succeed or fail the client needs to disconnect from the Master Server
                    client.Disconnect(true);
                    client = null;
                }
            }
        };

        client.Connect(masterServerHost, (ushort)masterServerPort);
    }
Exemplo n.º 19
0
        public void Refresh()
        {
            // Clear out all the currently listed servers
            for (int i = content.childCount - 1; i >= 0; --i)
            {
                Destroy(content.GetChild(i).gameObject);
            }

            // The Master Server communicates over TCP
            client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should sent it's get request
            client.serverAccepted += () =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", gameId);
                    getData.Add("type", gameType);
                    getData.Add("mode", gameMode);

                    sendData.Add("get", getData);

                    // Send the request to the server
                    client.Send(Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;
                }
            };

            // An event that is raised when the server responds with hosts
            client.textMessageReceived += (player, frame) =>
            {
                try
                {
                    // Get the list of hosts to iterate through from the frame payload
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    if (data["hosts"] != null)
                    {
                        MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);

                        if (response != null && response.serverResponse.Count > 0)
                        {
                            // Go through all of the available hosts and add them to the server browser
                            foreach (MasterServerResponse.Server server in response.serverResponse)
                            {
                                string protocol = server.Protocol;
                                string address  = server.Address;
                                ushort port     = server.Port;
                                string name     = server.Name;
                                // name, address, port, comment, type, mode, players, maxPlayers, protocol
                                CreateServerOption(name, () =>
                                {
                                    // Determine which protocol should be used when this client connects
                                    NetWorker socket = null;

                                    if (protocol == "udp")
                                    {
                                        // TODO:  Add NAT hole punching server
                                        socket = new UDPClient();
                                        ((UDPClient)socket).Connect(address, port);
                                    }
                                    else if (protocol == "tcp")
                                    {
                                        socket = new TCPClient();
                                        ((TCPClient)socket).Connect(address, port);
                                    }
                                    else if (protocol == "web")
                                    {
                                        socket = new TCPClientWebsockets();
                                        ((TCPClientWebsockets)socket).Connect(address, port);
                                    }

                                    if (socket == null)
                                    {
                                        throw new Exception("No socket of type " + protocol + " could be established");
                                    }

                                    Connected(socket);
                                });
                            }
                        }
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        client.Disconnect(true);
                        client = null;
                    }
                }
            };

            client.Connect(masterServerHost, (ushort)masterServerPort);
        }
Exemplo n.º 20
0
        public virtual JSONNode MasterServerRegisterData(NetWorker server, string id, string serverName, string type, string mode, string comment = "", bool useElo = false, int eloRequired = 0)
        {
            // Create the get request with the desired filters
            JSONNode  sendData     = JSONNode.Parse("{}");
            JSONClass registerData = new JSONClass();

            registerData.Add("id", id);
            registerData.Add("name", serverName);
            registerData.Add("port", new JSONData(server.Port));
            registerData.Add("playerCount", new JSONData(server.Players.Count));
            registerData.Add("maxPlayers", new JSONData(server.MaxConnections));
            registerData.Add("comment", comment);
            registerData.Add("type", type);
            registerData.Add("mode", mode);
            registerData.Add("protocol", server is UDPServer ? "udp" : "tcp");
            registerData.Add("elo", new JSONData(eloRequired));
            registerData.Add("useElo", new JSONData(useElo));
            sendData.Add("register", registerData);

            return(sendData);
        }
Exemplo n.º 21
0
        private static void AddEventToStore(JSONClass eventData)
#endif
        {
            // Check if datastore is available
            if (!GAStore.IsTableReady)
            {
                GALogger.W("Could not add event: SDK datastore error");
                return;
            }

            // Check if we are initialized
            if (!GAState.Initialized)
            {
                GALogger.W("Could not add event: SDK is not initialized");
                return;
            }

            try
            {
                // Check db size limits (10mb)
                // If database is too large block all except user, session and business
                if (GAStore.IsDbTooLargeForEvents && !GAUtilities.StringMatch(eventData["category"].AsString, "^(user|session_end|business)$"))
                {
                    GALogger.W("Database too large. Event has been blocked.");
                    return;
                }

                // Get default annotations
                JSONClass ev = GAState.GetEventAnnotations();

                // Create json with only default annotations
                string jsonDefaults = ev.SaveToBase64();

                // Merge with eventData
                foreach (KeyValuePair <string, JSONNode> pair in eventData)
                {
                    ev.Add(pair.Key, pair.Value);
                }

                // Create json string representation
                string json = ev.ToString();

                // output if VERBOSE LOG enabled

                GALogger.II("Event added to queue: " + json);

                // Add to store
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("$status", "new");
                parameters.Add("$category", ev["category"].Value);
                parameters.Add("$session_id", ev["session_id"].Value);
                parameters.Add("$client_ts", ev["client_ts"].Value);
                parameters.Add("$event", ev.SaveToBase64());
                string sql = "INSERT INTO ga_events (status, category, session_id, client_ts, event) VALUES($status, $category, $session_id, $client_ts, $event);";

                GAStore.ExecuteQuerySync(sql, parameters);

                // Add to session store if not last
                if (eventData["category"].AsString.Equals(CategorySessionEnd))
                {
                    parameters.Clear();
                    parameters.Add("$session_id", ev["session_id"].Value);
                    sql = "DELETE FROM ga_session WHERE session_id = $session_id;";
                    GAStore.ExecuteQuerySync(sql, parameters);
                }
                else
                {
                    sql = "INSERT OR REPLACE INTO ga_session(session_id, timestamp, event) VALUES($session_id, $timestamp, $event);";
                    parameters.Clear();
                    parameters.Add("$session_id", ev["session_id"].Value);
                    parameters.Add("$timestamp", GAState.SessionStart);
                    parameters.Add("$event", jsonDefaults);
                    GAStore.ExecuteQuerySync(sql, parameters);
                }
            }
            catch (Exception e)
            {
                GALogger.E("addEventToStoreWithEventData: error using json");
                GALogger.E(e.ToString());
            }
        }
Exemplo n.º 22
0
    public static void SetQuestionWasAnswered(string shieldNum, string key)
    {
        string values = PlayerPrefs.GetString("opened_questions");

        if (values != null && values.Length > 0)
        {
            var jsonStr = JSON.Parse(values);

            var listNode = jsonStr [key].AsArray;

            if (listNode != null)
            {
                foreach (JSONData i in listNode)
                {
                    if (i.Value == shieldNum)
                    {
                        return;
                    }
                }

                JSONNode jnod = new JSONNode();
                jnod.Add(shieldNum);

                listNode.Add(shieldNum);

                jsonStr [key] = listNode;
            }
            else
            {
                JSONArray listNode1 = new JSONArray();

                JSONNode jnod1 = new JSONNode();
                jnod1.Add(shieldNum);

                listNode1.Add(shieldNum);

                jsonStr.Add(key, listNode1);
            }



            //UserController.currentUser.Motto = jsonStr.ToString();
            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", jsonStr.ToString());

            return;
        }
        else
        {
            JSONArray listNode = new JSONArray();

            JSONNode jnod = new JSONNode();
            jnod.Add(shieldNum);

            listNode.Add(shieldNum);


            JSONClass rootNode = new JSONClass();
            rootNode.Add(key, listNode);

            //UserController.currentUser.Motto = rootNode.ToString();

            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", rootNode.ToString());

            return;
        }
    }
Exemplo n.º 23
0
 public static JSONClass ToJSON()
 {
     CacheGOs(true);
     JSONClass roomData = new JSONClass();
     JSONClass cachedRooms = new JSONClass();
     foreach (KeyValuePair<string, List<CachedPrefab>> kvp in roomGOs)
     {
         JSONArray roomObjects = new JSONArray();
         List<CachedPrefab> cachedGOs = kvp.Value;
         foreach (CachedPrefab cachedGO in cachedGOs)
         {
             JSONClass jsonObject = new JSONClass();
             jsonObject.Add("source", new JSONData(cachedGO.source));
             jsonObject.Add("hash", new JSONData(cachedGO.hash));
             jsonObject.Add("position", SaveGame.ConvertVector3(cachedGO.position));
             jsonObject.Add("scale", SaveGame.ConvertVector3(cachedGO.scale));
             jsonObject.Add("rotation", SaveGame.ConvertVector3(cachedGO.rotation));
             jsonObject.Add("components", cachedGO.components);
             roomObjects.Add(jsonObject);
         }
         cachedRooms.Add(kvp.Key, roomObjects);
     }
     roomData.Add("roomdata", cachedRooms);
     return roomData;
 }
Exemplo n.º 24
0
        private void RegisterOnMasterServer(ushort port, int maxPlayers, string masterServerHost, ushort masterServerPort, bool useElo = false, int eloRequired = 0)
        {
            // The Master Server communicates over TCP
            TCPMasterClient client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should send it's get request
            client.serverAccepted += () =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData     = JSONNode.Parse("{}");
                    JSONClass registerData = new JSONClass();
                    registerData.Add("id", "myGame");
                    registerData.Add("name", "Forge Game");
                    registerData.Add("port", new JSONData(port));
                    registerData.Add("playerCount", new JSONData(0));
                    registerData.Add("maxPlayers", new JSONData(maxPlayers));
                    registerData.Add("comment", "Demo comment...");
                    registerData.Add("type", "Deathmatch");
                    registerData.Add("mode", "Teams");
                    registerData.Add("protocol", "udp");
                    registerData.Add("elo", new JSONData(eloRequired));
                    registerData.Add("useElo", new JSONData(useElo));

                    sendData.Add("register", registerData);

                    Frame.Text temp = Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_REGISTER, true);

                    //Debug.Log(temp.GetData().Length);
                    // Send the request to the server
                    client.Send(temp);
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;
                }
            };

            client.Connect(masterServerHost, masterServerPort);

            Networker.disconnected += () =>
            {
                client.Disconnect(false);
                MasterServerNetworker = null;
            };

            MasterServerNetworker = client;
        }
Exemplo n.º 25
0
 public static JSONClass ConvertColor(Color convert)
 {
     JSONClass vector = new JSONClass();
     vector.Add("r", new JSONData(convert.r));
     vector.Add("g", new JSONData(convert.g));
     vector.Add("b", new JSONData(convert.b));
     vector.Add("a", new JSONData(convert.a));
     return vector;
 }
Exemplo n.º 26
0
        public void Serialize(JSONClass cls)
        {
            cls.Add("CodeGenDisabled", new JSONData(CodeGenDisabled));
            cls.Add("SnapSize", new JSONData(_snapSize));
            cls.Add("Snap", new JSONData(_snap));
            cls.Add("CodePathStrategyName", new JSONData(_codePathStrategyName));
            cls.Add("GridLinesColor", SerializeColor(GridLinesColor));
            cls.Add("GridLinesColorSecondary", SerializeColor(GridLinesColorSecondary));
            cls.Add("AssociationLinkColor", SerializeColor(_associationLinkColor));
            cls.Add("DefinitionLinkColor", SerializeColor(_definitionLinkColor));
            cls.Add("InheritanceLinkColor", SerializeColor(_inheritanceLinkColor));
            cls.Add("SceneManagerLinkColor", SerializeColor(_sceneManagerLinkColor));
            cls.Add("SubSystemLinkColor", SerializeColor(_subSystemLinkColor));
            cls.Add("TransitionLinkColor", SerializeColor(_transitionLinkColor));
            cls.Add("ViewLinkColor", SerializeColor(_viewLinkColor));

            cls.Add("RootNamespace", new JSONData(RootNamespace));
        }
Exemplo n.º 27
0
 public static JSONClass SaveField(object fieldObj, string fieldName)
 {
     JSONClass fieldData = null;
     if (fieldObj == null || fieldObj is LuaBinding)
     {
         return null;
     }
     else if (fieldObj is GameObject)
     {
         if ((GameObject)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper((GameObject)fieldObj).monoID));
     }
     else if (fieldObj is MonoHelper)
     {
         if ((MonoHelper)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = ((MonoHelper)fieldObj).GetType().Name; // For some reason, doing this in one step screws up serialization.
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(((MonoHelper)fieldObj).monoID));
     }
     else if (fieldObj is MonoBehaviour)
     {
         if ((MonoBehaviour)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = ((MonoBehaviour)fieldObj).GetType().Name;
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((MonoBehaviour)fieldObj).gameObject).monoID));
     }
     else if (fieldObj is Camera)
     {
         if ((Camera)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = "Camera";
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((Camera)fieldObj).gameObject).monoID));
     }
     else if (fieldObj is TextMesh)
     {
         if ((TextMesh)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = "TextMesh";
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((TextMesh)fieldObj).gameObject).monoID));
     }
     else if (fieldObj is string) // String is technically an IEnumerable so we need to check for it first
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, new JSONData((string)fieldObj));
     }
     else if (fieldObj is IEnumerable)
     {
         fieldData = SerializeIEnumerable((IEnumerable)fieldObj, fieldName);
     }
     else if (fieldObj is Vector2)
     {
         fieldData = ConvertVector2((Vector2)fieldObj);
     }
     else if (fieldObj is Vector3)
     {
         fieldData = ConvertVector3((Vector3)fieldObj);
     }
     else if (fieldObj is Vector4)
     {
         fieldData = ConvertVector4((Vector4)fieldObj);
     }
     else if (fieldObj is Color)
     {
         fieldData = ConvertColor((Color)fieldObj);
     }
     else if (fieldObj is bool)
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, new JSONData((bool)fieldObj));
     }
     else if (fieldObj is int)
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, new JSONData((int)fieldObj));
     }
     else if (fieldObj is float)
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, new JSONData((float)fieldObj));
     }
     else if (fieldObj is double)
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, new JSONData((double)fieldObj));
     }
     else if (fieldObj is Enum)
     {
         fieldData = new JSONClass();
         fieldData.Add(fieldName, SerializeEnum((Enum)fieldObj));
     }
     else if (fieldObj is AudioClip)
     {
         if ((AudioClip)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         fieldData.Add(fieldName, SerializeAudioClip((AudioClip)fieldObj));
     }
     else if (fieldObj is Renderer)
     {
         if ((Renderer)fieldObj == null || fieldObj is LineRenderer)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = "Renderer";
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((Renderer)fieldObj).gameObject).monoID));
     }
     else if (fieldObj is Collider)
     {
         if ((Collider)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = "Collider";
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((Collider)fieldObj).gameObject).monoID));
     }
     else if (fieldObj is Collider2D)
     {
         if ((Collider2D)fieldObj == null)
         {
             return null;
         }
         fieldData = new JSONClass();
         string typeName = "Collider2D";
         fieldData.Add(COMPONENT_NAME_JSON_STRING, new JSONData(typeName));
         fieldData.Add(OBJECT_ID_JSON_STRING, new JSONData(MonoHelper.GetMonoHelper(((Collider2D)fieldObj).gameObject).monoID));
     }
     else
     {
         // Etc
         Type t = fieldObj.GetType();
         System.Reflection.MethodInfo componentMethod = t.GetMethod("ToJSON"); // Let Component handle serialization if it can
         if (componentMethod != null)
         {
             fieldData = componentMethod.Invoke(fieldObj, null) as JSONClass;
         }
         else if (t.IsValueType)
         {
             fieldData = new JSONClass();
             JSONClass fieldClass = new JSONClass();
             BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
                             BindingFlags.Static | BindingFlags.Instance |
                             BindingFlags.FlattenHierarchy;
             FieldInfo[] fields = t.GetFields(flags);
             FieldInfo[] badFieldArray = typeof(MonoHelper).GetFields(flags);
             List<string> badFields = new List<string>();
             foreach (FieldInfo field in badFieldArray)
             {
                 badFields.Add(field.Name);
             }
             foreach (FieldInfo field in fields)
             {
                 object childObj = field.GetValue(fieldObj);
                 if (childObj == null)
                 {
                     continue;
                 }
                 string childName = field.Name;
                 if (badFields.Contains(childName))
                 {
                     continue;
                 }
                 JSONClass childData = SaveField(childObj, childName);
                 if (childData == null)
                 {
                     continue;
                 }
                 fieldClass.Add(childName, childData);
             }
             fieldData.Add(fieldName, fieldClass);
         }
         if (fieldData == null && t != typeof(Action))
         {
             Debug.LogWarning(fieldName + " (" + t + "): " + fieldObj);
         }
     }
     return fieldData;
 }
Exemplo n.º 28
0
    private static void LoadMetaDataFromDocumentDirectory()
    {
        SoundLoaderProxy.Instance.Initial();
        String        path          = Application.persistentDataPath + "/SoundEffect";
        String        path2         = Application.persistentDataPath + "/Music";
        DirectoryInfo directoryInfo = new DirectoryInfo(path);

        FileInfo[]    files          = directoryInfo.GetFiles();
        DirectoryInfo directoryInfo2 = new DirectoryInfo(path2);

        FileInfo[] files2    = directoryInfo2.GetFiles();
        Int32      num       = 0;
        JSONClass  jsonclass = new JSONClass();
        JSONArray  jsonarray = new JSONArray();

        jsonclass.Add("data", jsonarray);
        FileInfo[] array = files;
        for (Int32 i = 0; i < (Int32)array.Length; i++)
        {
            FileInfo fileInfo = array[i];
            jsonarray.Add(new JSONClass
            {
                {
                    "name",
                    fileInfo.Name
                },
                {
                    "soundIndex",
                    num.ToString()
                },
                {
                    "type",
                    "SoundEffect"
                }
            });
            num++;
        }
        JSONClass jsonclass2 = new JSONClass();
        JSONArray jsonarray2 = new JSONArray();

        jsonclass2.Add("data", jsonarray2);
        FileInfo[] array2 = files2;
        for (Int32 j = 0; j < (Int32)array2.Length; j++)
        {
            FileInfo fileInfo2 = array2[j];
            jsonarray2.Add(new JSONClass
            {
                {
                    "name",
                    fileInfo2.Name
                },
                {
                    "soundIndex",
                    num.ToString()
                },
                {
                    "type",
                    "Music"
                }
            });
            num++;
        }
        SoundMetaData.SoundEffectMetaData = jsonclass.ToString();
        SoundMetaData.MusicMetaData       = jsonclass2.ToString();
    }
Exemplo n.º 29
0
 private static JSONClass SerializeTextMesh(TextMesh mesh)
 {
     JSONClass fieldData = new JSONClass();
     fieldData.Add("alignment", new JSONData(mesh.alignment.ToString()));
     fieldData.Add("anchor", new JSONData(mesh.anchor.ToString()));
     fieldData.Add("size", new JSONData(mesh.characterSize));
     JSONClass textColor = ConvertColor(mesh.color);
     fieldData.Add("color", textColor);
     fieldData.Add("text", new JSONData(mesh.text));
     return fieldData;
 }
Exemplo n.º 30
0
        private static void TextMessageReceived(NetworkingPlayer player, Text frame, NetWorker sender)
        {
            try
            {
                var json = JSON.Parse(frame.ToString());

                if (json["register"] != null)
                {
                    string address = player.IPEndPointHandle.Address.ToString();
                    ushort port    = json["register"]["port"].AsUShort;

                    if (!hosts.ContainsKey(address))
                    {
                        hosts.Add(address, new List <Host>());
                    }

                    if (CheckAndUpdateRegisteredHost(player, address, port))
                    {
                        return;
                    }

                    RegisterNewHost(player, address, port);
                }
                else if (json["host"] != null && json["port"] != null)
                {
                    server.Disconnect(player, false);

                    string addresss      = json["host"];
                    ushort port          = json["port"].AsUShort;
                    ushort listeningPort = json["clientPort"].AsUShort;

                    addresss = NetWorker.ResolveHost(addresss, port).Address.ToString();

                    if (!hosts.ContainsKey(addresss))
                    {
                        return;
                    }

                    Host foundHost = new Host();
                    foreach (Host iHost in hosts[addresss])
                    {
                        if (iHost.port == port)
                        {
                            foundHost = iHost;
                            break;
                        }
                    }


                    if (string.IsNullOrEmpty(foundHost.host))
                    {
                        return;
                    }

                    JSONNode obj = JSONNode.Parse("{}");
                    obj.Add("host", new JSONData(player.IPEndPointHandle.Address.ToString().Split(':')[0]));
                    obj.Add("port", new JSONData(listeningPort));

                    JSONClass sendObj = new JSONClass();
                    sendObj.Add("nat", obj);

                    Text notifyFrame = Text.CreateFromString(server.Time.Timestep, sendObj.ToString(), false, Receivers.Target, MessageGroupIds.NAT_ROUTE_REQUEST, false);

                    server.Send(foundHost.player, notifyFrame, true);
                }
            }
            catch
            {
                server.Disconnect(player, true);
            }
        }
Exemplo n.º 31
0
 private static JSONClass SerializeIEnumerable(IEnumerable fieldObj, string fieldName)
 {
     JSONClass fieldData = new JSONClass();
     JSONArray fieldArray = new JSONArray();
     if (fieldObj is IDictionary)
     {
         foreach (DictionaryEntry item in (IDictionary)fieldObj)
         {
             JSONClass keyVal = SaveField(item.Key, "key");
             JSONClass itemVal = SaveField(item.Value, "value");
             if (itemVal == null || keyVal == null)
             {
                 continue;
             }
             JSONClass dictArray = new JSONClass();
             dictArray.Add("dictionarykey", keyVal);
             dictArray.Add("dictionaryvalue", itemVal);
             fieldArray.Add(dictArray);
         }
     }
     else
     {
         try
         {
             foreach (var item in (IEnumerable)fieldObj)
             {
                 JSONClass itemVal = SaveField(item, "value");
                 if (itemVal == null)
                 {
                     continue;
                 }
                 fieldArray.Add(itemVal);
             }
         }
         catch (UnassignedReferenceException)
         {
             return null;
         }
     }
     fieldData.Add(fieldName, fieldArray);
     return fieldData;
 }
Exemplo n.º 32
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
Exemplo n.º 33
0
 private static JSONClass SerializeEnum(Enum enumObj)
 {
     JSONClass fieldData = new JSONClass();
     fieldData.Add("type", new JSONData(enumObj.GetType().Name));
     fieldData.Add("value", new JSONData(enumObj.ToString()));
     return fieldData;
 }
Exemplo n.º 34
0
    private IEnumerator getGameFromServer()
    {
        string id_token   = GetIdToken();
        string id_game    = GetIdGame();
        string strColor1  = ColorUtility.ToHtmlStringRGB(picker1.GetComponent <Image>().color);
        string strColor2  = ColorUtility.ToHtmlStringRGB(picker2.GetComponent <Image>().color);
        string customText = input.text;

        WWWForm form    = new WWWForm();
        WWWDic  header1 = form.headers;

        header1["Authorization"] = id_token;
        Debug.Log("try to get on : " + "http://api.playarshop.com/games/" + id_game);
        string url1 = "http://api.playarshop.com/games/" + id_game;
        WWW    www  = new WWW(url1, null, header1);

        yield return(www);

        Debug.Log("JSON got " + www.text);
        var N = JSON.Parse(www.text);

        JSONClass rootClass = new JSONClass();

        rootClass.Add("game_ref", new JSONData(id_game));
        JSONClass secondClass = new JSONClass();

        secondClass.Add("ref", new JSONData("2"));

        if (N["game"][0]["name"] != null)
        {
            secondClass.Add("name", new JSONData(N["game"][0]["name"]));
        }
        else
        {
            secondClass.Add("name", new JSONData(""));
        }

        if (N["game"][0]["description"] != null)
        {
            secondClass.Add("description", new JSONData(N["game"][0]["description"]));
        }
        else
        {
            secondClass.Add("description", new JSONData(""));
        }

        secondClass.Add("color1", new JSONData(strColor1));
        secondClass.Add("color2", new JSONData(strColor2));

        if (N["game"][0]["perso1"] != null)
        {
            secondClass.Add("perso1", new JSONData(N["game"][0]["perso1"]));
        }
        else
        {
            secondClass.Add("perso1", new JSONData(""));
        }
        if (N["game"][0]["perso2"] != null)
        {
            secondClass.Add("perso2", new JSONData(N["game"][0]["perso2"]));
        }
        else
        {
            secondClass.Add("perso2", new JSONData(""));
        }

        secondClass.Add("custom", new JSONData(customText));
        rootClass.Add("game", secondClass);
        JSONNode rootNode = (JSONNode)rootClass;

        Debug.Log(rootNode.ToString());
        byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rootNode.ToString());

        string url     = "http://api.playarshop.com/games";
        WWWDic headers = new WWWDic();

        headers["Accept"]        = "application/json";
        headers["Content-Type"]  = "application/json";
        headers["Authorization"] = id_token;
        StartCoroutine(sendRequest(url, rawData, headers));
    }
Exemplo n.º 35
0
 private static JSONClass SerializeAudioClip(AudioClip clip)
 {
     if (clip == null)
     {
         return null;
     }
     JSONClass fieldData = new JSONClass();
     fieldData.Add("name", new JSONData(clip.name));
     return fieldData;
 }
Exemplo n.º 36
0
        public virtual void MatchmakingServersFromMasterServer(string masterServerHost,
                                                               ushort masterServerPort,
                                                               int elo,
                                                               System.Action <MasterServerResponse> callback = null,
                                                               string gameId   = "myGame",
                                                               string gameType = "any",
                                                               string gameMode = "all")
        {
            // The Master Server communicates over TCP
            TCPMasterClient client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should send it's get request
            client.serverAccepted += (sender) =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", gameId);
                    getData.Add("type", gameType);
                    getData.Add("mode", gameMode);
                    getData.Add("elo", new JSONData(elo));

                    sendData.Add("get", getData);

                    // Send the request to the server
                    client.Send(Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;

                    MainThreadManager.Run(() =>
                    {
                        if (callback != null)
                        {
                            callback(null);
                        }
                    });
                }
            };

            // An event that is raised when the server responds with hosts
            client.textMessageReceived += (player, frame, sender) =>
            {
                try
                {
                    // Get the list of hosts to iterate through from the frame payload
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    MainThreadManager.Run(() =>
                    {
                        if (data["hosts"] != null)
                        {
                            MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);
                            if (callback != null)
                            {
                                callback(response);
                            }
                        }
                        else
                        {
                            if (callback != null)
                            {
                                callback(null);
                            }
                        }
                    });
                }
                finally
                {
                    if (client != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        client.Disconnect(true);
                        client = null;
                    }
                }
            };

            try
            {
                client.Connect(masterServerHost, masterServerPort);
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.Message);
                MainThreadManager.Run(() =>
                {
                    if (callback != null)
                    {
                        callback(null);
                    }
                });
            }
        }
Exemplo n.º 37
0
    private JSONNode CreateStatement(string trace)
    {
        string[] parts     = trace.Split(',');
        string   timestamp = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).AddMilliseconds(long.Parse(parts [0])).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

        JSONNode statement = JSONNode.Parse("{\"timestamp\": \"" + timestamp + "\"}");

        if (actor != null)
        {
            statement.Add("actor", actor);
        }
        statement.Add("verb", CreateVerb(parts [1]));


        statement.Add("object", CreateObject(parts));

        if (parts.Length > 4)
        {
            // Parse extensions

            int extCount = parts.Length - 4;
            if (extCount > 0 && extCount % 2 == 0)
            {
                // Extensions come in <key, value> pairs

                JSONClass extensions      = new JSONClass();
                JSONNode  extensionsChild = null;

                for (int i = 4; i < parts.Length; i += 2)
                {
                    string key   = parts[i];
                    string value = parts[i + 1];
                    if (key.Equals("") || value.Equals(""))
                    {
                        continue;
                    }
                    if (key.Equals(Tracker.Extension.Score.ToString().ToLower()))
                    {
                        JSONClass score       = new JSONClass();
                        float     valueResult = 0f;
                        float.TryParse(value, out valueResult);
                        score.Add("raw", new JSONData(valueResult));
                        extensions.Add("score", score);
                    }
                    else if (key.Equals(Tracker.Extension.Success.ToString().ToLower()))
                    {
                        bool valueResult = false;
                        bool.TryParse(value, out valueResult);
                        extensions.Add("success", new JSONData(valueResult));
                    }
                    else if (key.Equals(Tracker.Extension.Completion.ToString().ToLower()))
                    {
                        bool valueResult = false;
                        bool.TryParse(value, out valueResult);
                        extensions.Add("completion", new JSONData(valueResult));
                    }
                    else if (key.Equals(Tracker.Extension.Response.ToString().ToLower()))
                    {
                        extensions.Add("response", new JSONData(value));
                    }
                    else
                    {
                        if (extensionsChild == null)
                        {
                            extensionsChild = JSONNode.Parse("{}");
                            extensions.Add("extensions", extensionsChild);
                        }

                        string id = key;
                        bool   tbool;
                        int    tint;
                        float  tfloat;
                        double tdouble;

                        if (extensionIds.ContainsKey(key))
                        {
                            id = extensionIds[key];
                        }

                        if (int.TryParse(value, out tint))
                        {
                            extensionsChild.Add(id, new JSONData(tint));
                        }
                        else if (float.TryParse(value, out tfloat))
                        {
                            extensionsChild.Add(id, new JSONData(tfloat));
                        }
                        else if (double.TryParse(value, out tdouble))
                        {
                            extensionsChild.Add(id, new JSONData(tdouble));
                        }
                        else if (bool.TryParse(value, out tbool))
                        {
                            extensionsChild.Add(id, new JSONData(tbool));
                        }
                        else
                        {
                            extensionsChild.Add(id, new JSONData(value));
                        }
                    }
                }
                statement.Add("result", extensions);
            }
        }

        return(statement);
    }
Exemplo n.º 38
0
        public static JSONClass SerializeComponent(this object component)
        {
            var node = new JSONClass();

            foreach (var property in component.GetType().GetProperties())
            {
                if (property.CanRead && property.CanWrite)
                {
                    if (property.PropertyType == typeof(int))
                    {
                        node.Add(property.Name, new JSONData((int)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(IntReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as IntReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new IntReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((int)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(float))
                    {
                        node.Add(property.Name, new JSONData((float)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(FloatReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as FloatReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new FloatReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((float)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(bool))
                    {
                        node.Add(property.Name, new JSONData((bool)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(BoolReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as BoolReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new BoolReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((bool)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(string))
                    {
                        node.Add(property.Name, new JSONData((string)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(StringReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as StringReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new StringReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((string)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector2))
                    {
                        node.Add(property.Name, new JSONData((Vector2)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector2ReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as Vector2ReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new Vector2ReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((Vector2)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector3))
                    {
                        node.Add(property.Name, new JSONData((Vector3)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector3ReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as Vector3ReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new Vector3ReactiveProperty();
                        }
                        node.Add(property.Name, new JSONData((Vector3)reactiveProperty.Value));
                        continue;
                    }
                }
            }
            return(node);
        }
Exemplo n.º 39
0
    void Test()
    {
        var N = JSONNode.Parse("{\"name\":\"test\", \"array\":[1,{\"data\":\"value\"}]}");

        N["array"][1]["Foo"] = "Bar";
        P("'nice formatted' string representation of the JSON tree:");
        P(N.ToString(""));
        P("");

        P("'normal' string representation of the JSON tree:");
        P(N.ToString());
        P("");

        P("content of member 'name':");
        P(N["name"]);
        P("");

        P("content of member 'array':");
        P(N["array"].ToString(""));
        P("");

        P("first element of member 'array': " + N["array"][0]);
        P("");

        N["array"][0].AsInt = 10;
        P("value of the first element set to: " + N["array"][0]);
        P("The value of the first element as integer: " + N["array"][0].AsInt);
        P("");

        P("N[\"array\"][1][\"data\"] == " + N["array"][1]["data"]);
        P("");

//        var data = N.SaveToBase64();
//        var data2 = N.SaveToCompressedBase64();
//        N = null;
//        P("Serialized to Base64 string:");
//        P(data);
//        P("Serialized to Base64 string (compressed):");
//        P(data2);
//        P("");
//
//        N = JSONNode.LoadFromBase64(data);
//        P("Deserialized from Base64 string:");
//        P(N.ToString());
//        P("");

        var I = new JSONClass();

        I["version"].AsInt     = 5;
        I["author"]["name"]    = "Bunny83";
        I["author"]["phone"]   = "0123456789";
        I["data"][-1]          = "First item\twith tab";
        I["data"][-1]          = "Second item";
        I["data"][-1]["value"] = "class item";
        I["data"].Add("Forth item");
        I["data"][1] = I["data"][1] + " 'addition to the second item'";
        I.Add("version", "1.0");

        P("Second example:");
        P(I.ToString());
        P("");

        P("I[\"data\"][0]            : " + I["data"][0]);
        P("I[\"data\"][0].ToString() : " + I["data"][0].ToString());
        P("I[\"data\"][0].Value      : " + I["data"][0].Value);
        P(I.ToString());
    }
Exemplo n.º 40
0
        public static JSONNode SerializeObject(object target)
        {
            if (target == null)
            {
                return(new JSONNode());
            }

            var objectType = target.GetType();


            //Handle special types first
            if (objectType == typeof(Guid))
            {
                return(new JSONData(target.ToString()));
            }
            //primitive detection
            var node = SerializePrimitive(target);

            if (node != null)
            {
                return(node);
            }

            //if
            if (objectType == typeof(DateTime))
            {
                var t = (DateTime)target;
                return(new JSONData(t.ToString()));
            }


            if (typeof(IList).IsAssignableFrom(objectType)) // collection detected
            {
                //var type = objectType.GetGenericArguments()[0];
                var list      = target as IEnumerable;
                var jsonArray = new JSONArray();

                if (list != null)
                {
                    foreach (var instance in list)
                    {
                        jsonArray.Add(SerializeObject(instance));
                    }
                }

                return(jsonArray);
            }



            //enum detection

            if (objectType.IsEnum)
            {
                return(new JSONData((int)target));
            }


            //poco-like detection

            JSONClass result = new JSONClass();

            var properties = target.GetType().GetProperties();

            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.IsDefined(typeof(JsonProperty), true) || propertyInfo.Name == "Identifier")
                {
                    var value = propertyInfo.GetValue(target, null);
                    if (value != null)
                    {
                        result.Add(propertyInfo.Name, SerializeObject(value));
                    }
                }
            }

            return(result);
        }
Exemplo n.º 41
0
 public void Serialize(JSONClass cls)
 {
     cls.Add("OutputIdentifier", OutputIdentifier ?? string.Empty);
     cls.Add("InputIdentifier", InputIdentifier ?? string.Empty);
 }
Exemplo n.º 42
0
 public static JSONClass GetFields(MonoHelper source, JSONClass fieldArray)
 {
     System.Type t = source.GetType();
     BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
                             BindingFlags.Static | BindingFlags.Instance |
                             BindingFlags.FlattenHierarchy;
     FieldInfo[] fields = t.GetFields(flags);
     FieldInfo[] badFieldArray = typeof(MonoHelper).GetFields(flags);
     List<string> badFields = new List<string>();
     foreach (FieldInfo field in badFieldArray)
     {
         badFields.Add(field.Name);
     }
     foreach (FieldInfo field in fields)
     {
         object fieldObj = field.GetValue(source);
         if (fieldObj == null)
         {
             continue;
         }
         string fieldName = field.Name;
         if (badFields.Contains(fieldName) || System.Attribute.IsDefined(field, typeof(DontSave)))
         {
             continue;
         }
         JSONClass fieldData = SaveGame.SaveField(fieldObj, fieldName);
         if (fieldData == null)
         {
             continue;
         }
         fieldArray.Add(fieldName, fieldData);
     }
     return fieldArray;
 }
Exemplo n.º 43
0
 public override void Add(string aKey, JSONNode aItem)
 {
     var tmp = new JSONClass();
     tmp.Add(aKey, aItem);
     Set(tmp);
 }
Exemplo n.º 44
0
 public JSONClass  Serialize()
 {
     JSONClass cls = new JSONClass();
     for (int index = 0; index < _keys.Count; index++)
     {
         var key = _keys[index];
         var value = _values[index];
         cls.Add(key, SerializeValue(value));
     }
     return cls;
 }
Exemplo n.º 45
0
        private void UpdateFrame()
        {
            var score = ScoreManager.Instance.score;

            while (cells.Count < score.Count)
            {
                var g = Object.Instantiate(cell) as GameObject;
                g.transform.parent = cell.transform.parent;
                Util.InitGameObject(g);
                cells.Add(g);
                g.SetActive(false);
            }
            foreach (var c in cells)
            {
                c.SetActive(false);
            }
            var keys = score.Keys.ToList();

            keys.Sort((a, b) =>
            {
                var ad = score[a];
                var bd = score[b];
                if (ad.killed > bd.killed)
                {
                    return(-1);
                }
                if (ad.killed < bd.killed)
                {
                    return(1);
                }
                return(0);
            });

            var ord = 0;

            for (var i = 0; i < keys.Count; i++)
            {
                var k = keys[i];
                //var player = ObjectManager.objectManager.GetPlayer(k);
                var un   = ScoreManager.Instance.GetCacheName(k);
                var myId = NetMatchScene.Instance.myId;
                //var un = player.GetComponent<NpcAttribute>().userName;
                if (!string.IsNullOrEmpty(un))
                {
                    var g = cells[i];
                    g.SetActive(true);
                    g.GetComponent <GameOverCell>()
                    .SetData(ord + 1, un, score[k].killed, score[k].serverId, score[k].killCount, score[k].deadCount, score[k].assistCount);
                    ord++;
                    if (ord == 1)
                    {
                        if (k != myId)
                        {
                            GetName("Title2").SetActive(true);
                            GetName("Title1").SetActive(false);
                        }
                        else//MVP 场次
                        {
                            var js = new JSONClass();
                            js.Add("mvp", new JSONData(1));
                            RecordData.UpdateRecord(js);
                        }
                    }
                }
            }
            StartCoroutine(WaitReset());
        }
Exemplo n.º 46
0
 private static string GetDefaultBindings()
 {
     JSONClass bindings = new JSONClass();
     KeyCode[] keys = Globals.instance.keys;
     InputCommandName[] actionNames = Globals.instance.actions;
     InputCommand[] actions = new InputCommand[actionNames.Length];
     for (int i = 0; i < actionNames.Length; i++)
     {
         actions[i] = InputCommand.FromEnum(actionNames[i]);
     }
     for (int i = 0; i < keys.Length; i++)
     {
         bindings.Add(keys[i].ToString().ToLower(), new JSONData(actions[i].ToString()));
     }
     return bindings.ToString();
 }
    public static JSONClass SaveNode(int type, int index, string fileName, float positionX, float positionY, float rotation, float scaleX, float scaleY,
                                     List <int> children, bool visible, bool load, List <MapObject.KeyTrigger> keyTriggers,
                                     MapObject transferTrigger, MapObject.ShiftCrystalTrigger shiftTrigger)
    {
        JSONClass result = new JSONClass();

        result.Add("Type", new JSONData(type));
        result.Add("Index", new JSONData(index));
        result.Add("FileName", new JSONData(fileName));
        result.Add("Position", new JSONArray
        {
            new JSONData(positionX),
            new JSONData(positionY)
        });
        result.Add("Rotation", new JSONData(rotation));
        result.Add("Scale", new JSONArray
        {
            new JSONData(scaleX),
            new JSONData(scaleY)
        });
        JSONArray childrenJSON = new JSONArray();

        foreach (int child in children)
        {
            childrenJSON.Add(new JSONData(child));
        }
        result.Add("Children", childrenJSON);
        result.Add("Visible", new JSONData(visible));
        result.Add("Load", new JSONData(load));
        JSONArray keyTrigger = new JSONArray();

        foreach (MapObject.KeyTrigger trigger in keyTriggers)
        {
            JSONClass triggerClass = new JSONClass();
            JSONArray indexArray   = new JSONArray();
            Debug.Log(trigger.dPosition.x);
            foreach (MapObject obj in trigger.objects)
            {
                indexArray.Add(new JSONData(obj.index));
            }

            triggerClass.Add("Index", indexArray);
            triggerClass.Add("dPosition", new JSONArray()
            {
                new JSONData(trigger.dPosition.x * 100.0f),
                new JSONData(trigger.dPosition.y * 100.0f)
            });
            triggerClass.Add("dRotation", new JSONData(trigger.dRotation));
            triggerClass.Add("dScale", new JSONArray()
            {
                new JSONData(trigger.dScale.x),
                new JSONData(trigger.dScale.y)
            });
            triggerClass.Add("Duration", new JSONData(trigger.duration));;
            triggerClass.Add("Visible", new JSONData(trigger.visible));
            triggerClass.Add("Triggerable", new JSONData(trigger.triggerable));
            triggerClass.Add("Load", new JSONData(trigger.load));
            keyTrigger.Add(triggerClass);
        }
        result.Add("KeyTrigger", keyTrigger);
        result.Add("TransferCrystalTrigger", new JSONData(transferTrigger.index));
        JSONClass shiftTriggerNode = new JSONClass();
        JSONArray shiftIndex       = new JSONArray();

        foreach (MapObject obj in shiftTrigger.objects)
        {
            shiftIndex.Add(new JSONData(obj.index));
        }
        shiftTriggerNode.Add("Index", shiftIndex);
        shiftTriggerNode.Add("Direction", new JSONData(shiftTrigger.direction));
        result.Add("ShiftCrystalTrigger", shiftTriggerNode);
        return(result);
    }
Exemplo n.º 48
0
 public override JSONNode this[string aKey]
 {
     get
     {
         return new JSONLazyCreator(this, aKey);
     }
     set
     {
         var tmp = new JSONClass();
         tmp.Add(aKey, value);
         Set(tmp);
     }
 }
Exemplo n.º 49
0
    void Update()
    {
        if (dummyMessageTimer >= 0) {
            if(Mathf.Abs(dummyMessageTimer - Time.time) >= 0.3f) {
                string msgJson = "MESG{\"channel_id\": \"0\", \"message\": \"Dummy Text on Editor Mode - " + Time.time + "\", \"user\": {\"image\": \"http://url\", \"name\": \"Sender\"}, \"ts\": 1418979273365, \"scrap_id\": \"\"}";
                _OnMessageReceived(msgJson);
                dummyMessageTimer = Time.time;
            }
        }

        if (dummyChannelListFlag) {
            dummyChannelListFlag = false;
            JSONArray channels = new JSONArray();
            JSONClass channel = new JSONClass();

            channel.Add ("id", new JSONData(1));
            channel.Add ("channel_url", new JSONData("app_prefix.channel_url"));
            channel.Add ("name", new JSONData("Sample"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(2));
            channel.Add ("channel_url", new JSONData("app_prefix.Unity3d"));
            channel.Add ("name", new JSONData("Unity3d"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(3));
            channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
            channel.Add ("name", new JSONData("Lobby"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(4));
            channel.Add ("channel_url", new JSONData("app_prefix.Cocos2d"));
            channel.Add ("name", new JSONData("Cocos2d"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(5));
            channel.Add ("channel_url", new JSONData("app_prefix.GameInsight"));
            channel.Add ("name", new JSONData("GameInsight"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(6));
            channel.Add ("channel_url", new JSONData("app_prefix.iOS"));
            channel.Add ("name", new JSONData("iOS"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(7));
            channel.Add ("channel_url", new JSONData("app_prefix.Android"));
            channel.Add ("name", new JSONData("Android"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(8));
            channel.Add ("channel_url", new JSONData("app_prefix.News"));
            channel.Add ("name", new JSONData("News"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(9));
            channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
            channel.Add ("name", new JSONData("Lobby"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(10));
            channel.Add ("channel_url", new JSONData("app_prefix.iPad"));
            channel.Add ("name", new JSONData("iPad"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            _OnQueryChannelList(channels.ToString());
        }
    }
Exemplo n.º 50
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
            switch (type)
            {
                case JSONBinaryTag.Array:
                    {
                        int count = aReader.ReadInt32();
                        JSONArray tmp = new JSONArray();
                        for (int i = 0; i < count; i++)
                            tmp.Add(Deserialize(aReader));
                        return tmp;
                    }
                case JSONBinaryTag.Class:
                    {
                        int count = aReader.ReadInt32();
                        JSONClass tmp = new JSONClass();
                        for (int i = 0; i < count; i++)
                        {
                            string key = aReader.ReadString();
                            var val = Deserialize(aReader);
                            tmp.Add(key, val);
                        }
                        return tmp;
                    }
                case JSONBinaryTag.Value:
                    {
                        return new JSONData(aReader.ReadString());
                    }
                case JSONBinaryTag.IntValue:
                    {
                        return new JSONData(aReader.ReadInt32());
                    }
                case JSONBinaryTag.DoubleValue:
                    {
                        return new JSONData(aReader.ReadDouble());
                    }
                case JSONBinaryTag.BoolValue:
                    {
                        return new JSONData(aReader.ReadBoolean());
                    }
                case JSONBinaryTag.FloatValue:
                    {
                        return new JSONData(aReader.ReadSingle());
                    }

                default:
                    {
                        throw new Exception("Error deserializing JSON. Unknown tag: " + type);
                    }
            }
        }
Exemplo n.º 51
0
    public string DebugFaceNeighbourhood(Face face)
    {
        HashSet <Face>     faces     = new HashSet <Face>();
        HashSet <Halfedge> halfedges = new HashSet <Halfedge>();
        HashSet <Vertex>   vertices  = new HashSet <Vertex>();

        // add neighbour faces
        foreach (var he in face.Circulate())
        {
            foreach (var heCirculate in he.CirculateVertex())
            {
                faces.Add(heCirculate.face);
            }
        }
        foreach (var f in faces)
        {
            foreach (var he in f.Circulate())
            {
                halfedges.Add(he);
                vertices.Add(he.vert);
            }
        }
        JSONClass o = new JSONClass();

        o.Add("face", new JSONData(face.id));
        var faceArray = new JSONArray();

        foreach (var f in faces)
        {
            var faceObj = new JSONClass();
            faceObj.Add("id", new JSONData(f.id));
            faceObj.Add("label", new JSONData(f.label));
            faceObj.Add("he", new JSONData(f.halfedge.id));
            faceArray.Add(faceObj);
        }
        o.Add("faces", faceArray);
        var halfedgeArray = new JSONArray();

        foreach (var he in halfedges)
        {
            var heObj = new JSONClass();
            heObj.Add("id", new JSONData(he.id));
            heObj.Add("opp", new JSONData(he.opp != null?he.opp.id:-1));
            heObj.Add("next", new JSONData(he.next.id));
            heObj.Add("label", new JSONData(he.label));
            heObj.Add("face", new JSONData(he.face.id));
            heObj.Add("vert", new JSONData(he.vert.id));
            halfedgeArray.Add(heObj);
        }
        o.Add("halfedges", halfedgeArray);

        var vertexArray = new JSONArray();

        foreach (var vert in vertices)
        {
            var vertObj = new JSONClass();
            vertObj.Add("id", new JSONData(vert.id));
            vertObj.Add("he", new JSONData(vert.halfedge.id));
            vertObj.Add("label", new JSONData(vert.label));
            var vertexPosition = new JSONArray();
            vertexPosition.Add(new JSONData(vert.positionD.x));
            vertexPosition.Add(new JSONData(vert.positionD.y));
            vertexPosition.Add(new JSONData(vert.positionD.z));
            vertObj.Add("position", vertexPosition);
            vertexArray.Add(vertObj);
        }
        o.Add("vertices", vertexArray);

        return(o.ToString());
    }