Пример #1
0
    public void CreateTerrain(ja2.Map Map_, ja2.TerrainMaterialManager MatManager)
    {
        if(Map_.width % ja2.TerrainPartition.PARTITION_WIDTH != 0 || Map_.width % ja2.TerrainPartition.PARTITION_WIDTH != 0)
            throw new System.ArgumentException("Map width/height must be normalized to terrain partition width/height.");
        // Create component
        mapInstance = ScriptableObject.CreateInstance<MapInstance>();
        mapInstance.map = Map_;

        // Need to create terrain partitions
        int partition_width = Map_.width / ja2.TerrainPartition.PARTITION_WIDTH;
        int partition_height = Map_.height / ja2.TerrainPartition.PARTITION_HEIGHT;
        for (int i = 0; i < partition_height; ++i)
        {
            for (int j = 0; j < partition_width; ++j)
            {
                // Create terrain GO
                GameObject terrain_go = new GameObject(PARTITION_NAME + j + "_" + i);
                terrain_go.isStatic = true;
                // Set parent
                terrain_go.transform.parent = transform;
                // Update position
                Vector3 tile_vertex_0 = ja2.TerrainPartition.TileVertex(j * ja2.TerrainPartition.PARTITION_WIDTH, i * ja2.TerrainPartition.PARTITION_HEIGHT, 0);
                Vector3 tile_vertex_1 = ja2.TerrainPartition.TileVertex(j * ja2.TerrainPartition.PARTITION_WIDTH, i * ja2.TerrainPartition.PARTITION_HEIGHT, 1);
                terrain_go.transform.position = new Vector3(tile_vertex_0.x, 0, tile_vertex_1.z);
                // Set layer
                terrain_go.layer = Terrain.LAYER;
                // Create component
                var terrain = terrain_go.AddComponent<Terrain>();
                terrain.CreatePartition(j, i, mapInstance, MatManager);
            }
        }
    }
