Пример #1
0
 public void addBeliefToAllActors(Belief b, int sourceId)
 {
     foreach (KeyValuePair <int, SoaActor> entry in soaActorDictionary)
     {
         entry.Value.addExternalBelief(b);
     }
 }
Пример #2
0
        public bool Commit(Belief belief)
        {
            lock (this)
            {
                CacheKey key = new CacheKey(belief.getTypeKey(), belief.getId());

                CachedBelief oldCache = null;
                if (beliefCache.TryGetValue(key, out oldCache))
                {
                    BeliefMerger merger = new BeliefMerger();
                    Belief       merged = merger.merge(oldCache.GetBelief(), belief);
                    if (merged == oldCache.GetBelief())
                    {
                        return(false);
                    }
                    belief = merged;
                }

                byte[]       serialized = serializer.serializeBelief(belief);
                Hash         hash       = hashFunction.generateHash(serialized);
                CachedBelief cached     = new CachedBelief(belief, serialized, hash);
                beliefCache[key] = cached;
                currentState     = RegenerateState();

                return(true);
            }
        }
Пример #3
0
            public void Send(Belief belief, int address)
            {
                List <Belief> beliefs = new List <Belief>(1);

                beliefs.Add(belief);
                sendToAll(beliefs, actorID, parent.GetCommunicatorsInRange(actorID, address));
            }
Пример #4
0
        // Check if belief is newer than current belief of matching type and id, if so,
        // replace old belief with b.
        public void addBeliefToDataManager(Belief b, int sourceId)
        {
            lock (dataManagerLock)
            {
                SortedDictionary <int, Belief> tempTypeDict = getBeliefsFor(b.getTypeKey());
                if (tempTypeDict != null)
                {
                    Belief oldBelief;
                    if (!getBeliefsFor(b.getTypeKey()).TryGetValue(b.getId(), out oldBelief) || oldBelief.getBeliefTime() < b.getBeliefTime())
                    {
                        getBeliefsFor(b.getTypeKey())[b.getId()] = b;
                    }
                }
                else
                {
                    getBeliefsFor(b.getTypeKey())[b.getId()] = b;
                }

                /*
                 * Do not update actors in this function
                 * SortedDictionary<int, bool> sourceDistanceDictionary;
                 * if (actorDistanceDictionary.TryGetValue(sourceId, out sourceDistanceDictionary))
                 * {
                 *  foreach (KeyValuePair<int, bool> entry in sourceDistanceDictionary)
                 *  {
                 *      SoaActor destActor = soaActorDictionary[entry.Key];
                 *      if (entry.Value)
                 *      {
                 *          destActor.addBelief(b, sourceId);
                 *      }
                 *  }
                 * }*/
            }
        }
Пример #5
0
        public void synchronizeBelief(Belief belief, int sourceID)
        {
            AgentMessageHandler handler = findHandler(sourceID);

            if (handler != null)
            {
                handler.synchronizeBelief(belief);
            }
        }
Пример #6
0
        /*public void addAndBroadcastBelief(Belief b, int sourceId, int[] recipients)
         * {
         *  if (cm != null)
         *  {
         *      cm.addOutgoing(b, sourceId, recipients);
         *      addBelief(b, sourceId);
         *  }
         *
         * }*/

        //Add incoming belief to correct agent
        public void addExternalBeliefToActor(Belief b, int sourceId)
        {
            SoaActor a;

            soaActorDictionary.TryGetValue(sourceId, out a);
            if (a != null)
            {
                a.addExternalBelief(b);
            }
        }
