Example #1
0
        private IEnumerable <StateDescriptor> RandomStateDescriptors(int count = 1)
        {
            for (; count >= 0; count--)
            {
                var ret = new StateDescriptor()
                {
                    Type  = RandomEnum <StateType>(),
                    Value = RandomBytes(_random.Next(1, byte.MaxValue))
                };

                switch (ret.Type)
                {
                case StateType.Account:
                {
                    ret.Key   = RandomBytes(20);
                    ret.Field = "Votes";
                    break;
                }

                case StateType.Validator:
                {
                    ret.Key   = RandomBytes(33);
                    ret.Field = "Registered";
                    break;
                }
                }

                yield return(ret);
            }
        }
Example #2
0
        /// <summary>
        /// Resets the trackers and reenables the RigidBodies.
        /// </summary>
        public override void End()
        {
            SelectedBody = null;
            //(PlayerPrefs.GetInt("analytics") == 1.ToString());
            //(SimUI.changeAnalytics.ToString());
            if (PlayerPrefs.GetInt("analytics") == 1)
            {
                Analytics.CustomEvent("Replay Mode", new Dictionary <string, object>
                {
                    { "time", Time.time - tStart },
                });
            }

            foreach (Tracker t in trackers)
            {
                if (t.Trace)
                {
                    UnityEngine.Object.Destroy(t.gameObject.GetComponent <LineRenderer>());
                }

                StateDescriptor currentState = t.States[(int)Math.Floor(RewindFrame)];

                RigidBody r = (RigidBody)t.GetComponent <BRigidBody>().GetCollisionObject();
                r.LinearFactor    = r.AngularFactor = BulletSharp.Math.Vector3.One;
                r.LinearVelocity  = currentState.LinearVelocity;
                r.AngularVelocity = currentState.AngularVelocity;

                t.Clear();
            }
        }
Example #3
0
        internal static void ProcessValidatorStateDescriptor(StateDescriptor descriptor, Snapshot snapshot)
        {
            ECPoint        pubkey    = ECPoint.DecodePoint(descriptor.Key, ECCurve.Secp256);
            ValidatorState validator = snapshot.Validators.GetAndChange(pubkey, () => new ValidatorState(pubkey));

            switch (descriptor.Field)
            {
            case "Registered":
                validator.Registered = BitConverter.ToBoolean(descriptor.Value, 0);
                break;
            }
        }
        private async Task ProcessAccountStateDescriptor(StateDescriptor descriptor)
        {
            var accountHash = new UInt160(descriptor.Key);

            switch (descriptor.Field)
            {
            case "Votes":
                var chosenValidators = _deserializer.Deserialize <ECPoint[]>(descriptor.Value);
                await _accountManager.UpdateVotes(accountHash, chosenValidators);

                break;
            }
        }
        private async Task ProcessValidatorStateDescriptor(StateDescriptor descriptor)
        {
            var pubKey    = new ECPoint(descriptor.Key);
            var validator = await _repository.GetValidator(pubKey) ?? new Validator
            {
                PublicKey = pubKey
            };

            switch (descriptor.Field)
            {
            case "Registered":
                validator.Registered = BitConverter.ToBoolean(descriptor.Value, 0);
                break;
            }

            await _repository.AddValidator(validator);
        }
Example #6
0
        /// <summary>
        /// Removes the current state from the StateMachine and
        /// resumes execution of the previous one if specified.
        /// </summary>
        /// <param name="resumePrevious"></param>
        /// <returns></returns>
        private State PopState(bool resumePrevious)
        {
            if (CurrentState == null)
            {
                return(null);
            }

            CurrentState.Pause();
            CurrentState.End();

            DisableAllObjects(true);

            activeStates.Pop();

            if (resumePrevious && activeStates.Count > 0)
            {
                CurrentState = activeStates.First();

                EnableAllObjects();

                CurrentState.Resume();
            }
            else
            {
                CurrentState = null;
            }

            if (unfreeze)
            {
                unfreeze = false;
                foreach (Tracker t in UnityEngine.Object.FindObjectsOfType <Tracker>().ToList())
                {
                    StateDescriptor currentState = t.States.First();

                    RigidBody r = (RigidBody)t.GetComponent <BRigidBody>().GetCollisionObject();
                    r.LinearFactor    = r.AngularFactor = BulletSharp.Math.Vector3.One;
                    r.LinearVelocity  = currentState.LinearVelocity;
                    r.AngularVelocity = currentState.AngularVelocity;
                    t.Clear();
                }
            }

            return(CurrentState);
        }
