﻿     1→-- Economy + crafting settings of the ornament machine (shared by server and client).
     2→-- Design: docs/economy_design.md. ONE resource: shards. A toy's worth = the shards the shredder gives for it.
     3→-- Change numbers here, not in the logic.
     4→local Config = {}
     5→
     6→---------------------------------------------------------------- admins (admin panel: AdminPanel / OrnamentAdminServer)
     7→-- The game belongs to a group: every member of THAT group with rank >= ADMIN_GROUP.MinRank gets the panel
     8→-- (group -> Configure -> Roles: the number next to a role is its rank; Owner = 255). Give the developers' role a
     9→-- rank >= MinRank or lower MinRank to it. ADMIN_GROUP.Id = another group's id instead of the owning one.
    10→-- ADMINS: extra single UserIds (anyone, also outside the group). In Studio every tester is an admin.
    11→Config.ADMIN_GROUP = { MinRank = 254 }
    12→Config.ADMINS = {
    13→	[11925419606] = true,
    14→}
    15→
    16→---------------------------------------------------------------- crafting grid
    17→Config.GRID_SIZE = 4
    18→Config.SLOT_COUNT = Config.GRID_SIZE * Config.GRID_SIZE
    19→Config.MIN_SHARDS = 8                 -- minimum CELLS in the grid (tier 1: 8 shards, tier 5: 8 x 2 = 16 shards)
    20→Config.LUCK_PER_SHARD = 0.25          -- per extra cell: 8 cells = x1, 12 = x2, 16 = x3
    21→Config.LUCK_TIER_EXP = 0.25           -- luck boosts higher rarities more: weight * luck^(k * (tier - 1))
    22→
    23→---------------------------------------------------------------- shards: free regeneration
    24→Config.REGEN_SECONDS = 45             -- +1 shard every 45 s ...
    25→Config.REGEN_CAP = 60                 -- ... while the player has fewer than 60 (recycling can go above)
    26→
    27→-- TEST ONLY: every profile is topped up (once) to at least this many shards on load. nil = off (release).
    28→Config.TEST_MIN_SHARDS = nil
    29→
    30→Config.STARTER = {
    31→	Shards = 100,                      -- shards of a new player
    32→	Boosters = { Luck2 = 2, Luck3 = 1 },
    33→}
    34→
    35→---------------------------------------------------------------- rarities ("level" of a toy)
    36→-- Shards = base worth of the rarity: what the shredder gives back (x toy multiplier x variant)
    37→-- Xp     = extra XP for rolling it
    38→Config.RARITIES = {
    39→	{ Id = "Common",    Name = "Common",     Weight = 60,  Shards = 2,   Xp = 0,   Color = Color3.fromRGB(205, 210, 220) },
    40→	{ Id = "Uncommon",  Name = "Uncommon",   Weight = 25,  Shards = 4,   Xp = 2,   Color = Color3.fromRGB(95, 215, 115) },
    41→	{ Id = "Rare",      Name = "Rare",      Weight = 10,  Shards = 9,   Xp = 5,   Color = Color3.fromRGB(75, 155, 255) },
    42→	{ Id = "Epic",      Name = "Epic",   Weight = 4,   Shards = 22,  Xp = 15,  Color = Color3.fromRGB(180, 95, 255) },
    43→	{ Id = "Legendary", Name = "Legendary", Weight = 0.9, Shards = 70,  Xp = 40,  Color = Color3.fromRGB(255, 180, 45) },
    44→	{ Id = "Mythic",    Name = "Mythic",  Weight = 0.1, Shards = 300, Xp = 120, Color = Color3.fromRGB(255, 65, 95) },
    45→}
    46→-- a generated toy of these rarities is announced to everyone on the server
    47→Config.ANNOUNCE_RARITIES = { Legendary = true, Mythic = true }
    48→Config.RarityById = {}
    49→for i, r in Config.RARITIES do
    50→	r.Index = i
    51→	Config.RarityById[r.Id] = r
    52→end
    53→
    54→-- bad-luck protection: after N rolls without this tier (or better) the next roll is at least this tier
    55→Config.PITY = {
    56→	{ Rarity = "Epic", Rolls = 40 },
    57→	{ Rarity = "Legendary", Rolls = 250 },
    58→	{ Rarity = "Mythic", Rolls = 1500 },
    59→}
    60→
    61→-- rare variants on top of rarity (pure lottery, not affected by luck)
    62→Config.VARIANTS = {
    63→	{ Id = "Golden", Name = "Golden", Chance = 1 / 1000, Mult = 10, Color = Color3.fromRGB(255, 205, 60) },
    64→	{ Id = "Shiny",  Name = "Shiny", Chance = 1 / 50,   Mult = 3,  Color = Color3.fromRGB(170, 240, 255) },
    65→	-- never rolled (Chance 0): only fusion gives it. Being a variant, it can not be fused again.
    66→	{ Id = "Fused",  Name = "Fused",  Chance = 0,        Mult = 3,  Color = Color3.fromRGB(255, 120, 220) },
    67→}
    68→Config.VariantById = {}
    69→for _, v in Config.VARIANTS do Config.VariantById[v.Id] = v end
    70→
    71→Config.BOOSTERS = {
    72→	Luck2 = { Name = "Luck x2", Luck = 2, Order = 1, Color = Color3.fromRGB(95, 215, 115) },
    73→	Luck3 = { Name = "Luck x3", Luck = 3, Order = 2, Color = Color3.fromRGB(255, 180, 45) },
    74→}
    75→Config.BOOSTER_MIGRATE = { Luck5 = "Luck3" }   -- old ids from the first prototype
    76→
    77→---------------------------------------------------------------- tiers ("farming levels") + toys
    78→-- The generator works on ONE tier at a time (player picks it). Tier N+1 opens at player Level AND after
    79→-- Need different toys of tier N were discovered (any rarity). Mult = value multiplier of its toys,
    80→-- CellCost = shards per grid cell (min 8 cells: 8 / 10 / 12 / 14 / 16 shards). Add a tier = add a row + 50 toys.
    81→Config.TOYS_PER_TIER = 50
    82→Config.TIERS = {
    83→	{ Id = 1, Name = "Tier 1", Level = 1,  Need = 0,  Mult = 1,   CellCost = 1,    Color = Color3.fromRGB(120, 220, 140) },
    84→	{ Id = 2, Name = "Tier 2", Level = 12, Need = 20, Mult = 1.6, CellCost = 1.25, Color = Color3.fromRGB(90, 190, 255) },
    85→	{ Id = 3, Name = "Tier 3", Level = 20, Need = 25, Mult = 2.5, CellCost = 1.5,  Color = Color3.fromRGB(190, 120, 255) },
    86→	{ Id = 4, Name = "Tier 4", Level = 30, Need = 30, Mult = 4,   CellCost = 1.75, Color = Color3.fromRGB(255, 185, 60) },
    87→	{ Id = 5, Name = "Tier 5", Level = 40, Need = 35, Mult = 6,   CellCost = 2,    Color = Color3.fromRGB(255, 80, 110) },
    88→}
    89→Config.TOYS = {}
    90→Config.ToyById = {}
    91→Config.ToysByTier = {}
    92→for i, row in require(script.Parent:WaitForChild("ToyCatalog")) do
    93→	local tier = math.ceil(i / Config.TOYS_PER_TIER)
    94→	if not Config.TIERS[tier] then break end
    95→	local t = { Id = row[1], Name = row[2], Tier = tier, Index = i }
    96→	Config.TOYS[i] = t
    97→	Config.ToyById[t.Id] = t
    98→	Config.ToysByTier[tier] = Config.ToysByTier[tier] or {}
    99→	table.insert(Config.ToysByTier[tier], t)
   100→end
   101→
   102→-- blinking pattern: every PATTERN_PERIOD seconds the generator flashes a reference pattern (same on server and
   103→-- client: seeded by the period number of the server clock). Repeating it raises luck: match < MIN = x1,
   104→-- full match = x PATTERN_MAX_LUCK (linear in between). The server accepts the current or previous period.
   105→Config.PATTERN_PERIOD = 10
   106→Config.PATTERN_CELLS = { 8, 12 }
   107→Config.PATTERN_MIN_MATCH = 0.5
   108→Config.PATTERN_MAX_LUCK = 1.5
   109→
   110→---------------------------------------------------------------- shredder
   111→Config.MAX_ORNAMENTS = 300
   112→Config.MAX_RECYCLE = 50
   113→Config.BATCH_SIZE = 5                 -- 5+ toys of the same kind in one run ...
   114→Config.BATCH_BONUS = 0.2              -- ... give +20% shards for those toys
   115→
   116→---------------------------------------------------------------- player level
   117→Config.MAX_LEVEL = 50
   118→Config.XP = { Generate = 20, Recycle = 1, Discover = 25 }
   119→function Config.XpToNext(level)
   120→	return math.floor(25 * level ^ 1.5)
   121→end
   122→function Config.LevelReward(level)
   123→	local r = { Shards = 15 + 5 * level, Boosters = {} }
   124→	if level % 10 == 0 then
   125→		r.Boosters.Luck3 = 1
   126→	elseif level % 5 == 0 then
   127→		r.Boosters.Luck2 = 1
   128→	end
   129→	return r
   130→end
   131→
   132→---------------------------------------------------------------- phase 2: workshop (all paid in shards)
   133→-- upgrades: cost of the next level = floor(Base * Growth ^ currentLevel)
   134→Config.UPGRADES = {
   135→	{ Id = "Luck",     Name = "Generator Luck", Max = 10, Base = 40, Growth = 1.6, Step = 0.08,
   136→	  Desc = "+8% luck on every generation" },
   137→	{ Id = "Regen",    Name = "Shard Regen",   Max = 10, Base = 30, Growth = 1.6, Step = 6,
   138→	  Desc = "+6 regen cap and 5% faster regen" },
   139→	{ Id = "Shredder", Name = "Shredder Power", Max = 10, Base = 50, Growth = 1.6, Step = 0.05,
   140→	  Desc = "+5% shards from recycling" },
   141→	{ Id = "Storage",  Name = "Toy Storage",    Max = 8,  Base = 25, Growth = 1.6, Step = 50,
   142→	  Desc = "+50 inventory slots" },
   143→}
   144→Config.UpgradeById = {}
   145→for i, u in Config.UPGRADES do
   146→	u.Order = i
   147→	Config.UpgradeById[u.Id] = u
   148→end
   149→function Config.UpgradeCost(id, level)
   150→	local u = Config.UpgradeById[id]
   151→	if not u or level >= u.Max then return nil end
   152→	return math.floor(u.Base * u.Growth ^ level)
   153→end
   154→function Config.LuckMult(level) return 1 + Config.UpgradeById.Luck.Step * (level or 0) end
   155→function Config.RegenCap(level) return Config.REGEN_CAP + Config.UpgradeById.Regen.Step * (level or 0) end
   156→function Config.RegenSeconds(level) return Config.REGEN_SECONDS * (0.95 ^ (level or 0)) end
   157→function Config.ShredderMult(level) return 1 + Config.UpgradeById.Shredder.Step * (level or 0) end
   158→function Config.StorageCap(level) return Config.MAX_ORNAMENTS + Config.UpgradeById.Storage.Step * (level or 0) end
   159→
   160→-- fusion: FUSION_COUNT identical toys (same kind + rarity, no special variant) + shards -> 1 "Fused" toy one rarity
   161→-- higher (variant Mult x4). Worth a bit MORE than its inputs (Ball: 5x2 + 4 = 14 -> 16, Rare 5x9 + 30 = 75 -> 88),
   162→-- and a Fused toy is a variant, so it can never be fused again (no chain up to Mythic).
   163→-- NEW: the result is a random toy of the NEXT tier with the same rarity (tag Fused). On the last tier the rarity
   164→-- goes up instead. Fee = FUSION_COST[rarity] x tier Mult. Fused toys can be sold instantly on the market for
   165→-- QUICK_SELL x the shards spent on them (Cost).
   166→Config.FUSION_COUNT = 5
   167→Config.FUSION_COST = { Common = 4, Uncommon = 10, Rare = 30, Epic = 120, Legendary = 600, Mythic = 2500 }
   168→Config.QUICK_SELL = 1.01
   169→Config.XP.Fuse = 10
   170→
   171→-- booster recipes
   172→Config.BOOSTER_COST = { Luck2 = 60, Luck3 = 150 }
   173→
   174→---------------------------------------------------------------- phase 3: trading
   175→Config.TRADE = {
   176→	MIN_LEVEL = 5,          -- both players
   177→	MAX_ITEMS = 8,          -- toys per side
   178→	TAX = 0.05,             -- shards passed in a trade lose 5% (sink)
   179→	MIN_AGE = 600,          -- toys younger than 10 minutes can not be traded (anti-dupe after a crash)
   180→	COUNTDOWN = 5,          -- seconds between "both ready" and "confirm"
   181→	REQUEST_TTL = 15,       -- seconds to accept a request
   182→	COOLDOWN = 10,          -- seconds between two trades of one player
   183→	PER_HOUR = 20,          -- trades per player per hour
   184→	WARN_RATIO = 3,         -- warn when one side is worth more than 3x the other
   185→}
   186→
   187→---------------------------------------------------------------- phase 5: cross-server market
   188→Config.MARKET = {
   189→	MIN_LEVEL = 10,             -- to list or buy
   190→	MAX_LISTINGS = 10,          -- active listings per player
   191→	TAX = 0.10,                 -- the seller gets the price minus 10% (sink)
   192→	DURATION = 3 * 24 * 3600,   -- a listing lives 3 days, then the toy goes back to the seller
   193→	MAX_PRICE = 1000000,
   194→	PAGE = 60,                  -- listings shown per browse request
   195→	-- NPC seller: keeps the market from looking empty. Its lots live only on this server (not in MemoryStore),
   196→	-- fill the gap up to TARGET real+bot lots and give way to players as they list. Price is always above the
   197→	-- shredder value (MARKUP x Value), so buying from the bot and shredding is never profitable.
   198→	BOT = {
   199→		TARGET = 14,                                   -- visible lots the market aims for (real + bot)
   200→		RESTOCK = 20,                                  -- seconds between bot updates (one lot added/removed per tick)
   201→		LIFE = { 10 * 60, 35 * 60 },                   -- a bot lot lives this long (seconds), then disappears
   202→		MARKUP = { 1.8, 3.2 },                         -- price = shredder value x random markup
   203→		RARITY = { Common = 42, Uncommon = 30, Rare = 18, Epic = 8, Legendary = 2 },
   204→		TIER = { 55, 25, 12, 6, 2 },                    -- weights of the tiers of bot lots
   205→		SHINY = 0.04,                                  -- chance of a Shiny variant
   206→		NAMES = { "Santa's Stall", "Elf Trader", "Gingerbread Gnome", "Bob the Snowman", "Snow Maiden's Stall" },
   207→	},
   208→}
   209→-- minimum price = what the shredder would pay (no point in selling cheaper)
   210→function Config.MinPrice(item) return math.max(1, Config.Value(item)) end
   211→
   212→---------------------------------------------------------------- shop: decorations for the player's plot (paid in shards)
   213→-- Model = ReplicatedStorage.OrnamentMachine.Decor/<Model>; Offset = position on the plot (plot space, +Z = front)
   214→Config.SHOP = {
   215→	{ Id = "Tree",      Name = "Christmas Tree", Price = 400, Model = "ChristmasTree", Offset = CFrame.new(-9, 0, -7),
   216→	  Desc = "A tall fluffy tree. Decorate it with your ornaments." },
   217→	{ Id = "PullUpBar", Name = "Pull-up Bar",          Price = 150, Model = "PullUpBar",     Offset = CFrame.new(9, 0, -8),
   218→	  Desc = "XP for every pull-up, +1 shard per 10 in a row. Up to 60 per set, then a 10 min rest." },
   219→	{ Id = "Bench",     Name = "Bench Press", Price = 250, Model = "BenchPress",  Offset = CFrame.new(9, 0, 4) * CFrame.Angles(0, math.rad(-90), 0),
   220→	  Desc = "A press bench and a loaded barbell." },
   221→	{ Id = "Fireworks", Name = "Fireworks",           Price = 200, Model = "Fireworks",     Offset = CFrame.new(-9, 0, 7),
   222→	  Desc = "A fireworks launcher. Walk up and launch it — everyone will see the show." },
   223→	-- OnTree: not placed on the plot but strung on the player's placed tree by clicking points on it
   224→	-- (Config.GARLAND limits; no footprint, follows the tree when it is moved, comes off when the tree is stored)
   225→	{ Id = "Garland",   Name = "Tree Garland", Price = 250, Model = "TreeGarland", OnTree = true, Offset = CFrame.new(),
   226→	  Desc = "Colorful lights. Wrap the tree yourself — click on it point by point." },
   227→	-- Craft: not sold in the shop, made in the Craft House (Config.CRAFTS). AroundTree: may stand centred on the tree
   228→	-- (the ring goes round the trunk) — the only allowed overlap.
   229→	{ Id = "Train",     Name = "Christmas Train", Price = 0, Model = "ChristmasTrain", Craft = true, AroundTree = true, Offset = CFrame.new(),
   230→	  Half = { 6.3, 6.3 },     -- footprint of the round track (the mesh boxes overestimate it)
   231→	  Desc = "A little steam train that runs round its track. Put it around your tree!" },
   232→}
   233→-- garland: the player clicks points on the tree, the wire goes through them (points stored in tree space)
   234→Config.GARLAND = {
   235→	MAX_POINTS = 60,      -- clicks per garland
   236→	MAX_LENGTH = 120,     -- studs of wire
   237→	BULB_STEP = 1.1,      -- a bulb every N studs
   238→	MAX_LIGHTS = 24,      -- PointLights per garland (every 4th bulb)
   239→	BOUNDS = { X = 7, YMIN = 0, YMAX = 27, Z = 7 },   -- points must be on / near the tree
   240→}
   241→Config.ShopById = {}
   242→for k, it in Config.SHOP do it.Order = k; Config.ShopById[it.Id] = it end
   243→
   244→---------------------------------------------------------------- Craft House: plot items made from toys
   245→-- (the UI groups lines of the same tier + rarity into one row)
   246→-- Recipe line = one specific toy (Toy id) of a rarity, any variant (without Toy: any toy of that tier). The server takes the cheapest fitting
   247→-- toys (by shredder value) that are not on the tree. Unlimited crafts: one stands on the plot, the rest wait in
   248→-- the inventory or are sold on the market (min price = Value = the shredder value of the ingredients).
   249→Config.CRAFTS = {
   250→	{ Id = "Train", Name = "Christmas Train", Icon = "🚂", Xp = 60,
   251→	  Desc = "A steam engine with two gift wagons. It runs round its track — put it around your Christmas tree!",
   252→	  Recipe = {
   253→		{ Toy = "001", Tier = 1, Rarity = "Epic", Count = 1 },        -- Red Bauble
   254→		{ Toy = "006", Tier = 1, Rarity = "Epic", Count = 1 },        -- Gold Star
   255→		{ Toy = "017", Tier = 1, Rarity = "Epic", Count = 1 },        -- Red Gift
   256→		{ Toy = "075", Tier = 2, Rarity = "Epic", Count = 1 },        -- Green Train
   257→		{ Toy = "059", Tier = 2, Rarity = "Epic", Count = 1 },        -- Green Gift
   258→		{ Toy = "030", Tier = 1, Rarity = "Legendary", Count = 1 },   -- Toy Train
   259→		{ Toy = "095", Tier = 2, Rarity = "Legendary", Count = 1 },   -- Sled
   260→	  } },
   261→}
   262→Config.CraftById = {}
   263→for k, c in Config.CRAFTS do
   264→	c.Order = k
   265→	local v = 0
   266→	for _, ing in c.Recipe do
   267→		v += Config.RarityById[ing.Rarity].Shards * Config.TIERS[ing.Tier].Mult * ing.Count
   268→	end
   269→	c.Value = math.floor(v + 0.5)
   270→	Config.CraftById[c.Id] = c
   271→end
   272→-- does a toy (item = { Toy, Rarity }) fit a recipe line?
   273→function Config.CraftFits(ing, item)
   274→	local t = Config.ToyById[item.Toy]
   275→	if ing.Toy and item.Toy ~= ing.Toy then return false end
   276→	return t ~= nil and t.Tier == ing.Tier and item.Rarity == ing.Rarity
   277→end
   278→-- picks the toys for a craft from `items` = { { uid, Toy, Rarity, Variant, OnTree } }: cheapest first, never toys
   279→-- on the tree. Returns { [lineIndex] = { item, ... } }, complete (true when every line is filled)
   280→function Config.CraftPick(craftId, items)
   281→	local c = Config.CraftById[craftId]
   282→	if not c then return {}, false end
   283→	local used, out, complete = {}, {}, true
   284→	for i, ing in c.Recipe do
   285→		local list = {}
   286→		for _, it in items do
   287→			if not it.OnTree and not used[it.uid] and Config.CraftFits(ing, it) then table.insert(list, it) end
   288→		end
   289→		table.sort(list, function(a, b)
   290→			local va, vb = Config.Value(a), Config.Value(b)
   291→			if va ~= vb then return va < vb end
   292→			return (tonumber(a.uid) or 0) < (tonumber(b.uid) or 0)
   293→		end)
   294→		out[i] = {}
   295→		for k = 1, math.min(ing.Count, #list) do
   296→			used[list[k].uid] = true
   297→			table.insert(out[i], list[k])
   298→		end
   299→		if #out[i] < ing.Count then complete = false end
   300→	end
   301→	return out, complete
   302→end
   303→Config.FIREWORKS_COOLDOWN = 15
   304→-- pull-up bar: one rep every RepSeconds gives XpPerRep experience (XP / level rewards like the generator);
   305→-- every ShardEvery reps in a row (one session on the bar, without getting off) give ShardReward shards
   306→-- MaxReps per session; after reaching it the bar is locked for that player for RestSeconds
   307→Config.PULLUP = { RepSeconds = 1.6, XpPerRep = 1, ShardEvery = 10, ShardReward = 1, MaxReps = 60, RestSeconds = 600 }
   308→-- placement on the plot (shared by server validation and the client's ghost preview)
   309→-- half extents (x, z) of a decoration around its pivot, from the template in OrnamentMachine.Decor
   310→local halfCache = {}
   311→function Config.DecorHalf(id)
   312→	if halfCache[id] then return halfCache[id][1], halfCache[id][2] end
   313→	local item = Config.ShopById[id]
   314→	if item and item.Half then return item.Half[1], item.Half[2] end
   315→	local decor = script.Parent and script.Parent:FindFirstChild("Decor")
   316→	local tpl = item and decor and decor:FindFirstChild(item.Model)
   317→	if not tpl then return 2, 2 end
   318→	local pivot = tpl:GetPivot()
   319→	local hx, hz = 0.5, 0.5
   320→	for _, p in tpl:GetDescendants() do
   321→		if p:IsA("BasePart") and p.Name ~= "Base" then
   322→			local cf = pivot:ToObjectSpace(p.CFrame)
   323→			local s = p.Size
   324→			local ex = math.abs(cf.RightVector.X) * s.X + math.abs(cf.UpVector.X) * s.Y + math.abs(cf.LookVector.X) * s.Z
   325→			local ez = math.abs(cf.RightVector.Z) * s.X + math.abs(cf.UpVector.Z) * s.Y + math.abs(cf.LookVector.Z) * s.Z
   326→			hx = math.max(hx, math.abs(cf.X) + ex / 2)
   327→			hz = math.max(hz, math.abs(cf.Z) + ez / 2)
   328→		end
   329→	end
   330→	halfCache[id] = { hx, hz }
   331→	return hx, hz
   332→end
   333→
   334→-- footprint half extents for a rotation step r (0..3 = 0/90/180/270 degrees)
   335→function Config.DecorFootprint(id, r)
   336→	local hx, hz = Config.DecorHalf(id)
   337→	if (r or 0) % 2 == 1 then return hz, hx end
   338→	return hx, hz
   339→end
   340→
   341→-- can `id` stand at plot-space (x, z) with rotation r? placements = { [otherId] = { X, Z, R } }
   342→-- AroundTree items (the train) may stand exactly centred on the tree: the ring goes round the trunk
   343→function Config.AroundTreeOk(a, ax, az, b, bx, bz)
   344→	local A, B = Config.ShopById[a], Config.ShopById[b]
   345→	local pair = (A and A.AroundTree and b == "Tree") or (B and B.AroundTree and a == "Tree")
   346→	return pair and math.abs(ax - bx) <= 0.5 and math.abs(az - bz) <= 0.5
   347→end
   348→-- placement area of a plot (plot space, x / z): the fenced plot itself + the snowy pad in front of the owner's name
   349→-- board (NameBoard at x 12.7, z 19.9, facing +z). The SAME area on every plot: zones are handed out at random and
   350→-- placements are saved in plot space, so a spot must be free on every zone. The pad stops at z 39.5 because zones 4
   351→-- and 10 have a prebuilt house (shop / Craft House) further up their pad (house front at z ~41).
   352→Config.PLOT_MARGIN = 0.25
   353→Config.PLOT_PAD = { { 6.5, 21 }, { 28, 21 }, { 33.5, 30 }, { 31.5, 37 }, { 29.3, 39.5 }, { 6.5, 39.5 } }
   354→function Config.PlotPad() return Config.PLOT_PAD end
   355→local function inPolygon(poly, x, z)
   356→	local inside, j = false, #poly
   357→	for i = 1, #poly do
   358→		local xi, zi, xj, zj = poly[i][1], poly[i][2], poly[j][1], poly[j][2]
   359→		if (zi > z) ~= (zj > z) and x < (xj - xi) * (z - zi) / (zj - zi) + xi then inside = not inside end
   360→		j = i
   361→	end
   362→	return inside
   363→end
   364→-- plot = the plot part or its Size
   365→function Config.InPlotArea(plot, x, z)
   366→	local size = typeof(plot) == "Instance" and plot.Size or plot
   367→	local m = Config.PLOT_MARGIN
   368→	if math.abs(x) <= size.X / 2 - m and math.abs(z) <= size.Z / 2 - m then return true end
   369→	return inPolygon(Config.PLOT_PAD, x, z)
   370→end
   371→-- is the whole footprint (centre x, z, half extents fx, fz) inside the area? Samples the rectangle every ~1 stud
   372→-- (edges + inside), so it can't straddle the gap between the plot and the pad.
   373→function Config.FootprintInArea(plot, x, z, fx, fz)
   374→	local nx, nz = math.max(1, math.ceil(fx * 2)), math.max(1, math.ceil(fz * 2))
   375→	for i = 0, nx do
   376→		for k = 0, nz do
   377→			if not Config.InPlotArea(plot, x - fx + 2 * fx * i / nx, z - fz + 2 * fz * k / nz) then return false end
   378→		end
   379→	end
   380→	return true
   381→end
   382→-- plot = the plot part or its Size
   383→function Config.DecorFits(plot, placements, id, x, z, r)
   384→	if Config.ShopById[id] and Config.ShopById[id].OnTree then return true end      -- lives on the tree
   385→	local fx, fz = Config.DecorFootprint(id, r)
   386→	if not Config.FootprintInArea(plot, x, z, fx, fz) then
   387→		return false, "Only inside the green area"
   388→	end
   389→	for other, pl in placements do
   390→		if other ~= id and type(pl) == "table" and not (Config.ShopById[other] and Config.ShopById[other].OnTree)
   391→			and not Config.AroundTreeOk(id, x, z, other, pl.X, pl.Z) then
   392→			local ox, oz = Config.DecorFootprint(other, pl.R)
   393→			if math.abs(x - pl.X) < fx + ox and math.abs(z - pl.Z) < fz + oz then
   394→				return false, "Blocked by: " .. Config.ShopById[other].Name
   395→			end
   396→		end
   397→	end
   398→	return true
   399→end
   400→
   401→---------------------------------------------------------------- premium shop (Robux, Developer Products)
   402→-- ProductId = the Developer Product id from the Creator Dashboard (0 = not set up yet: the card shows "скоро").
   403→-- Robux = fallback price only: the client shows the player's regional price from GetProductInfo (managed pricing).
   404→-- Robux is only shown in the UI; the real price is the one set on the product itself.
   405→Config.PREMIUM = {
   406→	{ Id = "Shards100",  Kind = "Shards",  Amount = 100,  Name = "Handful of Shards",   Robux = 30,  ProductId = 3732431258 },
   407→	{ Id = "Shards500",  Kind = "Shards",  Amount = 500,  Name = "Bag of Shards",    Robux = 132, ProductId = 3732431774, Tag = "+25% value" },
   408→	{ Id = "Shards1200", Kind = "Shards",  Amount = 1200, Name = "Chest of Shards",   Robux = 271, ProductId = 3732432053, Tag = "+50% value" },
   409→	{ Id = "Shards3000", Kind = "Shards",  Amount = 3000, Name = "Mountain of Shards",     Robux = 620, ProductId = 3732432975, Tag = "best value" },
   410→	{ Id = "Luck2x3",    Kind = "Booster", Booster = "Luck2", Amount = 3, Name = "3 × Luck x2", Robux = 63, ProductId = 3732434260 },
   411→	{ Id = "Luck3x3",    Kind = "Booster", Booster = "Luck3", Amount = 3, Name = "3 × Luck x3", Robux = 132, ProductId = 3732434667 },
   412→}
   413→Config.PremiumById, Config.PremiumByProduct = {}, {}
   414→for k, p in Config.PREMIUM do
   415→	p.Order = k
   416→	Config.PremiumById[p.Id] = p
   417→	if p.ProductId ~= 0 then Config.PremiumByProduct[p.ProductId] = p end
   418→end
   419→
   420→---------------------------------------------------------------- promo codes (OrnamentPromo, admin panel)
   421→-- Codes are created in the admin panel and redeemed in Settings -> Codes. Everything is checked on the server.
   422→Config.PROMO = {
   423→	TRIES = 3, WINDOW = 300,      -- a player may submit at most 3 codes per 5 minutes (any result counts)
   424→	MAX_LEN = 20,                 -- code: 3..20 of A-Z 0-9 _ - (case-insensitive, stored in upper case)
   425→	MAX_USES = 1000000,
   426→	MAX_SHARDS = 1000000,
   427→	MAX_BOOSTERS = 100,
   428→}
   429→
   430→---------------------------------------------------------------- VIP game pass
   431→-- PassId = the VIP Game Pass id from the Creator Dashboard (0 = not set up yet: nobody is VIP outside Studio tests).
   432→-- The server sets the player attribute "VIP" = true; every bonus below is permanent while the pass is owned.
   433→Config.VIP = {
   434→	PassId = 2089673529,
   435→	Price = 1000,     -- fallback price only: the shop shows the regional price from GetProductInfo
   436→	Luck = 1.5,       -- generator luck multiplier (stacks with everything else)
   437→	Shredder = 1.25,  -- shards from the shredder
   438→	XP = 1.5,         -- all experience
   439→}
   440→function Config.VipMult(isVip, key) return isVip and Config.VIP[key] or 1 end
   441→
   442→---------------------------------------------------------------- formulas
   443→-- luckLevel = the player's "Удача генератора" upgrade level
   444→-- cells = filled grid cells, patternMult = Config.PatternLuck(match)
   445→function Config.Luck(cells, boosterId, luckLevel, patternMult, isVip)
   446→	if cells < Config.MIN_SHARDS then return 0 end
   447→	local luck = (1 + (cells - Config.MIN_SHARDS) * Config.LUCK_PER_SHARD) * Config.LuckMult(luckLevel) * (patternMult or 1) * Config.VipMult(isVip, "Luck")
   448→	local b = boosterId and Config.BOOSTERS[boosterId]
   449→	if b then luck *= b.Luck end
   450→	return luck
   451→end
   452→
   453→-- shards for `cells` grid cells on a tier
   454→function Config.GenCost(cells, tier)
   455→	local t = Config.TIERS[tier] or Config.TIERS[1]
   456→	return math.max(0, math.ceil(cells * t.CellCost - 1e-6))
   457→end
   458→
   459→-- tiers: number of different toys of `tier` in a Discovered set ({ ["Toy|Rarity"] = true })
   460→function Config.TierFound(discovered, tier)
   461→	local seen, n = {}, 0
   462→	for key in discovered or {} do
   463→		local t = Config.ToyById[(tostring(key):match("^([^|]+)"))]
   464→		if t and t.Tier == tier and not seen[t.Id] then seen[t.Id] = true; n += 1 end
   465→	end
   466→	return n
   467→end
   468→-- highest tier the player can generate
   469→function Config.MaxTier(level, discovered)
   470→	local max = 1
   471→	for i = 2, #Config.TIERS do
   472→		local t = Config.TIERS[i]
   473→		if (level or 1) >= t.Level and Config.TierFound(discovered, i - 1) >= t.Need then max = i else break end
   474→	end
   475→	return max
   476→end
   477→
   478→-- reference pattern of a period (16-char "0101.." mask)
   479→function Config.PatternPeriod(serverTime) return math.floor(serverTime / Config.PATTERN_PERIOD) end
   480→function Config.PatternAt(period)
   481→	local r = Random.new(period * 7919 + 104729)
   482→	local n = r:NextInteger(Config.PATTERN_CELLS[1], Config.PATTERN_CELLS[2])
   483→	local cells = {}
   484→	for i = 1, Config.SLOT_COUNT do cells[i] = i end
   485→	local on = table.create(Config.SLOT_COUNT, "0")
   486→	for k = 1, n do
   487→		local j = r:NextInteger(k, Config.SLOT_COUNT)
   488→		cells[k], cells[j] = cells[j], cells[k]
   489→		on[cells[k]] = "1"
   490→	end
   491→	return table.concat(on)
   492→end
   493→function Config.Similarity(a, b)
   494→	local inter, union = 0, 0
   495→	for i = 1, math.min(#a, #b) do
   496→		local x, y = a:sub(i, i) == "1", b:sub(i, i) == "1"
   497→		if x and y then inter += 1 end
   498→		if x or y then union += 1 end
   499→	end
   500→	return union == 0 and 0 or inter / union
   501→end
   502→function Config.PatternLuck(match)
   503→	if match < Config.PATTERN_MIN_MATCH then return 1 end
   504→	return 1 + (Config.PATTERN_MAX_LUCK - 1) * (match - Config.PATTERN_MIN_MATCH) / (1 - Config.PATTERN_MIN_MATCH)
   505→end
   506→-- best match of a grid against the pattern of this or the previous period
   507→function Config.PatternMatch(slots, serverTime)
   508→	local p = Config.PatternPeriod(serverTime)
   509→	return math.max(Config.Similarity(slots, Config.PatternAt(p)), Config.Similarity(slots, Config.PatternAt(p - 1)))
   510→end
   511→
   512→function Config.Chances(luck)
   513→	luck = math.max(luck or 1, 1)
   514→	local w, total = {}, 0
   515→	for i, r in Config.RARITIES do
   516→		w[i] = r.Weight * luck ^ (Config.LUCK_TIER_EXP * (i - 1))
   517→		total += w[i]
   518→	end
   519→	for i in w do w[i] /= total end
   520→	return w
   521→end
   522→
   523→-- rolls a rarity; minIndex (pity) forces at least that tier (re-normalised over the allowed tiers)
   524→function Config.Roll(luck, rng, minIndex)
   525→	minIndex = minIndex or 1
   526→	local ch = Config.Chances(luck)
   527→	local total = 0
   528→	for i = minIndex, #ch do total += ch[i] end
   529→	local x = (rng or Random.new()):NextNumber() * total
   530→	local acc = 0
   531→	for i = minIndex, #ch do
   532→		acc += ch[i]
   533→		if x <= acc then return Config.RARITIES[i] end
   534→	end
   535→	return Config.RARITIES[#ch]
   536→end
   537→
   538→function Config.RollVariant(rng)
   539→	local x = (rng or Random.new()):NextNumber()
   540→	local acc = 0
   541→	for _, v in Config.VARIANTS do
   542→		acc += v.Chance
   543→		if x <= acc then return v end
   544→	end
   545→	return nil
   546→end
   547→
   548→-- a random toy of a tier (all 50 equally likely)
   549→function Config.RollToy(tier, rng)
   550→	local list = Config.ToysByTier[tier] or Config.ToysByTier[1]
   551→	return list[(rng or Random.new()):NextInteger(1, #list)]
   552→end
   553→
   554→-- fusion of 5 x (toy, rarity): fee, result tier, result rarity (nil = can not be fused)
   555→function Config.FusionInfo(toyId, rarityId)
   556→	local t, r = Config.ToyById[toyId], Config.RarityById[rarityId]
   557→	if not t or not r then return nil end
   558→	local tier, rarity = t.Tier + 1, r
   559→	if not Config.TIERS[tier] then
   560→		tier, rarity = t.Tier, Config.RARITIES[r.Index + 1]
   561→		if not rarity then return nil end
   562→	end
   563→	local fee = math.floor(Config.FUSION_COST[r.Id] * Config.TIERS[t.Tier].Mult + 0.5)
   564→	return fee, tier, rarity
   565→end
   566→
   567→-- instant system buyout on the market (Fused toys only): shards spent on it + 1%
   568→function Config.QuickSellPrice(item)
   569→	if item.Variant ~= "Fused" or type(item.Cost) ~= "number" or item.Cost <= 0 then return nil end
   570→	return math.ceil(item.Cost * Config.QUICK_SELL)
   571→end
   572→
   573→function Config.ToyTier(toyId)
   574→	local t = Config.ToyById[toyId]
   575→	return t and Config.TIERS[t.Tier]
   576→end
   577→
   578→-- shards one toy is worth (item = { Toy, Rarity, Variant }); the shredder pays exactly this
   579→function Config.Value(item)
   580→	if item.Craft then
   581→		local c = Config.CraftById[item.Craft]
   582→		return c and c.Value or 0
   583→	end
   584→	local r, t = Config.RarityById[item.Rarity], Config.ToyById[item.Toy]
   585→	if not r or not t then return 0 end
   586→	local v = item.Variant and Config.VariantById[item.Variant]
   587→	return math.max(1, math.floor(r.Shards * Config.TIERS[t.Tier].Mult * (v and v.Mult or 1) + 0.5))
   588→end
   589→
   590→-- shredder output for a list of items (5+ toys of the same kind in one run get the batch bonus);
   591→-- shredderLevel = the player's "Мощность шредера" upgrade level
   592→function Config.RecycleYield(items, shredderLevel, isVip)
   593→	local perToy = {}
   594→	-- "same kind" = same tier
   595→	local function kind(it) local t = Config.ToyById[it.Toy]; return t and t.Tier or 0 end
   596→	for _, it in items do perToy[kind(it)] = (perToy[kind(it)] or 0) + 1 end
   597→	local shards = 0
   598→	for _, it in items do
   599→		local s = Config.Value(it)
   600→		if perToy[kind(it)] >= Config.BATCH_SIZE then s *= 1 + Config.BATCH_BONUS end
   601→		shards += s
   602→	end
   603→	return math.floor(shards * Config.ShredderMult(shredderLevel) * Config.VipMult(isVip, "Shredder") + 0.5)
   604→end
   605→
   606→-- Discord community reward (OrnamentDiscordServer + DiscordWindow). Fill GuildId and Invite after publishing.
   607→-- The RoVer API key is NEVER stored here: put it into Creator Dashboard -> experience -> Secrets as "RoVerApiKey"
   608→-- (domain registry.rover.link). The server checks "joined the server + verified with RoVer" through the RoVer API.
   609→Config.DISCORD = {
   610→	GuildId = "1571845376296886322",                 -- Discord server id (Discord: Developer Mode -> right-click the server -> Copy Server ID)
   611→	Invite = "https://discord.gg/t8EDp4fss",                  -- shown to players as plain text, e.g. "discord.gg/abcd123" (no clickable links on Roblox)
   612→	Reward = 500,                 -- shards, once per Roblox account and once per Discord account
   613→	SecretName = "RoVerApiKey",
   614→	PromptAfter = 180,            -- seconds of play before the HUD button starts to glow for a player without the reward
   615→}
   616→
   617→return Config
   618→
