Beispiel #1
0
 public Guid GetNextGuid()
 {
     lock (this){
         LastAssignedGuid = GuidOps.Increment(LastAssignedGuid);
         return(LastAssignedGuid);
     }
 }
Beispiel #2
0
        internal void TryCreateArenaForPlayersAsync(IMatchMaker match_maker, List <Player> buffer)
        {
            if (is_disposing())
            {
                return;
            }

            Task.Run(async() =>
            {
                var attempt = new CreateArenaAttempt();
                foreach (var player in buffer)
                {
                    attempt.PlayerInfo.Add(new ArenaServer.PlayerInfo
                    {
                        AuthToken = GuidOps.ToByteString(Guid.NewGuid()),
                        BasicInfo = player.BasicPlayerInfo()
                    });
                }

                foreach (var arena in hosts)
                {
                    if (await arena.TryCreateArenaForPlayers(buffer, attempt))
                    {
                        return;
                    }
                }

                match_maker.AddPlayers(buffer);
            });
        }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Sequencer"/> class.
 /// </summary>
 /// <param name="sequencerKey">The sequencer key.</param>
 /// <param name="myIndex">The creator's index.</param>
 /// <param name="rootHeight">Height of the root.</param>
 public Sequencer(Guid sequencerKey, int myIndex, int rootHeight)
 {
     m_sequenceKey = sequencerKey;
     m_myIndex     = myIndex;
     m_myKey       = GuidOps.Add(sequencerKey, myIndex);
     m_rootHeight  = rootHeight;
 }
Beispiel #4
0
            internal Guid GetNextExecutionInstanceUid()
            {
                Debug.Assert(!m_nextExecutionInstanceUid.Equals(Guid.Empty));
                Guid retval = m_nextExecutionInstanceUid;

                m_nextExecutionInstanceUid = GuidOps.Increment(m_nextExecutionInstanceUid);
                m_numberOfIterations++;
                return(retval);
            }
Beispiel #5
0
 public Vessel(IModel model, string name, string description, Guid guid, double capacity, double pressure, bool autoReset)
 {
     InitializeIdentity(model, name, description, guid);
     m_mixture                  = new Mixture(model, name + ".Mixture", GuidOps.XOR(guid, s_mixture_Guidmask));
     m_mixtureMass              = new DoubleTracker();
     m_mixtureVolume            = new DoubleTracker();
     m_mixture.MaterialChanged += new MaterialChangeListener(m_mixture_MaterialChanged);
     m_pressure                 = m_initialPressure = pressure;
     m_capacity                 = capacity;
     m_autoReset                = autoReset;
     m_model.Starting          += new ModelEvent(m_model_Starting);
 }
Beispiel #6
0
 public int GetGenerationFromGuid(Guid guid)
 {
     for (int i = 0; i < 10; i++)
     {
         if (GuidOps.Add(Specification.Guid, i).Equals(guid))
         {
             return(i);
         }
     }
     throw new ApplicationException("Generation count exceeded ten - error.");
     // TODO: Need a more robust GUID subtraction routine.
 }
Beispiel #7
0
        /// <summary>
        /// Creates a new instance of the <see cref="T:Reaction"/> class.
        /// </summary>
        /// <param name="model">The model in which this object runs.</param>
        /// <param name="name">The user-friendly name of this object. Typically not required to be unique in a pan-model context.</param>
        /// <param name="guid">The GUID of this object. Typically registered as this object's ModelObject key, and thus, required to be unique in a pan-model context.</param>
        public Reaction(IModel model, string name, Guid guid)
        {
            InitializeIdentity(model, name, null, guid);

            if (model != null)
            {
                model.Starting += model_Starting;
            }
            m_model      = model;
            m_nextRiGuid = GuidOps.XOR(m_guid, DEFAULT_RI_GUIDMASK);

            IMOHelper.RegisterWithModel(this);
        }