Пример #2
0
 public void CreatePartition(int X, int Y, MapInstance Map, TerrainMaterialManager MatManager)
 {
     TerrainTileSet tile_set = MatManager.GetTerrainSet(Map.map.terrainName);
     // Create terrain partition
     terrainPartition = new ja2.TerrainPartition();
     Mesh mesh = terrainPartition.Create(X, Y, Map.map, tile_set);
     // Add needed components
     GetComponent<MeshFilter>().mesh = mesh;
     GetComponent<MeshCollider>().sharedMesh = mesh;
     var mesh_renderer = gameObject.GetComponent<MeshRenderer>();
     // Set map material
     mesh_renderer.sharedMaterial = Resources.LoadAssetAtPath("Assets/Materials/" + tile_set.materialName + ".mat", typeof(Material)) as Material;
     // Don't cast shadows
     mesh_renderer.castShadows = false;
 }
 //cria uma instancia do problema a partir de um nome de mapa
 public TravellingSalesmanMap(MapInstance map)
 {
     this.map = map;
     switch (map) {
         case MapInstance.M06:
             DistanceMatrix = ReadDistancesFile("..\\..\\..\\Commons\\MapDescriptions\\M06_Distances.txt");
             //CitiesAlias = new string[] { "Aveiro", "Badajoz", "Cordoba", "Evora", "Faro", "Madrid" };
             break;
         case MapInstance.M15:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\M15_Coordinates.txt");
             break;
         case MapInstance.BAY29:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\BAY29_Coordinates.txt");
             break;
         case MapInstance.M29:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\M29_Coordinates.txt");
             break;
         case MapInstance.M38:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\M38_Coordinates.txt");
             break;
         case MapInstance.ATT48:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\ATT48_Coordinates.txt");
             break;
         case MapInstance.BRAZIL58:
             DistanceMatrix = ReadDistancesFile("..\\..\\..\\Commons\\MapDescriptions\\BRAZIL58_Distances.txt");
             break;
         case MapInstance.ST70:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\ST70_Coordinates.txt");
             break;
         case MapInstance.EIL76:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\EIL76_Coordinates.txt");
             break;
         case MapInstance.RAT99:
             DistanceMatrix = ReadCoordinatesFile("..\\..\\..\\Commons\\MapDescriptions\\RAT99_Coordinates.txt");
             break;
     }
     CityCount = (int)Math.Sqrt(DistanceMatrix.Length);
 }
        public static void DrawOverlay()
        {
            var map = MapInstance.Get(Globals.Me.CurrentMap);

            if (map != null)
            {
                float ecTime = Globals.System.GetTimeMs() - sOverlayUpdate;

                if (OverlayColor.A != map.AHue ||
                    OverlayColor.R != map.RHue ||
                    OverlayColor.G != map.GHue ||
                    OverlayColor.B != map.BHue)
                {
                    if (OverlayColor.A < map.AHue)
                    {
                        if (OverlayColor.A + (int)(255 * ecTime / 2000f) > map.AHue)
                        {
                            OverlayColor.A = (byte)map.AHue;
                        }
                        else
                        {
                            OverlayColor.A += (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.A > map.AHue)
                    {
                        if (OverlayColor.A - (int)(255 * ecTime / 2000f) < map.AHue)
                        {
                            OverlayColor.A = (byte)map.AHue;
                        }
                        else
                        {
                            OverlayColor.A -= (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.R < map.RHue)
                    {
                        if (OverlayColor.R + (int)(255 * ecTime / 2000f) > map.RHue)
                        {
                            OverlayColor.R = (byte)map.RHue;
                        }
                        else
                        {
                            OverlayColor.R += (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.R > map.RHue)
                    {
                        if (OverlayColor.R - (int)(255 * ecTime / 2000f) < map.RHue)
                        {
                            OverlayColor.R = (byte)map.RHue;
                        }
                        else
                        {
                            OverlayColor.R -= (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.G < map.GHue)
                    {
                        if (OverlayColor.G + (int)(255 * ecTime / 2000f) > map.GHue)
                        {
                            OverlayColor.G = (byte)map.GHue;
                        }
                        else
                        {
                            OverlayColor.G += (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.G > map.GHue)
                    {
                        if (OverlayColor.G - (int)(255 * ecTime / 2000f) < map.GHue)
                        {
                            OverlayColor.G = (byte)map.GHue;
                        }
                        else
                        {
                            OverlayColor.G -= (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.B < map.BHue)
                    {
                        if (OverlayColor.B + (int)(255 * ecTime / 2000f) > map.BHue)
                        {
                            OverlayColor.B = (byte)map.BHue;
                        }
                        else
                        {
                            OverlayColor.B += (byte)(255 * ecTime / 2000f);
                        }
                    }

                    if (OverlayColor.B > map.BHue)
                    {
                        if (OverlayColor.B - (int)(255 * ecTime / 2000f) < map.BHue)
                        {
                            OverlayColor.B = (byte)map.BHue;
                        }
                        else
                        {
                            OverlayColor.B -= (byte)(255 * ecTime / 2000f);
                        }
                    }
                }
            }

            DrawGameTexture(Renderer.GetWhiteTexture(), new FloatRect(0, 0, 1, 1), CurrentView, OverlayColor, null);
            sOverlayUpdate = Globals.System.GetTimeMs();
        }
        private static void UpdateView()
        {
            if (Globals.Me == null)
            {
                CurrentView = new FloatRect(0, 0, Renderer.GetScreenWidth(), Renderer.GetScreenHeight());
                Renderer.SetView(CurrentView);

                return;
            }

            var map = MapInstance.Get(Globals.Me.CurrentMap);

            if (Globals.GameState == GameStates.InGame && map != null)
            {
                var en = Globals.Me;
                var x  = map.GetX() - Options.MapWidth * Options.TileWidth;
                var y  = map.GetY() - Options.MapHeight * Options.TileHeight;
                var x1 = map.GetX() + Options.MapWidth * Options.TileWidth * 2;
                var y1 = map.GetY() + Options.MapHeight * Options.TileHeight * 2;
                if (map.CameraHolds[(int)Directions.Up])
                {
                    y += Options.MapHeight * Options.TileHeight;
                }

                if (map.CameraHolds[(int)Directions.Left])
                {
                    x += Options.MapWidth * Options.TileWidth;
                }

                if (map.CameraHolds[(int)Directions.Right])
                {
                    x1 -= Options.MapWidth * Options.TileWidth;
                }

                if (map.CameraHolds[(int)Directions.Down])
                {
                    y1 -= Options.MapHeight * Options.TileHeight;
                }

                var w            = x1 - x;
                var h            = y1 - y;
                var restrictView = new FloatRect(x, y, w, h);
                CurrentView = new FloatRect(
                    (int)Math.Ceiling(en.GetCenterPos().X - Renderer.GetScreenWidth() / 2f),
                    (int)Math.Ceiling(en.GetCenterPos().Y - Renderer.GetScreenHeight() / 2f),
                    Renderer.GetScreenWidth(), Renderer.GetScreenHeight()
                    );

                if (restrictView.Width >= CurrentView.Width)
                {
                    if (CurrentView.Left < restrictView.Left)
                    {
                        CurrentView.X = restrictView.Left;
                    }

                    if (CurrentView.Left + CurrentView.Width > restrictView.Left + restrictView.Width)
                    {
                        CurrentView.X -=
                            CurrentView.Left + CurrentView.Width - (restrictView.Left + restrictView.Width);
                    }
                }

                if (restrictView.Height >= CurrentView.Height)
                {
                    if (CurrentView.Top < restrictView.Top)
                    {
                        CurrentView.Y = restrictView.Top;
                    }

                    if (CurrentView.Top + CurrentView.Height > restrictView.Top + restrictView.Height)
                    {
                        CurrentView.Y -=
                            CurrentView.Top + CurrentView.Height - (restrictView.Top + restrictView.Height);
                    }
                }
            }
            else
            {
                CurrentView = new FloatRect(0, 0, Renderer.GetScreenWidth(), Renderer.GetScreenHeight());
            }

            Renderer.SetView(CurrentView);
        }
Пример #6
0
        public void CheckForCollision()
        {
            if (mSpawnCount != 0 || mQuantity < mMyBase.Quantity)
            {
                for (var i = 0; i < mSpawnedAmount; i++)
                {
                    if (Spawns[i] != null && Globals.System.GetTimeMs() > Spawns[i].TransmittionTimer)
                    {
                        var spawnMap = MapInstance.Get(Spawns[i].MapId);
                        if (spawnMap != null)
                        {
                            var newx      = Spawns[i].X + (int)GetRangeX(Spawns[i].Dir, 1);
                            var newy      = Spawns[i].Y + (int)GetRangeY(Spawns[i].Dir, 1);
                            var newMapId  = Spawns[i].MapId;
                            var killSpawn = false;

                            Spawns[i].Distance++;

                            if (newx < 0)
                            {
                                if (MapInstance.Get(spawnMap.Left) != null)
                                {
                                    newMapId = spawnMap.Left;
                                    newx     = Options.MapWidth - 1;
                                }
                                else
                                {
                                    killSpawn = true;
                                }
                            }

                            if (newx > Options.MapWidth - 1)
                            {
                                if (MapInstance.Get(spawnMap.Right) != null)
                                {
                                    newMapId = spawnMap.Right;
                                    newx     = 0;
                                }
                                else
                                {
                                    killSpawn = true;
                                }
                            }

                            if (newy < 0)
                            {
                                if (MapInstance.Get(spawnMap.Up) != null)
                                {
                                    newMapId = spawnMap.Up;
                                    newy     = Options.MapHeight - 1;
                                }
                                else
                                {
                                    killSpawn = true;
                                }
                            }

                            if (newy > Options.MapHeight - 1)
                            {
                                if (MapInstance.Get(spawnMap.Down) != null)
                                {
                                    newMapId = spawnMap.Down;
                                    newy     = 0;
                                }
                                else
                                {
                                    killSpawn = true;
                                }
                            }

                            if (killSpawn)
                            {
                                Spawns[i].Dispose();
                                Spawns[i] = null;
                                mSpawnCount--;

                                continue;
                            }

                            Spawns[i].X     = newx;
                            Spawns[i].Y     = newy;
                            Spawns[i].MapId = newMapId;
                            var newMap = MapInstance.Get(newMapId);

                            //Check for Z-Dimension
                            if (newMap.Attributes[Spawns[i].X, Spawns[i].Y] != null)
                            {
                                if (newMap.Attributes[Spawns[i].X, Spawns[i].Y].Type == MapAttributes.ZDimension)
                                {
                                    if (((MapZDimensionAttribute)newMap.Attributes[Spawns[i].X, Spawns[i].Y])
                                        .GatewayTo >
                                        0)
                                    {
                                        Spawns[i].Z =
                                            ((MapZDimensionAttribute)newMap.Attributes[Spawns[i].X, Spawns[i].Y])
                                            .GatewayTo -
                                            1;
                                    }
                                }
                            }

                            if (killSpawn == false)
                            {
                                killSpawn = Collided(i);
                            }

                            Spawns[i].TransmittionTimer = Globals.System.GetTimeMs() +
                                                          (long)((float)mMyBase.Speed / (float)mMyBase.Range);

                            if (Spawns[i].Distance >= mMyBase.Range)
                            {
                                killSpawn = true;
                            }

                            if (killSpawn)
                            {
                                Spawns[i].Dispose();
                                Spawns[i] = null;
                                mSpawnCount--;
                            }
                        }
                    }
                }
            }
            else
            {
                Globals.Entities[Id].Dispose();
            }
        }
        public static void DrawInGame()
        {
            var currentMap = Globals.Me.MapInstance;

            if (currentMap == null)
            {
                return;
            }

            if (Globals.NeedsMaps)
            {
                return;
            }

            if (GridSwitched)
            {
                //Brightness
                var brightnessTarget = (byte)(currentMap.Brightness / 100f * 255);
                BrightnessLevel       = brightnessTarget;
                PlayerLightColor.R    = currentMap.PlayerLightColor.R;
                PlayerLightColor.G    = currentMap.PlayerLightColor.G;
                PlayerLightColor.B    = currentMap.PlayerLightColor.B;
                sPlayerLightSize      = currentMap.PlayerLightSize;
                sPlayerLightIntensity = currentMap.PlayerLightIntensity;
                sPlayerLightExpand    = currentMap.PlayerLightExpand;

                //Overlay
                OverlayColor.A = (byte)currentMap.AHue;
                OverlayColor.R = (byte)currentMap.RHue;
                OverlayColor.G = (byte)currentMap.GHue;
                OverlayColor.B = (byte)currentMap.BHue;

                //Fog && Panorama
                currentMap.GridSwitched();
                GridSwitched = false;
            }

            var animations = LiveAnimations.ToArray();

            foreach (var animInstance in animations)
            {
                if (animInstance.ParentGone())
                {
                    animInstance.Dispose();
                }
            }

            ClearDarknessTexture();

            var gridX = currentMap.MapGridX;
            var gridY = currentMap.MapGridY;

            //Draw Panoramas First...
            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        DrawMapPanorama(Globals.MapGrid[x, y]);
                    }
                }
            }

            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        DrawMap(Globals.MapGrid[x, y], 0);
                    }
                }
            }

            foreach (var animInstance in animations)
            {
                animInstance.Draw(false);
            }

            for (var y = 0; y < Options.MapHeight * 5; y++)
            {
                for (var x = 0; x < 3; x++)
                {
                    foreach (var entity in RenderingEntities[x, y])
                    {
                        entity.Draw();
                        EntitiesDrawn++;
                    }

                    if (x == 0 && y > 0 && y % Options.MapHeight == 0)
                    {
                        for (var x1 = gridX - 1; x1 <= gridX + 1; x1++)
                        {
                            var y1 = gridY - 2 + (int)Math.Floor(y / (float)Options.MapHeight);
                            if (x1 >= 0 &&
                                x1 < Globals.MapGridWidth &&
                                y1 >= 0 &&
                                y1 < Globals.MapGridHeight &&
                                Globals.MapGrid[x1, y1] != Guid.Empty)
                            {
                                var map = MapInstance.Get(Globals.MapGrid[x1, y1]);
                                if (map != null)
                                {
                                    map.DrawItemsAndLights();
                                }
                            }
                        }
                    }
                }
            }

            foreach (var animInstance in animations)
            {
                animInstance.Draw(false, true);
                animInstance.Draw(true, true);
            }

            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        DrawMap(Globals.MapGrid[x, y], 1);
                    }
                }
            }

            for (var y = 0; y < Options.MapHeight * 5; y++)
            {
                for (var x = 3; x < 6; x++)
                {
                    foreach (var entity in RenderingEntities[x, y])
                    {
                        entity.Draw();
                        EntitiesDrawn++;
                    }
                }
            }

            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        DrawMap(Globals.MapGrid[x, y], 2);
                    }
                }
            }

            foreach (var animInstance in animations)
            {
                animInstance.Draw(true);
            }


            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        var map = MapInstance.Get(Globals.MapGrid[x, y]);
                        if (map != null)
                        {
                            map.DrawWeather();
                            map.DrawFog();
                            map.DrawOverlayGraphic();
                            map.DrawItemNames();
                        }
                    }
                }
            }

            //Draw the players targets
            Globals.Me.DrawTargets();

            DrawOverlay();

            GenerateLightMap();
            DrawDarkness();

            for (var y = 0; y < Options.MapHeight * 5; y++)
            {
                for (var x = 0; x < 3; x++)
                {
                    foreach (var entity in RenderingEntities[x, y])
                    {
                        entity.DrawName(null);
                        if (entity.GetType() != typeof(Event))
                        {
                            entity.DrawTag();
                            entity.DrawHpBar();
                            entity.DrawCastingBar();
                        }

                        entity.DrawChatBubbles();
                    }
                }
            }

            for (var y = 0; y < Options.MapHeight * 5; y++)
            {
                for (var x = 3; x < 6; x++)
                {
                    foreach (var entity in RenderingEntities[x, y])
                    {
                        entity.DrawName(null);
                        if (entity.GetType() != typeof(Event))
                        {
                            entity.DrawTag();
                            entity.DrawHpBar();
                            entity.DrawCastingBar();
                        }

                        entity.DrawChatBubbles();
                    }
                }
            }

            //Draw action msg's
            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x < 0 ||
                        x >= Globals.MapGridWidth ||
                        y < 0 ||
                        y >= Globals.MapGridHeight ||
                        Globals.MapGrid[x, y] == Guid.Empty)
                    {
                        continue;
                    }

                    var map = MapInstance.Get(Globals.MapGrid[x, y]);
                    map?.DrawActionMsgs();
                }
            }

            foreach (var animInstance in animations)
            {
                animInstance.EndDraw();
            }
        }
        public PathfinderResult Update(long timeMs)
        {
            //TODO: Pull this out into server config :)
            var pathfindingRange = Math.Max(
                Options.MapWidth, Options.MapHeight
                ); //Search as far as 1 map out.. maximum.

            //Do lots of logic eventually leading up to an A* pathfinding run if needed.
            var returnVal = PathfinderResult.Failure;

            try
            {
                PathNode[,] mapGrid;
                SpatialAStar aStar;
                var          path = mPath;
                if (mWaitTime < timeMs)
                {
                    var currentMap = MapInstance.Get(mEntity.MapId);
                    if (currentMap != null && mTarget != null)
                    {
                        var grid  = DbInterface.GetGrid(currentMap.MapGrid);
                        var gridX = currentMap.MapGridX;
                        var gridY = currentMap.MapGridY;

                        var targetFound = false;
                        var targetX     = -1;
                        var targetY     = -1;
                        var sourceX     = Options.MapWidth + mEntity.X;
                        var sourceY     = Options.MapHeight + mEntity.Y;

                        //Loop through surrouding maps to see if our target is even around.
                        for (var x = gridX - 1; x <= gridX + 1; x++)
                        {
                            if (x == -1 || x >= grid.Width)
                            {
                                continue;
                            }

                            for (var y = gridY - 1; y <= gridY + 1; y++)
                            {
                                if (y == -1 || y >= grid.Height)
                                {
                                    continue;
                                }

                                if (grid.MyGrid[x, y] != Guid.Empty)
                                {
                                    if (grid.MyGrid[x, y] == mTarget.TargetMapId)
                                    {
                                        targetX     = (x - gridX + 1) * Options.MapWidth + mTarget.TargetX;
                                        targetY     = (y - gridY + 1) * Options.MapHeight + mTarget.TargetY;
                                        targetFound = true;
                                    }
                                }
                            }
                        }

                        if (targetFound)
                        {
                            if (AlongPath(mPath, targetX, targetY, mEntity.Passable))
                            {
                                path      = mPath;
                                returnVal = PathfinderResult.Success;
                            }
                            else
                            {
                                //See if the target is physically within range:
                                if (Math.Abs(sourceX - targetX) + Math.Abs(sourceY - targetY) < pathfindingRange)
                                {
                                    //Doing good...
                                    mapGrid = mGrid;

                                    for (var x = 0; x < Options.MapWidth * 3; x++)
                                    {
                                        for (var y = 0; y < Options.MapHeight * 3; y++)
                                        {
                                            if (mapGrid[x, y] == null)
                                            {
                                                mapGrid[x, y] = new PathNode(x, y, false);
                                            }
                                            else
                                            {
                                                mapGrid[x, y].Reset();
                                            }

                                            if (x < sourceX - pathfindingRange ||
                                                x > sourceX + pathfindingRange ||
                                                y < sourceY - pathfindingRange ||
                                                y > sourceY + pathfindingRange)
                                            {
                                                mapGrid[x, y].IsWall = true;
                                            }
                                        }
                                    }

                                    //loop through all surrounding maps.. gather blocking elements, resources, players, npcs, global events, and local events (if this is a local event)
                                    for (var x = gridX - 1; x <= gridX + 1; x++)
                                    {
                                        if (x == -1 || x >= grid.Width)
                                        {
                                            for (var y = 0; y < 3; y++)
                                            {
                                                FillArea(
                                                    mapGrid, (x + 1 - gridX) * Options.MapWidth, y * Options.MapHeight,
                                                    Options.MapWidth, Options.MapHeight
                                                    );
                                            }

                                            continue;
                                        }

                                        for (var y = gridY - 1; y <= gridY + 1; y++)
                                        {
                                            if (y == -1 || y >= grid.Height)
                                            {
                                                FillArea(
                                                    mapGrid, (x + 1 - gridX) * Options.MapWidth,
                                                    (y + 1 - gridY) * Options.MapHeight, Options.MapWidth,
                                                    Options.MapHeight
                                                    );

                                                continue;
                                            }

                                            if (grid.MyGrid[x, y] != Guid.Empty)
                                            {
                                                var tmpMap = MapInstance.Get(grid.MyGrid[x, y]);
                                                if (tmpMap != null)
                                                {
                                                    //Copy the cached array of tile blocks
                                                    var blocks = tmpMap.GetCachedBlocks(
                                                        mEntity.GetType() == typeof(Player)
                                                        );

                                                    foreach (var block in blocks)
                                                    {
                                                        mapGrid[(x + 1 - gridX) * Options.MapWidth + block.X,
                                                                (y + 1 - gridY) * Options.MapHeight + block.Y]
                                                        .IsWall = true;
                                                    }

                                                    //Block of Players, Npcs, and Resources
                                                    foreach (var en in tmpMap.GetEntities())
                                                    {
                                                        if (!en.IsPassable() && en.X > -1 && en.X < Options.MapWidth && en.Y > -1 && en.Y < Options.MapHeight)
                                                        {
                                                            mapGrid[(x + 1 - gridX) * Options.MapWidth + en.X,
                                                                    (y + 1 - gridY) * Options.MapHeight + en.Y]
                                                            .IsWall = true;
                                                        }
                                                    }

                                                    //Block Global Events if they are not passable.
                                                    foreach (var en in tmpMap.GlobalEventInstances)
                                                    {
                                                        if (en.Value != null && en.Value.X > -1 && en.Value.X < Options.MapWidth && en.Value.Y > -1 && en.Value.Y < Options.MapHeight)
                                                        {
                                                            foreach (var page in en.Value.GlobalPageInstance)
                                                            {
                                                                if (!page.Passable)
                                                                {
                                                                    mapGrid[
                                                                        (x + 1 - gridX) * Options.MapWidth +
                                                                        en.Value.X,
                                                                        (y + 1 - gridY) * Options.MapHeight +
                                                                        en.Value.Y]
                                                                    .IsWall = true;
                                                                }
                                                            }
                                                        }
                                                    }

                                                    //If this is a local event then we gotta loop through all other local events for the player
                                                    if (mEntity.GetType() == typeof(EventPageInstance))
                                                    {
                                                        var ev = (EventPageInstance)mEntity;
                                                        if (!ev.Passable && ev.Player != null)

                                                        //Make sure this is a local event
                                                        {
                                                            var player = ev.Player;
                                                            if (player != null)
                                                            {
                                                                if (player.EventLookup.Values.Count >
                                                                    Options.MapWidth * Options.MapHeight)
                                                                {
                                                                    //Find all events on this map (since events can't switch maps)
                                                                    for (var mapX = 0; mapX < Options.MapWidth; mapX++)
                                                                    {
                                                                        for (var mapY = 0;
                                                                             mapY < Options.MapHeight;
                                                                             mapY++)
                                                                        {
                                                                            var evt = player.EventExists(new MapTileLoc(
                                                                                                             ev.MapId, mapX, mapY
                                                                                                             ));

                                                                            if (evt != null)
                                                                            {
                                                                                if (evt.PageInstance != null &&
                                                                                    !evt.PageInstance.Passable &&
                                                                                    evt.PageInstance.X > -1 &&
                                                                                    evt.PageInstance.Y > -1)
                                                                                {
                                                                                    mapGrid[
                                                                                        (x + 1 - gridX) *
                                                                                        Options.MapWidth +
                                                                                        evt.X,
                                                                                        (y + 1 - gridY) *
                                                                                        Options.MapHeight +
                                                                                        evt.Y]
                                                                                    .IsWall = true;
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    var playerEvents = player.EventLookup.Values;
                                                                    foreach (var evt in playerEvents)
                                                                    {
                                                                        if (evt != null &&
                                                                            evt.PageInstance != null &&
                                                                            !evt.PageInstance.Passable &&
                                                                            evt.PageInstance.X > -1 &&
                                                                            evt.PageInstance.Y > -1)
                                                                        {
                                                                            mapGrid[
                                                                                (x + 1 - gridX) * Options.MapWidth +
                                                                                evt.PageInstance.X,
                                                                                (y + 1 - gridY) *
                                                                                Options.MapHeight +
                                                                                evt.PageInstance.Y]
                                                                            .IsWall = true;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //Optionally, move the along path check down here.. see if each tile is still open before returning success.
                                    //That would be more processor intensive but would also provide ai that recognize blocks in their path quicker.

                                    //Finally done.. let's get a path from the pathfinder.
                                    mapGrid[targetX, targetY].IsWall = false;
                                    aStar = new SpatialAStar(mapGrid);
                                    path  = aStar.Search(new Point(sourceX, sourceY), new Point(targetX, targetY), null);
                                    if (path == null)
                                    {
                                        returnVal = PathfinderResult.NoPathToTarget;
                                    }
                                    else
                                    {
                                        returnVal = PathfinderResult.Success;
                                    }
                                }
                                else
                                {
                                    returnVal = PathfinderResult.OutOfRange;
                                }
                            }
                        }
                        else
                        {
                            returnVal = PathfinderResult.OutOfRange;
                        }
                    }
                    else
                    {
                        mPath     = null;
                        returnVal = PathfinderResult.Failure;
                    }
                }
                else
                {
                    returnVal = PathfinderResult.Wait;
                }

                switch (returnVal)
                {
                case PathfinderResult.Success:
                    //Use the same path for at least a second before trying again.
                    mWaitTime         = timeMs + 200;
                    mConsecutiveFails = 0;

                    break;

                case PathfinderResult.OutOfRange:
                    //Npc might immediately find a new target. Give it a 500ms wait but make this wait grow if we keep finding targets out of range.
                    mConsecutiveFails++;
                    mWaitTime = timeMs + mConsecutiveFails * 500;

                    break;

                case PathfinderResult.NoPathToTarget:
                    //Wait 2 seconds and try again. This will move the npc randomly and might allow other npcs or players to get out of the way
                    mConsecutiveFails++;
                    mWaitTime = timeMs + 1000 + mConsecutiveFails * 500;

                    break;

                case PathfinderResult.Failure:
                    //Can try again in a second.. we don't waste much processing time on failures
                    mWaitTime         = timeMs + 500;
                    mConsecutiveFails = 0;

                    break;

                case PathfinderResult.Wait:
                    //Nothing to do here.. we are already waiting.
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                mPath = path;
            }
            catch (Exception exception)
            {
                Log.Error(exception);
            }

            return(returnVal);
        }
Пример #9
0
            public void RunThread()
            {
                while (!_shouldStop)
                {
                    IEnumerable <IGrouping <byte, Group> > groups = from grp in RegisteredGroups.GetAllItems()
                                                                    where grp.TalentArenaBattle != null
                                                                    group grp by grp.TalentArenaBattle.GroupLevel into grouping
                                                                    select grouping;

                    foreach (IGrouping <byte, Group> group in groups)
                    {
                        Group prevGroup = null;

                        foreach (Group g in group)
                        {
                            if (prevGroup == null)
                            {
                                prevGroup = g;
                            }
                            else
                            {
                                RegisteredGroups.Remove(g);
                                RegisteredGroups.Remove(prevGroup);

                                MapInstance mapInstance = ServerManager.GenerateMapInstance(2015, MapInstanceType.NormalInstance, new InstanceBag());
                                mapInstance.IsPvp = true;

                                g.TalentArenaBattle.MapInstance         = mapInstance;
                                prevGroup.TalentArenaBattle.MapInstance = mapInstance;

                                g.TalentArenaBattle.Side         = 0;
                                prevGroup.TalentArenaBattle.Side = 1;

                                g.TalentArenaBattle.Calls         = 5;
                                prevGroup.TalentArenaBattle.Calls = 5;

                                List <ClientSession> gs = g.Characters.GetAllItems().Concat(prevGroup.Characters.GetAllItems()).ToList();
                                foreach (ClientSession sess in gs)
                                {
                                    sess.SendPacket(UserInterfaceHelper.GenerateBsInfo(1, 3, -1, 2));
                                }
                                Thread.Sleep(1000);
                                foreach (ClientSession sess in gs)
                                {
                                    sess.SendPacket(UserInterfaceHelper.GenerateBsInfo(2, 3, 0, 0));
                                    sess.SendPacket(UserInterfaceHelper.GenerateTeamArenaClose());
                                }
                                Thread.Sleep(5000);
                                foreach (ClientSession sess in gs)
                                {
                                    sess.SendPacket(UserInterfaceHelper.GenerateTeamArenaMenu(0, 0, 0, 0, 0));
                                    short x = 125;
                                    if (sess.Character.Group.TalentArenaBattle.Side == 0)
                                    {
                                        x = 15;
                                    }
                                    ServerManager.Instance.ChangeMapInstance(sess.Character.CharacterId, mapInstance.MapInstanceId, x, 39);
                                    sess.SendPacketAfter(UserInterfaceHelper.GenerateTeamArenaMenu(3, 0, 0, 60, 0), 5000);
                                }

                                // TODO: Other Setup stuff

                                PlayingGroups[g.GroupId] = new List <Group> {
                                    g, prevGroup
                                };

                                BattleThread battleThread = new BattleThread();
                                Observable.Timer(TimeSpan.FromSeconds(0)).Subscribe(observer => battleThread.Run(PlayingGroups[g.GroupId]));

                                prevGroup = null;
                            }
                        }
                    }

                    Thread.Sleep(5000);
                }
            }
Пример #10
0
        public void GenerateRaid(byte type, byte faction)
        {
            Act4Guardians = new List <MapMonster>();
            ScriptedInstance raid  = ServerManager.Instance.Act4Raids.FirstOrDefault(r => r.Id == type);
            MapInstance      lobby = ServerManager.Instance.Act4Maps.FirstOrDefault(m => m.Map.MapId == 134);

            if (raid == null || lobby == null)
            {
                Logger.Log.Error(raid == null ? $"Act4 raids is missing - type : {type}" : "There is no map in Act4Maps with MapId == 134");
                return;
            }

            ServerManager.Instance.Act4RaidStart = DateTime.Now;

            lobby.CreatePortal(new Portal
            {
                SourceMapId = 134,
                SourceX     = 139,
                SourceY     = 100,
                Type        = (short)(9 + faction)
            }, 3600, true);

            #region Guardian Spawning

            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 147,
                MapY          = 88,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 149,
                MapY          = 94,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 147,
                MapY          = 101,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 139,
                MapY          = 105,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 132,
                MapY          = 101,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 129,
                MapY          = 94,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Act4Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 132,
                MapY          = 88,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = lobby.GetNextId(),
                ShouldRespawn = false,
                IsHostile     = true
            });

            foreach (MapMonster monster in Act4Guardians)
            {
                if (monster == null)
                {
                    continue;
                }

                monster.Initialize();
                lobby.AddMonster(monster);
                lobby.Broadcast(monster.GenerateIn());
            }

            Observable.Timer(TimeSpan.FromMinutes(60)).Subscribe(s =>
            {
                foreach (MapMonster monster in Act4Guardians)
                {
                    lobby.RemoveMonster(monster);
                    lobby.Broadcast(monster.GenerateOut());
                }
                Act4Guardians.Clear();
            });

            #endregion

            foreach (MapInstance map in ServerManager.Instance.Act4Maps)
            {
                map.Sessions.Where(s => s?.Character?.Faction == (FactionType)faction).ToList().ForEach(s =>
                                                                                                        s.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("ACT4_RAID_OPEN"), ((Act4RaidType)type).ToString()), 0)));
            }

            lock (ServerManager.Instance.FamilyList)
            {
                foreach (Family family in ServerManager.Instance.FamilyList.GetAllItems())
                {
                    if (family == null)
                    {
                        continue;
                    }
                    family.Act4Raid = ServerManager.Instance.Act4Raids.FirstOrDefault(r => r.Id == type)?.GetClone();
                    family.Act4Raid?.LoadScript(MapInstanceType.RaidInstance);
                    if (family.Act4Raid?.FirstMap == null)
                    {
                        continue;
                    }
                    family.Act4Raid.FirstMap.InstanceBag.Lock = true;
                }
            }

            Observable.Timer(TimeSpan.FromSeconds(3600)).Subscribe(s =>
            {
                foreach (Family family in ServerManager.Instance.FamilyList.GetAllItems())
                {
                    if (family == null)
                    {
                        continue;
                    }
                    family.Act4Raid?.MapInstanceDictionary?.Values.ToList().ForEach(m => m?.Dispose());
                    family.Act4Raid = null;
                }
            });
        }
Пример #11
0
        public override void DrawName(Color textColor, Color borderColor, Color backgroundColor)
        {
            if (HideName || Name.Trim().Length == 0)
            {
                return;
            }

            if (!WorldPos.IntersectsWith(Graphics.Renderer.GetView()))
            {
                return;
            }

            if (MapInstance.Get(CurrentMap) == null || !Globals.GridMaps.Contains(CurrentMap))
            {
                return;
            }

            var y      = (int)Math.Ceiling(GetCenterPos().Y);
            var x      = (int)Math.Ceiling(GetCenterPos().X);
            var height = Options.TileHeight;

            switch (Graphic.Type)
            {
            case EventGraphicType.Sprite:     //Sprite
                var entityTex = Globals.ContentManager.GetTexture(
                    GameContentManager.TextureType.Entity, Graphic.Filename
                    );

                if (entityTex != null)
                {
                    height = entityTex.GetHeight();
                }

                break;

            case EventGraphicType.Tileset:     //Tile
                if (mCachedTilesetName != Graphic.Filename)
                {
                    mCachedTilesetName = Graphic.Filename;
                    mCachedTileset     = Globals.ContentManager.GetTexture(
                        GameContentManager.TextureType.Tileset, Graphic.Filename
                        );
                }

                if (mCachedTileset != null)
                {
                    height = (Graphic.Height + 1) * Options.TileHeight;
                }

                break;
            }

            y = (int)GetTopPos(height) - 12;
            x = (int)Math.Ceiling(GetCenterPos().X);

            if (Graphic.Type == EventGraphicType.Tileset)
            {
                y -= 12;
            }

            var textSize = Graphics.Renderer.MeasureText(Name, Graphics.EntityNameFont, 1);

            if (CustomColors.Names.Events.Background != Color.Transparent)
            {
                Graphics.DrawGameTexture(
                    Graphics.Renderer.GetWhiteTexture(), new FloatRect(0, 0, 1, 1),
                    new FloatRect(x - textSize.X / 2f - 4, y, textSize.X + 8, textSize.Y),
                    CustomColors.Names.Events.Background
                    );
            }

            Graphics.Renderer.DrawString(
                Name, Graphics.EntityNameFont, (int)(x - (int)Math.Ceiling(textSize.X / 2f)), (int)y, 1,
                Color.FromArgb(CustomColors.Names.Events.Name.ToArgb()), true, null,
                Color.FromArgb(CustomColors.Names.Events.Outline.ToArgb())
                );
        }
Пример #12
0
        public void SpawnResourceItems(Entity killer)
        {
            //Find tile to spawn items
            var tiles = new List <TileHelper>();

            for (var x = X - 1; x <= X + 1; x++)
            {
                for (var y = Y - 1; y <= Y + 1; y++)
                {
                    var tileHelper = new TileHelper(MapId, x, y);
                    if (tileHelper.TryFix())
                    {
                        //Tile is valid.. let's see if its open
                        var map = MapInstance.Get(tileHelper.GetMapId());
                        if (map != null)
                        {
                            if (!map.TileBlocked(tileHelper.GetX(), tileHelper.GetY()))
                            {
                                tiles.Add(tileHelper);
                            }
                            else
                            {
                                if (killer.MapId == tileHelper.GetMapId() &&
                                    killer.X == tileHelper.GetX() &&
                                    killer.Y == tileHelper.GetY())
                                {
                                    tiles.Add(tileHelper);
                                }
                            }
                        }
                    }
                }
            }

            if (tiles.Count > 0)
            {
                TileHelper selectedTile = null;

                //Prefer the players tile, otherwise choose randomly
                for (var i = 0; i < tiles.Count; i++)
                {
                    if (tiles[i].GetMapId() == killer.MapId &&
                        tiles[i].GetX() == killer.X &&
                        tiles[i].GetY() == killer.Y)
                    {
                        selectedTile = tiles[i];
                    }
                }

                if (selectedTile == null)
                {
                    selectedTile = tiles[Globals.Rand.Next(0, tiles.Count)];
                }

                // Drop items
                foreach (var item in Items)
                {
                    if (ItemBase.Get(item.ItemId) != null)
                    {
                        MapInstance.Get(selectedTile.GetMapId())
                        .SpawnItem(selectedTile.GetX(), selectedTile.GetY(), item, item.Quantity);
                    }
                }
            }

            Items.Clear();
        }
Пример #13
0
        public void RunEvent(EventContainer evt, ClientSession session = null, MapMonster monster = null)
        {
            if (session != null)
            {
                evt.MapInstance = session.CurrentMapInstance;
                switch (evt.EventActionType)
                {
                    #region EventForUser

                case EventActionType.NPCDIALOG:
                    session.SendPacket(session.Character.GenerateNpcDialog((int)evt.Parameter));
                    break;

                case EventActionType.SENDPACKET:
                    session.SendPacket((string)evt.Parameter);
                    break;

                    #endregion
                }
            }
            if (evt.MapInstance != null)
            {
                switch (evt.EventActionType)
                {
                    #region EventForUser

                case EventActionType.NPCDIALOG:
                case EventActionType.SENDPACKET:
                    if (session == null)
                    {
                        evt.MapInstance.Sessions.ToList().ForEach(e =>
                        {
                            RunEvent(evt, e);
                        });
                    }
                    break;

                    #endregion

                    #region MapInstanceEvent

                case EventActionType.REGISTEREVENT:
                    Tuple <string, List <EventContainer> > even = (Tuple <string, List <EventContainer> >)evt.Parameter;
                    switch (even.Item1)
                    {
                    case "OnCharacterDiscoveringMap":
                        even.Item2.ForEach(s => evt.MapInstance.OnCharacterDiscoveringMapEvents.Add(new Tuple <EventContainer, List <long> >(s, new List <long>())));
                        break;

                    case "OnMoveOnMap":
                        evt.MapInstance.OnMoveOnMapEvents.AddRange(even.Item2);
                        break;

                    case "OnMapClean":
                        evt.MapInstance.OnMapClean.AddRange(even.Item2);
                        break;

                    case "OnLockerOpen":
                        evt.MapInstance.InstanceBag.UnlockEvents.AddRange(even.Item2);
                        break;
                    }
                    break;

                case EventActionType.REGISTERWAVE:
                    evt.MapInstance.WaveEvents.Add((EventWave)evt.Parameter);
                    break;

                case EventActionType.SETAREAENTRY:
                    ZoneEvent even2 = (ZoneEvent)evt.Parameter;
                    evt.MapInstance.OnAreaEntryEvents.Add(even2);

                    break;

                case EventActionType.REMOVEMONSTERLOCKER:
                    EventContainer evt2 = (EventContainer)evt.Parameter;
                    evt.MapInstance.InstanceBag.MonsterLocker.Current--;
                    if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 && evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                    {
                        evt.MapInstance.InstanceBag.UnlockEvents.ForEach(s => RunEvent(s));
                        evt.MapInstance.InstanceBag.UnlockEvents.RemoveAll(s => s != null);
                    }
                    break;

                case EventActionType.REMOVEBUTTONLOCKER:
                    evt2 = (EventContainer)evt.Parameter;
                    evt.MapInstance.InstanceBag.ButtonLocker.Current--;
                    if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 && evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                    {
                        evt.MapInstance.InstanceBag.UnlockEvents.ForEach(s => RunEvent(s));
                        evt.MapInstance.InstanceBag.UnlockEvents.RemoveAll(s => s != null);
                    }
                    break;

                case EventActionType.EFFECT:
                    short evt3 = (short)evt.Parameter;
                    if (monster != null && (DateTime.Now - monster.LastEffect).TotalSeconds >= 5)
                    {
                        evt.MapInstance.Broadcast(monster.GenerateEff(evt3));
                        monster.ShowEffect();
                    }
                    break;

                case EventActionType.CONTROLEMONSTERINRANGE:
                    if (monster != null)
                    {
                        Tuple <short, byte, List <EventContainer> > evnt = (Tuple <short, byte, List <EventContainer> >)evt.Parameter;
                        List <MapMonster> MapMonsters = evt.MapInstance.GetListMonsterInRange(monster.MapX, monster.MapY, evnt.Item2);
                        if (evnt.Item1 != 0)
                        {
                            MapMonsters.RemoveAll(s => s.MonsterVNum != evnt.Item1);
                        }
                        MapMonsters.ForEach(s => evnt.Item3.ForEach(e => RunEvent(e, monster: s)));
                    }
                    break;

                case EventActionType.ONTARGET:
                    if (monster.MoveEvent != null && monster.MoveEvent.InZone(monster.MapX, monster.MapY))
                    {
                        ((List <EventContainer>)evt.Parameter).ForEach(s => RunEvent(s, monster: monster));
                    }
                    break;

                case EventActionType.MOVE:
                    ZoneEvent evt4 = (ZoneEvent)evt.Parameter;
                    if (monster != null)
                    {
                        monster.FirstX    = evt4.X;
                        monster.FirstY    = evt4.Y;
                        monster.MoveEvent = evt4;
                        monster.Path      = BestFirstSearch.FindPath(new Node {
                            X = monster.MapX, Y = monster.MapY
                        }, new Node {
                            X = evt4.X, Y = evt4.Y
                        }, evt.MapInstance?.Map.Grid);
                    }
                    break;

                case EventActionType.CLOCK:
                    evt.MapInstance.InstanceBag.Clock.BasesSecondRemaining = Convert.ToInt32(evt.Parameter);
                    evt.MapInstance.InstanceBag.Clock.DeciSecondRemaining  = Convert.ToInt32(evt.Parameter);
                    break;

                case EventActionType.SETMONSTERLOCKERS:
                    evt.MapInstance.InstanceBag.MonsterLocker.Current = Convert.ToByte(evt.Parameter);
                    evt.MapInstance.InstanceBag.MonsterLocker.Initial = Convert.ToByte(evt.Parameter);
                    break;

                case EventActionType.SETBUTTONLOCKERS:
                    evt.MapInstance.InstanceBag.ButtonLocker.Current = Convert.ToByte(evt.Parameter);
                    evt.MapInstance.InstanceBag.ButtonLocker.Initial = Convert.ToByte(evt.Parameter);
                    break;

                case EventActionType.SCRIPTEND:
                    switch (evt.MapInstance.MapInstanceType)
                    {
                    case MapInstanceType.TimeSpaceInstance:
                        evt.MapInstance.InstanceBag.EndState = (byte)evt.Parameter;
                        ClientSession client = evt.MapInstance.Sessions.FirstOrDefault();
                        if (client != null)
                        {
                            Guid             MapInstanceId = ServerManager.Instance.GetBaseMapInstanceIdByMapId(client.Character.MapId);
                            MapInstance      map           = ServerManager.Instance.GetMapInstance(MapInstanceId);
                            ScriptedInstance si            = map.ScriptedInstances.FirstOrDefault(s => s.PositionX == client.Character.MapX && s.PositionY == client.Character.MapY);
                            byte             penalty       = 0;
                            if (penalty > (client.Character.Level - si.LevelMinimum) * 2)
                            {
                                penalty = penalty > 100 ? (byte)100 : penalty;
                                client.SendPacket(client.Character.GenerateSay(string.Format(Language.Instance.GetMessageFromKey("TS_PENALTY"), penalty), 10));
                            }
                            int    point      = evt.MapInstance.InstanceBag.Point * (100 - penalty) / 100;
                            string perfection = string.Empty;
                            perfection += evt.MapInstance.InstanceBag.MonstersKilled >= si.MonsterAmount ? 1 : 0;
                            perfection += evt.MapInstance.InstanceBag.NpcsKilled == 0 ? 1 : 0;
                            perfection += evt.MapInstance.InstanceBag.RoomsVisited >= si.RoomAmount ? 1 : 0;

                            evt.MapInstance.Broadcast($"score  {evt.MapInstance.InstanceBag.EndState} {point} 27 47 18 {si.DrawItems.Count()} {evt.MapInstance.InstanceBag.MonstersKilled} { si.NpcAmount - evt.MapInstance.InstanceBag.NpcsKilled} {evt.MapInstance.InstanceBag.RoomsVisited} {perfection} 1 1");
                        }
                        break;

                    case MapInstanceType.RaidInstance:
                        evt.MapInstance.InstanceBag.EndState = (byte)evt.Parameter;
                        client = evt.MapInstance.Sessions.FirstOrDefault();
                        if (client != null)
                        {
                            Group grp = client?.Character?.Group;
                            if (grp == null)
                            {
                                return;
                            }
                            if (evt.MapInstance.InstanceBag.EndState == 1)
                            {
                                foreach (ClientSession sess in grp.Characters)
                                {
                                    foreach (Gift gift in grp?.Raid?.GiftItems)
                                    {
                                        byte rare = 0;
                                        if (gift.IsRandomRare)
                                        {
                                            rare = (byte)ServerManager.Instance.RandomNumber(0, 7);
                                        }
                                        //TODO add random rarity for some object
                                        sess.Character.GiftAdd(gift.VNum, gift.Amount, rare, gift.Design);
                                    }
                                }
                                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("RAID_SUCCEED"), grp?.Raid?.Label, grp.Characters.ElementAt(0).Character.Name), 0));
                            }

                            Observable.Timer(TimeSpan.FromSeconds(evt.MapInstance.InstanceBag.EndState == 1 ? 30 : 0)).Subscribe(o =>
                            {
                                ClientSession[] grpmembers = new ClientSession[40];
                                grp.Characters.CopyTo(grpmembers);
                                foreach (ClientSession targetSession in grpmembers)
                                {
                                    if (targetSession != null)
                                    {
                                        if (targetSession.Character.Hp <= 0)
                                        {
                                            targetSession.Character.Hp = 1;
                                            targetSession.Character.Mp = 1;
                                        }
                                        targetSession.SendPacket(targetSession.Character.GenerateRaidBf(evt.MapInstance.InstanceBag.EndState));
                                        targetSession.SendPacket(targetSession.Character.GenerateRaid(1, true));
                                        targetSession.SendPacket(targetSession.Character.GenerateRaid(2, true));
                                        grp.LeaveGroup(targetSession);
                                    }
                                }
                                ServerManager.Instance.GroupList.RemoveAll(s => s.GroupId == grp.GroupId);
                                ServerManager.Instance.GroupsThreadSafe.Remove(grp.GroupId);
                                evt.MapInstance.Dispose();
                            });
                        }
                        break;
                    }
                    break;

                case EventActionType.MAPCLOCK:
                    evt.MapInstance.Clock.BasesSecondRemaining = Convert.ToInt32(evt.Parameter);
                    evt.MapInstance.Clock.DeciSecondRemaining  = Convert.ToInt32(evt.Parameter);
                    break;

                case EventActionType.STARTCLOCK:
                    Tuple <List <EventContainer>, List <EventContainer> > eve = (Tuple <List <EventContainer>, List <EventContainer> >)evt.Parameter;
                    evt.MapInstance.InstanceBag.Clock.StopEvents    = eve.Item2;
                    evt.MapInstance.InstanceBag.Clock.TimeoutEvents = eve.Item1;
                    evt.MapInstance.InstanceBag.Clock.StartClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                    break;

                case EventActionType.TELEPORT:
                    Tuple <short, short, short, short> tp = (Tuple <short, short, short, short>)evt.Parameter;
                    List <Character> characters           = evt.MapInstance.GetCharactersInRange(tp.Item1, tp.Item2, 5).ToList();
                    characters.ForEach(s =>
                    {
                        s.PositionX = tp.Item3;
                        s.PositionY = tp.Item4;
                        evt.MapInstance?.Broadcast(s.Session, s.GenerateTp(), ReceiverType.Group);
                    });
                    break;

                case EventActionType.STOPCLOCK:
                    evt.MapInstance.InstanceBag.Clock.StopClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                    break;

                case EventActionType.STARTMAPCLOCK:
                    eve = (Tuple <List <EventContainer>, List <EventContainer> >)evt.Parameter;
                    evt.MapInstance.Clock.StopEvents    = eve.Item2;
                    evt.MapInstance.Clock.TimeoutEvents = eve.Item1;
                    evt.MapInstance.Clock.StartClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                    break;

                case EventActionType.STOPMAPCLOCK:
                    evt.MapInstance.Clock.StopClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                    break;

                case EventActionType.SPAWNPORTAL:
                    evt.MapInstance.CreatePortal((Portal)evt.Parameter);
                    break;

                case EventActionType.REFRESHMAPITEMS:
                    evt.MapInstance.MapClear();
                    break;

                case EventActionType.NPCSEFFECTCHANGESTATE:
                    evt.MapInstance.Npcs.ForEach(s => s.EffectActivated = (bool)evt.Parameter);
                    break;

                case EventActionType.CHANGEPORTALTYPE:
                    Tuple <int, PortalType> param = (Tuple <int, PortalType>)evt.Parameter;
                    Portal portal = evt.MapInstance.Portals.FirstOrDefault(s => s.PortalId == param.Item1);
                    if (portal != null)
                    {
                        portal.Type = (short)param.Item2;
                    }
                    break;

                case EventActionType.CHANGEDROPRATE:
                    evt.MapInstance.DropRate = (int)evt.Parameter;
                    break;

                case EventActionType.CHANGEXPRATE:
                    evt.MapInstance.XpRate = (int)evt.Parameter;
                    break;

                case EventActionType.DISPOSEMAP:
                    evt.MapInstance.Dispose();
                    break;

                case EventActionType.SPAWNBUTTON:
                    evt.MapInstance.SpawnButton((MapButton)evt.Parameter);
                    break;

                case EventActionType.UNSPAWNMONSTERS:
                    evt.MapInstance.DespawnMonster((int)evt.Parameter);
                    break;

                case EventActionType.SPAWNMONSTERS:
                    evt.MapInstance.SummonMonsters((List <MonsterToSummon>)evt.Parameter);
                    break;

                case EventActionType.REFRESHRAIDGOAL:
                    ClientSession cl = evt.MapInstance.Sessions.FirstOrDefault();
                    if (cl?.Character != null)
                    {
                        ServerManager.Instance.Broadcast(cl, cl.Character?.Group.GeneraterRaidmbf(), ReceiverType.Group);
                        ServerManager.Instance.Broadcast(cl, UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("NEW_MISSION"), 0), ReceiverType.Group);
                    }
                    break;

                case EventActionType.SPAWNNPCS:
                    evt.MapInstance.SummonNpcs((List <NpcToSummon>)evt.Parameter);
                    break;

                case EventActionType.DROPITEMS:
                    evt.MapInstance.DropItems((List <Tuple <short, int, short, short> >)evt.Parameter);
                    break;

                case EventActionType.THROWITEMS:
                    Tuple <int, short, byte, int, int> parameters = (Tuple <int, short, byte, int, int>)evt.Parameter;
                    evt.MapInstance.ThrowItems(parameters);
                    break;

                case EventActionType.SPAWNONLASTENTRY:
                    Character lastincharacter = evt.MapInstance.Sessions.OrderByDescending(s => s.RegisterTime).FirstOrDefault()?.Character;
                    List <MonsterToSummon> summonParameters = new List <MonsterToSummon>();
                    MapCell hornSpawn = new MapCell
                    {
                        X = lastincharacter?.PositionX ?? 154,
                        Y = lastincharacter?.PositionY ?? 140
                    };
                    long hornTarget = lastincharacter?.CharacterId ?? -1;
                    summonParameters.Add(new MonsterToSummon(Convert.ToInt16(evt.Parameter), hornSpawn, hornTarget, true));
                    evt.MapInstance.SummonMonsters(summonParameters);
                    break;

                    #endregion
                }
            }
        }
Пример #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="map"></param>
 /// <param name="cellId"></param>
 public TrashCan(MapInstance map, int cellId)
     : base(map, cellId)
 {
     m_storage = new StorageInventory();
 }
Пример #15
0
 public MapIterator(Engine engine, MapInstance map) : base(engine)
 {
     _map      = map;
     _position = 0;
 }
Пример #16
0
 private void DestructInstance(MapInstance instance)
 {
     instance.Release();
     Maps[instance.MapId].Remove(instance);
 }
        public static void UpdatePlayerLight()
        {
            //Draw Light Around Player
            var map = MapInstance.Get(Globals.Me.CurrentMap);

            if (map != null)
            {
                float ecTime           = Globals.System.GetTimeMs() - sLightUpdate;
                var   valChange        = 255 * ecTime / 2000f;
                var   brightnessTarget = (byte)(map.Brightness / 100f * 255);
                if (BrightnessLevel < brightnessTarget)
                {
                    if (BrightnessLevel + valChange > brightnessTarget)
                    {
                        BrightnessLevel = brightnessTarget;
                    }
                    else
                    {
                        BrightnessLevel += valChange;
                    }
                }

                if (BrightnessLevel > brightnessTarget)
                {
                    if (BrightnessLevel - valChange < brightnessTarget)
                    {
                        BrightnessLevel = brightnessTarget;
                    }
                    else
                    {
                        BrightnessLevel -= valChange;
                    }
                }

                if (PlayerLightColor.R != map.PlayerLightColor.R ||
                    PlayerLightColor.G != map.PlayerLightColor.G ||
                    PlayerLightColor.B != map.PlayerLightColor.B)
                {
                    if (PlayerLightColor.R < map.PlayerLightColor.R)
                    {
                        if (PlayerLightColor.R + valChange > map.PlayerLightColor.R)
                        {
                            PlayerLightColor.R = map.PlayerLightColor.R;
                        }
                        else
                        {
                            PlayerLightColor.R += valChange;
                        }
                    }

                    if (PlayerLightColor.R > map.PlayerLightColor.R)
                    {
                        if (PlayerLightColor.R - valChange < map.PlayerLightColor.R)
                        {
                            PlayerLightColor.R = map.PlayerLightColor.R;
                        }
                        else
                        {
                            PlayerLightColor.R -= valChange;
                        }
                    }

                    if (PlayerLightColor.G < map.PlayerLightColor.G)
                    {
                        if (PlayerLightColor.G + valChange > map.PlayerLightColor.G)
                        {
                            PlayerLightColor.G = map.PlayerLightColor.G;
                        }
                        else
                        {
                            PlayerLightColor.G += valChange;
                        }
                    }

                    if (PlayerLightColor.G > map.PlayerLightColor.G)
                    {
                        if (PlayerLightColor.G - valChange < map.PlayerLightColor.G)
                        {
                            PlayerLightColor.G = map.PlayerLightColor.G;
                        }
                        else
                        {
                            PlayerLightColor.G -= valChange;
                        }
                    }

                    if (PlayerLightColor.B < map.PlayerLightColor.B)
                    {
                        if (PlayerLightColor.B + valChange > map.PlayerLightColor.B)
                        {
                            PlayerLightColor.B = map.PlayerLightColor.B;
                        }
                        else
                        {
                            PlayerLightColor.B += valChange;
                        }
                    }

                    if (PlayerLightColor.B > map.PlayerLightColor.B)
                    {
                        if (PlayerLightColor.B - valChange < map.PlayerLightColor.B)
                        {
                            PlayerLightColor.B = map.PlayerLightColor.B;
                        }
                        else
                        {
                            PlayerLightColor.B -= valChange;
                        }
                    }
                }

                if (sPlayerLightSize != map.PlayerLightSize)
                {
                    if (sPlayerLightSize < map.PlayerLightSize)
                    {
                        if (sPlayerLightSize + 500 * ecTime / 2000f > map.PlayerLightSize)
                        {
                            sPlayerLightSize = map.PlayerLightSize;
                        }
                        else
                        {
                            sPlayerLightSize += 500 * ecTime / 2000f;
                        }
                    }

                    if (sPlayerLightSize > map.PlayerLightSize)
                    {
                        if (sPlayerLightSize - 500 * ecTime / 2000f < map.PlayerLightSize)
                        {
                            sPlayerLightSize = map.PlayerLightSize;
                        }
                        else
                        {
                            sPlayerLightSize -= 500 * ecTime / 2000f;
                        }
                    }
                }

                if (sPlayerLightIntensity < map.PlayerLightIntensity)
                {
                    if (sPlayerLightIntensity + valChange > map.PlayerLightIntensity)
                    {
                        sPlayerLightIntensity = map.PlayerLightIntensity;
                    }
                    else
                    {
                        sPlayerLightIntensity += valChange;
                    }
                }

                if (sPlayerLightIntensity > map.AHue)
                {
                    if (sPlayerLightIntensity - valChange < map.PlayerLightIntensity)
                    {
                        sPlayerLightIntensity = map.PlayerLightIntensity;
                    }
                    else
                    {
                        sPlayerLightIntensity -= valChange;
                    }
                }

                if (sPlayerLightExpand < map.PlayerLightExpand)
                {
                    if (sPlayerLightExpand + 100f * ecTime / 2000f > map.PlayerLightExpand)
                    {
                        sPlayerLightExpand = map.PlayerLightExpand;
                    }
                    else
                    {
                        sPlayerLightExpand += 100f * ecTime / 2000f;
                    }
                }

                if (sPlayerLightExpand > map.PlayerLightExpand)
                {
                    if (sPlayerLightExpand - 100f * ecTime / 2000f < map.PlayerLightExpand)
                    {
                        sPlayerLightExpand = map.PlayerLightExpand;
                    }
                    else
                    {
                        sPlayerLightExpand -= 100f * ecTime / 2000f;
                    }
                }

                sLightUpdate = Globals.System.GetTimeMs();
            }
        }
Пример #18
0
        /// <summary>
        ///     Run Event
        /// </summary>
        /// <param name="evt">Event Container</param>
        /// <param name="session">Character Session that run the event</param>
        /// <param name="monster">Monster that run the event</param>
        public void RunEvent(EventContainer evt, ClientSession session = null, MapMonster monster = null)
        {
            if (session != null)
            {
                evt.MapInstance = session.CurrentMapInstance;
                switch (evt.EventActionType)
                {
                    #region EventForUser

                case EventActionType.NPCDIALOG:
                    session.SendPacket(session.Character.GenerateNpcDialog((int)evt.Parameter));
                    break;

                case EventActionType.SENDPACKET:
                    session.SendPacket((string)evt.Parameter);
                    break;

                    #endregion
                }
            }

            if (evt.MapInstance == null)
            {
                return;
            }

            switch (evt.EventActionType)
            {
                #region EventForUser

            case EventActionType.NPCDIALOG:
            case EventActionType.SENDPACKET:
                if (session == null)
                {
                    evt.MapInstance.Sessions.ToList().ForEach(e => { RunEvent(evt, e); });
                }

                break;

                #endregion

                #region MapInstanceEvent

            case EventActionType.REGISTEREVENT:
                Tuple <string, ConcurrentBag <EventContainer> > even =
                    (Tuple <string, ConcurrentBag <EventContainer> >)evt.Parameter;
                switch (even.Item1)
                {
                case "OnCharacterDiscoveringMap":
                    even.Item2.ToList().ForEach(s =>
                                                evt.MapInstance.OnCharacterDiscoveringMapEvents.Add(
                                                    new Tuple <EventContainer, List <long> >(s, new List <long>())));
                    break;

                case "OnMoveOnMap":
                    even.Item2.ToList().ForEach(s => evt.MapInstance.OnMoveOnMapEvents.Add(s));
                    break;

                case "OnMapClean":
                    even.Item2.ToList().ForEach(s => evt.MapInstance.OnMapClean.Add(s));
                    break;

                case "OnLockerOpen":
                    if (evt.MapInstance.MapInstanceType == MapInstanceType.RaidInstance)
                    {
                        even.Item2.ToList().ForEach(s => evt.MapInstance.UnlockEvents.Add(s));
                        break;
                    }

                    even.Item2.ToList().ForEach(s => evt.MapInstance.InstanceBag.UnlockEvents.Add(s));
                    break;
                }

                break;

            case EventActionType.REGISTERWAVE:
                evt.MapInstance.WaveEvents.Add((EventWave)evt.Parameter);
                break;

            case EventActionType.SETAREAENTRY:
                var even2 = (ZoneEvent)evt.Parameter;
                evt.MapInstance.OnAreaEntryEvents.Add(even2);
                break;

            case EventActionType.REMOVEMONSTERLOCKER:
                session = evt.MapInstance.Sessions.FirstOrDefault();
                if (evt.MapInstance.MapInstanceType == MapInstanceType.RaidInstance)
                {
                    if (evt.MapInstance.MonsterLocker.Current > 0)
                    {
                        evt.MapInstance.MonsterLocker.Current--;
                    }

                    if (evt.MapInstance.MonsterLocker.Current == 0 && evt.MapInstance.ButtonLocker.Current == 0)
                    {
                        foreach (EventContainer s in evt.MapInstance.UnlockEvents)
                        {
                            RunEvent(s);
                        }

                        evt.MapInstance.UnlockEvents.Clear();
                    }

                    evt.MapInstance.Broadcast(session?.Character?.Group?.GeneraterRaidmbf(evt.MapInstance));
                    break;
                }

                if (evt.MapInstance.InstanceBag.MonsterLocker.Current > 0)
                {
                    evt.MapInstance.InstanceBag.MonsterLocker.Current--;
                }

                if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 &&
                    evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                {
                    evt.MapInstance.InstanceBag.UnlockEvents.ToList().ForEach(s => RunEvent(s));
                    evt.MapInstance.InstanceBag.UnlockEvents.Clear();
                }

                break;

            case EventActionType.REMOVEBUTTONLOCKER:
                session = evt.MapInstance.Sessions.FirstOrDefault();
                if (evt.MapInstance.MapInstanceType == MapInstanceType.RaidInstance)
                {
                    if (evt.MapInstance.ButtonLocker.Current > 0)
                    {
                        evt.MapInstance.ButtonLocker.Current--;
                    }

                    if (evt.MapInstance.MonsterLocker.Current == 0 && evt.MapInstance.ButtonLocker.Current == 0)
                    {
                        evt.MapInstance.UnlockEvents.ToList().ForEach(s => RunEvent(s));
                        evt.MapInstance.UnlockEvents.Clear();
                    }

                    evt.MapInstance.Broadcast(session?.Character?.Group?.GeneraterRaidmbf(evt.MapInstance));
                    break;
                }

                if (evt.MapInstance.InstanceBag.ButtonLocker.Current > 0)
                {
                    evt.MapInstance.InstanceBag.ButtonLocker.Current--;
                }

                if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 &&
                    evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                {
                    evt.MapInstance.InstanceBag.UnlockEvents.ToList().ForEach(s => RunEvent(s));
                    evt.MapInstance.InstanceBag.UnlockEvents.Clear();
                }

                break;

            case EventActionType.EFFECT:
                short evt3 = (short)evt.Parameter;
                if (monster != null && (DateTime.Now - monster.LastEffect).TotalSeconds >= 5)
                {
                    evt.MapInstance.Broadcast(monster.GenerateEff(evt3));
                    monster.ShowEffect();
                }

                break;

            case EventActionType.INSTANTBATLLEREWARDS:
                RunEvent(new EventContainer(evt.MapInstance, EventActionType.SPAWNPORTAL,
                                            new Portal {
                    SourceX = 47, SourceY = 33, DestinationMapId = 1
                }));
                evt.MapInstance.Broadcast(
                    UserInterfaceHelper.Instance.GenerateMsg(
                        Language.Instance.GetMessageFromKey("INSTANTBATTLE_SUCCEEDED"), 0));
                Parallel.ForEach(evt.MapInstance.Sessions.Where(s => s.Character != null), cli =>
                {
                    cli.Character.GetReput(cli.Character.Level * 50, true);
                    cli.Character.GetGold(cli.Character.Level * 1000);
                    cli.Character.SpAdditionPoint += cli.Character.Level * 100;
                    cli.Character.SpAdditionPoint  = cli.Character.SpAdditionPoint > 1000000
                            ? 1000000
                            : cli.Character.SpAdditionPoint;
                    cli.SendPacket(cli.Character.GenerateSpPoint());
                    cli.SendPacket(cli.Character.GenerateGold());
                    cli.SendPacket(cli.Character.GenerateSay(
                                       string.Format(Language.Instance.GetMessageFromKey("WIN_SP_POINT"),
                                                     cli.Character.Level * 100), 10));
                });
                break;

            case EventActionType.CONTROLEMONSTERINRANGE:
                if (monster != null)
                {
                    Tuple <short, byte, ConcurrentBag <EventContainer> > evnt =
                        (Tuple <short, byte, ConcurrentBag <EventContainer> >)evt.Parameter;
                    List <MapMonster> mapMonsters =
                        evt.MapInstance.GetListMonsterInRange(monster.MapX, monster.MapY, evnt.Item2);
                    if (evnt.Item1 != 0)
                    {
                        mapMonsters.RemoveAll(s => s.MonsterVNum != evnt.Item1);
                    }

                    mapMonsters.ForEach(s => evnt.Item3.ToList().ForEach(e => RunEvent(e, monster: s)));
                }

                break;

            case EventActionType.ONTARGET:
                if (monster?.MoveEvent != null && monster.MoveEvent.InZone(monster.MapX, monster.MapY))
                {
                    monster.MoveEvent = null;
                    monster.Path      = null;
                    foreach (EventContainer s in (ConcurrentBag <EventContainer>)evt.Parameter)
                    {
                        RunEvent(s, monster: monster);
                    }
                }

                break;

            case EventActionType.MOVE:
                var evt4 = (ZoneEvent)evt.Parameter;
                if (monster != null)
                {
                    monster.MoveEvent = evt4;
                    monster.Path      = BestFirstSearch.FindPathJagged(new Node {
                        X = monster.MapX, Y = monster.MapY
                    },
                                                                       new Node {
                        X = evt4.X, Y = evt4.Y
                    }, evt.MapInstance?.Map.Grid);
                }

                break;

            case EventActionType.CLOCK:
                evt.MapInstance.InstanceBag.Clock.BasesSecondRemaining = Convert.ToInt32(evt.Parameter);
                evt.MapInstance.InstanceBag.Clock.DeciSecondRemaining  = Convert.ToInt32(evt.Parameter);
                break;

            case EventActionType.SETMONSTERLOCKERS:
                if (evt.MapInstance.MapInstanceType == MapInstanceType.RaidInstance)
                {
                    evt.MapInstance.MonsterLocker.Current = Convert.ToByte(evt.Parameter);
                    evt.MapInstance.MonsterLocker.Initial = Convert.ToByte(evt.Parameter);
                    break;
                }

                evt.MapInstance.InstanceBag.MonsterLocker.Current = Convert.ToByte(evt.Parameter);
                evt.MapInstance.InstanceBag.MonsterLocker.Initial = Convert.ToByte(evt.Parameter);
                break;

            case EventActionType.SETBUTTONLOCKERS:
                if (evt.MapInstance.MapInstanceType == MapInstanceType.RaidInstance)
                {
                    evt.MapInstance.ButtonLocker.Current = Convert.ToByte(evt.Parameter);
                    evt.MapInstance.ButtonLocker.Initial = Convert.ToByte(evt.Parameter);
                    break;
                }

                evt.MapInstance.InstanceBag.ButtonLocker.Current = Convert.ToByte(evt.Parameter);
                evt.MapInstance.InstanceBag.ButtonLocker.Initial = Convert.ToByte(evt.Parameter);
                break;

            case EventActionType.SCRIPTEND:
                ClientSession client = evt.MapInstance.Sessions.FirstOrDefault();
                if (client == null)
                {
                    return;
                }

                switch (evt.MapInstance.MapInstanceType)
                {
                case MapInstanceType.TimeSpaceInstance:
                    evt.MapInstance.InstanceBag.EndState = 5;
                    Guid mapInstanceId =
                        ServerManager.Instance.GetBaseMapInstanceIdByMapId(client.Character.MapId);
                    MapInstance      map = ServerManager.Instance.GetMapInstance(mapInstanceId);
                    ScriptedInstance si  = map?.ScriptedInstances?.FirstOrDefault(s =>
                                                                                  s.PositionX == client.Character.MapX && s.PositionY == client.Character.MapY);
                    if (si == null)
                    {
                        return;
                    }

                    byte penalty = (byte)(client.Character.Level - si.LevelMinimum > 50
                                ? 100
                                : (client.Character.Level - si.LevelMinimum) * 2);
                    if (penalty > 0)
                    {
                        client.SendPacket(client.Character.GenerateSay(
                                              string.Format(Language.Instance.GetMessageFromKey("TS_PENALTY"), penalty), 10));
                    }

                    int    point      = evt.MapInstance.InstanceBag.Point * (100 - penalty) / 100;
                    string perfection =
                        $"{(evt.MapInstance.InstanceBag.MonstersKilled >= si.MonsterAmount ? 1 : 0)}{(evt.MapInstance.InstanceBag.NpcsKilled == 0 ? 1 : 0)}{(evt.MapInstance.InstanceBag.RoomsVisited >= si.RoomAmount ? 1 : 0)}";
                    evt.MapInstance.Broadcast(
                        $"score  {evt.MapInstance.InstanceBag.EndState} {point} 27 47 18 {si.DrawItems.Count} {evt.MapInstance.InstanceBag.MonstersKilled} {si.NpcAmount - evt.MapInstance.InstanceBag.NpcsKilled} {evt.MapInstance.InstanceBag.RoomsVisited} {perfection} 1 1");
                    break;

                case MapInstanceType.RaidInstance:
                    evt.MapInstance.InstanceBag.EndState = (byte)evt.Parameter;

                    if (client.Character?.Family?.Act4Raid?.Maps?.FirstOrDefault(m =>
                                                                                 m != client.Character?.Family?.Act4Raid?.FirstMap) ==
                        evt.MapInstance)         // Act 4 raids
                    {
                        ScriptedInstance instance = client.Character?.Family?.Act4Raid;
                        if (instance?.FirstMap == null)
                        {
                            return;
                        }

                        Instance.RunEvent(new EventContainer(instance.FirstMap, EventActionType.REMOVEPORTAL,
                                                             instance.FirstMap.Portals.FirstOrDefault(port =>
                                                                                                      port.DestinationMapInstanceId == client.CurrentMapInstance.MapInstanceId)));
                        Instance.ScheduleEvent(TimeSpan.FromSeconds(5),
                                               new EventContainer(evt.MapInstance, EventActionType.SENDPACKET,
                                                                  UserInterfaceHelper.Instance.GenerateMsg(
                                                                      string.Format(Language.Instance.GetMessageFromKey("TELEPORTED_IN"), 10),
                                                                      0)));
                        int fxpReward = instance.Fxp * ServerManager.Instance.FamilyExpRate;
                        foreach (ClientSession cli in evt.MapInstance.Sessions)
                        {
                            if (DaoFactory.RaidLogDao.LoadByFamilyId(cli.Character.Family.FamilyId).Any(s =>
                                                                                                        s.RaidId == instance.Id && s.Time.AddHours(24) <= DateTime.Now))
                            {
                                // Raid has not been done in the last 24 hours
                                cli.Character.GenerateFamilyXp(fxpReward / evt.MapInstance.Sessions.Count());
                            }
                            else
                            {
                                // Raid has already been done in the last 24 hours
                                cli.Character.GenerateFamilyXp(
                                    fxpReward / 5 / evt.MapInstance.Sessions.Count());
                            }

                            cli.SendPacket(cli.Character.GenerateSay(
                                               string.Format(Language.Instance.GetMessageFromKey("FXP_INCREASE"),
                                                             fxpReward), 11));
                            cli.Character.IncrementQuests(QuestType.WinRaid, instance.Id);
                            if (evt.MapInstance.Sessions.Count(s => s.IpAddress.Equals(cli.IpAddress)) > 2 ||
                                instance.GiftItems == null)
                            {
                                continue;
                            }

                            foreach (Gift gift in instance.GiftItems)
                            {
                                sbyte rare = (sbyte)(gift.IsRandomRare
                                            ? ServerManager.Instance.RandomNumber()
                                            : 0);
                                if (rare > 90)
                                {
                                    rare = 7;
                                }
                                else if (rare > 80)
                                {
                                    rare = 6;
                                }
                                else
                                {
                                    rare = (sbyte)(gift.IsRandomRare
                                                ? ServerManager.Instance.RandomNumber(1, 6)
                                                : 0);
                                }

                                if (cli.Character.Level >= instance.LevelMinimum)
                                {
                                    cli.Character.GiftAdd(gift.VNum, gift.Amount, gift.Design, rare: rare);
                                }
                            }
                        }

                        LogHelper.Instance.InsertFamilyRaidLog(
                            evt.MapInstance.Sessions.FirstOrDefault(s => s.Character.Family != null).Character
                            .Family.FamilyId, instance.Id,
                            DateTime.Now);

                        Observable.Timer(TimeSpan.FromSeconds(15)).Subscribe(s =>
                        {
                            evt.MapInstance.Sessions.ToList().ForEach(cli =>
                                                                      ServerManager.Instance.ChangeMapInstance(cli.Character.CharacterId,
                                                                                                               instance.FirstMap.MapInstanceId, instance.StartX, instance.StartY));
                        });
                        return;
                    }

                    // Raids
                    Group grp = client.Character?.Group;
                    if (grp == null)
                    {
                        return;
                    }

                    if (evt.MapInstance.InstanceBag.EndState == 1 &&
                        evt.MapInstance.Monsters.Any(s => s.IsBoss && !s.IsAlive))
                    {
                        foreach (ClientSession sess in grp.Characters.Where(s =>
                                                                            s.CurrentMapInstance?.Monsters.Any(e => e.IsBoss) == true))
                        {
                            // TODO REMOTE THAT FOR PUBLIC RELEASE
                            if (grp.Characters.Count(s => s.IpAddress.Equals(sess.IpAddress)) > 2 ||
                                grp.Raid?.GiftItems == null)
                            {
                                continue;
                            }

                            if (grp.Raid.Reputation > 0 && sess.Character.Level > grp.Raid.LevelMinimum)
                            {
                                sess.Character.GetReput(grp.Raid.Reputation, true);
                            }

                            sess.Character.Dignity =
                                sess.Character.Dignity < 0 ? sess.Character.Dignity + 100 : 100;

                            if (sess.Character.Level > grp.Raid.LevelMaximum)
                            {
                                sess.Character.GiftAdd(2320, 1);         // RAID CERTIFICATE
                                continue;
                            }

                            if (grp.Raid?.GiftItems == null)
                            {
                                continue;
                            }

                            foreach (Gift gift in grp.Raid.GiftItems)
                            {
                                sbyte rare;
                                if (gift.IsHeroic)
                                {
                                    rare = (sbyte)(gift.IsRandomRare ? ServerManager.Instance.RandomNumber(-2, 9) : 0);
                                }
                                else
                                {
                                    rare = (sbyte)(gift.IsRandomRare ? ServerManager.Instance.RandomNumber(-2, 8) : 0);
                                }

                                if (sess.Character.Level >= grp.Raid.LevelMinimum)
                                {
                                    sess.Character.GiftAdd(gift.VNum, gift.Amount, gift.Design, rare: rare);
                                }
                            }

                            if (DaoFactory.RaidLogDao.LoadByCharacterId(sess.Character.CharacterId).Any(s =>
                                                                                                        s.RaidId == grp.Raid.Id && s.Time.AddHours(24) >= DateTime.Now) ||
                                sess.Character.Family == null)
                            {
                                continue;
                            }

                            int fxpReward = grp.Raid.Fxp * ServerManager.Instance.FamilyExpRate;
                            LogHelper.Instance.InsertRaidLog(sess.Character.CharacterId, grp.Raid.Id,
                                                             DateTime.Now);
                            sess.Character.GenerateFamilyXp(fxpReward);
                            sess.SendPacket(sess.Character.GenerateSay(
                                                string.Format(Language.Instance.GetMessageFromKey("FXP_INCREASE"),
                                                              fxpReward), 11));
                        }

                        // Remove monster when raid is over
                        evt.MapInstance.Monsters.Where(s => !s.IsBoss).ToList()
                        .ForEach(m => evt.MapInstance.DespawnMonster(m));
                        evt.MapInstance.WaveEvents.Clear();

                        ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(
                                                             string.Format(Language.Instance.GetMessageFromKey("RAID_SUCCEED"), grp.Raid?.Label,
                                                                           grp.Characters.ElementAt(0).Character.Name), 0));
                    }

                    Observable.Timer(TimeSpan.FromSeconds(evt.MapInstance.InstanceBag.EndState == 1 ? 30 : 0))
                    .Subscribe(obj =>
                    {
                        ClientSession[] grpmembers = new ClientSession[40];
                        grp.Characters.ToList().CopyTo(grpmembers);
                        foreach (ClientSession targetSession in grpmembers)
                        {
                            if (targetSession == null)
                            {
                                continue;
                            }

                            if (targetSession.Character.Hp <= 0)
                            {
                                targetSession.Character.Hp = 1;
                                targetSession.Character.Mp = 1;
                            }

                            targetSession.SendPacket(
                                targetSession.Character.GenerateRaidBf(evt.MapInstance.InstanceBag
                                                                       .EndState));
                            targetSession.SendPacket(targetSession.Character.GenerateRaid(1, true));
                            targetSession.SendPacket(targetSession.Character.GenerateRaid(2, true));
                            grp.LeaveGroup(targetSession);
                        }

                        ServerManager.Instance.GroupList.RemoveAll(s => s.GroupId == grp.GroupId);
                        ServerManager.Instance._groups.TryRemove(grp.GroupId, out Group _);
                        grp?.Raid?.MapInstanceDictionary?.Values?.ToList().ForEach(m => m?.Dispose());
                    });
                    break;

                case MapInstanceType.CaligorInstance:
                    FactionType winningFaction = Caligor.AngelDamage > Caligor.DemonDamage
                                ? FactionType.Angel
                                : FactionType.Demon;

                    foreach (ClientSession player in evt.MapInstance.Sessions)
                    {
                        if (player == null)
                        {
                            continue;
                        }

                        if (Caligor.RaidTime > 2400)
                        {
                            player.Character.GiftAdd(
                                player.Character.Faction == winningFaction ? (short)5960 : (short)5961, 1);
                        }
                        else
                        {
                            player.Character.GiftAdd(
                                player.Character.Faction == winningFaction ? (short)5961 : (short)5958, 1);
                        }

                        player.Character.GiftAdd(5959, 1);
                        player.Character.GenerateFamilyXp(500 * ServerManager.Instance.FamilyExpRate);
                    }

                    break;
                }

                break;

            case EventActionType.MAPCLOCK:
                evt.MapInstance.Clock.BasesSecondRemaining = Convert.ToInt32(evt.Parameter);
                evt.MapInstance.Clock.DeciSecondRemaining  = Convert.ToInt32(evt.Parameter);
                break;

            case EventActionType.STARTCLOCK:
                Tuple <ConcurrentBag <EventContainer>, ConcurrentBag <EventContainer> > eve =
                    (Tuple <ConcurrentBag <EventContainer>, ConcurrentBag <EventContainer> >)evt.Parameter;
                if (eve != null)
                {
                    evt.MapInstance.InstanceBag.Clock.StopEvents    = eve.Item2.ToList();
                    evt.MapInstance.InstanceBag.Clock.TimeoutEvents = eve.Item1.ToList();
                    evt.MapInstance.InstanceBag.Clock.StartClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                }

                break;

            case EventActionType.TELEPORT:
                Tuple <short, short, short, short> tp = (Tuple <short, short, short, short>)evt.Parameter;
                List <Character> characters           = evt.MapInstance.GetCharactersInRange(tp.Item1, tp.Item2, 5).ToList();
                characters.ForEach(s =>
                {
                    s.PositionX = tp.Item3;
                    s.PositionY = tp.Item4;
                    evt.MapInstance?.Broadcast(s.Session, s.GenerateTp(), ReceiverType.Group);
                });
                break;

            case EventActionType.STOPCLOCK:
                evt.MapInstance.InstanceBag.Clock.StopClock();
                evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                break;

            case EventActionType.STARTMAPCLOCK:
                eve = (Tuple <ConcurrentBag <EventContainer>, ConcurrentBag <EventContainer> >)evt.Parameter;
                if (eve != null)
                {
                    evt.MapInstance.Clock.StopEvents    = eve.Item2.ToList();
                    evt.MapInstance.Clock.TimeoutEvents = eve.Item1.ToList();
                    evt.MapInstance.Clock.StartClock();
                    evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                }

                break;

            case EventActionType.STOPMAPCLOCK:
                evt.MapInstance.Clock.StopClock();
                evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                break;

            case EventActionType.SPAWNPORTAL:
                evt.MapInstance.CreatePortal((Portal)evt.Parameter);
                break;

            case EventActionType.REFRESHMAPITEMS:
                evt.MapInstance.MapClear();
                break;

            case EventActionType.NPCSEFFECTCHANGESTATE:
                evt.MapInstance.Npcs.ForEach(s => s.EffectActivated = (bool)evt.Parameter);
                break;

            case EventActionType.CHANGEPORTALTYPE:
                Tuple <int, PortalType> param = (Tuple <int, PortalType>)evt.Parameter;
                Portal portal = evt.MapInstance.Portals.FirstOrDefault(s => s.PortalId == param.Item1);
                if (portal != null)
                {
                    portal.Type = (short)param.Item2;
                }

                break;

            case EventActionType.CHANGEDROPRATE:
                evt.MapInstance.DropRate = (int)evt.Parameter;
                break;

            case EventActionType.CHANGEXPRATE:
                evt.MapInstance.XpRate = (int)evt.Parameter;
                break;

            case EventActionType.DISPOSEMAP:
                evt.MapInstance.Dispose();
                break;

            case EventActionType.SPAWNBUTTON:
                evt.MapInstance.SpawnButton((MapButton)evt.Parameter);
                break;

            case EventActionType.UNSPAWNMONSTERS:
                evt.MapInstance.DespawnMonster((int)evt.Parameter);
                break;

            case EventActionType.SPAWNMONSTERS:
                evt.MapInstance.SummonMonsters(((ConcurrentBag <ToSummon>)evt.Parameter).ToList());
                break;

            case EventActionType.REFRESHRAIDGOAL:
                ClientSession cl = evt.MapInstance.Sessions.FirstOrDefault();
                if (cl?.Character != null)
                {
                    evt.MapInstance.Broadcast(cl.Character?.Group?.GeneraterRaidmbf(evt.MapInstance));
                    ServerManager.Instance.Broadcast(cl,
                                                     UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("NEW_MISSION"),
                                                                                              0), ReceiverType.Group);
                }

                break;

            case EventActionType.SPAWNNPCS:
                evt.MapInstance.SummonNpcs((List <ToSummon>)evt.Parameter);
                break;

            case EventActionType.DROPITEMS:
                evt.MapInstance.DropItems((List <Tuple <short, int, short, short> >)evt.Parameter);
                break;

            case EventActionType.THROWITEMS:
                Tuple <int, short, byte, int, int> parameters = (Tuple <int, short, byte, int, int>)evt.Parameter;
                if (monster != null)
                {
                    parameters = new Tuple <int, short, byte, int, int>(monster.MapMonsterId, parameters.Item2,
                                                                        parameters.Item3, parameters.Item4, parameters.Item5);
                }

                evt.MapInstance.ThrowItems(parameters);
                break;

            case EventActionType.SPAWNONLASTENTRY:
                Character lastincharacter = evt.MapInstance.Sessions.OrderByDescending(s => s.RegisterTime)
                                            .FirstOrDefault()?.Character;
                List <ToSummon> summonParameters = new List <ToSummon>();
                var             hornSpawn        = new MapCell
                {
                    X = lastincharacter?.PositionX ?? 154,
                    Y = lastincharacter?.PositionY ?? 140
                };
                summonParameters.Add(new ToSummon(Convert.ToInt16(evt.Parameter), hornSpawn, lastincharacter,
                                                  true));
                evt.MapInstance.SummonMonsters(summonParameters);
                break;

            case EventActionType.REMOVEPORTAL:
                Portal portalToRemove = null;
                lock (evt.MapInstance.Portals)
                {
                    portalToRemove = evt.Parameter is Portal p
                            ? evt.MapInstance.Portals.FirstOrDefault(s => s == p)
                            : evt.MapInstance.Portals.FirstOrDefault(s => s.PortalId == (int)evt.Parameter);
                }
                if (portalToRemove == null)
                {
                    return;
                }

                evt.MapInstance.Portals.Remove(portalToRemove);
                evt.MapInstance.MapClear();
                break;

            case EventActionType.ACT4RAIDEND:
                // tp // tp X // tp Y
                Tuple <MapInstance, short, short> endParameters = (Tuple <MapInstance, short, short>)evt.Parameter;
                Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(a =>
                {
                    evt.MapInstance.Broadcast(
                        $"{UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("TELEPORTED_IN"), 10), 0)}");

                    Observable.Timer(TimeSpan.FromSeconds(10)).Subscribe(s =>
                    {
                        evt.MapInstance.Sessions.ToList().ForEach(cli =>
                                                                  ServerManager.Instance.ChangeMapInstance(cli.Character.CharacterId,
                                                                                                           endParameters.Item1.MapInstanceId, endParameters.Item2, endParameters.Item3));
                    });
                });
                break;

            case EventActionType.CLEARMAPMONSTERS:
                evt.MapInstance.Monsters.ForEach(m => evt.MapInstance.DespawnMonster(m));
                break;

            case EventActionType.STARTACT4RAID:
                Tuple <byte, byte> raidParameters = (Tuple <byte, byte>)evt.Parameter;
                PercentBar         stat           = raidParameters.Item2 == (byte)FactionType.Angel
                        ? ServerManager.Instance.Act4AngelStat
                        : ServerManager.Instance.Act4DemonStat;
                stat.Mode      = 3;
                stat.TotalTime = 3600;
                Act4Raid.Instance.GenerateRaid(raidParameters.Item1, raidParameters.Item2);
                switch ((Act4RaidType)raidParameters.Item1)
                {
                case Act4RaidType.Morcos:
                    stat.IsMorcos = true;
                    break;

                case Act4RaidType.Hatus:
                    stat.IsHatus = true;
                    break;

                case Act4RaidType.Calvina:
                    stat.IsCalvina = true;
                    break;

                case Act4RaidType.Berios:
                    stat.IsBerios = true;
                    break;
                }

                break;

            case EventActionType.ONTIMEELAPSED:
                Tuple <int, ConcurrentBag <EventContainer> > timeElapsedEvts =
                    (Tuple <int, ConcurrentBag <EventContainer> >)evt.Parameter;
                Observable.Timer(TimeSpan.FromSeconds(timeElapsedEvts.Item1)).Subscribe(e => { timeElapsedEvts.Item2.ToList().ForEach(ev => RunEvent(ev)); });
                break;

                #endregion
            }
        }
Пример #19
0
        public override HashSet <Entity> DetermineRenderOrder(HashSet <Entity> renderList, MapInstance map)
        {
            if (RenderLevel == 1)
            {
                return(base.DetermineRenderOrder(renderList, map));
            }

            renderList?.Remove(this);
            if (map == null || Globals.Me == null || Globals.Me.MapInstance == null)
            {
                return(null);
            }

            var gridX = Globals.Me.MapInstance.MapGridX;
            var gridY = Globals.Me.MapInstance.MapGridY;

            for (var x = gridX - 1; x <= gridX + 1; x++)
            {
                for (var y = gridY - 1; y <= gridY + 1; y++)
                {
                    if (x >= 0 &&
                        x < Globals.MapGridWidth &&
                        y >= 0 &&
                        y < Globals.MapGridHeight &&
                        Globals.MapGrid[x, y] != Guid.Empty)
                    {
                        if (Globals.MapGrid[x, y] == CurrentMap)
                        {
                            if (RenderLevel == 0)
                            {
                                y--;
                            }

                            if (RenderLevel == 2)
                            {
                                y++;
                            }

                            var priority = mRenderPriority;
                            if (Z != 0)
                            {
                                priority += 3;
                            }

                            HashSet <Entity> renderSet = null;

                            if (y == gridY - 2)
                            {
                                renderSet = Graphics.RenderingEntities[priority, Y];
                            }
                            else if (y == gridY - 1)
                            {
                                renderSet = Graphics.RenderingEntities[priority, Options.MapHeight + Y];
                            }
                            else if (y == gridY)
                            {
                                renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 2 + Y];
                            }
                            else if (y == gridY + 1)
                            {
                                renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 3 + Y];
                            }
                            else if (y == gridY + 2)
                            {
                                renderSet = Graphics.RenderingEntities[priority, Options.MapHeight * 4 + Y];
                            }

                            renderSet?.Add(this);
                            renderList = renderSet;

                            return(renderList);
                        }
                    }
                }
            }

            return(renderList);
        }
Пример #20
0
        internal static void GenerateTalentArena()
        {
            long        groupid = 0;
            int         seconds = 0;
            IDisposable obs     = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(start2 =>
            {
                ServerManager.Instance.ArenaMembers.Where(s => s.ArenaType == EventType.TALENTARENA).ToList().ForEach(s =>
                {
                    s.Time -= 1;
                    List <long> groupids = new List <long>();
                    ServerManager.Instance.ArenaMembers.Where(o => o.GroupId != null).ToList().ForEach(o =>
                    {
                        if (ServerManager.Instance.ArenaMembers.Count(g => g.GroupId == o.GroupId) != 3)
                        {
                            return;
                        }
                        if (o.GroupId != null)
                        {
                            groupids.Add(o.GroupId.Value);
                        }
                    });

                    if (s.Time > 0)
                    {
                        if (s.GroupId == null)
                        {
                            List <ArenaMember> members = ServerManager.Instance.ArenaMembers
                                                         .Where(e => e.Session != s.Session && e.ArenaType == EventType.TALENTARENA && e.Session.Character.Level <= s.Session.Character.Level + 5 &&
                                                                e.Session.Character.Level >= s.Session.Character.Level - 5).ToList();
                            members.RemoveAll(o => o.GroupId != null && groupids.Contains(o.GroupId.Value));
                            ArenaMember member = members.FirstOrDefault();
                            if (member == null)
                            {
                                return;
                            }
                            {
                                if (member.GroupId == null)
                                {
                                    groupid++;
                                    member.GroupId = groupid;
                                }
                                s.GroupId = member.GroupId;
                                ServerManager.Instance.ArenaMembers.Where(e => e.ArenaType == EventType.TALENTARENA && e.GroupId == member.GroupId).ToList().ForEach(o =>
                                {
                                    o.Session.SendPacket(o.Session.Character.GenerateBsInfo(1, 2, -1, 6));
                                    o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("ARENA_TEAM_FOUND"), 10));
                                    Observable.Timer(TimeSpan.FromSeconds(1)).Subscribe(time =>
                                    {
                                        s.Time = 300;
                                        if (ServerManager.Instance.ArenaMembers.Count(g => g.GroupId == s.GroupId) < 3)
                                        {
                                            o.Session.SendPacket(o.Session.Character.GenerateBsInfo(0, 2, s.Time, 8));
                                            o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SEARCH_ARENA_TEAM"), 10));
                                        }
                                        else
                                        {
                                            o.Session.SendPacket(o.Session.Character.GenerateBsInfo(0, 2, s.Time, 1));
                                            o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SEARCH_RIVAL_ARENA_TEAM"), 10));
                                        }
                                    });
                                });
                            }
                        }
                        else
                        {
                            if (ServerManager.Instance.ArenaMembers.Count(g => g.GroupId == s.GroupId) != 3)
                            {
                                return;
                            }
                            ArenaMember member =
                                ServerManager.Instance.ArenaMembers.FirstOrDefault(o => o.GroupId != null && o.GroupId != s.GroupId && groupids.Contains(o.GroupId.Value) &&
                                                                                   o.Session.Character.Level <= s.Session.Character.Level + 5 &&
                                                                                   o.Session.Character.Level >= s.Session.Character.Level - 5);
                            if (member == null)
                            {
                                return;
                            }

                            MapInstance map = ServerManager.Instance.GenerateMapInstance(2015, MapInstanceType.TalentArenaMapInstance, new InstanceBag());
                            ConcurrentBag <ArenaTeamMember> arenaTeam = new ConcurrentBag <ArenaTeamMember>();
                            ServerManager.Instance.ArenaTeams.Add(arenaTeam);

                            ArenaMember[] arenamembers = ServerManager.Instance.ArenaMembers.Where(o => o.GroupId == member.GroupId || o.GroupId == s.GroupId).OrderBy(o => o.GroupId)
                                                         .ToArray();
                            for (int i = 0; i < 6; i++)
                            {
                                ItemInstance item = Inventory.InstantiateItemInstance((short)(4433 + (i > 2 ? 5 - i : i)), member.Session.Character.CharacterId);
                                item.Design       = (short)(4433 + (i > 2 ? 5 - i : i));
                                map.MapDesignObjects.Add(new MapDesignObject
                                {
                                    ItemInstance   = item,
                                    ItemInstanceId = item.Id,
                                    CharacterId    = member.Session.Character.CharacterId,
                                    MapX           = (short)(i > 2 ? 120 : 19),
                                    MapY           = (short)(i > 2 ? 35 + i % 3 * 4 : 36 + i % 3 * 4)
                                });
                            }
                            map.InstanceBag.Clock.BasesSecondRemaining = 60;
                            map.InstanceBag.Clock.DeciSecondRemaining  = 600;
                            map.InstanceBag.Clock.StartClock();
                            IDisposable obs4 = null;
                            IDisposable obs2 = null;
                            IDisposable obs3 = null;
                            IDisposable obs6 = null;
                            Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(time2 =>
                            {
                                obs3 = Observable.Interval(TimeSpan.FromSeconds(5)).Subscribe(effect =>
                                {
                                    arenamembers.ToList().ForEach(o => map.Broadcast(o.Session.Character.GenerateEff(o.GroupId == s.GroupId ? 3012 : 3013)));
                                });
                            });
                            IDisposable obs5 = Observable.Interval(TimeSpan.FromMilliseconds(500)).Subscribe(start3 =>
                            {
                                map.Broadcast(arenamembers.FirstOrDefault(o => o.Session != null)?.Session.Character.GenerateTaPs());
                                List <ArenaTeamMember> erenia = arenaTeam.Where(team => team.ArenaTeamType == ArenaTeamType.ERENIA).ToList();
                                List <ArenaTeamMember> zenas  = arenaTeam.Where(team => team.ArenaTeamType == ArenaTeamType.ZENAS).ToList();
                                BuffTeam(erenia);
                                BuffTeam(zenas);
                            });
                            arenamembers.ToList().ForEach(o =>
                            {
                                o.Session.SendPacket(o.Session.Character.GenerateBsInfo(0, 2, s.Time, 2));
                                o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("RIVAL_ARENA_TEAM_FOUND"), 10));

                                Observable.Timer(TimeSpan.FromSeconds(1)).Subscribe(time =>
                                {
                                    o.Session.SendPacket("ta_close");
                                    Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(time2 =>
                                    {
                                        o.Session.Character.Mates.Where(m => m.IsTeamMember).ToList().ForEach(m => m.IsTeamMember = false);
                                        o.Session.Character.GeneralLogs.Add(new GeneralLogDTO
                                        {
                                            AccountId   = o.Session.Account.AccountId,
                                            CharacterId = o.Session.Character.CharacterId,
                                            IpAddress   = o.Session.IpAddress,
                                            LogData     = "Entry",
                                            LogType     = "TalentArena",
                                            Timestamp   = DateTime.Now
                                        });
                                        List <BuffType> bufftodisable = new List <BuffType> {
                                            BuffType.Bad, BuffType.Good, BuffType.Neutral
                                        };
                                        o.Session.Character.DisableBuffs(bufftodisable);
                                        int i = Array.IndexOf(arenamembers, o) + 1;
                                        o.Session.Character.Hp = (int)o.Session.Character.HPLoad();
                                        o.Session.Character.Mp = (int)o.Session.Character.MPLoad();
                                        ServerManager.Instance.ChangeMapInstance(o.Session.Character.CharacterId, map.MapInstanceId, o.GroupId == member.GroupId ? 125 : 14,
                                                                                 (o.GroupId == member.GroupId ? 37 : 38) + i % 3 * 2);
                                        o.Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("SELECT_ORDER_ARENA_TIME"), 0));
                                        o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SELECT_ORDER_ARENA_TIME"), 10));
                                        o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SELECT_ORDER_ARENA"), 10));
                                        o.Session.SendPacket(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("SELECT_ORDER_ARENA"), 0));
                                        o.Session.SendPacket(o.Session.Character.GenerateTaM(0));
                                        o.Session.SendPacket("ta_sv 0");
                                        o.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Watch));
                                        o.Session.SendPacket(o.Session.Character.GenerateTaM(3));


                                        o.Session.SendPacket(o.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey(o.GroupId == s.GroupId ? "ZENAS" : "ERENIA"), 10));
                                        arenaTeam.Add(new ArenaTeamMember(o.Session, o.GroupId == s.GroupId ? ArenaTeamType.ZENAS : ArenaTeamType.ERENIA, null));
                                        o.Session.SendPacket(o.Session.Character.GenerateTaP(0, false));

                                        obs2 = Observable.Interval(TimeSpan.FromMilliseconds(100)).Subscribe(start3 =>
                                        {
                                            bool resettap = false;
                                            map.MapDesignObjects.ToList().ForEach(e =>
                                            {
                                                if (e.ItemInstance.Design >= 4433 && e.ItemInstance.Design <= 4435)
                                                {
                                                    Character chara = map.GetCharactersInRange(e.MapX, e.MapY, 0).FirstOrDefault();
                                                    if (chara != null)
                                                    {
                                                        resettap = true;
                                                        ArenaTeamMember teammember = arenaTeam.FirstOrDefault(at => at.Session == chara.Session);
                                                        if (teammember != null &&
                                                            !arenaTeam.Any(at => at.Order == (e.ItemInstance.ItemVNum - 4433) &&
                                                                           at.ArenaTeamType == (e.MapX == 120 ? ArenaTeamType.ERENIA : ArenaTeamType.ZENAS)))
                                                        {
                                                            if (teammember.Order != null)
                                                            {
                                                                MapDesignObject obj =
                                                                    map.MapDesignObjects.FirstOrDefault(mapobj => mapobj.ItemInstance.ItemVNum == e.ItemInstance.ItemVNum &&
                                                                                                        e.MapX == (teammember.ArenaTeamType == ArenaTeamType.ERENIA ? 120 : 19));
                                                                if (obj != null)
                                                                {
                                                                    obj.ItemInstance.Design = obj.ItemInstance.ItemVNum;
                                                                }
                                                            }
                                                            teammember.Order = (byte)(e.ItemInstance.ItemVNum - 4433);
                                                        }
                                                    }
                                                }
                                                else if (e.ItemInstance.Design == 4436)
                                                {
                                                    if (!map.GetCharactersInRange(e.MapX, e.MapY, 0).Any())
                                                    {
                                                        resettap = true;
                                                        ArenaTeamMember teammember = arenaTeam.FirstOrDefault(at =>
                                                                                                              at.Order == (e.ItemInstance.ItemVNum - 4433) && at.ArenaTeamType == (e.MapX == 120 ? ArenaTeamType.ERENIA : ArenaTeamType.ZENAS));
                                                        if (teammember != null)
                                                        {
                                                            teammember.Order = null;
                                                        }
                                                    }
                                                }
                                                if (!arenaTeam.Any(at => at.Order == (e.ItemInstance.ItemVNum - 4433) && at.ArenaTeamType == (e.MapX == 120 ? ArenaTeamType.ERENIA : ArenaTeamType.ZENAS)))
                                                {
                                                    if (e.ItemInstance.Design != 4436)
                                                    {
                                                        return;
                                                    }
                                                    e.ItemInstance.Design = e.ItemInstance.ItemVNum;
                                                    map.Broadcast(e.GenerateEffect(false));
                                                }
                                                else if (e.ItemInstance.Design != 4436)
                                                {
                                                    e.ItemInstance.Design = 4436;
                                                    map.Broadcast(e.GenerateEffect(false));
                                                }
                                            });

                                            if (resettap)
                                            {
                                                arenaTeam.ToList().ForEach(arenauser => { arenauser.Session.SendPacket(arenauser.Session.Character.GenerateTaP(2, false)); });
                                            }
                                        });

                                        Observable.Timer(TimeSpan.FromSeconds(map.InstanceBag.Clock.BasesSecondRemaining)).Subscribe(start =>
                                        {
                                            obs2.Dispose();
                                            arenaTeam.ToList().ForEach(arenauser =>
                                            {
                                                if (arenauser.Order == null)
                                                {
                                                    for (byte x = 0; x < 3; x++)
                                                    {
                                                        if (!arenaTeam.Any(at => at.ArenaTeamType == arenauser.ArenaTeamType && at.Order == x))
                                                        {
                                                            arenauser.Order = x;
                                                        }
                                                    }
                                                }
                                                arenauser.Session.SendPacket($"ta_pn {arenauser.Order + 1}");
                                                arenauser.Session.SendPacket(arenauser.Session.Character.GenerateTaP(2, true));
                                            });
                                            map.MapDesignObjects.ToList().ForEach(md => map.Broadcast(md.GenerateEffect(true)));
                                            map.MapDesignObjects.Clear();
                                        });
                                    });
                                });
                            });
                            Observable.Timer(TimeSpan.FromSeconds(map.InstanceBag.Clock.BasesSecondRemaining)).Subscribe(start =>
                            {
                                bool newround1   = true;
                                bool newround2   = true;
                                int count1       = 0;
                                int count2       = 0;
                                IDisposable obs7 = obs4;
                                obs4             = Observable.Interval(TimeSpan.FromMilliseconds(500)).Subscribe(start3 =>
                                {
                                    int ereniacount = arenaTeam.Count(at => at.Dead && at.ArenaTeamType == ArenaTeamType.ERENIA);
                                    int zenascount  = arenaTeam.Count(at => at.Dead && at.ArenaTeamType == ArenaTeamType.ZENAS);
                                    if (count1 != ereniacount || count2 != zenascount)
                                    {
                                        if (count1 != ereniacount)
                                        {
                                            newround1 = true;
                                        }
                                        if (count2 != zenascount)
                                        {
                                            newround2 = true;
                                        }
                                        count1 = ereniacount;
                                        count2 = zenascount;
                                    }

                                    ArenaTeamMember tm  = arenaTeam.OrderBy(tm3 => tm3.Order).FirstOrDefault(tm3 => tm3.ArenaTeamType == ArenaTeamType.ERENIA && !tm3.Dead);
                                    ArenaTeamMember tm2 = arenaTeam.OrderBy(tm3 => tm3.Order).FirstOrDefault(tm3 => tm3.ArenaTeamType == ArenaTeamType.ZENAS && !tm3.Dead);

                                    if (!newround1 && !newround2)
                                    {
                                        return;
                                    }
                                    map.InstanceBag.Clock.BasesSecondRemaining = 300;
                                    map.InstanceBag.Clock.DeciSecondRemaining  = 3000;
                                    arenaTeam.ToList().ForEach(friends =>
                                    {
                                        friends.Session.SendPacket(friends.Session.Character.GenerateTaM(2));
                                        friends.Session.SendPacket(friends.Session.Character.GenerateTaM(3));
                                    });
                                    map.Sessions.Except(arenaTeam.Select(ss => ss.Session)).ToList().ForEach(o =>
                                    {
                                        o.SendPacket(tm2?.Session.Character.GenerateTaM(2));
                                        o.SendPacket(tm2?.Session.Character.GenerateTaM(3));
                                    });

                                    obs6?.Dispose();
                                    obs6 = Observable.Timer(TimeSpan.FromSeconds(map.InstanceBag.Clock.BasesSecondRemaining)).Subscribe(start4 =>
                                    {
                                        if (tm2 != null && tm != null)
                                        {
                                            tm.Dead  = true;
                                            tm2.Dead = true;
                                            tm.Session.Character.PositionX  = 120;
                                            tm.Session.Character.PositionY  = 39;
                                            tm2.Session.Character.PositionX = 19;
                                            tm2.Session.Character.PositionY = 40;
                                            map.Broadcast(tm2.Session, tm.Session.Character.GenerateTp());
                                            map.Broadcast(tm2.Session, tm2.Session.Character.GenerateTp());
                                            tm.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Watch));
                                            tm2.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Watch));
                                            arenaTeam.Where(friends => friends.ArenaTeamType == tm.ArenaTeamType).ToList().ForEach(friends =>
                                            {
                                                friends.Session.SendPacket(friends.Session.Character.GenerateTaFc(0));
                                            });
                                        }
                                        newround1 = true;
                                        newround2 = true;
                                        arenaTeam.ToList().ForEach(arenauser => { arenauser.Session.SendPacket(arenauser.Session.Character.GenerateTaP(2, true)); });
                                    });

                                    if (tm != null && tm2 != null)
                                    {
                                        map.IsPVP = false;
                                        arenaTeam.Where(at => at.LastSummoned != null).ToList().ForEach(at =>
                                        {
                                            at.LastSummoned = null;
                                            at.Session.Character.PositionX = at.ArenaTeamType == ArenaTeamType.ERENIA ? (short)120 : (short)19;
                                            at.Session.Character.PositionY = at.ArenaTeamType == ArenaTeamType.ERENIA ? (short)39 : (short)40;
                                            at.Session.CurrentMapInstance.Broadcast(at.Session.Character.GenerateTp());
                                            at.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Watch));
                                        });
                                        if (newround1)
                                        {
                                            map.Broadcast(tm.Session.Character.GenerateTaFc(1));
                                            tm.Session.Character.PositionX = 87;
                                            tm.Session.Character.PositionY = 39;
                                            map.Broadcast(tm.Session, tm.Session.Character.GenerateTp());
                                        }

                                        if (newround2)
                                        {
                                            tm2.Session.Character.PositionX = 56;
                                            tm2.Session.Character.PositionY = 40;
                                            map.Broadcast(tm2.Session, tm2.Session.Character.GenerateTp());
                                        }

                                        arenaTeam.ToList().ForEach(friends =>
                                        {
                                            friends.Session.SendPacket(friends.ArenaTeamType == ArenaTeamType.ERENIA
                                                ? tm.Session.Character.GenerateTaFc(0)
                                                : tm2.Session.Character.GenerateTaFc(0));
                                        });

                                        map.Sessions.Except(arenaTeam.Select(ss => ss.Session)).ToList().ForEach(ss =>
                                        {
                                            ss.SendPacket(tm.Session.Character.GenerateTaFc(0));
                                            ss.SendPacket(tm2.Session.Character.GenerateTaFc(1));
                                        });

                                        tm.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Call));
                                        tm2.Session.SendPacket(UserInterfaceHelper.Instance.GenerateTaSt(TalentArenaOptionType.Call));

                                        map.Broadcast("ta_s");
                                        Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(start4 => { map.IsPVP = true; });
                                    }
                                    else
                                    {
                                        switch (tm)
                                        {
                                        case null when tm2 == null:
                                            map.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("EQUALITY"), 0));
                                            arenaTeam.ToList().ForEach(arenauser =>
                                            {
                                                arenauser.Session.SendPacket(arenauser.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("EQUALITY"), 10));
                                                arenauser.Session.SendPacket(arenauser.Session.Character.GenerateTaF(3));
                                            });
                                            map.Sessions.Except(arenamembers.Select(x => x.Session)).ToList().ForEach(
                                                x =>
                                            {
                                                ArenaTeamMember arenauser = arenaTeam.FirstOrDefault(se => se.Session != null);
                                                if (arenauser == null)
                                                {
                                                    return;
                                                }
                                                x.SendPacket(arenauser.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("EQUALITY"), 10));
                                                x.SendPacket(arenauser.Session.Character.GenerateTaF(0));
                                            }
                                                );
                                            break;

                                        case null:
                                            map.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("VICTORIOUS_ZENAS"), 0));

                                            arenaTeam.ToList().ForEach(arenauser =>
                                            {
                                                SendRewards(arenauser, arenauser.ArenaTeamType == ArenaTeamType.ZENAS);
                                            });
                                            map.Sessions.Except(arenamembers.Select(x => x.Session)).ToList().ForEach(x =>
                                            {
                                                ArenaTeamMember arenauser = arenaTeam.FirstOrDefault(se => se.Session != null);
                                                if (arenauser == null)
                                                {
                                                    return;
                                                }
                                                x.SendPacket(arenauser.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("VICTORIOUS_ZENAS"), 10));
                                                x.SendPacket(arenauser.Session.Character.GenerateTaF(1));
                                            });
                                            break;

                                        default:
                                            map.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("VICTORIOUS_ERENIA"), 0));
                                            arenaTeam.ToList().ForEach(arenauser =>
                                            {
                                                SendRewards(arenauser, arenauser.ArenaTeamType == ArenaTeamType.ERENIA);
                                            });
                                            map.Sessions.Except(arenamembers.Select(x => x.Session)).ToList().ForEach(
                                                x =>
                                            {
                                                ArenaTeamMember arenauser = arenaTeam.FirstOrDefault(se => se.Session != null);
                                                if (arenauser == null)
                                                {
                                                    return;
                                                }
                                                x.SendPacket(arenauser.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("VICTORIOUS_ERENIA"), 10));
                                                x.SendPacket(arenauser.Session.Character.GenerateTaF(2));
                                            }
                                                );
                                            break;
                                        }
                                        obs3.Dispose();
                                        obs2.Dispose();
                                        obs7?.Dispose();
                                        obs5.Dispose();
                                        Observable.Timer(TimeSpan.FromSeconds(30)).Subscribe(start4 =>
                                        {
                                            map.Dispose();
                                            arenaTeam.ToList().ForEach(o =>
                                            {
                                                if (o.Session?.CurrentMapInstance?.MapInstanceType == MapInstanceType.TalentArenaMapInstance)
                                                {
                                                    ServerManager.Instance.TeleportOnRandomPlaceInMap(o.Session, ServerManager.Instance.ArenaInstance.MapInstanceId);
                                                }
                                            });
                                        });
                                    }
                                    newround1 = false;
                                    newround2 = false;
                                });
                            });
                            ServerManager.Instance.ArenaMembers.Where(o => o.GroupId == member.GroupId || o.GroupId == s.GroupId).ToList()
                            .ForEach(se => { se.Session.SendPacket(se.Session.Character.GenerateBsInfo(2, 2, 0, 0)); });

                            ServerManager.Instance.ArenaMembers.RemoveAll(o => o.GroupId == member.GroupId || o.GroupId == s.GroupId);
                        }
                    }
                    else
                    {
                        if (s.GroupId == null)
                        {
                            if (s.Time != -1)
                            {
                                s.Session.SendPacket(s.Session.Character.GenerateBsInfo(1, 2, s.Time, 7));
                                s.Session.SendPacket(s.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("NO_TEAM_ARENA"), 10));
                            }
                            s.Time = 300;
                            s.Session.SendPacket(s.Session.Character.GenerateBsInfo(1, 2, s.Time, 5));
                            s.Session.SendPacket(s.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SEARCH_ARENA_TEAM"), 10));
                        }
                        else if (ServerManager.Instance.ArenaMembers.Count(g => g.GroupId == s.GroupId) < 3)
                        {
                            s.Session.SendPacket(s.Session.Character.GenerateBsInfo(1, 2, -1, 4));
                            Observable.Timer(TimeSpan.FromSeconds(1)).Subscribe(time =>
                            {
                                s.Time = 300;
                                s.Session.SendPacket(s.Session.Character.GenerateBsInfo(1, 2, s.Time, 8));
                                s.Session.SendPacket(s.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("RETRY_SEARCH_ARENA_TEAM"), 10));
                            });
                        }
                        else
                        {
                            s.Session.SendPacket(s.Session.Character.GenerateBsInfo(0, 2, -1, 3));
                            Observable.Timer(TimeSpan.FromSeconds(1)).Subscribe(time =>
                            {
                                s.Time = 300;
                                s.Session.SendPacket(s.Session.Character.GenerateBsInfo(0, 2, s.Time, 1));
                                s.Session.SendPacket(s.Session.Character.GenerateSay(Language.Instance.GetMessageFromKey("SEARCH_RIVAL_ARENA_TEAM"), 10));
                            });
                        }
                    }
                });
                seconds++;
            });

            Observable.Timer(TimeSpan.FromHours(7)).Subscribe(start2 =>
            {
                ServerManager.Instance.StartedEvents.Remove(EventType.TALENTARENA);
                obs.Dispose();
            });
        }