Example #7
0
        protected TState GetPartitionedState <TState, TNamespace, TValue>(
            TNamespace @namespace,
            TypeSerializer <TNamespace> namespaceSerializer,
            StateDescriptor <TState, TValue> stateDescriptor) where TState : IState
        {
            /*
             * TODO: NOTE: This method does a lot of work caching / retrieving states just to update the namespace.
             * This method should be removed for the sake of namespaces being lazily fetched from the keyed
             * state backend, or being set on the state directly.
             */

            if (KeyedStateStore == null)
            {
                throw new RuntimeException("Cannot create partitioned state. The keyed state " +
                                           "backend has not been set. This indicates that the operator is not " +
                                           "partitioned/keyed.");
            }

            return(KeyedStateBackend.GetPartitionedState(@namespace, namespaceSerializer, stateDescriptor));
        }
        internal override bool UpdateViewModel <S, O>(StateDescriptor <S, O> state)
        {
            TicTacToeStateDescriptor descriptor = state.State as TicTacToeStateDescriptor;

            OptionsDescriptor <TicTacToeOptionDescriptor>[] options = state.Options as OptionsDescriptor <TicTacToeOptionDescriptor>[];

            if (state.StateNo == 0 && LastState != 0)
            {
                string you   = GameLoader.Instance.Player.Name;
                string other = Match.CurrentPlayers.First(x => x != you);
                CrossPlayer  = state.CurrentPlayer == you ? you : other;
                CirclePlayer = CrossPlayer == you ? other : you;
                _symbols.Add(true, CrossPlayer == you ? "X" : "O");
                _symbols.Add(false, CrossPlayer == you ? "O" : "X");
            }
            if (Boxes == null)
            {
                Boxes = InitializeBoxes(descriptor.Board);
            }
            for (int i = 0; i < X; i++)
            {
                for (int j = 0; j < Y; j++)
                {
                    Boxes[Y * i + j].IsEnabled  = descriptor.Board[i][j] == null && state.CurrentPlayer == GameLoader.Instance.Player.Name;
                    Boxes[Y * i + j].Value      = descriptor.Board[i][j].HasValue ?_symbols[descriptor.Board[i][j].Value] : null;
                    Boxes[Y * i + j].OptionCode = options?.FirstOrDefault(x => x.Option.X == i && x.Option.Y == j)?.OptionCode;
                }
            }
            bool gameOver = descriptor.Message != null;

            if (gameOver)
            {
                EndgameMessage = descriptor.Message;
                return(true);
            }
            else
            {
                EndgameMessage = $"{state.CurrentPlayer}'s turn";
            }
            return(false);
        }
Example #9
0
        /// <summary>
        /// Resets the trackers and reenables the RigidBodies.
        /// </summary>
        public override void End()
        {
            SelectedBody = null;

            foreach (Tracker t in trackers)
            {
                if (t.Trace)
                {
                    UnityEngine.Object.Destroy(t.gameObject.GetComponent <LineRenderer>());
                }

                StateDescriptor currentState = t.States[(int)Math.Floor(RewindFrame)];

                RigidBody r = (RigidBody)t.GetComponent <BRigidBody>().GetCollisionObject();
                r.LinearFactor    = r.AngularFactor = BulletSharp.Math.Vector3.One;
                r.LinearVelocity  = currentState.LinearVelocity;
                r.AngularVelocity = currentState.AngularVelocity;

                t.Clear();
            }
        }
