Exemplo n.º 1
0
        public static void Generate()
        {
            //while (true)
            //    Test.Show(RenderNoiseBmp(500, 500));
            while (true)
            {
                int seed = Environment.TickCount;
                seed = new RRandom().Next(8, 16777216); // 16777216 = 8^8
                DateTime asdf = DateTime.Now;
                seed = asdf.Millisecond + asdf.Minute + asdf.Hour + asdf.Year;
                Random     rand = new Random(seed);
                PolygonMap map  = new PolygonMap(rand.Next());

                Console.Out.WriteLine("Generating map...");
                map.Generate(Size * 15);

                Console.Out.WriteLine("Creating terrain...");
                TerrainTile[,] dat = CreateTerrain(rand.Next(), map);

                Console.Out.WriteLine("Computing biomes...");
                new Biome(rand.Next(), map).ComputeBiomes(dat);


                new TerrainDisplay(dat).ShowDialog();
                //Test.Show(RenderMoistBmp(dat));
                //Test.Show(RenderEvalBmp(dat));

                map = null;
                dat = null;
                GC.WaitForFullGCComplete(-1);
                GC.Collect();
            }
        }
Exemplo n.º 2
0
        public SphereAreaLight(Vector3 pos, Vector3 col, float intens, int uniqSamples = 256) : base(pos, col, intens, uniqSamples)
        {
            int a     = 0;
            int steps = (int)Math.Sqrt(uniqSamples);

            for (int i = 0; i < steps; i++)
            {
                for (int j = 0; j < steps; j++)
                {
                    allPoints[a++] = Position + RRandom.RndUnitStratified(steps, i, j) * Radius;
                }
            }
        }
Exemplo n.º 3
0
        public SpotLightMultiSample(Vector3 position, Vector3 colour, float intensity, int uniqSamples = 256)
            : base(position, colour, intensity, uniqSamples)
        {
            int a     = 0;
            int steps = (int)Math.Sqrt(uniqSamples);

            for (int i = 0; i < steps; i++)
            {
                for (int j = 0; j < steps; j++)
                {
                    allPoints[a++] = Position + RRandom.RndUnitStratified(steps, i, j) * Radius;
                }
            }
        }
Exemplo n.º 4
0
        //points on surface of a sphere
        public override Vector3[] TrueStratified(uint max)
        {
            int a     = 0;
            int steps = (int)Math.Sqrt(max);

            Vector3[] arr = new Vector3[steps * steps];
            for (int i = 0; i < steps; i++)
            {
                for (int j = 0; j < steps; j++)
                {
                    arr[a++] = Position + RRandom.RndUnitStratified(steps, i, j) * Radius;
                }
            }
            return(arr);
        }
Exemplo n.º 5
0
        private bool CheckLevelUp()
        {
            if (Experience - GetLevelExp(Level) >= ExperienceGoal && Level < 20)
            {
                Level++;
                ExperienceGoal = GetExpGoal(Level);
                foreach (var i in Manager.GameData.ObjectTypeToElement[ObjectType].Elements("LevelIncrease"))
                {
                    var rand     = new RRandom();
                    var min      = int.Parse(i.Attribute("min").Value);
                    var max      = int.Parse(i.Attribute("max").Value) + 1;
                    var xElement = Manager.GameData.ObjectTypeToElement[ObjectType].Element(i.Value);
                    if (xElement == null)
                    {
                        continue;
                    }
                    var limit =
                        int.Parse(
                            xElement.Attribute("max").Value);
                    var idx = StatsManager.StatsNameToIndex(i.Value);
                    Stats[idx] += rand.Next(min, max);
                    if (Stats[idx] > limit)
                    {
                        Stats[idx] = limit;
                    }
                }
                HP = Stats[0] + Boost[0];
                Mp = Stats[1] + Boost[1];

                UpdateCount++;

                if (Level == 20)
                {
                    foreach (var i in Owner.Players.Values)
                    {
                        i.SendInfo(Name + " achieved level 20");
                    }
                    XpBoosted       = false;
                    XpBoostTimeLeft = 0;
                }
                Quest = null;
                return(true);
            }
            CalculateFame();
            return(false);
        }
