Files
Fishing/tools/build-guild-garden.lua

560 lines
21 KiB
Lua
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- Сад Гильдии (assets/props/guild_garden.bbmodel) и пасхалки: меч в камне, круглая дверь в холме, резиновая уточка.
-- Собирается tools/build-guild-garden.js, запускать в Edit ПОСЛЕ Гильдии v2 (сад в её системе координат).
-- Повторный запуск пересобирает только FishingMap.GuildGarden; то, что стояло на месте сада, — в ServerStorage.Backup.
local map = workspace:FindFirstChild("FishingMap")
assert(map, "Нет Workspace.FishingMap")
local hallModel = map:FindFirstChild("GuildHall") and map.GuildHall:FindFirstChild("GuildHallBuilding")
assert(hallModel, "Сначала соберите Гильдию v2 (tools/build-guild-hall3.js)")
local V = Vector3.new
local PIV = hallModel:GetPivot() -- та же точка и поворот, что у Гильдии
local TITLE_FONT = Font.new("rbxasset://fonts/families/Merriweather.json", Enum.FontWeight.Heavy)
local backup = game.ServerStorage:FindFirstChild("Backup") or Instance.new("Folder")
backup.Name = "Backup"
backup.Parent = game.ServerStorage
local old = map:FindFirstChild("GuildGarden")
if old then
old:Destroy()
end
local garden = Instance.new("Folder")
garden.Name = "GuildGarden"
garden.Parent = map
local function boundsOf(p)
local h = p.CFrame:VectorToWorldSpace(p.Size / 2)
h = V(math.abs(h.X), math.abs(h.Y), math.abs(h.Z))
return p.Position - h, p.Position + h
end
---------------------------------------------------------------- 1) сад
local model = BUILD.garden(garden)
model.Name = "GardenModel"
---------------------------------------------------------------- большой сад: группы крупнее и шире, модель не трогаем
-- Участок (координаты модели, z растёт за Гильдию): x ±52, z −10…66. Гильдия — x ±17, z до 12.2.
-- Пруд с мостиком — вместе ×2.2 вокруг общего центра; остальное — кучками, каждая вокруг своего центра.
-- Дорожки (ширина 7), траву и забор строим заново по новому краю.
local GX, GZ0, GZ1, PATH_W = 52, -10, 66, 7
local PONDC = V(14, 0, 43.5)
do
local function g(name)
return model:FindFirstChild(name, true)
end
local function partsIn(group)
local t = {}
for _, p in ipairs(group and group:GetDescendants() or {}) do
if p:IsA("BasePart") then
table.insert(t, p)
end
end
return t
end
local function ext(list)
local mn, mx = V(math.huge, math.huge, math.huge), V(-math.huge, -math.huge, -math.huge)
for _, p in ipairs(list) do
local a, b = boundsOf(p)
mn, mx = mn:Min(a), mx:Max(b)
end
return mn, mx
end
local function scaleList(list, c0, s, c1)
for _, p in ipairs(list) do
local rot, o = p.CFrame - p.Position, p.Position
p.Size = p.Size * s
p.CFrame = CFrame.new(c1.X + (o.X - c0.X) * s, o.Y * s, c1.Z + (o.Z - c0.Z) * s) * rot
end
end
-- образцы цветов — до очистки групп
local function palette(group)
local t, seen = {}, {}
for _, p in ipairs(partsIn(group)) do
local k = p.Color:ToHex()
if not seen[k] then
seen[k] = true
table.insert(t, p.Color)
end
end
return t
end
local grassCols, pathCols, fenceCols = palette(g("Grass")), palette(g("Paths")), palette(g("Fence"))
local function mk(parent, name, size, cf, color, mat)
local p = Instance.new("Part")
p.Name, p.Size, p.CFrame, p.Color = name, size, cf, color
p.Material = mat or Enum.Material.SmoothPlastic
p.Anchored = true
p.TopSurface, p.BottomSurface = Enum.SurfaceType.Smooth, Enum.SurfaceType.Smooth
p.Parent = parent
return p
end
-- пруд, вода, растения, точки рыб и мостик
local pondList = {}
for _, n in ipairs({ "Pond", "PondWater", "PondPlants", "FishSpots", "Bridge" }) do
for _, p in ipairs(partsIn(g(n))) do
table.insert(pondList, p)
end
end
scaleList(pondList, V(8, 0, 22.5), 2.2, PONDC)
-- проход дорожки: камни и вода по оси мостика за его концами убираем
local bmn, bmx = ext(partsIn(g("Bridge")))
for _, n in ipairs({ "Pond", "PondWater", "PondPlants" }) do
for _, p in ipairs(partsIn(g(n))) do
if math.abs(p.Position.Z - PONDC.Z) < 3.9 and (p.Position.X < bmn.X or p.Position.X > bmx.X) then
p:Destroy()
end
end
end
-- на месте уточки и капибары рыбы не плавают
for _, n in ipairs({ "FishSpot_2", "FishSpot_3" }) do
for _, p in ipairs(partsIn(g("FishSpots"))) do
if p.Name == n then
p:Destroy()
end
end
end
-- занятые места: { x0, x1, z0, z1 }
local busy = { { -19, 19, -14, 14 }, { -5, 33, 30, 57 } }
local function hw(a, b)
return { math.min(a.X, b.X) - PATH_W / 2, math.max(a.X, b.X) + PATH_W / 2, math.min(a.Z, b.Z) - PATH_W / 2, math.max(a.Z, b.Z) + PATH_W / 2 }
end
local ROUTES = {
{ V(-36, 0, GZ0), V(-36, 0, PONDC.Z) }, { V(36, 0, GZ0), V(36, 0, PONDC.Z) },
{ V(-36, 0, PONDC.Z), V(bmn.X, 0, PONDC.Z) }, { V(bmx.X, 0, PONDC.Z), V(36, 0, PONDC.Z) },
}
for _, r in ipairs(ROUTES) do
table.insert(busy, hw(r[1], r[2]))
end
table.insert(busy, { -52, -27, 46, 66 }) -- холм с дверью
table.insert(busy, { -52, -40, 33, 46 }) -- его почтовый ящик
table.insert(busy, { 37, 48, 50, 60 }) -- меч
-- отдельные постройки: группа, масштаб, новый центр
for _, s in ipairs({
{ "Gazebo", 2.4, -18.8, 54 }, { "Boat", 2.6, -8, 53 }, { "Bench", 2, -9, 36.5 },
{ "VegGarden", 2, -46, 8 }, { "FishRack", 2.2, 46, 8 }, { "Beehive", 2.4, 46, 27 },
}) do
local list = partsIn(g(s[1]))
local mn, mx = ext(list)
local c0 = (mn + mx) / 2
scaleList(list, c0, s[2], V(s[3], 0, s[4]))
local hx, hz = (mx.X - mn.X) * s[2] / 2, (mx.Z - mn.Z) * s[2] / 2
table.insert(busy, { s[3] - hx, s[3] + hx, s[4] - hz, s[4] + hz })
end
-- кучки (дерево, клумба, куст, фонарь): слияние деталей, которые касаются друг друга
local function clusters(list)
local box, par = {}, {}
for i, p in ipairs(list) do
local a, b = boundsOf(p)
box[i], par[i] = { a, b }, i
end
local function find(i)
while par[i] ~= i do
par[i] = par[par[i]]
i = par[i]
end
return i
end
for i = 1, #list do
for j = i + 1, #list do
local A, B = box[i], box[j]
if A[1].X < B[2].X + 0.15 and B[1].X < A[2].X + 0.15 and A[1].Z < B[2].Z + 0.15 and B[1].Z < A[2].Z + 0.15 then
par[find(i)] = find(j)
end
end
end
local out = {}
for i, p in ipairs(list) do
local k = find(i)
out[k] = out[k] or {}
table.insert(out[k], p)
end
return out
end
local function mapCenter(c)
if c.Z > 12.2 then
return V(c.X * GX / 30, 0, 20 + (c.Z - 12.2) * 2.7)
end
local ax = math.abs(c.X)
local nx = ax > 17 and 21 + (ax - 17) * 2.4 or ax
return V(nx * math.sign(c.X), 0, GZ0 + (c.Z + 10) * 1.5)
end
local dropped = 0
for _, s in ipairs({ { "Trees", 2.4, 0.35 }, { "Bushes", 2.3, 1 }, { "Beds", 1.8, 1 }, { "Lanterns", 2, 1 } }) do
for _, list in pairs(clusters(partsIn(g(s[1])))) do
local mn, mx = ext(list)
local c0 = (mn + mx) / 2
local c1 = mapCenter(c0)
local hx, hz = (mx.X - mn.X) * s[2] / 2 * s[3], (mx.Z - mn.Z) * s[2] / 2 * s[3]
local ok = false
for _ = 1, 14 do
c1 = V(math.clamp(c1.X, -GX + hx + 1, GX - hx - 1), 0, math.clamp(c1.Z, GZ0 + hz + 1, GZ1 - hz - 1))
local hit
for _, r in ipairs(busy) do
if c1.X + hx > r[1] and c1.X - hx < r[2] and c1.Z + hz > r[3] and c1.Z - hz < r[4] then
hit = r
break
end
end
if not hit then
ok = true
break
end
local dl, dr, dn, df = c1.X + hx - hit[1], hit[2] - (c1.X - hx), c1.Z + hz - hit[3], hit[4] - (c1.Z - hz)
local m = math.min(dl, dr, dn, df)
if m == dl then
c1 -= V(dl + 0.5, 0, 0)
elseif m == dr then
c1 += V(dr + 0.5, 0, 0)
elseif m == dn then
c1 -= V(0, 0, dn + 0.5)
else
c1 += V(0, 0, df + 0.5)
end
end
if ok then
scaleList(list, c0, s[2], c1)
table.insert(busy, { c1.X - hx, c1.X + hx, c1.Z - hz, c1.Z + hz })
else
for _, p in ipairs(list) do
p:Destroy()
end
dropped += 1
end
end
end
model:SetAttribute("DroppedClusters", dropped)
-- трава: участки вокруг Гильдии, плитами чуть разного оттенка
local grass, rng = g("Grass"), Random.new(11)
grass:ClearAllChildren()
local base = grassCols[1]
for _, r in ipairs({ { -GX, -17, GZ0, 12.2 }, { 17, GX, GZ0, 12.2 }, { -GX, GX, 12.2, GZ1 } }) do
local nx, nz = math.ceil((r[2] - r[1]) / 9), math.ceil((r[4] - r[3]) / 9)
local sx, sz = (r[2] - r[1]) / nx, (r[4] - r[3]) / nz
for i = 0, nx - 1 do
for j = 0, nz - 1 do
local c = base:Lerp(rng:NextNumber() < 0.5 and Color3.new(0, 0, 0) or Color3.new(1, 1, 0.6), rng:NextNumber(0, 0.07))
mk(grass, "GrassTile", V(sx, 0.3, sz), CFrame.new(r[1] + (i + 0.5) * sx, 0.15, r[3] + (j + 0.5) * sz), c)
end
end
end
-- дорожки: ряды крупного плитняка
local paths = g("Paths")
paths:ClearAllChildren()
for _, r in ipairs(ROUTES) do
local a, b = r[1], r[2]
local len = (b - a).Magnitude
local d = (b - a).Unit
local side = V(d.Z, 0, -d.X)
local rows = math.max(1, math.floor(len / 3.4))
local step = len / rows
for i = 0, rows - 1 do
local n = i % 2 == 0 and 2 or 3
local w = PATH_W / n
for k = 0, n - 1 do
local q = a + d * ((i + 0.5) * step) + side * ((k + 0.5) * w - PATH_W / 2)
local cf = CFrame.lookAt(V(q.X, 0.4, q.Z), V(q.X, 0.4, q.Z) + d)
mk(paths, "Flag", V(w - 0.14, 0.26, step - 0.14), cf, pathCols[rng:NextInteger(1, #pathCols)], Enum.Material.Slate)
end
end
end
-- забор по новому краю, калитки напротив дорожек
local fence = g("Fence")
fence:ClearAllChildren()
local wood, woodD = fenceCols[1], fenceCols[#fenceCols]
local function run(ax, az, bx, bz)
local a, b = V(ax, 0, az), V(bx, 0, bz)
local len = (b - a).Magnitude
local n = math.max(1, math.floor(len / 7))
local rot = CFrame.lookAt(V(), (b - a).Unit)
for i = 0, n do
local q = a:Lerp(b, i / n)
mk(fence, "Post", V(0.8, 4.4, 0.8), CFrame.new(q.X, 2.2, q.Z) * rot, woodD)
end
local mid = (a + b) / 2
for _, y in ipairs({ 1.5, 3.3 }) do
mk(fence, "Rail", V(0.3, 0.45, len), CFrame.new(mid.X, y, mid.Z) * rot, wood)
end
end
run(-GX, GZ1, GX, GZ1)
for _, s in ipairs({ -1, 1 }) do
run(s * GX, GZ1, s * GX, GZ0)
run(s * GX, GZ0, s * 39.8, GZ0)
run(s * 32.2, GZ0, s * 17, GZ0)
end
end
model:PivotTo(PIV)
-- участок сада в мире (по забору) — всё постороннее, что в него залезает, в архив
local fmn, fmx = V(math.huge, math.huge, math.huge), V(-math.huge, -math.huge, -math.huge)
for _, p in ipairs((model:FindFirstChild("Fence", true) or model):GetDescendants()) do
if p:IsA("BasePart") then
local a, b = boundsOf(p)
fmn, fmx = fmn:Min(a), fmx:Max(b)
end
end
local function inGarden(obj)
local cf, size
if obj:IsA("Model") then
cf, size = obj:GetBoundingBox()
elseif obj:IsA("BasePart") then
cf, size = obj.CFrame, obj.Size
else
return false
end
local c, h = cf.Position, size / 2
if size.Magnitude > 120 then
return false -- земля лобби, скалы целиком
end
return c.X + h.X > fmn.X and c.X - h.X < fmx.X and c.Z + h.Z > fmn.Z and c.Z - h.Z < fmx.Z and c.Y - h.Y < PIV.Position.Y + 8
end
local stashed = {}
local function stash(obj)
table.insert(stashed, obj:GetFullName())
obj.Name = obj.Name .. "_garden"
obj.Parent = backup
end
for _, c in ipairs(workspace:GetChildren()) do
if (c:IsA("Model") or c:IsA("BasePart")) and c ~= map and not c:IsA("Terrain") and inGarden(c) then
stash(c)
end
end
-- подножие скал: трава, цветы и камни лежат кучками внутри папок — переносим только задевающие сад
for _, f in ipairs({ "LobbyCliffFoot", "LobbyDecor", "LobbyTrees", "LobbyRockPlants", "LobbyForest" }) do
local folder = map:FindFirstChild(f)
for _, c in ipairs(folder and folder:GetDescendants() or {}) do
if c:IsDescendantOf(map) and (c:IsA("Model") or (c:IsA("BasePart") and not c:FindFirstAncestorWhichIsA("Model"))) and inGarden(c) then
stash(c)
end
end
end
-- материалы и столкновения: ходить по траве, дорожкам, мостику и дну пруда; забор, стволы, беседка,
-- лодка, улей, огород — твёрдые; растения, листва, вода, фонари — проходимые
local SOLID = { Grass = true, Paths = true, Bridge = true, Pond = true, Fence = true }
local SOFT = { PondWater = true, FishSpots = true, PondPlants = true, Lanterns = true, Beds = true, Bushes = true }
local water
local parts, collide = 0, 0
for _, p in ipairs(model:GetDescendants()) do
if p:IsA("BasePart") then
parts += 1
p.Anchored = true
local group = p.Parent and p.Parent.Name or ""
local s = { p.Size.X, p.Size.Y, p.Size.Z }
table.sort(s)
local localY = PIV:PointToObjectSpace(p.Position).Y
local solid
if SOLID[group] then
solid = s[3] >= 0.6
elseif SOFT[group] then
solid = false
elseif group == "Trees" then
solid = s[2] >= 0.8 and localY < 2.5 -- стволы; кроны — над головой
else
solid = s[2] >= 1
end
p.CanCollide, p.CanQuery, p.CanTouch = solid, solid, false
p.CastShadow = s[3] >= 3
if solid then
collide += 1
end
if group == "PondWater" then
-- вода как в фонтане лобби
p.Material = Enum.Material.Glass
p.Color = Color3.fromRGB(110, 190, 235)
p.Transparency = 0.3
p.CastShadow = false
water = water or p
elseif group == "FishSpots" then
p.Transparency = 1
elseif p.Name:find("_Glow") then
p.Material = Enum.Material.Neon
p.CastShadow = false
local l = Instance.new("PointLight")
l.Range, l.Brightness, l.Color = 20, 0.8, Color3.fromRGB(255, 205, 150)
l.Parent = p
end
end
end
if model.PrimaryPart then
model.PrimaryPart.CanCollide, model.PrimaryPart.CanQuery, model.PrimaryPart.Transparency = false, false, 1
end
local waterTop = -math.huge
for _, p in ipairs((model:FindFirstChild("PondWater", true) or model):GetDescendants()) do
if p:IsA("BasePart") then
local _, b = boundsOf(p)
waterTop = math.max(waterTop, b.Y)
end
end
model:SetAttribute("WaterTop", waterTop)
---------------------------------------------------------------- 2) пасхалки
local rp = RaycastParams.new()
rp.FilterType = Enum.RaycastFilterType.Exclude
rp.RespectCanCollide = true
local function groundY(pos, exclude)
rp.FilterDescendantsInstances = exclude
local hit = workspace:Raycast(pos + V(0, 8, 0), V(0, -20, 0), rp)
return hit and hit.Position.Y or PIV.Position.Y
end
-- поставить пасхалку на землю (x, z — в системе сада, лицо — к Гильдии)
local function placeAt(egg, x, z)
local cf = PIV * CFrame.new(x, 0, z)
egg:PivotTo(CFrame.new(cf.Position.X, groundY(cf.Position, { egg, eggs }), cf.Position.Z) * (cf - cf.Position))
end
local function eggPhysics(egg, softGroups)
for _, p in ipairs(egg:GetDescendants()) do
if p:IsA("BasePart") then
p.Anchored = true
local s = { p.Size.X, p.Size.Y, p.Size.Z }
table.sort(s)
local solid = s[2] >= 0.8 and not softGroups[p.Parent.Name]
p.CanCollide, p.CanQuery, p.CanTouch = solid, solid, false
p.CastShadow = s[3] >= 2
if p.Name:find("_Glow") then
p.Material = Enum.Material.Neon
p.CastShadow = false
end
end
end
if egg.PrimaryPart then
egg.PrimaryPart.CanCollide, egg.PrimaryPart.CanQuery, egg.PrimaryPart.Transparency = false, false, 1
end
end
local function find(root, name)
for _, d in ipairs(root:GetDescendants()) do
if d:IsA("BasePart") and d.Name == name then
return d
end
end
end
local function prompt(part, actionText, objectText, egg)
local pp = Instance.new("ProximityPrompt")
pp.ActionText, pp.ObjectText = actionText, objectText
pp.HoldDuration, pp.MaxActivationDistance, pp.RequiresLineOfSight = 0, 15, false
pp:SetAttribute("Egg", egg) -- обрабатывает GuildClient.client.lua (только на экране игрока)
pp.Parent = part
return pp
end
local eggs = Instance.new("Folder")
eggs.Name = "Eggs"
eggs.Parent = garden
local notes = {}
-- меч в камне — в дальнем правом углу сада (за ульем), лицом к саду
local sword = BUILD.sword(eggs)
sword.Name = "EggSwordStone"
sword:ScaleTo(1.9)
eggPhysics(sword, { Plaque = true })
placeAt(sword, 42, 55)
local plaque = find(sword, "Plaque_Face")
do -- столбик таблички торчал сквозь её лицо и перечёркивал текст
local post = find(sword, "PlaquePost")
if post then
post.Size -= V(0, 0.57, 0)
post.CFrame -= V(0, 0.285, 0)
end
end
if plaque then
local sg = Instance.new("SurfaceGui")
sg.Face = Enum.NormalId.Top
sg.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud
sg.PixelsPerStud = 120
sg.LightInfluence = 0.3
sg.Parent = plaque
local t = Instance.new("TextLabel")
-- у грани Top ось надписи идёт вдоль короткой стороны таблички: подпись поворачиваем на 90° и меняем пропорции
local long, short = math.max(plaque.Size.X, plaque.Size.Z), math.min(plaque.Size.X, plaque.Size.Z)
t.AnchorPoint = Vector2.new(0.5, 0.5)
t.Position = UDim2.fromScale(0.5, 0.5)
t.Size = UDim2.fromScale(long / short * 0.94, short / long * 0.86)
t.BackgroundTransparency = 1
t.FontFace = TITLE_FONT
t.TextScaled = true
t.TextColor3 = Color3.fromRGB(58, 38, 22)
t.Text = "Кто вытащит меч — станет королём рыбаков"
t.TextWrapped = true
t.Parent = sg
-- текст должен читаться со стороны зрителя: если «верх» таблички смотрит от него — развернуть
local look = plaque.CFrame.LookVector
local toViewer = (plaque.Position - sword:GetPivot().Position) * V(1, 0, 1)
if look:Dot(toViewer) < 0 then
t.Rotation = 180
end
t.Rotation -= 90
end
local blade = find(sword, "Grip") or find(sword, "Blade")
prompt(blade, "Вытащить меч", "Меч в камне", "Sword")
-- круглая дверь в холме — в дальнем левом углу, за беседкой, спиной к забору
local door = BUILD.door(eggs)
door.Name = "EggRoundDoor"
door:ScaleTo(3.4) -- дверь выше персонажа (6 стадов)
eggPhysics(door, { Glow = true, Mailbox = false })
placeAt(door, -39.5, 55)
local knob = find(door, "RoundDoor") or find(door, "DoorKnob")
prompt(knob, "Постучать", "Круглая дверь", "Door")
-- резиновая уточка — в пруду, на воде
local duck = BUILD.duck(eggs)
duck.Name = "EggRubberDuck"
duck:ScaleTo(2)
eggPhysics(duck, { Duck = true })
do
-- большая южная часть пруда; ровно на воде, боком к мостику
local c = PIV * V(14, 0, 50.2)
duck:PivotTo(CFrame.new(c.X, waterTop - 0.7, c.Z) * (PIV - PIV.Position) * CFrame.Angles(0, math.rad(90), 0))
duck.ModelStreamingMode = Enum.ModelStreamingMode.Persistent -- уточку качает клиент: она нужна ему всегда
end
-- капибара сидит в воде по пояс; свой маленький прудик не нужен
local capy = BUILD.capy(eggs)
capy.Name = "EggCapybara"
local capyWater = capy:FindFirstChild("Water", true)
if capyWater then
capyWater:Destroy()
end
capy:ScaleTo(2.4)
eggPhysics(capy, { Capybara = true, Mandarin = true })
do
local c = PIV * V(11.8, 0, 36.9)
capy:PivotTo(CFrame.new(c.X, waterTop - 1.5, c.Z) * (PIV - PIV.Position) * CFrame.Angles(0, math.rad(90), 0))
end
-- точки рыб и высота воды — атрибутами папки (папка приходит клиенту сразу, детали сада — по мере приближения)
do
local spots = {}
for _, p in ipairs((model:FindFirstChild("FishSpots", true) or model):GetDescendants()) do
if p:IsA("BasePart") then
table.insert(spots, ("%.2f,%.2f"):format(p.Position.X, p.Position.Z))
end
end
garden:SetAttribute("PondSpots", table.concat(spots, ";"))
garden:SetAttribute("PondWaterY", waterTop)
end
-- сад не должен залезать на скалы: сообщаем, если залез
local cliffHits = 0
do
local ov = OverlapParams.new()
ov.FilterType = Enum.RaycastFilterType.Include
local inc = {}
for _, n in ipairs({ "LobbyCliffs", "LobbyCliffDecor" }) do
table.insert(inc, map:FindFirstChild(n))
end
ov.FilterDescendantsInstances = inc
cliffHits = #workspace:GetPartBoundsInBox(CFrame.new((fmn + fmx) / 2), fmx - fmn + V(0, 6, 0), ov)
end
table.insert(notes, "скал в участке: " .. cliffHits)
return ("Сад: деталей %d, с коллизией %d, вода на Y=%.2f; в архив: %d (%s); %s"):format(parts, collide, waterTop, #stashed,
table.concat(stashed, ", "):sub(1, 400), table.concat(notes, "; "))