Beispiel #8
0
        protected void GetPermissionToStart(PfcExecutionContext myPfcec, StepStateMachine ssm)
        {
            PfcExecutionContext root = myPfcec;
            int ascents = m_rootHeight;

            while (ascents > 0)
            {
                root = (PfcExecutionContext)myPfcec.Parent.Payload;
                ascents--;
            }

            Exchange exchange = null;

            if (m_myIndex == 0)
            {
                //Console.WriteLine(myPfcec.Name + " is creating an exchange and injecting it into pfcec " + root.Name + " under key " + m_sequenceKey);
                exchange = new Exchange(myPfcec.Model.Executive);
                root.Add(m_sequenceKey, exchange);
            }
            else
            {
                //Console.WriteLine(myPfcec.Name + " is looking for an exchange in pfcec " + root.Name + " under key " + m_sequenceKey);
                DictionaryChange dc = new DictionaryChange(myPfcec_EntryAdded);
                while (true)
                {
                    exchange = (Exchange)root[m_sequenceKey];
                    if (exchange == null)
                    {
                        root.EntryAdded += dc;
                        m_idec           = myPfcec.Model.Executive.CurrentEventController;
                        m_idec.Suspend();
                    }
                    else
                    {
                        root.EntryAdded -= dc;
                        break;
                    }
                }
                exchange.Take(m_myKey, true); // Only indices 1,2, ... take (and wait?). Index 0 only posts.
                //Console.WriteLine(myPfcec.Name + " got the key I was looking for!");
            }
            Guid nextGuysKey = GuidOps.Increment(m_myKey);

            exchange.Post(nextGuysKey, nextGuysKey, false);
            //Console.WriteLine(myPfcec.Name + " posted the key the next guy is looking for!");
        }
Beispiel #9
0
        internal async Task Logout(ServerCallContext context)
        {
            if (disposedValue)
            {
                Log.Warning("Tried to log out player while auth is disposing.");
                return;
            }

            var  header = GetHeader(context, Constants.SessionTokenHeader);
            Guid session_id;

            if (!GuidOps.TryParse(header, out session_id))
            {
                return;
            }
            await Logout(session_id);
        }
Beispiel #10
0
        public GuidCollection ParseGuidList(string list, bool unique)
        {
            GuidCollection guids = new GuidCollection();

            foreach (string str in list.Split(new char[] { ',', ';', '|' }))
            {
                Guid guid = GuidOps.Str2Guid(str.Trim());
                if (guid != Guid.Empty)
                {
                    guids.Add(guid);
                }
            }
            if (!unique)
            {
                return(guids);
            }
            return(guids.RemoveDuplicates());
        }
Beispiel #11
0
        public IList <Guid> ParseGuidList(string list, bool unique)
        {
            List <Guid> guids = new List <Guid>();

            foreach (string str in list.Split(new char[] { ',', ';', '|' }))
            {
                Guid guid = GuidOps.Str2Guid(str.Trim());
                if (guid != Guid.Empty)
                {
                    guids.Add(guid);
                }
            }
            if (!unique)
            {
                return(guids);
            }
            return(guids);
        }
Beispiel #12
0
        public PfcExecutionContext(IProcedureFunctionChart pfc, string name, string description, Guid guid, PfcExecutionContext parent)
            : base(pfc.Model, name, description, guid, parent)
        {
            if (s_diagnostics)
            {
                string parentName = (parent == null ? "<null>" : parent.Name);
                Console.WriteLine("Creating PFCEC \"" + name + "\" under PFCEC \"" + parentName + "\" For parent " + pfc.Name + " and numbered " + guid);
            }

            m_pfc                = pfc;
            m_step               = null;
            m_timePeriod         = new TimePeriodEnvelope(name, GuidOps.XOR(guid, s_time_Period_Mask));
            m_timePeriod.Subject = this;
            if (parent != null)
            {
                ((TimePeriodEnvelope)parent.TimePeriod).AddTimePeriod(m_timePeriod);
            }
            m_timePeriod.ChangeEvent += new ObservableChangeHandler(m_timePeriod_ChangeEvent);
        }
Beispiel #13
0
        internal Player GetPlayer(ServerCallContext context)
        {
            if (disposedValue)
            {
                Log.Warning("Tried to get player while player auth is disposing.");
                return(null);
            }

            var  header = GetHeader(context, Constants.SessionTokenHeader);
            Guid session_token;

            if (header == null || !GuidOps.TryParse(header, out session_token))
            {
                return(null);
            }
            Player player;

            session_mapped_players.TryGetValue(session_token, out player);
            return(player);
        }
