//Constructor enemy with no weapon public Enemy(EnemyType type, float hp, int ms, GameObject referenceObject) { this.type = type; this.referenceObject = referenceObject; o = new ObjectUpdate(); }
private void OnMovingTowards_OnObjectUpdated(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { if (update.LocalID == Mover.LocalID) { UpdateAll(); } else { Primitive prim = Client.WorldSystem.GetPrimitive(update.LocalID); if (IsFacing(prim)) { if (!MoverFaceing.Contains(prim)) { MoverFaceing.Add(prim); } } else { if (MoverFaceing.Contains(prim)) { MoverFaceing.Remove(prim); } } } }
private void Objects_OnObjectUpdated(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { if (startTime == 0) return; if (update.LocalID == Client.Self.LocalID) { XYMovement(); ZMovement(); if (Client.Self.Movement.AtPos || Client.Self.Movement.AtNeg) { Client.Self.Movement.TurnToward(target); Debug("Flyxy "); } else if (Client.Self.Movement.UpPos || Client.Self.Movement.UpNeg) { Client.Self.Movement.TurnToward(target); //Client.Self.Movement.SendUpdate(false); Debug("Fly z "); } else if (Vector3.Distance(target, Client.Self.SimPosition) <= 2.0) { EndFlyto(); Debug("At Target"); } } if (Environment.TickCount - startTime > duration) { EndFlyto(); Debug("End Flyto"); } }
// Use this for initialization void Start() { // this creates alll the prefabs required at the start of the game ObjectUpdate o = instantiator.Start(); ObjectHandler.Update(o, gameObject); }
public void kamikazeInstantiation() { kamikazeInstantiationPoints = new List <Vector3>(); //THis for loop gets a separate instantiation point for each kamikaze swarm for (int i = 0; i < kamikazeSwarms; i++) { Vector3 instantiationPoint = GetRandomInstantiationPointOnSphere(); while (kamikazeInstantiationPoints.Contains(instantiationPoint)) //Checks to make sure point isn't already in the list { instantiationPoint = GetRandomInstantiationPointOnSphere(); } kamikazeInstantiationPoints.Add(instantiationPoint); } ObjectUpdate o = new ObjectUpdate(); //This for loop instantiates a group of kamikazes for each instantiation point received above and places them within a certain radius of each other foreach (Vector3 point in kamikazeInstantiationPoints) { for (int i = 0; i < kamikazePerSpawn; i++) { Vector3 randomInstanPoint = Random.insideUnitSphere * 5.0f + point; GameObject enemy = (GameObject)Instantiate(flyingKamikaze, randomInstanPoint, Quaternion.identity); Enemy e = new Enemy(EnemyType.FlyingKamikaze, 50, 10, enemy); Enemy.enemyList.Add(e); //InstantiationRequest instanRequest = new InstantiationRequest("KamikaziBird", randomInstanPoint, Quaternion.identity, false); //o.AddInstantiationRequest(instanRequest); } } ObjectHandler.Update(o, this.gameObject); }
/// <remarks> /// This method gets invoked by the update timer every UpdatePeriodSeconds. /// Use it to send object updates to subscribers. The argument is always null. /// </remarks> private Task UpdateObservers(object arg) { if (IsValuesUpdated || IsMovementUpdated) { MovementUpdate movementUpdate = null; ValuesUpdate valuesUpdate = null; if (IsValuesUpdated) { valuesUpdate = BuildValuesUpdate(false); State.UpdateMask.Clear(); } if (IsMovementUpdated) { movementUpdate = BuildMovementUpdate(); IsMovementUpdated = false; } var objectUpdate = new ObjectUpdate(State.Id, State.TypeId, UpdateFlags, movementUpdate, valuesUpdate); observerManager.Notify(observer => observer.HandleObjectUpdate(State, objectUpdate)); OnPostUpdate(); } return(Task.CompletedTask); }
public DeckScene() { ObjectAdd = delegate(DeckObject deckObject) { }; ObjectUpdate = delegate(DeckObject deckObject) { }; ObjectRemove = delegate(DeckObject deckObject) { }; BubbleAdd = delegate(DeckBubble deckObject) { }; BubbleRemove = delegate(DeckBubble deckObject) { }; }
private void OnSelfUpdated(Simulator simulator, ObjectUpdate update, ulong regionhandle) { lock (_lastKnownPosLock) { if (_lastKnownSimPostion == Vector3.Zero) { _lastKnownSimPostion = update.Position; return; } if (Vector3.Distance(update.Position, _lastKnownSimPostion) < 8) { return; } _lastKnownSimPostion = update.Position; } List <SimulatorCull> simCulls = null; List <SimPatchInfo> sendpatches = new List <SimPatchInfo>(); lock (SimulatorCullings) { simCulls = new List <SimulatorCull>(SimulatorCullings.Values); } foreach (SimulatorCull sc in simCulls) { lock (sc) { foreach (var p in sc.PatchesCulled) { if (Vector3d.Distance(CameraPosition, p.pos) < LandSightDistance) { sendpatches.Add(p); } } foreach (var p in sendpatches) { sc.PatchesCulled.Remove(p); sc.PatchesSent.Add(p); } } } foreach (var p in sendpatches) { landPatchCallback(p.simulator, p.x, p.y, p.width, p.data); } if (!ObjectsToManagedLayerIsRangeBased) { return; } foreach (SimulatorCull sc in simCulls) { lock (sc) OnSelfUpdatedObjects(sc); } }
public void UpdateObject(GameObjectInstance obj) { var session = sessions.Get(obj); var gobj = gameData.GetGameObject(obj.ObjectId); var transform = gameData.GetTransform(gobj.TransformId); foreach (var playerConnection in connectionProvider.GetAllActivePlayerConnections(session)) { playerConnection.Send(ObjectUpdate.Create(obj, transform, gobj.Static), SendOption.Reliable); } }
public override int ReadFrom(byte[] Buffer, int StartIndex = 0) { int cursor = StartIndex; cursor += base.ReadFrom(Buffer, cursor); UpdatedObject = new ObjectUpdate(Buffer, cursor); cursor += UpdatedObject.ByteLength; return(cursor - StartIndex); }
public ObjectUpdate generateFractal(int depth) { ObjectUpdate o = new ObjectUpdate(); List <List <Vector3> > shapePoints = new List <List <Vector3> >(); shapePoints.Add(pointsSingleShape); int currDepth = 0; while (currDepth < depth) { currDepth++; } return(o); }
private void Objects_OnObjectUpdated(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { lock (_Avatars) { if (_Avatars.Contains(update.LocalID)) { Avatar av; if (simulator.ObjectsAvatars.TryGetValue(update.LocalID, out av)) { UpdateAvatar(av); } } } }
private void objectUpdatedCallback(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { if (simulator == m_user.Network.CurrentSim) { if (m_user.Self.LocalID == update.LocalID) { OnSelfUpdated(simulator, update, regionHandle); } } if (OnObjectUpdate != null) { OnObjectUpdate(new VSimulator(simulator), update, regionHandle, timeDilation); } }
//This method is for IRenemies so that they can spawn squishy enemies to defend themselves, the squishy enemies will likely not be at full health public static void spawnEnemyWithinRadius(EnemyType type, GameObject enemy, float radius, Vector3 spawnPos, float maxHPProportion) { //Add code to adjust shrab and shly health Debug.Log("In RandomEnemySpawn function"); if (type == EnemyType.FlyingKamikaze || type == EnemyType.Shly) { Vector3 instantiationPoint = Random.insideUnitSphere * radius + spawnPos + new Vector3(0, 30f, 0); ObjectUpdate o = new ObjectUpdate(); GameObject bird = Instantiate(enemy, instantiationPoint, Quaternion.identity); SpawnEnemy(bird, "Kamikaze"); if (type == EnemyType.FlyingKamikaze) { bird.GetComponent <StatManager>().kamikazeMaxHP *= maxHPProportion; } //InstantiationRequest instanRequest = new InstantiationRequest("KamikaziBird", instantiationPoint, Quaternion.identity, false); //o.AddInstantiationRequest(instanRequest); } else if (type == EnemyType.Brawler || type == EnemyType.Shrab) { Vector3 basePoint = Random.insideUnitSphere * radius + spawnPos; Vector3 instanPoint = Vector3.zero; Vector3 raycastDirection = (-basePoint).normalized; RaycastHit hit; if (Physics.Raycast(basePoint, raycastDirection, out hit, Mathf.Infinity)) { instanPoint = hit.point; } else { Debug.Log("Raycast hit not detected"); } if (type == EnemyType.Brawler) { Debug.Log("Instantiating golem in RandomEnemySpawn"); GameObject golem = Instantiate(enemy, instanPoint, Quaternion.identity); SpawnEnemy(golem, "Golem"); golem.GetComponent <StatManager>().golemMaxHp *= maxHPProportion; } else if (type == EnemyType.Shrab) { Debug.Log("Instantinating shrab in RandomEnemySpawn"); GameObject shrab = Instantiate(enemy, instanPoint, Quaternion.identity); SpawnEnemy(shrab, "Shrab"); shrab.GetComponent <StatManager>().shrabMaxHp *= maxHPProportion; } } }
private void WriteValuesBlock(BinaryWriter writer, ObjectUpdate update) { if (update.ValuesUpdate != null) { writer.Write(update.ValuesUpdate.BlockCount); // inefficient? foreach (byte b in update.ValuesUpdate.UpdateMask) { writer.Write(b); } foreach (int i in update.ValuesUpdate.Fields) { writer.Write(i); } } }
public async void EnterWorld(WorldSession session) { var objectUpdate = new ObjectUpdate { NumObjUpdates = 1, MapId = (ushort)session.Player.Map, Obj = session.Player }; objectUpdate.CreateData.ThisIsYou = true; objectUpdate.CreateData.Move = new MovementUpdate(); objectUpdate.CreateData.Move.Status.MoverGUID = session.Player.Guid; objectUpdate.CreateData.Move.Status.Position = session.Player.Position; objectUpdate.CreateData.Move.Status.Facing = session.Player.Facing; await session.Send(objectUpdate); }
/* parameters: None * returns: ObjectUpdate with information neccesary to actually make the planet in unity. */ public int[] GeneratePlanet(DateTime start, out List <int>[] map, out List <Vector3> pts, out List <int>[][] trianglesHash) { map = ObjectUpdate.GetMap(connections); pts = Points; Debug.Log(pts.Count); triangles = new ObjectUpdate().GetTrianglesFromConnections(Points, map, out trianglesHash); //EventSystemMono.cacheObjMap = new List<int>[Points.Count]; List <Vector3> pointsCopy = new List <Vector3>(); foreach (Vector3 v in Points) { pointsCopy.Add(v); } //EventSystemMono.SetPoints(pointsCopy); //EventSystemMono.map = map; int[] mesh = MeshBuilder3D.GetMeshFrom(Points, triangles, map, trianglesHash); return(mesh); }
void handleObjectUpdate(ObjectUpdate oUpdate) { PropertyChange[] pc = oUpdate.changeSet; if (oUpdate.kind == ObjectUpdateKind.enter) { Console.WriteLine(" New Data:"); handleChanges(pc); } else if (oUpdate.kind == ObjectUpdateKind.leave) { Console.WriteLine(" Removed Data:"); handleChanges(pc); } else if (oUpdate.kind == ObjectUpdateKind.modify) { Console.WriteLine(" Changed Data:"); handleChanges(pc); } }
public void HandleObjectUpdate(ObjectEntity objectEntity, ObjectUpdate update) { // Maps only care about object updates if they have moved if (update.MovementUpdate != null) { if (objectEntity is WorldObjectEntity worldObjectEntity) { if (objects.Contains(worldObjectEntity)) { GetLogger().Debug($"{nameof(Map)} instance {this.GetPrimaryKeyLong()} observes a movement update of object {objectEntity.Id}"); // ObjectEntity is equal on ID, so removing and re-adding it updates its other properties objects.Remove(worldObjectEntity); objects.Add(worldObjectEntity); } else { GetLogger().Warn($"{nameof(Map)} instance {this.GetPrimaryKeyLong()} observes a movement update of object {objectEntity.Id} which is not in working memory"); } } } }
public async void EnterWorld(WorldSession session) { var objectUpdate = new ObjectUpdate { NumObjUpdates = 1, MapId = (ushort)session.Player.Map, Obj = session.Player }; objectUpdate.CreateData.ThisIsYou = true; objectUpdate.CreateData.Move = new MovementUpdate(); objectUpdate.CreateData.Move.Status.MoverGUID = session.Player.Guid; objectUpdate.CreateData.Move.Status.Position = session.Player.Position; objectUpdate.CreateData.Move.Status.Facing = session.Player.Facing; await session.Send(objectUpdate); if (ConnectedPlayers.TryAdd(session.Player.Guid, session.Player)) { Log.Debug($"New Player '{session.Player}' connected to world."); } }
//radius is (minimum) radius of the planet AKA distance from core to surface corners/points //variance is maximum radius - minimum, AKA variance is maximum radius added at any 1 point/corner //variance seed is just the rom seed //numPointsLat is number of points around (horizontally) on the sphere //numPointsLong is number of layers of points (layers horizontal and vertical in a way too) //points is an output bascially //cons (connections) is another output basically public static void MakePlanet(float radius, float variance, System.Random r, int numPointsLat, int numPointsLong, out List <Vector3> points, out List <int[]> cons) { points = new List <Vector3>(); cons = new List <int[]>(); float thetaSlerp = 0; double rot = 0; //making points for (int i = 0; i < numPointsLat - 1; i++) { for (int i1 = 0; i1 < numPointsLong; i1++) { float theta = Mathf.Lerp((float)(-Mathf.PI / 2 + Math.PI / (numPointsLat)), (float)(Mathf.PI / 2 - Math.PI / (numPointsLat)), thetaSlerp); double rad = radius + Mathf.PerlinNoise(theta, (float)rot) * variance; float x = (float)(Math.Cos(rot) * Math.Cos(theta) * (rad)); float y = (float)(Math.Sin(theta) * (rad)); float z = (float)(Math.Sin(rot) * Math.Cos(theta) * (rad)); points.Add(new Vector3(x, y, z)); rot += 2 * Math.PI / (numPointsLong); } thetaSlerp += 1.0f / numPointsLat; } for (int i = 0; i < points.Count - numPointsLong; i++) { if ((i + 1) % numPointsLong == 0) { cons.Add(new int[] { i, i + 1 - numPointsLong }); cons.Add(new int[] { i, i + numPointsLong }); cons.Add(new int[] { i, i + 1 }); } else { cons.Add(new int[] { i, i + 1 }); cons.Add(new int[] { i, i + numPointsLong }); cons.Add(new int[] { i, i + 1 + numPointsLong }); } } int count = points.Count; points.Add(new Vector3(0, radius, 0)); points.Add(new Vector3(0, -radius, 0)); for (int i = 0; i < numPointsLong; i++) { cons.Add(new int[] { i, points.Count - 1 }); cons.Add(new int[] { i + count - numPointsLong, points.Count - 2 }); if (i != numPointsLong - 1) { cons.Add(new int[] { i + count - numPointsLong, i + count - numPointsLong + 1 }); } } cons.Add(new int[] { count - 1, count - numPointsLong }); List <int>[] map = ObjectUpdate.GetMap(cons); //valley int num = r.Next(10, 15); for (int i = 0; i < num; i++) { int index = r.Next(0, points.Count); points[index] = points[index].normalized * radius * 0.75f; points = Smooth(index, 5, 0.6f, map, points); } //hill num = r.Next(5, 8); for (int i = 0; i < num; i++) { int index = r.Next(0, points.Count); points[index] = points[index].normalized * radius * 1.2f; points = Smooth(index, 5, 0.65f, map, points); } //plateau num = r.Next(5, 8); for (int i = 0; i < num; i++) { int index = r.Next(0, points.Count); points[index] = points[index].normalized * radius * 1.2f; points = Smooth(index, 2, 1f, map, points); } //flat num = r.Next(1, 3); for (int i = 0; i < num; i++) { int index = r.Next(0, points.Count); points[index] = points[index].normalized * radius * 1.1f; points = Smooth(index, 5, 0.95f, map, points); } //rolling hill num = r.Next(5, 8); for (int i = 0; i < num; i++) { int index = r.Next(0, points.Count); points[index] = points[index].normalized * radius * 1f; points = Smooth(index, 5, 0.3f, map, points); } for (int i = 0; i < points.Count; i++) { points[i] += points[i].normalized * variance * (float)r.NextDouble(); } }
void handleObjectUpdate(ObjectUpdate oUpdate) { PropertyChange[] pc = oUpdate.changeSet; if(oUpdate.kind==ObjectUpdateKind.enter) { Console.WriteLine(" New Data:"); handleChanges(pc); } else if (oUpdate.kind==ObjectUpdateKind.leave) { Console.WriteLine(" Removed Data:"); handleChanges(pc); } else if (oUpdate.kind==ObjectUpdateKind.modify) { Console.WriteLine(" Changed Data:"); handleChanges(pc); } }
/// <summary> /// A terse object update, used when a transformation matrix or /// velocity/acceleration for an object changes but nothing else /// (scale/position/rotation/acceleration/velocity). (From OpenMetaverse, with edits) /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> private Packet TerseUpdateHandler(Packet packet, IPEndPoint simulator) { ImprovedTerseObjectUpdatePacket terse = (ImprovedTerseObjectUpdatePacket)packet; //UpdateDilation(simulator, terse.RegionData.TimeDilation); for (int i = 0; i < terse.ObjectData.Length; i++) { ImprovedTerseObjectUpdatePacket.ObjectDataBlock block = terse.ObjectData[i]; try { int pos = 4; uint localid = Utils.BytesToUInt(block.Data, 0); // Check if we are interested in this update //if (!Client.Settings.ALWAYS_DECODE_OBJECTS && localid != Client.Self.localID && OnObjectUpdated == null) //continue; #region Decode update data ObjectUpdate update = new ObjectUpdate(); // LocalID update.LocalID = localid; // State update.State = block.Data[pos++]; // Avatar boolean update.Avatar = (block.Data[pos++] != 0); // Collision normal for avatar if (update.Avatar) { update.CollisionPlane = new Vector4(block.Data, pos); pos += 16; } // Position update.Position = new Vector3(block.Data, pos); pos += 12; // Velocity update.Velocity = new Vector3( Utils.UInt16ToFloat(block.Data, pos, -128.0f, 128.0f), Utils.UInt16ToFloat(block.Data, pos + 2, -128.0f, 128.0f), Utils.UInt16ToFloat(block.Data, pos + 4, -128.0f, 128.0f)); pos += 6; // Acceleration update.Acceleration = new Vector3( Utils.UInt16ToFloat(block.Data, pos, -64.0f, 64.0f), Utils.UInt16ToFloat(block.Data, pos + 2, -64.0f, 64.0f), Utils.UInt16ToFloat(block.Data, pos + 4, -64.0f, 64.0f)); pos += 6; // Rotation (theta) update.Rotation = new Quaternion( Utils.UInt16ToFloat(block.Data, pos, -1.0f, 1.0f), Utils.UInt16ToFloat(block.Data, pos + 2, -1.0f, 1.0f), Utils.UInt16ToFloat(block.Data, pos + 4, -1.0f, 1.0f), Utils.UInt16ToFloat(block.Data, pos + 6, -1.0f, 1.0f)); pos += 8; // Angular velocity update.AngularVelocity = new Vector3( Utils.UInt16ToFloat(block.Data, pos, -64.0f, 64.0f), Utils.UInt16ToFloat(block.Data, pos + 2, -64.0f, 64.0f), Utils.UInt16ToFloat(block.Data, pos + 4, -64.0f, 64.0f)); pos += 6; // Textures // FIXME: Why are we ignoring the first four bytes here? if (block.TextureEntry.Length != 0) update.Textures = new Primitive.TextureEntry(block.TextureEntry, 4, block.TextureEntry.Length - 4); #endregion Decode update data //Primitive obj = (update.Avatar) ? //(Primitive)GetAvatar(simulator, update.LocalID, UUID.Zero) : //(Primitive)GetPrimitive(simulator, update.LocalID, UUID.Zero); #region Update Client.Self /* if (update.LocalID == Client.Self.localID) { Client.Self.collisionPlane = update.CollisionPlane; Client.Self.relativePosition = update.Position; Client.Self.velocity = update.Velocity; Client.Self.acceleration = update.Acceleration; Client.Self.relativeRotation = update.Rotation; Client.Self.angularVelocity = update.AngularVelocity; } * */ #endregion Update Client.Self if (update.LocalID == mid) mpos = update.Position; else ObjectWithVel(update.Position, update.Velocity); } catch { //Logger.Log(e.Message, Helpers.LogLevel.Warning, Client, e); } } return packet; }
// Update is called once per frame public static void CheckUpdate() { PlayerUpdate?.Invoke(); UIupdate?.Invoke(); ObjectUpdate?.Invoke(); }
private void WriteMovementBlock(BinaryWriter writer, ObjectUpdate update) { if (update.MovementUpdate != null) { var updateFlags = update.UpdateFlags; if (update.ObjectId == TargetObjectId) { updateFlags |= ObjectUpdateFlags.Self; } writer.Write((byte)updateFlags); if (updateFlags.HasFlag(ObjectUpdateFlags.Living)) { var moveFlags = update.MovementUpdate.MoveFlags; writer.Write((int)moveFlags); writer.Write(update.MovementUpdate.MoveTime); writer.Write(update.MovementUpdate.Position.X); writer.Write(update.MovementUpdate.Position.Y); writer.Write(update.MovementUpdate.Position.Z); writer.Write(update.MovementUpdate.Orientation); // TODO: support transports if (moveFlags.HasFlag(MovementFlags.ModeSwimming)) { writer.Write(update.MovementUpdate.MovePitch); } writer.Write(update.MovementUpdate.FallTime); if (moveFlags.HasFlag(MovementFlags.ModeFalling)) { writer.Write(update.MovementUpdate.JumpVelocity); writer.Write(update.MovementUpdate.JumpSineAngle); writer.Write(update.MovementUpdate.JumpCosineAngle); writer.Write(update.MovementUpdate.JumpXYSpeed); } if (moveFlags.HasFlag(MovementFlags.SplineElevation)) { writer.Write(update.MovementUpdate.UnknownSplineThingy); } writer.Write(update.MovementUpdate.SpeedWalking); writer.Write(update.MovementUpdate.SpeedRunning); writer.Write(update.MovementUpdate.SpeedRunningBack); writer.Write(update.MovementUpdate.SpeedSwimming); writer.Write(update.MovementUpdate.SpeedSwimmingBack); writer.Write(update.MovementUpdate.SpeedTurning); // TODO: support spline motion } else if (updateFlags.HasFlag(ObjectUpdateFlags.HasPosition)) { writer.Write(update.MovementUpdate.Position.X); writer.Write(update.MovementUpdate.Position.Y); writer.Write(update.MovementUpdate.Position.Z); writer.Write(update.MovementUpdate.Orientation); } if (updateFlags.HasFlag(ObjectUpdateFlags.MaskId)) { writer.Write(update.ObjectId.MaskId); } if (updateFlags.HasFlag(ObjectUpdateFlags.All)) { writer.Write(1); } // TODO: support fullguid, transports } }
public override void HandleObjectUpdate(ObjectEntity objectEntity, ObjectUpdate update) { base.HandleObjectUpdate(objectEntity, update); var tasks = new LinkedList <Task>(); var objectUpdateRequest = new ObjectUpdateRequest() { TargetObjectId = State.Id, }; objectUpdateRequest.ObjectUpdates.Add(update); tasks.AddLast(Send(objectUpdateRequest)); // for Unit entities, we need to send move start/stop/heartbeat packets as well if (objectEntity is UnitEntity unitEntity) { var opcodes = new LinkedList <ShardServerOpcode>(); if (unitEntity.Jumped) { opcodes.AddLast(ShardServerOpcode.MoveJump); } if (unitEntity.PreviousMoveFlags.HasFlag(MovementFlags.ModeFalling) && !unitEntity.MoveFlags.HasFlag(MovementFlags.ModeFalling)) { opcodes.AddLast(ShardServerOpcode.MoveFallLand); } if ((unitEntity.MoveFlags & MovementFlags.MoveMask) != 0 && unitEntity.PreviousMoveFlags == unitEntity.MoveFlags) { // heartbeat opcodes.AddLast(ShardServerOpcode.MoveHeartbeat); } else { // complicated if ((unitEntity.MoveFlags & MovementFlags.MoveLeft) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.MoveLeft) == 0) { opcodes.AddLast(ShardServerOpcode.MoveStrafeStartLeft); } else if ((unitEntity.MoveFlags & MovementFlags.MoveRight) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.MoveRight) == 0) { opcodes.AddLast(ShardServerOpcode.MoveStrafeStartRight); } else if ((unitEntity.MoveFlags & (MovementFlags.MoveLeft | MovementFlags.MoveRight)) == 0 && (unitEntity.PreviousMoveFlags & (MovementFlags.MoveLeft | MovementFlags.MoveRight)) != 0) { opcodes.AddLast(ShardServerOpcode.MoveStrafeStop); } if ((unitEntity.MoveFlags & MovementFlags.MoveForward) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.MoveForward) == 0) { opcodes.AddLast(ShardServerOpcode.MoveStartForward); } else if ((unitEntity.MoveFlags & MovementFlags.MoveBackward) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.MoveBackward) == 0) { opcodes.AddLast(ShardServerOpcode.MoveStartBackward); } else if ((unitEntity.MoveFlags & (MovementFlags.MoveForward | MovementFlags.MoveBackward)) == 0 && (unitEntity.PreviousMoveFlags & (MovementFlags.MoveForward | MovementFlags.MoveBackward)) != 0) { opcodes.AddLast(ShardServerOpcode.MoveStop); } if ((unitEntity.MoveFlags & MovementFlags.TurnLeft) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.TurnLeft) == 0) { opcodes.AddLast(ShardServerOpcode.MoveTurnStartLeft); } else if ((unitEntity.MoveFlags & MovementFlags.TurnRight) != 0 && (unitEntity.PreviousMoveFlags & MovementFlags.TurnRight) == 0) { opcodes.AddLast(ShardServerOpcode.MoveTurnStartRight); } else if ((unitEntity.MoveFlags & (MovementFlags.TurnLeft | MovementFlags.TurnRight)) == 0 && (unitEntity.PreviousMoveFlags & (MovementFlags.TurnLeft | MovementFlags.TurnRight)) != 0) { opcodes.AddLast(ShardServerOpcode.MoveTurnStop); } } if (unitEntity.Orientation != unitEntity.PreviousOrientation && (unitEntity.MoveFlags & (MovementFlags.TurnLeft | MovementFlags.TurnRight)) == 0) { opcodes.AddLast(ShardServerOpcode.MoveSetOrientation); } foreach (var opcode in opcodes) { var movePacket = new MovementOutPacket(opcode) { ObjectId = unitEntity.Id, FallTime = unitEntity.FallTime, MovementFlags = unitEntity.MoveFlags, Orientation = unitEntity.Orientation, Pitch = unitEntity.MovePitch, Position = unitEntity.Position, Time = unitEntity.MoveTime, Falling = new MovementOutPacket.FallingInfo() { CosAngle = unitEntity.Jump.CosineAngle, SinAngle = unitEntity.Jump.SineAngle, Velocity = unitEntity.Jump.Velocity, XYSpeed = unitEntity.Jump.XYSpeed, }, Transport = null, }; tasks.AddLast(Send(movePacket)); } } Task.WhenAll(tasks).Wait(); }
// TODO naming public void SyncFrame(float dt) { foreach (var obj in Objects.Values) { obj.ProcessBeforeSync(dt); } ProcessControlMessages(); // Receive states of copy objects and ACK from other nodes List <KeyValuePair <uint, Connection> > pairs; lock (Connections) { pairs = Connections.ToList(); } foreach (var connPair in pairs) { uint connNodeId = connPair.Key; Connection conn = connPair.Value; ISyncMessage msg; while (conn.TryReceiveMessage <ISyncMessage>(Connection.ChannelType.Sync, out msg)) { switch (msg) { case UpdateMessage updateMsg: ProcessUpdateMessage(updateMsg, connNodeId, conn); break; case AckMessage ackMsg: ProcessAckMessage(ackMsg, connNodeId); break; } } } // Send states of objects foreach (var connPair in pairs) { uint connNodeId = connPair.Key; Connection conn = connPair.Value; // If no ACK has came from the connection yet (e.g. new connection), send all fields (any uint is larger than -1) long ackedTick = LastTickAcknowledged.ContainsKey(connNodeId) ? (long)LastTickAcknowledged[connNodeId] : -1; // Collect object updates var updates = new List <ObjectUpdate>(); foreach (var pair in Objects) { var id = pair.Key; var obj = pair.Value; // If this is the server, don't send object to the node which has original // If this is a client, don't send objects that this node does not have original if (obj.OriginalNodeId == connNodeId || (NodeId != ServerNodeId && obj.OriginalNodeId != NodeId)) { continue; } // field updates var fields = obj.Fields.Where(field => // Send fields which have been updated // Because updates run after sending, lastUpdatedTick==ackedTick must be included. field.Value.LastUpdatedTick >= ackedTick ).Select(field => new FieldUpdate { Name = field.Key, Value = field.Value.Value } ).ToList(); if (fields.Count == 0) { continue; // When no field have to be sent, skip entire object } ObjectUpdate update = new ObjectUpdate { ObjectId = id, Fields = fields }; updates.Add(update); } if (updates.Count == 0) { continue; // When no object have to be sent, skip the receiving node } // Construct message and send UpdateMessage msg = new UpdateMessage { Tick = Tick, ObjectUpdates = updates }; conn.SendMessage <ISyncMessage>(Connection.ChannelType.Sync, msg); } Tick += 1; foreach (var obj in Objects.Values) { obj.ProcessAfterSync(dt); } }
/* parameters: None * returns: ObjectUpdate with all the GameObjects to instantiate at the Start. */ ///@TODO: this is a stub that needs to be implemented public ObjectUpdate Start() { ObjectUpdate o = new ObjectUpdate(); return(o); }
public void RegisterForObjectUpdates(ObjectUpdate p) { PacketProcessors.ObjectUpdateEvent += p; }
/// <summary> /// Handle Updates for a single object. /// waits till expected values of properties to check are reached /// Destroys the ObjectFilter when done. /// </summary> /// <param name="objmor">MOR of the Object to wait for</param> /// <param name="filterProps">Properties list to filter</param> /// <param name="endWaitProps"> /// Properties list to check for expected values /// these be properties of a property in the filter properties list /// </param> /// <param name="expectedVals">values for properties to end the wait</param> /// <returns>true indicating expected values were met, and false otherwise</returns> public object[] WaitForValues( ManagedObjectReference objmor, string[] filterProps, string[] endWaitProps, object[][] expectedVals ) { // version string is initially null string version = ""; object[] endVals = new object[endWaitProps.Length]; object[] filterVals = new object[filterProps.Length]; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = objmor; spec.propSet = new PropertySpec[] { new PropertySpec() }; spec.propSet[0].pathSet = filterProps; spec.propSet[0].type = objmor.type; spec.objectSet[0].selectSet = null; spec.objectSet[0].skip = false; spec.objectSet[0].skipSpecified = true; ManagedObjectReference filterSpecRef = _connection.Service.CreateFilter( _connection.PropCol, spec, true ); bool reached = false; UpdateSet updateset = null; PropertyFilterUpdate[] filtupary = null; PropertyFilterUpdate filtup = null; ObjectUpdate[] objupary = null; ObjectUpdate objup = null; PropertyChange[] propchgary = null; PropertyChange propchg = null; while (!reached) { updateset = _connection.Service.WaitForUpdates( _connection.PropCol, version ); version = updateset.version; if (updateset == null || updateset.filterSet == null) { continue; } // Make this code more general purpose when PropCol changes later. filtupary = updateset.filterSet; filtup = null; for (int fi = 0; fi < filtupary.Length; fi++) { filtup = filtupary[fi]; objupary = filtup.objectSet; objup = null; propchgary = null; for (int oi = 0; oi < objupary.Length; oi++) { objup = objupary[oi]; // TODO: Handle all "kind"s of updates. if (objup.kind == ObjectUpdateKind.modify || objup.kind == ObjectUpdateKind.enter || objup.kind == ObjectUpdateKind.leave ) { propchgary = objup.changeSet; for (int ci = 0; ci < propchgary.Length; ci++) { propchg = propchgary[ci]; UpdateValues(endWaitProps, endVals, propchg); UpdateValues(filterProps, filterVals, propchg); } } } } object expctdval = null; // Check if the expected values have been reached and exit the loop if done. // Also exit the WaitForUpdates loop if this is the case. for (int chgi = 0; chgi < endVals.Length && !reached; chgi++) { for (int vali = 0; vali < expectedVals[chgi].Length && !reached; vali++) { expctdval = expectedVals[chgi][vali]; reached = expctdval.Equals(endVals[chgi]) || reached; } } } // Destroy the filter when we are done. _connection.Service.DestroyPropertyFilter(filterSpecRef); return(filterVals); }
//Uncompress and process update private static void ProcessUnreliableClientUpdate(Session MySession, List <byte> MyPacket) { //Get Unreliable length UnreliableLength = MyPacket[0]; //Get Message # we are acknowledging XorMessage = (ushort)(MyPacket[2] << 8 | MyPacket[1]); //Get xor byte /Technically not needed...? Tells us what message to xor with but that should be the last message we xor'd... right? XorByte = MyPacket[3]; //Remove read bytes MyPacket.RemoveRange(0, 4); //This means that this is a deprecated packet that may of got lost on the way, base xor is behind current basexor //Let's not bother to even process it if (MySession.Channel40Base.ThisMessagenumber > (XorMessage - XorByte)) { //clear packet MyPacket.Clear(); return; } //Uncompress the packet Compression.UncompressUnreliable(MyPacket, UnreliableLength); //First 0x4029 from client if (XorByte == 0) { MySession.MyCharacter.World = MyPacket[0]; //This should match what we have stored for the character? Let's verify this? MySession.MyCharacter.XCoord = ConvertXZ(Get3ByteInt(MyPacket.GetRange(1, 3))); MySession.MyCharacter.YCoord = ConvertY(Get3ByteInt(MyPacket.GetRange(4, 3))); MySession.MyCharacter.ZCoord = ConvertXZ(Get3ByteInt(MyPacket.GetRange(7, 3))); //Skip 12 bytes... MySession.MyCharacter.Facing = ConvertFacing(MyPacket[22]); //Skip 12 bytes... MySession.MyCharacter.Animation = (short)(GetShort(MyPacket.GetRange(35, 2))); MySession.MyCharacter.Target = Get4ByteInt(MyPacket.GetRange(37, 4)); //Indicates character is appearing on screen/in world MySession.InGame = true; //Add xor base message to our list to track MySession.Channel40Base = new Message(XorMessage, MyPacket); //Should we generate a C9 here? List <byte> MyObject = Compression.CompressUnreliable(new List <byte>(ObjectUpdate.GatherObjectUpdate(MySession.MyCharacter, MySession.sessionIDUp))); MyObject.Insert(0, 0); MyObject.InsertRange(0, BitConverter.GetBytes(MySession.Channel0Message)); MyObject.Insert(0, 0xC9); MyObject.Insert(0, 0); //Add 0 on to end to denote end of this channel MyObject.Add(0); lock (MySession.SessionMessages) { MySession.SessionMessages.AddRange(MyObject); } MyObject.Clear(); } //Following client updates MySession.Channel40Base.ThisMessage //Lots of xor'ing... else { MySession.MyCharacter.World = (byte)(MySession.Channel40Base.ThisMessage[0] ^ MyPacket[0]); //This should match what we have stored for the character? Let's verify this? MySession.MyCharacter.XCoord = ConvertXZ(Get3ByteIntXOR((byte)(MySession.Channel40Base.ThisMessage[1] ^ MyPacket[1]), (byte)(MySession.Channel40Base.ThisMessage[2] ^ MyPacket[2]), (byte)(MySession.Channel40Base.ThisMessage[3] ^ MyPacket[3]))); MySession.MyCharacter.YCoord = ConvertY(Get3ByteIntXOR((byte)(MySession.Channel40Base.ThisMessage[4] ^ MyPacket[4]), (byte)(MySession.Channel40Base.ThisMessage[5] ^ MyPacket[5]), (byte)(MySession.Channel40Base.ThisMessage[6] ^ MyPacket[6]))); MySession.MyCharacter.ZCoord = ConvertXZ(Get3ByteIntXOR((byte)(MySession.Channel40Base.ThisMessage[7] ^ MyPacket[7]), (byte)(MySession.Channel40Base.ThisMessage[8] ^ MyPacket[8]), (byte)(MySession.Channel40Base.ThisMessage[9] ^ MyPacket[9]))); //Skip 12 bytes... MySession.MyCharacter.Facing = ConvertFacing((byte)(MySession.Channel40Base.ThisMessage[22] ^ MyPacket[22])); //Skip 12 bytes... MySession.MyCharacter.Animation = (short)(GetShortXOR((byte)(MySession.Channel40Base.ThisMessage[35] ^ MyPacket[35]), (byte)(MySession.Channel40Base.ThisMessage[36] ^ MyPacket[36]))); MySession.MyCharacter.Target = Get4ByteIntXOR((byte)(MySession.Channel40Base.ThisMessage[37] ^ MyPacket[37]), (byte)(MySession.Channel40Base.ThisMessage[38] ^ MyPacket[38]), (byte)(MySession.Channel40Base.ThisMessage[39] ^ MyPacket[39]), (byte)(MySession.Channel40Base.ThisMessage[40] ^ MyPacket[40])); //Means client has started a new basemessage, follow suit if (MySession.Channel40Base.ThisMessagenumber < (XorMessage - XorByte)) { //Grab new base message to xor against Message NewBaseMessage = MySession.Channel40BaseList.Find(i => i.ThisMessagenumber == (XorMessage - XorByte)); //Add our new xor'd base message and start over MySession.Channel40Base = new Message(XorMessage, GetArrayXOR(NewBaseMessage.ThisMessage, MyPacket)); //Remove all other possible base messages MySession.Channel40BaseList.Clear(); } //Means update is based off same xor base else if (MySession.Channel40Base.ThisMessagenumber == (XorMessage - XorByte)) { MySession.Channel40BaseList.Add(new Message(XorMessage, GetArrayXOR(MySession.Channel40Base.ThisMessage, MyPacket))); } } //Let outbound rdpreport know to include this to outbound ack's //This is purely as inbetween for message ack's MySession.Channel40Message = XorMessage; MySession.Channel40Ack = true; MyPacket.Clear(); }
public Enemy(float maxhp, int ms, float defense, GameObject referenceObject) { enemyStats = new StatSystem(maxhp, ms, defense); this.referenceObject = referenceObject; o = new ObjectUpdate(); }
/* Parameters: * o: list of changes to make to the gameObject, as well as new gameObjects to instantiate and behaviors to attatch to the new gameObjects. * gameObject: the gameObject to change * * Description: * changes the gameObject as specified by 'o', instantiates new objects as specified by 'o'. */ public static void Update(ObjectUpdate o, GameObject gameObject) { //handling all the instantiation requests foreach (InstantiationRequest i in o.instatiationRequests) { GameObject resource = (GameObject)Resources.Load(i.resourcePath); /* * if (i.triangle != null) * { * bool existsInCache = false; * for(int a = 0; a < cachedObjects.Count; a++) * { * if (cachedObjects[a].name.Equals(i.resourcePath)) * { * cachedObjects[a].positions.Add(i.position); * cachedObjects[a].orientations.Add(i.orientation); * * if(cacheObjMap[i.triangle[0], i.triangle[1]] == null) * { * cacheObjMap[i.triangle[0], i.triangle[1]] = new List<CacheObjTuple>(); * } * if (cacheObjMap[i.triangle[0], i.triangle[2]] == null) * { * cacheObjMap[i.triangle[0], i.triangle[2]] = new List<CacheObjTuple>(); * } * if (cacheObjMap[i.triangle[1], i.triangle[2]] == null) * { * cacheObjMap[i.triangle[1], i.triangle[2]] = new List<CacheObjTuple>(); * } * CacheObjTuple t = new CacheObjTuple { cacheObjIndex = a, objIndex = cachedObjects[a].positions.Count - 1 }; * * cacheObjMap[i.triangle[0], i.triangle[1]].Add(t); * cacheObjMap[i.triangle[0], i.triangle[2]].Add(t); * cacheObjMap[i.triangle[1], i.triangle[2]].Add(t); * * existsInCache = true; * break; * } * } * if (!existsInCache) * { * Debug.Log("making new cache " + i.resourcePath); * CacheObject newCache = new CacheObject(i.resourcePath, new List<Vector3> { i.position }, * new List<Quaternion> { i.orientation }, resource); * * if (cacheObjMap[i.triangle[0], i.triangle[1]] == null) * { * cacheObjMap[i.triangle[0], i.triangle[1]] = new List<CacheObjTuple>(); * } * if (cacheObjMap[i.triangle[0], i.triangle[2]] == null) * { * cacheObjMap[i.triangle[0], i.triangle[2]] = new List<CacheObjTuple>(); * } * if (cacheObjMap[i.triangle[1], i.triangle[2]] == null) * { * cacheObjMap[i.triangle[1], i.triangle[2]] = new List<CacheObjTuple>(); * } * CacheObjTuple t = new CacheObjTuple { cacheObjIndex = cachedObjects.Count, objIndex = 0 }; * * cacheObjMap[i.triangle[0], i.triangle[1]].Add(t); * cacheObjMap[i.triangle[0], i.triangle[2]].Add(t); * cacheObjMap[i.triangle[1], i.triangle[2]].Add(t); * * for (int i1 = 0; i1 < newCache.numInCache; i1++) * { * newCache.objs.Add(UnityEngine.Object.Instantiate(resource, new Vector3(100000,100000,100000), Quaternion.Euler(Vector3.zero))); * } * cachedObjects.Add(newCache); * } * continue; * } */ foreach (IClass c in i.behaviorsToAdd) { if (c == null) { throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: the class of type " + c.GetType().Name + " is null!"); } IMono comp = (IMono)resource.AddComponent(c.MonoScript); if (comp == null) { throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: Monobehavior " + c.MonoScript.Name + " for class " + c.GetType().Name + " does not exist, is not a Monobehavior, or does not implement the IMono interface"); } comp.SetMainClass(c); } //instantiating the new gameobject with the behaviors added above GameObject gameObj = GameObject.Instantiate(resource, i.position, i.orientation) as GameObject; if (gameObj == null) { Debug.Log("gameObject is NULL!!!"); } server.Create(gameObj, i.resourcePath); } //setting all of the values here //set position and orientation if (o.position != null) { gameObject.transform.position = o.position.GetVector(); } if (o.rotation != null) { gameObject.transform.rotation = o.rotation.GetQuaternion(); } //if you're trying to set the velocity or force of the object, but there is no Rigidbody, throw an exception Rigidbody r = gameObject.GetComponent <Rigidbody>(); if (o.velocity != null || o.force != null && r == null) { throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: there is no rigidbody component for this gameObject"); } //set velocity and force if (o.velocity != null) { r.velocity = o.velocity.GetVector(); } if (o.force != null) { r.AddForce(o.force.GetVector()); } ///@TODO: when faces are implemented, they'll need another if statement here. //setting mesh if (o.meshPoints != null) { List <Vector3> meshPointsUnwrapped = new List <Vector3>(); foreach (Vector3Wrapper v in o.meshPoints) { meshPointsUnwrapped.Add(v.GetVector()); } if (o.triangles != null) { /*Mesh newMesh = MeshBuilder3D.GetMeshFrom(meshPointsUnwrapped, o.triangles); * gameObject.GetComponent<MeshFilter>().mesh = newMesh; * gameObject.GetComponent<MeshCollider>().sharedMesh = newMesh;*/ } } }