Example #10
0
        internal static void ProcessAccountStateDescriptor(StateDescriptor descriptor, Snapshot snapshot)
        {
            UInt160      hash    = new UInt160(descriptor.Key);
            AccountState account = snapshot.Accounts.GetAndChange(hash, () => new AccountState(hash));

            switch (descriptor.Field)
            {
            case "Votes":
                Fixed8 balance = account.GetBalance(GoverningToken.Hash);
                foreach (ECPoint pubkey in account.Votes)
                {
                    ValidatorState validator = snapshot.Validators.GetAndChange(pubkey);
                    validator.Votes -= balance;
                    if (!validator.Registered && validator.Votes.Equals(Fixed8.Zero))
                    {
                        snapshot.Validators.Delete(pubkey);
                    }
                }
                ECPoint[] votes = descriptor.Value.AsSerializableArray <ECPoint>().Distinct().ToArray();
                if (votes.Length != account.Votes.Length)
                {
                    ValidatorsCountState count_state = snapshot.ValidatorsCount.GetAndChange();
                    if (account.Votes.Length > 0)
                    {
                        count_state.Votes[account.Votes.Length - 1] -= balance;
                    }
                    if (votes.Length > 0)
                    {
                        count_state.Votes[votes.Length - 1] += balance;
                    }
                }
                account.Votes = votes;
                foreach (ECPoint pubkey in account.Votes)
                {
                    snapshot.Validators.GetAndChange(pubkey, () => new ValidatorState(pubkey)).Votes += balance;
                }
                break;
            }
        }
Example #11
0
    public IObservable <StateDescriptor> Process(IObservable <StateInfo> source)
    {
        return(Observable.Create <StateDescriptor>(observer =>
        {
            var currentTrial = default(StateDescriptor);
            var stateObserver = Observer.Create <StateInfo>(
                info =>
            {
                if (currentTrial == null || currentTrial.Trial != info.Trial)
                {
                    currentTrial = new StateDescriptor(info.Trial);
                }

                var output = new StateDescriptor(currentTrial.Trial);
                if (info.Id < StateId.Annotation)
                {
                    currentTrial.Statistics[(int)info.Id] = info.ElapsedTime;
                }
                else
                {
                    output.Events = new[]
                    {
                        new EventDescriptor {
                            Id = info.Id, Value = info.ElapsedTime
                        }
                    }
                };

                for (int i = 0; i < output.Statistics.Length; i++)
                {
                    output.Statistics[i] = currentTrial.Statistics[i];
                }
                observer.OnNext(output);
            },
                observer.OnError,
                observer.OnCompleted);
            return StateInterval(source).SubscribeSafe(stateObserver);
        }));
    }
Example #12
0
        internal override bool UpdateViewModel <S, O>(StateDescriptor <S, O> state)
        {
            CEStateDescriptor descriptor = state.State as CEStateDescriptor;

            OptionsDescriptor <CEOptionDescriptor>[] options = state.Options as OptionsDescriptor <CEOptionDescriptor>[];
            currentOptions = options;

            Player             = descriptor.Player;
            CanUpgradeChampion = options.Any(x => x.Option.Action == "Upgrade");
            CurrentStage       = descriptor.Stage;
            Contracts          = descriptor.Contracts.Select(x => GameData.Cards.FirstOrDefault(y => y.ID == x));
            CurrentOptions     = options.Select(x => x.Option);
            StateName          = descriptor.StateName;

            if (StateName == "ChooseResources")
            {
                CardList      = Player.Hand.Select(id => GameData.Cards.First(x => x.ID == id));
                BonusCardList = Player.BonusCards.Select(id => GameData.Bonus.First(x => x.ID == id));
            }

            return(false);
        }
Example #13
0
 protected TState GetPartitionedState <TState, TValue>(StateDescriptor <TState, TValue> stateDescriptor) where TState : IState =>
 GetPartitionedState(VoidNamespace.Instance, VoidNamespaceSerializer.Instance, stateDescriptor);
 protected virtual TState GetPartitionedState <TState, TValue>(StateDescriptor <TState, TValue> stateDescriptor)
     where TState : IState
 {
     return(KeyedStateBackend.GetPartitionedState(VoidNamespace.Instance, VoidNamespaceSerializer.Instance, stateDescriptor));
 }