Beispiel #14
0
        /// <summary>
        /// Creates pfc execution contexts, one per action under the step that is currently running. Each
        /// is given an instance count of zero, as a step can run its action only once, currently.
        /// </summary>
        /// <param name="parentContext">The parent context, that of the step that is currently running.</param>
        /// <param name="kids">The procedure function charts that live in the actions under the step that is currently running.</param>
        /// <param name="kidContexts">The pfc execution contexts that will correspond to the running of each of the child PFCs.</param>
        protected virtual void CreateChildContexts(PfcExecutionContext parentContext, out IProcedureFunctionChart[] kids, out PfcExecutionContext[] kidContexts)
        {
            int kidCount = MyStep.Actions.Count;

            kids        = new ProcedureFunctionChart[kidCount];
            kidContexts = new PfcExecutionContext[kidCount];
            int i = 0;

            foreach (KeyValuePair <string, IProcedureFunctionChart> kvp in MyStep.Actions)
            {
                IProcedureFunctionChart kid = kvp.Value;
                kids[i] = kid;
                Guid kidGuid = GuidOps.XOR(parentContext.Guid, kid.Guid);
                while (parentContext.Contains(kidGuid))
                {
                    kidGuid = GuidOps.Increment(kidGuid);
                }
                kidContexts[i] = new PfcExecutionContext(kid, kvp.Key, null, kidGuid, parentContext);
                kidContexts[i].InstanceCount = 0;
                i++;
            }
        }
Beispiel #15
0
        public PfcExecutionContext(IPfcStepNode stepNode, string name, string description, Guid guid, PfcExecutionContext parent)
            : base(stepNode.Parent.Model, name, description, guid, parent)
        {
            if (s_diagnostics)
            {
                Console.WriteLine("Creating PfcEC \"" + name + "\" under PfcEC \"" + parent.Name + "\" For parent " + stepNode.Name + " and numbered " + guid);
            }

            m_pfc  = stepNode.Parent;
            m_step = stepNode;
            if (stepNode.Actions.Count == 0)
            {
                m_timePeriod         = new TimePeriod(name, GuidOps.XOR(guid, s_time_Period_Mask), TimeAdjustmentMode.InferDuration);
                m_timePeriod.Subject = this;
                ((TimePeriodEnvelope)parent.TimePeriod).AddTimePeriod(m_timePeriod);
            }
            else
            {
                m_timePeriod         = new TimePeriodEnvelope(name, GuidOps.XOR(guid, s_time_Period_Mask));
                m_timePeriod.Subject = this;
                ((TimePeriodEnvelope)parent.TimePeriod).AddTimePeriod(m_timePeriod);
            }
            m_timePeriod.ChangeEvent += new ObservableChangeHandler(m_timePeriod_ChangeEvent);
        }