Exemplo n.º 6
0
        //private static int DistSqr(IntPoint a, IntPoint b)
        //{
        //    return (a.X - b.X)*(a.X - b.X) + (a.Y - b.Y)*(a.Y - b.Y);
        //}

        public static void ApplySetPieces(World world)
        {
            log.InfoFormat("Applying set pieces to world {0}({1}).", world.Id, world.Name);

            Wmap map = world.Map;
            int  w = map.Width, h = map.Height;

            Random         rand  = new RRandom();
            HashSet <Rect> rects = new HashSet <Rect>();

            foreach (Tuple <ISetPiece, int, int, WmapTerrain[]> dat in setPieces)
            {
                int size  = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect     rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect {
                            x = pt.X, y = pt.Y, w = size, h = size
                        };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                              rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0)
                    {
                        continue;
                    }
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }

            log.Info("Set pieces applied.");
        }
Exemplo n.º 7
0
        private void Spawn()
        {
            /*
             * if(wave % 5 == 0)
             * {
             *      nextDifficulty();
             * }
             */
            try
            {
                List <string> enems = new List <string>();
                Random        r     = new RRandom();

                for (int i = 0; i < wave / 3 + 1; i++)
                {
                    enems.Add(Gods[r.Next(0, Gods.Length)]);
                }
                for (int i = 0; i < wave / 3 + 1; i++)
                {
                    enems.Add(NormalEnemies[r.Next(0, NormalEnemies.Length)]);
                }
                for (int i = 0; i < wave / 3 + 1; i++)
                {
                    enems.Add(WeakEnemies[r.Next(0, WeakEnemies.Length)]);
                }
                Random r2 = new RRandom();
                foreach (string i in enems)
                {
                    ushort id    = Manager.GameData.IdToObjectType[i];
                    int    xloc  = r2.Next(10, Map.Width) - 6;
                    int    yloc  = r2.Next(10, Map.Height) - 6;
                    Entity enemy = Entity.Resolve(Manager, id);
                    enemy.Move(xloc, yloc);
                    EnterWorld(enemy);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
Exemplo n.º 8
0
        public static GiftCode GenerateRandom(XmlData data, int minGold = 0, int maxGold = 10000, int minFame = 0, int maxFame = 10000, int minCharSlots = 0, int maxCharSlots = 4, int minVaultChests = 0, int maxVaultChests = 4, int maxItemStack = 10, int minItemStack = 1, int maxItemTypes = 10, int minItemTypes = 1)
        {
            var rand = new RRandom();
            var ret  = new GiftCode();

            var types = rand.Next(minItemTypes, maxItemTypes);
            var c     = rand.Next(minItemStack, maxItemStack);

            for (var i = 0; i < types; i++)
            {
                var t = data.Items.ElementAt(rand.Next(0, data.Items.Count)).Key;
                for (var j = 0; j < c; j++)
                {
                    ret.Gifts.Add(t);
                }
                c = rand.Next(minItemStack, maxItemStack);
            }
            ret.CharSlots   = rand.Next(minCharSlots, maxCharSlots);
            ret.VaultChests = rand.Next(minVaultChests, maxVaultChests);
            ret.Gold        = rand.Next(minGold, maxGold);
            ret.Fame        = rand.Next(minFame, maxFame);
            return(ret);
        }
Exemplo n.º 9
0
        // ------------ Convert to UDL format ------------- //
        public static byte[] ConvertUDL(RealmManager manager, string json)
        {
            json_dat obj = JsonConvert.DeserializeObject <json_dat>(json);

            byte[] dat = ZlibStream.UncompressBuffer(obj.data);

            Random rand = new RRandom();

            Dictionary <ushort, TerrainTile> tileDict = new Dictionary <ushort, TerrainTile>();

            for (int i = 0; i < obj.dict.Length; i++)
            {
                loc o = obj.dict[i];
                tileDict[(ushort)i] = new TerrainTile
                {
                    TileId  = o.ground == null ? (ushort)0xff : manager.GameData.IdToObjectType[o.ground],
                    TileObj = o.objs == null ? null : o.objs[0].id,
                    Name    = o.objs == null ? "" : o.objs[0].name ?? "",
                    Terrain = TerrainType.None,
                    Region  =
                        o.regions == null
                            ? TileRegion.None
                            : (TileRegion)Enum.Parse(typeof(TileRegion), o.regions[0].id.Replace(' ', '_'))
                };
            }

            TerrainTile[,] tiles = new TerrainTile[obj.width, obj.height];
            using (NReader rdr = new NReader(new MemoryStream(dat)))
                for (int y = 0; y < obj.height; y++)
                {
                    for (int x = 0; x < obj.width; x++)
                    {
                        tiles[x, y]   = tileDict[(ushort)rdr.ReadInt16()];
                        tiles[x, y].X = x;
                        tiles[x, y].Y = y;
                    }
                }

            foreach (TerrainTile i in tiles)
            {
                if (i.TileId == 0xff && i.TileObj == null)
                {
                    bool createWall = false;
                    for (int ty = -1; ty <= 1; ty++)
                    {
                        for (int tx = -1; tx <= 1; tx++)
                        {
                            try
                            {
                                if (tiles[i.X + tx, i.Y + ty].TileId != 0xff && tiles[i.X + tx, i.Y + ty].TileId != 0xfe &&
                                    tiles[i.X + tx, i.Y + ty].TileId != 0xfd && tiles[i.X + tx, i.Y + ty].TileId != 0xe8)
                                {
                                    createWall = true;
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    if (createWall)
                    {
                        tiles[i.X, i.Y].TileObj = rand.Next(1, 5) == 1 ? "Grey Torch Wall" : "Grey Wall";
                    }
                }
                else if (i.TileId == manager.GameData.IdToObjectType["Grey Closed"] && rand.Next(1, 4) == 1)
                {
                    tiles[i.X, i.Y].TileId = manager.GameData.IdToObjectType["Grey Quad"];
                }
            }

            return(WorldMapExporter.Export(tiles));
        }
Exemplo n.º 10
0
        public override void Init(World owner)
        {
            WorldInstance = owner;
            var rand = new RRandom();
            int x, y;

            do
            {
                x = rand.Next(0, owner.Map.Width);
                y = rand.Next(0, owner.Map.Height);
            } while (owner.Map[x, y].Region != TileRegion.Spawn);
            Move(x + 0.5f, y + 0.5f);
            tiles = new byte[owner.Map.Width, owner.Map.Height];
            SetNewbiePeriod();
            base.Init(owner);

            if (Client.Character.Pet != null)
            {
                GivePet(Client.Character.Pet);
            }

            if (owner.Id == World.NEXUS_ID || owner.Name == "Vault")
            {
                Client.SendPacket(new Global_NotificationPacket
                {
                    Type = 0,
                    Text = Client.Account.Gifts.Count > 0 ? "giftChestOccupied" : "giftChestEmpty"
                });
            }

            SendAccountList(Locked, AccountListPacket.LOCKED_LIST_ID);
            SendAccountList(Ignored, AccountListPacket.IGNORED_LIST_ID);

            WorldTimer[] accTimer = { null };
            owner.Timers.Add(accTimer[0] = new WorldTimer(5000, (w, t) =>
            {
                Manager.Database.DoActionAsync(db =>
                {
                    if (Client?.Account == null)
                    {
                        return;
                    }
                    Client.Account = db.GetAccount(AccountId, Manager.GameData);
                    Credits        = Client.Account.Credits;
                    CurrentFame    = Client.Account.Stats.Fame;
                    Tokens         = Client.Account.FortuneTokens;
                    accTimer[0].Reset();
                    Manager.Logic.AddPendingAction(_ => w.Timers.Add(accTimer[0]), PendingPriority.Creation);
                });
            }));

            WorldTimer[] pingTimer = { null };
            owner.Timers.Add(pingTimer[0] = new WorldTimer(PING_PERIOD, (w, t) =>
            {
                Client.SendPacket(new PingPacket {
                    Serial = pingSerial++
                });
                pingTimer[0].Reset();
                Manager.Logic.AddPendingAction(_ => w.Timers.Add(pingTimer[0]), PendingPriority.Creation);
            }));
            Manager.Database.DoActionAsync(db =>
            {
                db.UpdateLastSeen(Client.Account.AccountId, Client.Character.CharacterId, owner.Name);
                db.LockAccount(Client.Account);
            });

            if (Client.Account.IsGuestAccount)
            {
                owner.Timers.Add(new WorldTimer(1000, (w, t) => Client.Disconnect()));
                Client.SendPacket(new networking.svrPackets.FailurePacket
                {
                    ErrorId          = 8,
                    ErrorDescription = "Registration needed."
                });
                Client.SendPacket(new PasswordPromtPacket
                {
                    CleanPasswordStatus = PasswordPromtPacket.REGISTER
                });
                return;
            }

            if (!Client.Account.VerifiedEmail && Program.Verify)
            {
                Client.SendPacket(new VerifyEmailDialogPacket());
                owner.Timers.Add(new WorldTimer(1000, (w, t) => Client.Disconnect()));
                return;
            }
            CheckSetTypeSkin();
        }
Exemplo n.º 11
0
        protected override void HandleRequest()
        {
            using (var db = new Database())
            {
                int currency = -1;
                int price    = -1;
                int.TryParse(Query["currency"], out currency);
                string  status = "<Error>Internal Server Error</Error>";
                Account acc;

                if (CheckAccount(acc = db.Verify(Query["guid"], Query["password"], Program.GameData), db, false))
                {
                    var cmd = db.CreateQuery();
                    cmd.CommandText = "SELECT * FROM thealchemist WHERE startTime <= now() AND endTime >= now() AND id=@gameId;";
                    cmd.Parameters.AddWithValue("@gameId", Query["gameId"]);
                    Random     rand  = new RRandom();
                    List <int> gifts = new List <int>();

                    using (var rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        if (rdr.HasRows)
                        {
                            List <int> items      = Utils.FromCommaSepString32(rdr.GetString("contents")).ToList();
                            List <int> candidates = new List <int>(3);

                            do
                            {
                                int item = items[rand.Next(items.Count)];
                                if (!candidates.Contains(item))
                                {
                                    candidates.Add(item);
                                }
                            } while (candidates.Count < 3);

                            if (currency == GOLD)
                            {
                                if (Query["status"] == "0")
                                {
                                    if (CurrentGames.ContainsKey(acc.AccountId))
                                    {
                                        CurrentGames.Remove(acc.AccountId);
                                    }
                                    CurrentGames.Add(acc.AccountId, candidates.ToArray());
                                    price  = rdr.GetInt32("priceFirstInGold");
                                    status = "<Success><Candidates>" +
                                             Utils.GetCommaSepString(candidates.ToArray()) +
                                             "</Candidates><Gold>" +
                                             (acc.Credits - price) +
                                             "</Gold></Success>";
                                }
                                else if (Query["status"] == "1")
                                {
                                    if (CurrentGames.ContainsKey(acc.AccountId))
                                    {
                                        candidates = CurrentGames[acc.AccountId].ToList();
                                        candidates.Shuffle();
                                        status = "<Success><Awards>" + candidates[int.Parse(Query["choice"])] + "</Awards></Success>";
                                        gifts.Add(candidates[int.Parse(Query["choice"])]);
                                        candidates.Remove(candidates[int.Parse(Query["choice"])]);
                                        CurrentGames[acc.AccountId] = candidates.ToArray();
                                    }
                                }
                                else if (Query["status"] == "2")
                                {
                                    if (CurrentGames.ContainsKey(acc.AccountId))
                                    {
                                        candidates = CurrentGames[acc.AccountId].ToList();
                                        candidates.Shuffle();
                                        price  = rdr.GetInt32("priceSecondInGold");
                                        status = "<Success><Awards>" + candidates[int.Parse(Query["choice"])] + "</Awards></Success>";
                                        gifts.Add(candidates[int.Parse(Query["choice"])]);
                                        CurrentGames.Remove(acc.AccountId);
                                    }
                                }
                            }
                            else if (currency == FORTUNETOKENS)
                            {
                                if (Query["status"] == "0")
                                {
                                    if (CurrentGames.ContainsKey(acc.AccountId))
                                    {
                                        CurrentGames.Remove(acc.AccountId);
                                    }
                                    CurrentGames.Add(acc.AccountId, candidates.ToArray());
                                    price  = rdr.GetInt32("priceFirstInToken");
                                    status = "<Success><Candidates>" +
                                             Utils.GetCommaSepString(candidates.ToArray()) +
                                             "</Candidates><FortuneToken>" +
                                             (acc.FortuneTokens - price) +
                                             "</FortuneToken></Success>";
                                }
                                else if (Query["status"] == "1")
                                {
                                    if (CurrentGames.ContainsKey(acc.AccountId))
                                    {
                                        candidates = CurrentGames[acc.AccountId].ToList();
                                        candidates.Shuffle();
                                        status = "<Success><Awards>" + candidates[int.Parse(Query["choice"])] + "</Awards></Success>";
                                        gifts.Add(candidates[int.Parse(Query["choice"])]);
                                        candidates.Remove(candidates[int.Parse(Query["choice"])]);
                                        CurrentGames[acc.AccountId] = candidates.ToArray();
                                    }
                                }
                                else if (Query["status"] == "2")
                                {
                                    status = "<Error>You can not play twiche with a Fortune Token</Error>";
                                }
                            }
                            else
                            {
                                status = "<Error>Invalid currency</Error>";
                            }
                        }
                        else
                        {
                            status = "<Error>Invalid gameId</Error>";
                        }
                    }
                    if (currency == GOLD)
                    {
                        db.UpdateCredit(acc, price == -1 ? 0 : -price);
                    }
                    else if (currency == FORTUNETOKENS)
                    {
                        db.UpdateFortuneToken(acc, price == -1 ? 0 : -price);
                    }

                    db.AddGifts(acc, gifts);
                }
                else
                {
                    status = "<Error>Account not found</Error>";
                }

                using (StreamWriter wtr = new StreamWriter(Context.Response.OutputStream))
                    wtr.Write(status);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Trace the ray and go around the world in 80ns. Or more :S
        /// </summary>
        /// <param name="ray"></param>
        /// <param name="debug"></param>
        /// <returns></returns>
        public Vector3 TraceRay(Ray ray, bool debug = false)
        {
            Vector3 ret = Vector3.Zero;

            if (ray.Depth > Settings.MaxDepth)
            {
                return(ret);
            }

            // Check for intersections
            RayHit hit = intersect(ray);

            if (hit.Obj == null)
            {
                return(World.Environent == null ? Vector3.Zero : World.Environent.GetColor(ray));
            }
            if (debug)
            {
                DebugData.PrimaryRays.Add(new Tuple <Ray, RayHit>(ray, hit));
            }

            // Calculate color and specular highlights. Pure mirrors dont have diffuse
            Vector3 specular = Vector3.Zero;
            Vector3 color    = Vector3.Zero;

            if (!hit.Obj.Material.IsMirror)
            {
                color += illuminate(ray, hit, ref specular, debug);
                color += World.Environent.AmbientLight;
            }


            // Different materials are handled differently. Would be cool to move that into material
            if (hit.Obj.Material.IsMirror)
            {
                ret = TraceRay(RayTrans.Reflect(ray, hit), debug);
            }
            else if (hit.Obj.Material.IsDielectic)
            {
                var   n1 = ray.isOutside() ? Constants.LIGHT_IOR : hit.Obj.Material.RefractionIndex; // TODO: shorten this shizzle into a func
                var   n2 = ray.isOutside() ? hit.Obj.Material.RefractionIndex : Constants.LIGHT_IOR;
                float reflect_multiplier = QuickMaths.Fresnel(n1, n2, hit.Normal, ray.Direction);
                reflect_multiplier = hit.Obj.Material.Reflectivity + (1f - hit.Obj.Material.Reflectivity) * reflect_multiplier;
                float transmission_multiplier = 1 - reflect_multiplier;

                // Reflect if its worth it
                if (reflect_multiplier > Constants.EPSILON)
                {
                    Ray  reflRay     = RayTrans.Reflect(ray, hit);
                    uint takeSamples = 0;
                    if (hit.Obj.Material.Roughness > 0.001f && ray.Refldepth <= 1)
                    {
                        takeSamples = Settings.MaxReflectionSamples;
                    }
                    else
                    {
                        takeSamples = 1;
                    }
                    //Take many samples for rough reflections
                    for (int i = 0; i < takeSamples; i++)
                    {
                        Ray localRay = reflRay;
                        localRay.Direction = RRandom.RandomChange(reflRay.Direction, hit.Obj.Material.Roughness);
                        ret += reflect_multiplier * TraceRay(localRay, debug);
                    }
                    ret /= takeSamples;
                }
                if (transmission_multiplier > Constants.EPSILON)
                {
                    if (hit.Obj.Material.IsRefractive)
                    {
                        var tmp_ray = RayTrans.Refract(ray, hit);
                        if (!float.IsNaN(tmp_ray.Direction.X)) // Happens rarely
                        {
                            ret += transmission_multiplier * traceRayInside(tmp_ray, hit.Obj, debug);
                        }
                    }
                    else
                    {
                        ret += transmission_multiplier * color;
                    }
                }
            }
            else
            {
                // Standard diffuse
                ret = color;
            }

            return(ret + specular);
        }