Example #15
0
        /// <summary>
        /// Updates the positions and rotations of each tracker's parent object according to the replay time.
        /// </summary>
        public override void LateUpdate()
        {
            if (dynamicCamera == null)
            {
                dynamicCamera = UnityEngine.Object.FindObjectOfType <DynamicCamera>();
                camera        = dynamicCamera.GetComponent <UnityEngine.Camera>();
            }

            if (Input.InputControl.GetButtonDown(Controls.buttons[0].cameraToggle))
            {
                dynamicCamera.ToggleCameraState(dynamicCamera.ActiveState);
            }

            if (firstFrame)
            {
                firstFrame = false;
            }
            else if (UnityEngine.Input.GetKeyDown(KeyCode.Space))
            {
                if (UnityEngine.Input.GetKey(KeyCode.LeftControl) || UnityEngine.Input.GetKey(KeyCode.RightControl))
                {
                    rewindTime   = Tracker.Lifetime;
                    playbackMode = PlaybackMode.Play;
                }
                else
                {
                    switch (playbackMode)
                    {
                    case PlaybackMode.Paused:
                        if (rewindTime == 0f)
                        {
                            rewindTime = Tracker.Lifetime;
                        }
                        playbackMode = PlaybackMode.Play;
                        break;

                    case PlaybackMode.Play:
                    case PlaybackMode.Rewind:
                        playbackMode = PlaybackMode.Paused;
                        break;
                    }
                }
            }

            switch (playbackMode)
            {
            case PlaybackMode.Rewind:
                rewindTime += Time.deltaTime;
                break;

            case PlaybackMode.Play:
                rewindTime -= Time.deltaTime;
                break;
            }

            if (UnityEngine.Input.GetKey(KeyCode.LeftArrow))
            {
                rewindTime  += Time.deltaTime * (UnityEngine.Input.GetKey(KeyCode.LeftControl) || UnityEngine.Input.GetKey(KeyCode.RightControl) ? 0.05f : 0.25f);
                playbackMode = PlaybackMode.Paused;
            }

            if (UnityEngine.Input.GetKey(KeyCode.RightArrow))
            {
                rewindTime  -= Time.deltaTime * (UnityEngine.Input.GetKey(KeyCode.LeftControl) || UnityEngine.Input.GetKey(KeyCode.RightControl) ? 0.05f : 0.25f);
                playbackMode = PlaybackMode.Paused;
            }

            if (rewindTime < 0.0f)
            {
                rewindTime   = 0.0f;
                playbackMode = PlaybackMode.Paused;
            }
            else if (rewindTime > Tracker.Lifetime)
            {
                rewindTime   = Tracker.Lifetime;
                playbackMode = PlaybackMode.Paused;
            }

            foreach (Tracker t in trackers)
            {
                float replayTime   = RewindFrame;
                int   currentIndex = (int)Math.Floor(replayTime);

                StateDescriptor lowerState = t.States[currentIndex];
                StateDescriptor upperState = currentIndex < t.States.Length - 1 ? t.States[currentIndex + 1] : lowerState;

                float percent = replayTime - currentIndex;

                BRigidBody rb = t.GetComponent <BRigidBody>();

                if (!rb.GetCollisionObject().IsActive)
                {
                    rb.GetCollisionObject().Activate();
                }

                rb.SetPosition(BulletSharp.Math.Vector3.Lerp(lowerState.Position, upperState.Position, percent).ToUnity());
                rb.SetRotation(BulletSharp.Math.Matrix.Lerp(lowerState.Rotation, upperState.Rotation, percent).GetOrientation().ToUnity());
            }
        }
Example #16
0
 /// <summary>
 /// Applies the provided <paramref name="function"/> to the state associated with the provided <see cref="StateDescriptor{TState,TValue}"/>.
 /// </summary>
 /// <typeparam name="TStateValue"></typeparam>
 /// <typeparam name="TState"></typeparam>
 /// <param name="stateDescriptor">the descriptor of the state to be processed.</param>
 /// <param name="function">the function to be applied.</param>
 public abstract void ApplyToKeyedState <TStateValue, TState>(StateDescriptor <TState, TStateValue> stateDescriptor, IKeyedStateFunction <TKey, TState> function)
     where TState : IState;
Example #17
0
 public void MergePartitionedState <TState>(StateDescriptor <TState, object> stateDescriptor) where TState : IMergingState <object, object>
 {
     throw new NotImplementedException();
 }
Example #18
0
 public TState GetPartitionedState <TState, TValue>(StateDescriptor <TState, TValue> stateDescriptor) where TState : IState
 {
     throw new NotImplementedException();
 }
Example #19
0
 protected override TState GetPartitionedState <TState, TValue>(StateDescriptor <TState, TValue> stateDescriptor)
 {
     return(KeyedStateBackend.GetPartitionedState(Window, WindowSerializer, stateDescriptor));
 }