Beispiel #16
0
        /// <summary>
        /// Causes the reaction to take place, if possible, in (and perform modifications to, the provided target mixture.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public ReactionInstance React(Mixture target)
        {
            // We will handle a reaction's completion percentage/equilibrium
            // calculation by first using the reverse reaction to move all of
            // the already-existent (in proportion) products over to the
            // reactant side, and then move rxnPct % back to the product side.
            double fwdScale = double.MaxValue;
            double revScale = double.MaxValue;

            if (m_reactants.Count != 0)
            {
                foreach (ReactionParticipant rp in m_reactants)
                {
                    double howMuch = target.ContainedMassOf(rp.MaterialType);
                    if (howMuch > 0 && rp.IsCatalyst)
                    {
                        howMuch = double.MaxValue;
                    }
                    fwdScale = Math.Min(fwdScale, howMuch / rp.Mass);
                    if (s_diagnostics)
                    {
                        _Debug.WriteLine("target contains " + howMuch + " of reactant " + rp.MaterialType.Name + " so fwdScale is " + fwdScale);
                    }
                }
                if (fwdScale == double.MaxValue)
                {
                    fwdScale = 0.0;
                }
            }
            else
            {
                fwdScale = 0.0;
            }
            fwdScale *= m_rxPct;

            if (m_products.Count != 0)
            {
                foreach (ReactionParticipant rp in m_products)
                {
                    double howMuch = target.ContainedMassOf(rp.MaterialType);
                    if (howMuch > 0 && rp.IsCatalyst)
                    {
                        howMuch = double.MaxValue;
                    }
                    revScale = Math.Min(revScale, howMuch / rp.Mass);
                    if (s_diagnostics)
                    {
                        _Debug.WriteLine("target contains " + howMuch + " of product " + rp.MaterialType.Name + " so revScale is " + revScale);
                    }
                }

                if (revScale == double.MaxValue)
                {
                    revScale = 0.0;
                }
            }
            else
            {
                revScale = 0.0;
            }
            revScale *= (1 - m_rxPct);

            // If we're going to undo and then redo the same thing, the reaction didn't happen.
            if ((fwdScale == 0.0 && revScale == 0.0) || (Math.Abs(fwdScale - revScale) < 0.000001))
            {
                if (s_diagnostics)
                {
                    _Debug.WriteLine("Reaction " + Name + " won't happen in mixture " + target);
                }
                return(null);
            }

            if (s_diagnostics)
            {
                _Debug.WriteLine("Mixture is " + target);
            }
            if (s_diagnostics)
            {
                _Debug.WriteLine("Reaction " + Name + " is happening. " + ToString());
            }

            ReactionGoingToHappenEvent?.Invoke(this, target);
            target.ReactionGoingToHappen(this);

            Mixture mixtureWas = (Mixture)target.Clone();

            target.SuspendChangeEvents();

            if (s_diagnostics)
            {
                _Debug.WriteLine(revScale > 0.0 ? "Performing reverse reaction..." : "Reverse reaction won't happen.");
            }
            if (revScale > 0.0)
            {
                React(target, m_products, m_reactants, revScale);
            }

            if (s_diagnostics)
            {
                _Debug.WriteLine(fwdScale > 0.0 ? "Performing forward reaction..." : "Forward reaction won't happen.");
            }
            if (fwdScale > 0.0)
            {
                React(target, m_reactants, m_products, fwdScale * m_rxPct);
            }

            // Percent completion is pulled out of the Reaction object.

            ReactionInstance ri = new ReactionInstance(this, fwdScale, revScale, m_nextRiGuid);

            m_nextRiGuid = GuidOps.Increment(m_nextRiGuid);

            ReactionHappenedEvent?.Invoke(ri);
            target.ReactionHappened(ri);

            target.AddEnergy(m_energy * (fwdScale - revScale));

            target.ResumeChangeEvents(!mixtureWas.ToString("F2", "F3").Equals(target.ToString("F2", "F3"))); // Only emit summary events if the mixture has changed.

            return(ri);
        }
Beispiel #17
0
 private void model_Starting(IModel theModel)
 {
     m_nextRiGuid = GuidOps.XOR(m_guid, DEFAULT_RI_GUIDMASK);
 }