Пример #21
0
        public override void Draw()
        {
            WorldPos.Reset();
            if (MapInstance.Get(CurrentMap) == null || !Globals.GridMaps.Contains(CurrentMap))
            {
                return;
            }


            var         map           = MapInstance.Get(CurrentMap);
            var         srcRectangle  = new FloatRect();
            var         destRectangle = new FloatRect();
            GameTexture srcTexture    = null;
            var         height        = 0;
            var         width         = 0;
            var         d             = 0;

            switch (Graphic.Type)
            {
            case EventGraphicType.Sprite:     //Sprite
                var entityTex = Globals.ContentManager.GetTexture(
                    GameContentManager.TextureType.Entity, Graphic.Filename
                    );

                if (entityTex != null)
                {
                    srcTexture = entityTex;
                    height     = srcTexture.GetHeight() / Options.Instance.Sprites.Directions;
                    width      = srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames;
                    d          = Graphic.Y;
                    if (!DirectionFix)
                    {
                        switch (Dir)
                        {
                        case 0:
                            d = 3;

                            break;

                        case 1:
                            d = 0;

                            break;

                        case 2:
                            d = 1;

                            break;

                        case 3:
                            d = 2;

                            break;
                        }
                    }

                    var frame = Graphic.X;
                    if (WalkingAnim)
                    {
                        frame = WalkFrame;
                    }

                    if (Options.AnimatedSprites.Contains(Graphic.Filename.ToLower()))
                    {
                        srcRectangle = new FloatRect(
                            AnimationFrame * (int)entityTex.GetWidth() / Options.Instance.Sprites.NormalFrames, d * (int)entityTex.GetHeight() / Options.Instance.Sprites.Directions,
                            (int)entityTex.GetWidth() / Options.Instance.Sprites.NormalFrames, (int)entityTex.GetHeight() / Options.Instance.Sprites.Directions
                            );
                    }
                    else
                    {
                        srcRectangle = new FloatRect(
                            frame * (int)srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames, d * (int)srcTexture.GetHeight() / Options.Instance.Sprites.Directions,
                            (int)srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames, (int)srcTexture.GetHeight() / Options.Instance.Sprites.Directions
                            );
                    }
                }

                break;

            case EventGraphicType.Tileset:     //Tile
                if (mCachedTilesetName != Graphic.Filename)
                {
                    mCachedTilesetName = Graphic.Filename;
                    mCachedTileset     = Globals.ContentManager.GetTexture(
                        GameContentManager.TextureType.Tileset, Graphic.Filename
                        );
                }

                var tileset = mCachedTileset;
                if (tileset != null)
                {
                    srcTexture   = tileset;
                    width        = (Graphic.Width + 1) * Options.TileWidth;
                    height       = (Graphic.Height + 1) * Options.TileHeight;
                    srcRectangle = new FloatRect(
                        Graphic.X * Options.TileWidth, Graphic.Y * Options.TileHeight,
                        (Graphic.Width + 1) * Options.TileWidth, (Graphic.Height + 1) * Options.TileHeight
                        );
                }

                break;
            }

            destRectangle.X = map.GetX() + X * Options.TileWidth + OffsetX;
            if (height > Options.TileHeight)
            {
                destRectangle.Y = map.GetY() + Y * Options.TileHeight + OffsetY - (height - Options.TileHeight);
            }
            else
            {
                destRectangle.Y = map.GetY() + Y * Options.TileHeight + OffsetY;
            }

            if (width > Options.TileWidth)
            {
                destRectangle.X -= (width - Options.TileWidth) / 2;
            }

            destRectangle.X      = (int)Math.Ceiling(destRectangle.X);
            destRectangle.Y      = (int)Math.Ceiling(destRectangle.Y);
            destRectangle.Width  = srcRectangle.Width;
            destRectangle.Height = srcRectangle.Height;
            WorldPos             = destRectangle;
            if (srcTexture != null)
            {
                Graphics.DrawGameTexture(srcTexture, srcRectangle, destRectangle, Intersect.Color.White);
            }
        }
