- 为铁球、陶瓷球和木球制作风格化材质,归档 CC0 原始参考 - 更新方形球洞和实心滑槽,统一 90° 弯槽并兼容旧存档 - 用顺流泡沫表示水流方向,为冰块制作三种交错的裂纹 - 同步 Blender 源资产、Godot 加载、工坊和试玩预览
323 lines
17 KiB
Python
323 lines
17 KiB
Python
"""Read current IntoHole parameters and calculate ceramic buoyancy/drift.
|
||
|
||
Pure-Python stage: SciPy continuous submerged-sphere / ideal rolling model.
|
||
Optional Godot stage: candidate masses on actual assets and actual ball behavior.
|
||
Neither stage writes to the live physics profiles or any existing scene.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
from dataclasses import asdict, dataclass
|
||
import hashlib
|
||
import json
|
||
import math
|
||
from pathlib import Path
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
|
||
import numpy as np
|
||
import scipy
|
||
from scipy.integrate import solve_ivp
|
||
from scipy.optimize import brentq
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
HERE = Path(__file__).resolve().parent
|
||
OUT = HERE / 'results'
|
||
INPUTS = [ROOT / p for p in (
|
||
'assets/collections/storybook/catalog.json',
|
||
'assets/collections/storybook/physics.json',
|
||
'assets/blocks/water/behavior.gd',
|
||
'assets/balls/shared/physics.gd',
|
||
'playtest/environment/data/water.json',
|
||
'godot_engine/project.godot',
|
||
)]
|
||
|
||
|
||
def constant(text: str, name: str) -> float:
|
||
match = re.search(r'const\s+' + re.escape(name) + r'\s*:=\s*([0-9.eE+-]+)', text)
|
||
if not match:
|
||
raise ValueError(f'Cannot read current constant {name}')
|
||
return float(match[1])
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Parameters:
|
||
radius: float
|
||
original_mass: float
|
||
gravity: float
|
||
water_density: float
|
||
water_cd: float
|
||
flow_speed: float
|
||
air_density: float
|
||
air_cd: float
|
||
mu_static: float
|
||
mu_dynamic: float
|
||
rolling_resistance: float
|
||
restitution: float
|
||
inertia_factor: float
|
||
water_bottom: float
|
||
water_top: float
|
||
release_center_y: float
|
||
duration: float = 8.0
|
||
distance_limit: float = 2.0
|
||
|
||
@property
|
||
def volume(self):
|
||
return 4 * math.pi * self.radius**3 / 3
|
||
|
||
@property
|
||
def area(self):
|
||
return math.pi * self.radius**2
|
||
|
||
@property
|
||
def neutral_mass(self):
|
||
return self.water_density * self.volume
|
||
|
||
@property
|
||
def drag_k(self):
|
||
return 0.5 * self.water_density * self.water_cd * self.area
|
||
|
||
def immersed_fraction(self, center_y):
|
||
# Volume under a horizontal plane, integrated from the bottom of sphere.
|
||
def cap(plane):
|
||
h = np.clip(plane - (center_y - self.radius), 0, 2*self.radius)
|
||
return math.pi * h*h * (self.radius-h/3)
|
||
return float((cap(self.water_top)-cap(self.water_bottom))/self.volume)
|
||
|
||
|
||
def load_parameters(duration=8.0, limit=2.0) -> Parameters:
|
||
catalog = json.loads(INPUTS[0].read_text())['models']
|
||
physics = json.loads(INPUTS[1].read_text())
|
||
water_source = INPUTS[2].read_text()
|
||
level = json.loads(INPUTS[4].read_text())
|
||
ball = next(b for b in physics['ballTypes'] if b['ballTypeId'] == 'ceramic_ball')
|
||
profile = physics['physicsProfiles'][ball['physicsProfileId']]
|
||
pair = next(p for p in physics['contactMaterialPairs']
|
||
if {p['materialAId'], p['materialBId']} == {profile['contactMaterialId'], 'wall'})
|
||
spawn = next(b for b in level['balls'] if b['ballTypeId'] == 'ceramic_ball')
|
||
water = next(e for e in level['entities'] if e['kind']=='water' and e['position'][2]==spawn['position'][2])
|
||
gravity = float(re.search(r'3d/default_gravity=([0-9.]+)', INPUTS[-1].read_text())[1])
|
||
bounds = catalog['water']['boundsBlender']
|
||
inertia = {'solidSphere': 2/5, 'thinSphericalShell': 2/3}[profile['inertiaModel']]
|
||
return Parameters(
|
||
radius=catalog[ball['assetId']]['radius'], original_mass=profile['massKg'],
|
||
gravity=gravity, water_density=constant(water_source,'DENSITY'),
|
||
water_cd=constant(water_source,'DRAG_COEFFICIENT'), flow_speed=constant(water_source,'FLOW_SPEED'),
|
||
air_density=physics['airDensity'], air_cd=profile['dragCoefficient'],
|
||
mu_static=pair['staticFriction'], mu_dynamic=pair['dynamicFriction'],
|
||
rolling_resistance=pair['rollingResistance'], restitution=pair['restitution'],
|
||
inertia_factor=inertia, water_bottom=water['position'][1]+bounds['min'][2],
|
||
water_top=water['position'][1]+bounds['max'][2], release_center_y=spawn['position'][1],
|
||
duration=duration, distance_limit=limit,
|
||
)
|
||
|
||
|
||
def continuous_trial(mass: float, p: Parameters, max_step=1/240) -> dict:
|
||
"""Conditional ideal model, NOT a replacement for Jolt contact solving.
|
||
|
||
1. Continuous x/y motion and spherical-cap immersion until the river floor.
|
||
2. Dissipative conversion to pure rolling, then constant-load rolling drag.
|
||
3. Ideal static rolling resistance holds at rest if its torque is sufficient.
|
||
Current game torque implementation has no such explicit static hold.
|
||
"""
|
||
def flying(t, state):
|
||
_, y, vx, vy = state
|
||
alpha = p.immersed_fraction(y)
|
||
relative = np.array([vx-p.flow_speed, vy])
|
||
water_drag = -p.drag_k * alpha * np.linalg.norm(relative) * relative
|
||
velocity = np.array([vx, vy])
|
||
air_drag = -.5*p.air_density*p.air_cd*p.area*(1-alpha)*np.linalg.norm(velocity)*velocity
|
||
acceleration = (water_drag+air_drag)/mass
|
||
acceleration[1] += p.gravity*(p.neutral_mass*alpha/mass-1)
|
||
return [vx, vy, *acceleration]
|
||
|
||
def touches_floor(t, state):
|
||
return state[1]-(p.water_bottom+p.radius)
|
||
touches_floor.terminal = True
|
||
touches_floor.direction = -1
|
||
flight = solve_ivp(flying, (0,p.duration), [0,p.release_center_y,0,0],
|
||
events=touches_floor, rtol=1e-9, atol=1e-10, max_step=max_step)
|
||
x,y,vx,vy = map(float, flight.y[:,-1])
|
||
touchdown = float(flight.t[-1]) if len(flight.t_events[0]) else None
|
||
result = {'mass_kg':mass, 'sinks_in_principle':mass>p.neutral_mass,
|
||
'touchdown_seconds':touchdown, 'touchdown_x_m':x if touchdown is not None else None,
|
||
'distance_8s_m':x,'final_speed_mps':vx,'final_center_y_m':y,
|
||
'ideal_stop_seconds':None,'rolling_assumption_valid':None}
|
||
if touchdown is None:
|
||
return result
|
||
normal = (mass-p.neutral_mass)*p.gravity
|
||
if normal <= 0:
|
||
result['rolling_assumption_valid'] = False
|
||
return result
|
||
# Perfectly inelastic landing approximation, including impulse needed for rolling.
|
||
tangent_impulse = mass*p.inertia_factor/(1+p.inertia_factor)*abs(vx)
|
||
available_impulse = p.mu_dynamic*mass*(1+p.restitution)*abs(vy)
|
||
initial_v = vx/(1+p.inertia_factor)
|
||
rr_force = p.rolling_resistance*normal # rolling resistance torque divided by R
|
||
def grounded(t, state):
|
||
speed = state[1]
|
||
drive = p.drag_k*(p.flow_speed-speed)*abs(p.flow_speed-speed)
|
||
return [speed,(drive-rr_force)/(mass*(1+p.inertia_factor))]
|
||
def stops(t, state):
|
||
return state[1]
|
||
stops.terminal = True
|
||
stops.direction = -1
|
||
ground = solve_ivp(grounded, (touchdown,p.duration), [x,initial_v], events=stops,
|
||
rtol=1e-9,atol=1e-10,max_step=max_step)
|
||
drive = p.drag_k*(p.flow_speed-ground.y[1])*np.abs(p.flow_speed-ground.y[1])
|
||
required_friction = (p.inertia_factor*drive+rr_force)/(1+p.inertia_factor)
|
||
result.update(distance_8s_m=float(ground.y[0,-1]), final_speed_mps=max(0.,float(ground.y[1,-1])),
|
||
rolling_assumption_valid=bool(tangent_impulse<=available_impulse and
|
||
np.max(np.abs(required_friction))<=p.mu_static*normal),
|
||
ideal_stop_seconds=float(ground.t[-1]) if len(ground.t_events[0]) else None)
|
||
return result
|
||
|
||
|
||
def analytical(p: Parameters):
|
||
drag = p.drag_k*p.flow_speed**2
|
||
hold = p.neutral_mass+drag/(min(p.mu_static,p.rolling_resistance)*p.gravity)
|
||
# Root must be in the parameter range where rolling friction constraints hold.
|
||
root_mass = brentq(lambda m:continuous_trial(m,p)['distance_8s_m']-p.distance_limit,
|
||
p.neutral_mass+1, max(2*hold,1000), xtol=1e-5)
|
||
at_root = continuous_trial(root_mass,p)
|
||
refined = continuous_trial(root_mass,p,max_step=1/480)
|
||
if not at_root['rolling_assumption_valid']:
|
||
raise ValueError('Distance root lies outside valid rolling approximation')
|
||
if abs(refined['distance_8s_m']-at_root['distance_8s_m'])>1e-5:
|
||
raise ValueError('ODE convergence check failed')
|
||
if abs(p.immersed_fraction(p.water_top)-.5)>1e-12:
|
||
raise ValueError('Half-sphere immersion check failed')
|
||
return {'volume_m3':p.volume,'max_buoyancy_N':p.neutral_mass*p.gravity,
|
||
'strict_sinking_mass_gt_kg':p.neutral_mass,
|
||
'full_immersion_water_push_at_rest_N':drag,
|
||
'ideal_static_hold_mass_ge_kg':hold,
|
||
'ideal_8s_two_meter_root_kg':root_mass,'at_ideal_root':at_root,
|
||
'ode_step_halving_distance_change_m':refined['distance_8s_m']-at_root['distance_8s_m']}
|
||
|
||
|
||
def engine_batch(masses: list[float], index: int, duration=8.0):
|
||
request=OUT/f'engine_request_{index:02}.json'
|
||
result=OUT/f'engine_result_{index:02}.json'
|
||
request.write_text(json.dumps({'masses_kg':masses,'duration_seconds':duration,'physics_hz':120},indent=2))
|
||
executable=Path('/Applications/Godot.app/Contents/MacOS/Godot')
|
||
command=[str(executable),'--headless','--path',str(ROOT/'godot_engine'),
|
||
'--fixed-fps','120','--log-file',str(OUT/f'engine_{index:02}.log'),
|
||
'--script','res://playtest/mass_calibration/godot_probe.gd','--',
|
||
f'--request={request}',f'--result={result}']
|
||
with (OUT/f'engine_stdout_{index:02}.log').open('w') as log:
|
||
subprocess.run(command,check=True,stdout=log,stderr=subprocess.STDOUT,timeout=180)
|
||
log=(OUT/f'engine_stdout_{index:02}.log').read_text()
|
||
if 'ERROR:' in log:
|
||
raise RuntimeError(log)
|
||
return json.loads(result.read_text())['trials']
|
||
|
||
|
||
def verify_engine(p: Parameters, model: dict):
|
||
center=math.ceil(model['ideal_8s_two_meter_root_kg']/10)*10
|
||
masses=sorted(set([p.original_mass,114.,150.,200.,250.,300.,350.,400.,500.,
|
||
float(center),float(center+20)]))
|
||
trials=engine_batch(masses,0,p.duration)
|
||
passing=lambda r:r['max_downstream_m']<=p.distance_limit and r['settled_on_bed']
|
||
ordered=sorted(trials,key=lambda r:r['candidate_mass_kg'])
|
||
pairs=[(a,b) for a,b in zip(ordered,ordered[1:]) if not passing(a) and passing(b)]
|
||
if not pairs:
|
||
raise RuntimeError('Native scan did not bracket the two-meter threshold')
|
||
lower,upper=pairs[0][0]['candidate_mass_kg'],pairs[0][1]['candidate_mass_kg']
|
||
batch=1
|
||
while upper-lower>0.25:
|
||
mid=(lower+upper)/2
|
||
trial=engine_batch([mid],batch,p.duration)[0];trials.append(trial);batch+=1
|
||
if passing(trial):upper=mid
|
||
else:lower=mid
|
||
recommended=math.ceil((upper+10)/10)*10
|
||
# Repeat the boundary and round-number margin under the same authored conditions.
|
||
repeats=engine_batch([upper,recommended,upper,recommended,recommended],batch,p.duration)
|
||
trials.extend(repeats)
|
||
if not all(passing(t) for t in repeats):
|
||
raise RuntimeError('The repeated margin/boundary checks did not pass')
|
||
return {'failing_mass_kg':lower,'passing_mass_kg':upper,
|
||
'recommended_candidate_kg':recommended,'trials':trials,
|
||
'recommendation_repeats':[t for t in repeats if t['candidate_mass_kg']==recommended]}
|
||
|
||
|
||
def write_summary(report: dict):
|
||
p=report['parameters'];m=report['model']
|
||
lines=[
|
||
'# 陶瓷球质量计算结果', '',
|
||
'日期:2026-11-17。使用项目当前 uv 虚拟环境中的 NumPy / SciPy;正式质量配置未修改。', '',
|
||
'## 条件', '',
|
||
f"- 球半径 {p['radius']} m;水深 {p['water_top']-p['water_bottom']} m;流速 {p['flow_speed']} m/s。",
|
||
f"- 从球心 Y={p['release_center_y']} m 静止释放;河床顶面 Y={p['water_bottom']} m。",
|
||
f"- 从释放起计时 {p['duration']} s;限制顺流方向最大水平位移 {p['distance_limit']} m,不把下沉高度加入距离。",
|
||
'- 保持真实陶瓷球空气参数、墙面摩擦与滚动阻力;候选质量只作用于独立计算实例。', '',
|
||
'## 浮力与理想模型', '',
|
||
f"- 体积:{m['volume_m3']:.9f} m³。",
|
||
f"- 最大浮力:{m['max_buoyancy_N']:.6f} N。",
|
||
f"- 完全浸没的中性质量:{m['strict_sinking_mass_gt_kg']:.9f} kg;下沉要求严格大于它。",
|
||
f"- 完全浸没、相对地面静止时的水流推力:{m['full_immersion_water_push_at_rest_N']:.6f} N。",
|
||
f"- 理想纯滚动模型的 8 秒 / 2 米临界质量:{m['ideal_8s_two_meter_root_kg']:.6f} kg。",
|
||
f"- 理想静态滚阻足以抗住水流的质量:{m['ideal_static_hold_mass_ge_kg']:.6f} kg。该条件不等于当前引擎能永久锁止。",
|
||
f"- ODE 最大步长减半,临界点位移变化:{m['ode_step_halving_distance_change_m']:.3g} m。", '',
|
||
]
|
||
if 'native' in report:
|
||
n=report['native'];r=n['recommendation_repeats']
|
||
lines += ['## 当前引擎核验', '',
|
||
f"在 120 Hz、现有河道布局下,失败质量 {n['failing_mass_kg']:.5f} kg,成功质量 {n['passing_mass_kg']:.5f} kg;这是有限精度的局部边界,不是任意场景下的物理保证。",
|
||
f"建议候选:**{n['recommended_candidate_kg']} kg**。{len(r)} 次重复测试的最大位移为 {min(v['max_downstream_m'] for v in r):.6f}~{max(v['max_downstream_m'] for v in r):.6f} m。", '',
|
||
'| 质量 kg | 8 秒最大顺流位移 m | 最终球心高度 m | 说明 |',
|
||
'| ---: | ---: | ---: | --- |']
|
||
chosen=[75,114,150,200,250,300,310,315,320,330,350,400,500]
|
||
for mass in chosen:
|
||
row=next((v for v in n['trials'] if abs(v['candidate_mass_kg']-mass)<1e-5),None)
|
||
if row is None:continue
|
||
note='被下游墙截断,不能视为自然停止距离' if row['hit_downstream_end'] else '满足 2 米且落底' if row['max_downstream_m']<=p['distance_limit'] and row['settled_on_bed'] else '超过 2 米'
|
||
lines.append(f"| {mass} | {row['max_downstream_m']:.4f} | {row['final_center_y_m']:.4f} | {note} |")
|
||
lines += ['', '8 秒末候选球仍有约 0.10 m/s 的运动;本结果不保证持续水流下的无限时间位移也小于 2 米。达到 2 米约束的候选均未触及下游墙。', '']
|
||
lines += ['## 方法限制', '',
|
||
'连续模型先计算球入水和下沉,再近似为在墙壁河床上的纯滚动:接触时耗散地转为滚动,之后使用恒定支持力与滚动阻力。理想模型允许静止时的滚阻保持平衡;当前游戏仅对非零角速度施加有单步上限的滚阻力矩,因此会有缓慢漂移,两者不能视为同一个求解器。',
|
||
'连续表中 rolling_assumption_valid=false 的低质量行违反纯滚动所需摩擦条件,仅作诊断,不用于寻找推荐质量。当前约 310 kg 的根满足该条件。',
|
||
'水中阻力用浸没比例近似有效面积。Python 使用解析球冠体积;当前游戏用截柱采样,接触、回弹和时间离散也造成差别。因此推荐值以真实场景核验为准。',
|
||
'这里的严格下沉门槛指没有岸壁支撑的浮力/重力比较。河岸碰撞、其他初速度、水深和持续时间改变时,应重新计算。', '',
|
||
'原始逐帧采样、参数版本和输入 SHA-256 见 calculation.json;候选质量与结果分别见 engine_request_*.json、engine_result_*.json。',
|
||
]
|
||
(OUT/'report.md').write_text('\n'.join(lines)+'\n')
|
||
|
||
|
||
def main():
|
||
parser=argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument('--verify-godot',action='store_true')
|
||
args=parser.parse_args()
|
||
OUT.mkdir(exist_ok=True)
|
||
p=load_parameters()
|
||
snapshot={str(path.relative_to(ROOT)):hashlib.sha256(path.read_bytes()).hexdigest() for path in INPUTS}
|
||
model=analytical(p)
|
||
rows=[continuous_trial(m,p) for m in [75,114,120,150,200,250,300,310,320,330,350,400,500,890.0760306150601]]
|
||
report={'parameters':asdict(p),'model':model,'continuous_scan':rows,
|
||
'versions':{'python':sys.version.split()[0],'scipy':scipy.__version__,'numpy':np.__version__},
|
||
'input_sha256':snapshot,'scope':'8 seconds from current ceramic release; downstream displacement; live profile unchanged'}
|
||
print(json.dumps(model,indent=2),flush=True)
|
||
if args.verify_godot:
|
||
report['native']=verify_engine(p,model)
|
||
print('Native mass bracket:',report['native']['failing_mass_kg'],report['native']['passing_mass_kg'],flush=True)
|
||
print('Recommended test candidate:',report['native']['recommended_candidate_kg'],flush=True)
|
||
after={str(path.relative_to(ROOT)):hashlib.sha256(path.read_bytes()).hexdigest() for path in INPUTS}
|
||
if after!=snapshot:raise RuntimeError('Source parameters changed during the calculation; rerun against a stable configuration')
|
||
(OUT/'calculation.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||
(OUT/'physics_input.json').write_text(INPUTS[1].read_text())
|
||
with (OUT/'continuous_scan.csv').open('w',newline='') as stream:
|
||
writer=csv.DictWriter(stream,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
|
||
if args.verify_godot:
|
||
trials=report['native']['trials']
|
||
with (OUT/'native_scan.csv').open('w',newline='') as stream:
|
||
fields=[k for k in trials[0] if k!='trace']
|
||
writer=csv.DictWriter(stream,fieldnames=fields);writer.writeheader()
|
||
writer.writerows({k:r[k] for k in fields} for r in trials)
|
||
write_summary(report)
|
||
print('Report:',OUT/'report.md')
|
||
|
||
|
||
if __name__=='__main__':
|
||
main()
|