Files
Ornament-Generator-RNG/gym/BenchPressServer.server.luau
T

370 lines
16 KiB
Luau

-- BenchPressServer (Script, ServerScriptService) — bench press on the player's "Bench" decoration (Decor/BenchPress).
-- Prompt "Bench press" on the owner's bench -> the character lies on the pad, takes the barbell off the hooks and
-- presses it (server tweens the root, arm joints and the bar). Rewards = pull-up bar x1.5 (Config.PULLUP):
-- XP and shards per press are accumulated as fractions and paid out as whole numbers (20 presses = 30 XP, 3 shards).
-- Set: at most BENCH.MaxReps presses; the count is kept per UserId across get-ups (getting up at 19 does not reset it),
-- after the last press the bench is locked for BENCH.RestSeconds. All limits live here (server), the client only shows
-- the attribute BenchRestUntil (server time) and BenchReps. Stop: prompt again, a jump (RemoteEvent "BenchPress"
-- "Stop"), death, leaving, the bench being removed.
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService = game:GetService("TweenService")
local folder = ReplicatedStorage:WaitForChild("OrnamentMachine")
local Config = require(folder:WaitForChild("Config"))
local PlayerData = require(script.Parent:WaitForChild("OrnamentPlayerData"))
local notify = folder:WaitForChild("Notify")
local giveXP = game:GetService("ServerStorage"):WaitForChild("OrnamentGiveXP", 10)
local P = Config.PULLUP
local MULT = 1.5
local BENCH = Config.BENCH or {
RepSeconds = 2.2,
XpPerRep = P.XpPerRep * MULT, -- 1.5 XP per press
ShardsPerRep = (P.ShardReward or 1) / P.ShardEvery * MULT, -- 0.15 shard per press
MaxReps = 20,
RestSeconds = 600,
}
local remote = folder:FindFirstChild("BenchPress")
if not remote then
remote = Instance.new("RemoteEvent")
remote.Name = "BenchPress"
remote.Parent = folder
end
local pressing = {} -- [Player] = session
local sets = {} -- [UserId] = { reps, xp, shards } of the current set
local restUntil = {} -- [UserId] = server time when the bench is free again
local function now() return workspace:GetServerTimeNow() end
local function mmss(sec)
local t = math.max(0, math.ceil(sec))
return math.floor(t / 60) .. ":" .. string.format("%02d", t % 60)
end
local function j0Target(j) if j:IsA("Motor6D") then return j, "C0" end return j.Attachment0, "CFrame" end
local function j0(j) local o, p = j0Target(j); return o[p] end
local function j1(j) if j:IsA("Motor6D") then return j.C1 end return j.Attachment1.CFrame end
local function stopBench(player)
local s = pressing[player]
if not s then return end
pressing[player] = nil
s.active = false
for _, t in s.tweens do t:Cancel() end
for _, c in s.conns do c:Disconnect() end
for i = #s.saved, 1, -1 do -- reverse order: bar CFrame, then Anchored, then welds
local v = s.saved[i]
if v.obj.Parent then v.obj[v.prop] = v.value end
end
for _, inst in s.temp do inst:Destroy() end
if s.hrp.Parent then
s.hrp.CFrame = s.exitCF
s.hrp.Anchored = false
end
if s.hum.Parent then s.hum.PlatformStand = false end
if s.prompt.Parent then s.prompt.ActionText = "Bench press" end
if s.model.Parent then s.model:SetAttribute("InUse", nil) end
if player.Parent then
player:SetAttribute("BenchPressing", nil)
if s.reps > 0 then
local msg = "Bench presses: " .. s.reps .. " · +" .. s.xp .. " XP"
if s.shards > 0 then msg ..= " · +" .. s.shards .. " shard" .. (s.shards == 1 and "" or "s") end
notify:FireClient(player, msg, "shards")
end
end
end
local function startBench(player, model, prompt)
local char = player.Character
local hum = char and char:FindFirstChildOfClass("Humanoid")
local hrp = char and char:FindFirstChild("HumanoidRootPart")
local pad, bar = model:FindFirstChild("Pad"), model:FindFirstChild("Bar")
if not hum or hum.Health <= 0 or not hrp or not pad or not bar or pressing[player] then return end
if model:GetAttribute("InUse") or player:GetAttribute("PullingUp") then return end
local uid = player.UserId
local left = (restUntil[uid] or 0) - now()
if left > 0 then return end -- the client shows the rest timer for a few seconds (BenchRestUntil)
if restUntil[uid] then restUntil[uid] = nil; sets[uid] = nil; player:SetAttribute("BenchRestUntil", nil) end
local set = sets[uid] or { reps = 0, xp = 0, shards = 0 }
sets[uid] = set
local function jointNamed(name)
for _, d in char:GetDescendants() do
if d.Name == name and (d:IsA("Motor6D") or d:IsA("AnimationConstraint")) then return d end
end
end
-- geometry: lie along the pad's long axis, head towards the rack (the bar side), face up
local padCF, padSize, padC = pad.CFrame, pad.Size, pad.Position
local ax = padSize.X >= padSize.Z and padCF.RightVector or padCF.LookVector
ax = Vector3.new(ax.X, 0, ax.Z).Unit
local barCF0 = bar.CFrame
local toBar = Vector3.new(barCF0.X - padC.X, 0, barCF0.Z - padC.Z)
local headDir = toBar:Dot(ax) >= 0 and ax or -ax
local up = Vector3.yAxis
local right = headDir:Cross(-up) -- body's right when lying on the back
local rot = CFrame.fromMatrix(Vector3.zero, right, headDir) -- LookVector = up
local padTop = padC.Y + padSize.Y / 2
local barAlong = toBar:Dot(headDir) - 0.9 -- press line a bit towards the feet, away from the uprights
-- R15 arms (same two-bone solver as the pull-up bar)
local arms = {}
local root, waist = jointNamed("Root"), jointNamed("Waist")
if root and waist then
for _, side in { "Right", "Left" } do
local sh, el, wr = jointNamed(side .. "Shoulder"), jointNamed(side .. "Elbow"), jointNamed(side .. "Wrist")
if sh and el and wr and char:FindFirstChild(side .. "Hand") then
local w1 = j0(el).Position - j1(sh).Position
local w2 = (j0(wr) * j1(wr):Inverse()).Position - j1(el).Position
local function basis(w)
local y = -w.Unit
local x = Vector3.xAxis - y * y.X
return CFrame.fromMatrix(Vector3.zero, x.Unit, y)
end
table.insert(arms, {
sh = sh, el = el, sign = side == "Right" and 1 or -1,
sh0 = j0(sh), sh1 = j1(sh), el0 = j0(el), el1 = j1(el),
a = w1.Magnitude, b = w2.Magnitude,
uaBasisInv = basis(w1):Inverse(), laBasisInv = basis(w2):Inverse(),
})
end
end
end
local analytic = #arms == 2
local utOff = analytic and (j0(root) * j1(root):Inverse() * j0(waist) * j1(waist):Inverse()) or CFrame.new()
local sLocal = analytic and (utOff * arms[1].sh0).Position or Vector3.new(1, 1.5, 0)
local reach = analytic and (arms[1].a + arms[1].b) or 2
-- shoulders a little past the bar (bar over the chest)
local hrpAlong = barAlong + 0.35 - sLocal.Y
local bodyPos = Vector3.new(padC.X, padTop + hrp.Size.Z / 2 + 0.05, padC.Z) + headDir * hrpAlong
local bodyCF = CFrame.new(bodyPos) * rot
local shoulderY = (bodyCF * Vector3.new(0, sLocal.Y, sLocal.Z)).Y
local barXZ = padC + headDir * barAlong
local function barAt(y) return CFrame.new(barXZ.X, y, barXZ.Z) * barCF0.Rotation end
local topCF = barAt(shoulderY + reach * 0.9)
local bottomCF = barAt(bodyPos.Y + hrp.Size.Z / 2 + 0.45)
local barLen = math.max(bar.Size.X, bar.Size.Y, bar.Size.Z)
local GRIP = math.clamp(barLen * 0.2, 0.9, 1.15)
for _, d in model:GetChildren() do -- hands stay inside the uprights
if d.Name == "Upright" and d:IsA("BasePart") then
local inner = math.abs((d.Position - barXZ):Dot(right)) - math.min(d.Size.X, d.Size.Z) / 2
if inner > 1 then GRIP = math.min(GRIP, inner - 0.55) end
end
end
local function solve(barPos)
local out = {}
local UT = bodyCF * utOff
for _, arm in arms do
local S = (UT * arm.sh0).Position
local H = barPos + right * (GRIP * arm.sign)
local toH = H - S
local D = math.clamp(toH.Magnitude, math.abs(arm.a - arm.b) + 0.05, arm.a + arm.b - 0.01)
local u = toH.Unit
local pref = right * (0.8 * arm.sign) - up * 0.6 -- elbows out and down
local perp = pref - u * pref:Dot(u)
perp = perp.Magnitude > 1e-3 and perp.Unit or -up
local x = (arm.a * arm.a - arm.b * arm.b + D * D) / (2 * D)
local h = math.sqrt(math.max(arm.a * arm.a - x * x, 0))
local E = S + u * x + perp * h
local d1 = (E - S).Unit
local d2 = (S + u * D - E).Unit
local X = d1:Cross(d2)
if X.Magnitude < 1e-3 then X = right - d1 * right:Dot(d1) end
X = X.Unit
local UA = CFrame.fromMatrix(Vector3.zero, X, -d1) * arm.uaBasisInv
local LA = CFrame.fromMatrix(Vector3.zero, X, -d2) * arm.laBasisInv
out[arm.sh] = CFrame.new(arm.sh0.Position) * (UT.Rotation:Inverse() * UA * arm.sh1.Rotation)
out[arm.el] = CFrame.new(arm.el0.Position) * (UA:Inverse() * LA * arm.el1.Rotation)
end
return out
end
local STEPS = 6
local frames = {} -- 0 = arms extended, STEPS = bar on the chest
for k = 0, STEPS do
local f = (1 - math.cos(math.pi * k / STEPS)) / 2
local cf = topCF:Lerp(bottomCF, f)
frames[k] = { bar = cf, pose = analytic and solve(cf.Position) or nil }
end
local rackFrame = { bar = barCF0, pose = analytic and solve(barCF0.Position) or nil }
local exitPos = Vector3.new(padC.X, model:GetPivot().Position.Y + hum.HipHeight + hrp.Size.Y / 2 + 0.3, padC.Z)
+ right * (math.min(padSize.X, padSize.Z) / 2 + 2)
local s = {
active = true, hrp = hrp, hum = hum, prompt = prompt, model = model, reps = 0, xp = 0, shards = 0,
tweens = {}, saved = {}, conns = {}, temp = {}, exitCF = CFrame.lookAt(exitPos, exitPos - right),
}
local function remember(obj, prop) table.insert(s.saved, { obj = obj, prop = prop, value = obj[prop] }) end
-- barbell group (bar + plates + collars) moves as one, welds off while it moves
local barParts, isBar = {}, {}
for _, d in model:GetChildren() do
if d:IsA("BasePart") and (d.Name == "Bar" or d.Name == "Plate" or d.Name == "Collar") then
isBar[d] = true
table.insert(barParts, { part = d, rel = barCF0:Inverse() * d.CFrame })
end
end
for _, w in model:GetDescendants() do
if (w:IsA("WeldConstraint") or w:IsA("JointInstance")) and (isBar[w.Part0] ~= isBar[w.Part1]) and w.Enabled then
remember(w, "Enabled"); w.Enabled = false
end
end
for _, b in barParts do remember(b.part, "Anchored"); b.part.Anchored = true end
for _, b in barParts do remember(b.part, "CFrame") end
local barVal = Instance.new("CFrameValue")
barVal.Value = barCF0
table.insert(s.temp, barVal)
table.insert(s.conns, barVal.Changed:Connect(function(v)
for _, b in barParts do b.part.CFrame = v * b.rel end
end))
pressing[player] = s
model:SetAttribute("InUse", true)
prompt.ActionText = "Get up"
if analytic then
for _, arm in arms do remember(j0Target(arm.sh)); remember(j0Target(arm.el)) end
for j, v in rackFrame.pose do local o, p = j0Target(j); o[p] = v end
-- knees bent, shins down off the pad
for _, n in { "RightKnee", "LeftKnee" } do
local j = jointNamed(n)
if j then local o, p = j0Target(j); remember(o, p); o[p] = o[p] * CFrame.Angles(math.rad(-80), 0, 0) end
end
else
for _, n in { "Right Shoulder", "Left Shoulder" } do -- R6: arms straight up
local j = jointNamed(n)
if j then remember(j, "C0"); j.C0 = j.C0 * CFrame.Angles(0, 0, (n == "Right Shoulder" and 1 or -1) * math.pi / 2) end
end
end
hum.PlatformStand = true
hrp.Anchored = true
hrp.CFrame = bodyCF
player:SetAttribute("BenchPressing", true)
-- counter over the bench (everyone sees it)
local counter = Instance.new("BillboardGui")
counter.Name = "BenchCounter"
counter.Size = UDim2.fromOffset(200, 40)
counter.StudsOffsetWorldSpace = Vector3.new(0, 4, 0)
counter.MaxDistance = 80
counter.Adornee = pad
local label = Instance.new("TextLabel")
label.Size = UDim2.fromScale(1, 1)
label.BackgroundColor3 = Color3.fromRGB(16, 24, 48)
label.BackgroundTransparency = 0.15
label.TextColor3 = Color3.fromRGB(255, 220, 140)
label.Font = Enum.Font.GothamBold
label.TextScaled = true
label.Text = "Bench press: " .. set.reps .. " / " .. BENCH.MaxReps
local c = Instance.new("UICorner"); c.CornerRadius = UDim.new(0, 10); c.Parent = label
local st = Instance.new("UIStroke"); st.Color = Color3.fromRGB(255, 200, 90); st.Thickness = 2; st.ApplyStrokeMode = Enum.ApplyStrokeMode.Border; st.Parent = label
label.Parent = counter
counter.Parent = model
table.insert(s.temp, counter)
local function finish() stopBench(player) end
s.finish = finish
table.insert(s.conns, hum.Died:Connect(finish))
table.insert(s.conns, char.AncestryChanged:Connect(function() if not char:IsDescendantOf(workspace) then finish() end end))
table.insert(s.conns, pad.AncestryChanged:Connect(function() if not pad:IsDescendantOf(workspace) then finish() end end))
local function go(fr, t)
local info = TweenInfo.new(t, Enum.EasingStyle.Linear)
local list = { TweenService:Create(barVal, info, { Value = fr.bar }) }
if fr.pose then
for j, v in fr.pose do
local o, p = j0Target(j)
table.insert(list, TweenService:Create(o, info, { [p] = v }))
end
end
s.tweens = list
for _, tw in list do tw:Play() end
task.wait(t)
return s.active
end
local rep = BENCH.RepSeconds
local seg = rep * 0.38 / STEPS
task.spawn(function()
task.wait(0.3)
if not (s.active and go(frames[0], 0.6)) then return end -- unrack
while s.active do
for i = 1, STEPS do if not go(frames[i], seg) then return end end
task.wait(rep * 0.08)
for i = STEPS - 1, 0, -1 do if not go(frames[i], seg) then return end end
if not s.active then return end
-- one press done: rewards (server side, fractions accumulate over the whole set)
s.reps += 1
set.reps += 1
player:SetAttribute("BenchReps", set.reps)
label.Text = "Bench press: " .. set.reps .. " / " .. BENCH.MaxReps
local xpDue = math.floor(set.reps * BENCH.XpPerRep + 1e-6) - set.xp
if xpDue > 0 then
set.xp += xpDue; s.xp += xpDue
if giveXP then giveXP:Fire(player, xpDue) end
end
local shDue = math.floor(set.reps * BENCH.ShardsPerRep + 1e-6) - set.shards
if shDue > 0 and PlayerData.AddShards(player, shDue) then
set.shards += shDue; s.shards += shDue
notify:FireClient(player, "+" .. shDue .. " shard for " .. set.reps .. " presses!", "shards")
end
if set.reps >= BENCH.MaxReps then
restUntil[uid] = now() + BENCH.RestSeconds
player:SetAttribute("BenchRestUntil", restUntil[uid])
notify:FireClient(player, "Set complete: " .. BENCH.MaxReps .. " presses! The barbell is available again in " .. math.floor(BENCH.RestSeconds / 60) .. " min", "level")
go(rackFrame, 0.6)
if s.active then finish() end
return
end
task.wait(rep * 0.16)
end
end)
end
remote.OnServerEvent:Connect(function(player, action)
if action == "Stop" and pressing[player] then pressing[player].finish() end
end)
Players.PlayerRemoving:Connect(function(player) if pressing[player] then pressing[player].finish() end end)
Players.PlayerAdded:Connect(function(player) -- rejoin on the same server: the rest timer is still shown
local t = restUntil[player.UserId]
if t and t > now() then player:SetAttribute("BenchRestUntil", t) end
if sets[player.UserId] then player:SetAttribute("BenchReps", sets[player.UserId].reps) end
end)
-- benches: model "Bench" in <plot>/Decor (placed by OrnamentShopServer); the owner is the plot's Owner attribute
local function setupBench(model)
if model:GetAttribute("BenchReady") then return end
local base = model:FindFirstChild("Pad") or model:FindFirstChild("Base") or model.PrimaryPart
if not base then return end
model:SetAttribute("BenchReady", true)
local prompt = Instance.new("ProximityPrompt")
prompt.Name = "BenchPrompt"
prompt.ActionText = "Bench press"
prompt.ObjectText = "Bench Press"
prompt.HoldDuration = 0
prompt.MaxActivationDistance = 10
prompt.RequiresLineOfSight = false
prompt.Parent = base
prompt.Triggered:Connect(function(who)
local plot = model.Parent and model.Parent.Parent
local ownerId = plot and plot:GetAttribute("Owner")
if who.UserId ~= ownerId then
notify:FireClient(who, "This bench belongs to " .. tostring(plot and plot:GetAttribute("OwnerName") or "another player"), "warn")
return
end
if pressing[who] then pressing[who].finish() else startBench(who, model, prompt) end
end)
end
local function check(inst)
if inst:IsA("Model") and inst.Name == "Bench" and inst.Parent and inst.Parent.Name == "Decor" then
task.defer(setupBench, inst)
end
end
workspace.DescendantAdded:Connect(check)
for _, d in workspace:GetDescendants() do check(d) end