Example #20
0
        private IKeyedStateStore CheckPreconditionsAndGetKeyedStateStore <TState, TValue>(StateDescriptor <TState, TValue> stateDescriptor) where TState : IState
        {
            Preconditions.CheckNotNull(stateDescriptor, "The state properties must not be null");

            var keyedStateStore = _operator.KeyedStateStore;

            Preconditions.CheckNotNull(keyedStateStore, "Keyed state can only be used on a 'keyed stream', i.e., after a 'keyBy()' operation.");

            return(keyedStateStore);
        }
Example #21
0
            public StateMachine <TState> Build()
            {
                var machineName = name;

                onInvalidTransition = onInvalidTransition ?? ((f, t) =>
                {
                    throw new NotSupportedException(String.Format("{0} transition not supported: {1} -> {2}", machineName, f, t));
                });

                stateComparer = stateComparer ?? EqualityComparer <TState> .Default;

                var enter  = new Dictionary <TState, List <Action <TState> > >(stateComparer);
                var exit   = new Dictionary <TState, List <Action <TState> > >(stateComparer);
                var update = new Dictionary <TState, List <Action <TState> > >(stateComparer);
                var trans  = new Dictionary <TState, Dictionary <TState, List <Action <TState, TState> > > >(stateComparer);

                foreach (var item in activations)
                {
                    Dictionary <TState, List <Action <TState> > > dict = null;
                    switch (item.mode)
                    {
                    case ActivationMode.Enter:
                        dict = enter;
                        break;

                    case ActivationMode.Update:
                        dict = update;
                        break;

                    case ActivationMode.Exit:
                        dict = exit;
                        break;
                    }
                    List <Action <TState> > list;
                    if (!dict.TryGetValue(item.state, out list))
                    {
                        list = new List <Action <TState> >();
                        dict.Add(item.state, list);
                    }

                    list.Add(item.onTrigger);
                }

                foreach (var item in transitions)
                {
                    Dictionary <TState, List <Action <TState, TState> > > listDict;
                    if (!trans.TryGetValue(item.fromState, out listDict))
                    {
                        listDict = new Dictionary <TState, List <Action <TState, TState> > >(stateComparer);
                        trans.Add(item.fromState, listDict);
                    }

                    List <Action <TState, TState> > list;
                    if (!listDict.TryGetValue(item.toState, out list))
                    {
                        list = new List <Action <TState, TState> >();
                        listDict.Add(item.toState, list);
                    }

                    list.Add(item.onTrigger);
                }

                var states = new Dictionary <TState, StateDescriptor <TState> >(stateComparer);
                var keys   = enter.Keys
                             .Concat(exit.Keys).Concat(update.Keys).Concat(trans.Keys)
                             .Distinct(stateComparer);

                var EmptyActions = new Action <TState> [0];

                states = keys.ToDictionary(
                    s => s,
                    s =>
                {
                    var onEnterActions  = enter.ContainsKey(s) ? enter[s].ToArray() : EmptyActions;
                    var onUpdateActions = update.ContainsKey(s) ? update[s].ToArray() : EmptyActions;
                    var onExitActions   = exit.ContainsKey(s) ? exit[s].ToArray() : EmptyActions;
                    var transitions     = trans.ContainsKey(s) ? trans[s].ToDictionary(p => p.Key, p => p.Value.ToArray(), stateComparer) : new Dictionary <TState, Action <TState, TState>[]>();

                    return(new StateDescriptor <TState>
                    {
                        current = s,
                        onEnterActions = onEnterActions,
                        onUpdateActions = onUpdateActions,
                        onExitActions = onExitActions,
                        transitions = transitions,
                    });
                },
                    stateComparer);

                var anyState = new StateDescriptor <TState>
                {
                    current         = default(TState),
                    onEnterActions  = activationsAny.Where(a => a.mode == ActivationMode.Enter).Select(a => a.onTrigger).ToArray(),
                    onUpdateActions = activationsAny.Where(a => a.mode == ActivationMode.Update).Select(a => a.onTrigger).ToArray(),
                    onExitActions   = activationsAny.Where(a => a.mode == ActivationMode.Exit).Select(a => a.onTrigger).ToArray(),
                    transitions     = new Dictionary <TState, Action <TState, TState>[]>(),
                };

                var anyTransition = transitionsAny.Select(t => t.onTrigger).ToArray();

                return(new StateMachine <TState>(
                           machineName,
                           initialState,
                           stateComparer ?? EqualityComparer <TState> .Default,
                           onInvalidTransition,
                           states,
                           anyState,
                           anyTransition
                           ));
            }