Пример #22
0
        public static void GenerateInstantBattle(bool useTimer = true)
        {
            if (useTimer)
            {
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES"), 5), 0));
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES"), 5), 1));
                Thread.Sleep(4 * 60 * 1000);
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES"), 1), 0));
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES"), 1), 1));
                Thread.Sleep(30 * 1000);
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS"), 30), 0));
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS"), 30), 1));
                Thread.Sleep(20 * 1000);
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS"), 10), 0));
                ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS"), 10), 1));
                Thread.Sleep(10 * 1000);
            }
            ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_STARTED"), 1));
            ServerManager.Instance.Broadcast($"qnaml 1 #guri^506 {Language.Instance.GetMessageFromKey("INSTANTBATTLE_QUESTION")}");
            ServerManager.Instance.EventInWaiting = true;
            Thread.Sleep(30 * 1000);
            ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_STARTED"), 1));
            ServerManager.Instance.Sessions.Where(s => s.Character != null && !s.Character.IsWaitingForEvent).ToList().ForEach(s => s.SendPacket("esf"));
            ServerManager.Instance.EventInWaiting = false;
            IEnumerable <ClientSession> sessions = ServerManager.Instance.Sessions.Where(s =>
                                                                                         s.Character != null && s.Character.IsWaitingForEvent && s.CurrentMapInstance?.MapInstanceType == MapInstanceType.BaseMapInstance);
            List <Tuple <MapInstance, byte> > maps = new List <Tuple <MapInstance, byte> >();
            MapInstance map           = null;
            int         i             = -1;
            int         level         = 0;
            byte        instancelevel = 1;

            foreach (ClientSession s in sessions.OrderBy(s => s.Character?.Level))
            {
                i++;
                if (s.Character.Level > 79 && level <= 79)
                {
                    i             = 0;
                    instancelevel = 80;
                }
                else if (s.Character.Level > 69 && level <= 69)
                {
                    i             = 0;
                    instancelevel = 70;
                }
                else if (s.Character.Level > 59 && level <= 59)
                {
                    i             = 0;
                    instancelevel = 60;
                }
                else if (s.Character.Level > 49 && level <= 49)
                {
                    i             = 0;
                    instancelevel = 50;
                }
                else if (s.Character.Level > 39 && level <= 39)
                {
                    i             = 0;
                    instancelevel = 30;
                }
                if ((i % 50) == 0)
                {
                    map = ServerManager.Instance.GenerateMapInstance(2004, MapInstanceType.NormalInstance, new InstanceBag());
                    maps.Add(new Tuple <MapInstance, byte>(map, instancelevel));
                }
                if (map != null)
                {
                    ServerManager.Instance.TeleportOnRandomPlaceInMap(s, map.MapInstanceId);
                }

                level = s.Character.Level;
            }
            ServerManager.Instance.Sessions.Where(s => s.Character != null).ToList().ForEach(s => s.Character.IsWaitingForEvent = false);
            long maxGold = ServerManager.Instance.MaxGold;

            foreach (Tuple <MapInstance, byte> mapinstance in maps)
            {
                ServerManager.Instance.StartedEvents.Remove(EventType.INSTANTBATTLE);
                Thread.Sleep(10 * 1000);
                if (mapinstance.Item1.Sessions.Count() < 3)
                {
                    mapinstance.Item1.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_NOT_ENOUGH_PLAYERS"), 0));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(5), new EventContainer(mapinstance.Item1, EventActionType.DISPOSEMAP, null));
                }
                else
                {
                    Observable.Timer(TimeSpan.FromMinutes(12)).Subscribe(X =>
                    {
                        for (int d = 0; d < 180; d++)
                        {
                            if (!mapinstance.Item1.Monsters.Any(s => s.CurrentHp > 0))
                            {
                                EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(0),
                                                                   new EventContainer(mapinstance.Item1, EventActionType.SPAWNPORTAL, new Portal {
                                    SourceX = 47, SourceY = 33, DestinationMapId = 1
                                }));
                                mapinstance.Item1.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SUCCEEDED"), 0));
                                foreach (ClientSession cli in mapinstance.Item1.Sessions.Where(s => s.Character != null).ToList())
                                {
                                    cli.Character.GetReput(cli.Character.Level * 50);
                                    cli.Character.GetGold(cli.Character.Level * 1000);
                                    cli.Character.SpAdditionPoint += cli.Character.Level * 100;
                                    cli.Character.SpAdditionPoint  = cli.Character.SpAdditionPoint > 1000000 ? 1000000 : cli.Character.SpAdditionPoint;
                                    cli.SendPacket(cli.Character.GenerateSpPoint());
                                    cli.SendPacket(cli.Character.GenerateGold());
                                    cli.SendPacket(cli.Character.GenerateSay(string.Format(Language.Instance.GetMessageFromKey("WIN_SP_POINT"), cli.Character.Level * 100), 10));
                                }
                                break;
                            }
                            Thread.Sleep(1000);
                        }
                    });

                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(15), new EventContainer(mapinstance.Item1, EventActionType.DISPOSEMAP, null));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(3),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 12), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(5),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 10), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(10),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 5), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(11),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 4), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(12),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 3), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(13),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 2), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(14),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MINUTES_REMAINING"), 1), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(14.5),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS_REMAINING"), 30), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(14.5),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("INSTANTBATTLE_SECONDS_REMAINING"), 30), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromMinutes(0),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_INCOMING"), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(7),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_APPEAR"), 0)));
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(3),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                          UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_HERE"), 0)));

                    for (int wave = 0; wave < 4; wave++)
                    {
                        EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(130 + wave * 160),
                                                           new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                              UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_WAVE"), 0)));
                        EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(160 + wave * 160),
                                                           new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                              UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_INCOMING"), 0)));
                        EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(170 + wave * 160),
                                                           new EventContainer(mapinstance.Item1, EventActionType.SENDPACKET,
                                                                              UserInterfaceHelper.Instance.GenerateMsg(Language.Instance.GetMessageFromKey("INSTANTBATTLE_MONSTERS_HERE"), 0)));
                        EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(10 + wave * 160),
                                                           new EventContainer(mapinstance.Item1, EventActionType.SPAWNMONSTERS, GetInstantBattleMonster(mapinstance.Item1.Map, mapinstance.Item2, wave)));
                        EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(140 + wave * 160),
                                                           new EventContainer(mapinstance.Item1, EventActionType.DROPITEMS, GetInstantBattleDrop(mapinstance.Item1.Map, mapinstance.Item2, wave)));
                    }
                    EventHelper.Instance.ScheduleEvent(TimeSpan.FromSeconds(650),
                                                       new EventContainer(mapinstance.Item1, EventActionType.SPAWNMONSTERS, GetInstantBattleMonster(mapinstance.Item1.Map, mapinstance.Item2, 4)));
                }
            }
        }
