Example #1
0
    public static ConsumableEvent Create(GameObject gameObject, float reward, Vector3 position)
    {
        ConsumableEvent e = new ConsumableEvent();

        e.Type     = QuarkEventType.Consumable;
        e.Id       = gameObject.GetInstanceID();
        e.Tag      = gameObject.tag;
        e.Reward   = reward;
        e.Position = position;
        return(e);
    }
Example #2
0
 /// <summary>
 /// Invoked to actually execute a single workitem
 /// </summary>
 /// <param name="workItem"></param>
 protected virtual async Task <bool> Execute(ConsumableEvent workItem)
 {
     // Only process if still invisible (serial processing of a list of workitems may cause workitems to expire before being processed)
     if (workItem.InvisibleUntilUtc > DateTime.UtcNow) // DateTime not queried on repo, because of excessive load
     {
         return(await ExecuteConcrete(workItem).ConfigureAwait(false));
     }
     else
     {
         LogWarning("ConsumableEvent with id {Id} has expired: InvisibleUntilUtc ({InvisibleUntilUtc}) < UtcNow ({UtcNow}).",
                    workItem.Id, workItem.InvisibleUntilUtc, DateTime.UtcNow);
         return(false);
     }
 }
Example #3
0
        private void sendConsumableEvent(EntityRef entity, Event @event, IList <EventHandlerInfo> selectedHandlers)
        {
            ConsumableEvent consumableEvent = (ConsumableEvent)@event;

            foreach (EventHandlerInfo handler in selectedHandlers)
            {
                // Check isValid at each stage in case components were removed.
                if (handler.isValidFor(entity))
                {
                    handler.invoke(entity, @event);
                    if (consumableEvent.Consumed)
                    {
                        return;
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Executes a workitem and calls Complete on success (no exception and true returned by Execute) or Failed otherwise.
        /// </summary>
        /// <param name="workItem"></param>
        private async Task ExecuteWork(ConsumableEvent workItem)
        {
            bool      success = false;
            Exception execEx  = null;

            Stopwatch w = new Stopwatch();

            w.Start();
            try
            {
                success = await this.Execute(workItem).ConfigureAwait(false);

                w.Stop();
            }
            catch (Exception ex)
            {
                w.Stop();
                success = false;
                execEx  = ex;
            }
        }
Example #5
0
    public override void AddReward(BaseAgent agent, float[] vectorActions)
    {
        Mult = AcademyParameters.Update(academy, MultKeyVal, Mult);
        agent.TriggerCollider
        .Filter(tc => tc != null)
        .Filter(tc => tc.gameObject.tag == "consumable")
        .MatchSome(tc => {
            GameObject go         = tc.gameObject;
            Consumable consumable = go.GetComponent <Consumable>();
            agent.AddReward(consumable.value * Mult);

            SpawnDistance         = AcademyParameters.Update(academy, SpawnDistanceKeyVal, SpawnDistance);
            Vector2 pos           = new Vector2(Random.Range(-SpawnDistance, SpawnDistance), Random.Range(-SpawnDistance, SpawnDistance));
            go.transform.position = new Vector3(pos.x, go.transform.position.y, pos.y);

            if (agent.area.EventSystem != null)
            {
                agent.area.EventSystem.RaiseEvent(ConsumableEvent.Create(agent.gameObject, consumable.value, tc.transform.position));
            }
        });
    }
        private void onConsumableUsed(GameServerEvent gameServerEvent, object data)
        {
            ConsumableEvent consumableEvent = (ConsumableEvent)data;

            Service.Get <EventDispatcher>().DispatchEvent(new ConsumableServiceEvents.ConsumableUsed(consumableEvent.SessionId, consumableEvent.Type));
        }
Example #7
0
        private async Task <bool> ExecuteConcrete(ConsumableEvent ce)
        {
            ConsumeResult result       = null;
            bool          mustRollback = false;

            try
            {
                LogTrace("Processing event with id {Id} and functional key {FunctionalKey}.",
                         ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a");
                result = await _consumeAction(ce).ConfigureAwait(false);
            }
            catch (Exception procEx)
            {
                // Unhandled exception is translated to Failed
                result = ConsumeResult.Failed(procEx.ToString());
            }

            LogTrace("Processing done for event with id {Id} and functional key {FunctionalKey}. Result: {result}",
                     ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a", result);

            switch (result.ResultType)
            {
            case ConsumeResultType.Succeeded:
            {
                bool markedConsumed = false;

                try
                {
                    await _eventConsumer.MarkConsumedAsync(ce.Id, ce.DeliveryKey).ConfigureAwait(false);

                    markedConsumed = true;
                    LogTrace("Event consumption succeeded for event with id {Id} and functional key {FunctionalKey}.",
                             ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a");
                }
                catch (Exception ex)
                {
                    LogError("Failed to mark event consumed with id {Id} and functional key {FunctionalKey}, cause event to be processes again! Details: {Exception}.",
                             ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a", ex);
                    // mustRollback doesn't actually need to be set, since markedConsumed will no longer be true
                    mustRollback = true;
                }

                if (!markedConsumed)
                {
                    mustRollback = true;
                }
            }
            break;

            case ConsumeResultType.Failed:
            {
                mustRollback = true;
                LogError("Exception occurred while processing event with id {Id} and functional key {FunctionalKey}: {Reason}.",
                         ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a", result.Reason);

                try
                {
                    await _eventConsumer.MarkFailedAsync(ce.Id, ce.DeliveryKey, Reason.Other(result.Reason)).ConfigureAwait(false);
                }
                catch (Exception) { }         // Swallow, since it's not a disaster if this gets processed again
            }
            break;

            case ConsumeResultType.MustSuspend:
            {
                mustRollback = true;
                var suspendedUntilUtc = this.Suspend(result.SuspendDuration.GetValueOrDefault(TimeSpan.FromSeconds(60)));
                LogError("Event consumption failed for event with id {Id} and functional key {FunctionalKey}. Processing should (continue to) suspend. Details: {Reason}.",
                         ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a", result.Reason);
            }
            break;

            case ConsumeResultType.MustRetry:
            {
                mustRollback = true;
                LogWarning("Retry requested while processing event with id {Id} and functional key {FunctionalKey}: {Reason}.",
                           ce.Id, ce.FunctionalKey != null ? ce.FunctionalKey : "n/a", result.Reason);  // Logged as warning, since a requested retry is not (yet) an error
            }
            break;

            default:
                // No special handling for other cases
                break;
            }

            return(result.ResultType == ConsumeResultType.Succeeded && !mustRollback);
        }
Example #8
0
        private void onExtensionResponse(BaseEvent evt)
        {
            try
            {
                ISFSObject iSFSObject = (ISFSObject)evt.Params["params"];
                if (mt.SmartFoxEncryptor != null)
                {
                    mt.SmartFoxEncryptor.DecryptParameters(iSFSObject);
                }
                int?userId = null;
                if (iSFSObject.ContainsKey("senderId"))
                {
                    userId = iSFSObject.GetInt("senderId");
                }
                SmartfoxCommand?smartfoxCommand = SmartFoxCommand.FromString((string)evt.Params["cmd"]);
                if (!smartfoxCommand.HasValue)
                {
                    return;
                }
                object          data            = null;
                GameServerEvent?gameServerEvent = null;
                switch (smartfoxCommand.Value)
                {
                case SmartfoxCommand.CHAT_ACTIVITY:
                    gameServerEvent = GameServerEvent.CHAT_ACTIVITY_RECEIVED;
                    data            = getSessionId(userId);
                    break;

                case SmartfoxCommand.CHAT_ACTIVITY_CANCEL:
                    gameServerEvent = GameServerEvent.CHAT_ACTIVITY_CANCEL_RECEIVED;
                    data            = getSessionId(userId);
                    break;

                case SmartfoxCommand.CHAT:
                    gameServerEvent = GameServerEvent.CHAT_MESSAGE_RECEIVED;
                    data            = mt.JsonService.Deserialize <ReceivedChatMessage>(iSFSObject.GetUtfString("msg"));
                    break;

                case SmartfoxCommand.GET_SERVER_TIME:
                    timeStampRecieved(iSFSObject.GetLong("ct"), iSFSObject.GetLong("st"));
                    break;

                case SmartfoxCommand.SERVER_TIME_ERROR:
                    fetchServerTimestamp(fetchEncryptionKeyAfterwards: false);
                    break;

                case SmartfoxCommand.GET_ROOM_ENCRYPTION_KEY:
                    encryptionKeyReceived(iSFSObject.GetUtfString("ek"));
                    break;

                case SmartfoxCommand.ENCRYPTION_KEY_ERROR:
                    Log.LogError(this, "Failed to get room encryption key.");
                    mt.teardown();
                    gameServerEvent = GameServerEvent.ROOM_JOIN_ERROR;
                    data            = null;
                    break;

                case SmartfoxCommand.LOCOMOTION_ACTION:
                    gameServerEvent = GameServerEvent.USER_LOCO_ACTION;
                    data            = locomotionActionEventFromProps(userId.Value, iSFSObject);
                    break;

                case SmartfoxCommand.PROTOTYPE:
                {
                    gameServerEvent = GameServerEvent.PROTOTYPE_ACTION;
                    PrototypeAction prototypeAction = default(PrototypeAction);
                    prototypeAction.userid = getSessionId(userId);
                    prototypeAction.data   = JsonMapper.ToObject(iSFSObject.GetUtfString("data"));
                    data = prototypeAction;
                    break;
                }

                case SmartfoxCommand.SERVER_OBJECTIVE_COMPLETED:
                    gameServerEvent = GameServerEvent.QUEST_OBJECTIVES_UPDATED;
                    data            = mt.JsonService.Deserialize <SignedResponse <QuestObjectives> >(iSFSObject.GetUtfString("data"));
                    break;

                case SmartfoxCommand.SERVER_QUEST_ERROR:
                    gameServerEvent = GameServerEvent.QUEST_ERROR;
                    data            = null;
                    break;

                case SmartfoxCommand.SET_QUEST_STATES:
                    gameServerEvent = GameServerEvent.QUEST_DATA_SYNCED;
                    data            = null;
                    break;

                case SmartfoxCommand.USE_CONSUMABLE:
                {
                    gameServerEvent = GameServerEvent.CONSUMABLE_USED;
                    ConsumableEvent consumableEvent = default(ConsumableEvent);
                    consumableEvent.SessionId = getSessionId(userId);
                    consumableEvent.Type      = iSFSObject.GetUtfString("type");
                    data = consumableEvent;
                    break;
                }

                case SmartfoxCommand.REUSE_FAILED:
                {
                    gameServerEvent = GameServerEvent.CONSUMABLE_REUSE_FAILED;
                    ConsumableUseFailureEvent consumableUseFailureEvent = default(ConsumableUseFailureEvent);
                    consumableUseFailureEvent.Type       = iSFSObject.GetUtfString("type");
                    consumableUseFailureEvent.Properties = JsonMapper.ToObject(iSFSObject.GetUtfString("prop"));
                    data = consumableUseFailureEvent;
                    break;
                }

                case SmartfoxCommand.CONSUMABLE_MMO_DEPLOYED:
                    if (iSFSObject.ContainsKey("ownerId") && iSFSObject.ContainsKey("senderId"))
                    {
                        gameServerEvent = GameServerEvent.CONSUMABLE_MMO_DEPLOYED;
                        ConsumableMMODeployedEvent consumableMMODeployedEvent = default(ConsumableMMODeployedEvent);
                        consumableMMODeployedEvent.SessionId    = getSessionId(iSFSObject.GetInt("ownerId"));
                        consumableMMODeployedEvent.ExperienceId = iSFSObject.GetInt("senderId");
                        data = consumableMMODeployedEvent;
                    }
                    break;

                case SmartfoxCommand.SET_CONSUMABLE_PARTIAL_COUNT:
                    gameServerEvent = GameServerEvent.COMSUMBLE_PARTIAL_COUNT_SET;
                    data            = mt.JsonService.Deserialize <SignedResponse <UsedConsumable> >(iSFSObject.GetUtfString("data"));
                    break;

                case SmartfoxCommand.RECEIVED_REWARDS:
                    gameServerEvent = GameServerEvent.RECEIVED_REWARDS;
                    data            = mt.JsonService.Deserialize <SignedResponse <RewardedUserCollectionJsonHelper> >(iSFSObject.GetUtfString("reward"));
                    break;

                case SmartfoxCommand.RECEIVED_REWARDS_DELAYED:
                    gameServerEvent = GameServerEvent.RECEIVED_REWARDS_DELAYED;
                    data            = mt.JsonService.Deserialize <SignedResponse <RewardedUserCollectionJsonHelper> >(iSFSObject.GetUtfString("reward"));
                    break;

                case SmartfoxCommand.RECEIVED_ROOOM_REWARDS:
                    gameServerEvent = GameServerEvent.RECEIVED_ROOOM_REWARDS;
                    data            = mt.JsonService.Deserialize <SignedResponse <InRoomRewards> >(iSFSObject.GetUtfString("reward"));
                    break;

                case SmartfoxCommand.PROGRESSION_LEVELUP:
                {
                    gameServerEvent = GameServerEvent.LEVELUP;
                    UserLevelUpEvent userLevelUpEvent = default(UserLevelUpEvent);
                    userLevelUpEvent.SessionId = getSessionId(userId);
                    userLevelUpEvent.Level     = iSFSObject.GetInt("level");
                    data = userLevelUpEvent;
                    break;
                }

                case SmartfoxCommand.ROOM_TRANSIENT_DATA:
                    mt.LastRoomTransientData = mt.JsonService.Deserialize <SignedResponse <TransientData> >(iSFSObject.GetUtfString("d"));
                    break;

                case SmartfoxCommand.TASK_COUNT:
                {
                    gameServerEvent = GameServerEvent.TASK_COUNT_UPDATED;
                    TaskProgress taskProgress = default(TaskProgress);
                    taskProgress.taskId  = iSFSObject.GetUtfString("t");
                    taskProgress.counter = iSFSObject.GetInt("c");
                    data = taskProgress;
                    break;
                }

                case SmartfoxCommand.TASK_PROGRESS:
                    gameServerEvent = GameServerEvent.TASK_PROGRESS_UPDATED;
                    data            = mt.JsonService.Deserialize <SignedResponse <TaskProgress> >(iSFSObject.GetUtfString("d"));
                    break;

                case SmartfoxCommand.GET_SIGNED_STATE:
                    gameServerEvent = GameServerEvent.STATE_SIGNED;
                    data            = mt.JsonService.Deserialize <SignedResponse <InWorldState> >(iSFSObject.GetUtfString("data"));
                    break;

                case SmartfoxCommand.GET_PLAYER_LOCATION:
                    gameServerEvent = GameServerEvent.PLAYER_LOCATION_RECEIVED;
                    data            = SmartFoxGameServerClientShared.deserializeVec3(iSFSObject, "pos");
                    break;

                case SmartfoxCommand.PLAYER_NOT_FOUND:
                    gameServerEvent = GameServerEvent.PLAYER_NOT_FOUND;
                    break;

                case SmartfoxCommand.PARTY_GAME_START:
                    gameServerEvent = GameServerEvent.PARTY_GAME_START;
                    data            = partyGameStartEventFromProps(iSFSObject);
                    break;

                case SmartfoxCommand.PARTY_GAME_START_V2:
                    gameServerEvent = GameServerEvent.PARTY_GAME_START_V2;
                    data            = partyGameStartEventV2FromProps(iSFSObject);
                    break;

                case SmartfoxCommand.PARTY_GAME_END:
                    gameServerEvent = GameServerEvent.PARTY_GAME_END;
                    data            = partyGameEndEventFromProps(iSFSObject);
                    break;

                case SmartfoxCommand.PARTY_GAME_MESSAGE:
                    gameServerEvent = GameServerEvent.PARTY_GAME_MESSAGE;
                    data            = partyGameMessageEventFromProps(iSFSObject);
                    break;

                case SmartfoxCommand.IGLOO_UPDATED:
                    gameServerEvent = GameServerEvent.IGLOO_UPDATED;
                    data            = iSFSObject.GetUtfString("igloo_id");
                    break;

                case SmartfoxCommand.FORCE_LEAVE:
                    gameServerEvent = GameServerEvent.FORCE_LEAVE;
                    data            = mt.JsonService.Deserialize <ZoneId>(iSFSObject.GetUtfString("zone_id"));
                    break;
                }
                if (gameServerEvent.HasValue)
                {
                    mt.triggerEvent(gameServerEvent.Value, data);
                }
            }
            catch (JsonException ex)
            {
                Log.LogNetworkError(this, "Error occurred getting data from SFS: " + ex.Message);
            }
        }