Beispiel #18
0
        public static ProcedureFunctionChart CreateRandomPFC(int nSteps, int seed)
        {
            Guid mask     = GuidOps.FromString(string.Format("{0}, {1}", nSteps, seed));
            Guid seedGuid = GuidOps.FromString(string.Format("{0}, {1}", seed, nSteps));
            int  rotate   = 3;

            GuidGenerator     guidGen = new GuidGenerator(seedGuid, mask, rotate);
            PfcElementFactory pfcef   = new PfcElementFactory(guidGen);

            ProcedureFunctionChart pfc = new ProcedureFunctionChart(new Highpoint.Sage.SimCore.Model("Test model", Guid.NewGuid()), "Name", "", guidGen.Next(), pfcef);

            IPfcStepNode start  = pfc.CreateStep("Start", "", Guid.Empty);
            IPfcStepNode step1  = pfc.CreateStep("Step1", "", Guid.Empty);
            IPfcStepNode finish = pfc.CreateStep("Finish", "", Guid.Empty);

            pfc.Bind(start, step1);
            pfc.Bind(step1, finish);

            Console.WriteLine("Seed = {0}.", seed);

            Random r = new Random(seed);

            while (pfc.Steps.Count < nSteps)
            {
                double steeringValue = r.NextDouble();

                if (steeringValue < .5)
                {
                    // Insert a step in series.
                    IPfcLinkElement link     = pfc.Links[r.Next(0, pfc.Links.Count - 1)];
                    IPfcStepNode    stepNode = pfc.CreateStep();
                    pfc.Bind(link.Predecessor, stepNode);
                    pfc.Bind(stepNode, link.Successor);
                    //Console.WriteLine("Inserted {0} between {1} and {2}.", stepNode.Name, link.Predecessor.Name, link.Successor.Name);
                    link.Detach();
                }
                else if (steeringValue < .666)
                {
                    // Insert a step in parallel.
                    for (int i = 0; i < 50; i++)   // Try, but give up if don't find suitable step.
                    {
                        IPfcStepNode target = pfc.Steps[r.Next(0, pfc.Steps.Count - 1)];
                        if (target.PredecessorNodes.Count == 1 && target.SuccessorNodes.Count == 1)
                        {
                            IPfcStepNode stepNode = pfc.CreateStep();
                            pfc.Bind(target.PredecessorNodes[0], stepNode);
                            pfc.Bind(stepNode, target.SuccessorNodes[0]);
                            //Console.WriteLine("Inserted {0} parallel to {1}.", stepNode.Name, target.Name);
                            break;
                        }
                    }
                }
                else if (steeringValue < .833)
                {
                    // Insert a branch
                    for (int i = 0; i < 50; i++)   // Try, but give up if don't find suitable step.
                    {
                        IPfcStepNode step = pfc.Steps[r.Next(0, pfc.Steps.Count - 1)];
                        if (step.PredecessorNodes.Count == 1 && step.SuccessorNodes.Count == 1)
                        {
                            IPfcStepNode entryStep = pfc.CreateStep(step.Name + "_IN", null, Guid.Empty);
                            IPfcStepNode exitStep  = pfc.CreateStep(step.Name + "_OUT", null, Guid.Empty);
                            IPfcStepNode leftStep  = pfc.CreateStep(step.Name + "_LFT", null, Guid.Empty);
                            IPfcStepNode rightStep = pfc.CreateStep(step.Name + "_RGT", null, Guid.Empty);
                            pfc.Bind(step.PredecessorNodes[0], entryStep);
                            pfc.Bind(entryStep, leftStep);
                            pfc.Bind(entryStep, rightStep);
                            pfc.Bind(leftStep, exitStep);
                            pfc.Bind(rightStep, exitStep);
                            pfc.Bind(exitStep, step.SuccessorNodes[0]);
                            pfc.Unbind(step.PredecessorNodes[0], step);
                            pfc.Unbind(step, step.SuccessorNodes[0]);
                            //Console.WriteLine("Inserted a branch in place of {0}.", step.Name);
                            break;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < 50; i++)   // Try, but give up if don't find suitable step.
                    {
                        IPfcTransitionNode trans = pfc.Transitions[r.Next(0, pfc.Transitions.Count - 1)];
                        if (trans.PredecessorNodes.Count == 1 && trans.SuccessorNodes.Count == 1)
                        {
                            IPfcStepNode successor = (IPfcStepNode)trans.SuccessorNodes[0];
                            IPfcStepNode subject   = pfc.CreateStep();
                            pfc.Bind(trans, subject);
                            pfc.Bind(subject, successor);
                            pfc.Unbind(trans, successor);
                            IPfcStepNode loopback = pfc.CreateStep();
                            pfc.Bind(subject, loopback);
                            pfc.Bind(loopback, subject);
                            //Console.WriteLine("Inserted {0} between {1} and {2}, and created a branchback around it using {3}.",
                            //    subject.Name, trans.PredecessorNodes[0].Name, successor.Name, loopback.Name);
                            break;
                        }
                    }
                    //// insert a loopback
                    //IPfcStepNode step;
                    //do { step = pfc.Steps[r.Next(0, pfc.Steps.Count - 1)]; } while (step == start || step == finish);
                    //IPfcStepNode newNode = pfc.CreateStep();
                    //pfc.Bind(step, newNode);
                    //pfc.Bind(newNode, step);
                    //Console.WriteLine("Inserted a loopback around {0} using new step, {1}.", step.Name, newNode.Name);
                }

                //IPfcStepNode origin = pfc.Steps[r.Next(0, pfc.Steps.Count - 1)];
                //if (origin.Equals(finish)) continue;

                //if (r.NextDouble() < .2) {
                //    IPfcStepNode stepNode = pfc.CreateStep();
                //    IPfcNode target = origin.SuccessorNodes[r.Next(0, origin.SuccessorNodes.Count - 1)];
                //    // Insert a step in series.
                //    pfc.Bind(origin, stepNode);
                //    pfc.Bind(stepNode, target);
                //    pfc.Unbind(origin, target);
                //    Console.WriteLine("Inserting {0} between {1} and {2}.",
                //        stepNode.Name, origin.Name, target.Name);


                //} else if (r.NextDouble() < .55) {
                //    // Insert a step in parallel
                //    if (origin.PredecessorNodes.Count == 1 && origin.SuccessorNodes.Count == 1) {
                //        origin = origin.PredecessorNodes[0];
                //        target = origin.SuccessorNodes[0];
                //        pfc.Bind(origin, stepNode);
                //        pfc.Bind(stepNode, target);
                //        Console.WriteLine("Inserting {0} parallel to {1} - between {2} and {3}.",
                //            stepNode.Name, parallelTo.Name, origin.Name, target.Name);

                //    }

                //} else {
                //    // Insert a loopback or branchforward.
                //    IPfcNode target = null;
                //    string parallelType = null;
                //    if (!origin.PredecessorNodes.Contains(start) && r.NextDouble() < .5) {
                //        target = origin;
                //        parallelType = "loopback";
                //    } else if (origin.SuccessorNodes.Count==1 && origin.PredecessorNodes==1) {
                //        target = origin.SuccessorNodes[r.Next(0, origin.SuccessorNodes.Count - 1)];
                //        parallelType = "branch forward";
                //    }

                //    if (target != null) {
                //        IPfcStepNode stepNode = pfc.CreateStep();
                //        pfc.Bind(origin, stepNode);
                //        pfc.Bind(stepNode, target);
                //        Console.WriteLine("Inserting {0} around {1} to {2}, with {3} on the new alternate path.",
                //            parallelType, origin.Name, target.Name, stepNode.Name);
                //    }
                //}
            }

            return(pfc);
        }
Beispiel #19
0
        public object GetInstance(Guid specificationGuid, int generation)
        {
            Guid instanceGuid = GuidOps.Add(specificationGuid, generation);

            return(((InstanceData)m_instanceDataByGuid[instanceGuid]).Instance);
        }
Beispiel #20
0
 public Guid GenerationizedGuid(int generation)
 {
     return(GuidOps.Add(m_guid, generation));
 }
Beispiel #21
0
 internal void InitializeExecutionInstanceUid(Guid parentExecutionContextUid, Guid myStepUid)
 {
     Debug.Assert(m_nextExecutionInstanceUid.Equals(Guid.Empty));
     m_nextExecutionInstanceUid = GuidOps.XOR(parentExecutionContextUid, myStepUid);
 }
Beispiel #22
0
        /// <summary>
        /// Returns the guid for an object created (or to be created) by the specification
        /// with the specCentricGuid that is of the same generation as the instance provided.
        /// This is useful for determining the guid to assign to a port that is owned by a
        /// parent operation.
        /// </summary>
        /// <param name="specCentricGuid">The guid of the specification for which the instance
        /// guid is desired. (In the example above, it would be the port specification.)</param>
        /// <param name="instance">The correlated instance. (In the example above, it would be
        /// the parent task.)</param>
        /// <returns>The correlated guid. (In the example, above, it would be the guid to be
        /// assigned to a new port that is to be added to the given parent task.)</returns>
        public Guid GetInstanceSpecificGuid(Guid specCentricGuid, object instance)
        {
            int instanceGeneration = ((InstanceData)m_instanceDataByInstance[instance]).Generation;

            return(GuidOps.Add(specCentricGuid, instanceGeneration));
        }