Пример #23
0
        public void Update(long timeMs, MapInstance map)
        {
            var sendLeave = false;
            var originalPageInstance = PageInstance;
            if (PageInstance != null)
            {
                //Check for despawn
                if (PageInstance.ShouldDespawn(map))
                {
                    X = PageInstance.X;
                    Y = PageInstance.Y;
                    if (PageInstance.GlobalClone != null)
                    {
                        Player.GlobalPageInstanceLookup.TryRemove(PageInstance.GlobalClone, out Event val);
                    }
                    PageInstance = null;
                    CallStack.Clear();
                    PlayerHasDied = false;
                    if (HoldingPlayer)
                    {
                        PacketSender.SendReleasePlayer(Player, Id);
                        HoldingPlayer = false;
                    }

                    sendLeave = true;
                }
                else
                {
                    if (!Global)
                    {
                        PageInstance.Update(
                            CallStack.Count > 0, timeMs
                        ); //Process movement and stuff that is client specific
                    }

                    //Check to see if we should process event commands
                    if (CallStack.Count > 0)
                    {
                        var curStack = CallStack.Peek();
                        if (curStack == null)
                        {
                            Log.Error("Curstack variable in event update is null.. not sure how nor how to recover so just gonna let this crash now..");
                        }
                        if (Player == null)
                        {
                            Log.Error("Player variable in event update is null.. not sure how nor how to recover so just gonna let this crash now..");
                        }
                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Shop && Player.InShop == null)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Crafting &&
                            Player.CraftingTableId == Guid.Empty)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Bank && Player.InBank == false)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Quest &&
                            !Player.QuestOffers.Contains(((StartQuestCommand) curStack.WaitingOnCommand).QuestId))
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Timer &&
                            WaitTimer < Globals.Timing.Milliseconds)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        var commandsExecuted = 0;
                        while (curStack != null && curStack.WaitingForResponse == CommandInstance.EventResponse.None &&
                               !(PageInstance?.ShouldDespawn(map) ?? false) &&
                               commandsExecuted < Options.EventWatchdogKillThreshhold)
                        {
                            if (curStack.WaitingForRoute != Guid.Empty)
                            {
                                if (curStack.WaitingForRoute == Player.Id)
                                {
                                    if (Player.MoveRoute == null ||
                                        Player.MoveRoute.Complete && Player.MoveTimer < Globals.Timing.Milliseconds)
                                    {
                                        curStack.WaitingForRoute = Guid.Empty;
                                        curStack.WaitingForRouteMap = Guid.Empty;
                                    }
                                }
                                else
                                {
                                    //Check if the exist exists && if the move route is completed.
                                    foreach (var evt in Player.EventLookup)
                                    {
                                        if (evt.Value.MapId == curStack.WaitingForRouteMap &&
                                            evt.Value.BaseEvent.Id == curStack.WaitingForRoute)
                                        {
                                            if (evt.Value.PageInstance == null)
                                            {
                                                break;
                                            }

                                            if (!evt.Value.PageInstance.MoveRoute.Complete)
                                            {
                                                break;
                                            }

                                            curStack.WaitingForRoute = Guid.Empty;
                                            curStack.WaitingForRouteMap = Guid.Empty;

                                            break;
                                        }
                                    }
                                }

                                if (curStack.WaitingForRoute != Guid.Empty)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                if (curStack.CommandIndex >= curStack.CommandList.Count)
                                {
                                    CallStack.Pop();
                                }
                                else
                                {
                                    if (WaitTimer < Globals.Timing.Milliseconds)
                                    {
                                        CommandProcessing.ProcessCommand(curStack.Command, Player, this);
                                        commandsExecuted++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                if (CallStack.Count == 0)
                                {
                                    PlayerHasDied = false;

                                    break;
                                }
                            }

                            curStack = CallStack.Peek();
                        }

                        if (commandsExecuted >= Options.EventWatchdogKillThreshhold)
                        {
                            CallStack.Clear(); //Killing this event, we're over it.
                            if (this.BaseEvent.MapId == Guid.Empty)
                            {
                                Log.Error(Strings.Events.watchdogkillcommon.ToString(BaseEvent.Name));
                                if (Player.Power.IsModerator)
                                {
                                    PacketSender.SendChatMsg(
                                        Player, Strings.Events.watchdogkillcommon.ToString(BaseEvent.Name), ChatMessageType.Error, Color.Red
                                    );
                                }
                            }
                            else
                            {
                                Log.Error(Strings.Events.watchdogkill.ToString(map.Name, BaseEvent.Name));
                                if (Player.Power.IsModerator)
                                {
                                    PacketSender.SendChatMsg(
                                        Player, Strings.Events.watchdogkill.ToString(map.Name, BaseEvent.Name),
                                        ChatMessageType.Error, Color.Red
                                    );
                                }
                            }
                        }
                    }
                    else
                    {
                        if (PageInstance.Trigger == EventTrigger.Autorun && WaitTimer < Globals.Timing.Milliseconds)
                        {
                            var newStack = new CommandInstance(PageInstance.MyPage);
                            CallStack.Push(newStack);
                        }
                    }
                }
            }

            if (PageInstance == null)
            {
                //Try to Spawn a PageInstance.. if we can
                for (var i = BaseEvent.Pages.Count - 1; i >= 0; i--)
                {
                    if (Conditions.CanSpawnPage(BaseEvent.Pages[i], Player, this))
                    {
                        if (Global)
                        {
                            var globalEvent = MapInstance.Get(MapId).GetGlobalEventInstance(BaseEvent);
                            if (globalEvent != null)
                            {
                                PageInstance = new EventPageInstance(
                                    BaseEvent, BaseEvent.Pages[i], BaseEvent.Id, MapId, this, Player,
                                    globalEvent.GlobalPageInstance[i]
                                );

                                if (PageInstance.GlobalClone != null)
                                {
                                    Player.GlobalPageInstanceLookup.AddOrUpdate(globalEvent.GlobalPageInstance[i], this, (key, oldValue) => this);
                                }

                                sendLeave = false;
                                PageIndex = i;
                            }
                        }
                        else
                        {
                            PageInstance = new EventPageInstance(BaseEvent, BaseEvent.Pages[i], MapId, this, Player);
                            sendLeave = false;
                            PageIndex = i;
                        }

                        break;
                    }
                }

                if (sendLeave && originalPageInstance != null)
                {
                    PacketSender.SendEntityLeaveTo(Player, originalPageInstance);
                }
            }
        }
