Create New World: vanilla's Game, World and More tabs

CreateWorldScreen as in 26.3: a MenuTabBar (tab sprites, header
separators, underline) over the transparent tab header, each tab's
GridLayout aligned at (0.5, 1/6) between it and a 33-pixel footer with
Create New World and Cancel.

Game: the world name box with its save-folder tooltip, Game Mode
(Survival, Hardcore, Creative), Difficulty and Allow Commands, locked
in Hardcore. World: World Type (Default, Superflat), Customize, the seed
box with its hint, and the Generate Structures / Bonus Chest switches.
More: Game Rules, Experiments and Data Packs. Tooltips follow vanilla's.

The choices reach the new world: hardcore, difficulty and allowCommands
in level.dat, and world_gen_settings with the flat preset, structures and
bonus chest written before streaming starts. Re-Create reads them back.

Fixes #281

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 10:24:52 +02:00
parent a8bd497132
commit dc863a66a4
10 changed files with 863 additions and 182 deletions
+2 -8
View File
@@ -154,6 +154,7 @@ impl Title {
seed,
creative,
focus,
..
} => {
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
create_page(ui, x, w, name, seed, *creative, *focus, caret);
@@ -379,14 +380,7 @@ impl Title {
};
}
}
CREATE => {
self.mode = Mode::Create {
name: "New World".into(),
seed: String::new(),
creative: false,
focus: 0,
}
}
CREATE => self.mode = Title::new_world(),
DELETE_WORLD => {
if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
self.mode = Mode::Delete { world };
+19 -4
View File
@@ -5805,6 +5805,7 @@ impl Game<'_> {
name: Option<&str>,
seed: Option<i64>,
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
self.perf.world_opening();
let save_root = std::env::current_dir()?.join("saves").join(folder);
@@ -5825,7 +5826,9 @@ impl Game<'_> {
.map(|d| horizon_client::random_sequences::RandomSequences::from_nbt(&d))
.unwrap_or_default();
self.border = Default::default();
let level = Level::read(&save_root).unwrap_or_else(|| Level {
let existing = Level::read(&save_root);
let created = existing.is_none();
let level = existing.unwrap_or_else(|| Level {
name: name.unwrap_or(folder).to_owned(),
// WorldOptions.randomSeed when no seed was given.
seed: seed.unwrap_or_else(|| {
@@ -5842,6 +5845,13 @@ impl Game<'_> {
..Level::default()
});
let mut level = level;
// CreateWorldScreen's choices, before streaming reads the generator.
if created && let Some(o) = create {
level.hardcore = o.hardcore;
level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into();
level.allow_commands = Some(o.commands(creative));
horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?;
}
horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name));
if let Some(d) = &self.options.dimension {
level.dimension = d.clone();
@@ -8795,13 +8805,18 @@ impl ApplicationHandler for Game<'_> {
Action::Language => {
self.open_options_at(true, horizon_client::options_ui::Page::Language)
}
Action::Play { folder } => self.open_world(&folder, None, None, false)?,
Action::Play { folder } => {
self.open_world(&folder, None, None, false, None)?
}
Action::Create {
folder,
name,
seed,
creative,
} => self.open_world(&folder, Some(&name), seed, creative)?,
options,
} => {
self.open_world(&folder, Some(&name), seed, creative, Some(&options))?
}
Action::Connect { address } => {
self.connect_server(&address, &self.options.player_name())?
}
@@ -9726,7 +9741,7 @@ pub fn run() -> Result<()> {
}
Some(folder) => {
let (seed, creative) = (game.options.seed, game.options.creative);
game.open_world(&folder, None, Some(seed), creative)?;
game.open_world(&folder, None, Some(seed), creative, None)?;
}
None => {
let title = Title::new(
+18 -3
View File
@@ -485,11 +485,19 @@ impl Game<'_> {
seed,
creative,
focus,
options,
} => json!({
"mode": "create-world",
"tab": (["game", "world", "more"][options.tab.min(2)]),
"fields": { "name": name, "seed": seed },
"focus": match focus { 0 => "name", 1 => "seed", _ => "none" },
"creative": creative,
"hardcore": options.hardcore,
"difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()],
"allow_commands": options.commands(*creative),
"superflat": options.flat,
"generate_structures": options.structures,
"bonus_chest": options.bonus_chest(),
}),
Mode::Edit {
world,
@@ -1322,10 +1330,17 @@ impl Game<'_> {
let title = self.title.as_mut().ok_or("no title screen")?;
if let Some(field) = &field {
match &mut title.mode {
horizon_client::title::Mode::Create { focus, .. } => {
horizon_client::title::Mode::Create { focus, options, .. } => {
// Each box is on its own tab.
*focus = match field.as_str() {
"name" => 0,
"seed" => 1,
"name" => {
options.tab = 0;
0
}
"seed" => {
options.tab = 1;
1
}
other => {
return Err(format!(
"the create-world fields are name and seed, not {other}"
+1 -1
View File
@@ -488,7 +488,7 @@ impl Game<'_> {
let folder = arg(1)?;
let seed = words.get(2).map(|s| s.parse::<i64>()).transpose()?;
let creative = words.get(3) == Some(&"creative");
self.open_world(folder, Some(folder), seed, creative)?;
self.open_world(folder, Some(folder), seed, creative, None)?;
ok()
}
"connect" => {
+7 -1
View File
@@ -372,7 +372,13 @@ impl Game<'_> {
let world_dir = std::env::current_dir()?.join(&universe).join(&level_name);
let folder = world_dir.to_string_lossy().into_owned();
let new_world = !world_dir.join("level.dat").exists();
self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?;
self.open_world(
&folder,
Some(&level_name),
Some(props.seed),
game_mode == 1,
None,
)?;
if new_world {
self.level.hardcore = props.hardcore;
}
+146 -57
View File
@@ -1922,6 +1922,145 @@ const INT_RULES: [&str; 11] = [
/// World and player state stored in `level.dat`, the saved-data files and
/// the player file.
/// The world options CreateWorldScreen sets (`WorldOptions` and the world
/// preset) that `world_gen_settings` keeps.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorldGen {
/// The `minecraft:flat` preset (Superflat) instead of `normal`.
pub flat: bool,
pub structures: bool,
pub bonus_chest: bool,
}
impl WorldGen {
/// A saved world's choices, from its `world_gen_settings`.
pub fn read(world: &Path) -> Option<Self> {
let settings = world_gen_settings(world)?;
let flag = |key: &str, default: bool| number(settings.get(key)).map_or(default, |v| v != 0);
let generator = settings
.get("dimensions")
.and_then(|d| d.get("minecraft:overworld"))
.and_then(|o| o.get("generator"));
Some(Self {
flat: text(generator.and_then(|g| g.get("type")))
.is_some_and(|t| t.trim_start_matches("minecraft:") == "flat"),
structures: flag("generate_structures", true),
bonus_chest: flag("bonus_chest", false),
})
}
}
impl Default for WorldGen {
fn default() -> Self {
Self {
flat: false,
structures: true,
bonus_chest: false,
}
}
}
/// Writes a new world's `world_gen_settings` (seed, options and dimensions).
pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> {
fs::create_dir_all(dir)?;
// worldgen/world_preset/flat.json's overworld: the classic flat layers.
let layer = |block: &str, height: i32| {
Tag::compound([("block", string(block)), ("height", Tag::Int(height))])
};
let flat = Tag::compound([
("type", string("minecraft:overworld")),
(
"generator",
Tag::compound([
("type", string("minecraft:flat")),
(
"settings",
Tag::compound([
("biome", string("minecraft:plains")),
("features", Tag::Byte(0)),
("lakes", Tag::Byte(0)),
(
"layers",
Tag::List(vec![
layer("minecraft:bedrock", 1),
layer("minecraft:dirt", 2),
layer("minecraft:grass_block", 1),
]),
),
(
"structure_overrides",
Tag::List(vec![
string("minecraft:strongholds"),
string("minecraft:villages"),
]),
),
]),
),
]),
),
]);
let dimension = |kind: &str, settings: &str, source: Tag| {
Tag::compound([
("type", string(kind)),
(
"generator",
Tag::compound([
("type", string("minecraft:noise")),
("settings", string(settings)),
("biome_source", source),
]),
),
])
};
let preset = |p: &str| {
Tag::compound([
("type", string("minecraft:multi_noise")),
("preset", string(p)),
])
};
write_saved_data(
dir,
"world_gen_settings",
Tag::compound([
("seed", Tag::Long(seed)),
(
"generate_structures",
Tag::Byte(i8::from(options.structures)),
),
("bonus_chest", Tag::Byte(i8::from(options.bonus_chest))),
(
"dimensions",
Tag::compound([
(
"minecraft:overworld",
if options.flat {
flat
} else {
dimension(
"minecraft:overworld",
"minecraft:overworld",
preset("minecraft:overworld"),
)
},
),
(
"minecraft:the_nether",
dimension(
"minecraft:the_nether",
"minecraft:nether",
preset("minecraft:nether"),
),
),
(
"minecraft:the_end",
dimension(
"minecraft:the_end",
"minecraft:end",
Tag::compound([("type", string("minecraft:the_end"))]),
),
),
]),
),
]),
)
}
#[derive(Clone, Debug, Default)]
pub struct Level {
pub name: String,
@@ -1964,6 +2103,9 @@ pub struct Level {
pub world_spawn: Option<[i32; 3]>,
pub difficulty: String,
pub hardcore: bool,
/// `allowCommands` chosen on the Create New World screen; unset keeps
/// the saved value (off for a new world).
pub allow_commands: Option<bool>,
/// Game rule values by name without namespace (`keep_inventory`, ...).
pub game_rules: BTreeMap<String, i32>,
pub player_uuid: Option<[i32; 4]>,
@@ -2524,6 +2666,9 @@ impl Level {
}
if let Tag::Compound(map) = &mut data {
map.entry("allowCommands".into()).or_insert(Tag::Byte(0));
if let Some(allow) = self.allow_commands {
map.insert("allowCommands".into(), Tag::Byte(i8::from(allow)));
}
map.entry("WasModded".into()).or_insert(Tag::Byte(0));
map.entry("DataPacks".into()).or_insert_with(|| {
Tag::compound([
@@ -2567,63 +2712,7 @@ impl Level {
}
write_saved_data(dir, "world_clocks", clocks)?;
if legacy || !saved_data_path(dir, "world_gen_settings").exists() {
let dimension = |kind: &str, settings: &str, source: Tag| {
Tag::compound([
("type", string(kind)),
(
"generator",
Tag::compound([
("type", string("minecraft:noise")),
("settings", string(settings)),
("biome_source", source),
]),
),
])
};
let preset = |p: &str| {
Tag::compound([
("type", string("minecraft:multi_noise")),
("preset", string(p)),
])
};
write_saved_data(
dir,
"world_gen_settings",
Tag::compound([
("seed", Tag::Long(self.seed)),
("generate_structures", Tag::Byte(1)),
("bonus_chest", Tag::Byte(0)),
(
"dimensions",
Tag::compound([
(
"minecraft:overworld",
dimension(
"minecraft:overworld",
"minecraft:overworld",
preset("minecraft:overworld"),
),
),
(
"minecraft:the_nether",
dimension(
"minecraft:the_nether",
"minecraft:nether",
preset("minecraft:nether"),
),
),
(
"minecraft:the_end",
dimension(
"minecraft:the_end",
"minecraft:end",
Tag::compound([("type", string("minecraft:the_end"))]),
),
),
]),
),
]),
)?;
write_world_gen_settings(dir, self.seed, WorldGen::default())?;
}
if !saved_data_path(dir, "game_rules").exists() || !self.game_rules.is_empty() {
// Only rules vanilla knows: an unknown key makes it reject the file.
+71 -107
View File
@@ -12,9 +12,11 @@ use std::{
sync::mpsc,
};
mod create_world;
#[cfg(test)]
mod tests;
mod world_management;
pub use create_world::{DIFFICULTIES, WorldOptions};
/// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`.
const LIST_TOP: f32 = 49.0;
@@ -81,6 +83,7 @@ pub enum Mode {
seed: String,
creative: bool,
focus: u8,
options: WorldOptions,
},
Edit {
world: WorldEntry,
@@ -114,6 +117,7 @@ pub enum Action {
name: String,
seed: Option<i64>,
creative: bool,
options: WorldOptions,
},
Connect {
address: String,
@@ -140,7 +144,7 @@ pub struct Title {
/// The saves listed for Home, re-read every couple of seconds.
recent: std::cell::RefCell<Option<(std::time::Instant, Vec<WorldEntry>)>>,
}
struct Button {
pub(crate) struct Button {
x: f32,
y: f32,
w: f32,
@@ -265,12 +269,13 @@ impl Title {
}
};
}
fn new_world() -> Mode {
pub(crate) fn new_world() -> Mode {
Mode::Create {
name: "New World".into(),
seed: String::new(),
creative: false,
focus: 0,
options: WorldOptions::default(),
}
}
fn return_to_list(&mut self, folder: Option<&str>) {
@@ -483,11 +488,22 @@ impl Title {
name,
seed,
creative,
options,
..
} = &self.mode
else {
return Action::None;
};
Action::Create {
folder: self.target_folder(name),
name: name.clone(),
seed: parse_seed(seed),
creative: *creative,
options: options.clone(),
}
}
/// The folder a new world named `name` gets (`findResultFolder`).
fn target_folder(&self, name: &str) -> String {
let base: String = name
.chars()
.map(|c| {
@@ -510,12 +526,7 @@ impl Title {
folder = format!("{base} ({n})");
n += 1;
}
Action::Create {
folder,
name: name.clone(),
seed: parse_seed(seed),
creative: *creative,
}
folder
}
fn buttons(&self, w: f32, h: f32) -> Vec<Button> {
let (w, h) = (w.ceil(), h.ceil());
@@ -609,29 +620,9 @@ impl Title {
),
b((w / 2.0).floor() + 83.0, h - 28.0, 71.0, "Back", true, 12),
],
Mode::Create { creative, .. } => vec![
b(
(w / 2.0).floor() - 75.0,
120.0,
150.0,
if *creative {
"Game Mode: Creative"
} else {
"Game Mode: Survival"
},
true,
20,
),
b(
(w / 2.0).floor() - 155.0,
h - 28.0,
150.0,
"Create New World",
true,
21,
),
b((w / 2.0).floor() + 5.0, h - 28.0, 150.0, "Cancel", true, 22),
],
Mode::Create {
creative, options, ..
} => create_world::buttons(w, h, *creative, options),
Mode::Edit { world, name, .. } => {
let x = (w / 2.0).floor() - 100.0;
let top = edit_top(h);
@@ -920,71 +911,12 @@ impl Title {
);
}
Mode::Create {
name, seed, focus, ..
} => {
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
let title = "Create New World";
let tw = HudBatch::text_width(atlas, title);
batch.text(atlas, title, (w - tw) / 2.0, 8.0, u32::MAX, true);
let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2);
for (i, (label, value)) in [
("World Name", name),
(
"Seed for the World Generator (leave blank for random)",
seed,
),
]
.iter()
.enumerate()
{
let y = 40.0 + i as f32 * 40.0;
crate::widgets::target_as(
[(w / 2.0).floor() - 100.0, y + 11.0, 200.0, 20.0],
crate::widgets::Kind::Field,
);
batch.text(
atlas,
label,
(w / 2.0).floor() - 100.0,
y,
rgba(160, 160, 160, 255),
true,
);
batch.fill(
atlas,
(w / 2.0).floor() - 100.0,
y + 11.0,
200.0,
20.0,
if *focus == i as u8 {
u32::MAX
} else {
rgba(160, 160, 160, 255)
},
);
batch.fill(
atlas,
(w / 2.0).floor() - 99.0,
y + 12.0,
198.0,
18.0,
rgba(0, 0, 0, 255),
);
let shown = if *focus == i as u8 && blink {
format!("{value}_")
} else {
value.to_string()
};
batch.text(
atlas,
&shown,
(w / 2.0).floor() - 96.0,
y + 17.0,
rgba(224, 224, 224, 255),
true,
);
}
}
name,
seed,
focus,
options,
..
} => self.draw_create(atlas, batch, cursor, name, seed, *focus, options),
Mode::Edit { name, focused, .. } => {
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
centered(
@@ -1138,6 +1070,15 @@ impl Title {
true,
);
}
if let Mode::Create {
name,
creative,
options,
..
} = &self.mode
{
self.create_tooltip(atlas, batch, cursor, name, *creative, options);
}
if let Some((at, toast)) = &self.toast
&& at.elapsed().as_secs() < 5
{
@@ -1163,6 +1104,17 @@ impl Title {
/// Navigation buttons can return `Action::None` while still sounding.
pub fn click(&mut self, x: f32, y: f32, size: (f32, f32)) -> (Action, bool) {
let (w, h) = (size.0.ceil(), size.1.ceil());
// MenuTabBar: a new tab clears the focus and clicks.
if let Mode::Create { focus, options, .. } = &mut self.mode
&& let Some(tab) = create_world::tab_at(w, (x, y))
{
let changed = options.tab != tab;
if changed {
options.tab = tab;
*focus = 2;
}
return (Action::None, changed);
}
let hit = self
.buttons(w, h)
.into_iter()
@@ -1226,11 +1178,17 @@ impl Title {
_ => {
if let Some(level) = Level::read(&self.saves.join(&world.folder)) {
self.create_return_to_main = false;
let options = WorldOptions::of_world(
&level,
world.commands,
&self.saves.join(&world.folder),
);
self.mode = Mode::Create {
name: level.name,
seed: level.seed.to_string(),
creative: level.creative,
focus: 0,
options,
};
}
}
@@ -1325,8 +1283,13 @@ impl Title {
self.mode = *return_to.clone();
Action::None
}
(Mode::Create { creative, .. }, Some(20)) => {
*creative = !*creative;
(
Mode::Create {
creative, options, ..
},
Some(id),
) if id != 21 && id != 22 => {
options.press(id, creative);
Action::None
}
(Mode::Create { .. }, Some(21)) => self.create_action(),
@@ -1334,13 +1297,8 @@ impl Title {
self.cancel_create();
Action::None
}
(Mode::Create { focus, .. }, None) => {
for i in 0..2u8 {
let fy = 40.0 + f32::from(i) * 40.0 + 11.0;
if y >= fy && y < fy + 20.0 && (x - (w / 2.0).floor()).abs() < 100.0 {
*focus = i;
}
}
(Mode::Create { focus, options, .. }, None) => {
*focus = create_world::field_at(w, h, options.tab, (x, y)).unwrap_or(2);
Action::None
}
_ => Action::None,
@@ -1421,8 +1379,14 @@ impl Title {
if let Mode::Multiplayer(screen) = &mut self.mode {
screen.tab();
}
if let Mode::Create { focus, .. } = &mut self.mode {
*focus = (*focus + 1) % 2;
// The open tab's one text box, then nothing.
if let Mode::Create { focus, options, .. } = &mut self.mode {
let field = if options.tab == 1 { 1 } else { 0 };
*focus = if *focus == field || options.tab == 2 {
2
} else {
field
};
}
}
/// The server auto-reconnect retries now, once its countdown is over.
@@ -0,0 +1,498 @@
//! CreateWorldScreen: the Game, World and More tabs under a MenuTabBar, with
//! Create New World and Cancel in a 33-pixel footer.
use super::{Button, Title};
use crate::{
hud::{HudAtlas, HudBatch},
text::Text,
ui,
};
/// MenuTabBar.HEIGHT: the header above the tab area.
const TAB_BAR: f32 = 24.0;
/// HeaderAndFooterLayout's default footer height.
const FOOTER: f32 = 33.0;
const TABS: [&str; 3] = [
"createWorld.tab.game.title",
"createWorld.tab.world.title",
"createWorld.tab.more.title",
];
/// Difficulty ids, in the cycle button's order.
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
/// WorldCreationUiState beyond the name and seed.
#[derive(Clone, Debug, PartialEq)]
pub struct WorldOptions {
/// The open tab: Game, World or More.
pub tab: usize,
/// Survival locked to Hard, one life (`SelectedGameMode.HARDCORE`).
pub hardcore: bool,
/// Index in `DIFFICULTIES`.
pub difficulty: usize,
/// Allow Cheats as toggled; unset follows the game mode.
pub commands: Option<bool>,
/// The Superflat world preset instead of Default.
pub flat: bool,
pub structures: bool,
pub bonus_chest: bool,
}
impl Default for WorldOptions {
fn default() -> Self {
Self {
tab: 0,
hardcore: false,
difficulty: 2,
commands: None,
flat: false,
structures: true,
bonus_chest: false,
}
}
}
impl WorldOptions {
/// Re-Create: the saved world's choices.
pub(super) fn of_world(
level: &crate::save::Level,
commands: bool,
dir: &std::path::Path,
) -> Self {
let generation = crate::save::WorldGen::read(dir).unwrap_or_default();
Self {
hardcore: level.hardcore,
difficulty: DIFFICULTIES
.iter()
.position(|d| *d == level.difficulty)
.unwrap_or(2),
commands: Some(commands),
flat: generation.flat,
structures: generation.structures,
bonus_chest: generation.bonus_chest,
..Self::default()
}
}
/// `getDifficulty`: Hardcore is always Hard.
pub fn difficulty(&self) -> usize {
if self.hardcore { 3 } else { self.difficulty }
}
/// `isAllowCommands`: never in Hardcore, else on for Creative until toggled.
pub fn commands(&self, creative: bool) -> bool {
!self.hardcore && self.commands.unwrap_or(creative)
}
/// `isBonusChest`: never in Hardcore.
pub fn bonus_chest(&self) -> bool {
!self.hardcore && self.bonus_chest
}
pub fn world_gen(&self) -> crate::save::WorldGen {
crate::save::WorldGen {
flat: self.flat,
structures: self.structures,
bonus_chest: self.bonus_chest(),
}
}
/// A press on one of the open tab's cycle buttons or switches.
pub(super) fn press(&mut self, id: u8, creative: &mut bool) {
match id {
// Survival, Hardcore, Creative.
20 => {
(*creative, self.hardcore) = match (*creative, self.hardcore) {
(false, false) => (false, true),
(false, true) => (true, false),
_ => (false, false),
}
}
23 => self.difficulty = (self.difficulty + 1) % DIFFICULTIES.len(),
24 => self.commands = Some(!self.commands(*creative)),
25 => self.flat = !self.flat,
27 => self.structures = !self.structures,
28 => self.bonus_chest = !self.bonus_chest,
_ => {}
}
}
}
/// `Mth.roundToward`: up to a multiple of `step`.
fn round_toward(value: f32, step: f32) -> f32 {
(value / step).ceil() * step
}
/// MenuTabBar.arrangeElements: the first tab's x and every tab's width.
fn tabs(w: f32) -> (f32, f32) {
let width = w.min(400.0) - 28.0;
(
round_toward(((w - width) / 2.0).trunc(), 2.0),
round_toward((width / TABS.len() as f32).trunc(), 2.0),
)
}
/// The tab under the pointer.
pub(super) fn tab_at(w: f32, (x, y): (f32, f32)) -> Option<usize> {
let (x0, width) = tabs(w);
((0.0..TAB_BAR).contains(&y) && x >= x0)
.then(|| ((x - x0) / width) as usize)
.filter(|i| *i < TABS.len())
}
/// GridLayoutTab.doLayout: the open tab's grid, aligned at (0.5, 1/6) in the
/// area between the tab bar and the footer.
fn grid(w: f32, h: f32, tab: usize) -> (f32, f32) {
// Game: the labelled name box (9 + 4 + 20) and three buttons, 8 apart.
// World: a button row, the labelled seed box and the SwitchGrid
// (4 + 20 + 4 + 20 under its empty spacer row). More: three buttons.
let (gw, gh) = match tab {
0 => (210.0, 117.0),
1 => (310.0, 117.0),
_ => (210.0, 76.0),
};
let area = h - TAB_BAR - FOOTER;
(
((w - gw) * 0.5).trunc(),
TAB_BAR + ((area - gh) * 0.166_666_67).trunc(),
)
}
/// The text box under the pointer: 0 the name, 1 the seed.
pub(super) fn field_at(w: f32, h: f32, tab: usize, (x, y): (f32, f32)) -> Option<u8> {
let (gx, gy) = grid(w, h, tab);
match tab {
0 => ui::hovered((x, y), gx + 1.0, gy + 13.0, 208.0, 20.0).then_some(0),
1 => ui::hovered((x, y), gx, gy + 41.0, 308.0, 20.0).then_some(1),
_ => None,
}
}
fn tr(key: &str) -> String {
Text::translate(key, &[]).plain()
}
/// `CycleButton`'s "Label: Value" (`options.generic_value`).
fn labelled(key: &str, value: String) -> String {
Text::translate(
"options.generic_value",
&[Text::translate(key, &[]), Text::literal(value)],
)
.plain()
}
fn on_off(on: bool) -> String {
tr(if on { "options.on" } else { "options.off" })
}
fn game_mode(creative: bool, hardcore: bool) -> &'static str {
match (creative, hardcore) {
(true, _) => "selectWorld.gameMode.creative",
(false, true) => "selectWorld.gameMode.hardcore",
(false, false) => "selectWorld.gameMode.survival",
}
}
/// The open tab's buttons and the footer's.
pub(super) fn buttons(w: f32, h: f32, creative: bool, o: &WorldOptions) -> Vec<Button> {
let b = |x: f32, y: f32, w: f32, label: String, enabled: bool, id: u8| Button {
x,
y,
w,
label,
enabled,
id,
icon: None,
};
let (gx, gy) = grid(w, h, o.tab);
let mut buttons = match o.tab {
0 => vec![
b(
gx,
gy + 41.0,
210.0,
labelled("selectWorld.gameMode", tr(game_mode(creative, o.hardcore))),
true,
20,
),
b(
gx,
gy + 69.0,
210.0,
labelled(
"options.difficulty",
tr(&format!(
"options.difficulty.{}",
DIFFICULTIES[o.difficulty()]
)),
),
!o.hardcore,
23,
),
b(
gx,
gy + 97.0,
210.0,
labelled("selectWorld.allowCommands", on_off(o.commands(creative))),
!o.hardcore,
24,
),
],
1 => vec![
b(
gx,
gy,
150.0,
labelled(
"selectWorld.mapType",
tr(if o.flat {
"generator.minecraft.flat"
} else {
"generator.minecraft.normal"
}),
),
true,
25,
),
// Horizon has no preset editor (CreateFlatWorldScreen) yet.
b(
gx + 160.0,
gy,
150.0,
tr("selectWorld.customizeType"),
false,
26,
),
// SwitchGrid: 44-wide value-only buttons at the grid's right.
b(gx + 266.0, gy + 73.0, 44.0, on_off(o.structures), true, 27),
b(
gx + 266.0,
gy + 97.0,
44.0,
on_off(o.bonus_chest()),
!o.hardcore,
28,
),
],
// Game rules, experiments and data packs have no screens yet.
_ => [
"selectWorld.gameRules",
"selectWorld.experiments",
"selectWorld.dataPacks",
]
.iter()
.enumerate()
.map(|(i, key)| {
b(
gx,
gy + 28.0 * i as f32,
210.0,
tr(key),
false,
29 + i as u8,
)
})
.collect(),
};
// The footer: two 150-wide buttons 8 apart, centred in its 33 pixels.
let x = ((w - 308.0) * 0.5).trunc();
buttons.push(b(
x,
h - 27.0,
150.0,
crate::lang::get_or("selectWorld.create", "Create New World"),
true,
21,
));
buttons.push(b(
x + 158.0,
h - 27.0,
150.0,
crate::lang::get_or("gui.cancel", "Cancel"),
true,
22,
));
buttons
}
impl Title {
/// Everything but the buttons, which `draw` adds after.
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_create(
&self,
atlas: &HudAtlas,
batch: &mut HudBatch,
cursor: (f32, f32),
name: &str,
seed: &str,
focus: u8,
o: &WorldOptions,
) {
let (w, h) = (batch.width.ceil(), batch.height.ceil());
// extractMenuBackground: the tab header strip, the menu background under it.
ui::tiled(
batch,
atlas,
"gui/tab_header_background",
0.0,
0.0,
w,
TAB_BAR,
16.0,
u32::MAX,
);
ui::menu_background(batch, atlas, 0.0, TAB_BAR, w, h - TAB_BAR, false);
// MenuTabBar: header separators either side of the tabs.
let (x0, tw) = tabs(w);
let right = x0 + tw * TABS.len() as f32;
for (x, width) in [(0.0, x0), (right, w - right)] {
ui::tiled(
batch,
atlas,
"gui/header_separator",
x,
TAB_BAR - 2.0,
width,
2.0,
32.0,
u32::MAX,
);
}
for (i, key) in TABS.iter().enumerate() {
let x = x0 + tw * i as f32;
let selected = o.tab == i;
let label = Text::translate(key, &[]);
crate::widgets::record(&label.plain(), [x, 0.0, tw, TAB_BAR], true);
let sprite = match (selected, ui::hovered(cursor, x, 0.0, tw, TAB_BAR)) {
(true, true) => "gui/sprites/widget/tab_selected_highlighted",
(true, false) => "gui/sprites/widget/tab_selected",
(false, true) => "gui/sprites/widget/tab_highlighted",
(false, false) => "gui/sprites/widget/tab",
};
ui::nine_slice(batch, atlas, sprite, x, 0.0, tw, TAB_BAR, u32::MAX);
let lw = atlas.font.width_text(&label).floor();
if selected {
ui::menu_background(batch, atlas, x + 2.0, 2.0, tw - 4.0, TAB_BAR - 2.0, false);
// renderFocusUnderline.
let uw = lw.min(tw - 4.0);
batch.fill(
atlas,
x + ((tw - uw) / 2.0).floor(),
TAB_BAR - 2.0,
uw,
1.0,
u32::MAX,
);
}
// The label sits 3 pixels lower on unselected tabs.
let top = if selected { 0.0 } else { 3.0 };
batch.text_styled(
atlas,
&label,
x + (tw / 2.0).floor() - (lw / 2.0).floor(),
((top + TAB_BAR - 9.0) / 2.0).floor() + 1.0,
u32::MAX,
true,
);
}
let (gx, gy) = grid(w, h, o.tab);
let label = |batch: &mut HudBatch, key: &str, x: f32, y: f32| {
batch.text_styled(atlas, &Text::translate(key, &[]), x, y, u32::MAX, true);
};
match o.tab {
0 => {
// CommonLayouts.labeledElement, centred in the 210 column.
label(batch, "selectWorld.enterName", gx + 1.0, gy);
self.create_field(
atlas,
batch,
name,
[gx + 1.0, gy + 13.0, 208.0],
focus == 0,
None,
);
}
1 => {
label(batch, "selectWorld.enterSeed", gx, gy + 28.0);
self.create_field(
atlas,
batch,
seed,
[gx, gy + 41.0, 308.0],
focus == 1,
Some("selectWorld.seedInfo"),
);
// SwitchGrid labels, centred on their switch rows.
label(batch, "selectWorld.mapFeatures", gx, gy + 78.0);
label(batch, "selectWorld.bonusItems", gx, gy + 102.0);
}
_ => {}
}
// The footer separator, drawn over the screen.
ui::tiled(
batch,
atlas,
"gui/footer_separator",
0.0,
h - FOOTER - 2.0,
w,
2.0,
32.0,
u32::MAX,
);
}
/// An EditBox with its cursor at the end; `hint` shows while it is empty
/// and unfocused.
fn create_field(
&self,
atlas: &HudAtlas,
batch: &mut HudBatch,
value: &str,
[x, y, width]: [f32; 3],
focused: bool,
hint: Option<&str>,
) {
let mut field = ui::EditBox::new(x, y, width, 20.0);
field.value = value.to_owned();
field.cursor = ui::char_len(value);
field.highlight = field.cursor;
field.focused = focused;
field.focused_since(self.started);
field.draw(batch, atlas, None);
if let Some(hint) = hint
&& value.is_empty()
&& !focused
{
batch.text_styled(
atlas,
&Text::translate(hint, &[]).with_color(crate::text::DARK_GRAY),
field.text_x(),
field.text_y(),
u32::MAX,
true,
);
}
}
/// The hovered widget's tooltip, wrapped to Tooltip's 170 pixels.
pub(super) fn create_tooltip(
&self,
atlas: &HudAtlas,
batch: &mut HudBatch,
cursor: (f32, f32),
name: &str,
creative: bool,
o: &WorldOptions,
) {
let (w, h) = (batch.width.ceil(), batch.height.ceil());
let (gx, gy) = grid(w, h, o.tab);
let over = |x: f32, y: f32, width: f32| ui::hovered(cursor, x, y, width, 20.0);
let text = match o.tab {
0 if over(gx + 1.0, gy + 13.0, 208.0) => Some(Text::translate(
"selectWorld.targetFolder",
&[Text::literal(self.target_folder(name)).italic()],
)),
0 if over(gx, gy + 41.0, 210.0) => Some(Text::translate(
&format!("{}.info", game_mode(creative, o.hardcore)),
&[],
)),
0 if over(gx, gy + 69.0, 210.0) => Some(Text::translate(
&format!("options.difficulty.{}.info", DIFFICULTIES[o.difficulty()]),
&[],
)),
0 if over(gx, gy + 97.0, 210.0) => {
Some(Text::translate("selectWorld.allowCommands.info", &[]))
}
1 if over(gx + 266.0, gy + 73.0, 44.0) => {
Some(Text::translate("selectWorld.mapFeatures.info", &[]))
}
_ => None,
};
if let Some(text) = text {
ui::tooltip(batch, atlas, &atlas.font.split(&text, 170.0), cursor);
}
}
}
+97 -1
View File
@@ -447,8 +447,15 @@ fn classic_navigation_buttons_sound_even_without_a_game_action() {
f.title.click(240.0, 55.0, (480.0, 262.0)),
(Action::None, false)
);
// The Game tab's game mode cycle button.
let mode = f
.title
.buttons(480.0, 262.0)
.into_iter()
.find(|b| b.id == 20)
.unwrap();
assert_eq!(
f.click_with_sound("Game Mode: Survival"),
f.title.click(mode.x + 1.0, mode.y + 1.0, (480.0, 262.0)),
(Action::None, true)
);
assert_eq!(f.click_with_sound("Cancel"), (Action::None, true));
@@ -584,3 +591,92 @@ fn scrolled_world_list_draws_inside_the_list_and_drags_its_scroller() {
f.title.draw(&atlas, &mut batch, (0.0, 0.0), true);
assert!(!batch.vertices.is_empty());
}
#[test]
fn create_world_tabs_follow_vanilla_and_their_choices_reach_the_action() {
let mut f = Fixture::new();
f.click("Singleplayer");
let size = (480.0, 262.0);
let labels = |f: &Fixture| -> Vec<(String, f32, f32, bool)> {
f.title
.buttons(size.0, size.1)
.into_iter()
.map(|b| (b.label, b.x, b.y, b.enabled))
.collect()
};
// Game tab: the grid (210 × 117) at (0.5, 1/6) of 24..h-33, footer centred.
let game = labels(&f);
assert_eq!(game[0].1, 135.0);
assert_eq!(game[0].2, 24.0 + 14.0 + 41.0);
assert_eq!((game[3].1, game[3].2), (86.0, 235.0));
assert_eq!((game[4].1, game[4].2), (244.0, 235.0));
// Survival, Hardcore (Hard, no cheats, both locked), Creative (cheats on).
f.title.click(240.0, game[0].2 + 10.0, size);
let Mode::Create { options, .. } = &f.title.mode else {
panic!()
};
assert!(options.hardcore && options.difficulty() == 3 && !options.commands(false));
assert!(!labels(&f)[1].3 && !labels(&f)[2].3);
f.title.click(240.0, game[0].2 + 10.0, size);
let Mode::Create {
creative, options, ..
} = &f.title.mode
else {
panic!()
};
assert!(*creative && !options.hardcore && options.commands(true));
// The World tab (second of three 124-wide tabs from x 54): its seed box
// takes the focus, Superflat and the switches toggle.
let (action, sound) = f.title.click(54.0 + 124.0 + 10.0, 10.0, size);
assert!(sound && action == Action::None);
let world = labels(&f);
assert_eq!((world[0].1, world[0].2), (85.0, 38.0));
assert_eq!((world[2].1, world[2].2), (85.0 + 266.0, 38.0 + 73.0));
f.title.click(world[0].1 + 10.0, world[0].2 + 10.0, size);
f.title.click(world[3].1 + 10.0, world[3].2 + 10.0, size);
f.title.click(100.0, 38.0 + 41.0 + 10.0, size);
let Mode::Create { focus, options, .. } = &f.title.mode else {
panic!()
};
assert_eq!(*focus, 1);
assert!(options.flat && options.bonus_chest());
let Action::Create { options, .. } = f.title.create_action() else {
panic!()
};
assert_eq!(
options.world_gen(),
crate::save::WorldGen {
flat: true,
structures: true,
bonus_chest: true
}
);
// The More tab's screens don't exist yet.
f.title.click(54.0 + 248.0 + 10.0, 10.0, size);
assert!(labels(&f)[..3].iter().all(|b| !b.3));
}
#[test]
fn new_world_generation_settings_round_trip() {
let f = Fixture::new();
let dir = f.root.join("flat");
let options = crate::save::WorldGen {
flat: true,
structures: false,
bonus_chest: true,
};
crate::save::write_world_gen_settings(&dir, 42, options).unwrap();
assert_eq!(crate::save::WorldGen::read(&dir), Some(options));
let settings = crate::save::world_gen_settings(&dir).unwrap();
assert_eq!(
crate::save::text(
settings
.get("dimensions")
.and_then(|d| d.get("minecraft:overworld"))
.and_then(|o| o.get("generator"))
.and_then(|g| g.get("type"))
)
.as_deref(),
Some("minecraft:flat")
);
}
+4
View File
@@ -637,6 +637,10 @@ impl EditBox {
text_color: rgba(224, 224, 224, 255),
}
}
/// When the field gained focus, for the cursor's blink.
pub fn focused_since(&mut self, at: Instant) {
self.focused_at = at;
}
pub fn inner_width(&self) -> f32 {
if self.bordered {
self.width - 8.0