Пример #7
0
        public void handleMessage(BSPMessage message)
        {
            Belief belief = serializer.generateBelief(message.getData().getBuffer());

            if (belief.getBeliefType() == Belief.BeliefType.WAYPOINT_PATH)
            {
                Log.debug("Received waypoint path");
            }
            repo.Commit(belief);
        }
        public void synchronizeBelief(Belief belief)
        {
            IEnumerable <CachedBelief> changedBeliefs = repo.Diff(remoteState);

            foreach (CachedBelief cached in changedBeliefs)
            {
                if (cached.GetBelief().getTypeKey() == belief.getTypeKey() &&
                    cached.GetBelief().getId() == belief.getId())
                {
                    protocol.post(cached);
                    break;
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Adds information from data manager to outgoing queue using specified source ID
        /// Use null for targetActorIDs if broadcast
        /// </summary>
        public void addOutgoing(Belief b, int sourceID, int[] targetActorIDs)
        {
            // Serialize the 4-byte source ID, network byte order (Big Endian)
            Byte[] sourceIDBytes = BitConverter.GetBytes(sourceID);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(sourceIDBytes);
            }

            Byte[] beliefBytes = serializer.serializeBelief(b);

            // Enqueue the serialized message if serialization was
            // successful (if serial is nonempty)
            if (beliefBytes.Length > 0)
            {
                // Combine the serialized source ID and belief into one message
                Byte[] message = new Byte[4 + beliefBytes.Length];
                System.Buffer.BlockCopy(sourceIDBytes, 0, message, 0, 4);
                System.Buffer.BlockCopy(beliefBytes, 0, message, 4, beliefBytes.Length);

                lock (outgoingQueue)
                {
                    if (outgoingQueue.Count < maxQueueSize)
                    {
                        // There is still space in queue, go ahead and enqueue
                        outgoingQueue.Enqueue(message);
                        outgoingTargetQueue.Enqueue(targetActorIDs);
                    }
                    else if (outgoingQueue.Count == maxQueueSize && overwriteWhenQueueFull)
                    {
                        // No more space left and our policy is to overwrite old data
                        // Dequeue the oldest entry before enqueuing the new data
                        outgoingQueue.Dequeue();
                        outgoingTargetQueue.Dequeue();
                        outgoingQueue.Enqueue(message);
                        outgoingTargetQueue.Enqueue(targetActorIDs);
                    }
                    else
                    {
                        // No space left, policy says to do nothing and drop newest entry
                    }
                } // Unlock
            }
            else
            {
                // Something went wrong with serialization
                Log.debug("PhotonCloudCommManager: Belief serialization failed");
            }
        }
Пример #10
0
        public Belief merge(Belief oldBelief, Belief b)
        {
            if (b.getBeliefType() == Belief.BeliefType.ACTOR)
            {
                // Convert to belief actors
                Belief_Actor oldActorBelief      = (Belief_Actor)oldBelief;
                Belief_Actor incomingActorBelief = (Belief_Actor)b;

                // To keep track of what to merge
                bool incomingBeliefMoreRecent = !incomingActorBelief.getIsAlive() && oldActorBelief.getIsAlive() ||
                                                incomingActorBelief.getBeliefTime() > oldActorBelief.getBeliefTime();

                bool onlyIncomingBeliefIsClassified = oldActorBelief.getAffiliation() == (int)Affiliation.UNCLASSIFIED &&
                                                      incomingActorBelief.getAffiliation() != (int)Affiliation.UNCLASSIFIED;

                bool onlyOldBeliefIsClassified = oldActorBelief.getAffiliation() != (int)Affiliation.UNCLASSIFIED &&
                                                 incomingActorBelief.getAffiliation() == (int)Affiliation.UNCLASSIFIED;

                if (!incomingBeliefMoreRecent && !onlyIncomingBeliefIsClassified)
                {
                    return(oldBelief);
                }
                else if (incomingBeliefMoreRecent && onlyOldBeliefIsClassified)
                {
                    return(mergeActorBeliefs(oldActorBelief, incomingActorBelief));
                }
                else if (!incomingBeliefMoreRecent && onlyIncomingBeliefIsClassified)
                {
                    return(mergeActorBeliefs(incomingActorBelief, oldActorBelief));
                }
                else
                {
                    return(incomingActorBelief);
                }
            } // end actor merge policy
            else
            {
                // General merge policy (take newest belief) for every belief except actor
                if (oldBelief.getBeliefTime() < b.getBeliefTime())
                {
                    return(b);
                }
                else
                {
                    return(oldBelief);
                }
            }
        }
Пример #11
0
 public void SetWaypointBelief(soa.Belief_Waypoint belief)
 {
     lock (waypoints)
     {
         if (belief != lastBelief && belief != null)
         {
             this.waypoints.Clear();
             Vector3 location = new Vector3(belief.getPos_x() * SimControl.KmToUnity,
                                            belief.getPos_y() * SimControl.KmToUnity,
                                            belief.getPos_z() * SimControl.KmToUnity);
             waypoints.Add(new Waypoint(location, belief.getSpeed()));
             waypointIndex = 0;
             lastBelief    = belief;
             UpdateDisplay();
         }
     }
 }
Пример #12
0
    public void SetWaypointBelief(soa.Belief_WaypointPath belief)
    {
        lock (waypoints)
        {
            if (belief != lastBelief && belief != null)
            {
                this.waypoints.Clear();

                foreach (soa.Waypoint waypoint in belief.getWaypoints())
                {
                    Vector3 location = new Vector3(waypoint.x * SimControl.KmToUnity,
                                                   waypoint.y * SimControl.KmToUnity,
                                                   waypoint.z * SimControl.KmToUnity);
                    waypoints.Add(new Waypoint(location, waypoint.speed));
                }

                this.waypointIndex = 0;
                lastBelief         = belief;

                UpdateDisplay();
            }
        }
    }
Пример #13
0
 private SortedDictionary <int, Belief> getBeliefsFor(Belief.BeliefType type)
 {
     return(getBeliefsFor(Belief.keyOf(type)));
 }
Пример #14
0
        // Serialize a Belief object into a byte array using Google Protobuf + 1 header byte
        public override byte[] serializeBelief(Belief belief)
        {
            // Variables to hold serialized message
            byte header;

            byte[] body, message;

            // Initialize based on type of belief
            switch (belief.getBeliefType())
            {
            case Belief.BeliefType.ACTOR:
            {         // Actor
                Gpb_Actor.Builder proto = Gpb_Actor.CreateBuilder();
                Belief_Actor      b     = (Belief_Actor)belief;
                proto.SetUniqueId(b.getUnique_id());
                proto.SetAffiliation(b.getAffiliation());
                proto.SetType(b.getType());
                proto.SetIsAlive(b.getIsAlive());
                proto.SetNumStorageSlots(b.getNumStorageSlots());
                proto.SetNumCasualtiesStored(b.getNumCasualtiesStored());
                proto.SetNumSuppliesStored(b.getNumSuppliesStored());
                proto.SetNumCiviliansStored(b.getNumCiviliansStored());
                proto.SetIsWeaponized(b.getIsWeaponized());
                proto.SetHasJammer(b.getHasJammer());
                proto.SetFuelRemaining(b.getFuelRemaining());
                proto.SetPosX(b.getPos_x());
                proto.SetPosY(b.getPos_y());
                proto.SetPosZ(b.getPos_z());
                // Optional fields
                if (b.getVelocity_x_valid())
                {
                    proto.SetVelocityX(b.getVelocity_x());
                }
                if (b.getVelocity_y_valid())
                {
                    proto.SetVelocityY(b.getVelocity_y());
                }
                if (b.getVelocity_z_valid())
                {
                    proto.SetVelocityZ(b.getVelocity_z());
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.ACTOR;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.BASE:
            {         // Base
                Gpb_Base.Builder proto = Gpb_Base.CreateBuilder();
                Belief_Base      b     = (Belief_Base)belief;
                proto.SetId(b.getId());
                proto.SetSupplies(b.getSupplies());
                // Copy contents of cell list
                List <GridCell> cells = b.getCells();
                for (int i = 0; i < cells.Count; i++)
                {
                    Gpb_GridCell.Builder g = Gpb_GridCell.CreateBuilder();
                    g.SetRow(cells[i].getRow());
                    g.SetCol(cells[i].getCol());
                    proto.AddCells(g.Build());
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.BASE;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.CASUALTY_DELIVERY:
            {         // Casualty Delivery
                Gpb_CasualtyDelivery.Builder proto = Gpb_CasualtyDelivery.CreateBuilder();
                Belief_Casualty_Delivery     b     = (Belief_Casualty_Delivery)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetGreedy(b.getGreedy());
                proto.SetMultiplicity(b.getMultiplicity());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.CASUALTY_DELIVERY;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.CASUALTY_PICKUP:
            {         // Casualty Pickup
                Gpb_CasualtyPickup.Builder proto = Gpb_CasualtyPickup.CreateBuilder();
                Belief_Casualty_Pickup     b     = (Belief_Casualty_Pickup)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetGreedy(b.getGreedy());
                // Copy contents of id list
                int[] ids = b.getIds();
                for (int i = 0; i < ids.Length; i++)
                {
                    proto.AddIds(ids[i]);
                }
                // Copy contents of multiplicity list
                int[] multiplicity = b.getMultiplicity();
                for (int i = 0; i < multiplicity.Length; i++)
                {
                    proto.AddMultiplicity(multiplicity[i]);
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.CASUALTY_PICKUP;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.GRIDSPEC:
            {         // Grid Specification
                Gpb_GridSpec.Builder proto = Gpb_GridSpec.CreateBuilder();
                Belief_GridSpec      b     = (Belief_GridSpec)belief;
                proto.SetWidth(b.getWidth());
                proto.SetHeight(b.getHeight());
                proto.SetGridOriginX(b.getGridOrigin_x());
                proto.SetGridOriginZ(b.getGridOrigin_z());
                proto.SetGridToWorldScale(b.getGridToWorldScale());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.GRIDSPEC;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.MODE_COMMAND:
            {         // Mode Command
                Gpb_Mode_Command.Builder proto = Gpb_Mode_Command.CreateBuilder();
                Belief_Mode_Command      b     = (Belief_Mode_Command)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetModeId(b.getMode_id());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.MODE_COMMAND;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.NGOSITE:
            {         // NGO Site
                Gpb_NGOSite.Builder proto = Gpb_NGOSite.CreateBuilder();
                Belief_NGOSite      b     = (Belief_NGOSite)belief;
                proto.SetId(b.getId());
                proto.SetSupplies(b.getSupplies());
                proto.SetCasualties(b.getCasualties());
                proto.SetCivilians(b.getCivilians());
                // Copy contents of cell list
                List <GridCell> cells = b.getCells();
                for (int i = 0; i < cells.Count; i++)
                {
                    Gpb_GridCell.Builder g = Gpb_GridCell.CreateBuilder();
                    g.SetRow(cells[i].getRow());
                    g.SetCol(cells[i].getCol());
                    proto.AddCells(g.Build());
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.NGOSITE;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.ROADCELL:
            {         // Road Cell
                Gpb_RoadCell.Builder proto = Gpb_RoadCell.CreateBuilder();
                Belief_RoadCell      b     = (Belief_RoadCell)belief;
                proto.SetIsRoadEnd(b.getIsRoadEnd());
                // Copy contents of cell
                GridCell             cell = b.getCell();
                Gpb_GridCell.Builder g    = Gpb_GridCell.CreateBuilder();
                g.SetRow(cell.getRow());
                g.SetCol(cell.getCol());
                proto.SetCell(g.Build());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.ROADCELL;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.SPOI:
            {         // SPOI
                Gpb_SPOI.Builder proto = Gpb_SPOI.CreateBuilder();
                Belief_SPOI      b     = (Belief_SPOI)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetPosX(b.getPos_x());
                proto.SetPosY(b.getPos_y());
                proto.SetPosZ(b.getPos_z());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.SPOI;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.SUPPLY_DELIVERY:
            {         // Supply Delivery
                Gpb_SupplyDelivery.Builder proto = Gpb_SupplyDelivery.CreateBuilder();
                Belief_Supply_Delivery     b     = (Belief_Supply_Delivery)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetGreedy(b.getGreedy());
                // Copy contents of id list
                int[] ids = b.getIds();
                for (int i = 0; i < ids.Length; i++)
                {
                    proto.AddIds(ids[i]);
                }
                // Copy contents of multiplicity list
                int[] multiplicity = b.getMultiplicity();
                for (int i = 0; i < multiplicity.Length; i++)
                {
                    proto.AddMultiplicity(multiplicity[i]);
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.SUPPLY_DELIVERY;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.SUPPLY_PICKUP:
            {         // Supply Pickup
                Gpb_SupplyPickup.Builder proto = Gpb_SupplyPickup.CreateBuilder();
                Belief_Supply_Pickup     b     = (Belief_Supply_Pickup)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetGreedy(b.getGreedy());
                proto.SetMultiplicity(b.getMultiplicity());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.SUPPLY_PICKUP;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.TERRAIN:
            {         // Terrain
                Gpb_Terrain.Builder proto = Gpb_Terrain.CreateBuilder();
                Belief_Terrain      b     = (Belief_Terrain)belief;
                proto.SetType(b.getType());
                // Copy contents of cell list
                List <GridCell> cells = b.getCells();
                for (int i = 0; i < cells.Count; i++)
                {
                    Gpb_GridCell.Builder g = Gpb_GridCell.CreateBuilder();
                    g.SetRow(cells[i].getRow());
                    g.SetCol(cells[i].getCol());
                    proto.AddCells(g.Build());
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.TERRAIN;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.TIME:
            {         // Time
                Gpb_Time.Builder proto = Gpb_Time.CreateBuilder();
                Belief_Time      b     = (Belief_Time)belief;
                proto.SetTime(b.getTime());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.TIME;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.VILLAGE:
            {         // Village
                Gpb_Village.Builder proto = Gpb_Village.CreateBuilder();
                Belief_Village      b     = (Belief_Village)belief;
                proto.SetId(b.getId());
                proto.SetSupplies(b.getSupplies());
                proto.SetCasualties(b.getCasualties());
                // Copy contents of cell list
                List <GridCell> cells = b.getCells();
                for (int i = 0; i < cells.Count; i++)
                {
                    Gpb_GridCell.Builder g = Gpb_GridCell.CreateBuilder();
                    g.SetRow(cells[i].getRow());
                    g.SetCol(cells[i].getCol());
                    proto.AddCells(g.Build());
                }
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.VILLAGE;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.WAYPOINT:
            {         // Waypoint
                Gpb_Waypoint.Builder proto = Gpb_Waypoint.CreateBuilder();
                Belief_Waypoint      b     = (Belief_Waypoint)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetPosX(b.getPos_x());
                proto.SetPosY(b.getPos_y());
                proto.SetPosZ(b.getPos_z());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.WAYPOINT;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.WAYPOINT_OVERRIDE:
            {         // Waypoint Override
                Gpb_Waypoint_Override.Builder proto = Gpb_Waypoint_Override.CreateBuilder();
                Belief_Waypoint_Override      b     = (Belief_Waypoint_Override)belief;
                proto.SetRequestTime(b.getRequest_time());
                proto.SetActorId(b.getActor_id());
                proto.SetPosX(b.getPos_x());
                proto.SetPosY(b.getPos_y());
                proto.SetPosZ(b.getPos_z());
                // Add on belief time
                proto.SetBeliefTime(b.getBeliefTime());
                // Form header + serialized message
                header = (byte)MessageType.WAYPOINT_OVERRIDE;
                body   = proto.Build().ToByteArray();
                break;
            }

            case Belief.BeliefType.WAYPOINT_PATH:
            {
                Gpb_WaypointPath.Builder proto = Gpb_WaypointPath.CreateBuilder();
                Belief_WaypointPath      b     = (Belief_WaypointPath)belief;
                proto.SetActorId(b.getId());
                proto.SetBeliefTime(b.getBeliefTime());
                proto.SetRequestTime(b.getRequestTime());

                foreach (Waypoint point in b.getWaypoints())
                {
                    Gpb_SingleWaypoint.Builder pointBuilder = Gpb_SingleWaypoint.CreateBuilder();
                    pointBuilder.SetX(point.x);
                    pointBuilder.SetY(point.y);
                    pointBuilder.SetZ(point.z);
                    pointBuilder.SetHeading(point.heading);
                    pointBuilder.SetVisited(point.visited);
                    proto.AddWaypoints(pointBuilder.Build());
                }

                header = (byte)MessageType.WAYPOINT_PATH;
                body   = proto.Build().ToByteArray();

                break;
            }

            case Belief.BeliefType.CUSTOM:
            {         // Custom
                Gpb_Custom.Builder proto = Gpb_Custom.CreateBuilder();
                Belief_Custom      b     = (Belief_Custom)belief;
                proto.SetData(Google.ProtocolBuffers.ByteString.CopyFrom(b.getData()));
                // Add on belief time
                proto.SetCustomType(b.getCustomType());
                proto.SetActorId(b.getId());
                proto.SetBeliefTime(b.getBeliefTime());

                // Form header + serialized message
                header = (byte)MessageType.CUSTOM;
                body   = proto.Build().ToByteArray();
                break;
            }

            default:
                // Unrecognized type, return empty array
                Log.debug("ProtobufSerializer.serializeBelief(): Unrecognized Belief type");
                return(new byte[0]);
            }

            // Return serialized message (header + body)
            message    = new Byte[body.Length + 1];
            message[0] = header;
            System.Buffer.BlockCopy(body, 0, message, 1, body.Length);
            return(message);
        }
Пример #15
0
        // Callback to handle messages received over Photon game network
        public void OnEvent(EventData eventData)
        {
            // Take action based on received event code
            switch (eventData.Code)
            {
            case 0:     // Received a Protobuff message
            {
                // Get the byte[] message from protobuf
                // Message = 1 byte for length of rest of message, 4 bytes for source ID, rest is serialized belief
                Hashtable evData = (Hashtable)eventData.Parameters[LiteEventKey.Data];
                Byte[]    packet = (Byte[])evData[(byte)0];

                // Extract 4-byte message length (convert from network byte order (Big Endian) to native order if necessary)
                Byte[] messageLengthBytes = new Byte[4];
                System.Buffer.BlockCopy(packet, 0, messageLengthBytes, 0, 4);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(messageLengthBytes);
                }
                int messageLength = BitConverter.ToInt32(messageLengthBytes, 0);

                // Extract 4-byte source ID (convert from network byte order (Big Endian) to native order if necessary)
                Byte[] sourceIDBytes = new Byte[4];
                System.Buffer.BlockCopy(packet, 4, sourceIDBytes, 0, 4);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(sourceIDBytes);
                }
                int sourceID = BitConverter.ToInt32(sourceIDBytes, 0);

                // Get belief length
                int serializedBeliefLength = messageLength - 4;

                // Extract serialized belief
                Byte[] serializedBelief = new Byte[serializedBeliefLength];
                System.Buffer.BlockCopy(packet, 8, serializedBelief, 0, serializedBeliefLength);

                // Extract the belief
                Belief b = serializer.generateBelief(serializedBelief);

                // If deserialization was successful
                if (b != null)
                {
                    // Add the belief to the data manager if it passed filter
                    dataManager.addExternalBeliefToActor(b, sourceID);
                }
                else
                {
                    // Something went wrong with deserialization
                            #if (UNITY_STANDALONE)
                    Debug.Log("PhotonLiteCommManager: Belief deserialization failed");
                            #else
                    Console.Error.WriteLine("PhotonLiteCommManager: Belief deserialization failed");
                            #endif
                }
                break;
            }

            case LiteEventCode.Join:
            {
                // New player just joined, print status if that player isn't me
                int actorNrJoined = (int)eventData.Parameters[LiteEventKey.ActorNr];
                if (actorNrJoined != mActorNumber)
                {
                    Log.debug("PhotonLiteCommManager: Player " + actorNrJoined + " joined the room");
                }

                // Provide update on all players in room
                int[] actorList = (int[])eventData.Parameters[LiteEventKey.ActorList];
                if (actorList.Length > 0)
                {
                    string statusMessage = "PhotonLiteCommManager: Players currently in room {" + actorList[0];
                    for (int i = 1; i < actorList.Length; i++)
                    {
                        statusMessage += (", " + actorList[i]);
                    }
                    statusMessage += "}";
                    Log.debug(statusMessage);
                }
                break;
            }

            case LiteEventCode.Leave:
            {
                // Exiting player just left, print status
                int actorNrJoined = (int)eventData.Parameters[LiteEventKey.ActorNr];
                Log.debug("PhotonLiteCommManager: Player " + actorNrJoined + " left the room");

                // Provide update on all players in room
                int[] actorList = (int[])eventData.Parameters[LiteEventKey.ActorList];
                if (actorList.Length > 0)
                {
                    string statusMessage = "PhotonLiteCommManager: Players currently in room {" + actorList[0];
                    for (int i = 1; i < actorList.Length; i++)
                    {
                        statusMessage += (", " + actorList[i]);
                    }
                    statusMessage += "}";
                    Log.debug(statusMessage);
                }
                break;
            }

            default:
                // Ignore other events
                break;
            }
        }
Пример #16
0
 public void synchronizeBelief(Belief b, int sourceID)
 {
     protocol.synchronizeBelief(b, sourceID);
 }
Пример #17
0
 public void synchronizeBelief(Belief b, int sourceID)
 {
     cm.synchronizeBelief(b, sourceID);
 }
Пример #18
0
 // Belief to serialized string
 public abstract Byte[] serializeBelief(Belief b);
Пример #19
0
 public BeliefType Find <BeliefType>(Belief.BeliefType type, int id) where BeliefType : Belief
 {
     return(Find <BeliefType>(Belief.keyOf(type), id));
 }
Пример #20
0
 // Initialization beliefs are kept separately from actual belief manager beliefs
 // in case a player joins mid game
 public void addInitializationBelief(Belief b)
 {
     initializationBeliefs.Add(b);
 }
Пример #21
0
        public void handleMessage(BSPMessage message)
        {
            Belief belief = serializer.generateBelief(message.getData().getBuffer());

            repo.Commit(belief);
        }
Пример #22
0
        /// <summary>
        /// Callback to handle messages received over Photon game network
        /// Processed within PhotonPeer.DispatchIncomingCommands()!
        /// </summary>
        public override void OnEvent(EventData photonEvent)
        {
            // Call original OnEvent()
            base.OnEvent(photonEvent);

            // Handle our custom event
            switch (photonEvent.Code)
            {
            case 0:     // Received a Protobuff message
            {
                // Get the byte[] message from protobuf
                // Message = 1 byte for length of rest of message, 4 bytes for source ID, rest is serialized belief
                Hashtable evData = (Hashtable)photonEvent.Parameters[ParameterCode.Data];
                Byte[]    packet = (Byte[])evData[(byte)0];

                // Extract 4-byte message length (convert from network byte order (Big Endian) to native order if necessary)
                Byte[] messageLengthBytes = new Byte[4];
                System.Buffer.BlockCopy(packet, 0, messageLengthBytes, 0, 4);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(messageLengthBytes);
                }
                int messageLength = BitConverter.ToInt32(messageLengthBytes, 0);

                // Extract 4-byte source ID (convert from network byte order (Big Endian) to native order if necessary)
                Byte[] sourceIDBytes = new Byte[4];
                System.Buffer.BlockCopy(packet, 4, sourceIDBytes, 0, 4);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(sourceIDBytes);
                }
                int sourceID = BitConverter.ToInt32(sourceIDBytes, 0);

                // Get belief length
                int serializedBeliefLength = messageLength - 4;

                // Extract serialized belief
                Byte[] serializedBelief = new Byte[serializedBeliefLength];
                System.Buffer.BlockCopy(packet, 8, serializedBelief, 0, serializedBeliefLength);

                // Extract the belief
                Belief b = serializer.generateBelief(serializedBelief);

                // If deserialization was successful
                if (b != null)
                {
                    // Add the belief to the data manager if it passed filter, no filter for Unity
                    dataManager.addExternalBeliefToActor(b, sourceID);
                }
                else
                {
                    // Something went wrong with deserialization
                    Log.debug("PhotonCloudCommManager: Belief deserialization failed");
                }
                break;
            }

            case EventCode.Join:     // Someone joined the game
            {
                // Get ID of actor that joined
                int actorNrJoined = (int)photonEvent.Parameters[ParameterCode.ActorNr];

                // Determine if the player that joined is myself
                bool isLocal = (this.LocalPlayer.ID == actorNrJoined);

                // Get initialization beliefs
                List <Belief> initializationBeliefs = dataManager.getInitializationBeliefs();

                // Only send if not null or empty list
                bool sendInitializationBeliefs = (initializationBeliefs != null) && (initializationBeliefs.Count > 0);

                if (isLocal)
                {
                    // I just joined the room, broadcast initialization beliefs to everyone
                    // Use -1 source ID to override comms distances constraints
                    if (sendInitializationBeliefs)
                    {
                        addOutgoing(initializationBeliefs, -1, null);
                    }
                }
                else
                {
                    // Someone else just joined the room, print status message
                    Log.debug("PhotonCloudCommManager: Player " + actorNrJoined + " just joined");

                    // Get initialization beliefs and only send to that player
                    // Use -1 source ID to override comms distances constraints
                    if (sendInitializationBeliefs)
                    {
                        addOutgoing(initializationBeliefs, -1, new int[] { actorNrJoined });
                    }
                }
                break;
            }
            }
        }
Пример #23
0
 public CachedBelief(Belief belief, byte[] serialized, Hash hash)
 {
     this.belief     = belief;
     this.serialized = serialized;
     this.hash       = hash;
 }
Пример #24
0
 public void synchronizeBelief(Belief belief)
 {
     syncHandler.synchronizeBelief(belief);
 }