Пример #24
0
        // TODO: Improve NPC movement to be more fluid like a player
        //General Updating
        public override void Update(long timeMs)
        {
            var curMapLink = MapId;

            base.Update(timeMs);

            var statuses = Statuses.Values.ToArray();

            foreach (var status in statuses)
            {
                if (status.Type == StatusTypes.Stun || status.Type == StatusTypes.Sleep)
                {
                    return;
                }
            }

            //TODO Clear Damage Map if out of combat (target is null and combat timer is to the point that regen has started)
            if (Target == null && Globals.Timing.TimeMs > CombatTimer && Globals.Timing.TimeMs > RegenTimer)
            {
                DamageMap.Clear();
            }

            var fleeing = false;

            if (Base.FleeHealthPercentage > 0)
            {
                var fleeHpCutoff = GetMaxVital(Vitals.Health) * ((float)Base.FleeHealthPercentage / 100f);
                if (GetVital(Vitals.Health) < fleeHpCutoff)
                {
                    fleeing = true;
                }
            }

            if (MoveTimer < Globals.Timing.TimeMs)
            {
                var targetMap = Guid.Empty;
                var targetX   = 0;
                var targetY   = 0;
                var targetZ   = 0;

                //Check if there is a target, if so, run their ass down.
                if (Target != null)
                {
                    if (!Target.IsDead() && CanAttack(Target, null))
                    {
                        targetMap = Target.MapId;
                        targetX   = Target.X;
                        targetY   = Target.Y;
                        targetZ   = Target.Z;
                        var targetStatuses = Target.Statuses.Values.ToArray();
                        foreach (var targetStatus in targetStatuses)
                        {
                            if (targetStatus.Type == StatusTypes.Stealth)
                            {
                                targetMap = Guid.Empty;
                                targetX   = 0;
                                targetY   = 0;
                                targetZ   = 0;
                            }
                        }
                    }
                    else
                    {
                        if (CastTime <= 0)
                        {
                            RemoveTarget();
                        }
                    }
                }
                else //Find a target if able
                {
                    long   dmg = 0;
                    Entity tgt = null;
                    foreach (var pair in DamageMap)
                    {
                        if (pair.Value > dmg)
                        {
                            dmg = pair.Value;
                            tgt = pair.Key;
                        }
                    }

                    if (tgt != null)
                    {
                        AssignTarget(tgt);
                    }
                    else
                    {
                        // Check if attack on sight or have other npc's to target
                        TryFindNewTarget(timeMs);
                    }
                }

                if (targetMap != Guid.Empty)
                {
                    //Check if target map is on one of the surrounding maps, if not then we are not even going to look.
                    if (targetMap != MapId)
                    {
                        if (MapInstance.Get(MapId).SurroundingMaps.Count > 0)
                        {
                            for (var x = 0; x < MapInstance.Get(MapId).SurroundingMaps.Count; x++)
                            {
                                if (MapInstance.Get(MapId).SurroundingMaps[x] == targetMap)
                                {
                                    break;
                                }

                                if (x == MapInstance.Get(MapId).SurroundingMaps.Count - 1)
                                {
                                    targetMap = Guid.Empty;
                                }
                            }
                        }
                        else
                        {
                            targetMap = Guid.Empty;
                        }
                    }
                }

                if (targetMap != Guid.Empty)
                {
                    if (mPathFinder.GetTarget() != null)
                    {
                        if (targetMap != mPathFinder.GetTarget().TargetMapId ||
                            targetX != mPathFinder.GetTarget().TargetX ||
                            targetY != mPathFinder.GetTarget().TargetY)
                        {
                            mPathFinder.SetTarget(null);
                        }
                    }

                    if (mPathFinder.GetTarget() == null)
                    {
                        mPathFinder.SetTarget(new PathfinderTarget(targetMap, targetX, targetY, targetZ));
                    }

                    if (mPathFinder.GetTarget() != null)
                    {
                        TryCastSpells();
                        if (!IsOneBlockAway(
                                mPathFinder.GetTarget().TargetMapId, mPathFinder.GetTarget().TargetX,
                                mPathFinder.GetTarget().TargetY, mPathFinder.GetTarget().TargetZ
                                ))
                        {
                            switch (mPathFinder.Update(timeMs))
                            {
                            case PathfinderResult.Success:
                                var dir = mPathFinder.GetMove();
                                if (dir > -1)
                                {
                                    if (fleeing)
                                    {
                                        switch (dir)
                                        {
                                        case 0:
                                            dir = 1;

                                            break;

                                        case 1:
                                            dir = 0;

                                            break;

                                        case 2:
                                            dir = 3;

                                            break;

                                        case 3:
                                            dir = 2;

                                            break;

                                        case 4:
                                            dir = 5;

                                            break;

                                        case 5:
                                            dir = 4;

                                            break;

                                        case 6:
                                            dir = 7;

                                            break;

                                        case 7:
                                            dir = 6;

                                            break;
                                        }
                                    }

                                    if (CanMove(dir) == -1 || CanMove(dir) == -4)
                                    {
                                        //check if NPC is snared or stunned
                                        statuses = Statuses.Values.ToArray();
                                        foreach (var status in statuses)
                                        {
                                            if (status.Type == StatusTypes.Stun ||
                                                status.Type == StatusTypes.Snare ||
                                                status.Type == StatusTypes.Sleep)
                                            {
                                                return;
                                            }
                                        }

                                        Move((byte)dir, null);
                                    }
                                    else
                                    {
                                        mPathFinder.PathFailed(timeMs);
                                    }
                                }

                                break;

                            case PathfinderResult.OutOfRange:
                                RemoveTarget();
                                targetMap = Guid.Empty;

                                break;

                            case PathfinderResult.NoPathToTarget:
                                TryFindNewTarget(timeMs, Target?.Id ?? Guid.Empty);
                                targetMap = Guid.Empty;

                                break;

                            case PathfinderResult.Failure:
                                targetMap = Guid.Empty;
                                RemoveTarget();

                                break;

                            case PathfinderResult.Wait:
                                targetMap = Guid.Empty;

                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                        else
                        {
                            var fleed = false;
                            if (fleeing)
                            {
                                var dir = DirToEnemy(Target);
                                switch (dir)
                                {
                                case 0:
                                    dir = 1;

                                    break;

                                case 1:
                                    dir = 0;

                                    break;

                                case 2:
                                    dir = 3;

                                    break;

                                case 3:
                                    dir = 2;

                                    break;

                                case 4:
                                    dir = 5;

                                    break;

                                case 5:
                                    dir = 4;

                                    break;

                                case 6:
                                    dir = 7;

                                    break;

                                case 7:
                                    dir = 6;

                                    break;
                                }

                                if (CanMove(dir) == -1 || CanMove(dir) == -4)
                                {
                                    //check if NPC is snared or stunned
                                    statuses = Statuses.Values.ToArray();
                                    foreach (var status in statuses)
                                    {
                                        if (status.Type == StatusTypes.Stun ||
                                            status.Type == StatusTypes.Snare ||
                                            status.Type == StatusTypes.Sleep)
                                        {
                                            return;
                                        }
                                    }

                                    Move(dir, null);
                                    fleed = true;
                                }
                            }

                            if (!fleed)
                            {
                                if (Dir != DirToEnemy(Target) && DirToEnemy(Target) != -1)
                                {
                                    ChangeDir(DirToEnemy(Target));
                                }
                                else
                                {
                                    if (Target.IsDisposed)
                                    {
                                        Target = null;
                                    }
                                    else
                                    {
                                        if (CanAttack(Target, null))
                                        {
                                            TryAttack(Target);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //Move randomly
                if (targetMap != Guid.Empty)
                {
                    return;
                }

                if (LastRandomMove >= Globals.Timing.TimeMs || CastTime > 0)
                {
                    return;
                }

                if (Base.Movement == (int)NpcMovement.StandStill)
                {
                    LastRandomMove = Globals.Timing.TimeMs + Randomization.Next(1000, 3000);

                    return;
                }
                else if (Base.Movement == (int)NpcMovement.TurnRandomly)
                {
                    ChangeDir((byte)Randomization.Next(0, 4));
                    LastRandomMove = Globals.Timing.TimeMs + Randomization.Next(1000, 3000);

                    return;
                }

                var i = Randomization.Next(0, 1);
                if (i == 0)
                {
                    i = Randomization.Next(0, 8);
                    if (CanMove(i) == -1)
                    {
                        //check if NPC is snared or stunned
                        statuses = Statuses.Values.ToArray();
                        foreach (var status in statuses)
                        {
                            if (status.Type == StatusTypes.Stun ||
                                status.Type == StatusTypes.Snare ||
                                status.Type == StatusTypes.Sleep)
                            {
                                return;
                            }
                        }

                        Move((byte)i, null);
                    }
                }

                LastRandomMove = Globals.Timing.TimeMs + Randomization.Next(1000, 3000);

                if (fleeing)
                {
                    LastRandomMove = Globals.Timing.TimeMs + (long)GetMovementTime();
                }
            }

            //If we switched maps, lets update the maps
            if (curMapLink != MapId)
            {
                if (curMapLink == Guid.Empty)
                {
                    MapInstance.Get(curMapLink).RemoveEntity(this);
                }

                if (MapId != Guid.Empty)
                {
                    MapInstance.Get(MapId).AddEntity(this);
                }
            }
            // End of the Npc Movement
        }
Пример #25
0
        public bool CheckForCollision(ProjectileSpawn spawn)
        {
            var killSpawn = MoveFragment(spawn, false);

            //Check Map Entities For Hits
            var map = MapInstance.Get(spawn.MapId);

            if (!killSpawn && map != null)
            {
                var attribute = map.Attributes[(int)spawn.X, (int)spawn.Y];

                //Check for Z-Dimension
                if (!spawn.ProjectileBase.IgnoreZDimension)
                {
                    if (attribute != null && attribute.Type == MapAttributes.ZDimension)
                    {
                        if (((MapZDimensionAttribute)attribute).GatewayTo > 0)
                        {
                            spawn.Z = (byte)(((MapZDimensionAttribute)attribute).GatewayTo - 1);
                        }
                    }
                }

                //Check for grapplehooks.
                if (attribute != null &&
                    attribute.Type == MapAttributes.GrappleStone &&
                    Base.GrappleHook == true &&
                    !spawn.Parent.HasGrappled)
                {
                    if (spawn.Dir <= 3)  //Don't handle directional projectile grapplehooks
                    {
                        spawn.Parent.HasGrappled = true;

                        //Only grapple if the player hasnt left the firing position.. if they have then we assume they dont wanna grapple
                        if (Owner.X == X && Owner.Y == Y && Owner.MapId == MapId)
                        {
                            Owner.Dir = spawn.Dir;
                            new Dash(
                                Owner, spawn.Distance, (byte)Owner.Dir, Base.IgnoreMapBlocks,
                                Base.IgnoreActiveResources, Base.IgnoreExhaustedResources, Base.IgnoreZDimension
                                );
                        }

                        killSpawn = true;
                    }
                }

                if (attribute != null &&
                    attribute.Type == MapAttributes.Blocked &&
                    !spawn.ProjectileBase.IgnoreMapBlocks)
                {
                    killSpawn = true;
                }
            }

            if (!killSpawn && map != null)
            {
                var entities = map.GetEntities();
                for (var z = 0; z < entities.Count; z++)
                {
                    if (entities[z] != null &&
                        (entities[z].X == Math.Round(spawn.X) || entities[z].X == Math.Ceiling(spawn.X) || entities[z].X == Math.Floor(spawn.X)) &&
                        (entities[z].Y == Math.Round(spawn.Y) || entities[z].Y == Math.Ceiling(spawn.Y) || entities[z].Y == Math.Floor(spawn.Y)) &&
                        entities[z].Z == spawn.Z)
                    {
                        killSpawn = spawn.HitEntity(entities[z]);
                        if (killSpawn && !spawn.ProjectileBase.PierceTarget)
                        {
                            return(killSpawn);
                        }
                    }
                    else
                    {
                        if (z == entities.Count - 1)
                        {
                            spawn.TransmittionTimer = Globals.Timing.Milliseconds +
                                                      (long)((float)Base.Speed / (float)Base.Range);

                            if (spawn.Distance >= Base.Range)
                            {
                                killSpawn = true;
                            }
                        }
                    }
                }
            }

            return(killSpawn);
        }
Пример #26
0
        public static void GenerateRaida(MapInstanceType raidType, byte faction)
        {
            Guardians = new List <MapMonster>();
            MapInstance bitoren = ServerManager.GetMapInstance(ServerManager.GetBaseMapInstanceIdByMapId(134));

            bitoren.CreatePortal(new Portal
            {
                SourceMapId      = 134,
                SourceX          = 140,
                SourceY          = 100,
                DestinationMapId = 0,
                DestinationX     = 1,
                DestinationY     = 1,
                Type             = (short)(9 + faction)
            });

            #region Guardian Spawning

            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 147,
                MapY          = 88,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 149,
                MapY          = 94,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 147,
                MapY          = 101,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 139,
                MapY          = 105,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 132,
                MapY          = 101,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 129,
                MapY          = 94,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });
            Guardians.Add(new MapMonster
            {
                MonsterVNum   = (short)(678 + faction),
                MapX          = 132,
                MapY          = 88,
                MapId         = 134,
                Position      = 2,
                IsMoving      = false,
                MapMonsterId  = bitoren.GetNextMonsterId(),
                ShouldRespawn = false,
                IsHostile     = true
            });

            #endregion

            foreach (MapMonster monster in Guardians)
            {
                monster.Initialize(bitoren);
                bitoren.AddMonster(monster);
                bitoren.Broadcast(monster.GenerateIn());
            }

            Act4RaidThread raidThread = new Act4RaidThread();
            Observable.Timer(TimeSpan.FromMinutes(0)).Subscribe(X => raidThread.Run(raidType, faction));
        }
Пример #27
0
        public bool MoveFragment(ProjectileSpawn spawn, bool move = true)
        {
            float newx     = spawn.X;
            float newy     = spawn.Y;
            var   newMapId = spawn.MapId;

            if (move)
            {
                spawn.Distance++;
                newx = spawn.X + GetRangeX(spawn.Dir, 1);
                newy = spawn.Y + GetRangeY(spawn.Dir, 1);
            }

            var killSpawn = false;
            var map       = MapInstance.Get(spawn.MapId);

            if (Math.Round(newx) < 0)
            {
                if (MapInstance.Get(map.Left) != null)
                {
                    newMapId = MapInstance.Get(spawn.MapId).Left;
                    newx     = Options.MapWidth - 1;
                }
                else
                {
                    killSpawn = true;
                }
            }

            if (Math.Round(newx) > Options.MapWidth - 1)
            {
                if (MapInstance.Get(map.Right) != null)
                {
                    newMapId = MapInstance.Get(spawn.MapId).Right;
                    newx     = 0;
                }
                else
                {
                    killSpawn = true;
                }
            }

            if (Math.Round(newy) < 0)
            {
                if (MapInstance.Get(map.Up) != null)
                {
                    newMapId = MapInstance.Get(spawn.MapId).Up;
                    newy     = Options.MapHeight - 1;
                }
                else
                {
                    killSpawn = true;
                }
            }

            if (Math.Round(newy) > Options.MapHeight - 1)
            {
                if (MapInstance.Get(map.Down) != null)
                {
                    newMapId = MapInstance.Get(spawn.MapId).Down;
                    newy     = 0;
                }
                else
                {
                    killSpawn = true;
                }
            }

            spawn.X     = newx;
            spawn.Y     = newy;
            spawn.MapId = newMapId;

            return(killSpawn);
        }
Пример #28
0
            public void Run(MapInstance map)
            {
                _map = map;

                foreach (ClientSession session in _map.Sessions)
                {
                    ServerManager.Instance.TeleportOnRandomPlaceInMap(session, map.MapInstanceId);
                    if (session.Character.IsVehicled)
                    {
                        session.Character.RemoveVehicle();
                    }
                    if (session.Character.UseSp)
                    {
                        session.Character.LastSp = (DateTime.Now - Process.GetCurrentProcess().StartTime.AddSeconds(-50)).TotalSeconds;
                        ItemInstance specialist = session.Character.Inventory.LoadBySlotAndType((byte)EquipmentType.Sp, InventoryType.Wear);
                        if (specialist != null)
                        {
                            removeSP(session, specialist.ItemVNum);
                        }
                    }
                    Spawn = true;
                    session.Character.NoAttack      = false;
                    session.Character.Speed         = 5;
                    session.Character.IsVehicled    = true;
                    session.Character.IsCustomSpeed = true;
                    session.Character.Morph         = 1009;
                    session.Character.ArenaWinner   = 0;
                    session.Character.MorphUpgrade  = 0;
                    session.Character.MorphUpgrade2 = 0;
                    session.SendPacket(session.Character.GenerateCond());
                    session.Character.LastSpeedChange = DateTime.Now;
                    session.CurrentMapInstance?.Broadcast(session.Character.GenerateCMode());
                    session.SendPacket($"eff_s 1 {session.Character.CharacterId} 4323");
                    _map.Broadcast("srlst 0");
                    session.SendPacket("say 1 -1 10 Dans 30 secondes Le raid de la Ferme des moutons commence bientôt.");
                    Observable.Timer(TimeSpan.FromSeconds(30)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 10 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(35)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 5 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(36)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 4 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(37)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 3 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(38)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 2 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(39)).Subscribe(o =>
                    {
                        session.SendPacket("say 1 -1 10 Dans 1 secondes Le raid de la Ferme des moutons commence bientôt.");
                    });
                    Observable.Timer(TimeSpan.FromSeconds(50)).Subscribe(o =>
                    {
                        _map.Broadcast("srlst 3");
                        _map.Broadcast("sh_o");
                    });
                    Observable.Timer(TimeSpan.FromMinutes(5)).Subscribe(o =>
                    {
                        End(session.Character);
                    });
                }

                int i = 0;

                while (_map?.Sessions?.Any() == true)
                {
                    runRound(i++);
                }

                //ended
            }